UNPKG

@widergy/web-utils

Version:
728 lines (727 loc) 41.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.noValues = exports.getMetricByType = exports.hasAmount = exports.hasExceededPowerCheck = exports.hasHolidaysCheck = exports.hasPreviousAverageTemperatureCheck = exports.hasCurrentAverageTemperatureCheck = exports.hasCurrentNonSmartDataCheck = exports.hasCurrentSmartDataCheck = exports.hasPreviousSmartDataCheck = exports.hasPreviousNonSmartDataCheck = exports.getAvailableYears = exports.getMostRecentYear = exports.isCurrentPeriod = exports.generateCarbonFootprintTotalConsumption = exports.getConcepts = exports.generateCarbonFootprintData = exports.desagregateConcepts = exports.handleCheckProfile = exports.references = exports.getXAxisDefinitionV0 = exports.getBarData = exports.formatPeriod = exports.isPeriodCurrentYear = exports.getAnnualcarbonFootprintKpiValues = exports.getXAxisDefinition = exports.getLinearData = exports.removeDots = exports.addConcepts = exports.generateCSVData = exports.processData = exports.getColors = exports.getCurrentDay = exports.processTempData = exports.processChartData = exports.getPeriodData = exports.getTooltipContent = exports.getHighestConsumption = exports.getHiredPower = exports.getDateIndexInPeriod = exports.getGranularityLength = exports.getPeriodDuration = exports.carbonFootprintValue = exports.getDayIndicators = exports.getMonthIndicators = exports.getMonthsFromChartData = exports.getMonthLabel = exports.extractYear = exports.extractPeriod = exports.getPagination = void 0; exports.changeValue = exports.getBreadCrumbsOptions = exports.granularitySelectionOptions = exports.getInitialValues = exports.getDaysFromData = exports.getConsumptionPercentage = exports.percentage = exports.getpercentageOfPeriod = exports.isFuturePeriod = exports.hasPeriodFinished = exports.getEndAngle = exports.getStartAngle = exports.linearScaler = exports.getCurrentPeriod = exports.noImportAmountValues = void 0; const dayjs_1 = __importDefault(require("dayjs")); const timezone_1 = __importDefault(require("dayjs/plugin/timezone")); const d3 = __importStar(require("d3")); const consumptionConstants_1 = require("./constants/consumptionConstants"); const array_1 = require("./array"); dayjs_1.default.extend(timezone_1.default); const { YEAR, PERIOD, DAY } = consumptionConstants_1.HISTORY_GRAPHIC_GRANULARITY; const getPagination = (granularity, year, day, period) => ({ [YEAR]: year, [DAY]: day, [PERIOD]: period, })[granularity]; exports.getPagination = getPagination; const extractPeriod = (value = '') => parseInt(value.split('-')[1], 10); exports.extractPeriod = extractPeriod; const extractYear = (value = '') => parseInt(value.split('-')[0], 10); exports.extractYear = extractYear; const getMonthLabel = (key) => `${consumptionConstants_1.MONTHS[(0, exports.extractPeriod)(key) - 1]}-${(0, exports.extractYear)(key) % 2000}`; exports.getMonthLabel = getMonthLabel; const getMonthsFromChartData = (data) => { const periodSet = new Set(); data.forEach(({ key }) => periodSet.add((0, exports.getMonthLabel)(key))); return periodSet; }; exports.getMonthsFromChartData = getMonthsFromChartData; const getMonthIndicators = (config) => { const { data, currentPage, pagination } = config; const indicators = []; let foundIndex; const periodSet = (0, exports.getMonthsFromChartData)(data[0]); periodSet.forEach((period) => { foundIndex = data[0].findIndex(({ key }) => (0, exports.getMonthLabel)(key) === period); if (foundIndex >= 0) indicators.push({ label: period, x: foundIndex + currentPage * pagination, textAnchor: 'start', }); }); return indicators; }; exports.getMonthIndicators = getMonthIndicators; const getDayIndicators = (indicators) => (config) => { const { currentPage, pagination } = config; const indicatorsToShow = []; if (indicators) indicators .filter(({ range }) => (pagination ? Math.floor(range / pagination) === currentPage : true)) .forEach((_a) => { var { range } = _a, indicator = __rest(_a, ["range"]); return indicatorsToShow.push(Object.assign(Object.assign({ x: pagination ? (range % pagination) + currentPage * pagination : range }, indicator), { textAnchor: 'start', withLine: true })); }); return indicatorsToShow; }; exports.getDayIndicators = getDayIndicators; const carbonFootprintValue = (currentData) => currentData.reduce((acc, current) => acc + current.value, 0); exports.carbonFootprintValue = carbonFootprintValue; const getPeriodDuration = (startDate, endDate) => { if ((0, dayjs_1.default)(startDate).tz().isSame((0, dayjs_1.default)(endDate).tz())) return 0; const a = (0, dayjs_1.default)(startDate).tz().startOf('day'); const b = (0, dayjs_1.default)(endDate).tz().endOf('day'); return b.diff(a, 'days'); }; exports.getPeriodDuration = getPeriodDuration; const getGranularityLength = (granularity, data, selectedPeriod) => { switch (granularity) { case YEAR: return consumptionConstants_1.GRANULARITY_DEFAULT_PERIOD_LENGTH[YEAR]; case PERIOD: { if (data) { const { periods } = data; if (periods) { const period = periods.find((p) => p.period === selectedPeriod); return period ? (0, exports.getPeriodDuration)(period.start_date, period.end_date) : consumptionConstants_1.DEFAULT_PERIOD_LENGTH; } } return consumptionConstants_1.DEFAULT_PERIOD_LENGTH; } case DAY: return consumptionConstants_1.GRANULARITY_DEFAULT_PERIOD_LENGTH[DAY]; default: return 0; } }; exports.getGranularityLength = getGranularityLength; const getDateIndexInPeriod = (startDate, date) => { const mStartDate = (0, dayjs_1.default)(startDate).tz(); const mDate = (0, dayjs_1.default)(date).tz(); return mDate.diff(mStartDate, 'days'); }; exports.getDateIndexInPeriod = getDateIndexInPeriod; const getHiredPower = (chartData, selectedYear, selectedPeriod) => { var _a, _b, _c, _d, _e, _f, _g; return (_g = (_f = (_e = (_d = (_c = (_b = (_a = chartData[selectedYear]) === null || _a === void 0 ? void 0 : _a.periods) === null || _b === void 0 ? void 0 : _b.find((item) => item.period === selectedPeriod)) === null || _c === void 0 ? void 0 : _c.current_consumption) === null || _d === void 0 ? void 0 : _d.find((item) => item.metric === consumptionConstants_1.METRICS.POWER)) === null || _e === void 0 ? void 0 : _e.values) === null || _f === void 0 ? void 0 : _f.find((item) => item.type === consumptionConstants_1.HIRED_POWER_KEY)) === null || _g === void 0 ? void 0 : _g.value; }; exports.getHiredPower = getHiredPower; const getHighestConsumption = (days) => days.reduce((prev, curr) => { var _a, _b, _c, _d; if (prev && (prev === null || prev === void 0 ? void 0 : prev.current_consumption) && curr && (curr === null || curr === void 0 ? void 0 : curr.current_consumption)) { const prevPowerValues = (_a = prev.current_consumption.find((it) => it.metric === consumptionConstants_1.METRICS.POWER)) === null || _a === void 0 ? void 0 : _a.values; const currPowerValues = (_b = curr.current_consumption.find((it) => it.metric === consumptionConstants_1.METRICS.POWER)) === null || _b === void 0 ? void 0 : _b.values; const prevTotalValue = (_c = prevPowerValues === null || prevPowerValues === void 0 ? void 0 : prevPowerValues.find((it) => it.type === consumptionConstants_1.TOTAL)) === null || _c === void 0 ? void 0 : _c.value; const currTotalValue = (_d = currPowerValues === null || currPowerValues === void 0 ? void 0 : currPowerValues.find((it) => it.type === consumptionConstants_1.TOTAL)) === null || _d === void 0 ? void 0 : _d.value; if (prevTotalValue && currTotalValue) { if (prevTotalValue < currTotalValue) { return curr; } } } return prev; }); exports.getHighestConsumption = getHighestConsumption; const getTooltipContent = (period, year, periodText = 'Período') => `${periodText}\n${String(period).padStart(2, '0')}/${year}`; exports.getTooltipContent = getTooltipContent; const getPeriodData = (consumption, metric, type, forCsv, carbonDioxidePerKilowattHour, isCarbonFootprintTab) => { var _a; let value = 0; const consumptionValues = consumption === null || consumption === void 0 ? void 0 : consumption.find((data) => data.metric === metric); if (consumptionValues) { const typevalue = consumptionValues.values.find((data) => data.type === type); const forCsvValue = (_a = typevalue === null || typevalue === void 0 ? void 0 : typevalue.value) === null || _a === void 0 ? void 0 : _a.toString().replace('.', ','); value = typevalue && forCsv ? forCsvValue : typevalue && (typevalue === null || typevalue === void 0 ? void 0 : typevalue.value) && typeof (typevalue === null || typevalue === void 0 ? void 0 : typevalue.value) === 'string' ? typevalue === null || typevalue === void 0 ? void 0 : typevalue.value : Number(typevalue === null || typevalue === void 0 ? void 0 : typevalue.value) * (isCarbonFootprintTab ? (carbonDioxidePerKilowattHour !== null && carbonDioxidePerKilowattHour !== void 0 ? carbonDioxidePerKilowattHour : 1) : 1); } return value; }; exports.getPeriodData = getPeriodData; const processChartData = (unprocessedData, dataType, granularity, year, withLastYear, selectedPeriod, selectedDay, periodChartData, unit, carbonDioxidePerKilowattHour, isCarbonFootprintTab, roundMetricValue) => { var _a; const yearData = unprocessedData[year]; const periodLength = (0, exports.getGranularityLength)(granularity, yearData, selectedPeriod); const processedData = new Array(periodLength).fill(0); switch (granularity) { case YEAR: { if (!(0, array_1.isEmpty)(yearData === null || yearData === void 0 ? void 0 : yearData.periods)) { yearData.periods.forEach((period, index) => { var _a, _b; const periodName = `${String(period.period).padStart(2, '0')}/${Number(year) % 2000}`; const currentConsumption = period.current_consumption; const lastConsumption = period.last_consumption; const value = (currentConsumption && (0, exports.getPeriodData)(currentConsumption, dataType, consumptionConstants_1.TOTAL, false, carbonDioxidePerKilowattHour, isCarbonFootprintTab)) || 0; const lastValue = (lastConsumption && (0, exports.getPeriodData)(lastConsumption, dataType, consumptionConstants_1.TOTAL, false, carbonDioxidePerKilowattHour, isCarbonFootprintTab)) || 0; const isSmart = period.smart || false; const tooltipContent = (0, exports.getTooltipContent)(period.period, year); const lastYearTooltipContent = (0, exports.getTooltipContent)(period.period, Number(year) - 1); const lastYearIsSmart = (_b = (_a = unprocessedData[Number(year) - 1]) === null || _a === void 0 ? void 0 : _a.periods[index]) === null || _b === void 0 ? void 0 : _b.smart; processedData[period.period - 1] = Object.assign(Object.assign({ key: period.period, value }, (withLastYear ? { lastValue, lastYearTooltipContent, lastYearIsSmart } : {})), { mainLabel: periodName, stacked: false, selectable: isSmart, tooltipContent, isSmart }); }); } return processedData.map((data, index) => { if (data === 0) { const periodName = `${String(index + 1).padStart(2, '0')}/${Number(year) % 2000}`; const tooltipContent = (0, exports.getTooltipContent)(index + 1, year); return { key: index + 1, data, mainLabel: periodName, stacked: false, selectable: false, tooltipContent, isSmart: false, value: 0, }; } return data; }); } case PERIOD: { const period = yearData.periods.find((p) => p.period === selectedPeriod); if (period) { if (!(0, array_1.isEmpty)(period.days)) { const highestConsumptionDay = (0, exports.getHighestConsumption)(period.days); period.days.forEach((day) => { const index = (0, exports.getDateIndexInPeriod)(period.start_date, day.day); const currentConsumption = day.current_consumption; const value = (currentConsumption && (0, exports.getPeriodData)(currentConsumption, dataType, consumptionConstants_1.TOTAL, false, carbonDioxidePerKilowattHour, isCarbonFootprintTab)) || 0; const hiredPower = (currentConsumption && (0, exports.getPeriodData)(currentConsumption, dataType, consumptionConstants_1.HIRED_POWER_KEY, false, carbonDioxidePerKilowattHour, isCarbonFootprintTab)) || 0; const dayValue = (0, dayjs_1.default)(day.day, 'YYYY-MM-DD').tz().format('YYYY-MM-DD') || ''; const isHoliday = !day.workday || false; const dayNumber = (0, dayjs_1.default)(dayValue).tz().date(); const tooltipContent = `${(0, dayjs_1.default)(dayValue).tz().format('DD/MM/YY')}\n${roundMetricValue(value, dataType)} ${unit}`; processedData[index] = { key: dayValue, value, highlighted: isHoliday, mainLabel: String(dayNumber).padStart(2, '0'), secondaryLabel: consumptionConstants_1.DAYS[(0, dayjs_1.default)(dayValue).tz().day()], selectable: true, highlightColor: '#E6E6E6', isSmart: true, tooltipContent, overHiredPower: day === highestConsumptionDay && dataType === consumptionConstants_1.METRICS.POWER && value > hiredPower, }; }); } } return processedData.map((data, index) => { if (data === 0) { const dayValue = (0, dayjs_1.default)(period === null || period === void 0 ? void 0 : period.start_date, 'YYYY-MM-DD').tz().add(index, 'd').format('YYYY-MM-DD'); const dayNumber = (0, dayjs_1.default)(dayValue).tz().date(); const tooltipContent = `${(0, dayjs_1.default)(dayValue).tz().format('DD/MM/YY')}\n${0} ${unit}`; return { key: dayValue, value: 0, lastValue: false, mainLabel: String(dayNumber).padStart(2, '0'), secondaryLabel: consumptionConstants_1.DAYS[(0, dayjs_1.default)(dayValue).tz().day()], selectable: true, stacked: true, isSmart: true, tooltipContent, }; } return data; }); } case DAY: { const day = (_a = periodChartData === null || periodChartData === void 0 ? void 0 : periodChartData.days) === null || _a === void 0 ? void 0 : _a.find((d) => d.day === selectedDay); if (day) { const { hours } = day; if (hours && !(0, array_1.isEmpty)(hours)) { hours === null || hours === void 0 ? void 0 : hours.forEach((hour) => { const currentConsumption = hour.current_consumption; const value = currentConsumption && (0, exports.getPeriodData)(currentConsumption, dataType, consumptionConstants_1.TOTAL, false, carbonDioxidePerKilowattHour, isCarbonFootprintTab); const tooltipContent = `${roundMetricValue(value, dataType)} ${unit}`; processedData[hour.hour] = { key: hour.hour, value, mainLabel: String(hour.hour).padStart(2, '0'), selectable: false, stacked: true, isSmart: true, tooltipContent, }; }); } } return processedData.map((data, index) => { if (data === 0) { const tooltipContent = `0 ${unit}`; return { key: index, value: 0, mainLabel: String(index).padStart(2, '0'), selectable: false, stacked: true, isSmart: true, tooltipContent, }; } return data; }); } default: return processedData; } }; exports.processChartData = processChartData; const processTempData = (chartData, granularity, year, withLastYear, selectedPeriod) => { const yearData = chartData[year]; const periodLength = (0, exports.getGranularityLength)(granularity, yearData, selectedPeriod); const processedData = Array.from({ length: periodLength }, () => 0); switch (granularity) { case YEAR: { const { periods } = yearData; if (!(0, array_1.isEmpty)(periods)) { periods.forEach((period) => { const currentConsumption = period.current_consumption; const lastConsumption = period.last_consumption; const value = currentConsumption && (0, exports.getPeriodData)(currentConsumption, 'temperature', 'daily_avg', false, 0); const lastValue = lastConsumption && (0, exports.getPeriodData)(lastConsumption, 'temperature', 'daily_avg', false, 0); processedData[period.period - 1] = Object.assign(Object.assign({ value }, (withLastYear ? { lastValue } : {})), { xCoordinate: period.period - 1, isLinear: true }); }); } return processedData.filter((data) => data.value > 0); } case PERIOD: { const period = yearData.periods.find((p) => p.period === selectedPeriod); if (period) { if (!(0, array_1.isEmpty)(period.days)) { period.days.forEach((day) => { const index = (0, exports.getDateIndexInPeriod)(period.start_date, day.day); const currentConsumption = day.current_consumption; const value = currentConsumption && (0, exports.getPeriodData)(currentConsumption, 'temperature', 'hourly_avg', false, 0); processedData[index] = { value, xCoordinate: index, isLinear: true }; }); } } return processedData.filter((data) => data.value > 0); } default: { return []; } } }; exports.processTempData = processTempData; const getCurrentDay = (periodChartData, selectedDay) => { var _a; return (_a = periodChartData === null || periodChartData === void 0 ? void 0 : periodChartData.days) === null || _a === void 0 ? void 0 : _a.find((day) => day.day === selectedDay); }; exports.getCurrentDay = getCurrentDay; const getColors = (key, periodConcepts, defaultColor) => { var _a; return ((_a = periodConcepts.find((elem) => elem.reference === key || elem.label === key)) === null || _a === void 0 ? void 0 : _a.color) || defaultColor; }; exports.getColors = getColors; const processData = (unprocessedData, currentTab, year, withGradient, defaultTangentGradientColor) => { const yearData = unprocessedData[year]; const processedData = Array.from({ length: 12 }, () => 0); if (yearData) { const { periods } = yearData; if (!(0, array_1.isEmpty)(periods)) { periods.forEach((period) => { const currentConsumption = period.current_consumption; const value = (0, exports.getPeriodData)(currentConsumption, currentTab, 'total', false, 0); const periodName = `${period.period.toString().padStart(2, '0')}/${Number(year) % 2000}`; processedData[period.period - 1] = { value, mainLabel: periodName, key: consumptionConstants_1.TANGET_KEY, color: withGradient ? `url(#${consumptionConstants_1.TANGET_KEY})` : defaultTangentGradientColor, tooltipContent: `${periodName}\n**${Number(value).toFixed(2).replace('.', ',')}**`, }; }); } return processedData.map((data, index) => { if (data === 0) { const periodName = `${index < 9 ? '0' : ''}${index + 1}/${Number(year) % 2000}`; return { value: 0, mainLabel: periodName, key: index + 1 }; } return data; }); } }; exports.processData = processData; const generateCSVData = (consumptionHistory) => consumptionHistory.bills.map((period) => period && Object.assign({ year: period.year, month: period.month, period_started_on: period.period_started_on, period_ended_on: period.period_ended_on, consumption: period.consumption, consumption_on_peak: period.consumption_on_peak, consumption_remainder: period.consumption_remainder, consumption_valley: period.consumption_valley, amount: Number(period.amount).toFixed(2) || 0, power_billed_on_peak: period.power_billed_on_peak, power_billed_remainder: period.power_billed_remainder || 0, power_billed_valley: period.power_billed_valley || 0, phi_tangent: period.phi_tangent, purchased_power: period.purchased_power_on_peak, billed_power: period.billed_power }, (period.carbonFootprint ? { carbonFootprint: Number(period.carbonFootprint.toFixed(2)) } : {}))); exports.generateCSVData = generateCSVData; const addConcepts = (config, concepts, hasConcepts) => { if (!hasConcepts) return config; const newConfig = Object.assign({}, config); const newBars = concepts.map((concept, index) => ({ id: `Concept${index}`, key: concept, name: concept, })); newConfig.bars = newBars; return newConfig; }; exports.addConcepts = addConcepts; const removeDots = (value) => value.replace('.', ''); exports.removeDots = removeDots; const getLinearData = (bills = [], lines = [], isCarbonFootprintTab, carbonDioxidePerKilowattHour) => lines.map((line) => ({ data: bills.map((bill, index) => ({ xCoordinate: index, value: isCarbonFootprintTab ? bill[line.key] * carbonDioxidePerKilowattHour : bill[line.key], })), type: consumptionConstants_1.LINE_TYPES.CUSTOM, color: line.color, customLineProps: consumptionConstants_1.LINEAR_DATA_CUSTOMIZATION, })); exports.getLinearData = getLinearData; const getXAxisDefinition = (bills = [], billDetails, yearsToDisplay = [], getYearColor, activeColor, disabledColor, fullPeriodLabel = false, square, labelBackgroundPadding, namePeriodLabel = false) => bills.map(({ period, year }) => { const [periodMonth, periodYear] = period.split('/'); const formattedPeriod = (0, dayjs_1.default)(period, 'MM/YYYY'); const formattedMonth = formattedPeriod.format('MMM'); const isActiveValue = periodMonth === billDetails.month && periodYear === billDetails.year.toString(); const periodCircleColor = isActiveValue && getYearColor(yearsToDisplay, year); return { mainLabel: fullPeriodLabel ? `${periodMonth}/${String(periodYear).slice(2)}` : namePeriodLabel ? formattedMonth.charAt(0).toUpperCase() + formattedMonth.slice(1) : periodMonth, mainLabelStyles: { fontWeight: isActiveValue ? 'bold' : 'normal' }, color: isActiveValue ? activeColor : disabledColor, circle: isActiveValue && !square && Object.assign({ fill: periodCircleColor }, consumptionConstants_1.X_AXIS_CIRCLE_CUSTOMIZATION), square: isActiveValue && square, labelBackgroundPadding, }; }); exports.getXAxisDefinition = getXAxisDefinition; const getAnnualcarbonFootprintKpiValues = (carbonFootprintKpis) => { const carbonFootprintAnnualConsumption = carbonFootprintKpis .slice(-12) .reduce((acc, curr) => acc + curr.carbonFootprint, 0); const kmPerKilowattHourAnnual = carbonFootprintKpis .slice(-12) .reduce((acc, curr) => acc + curr.kmPerKilowattHour, 0); const treesPerKilowattHourAnnual = carbonFootprintKpis .slice(-12) .reduce((acc, curr) => acc + curr.treesPerKilowattHour, 0); return { carbonFootprintAnnualConsumption, kmPerKilowattHourAnnual, treesPerKilowattHourAnnual, }; }; exports.getAnnualcarbonFootprintKpiValues = getAnnualcarbonFootprintKpiValues; const isPeriodCurrentYear = (period) => { const year = period.split('/')[1]; return (0, dayjs_1.default)().tz().format('YYYY') === year; }; exports.isPeriodCurrentYear = isPeriodCurrentYear; const formatPeriod = (period, monthYearFormat = false) => { const [month, year] = period.split('/'); return monthYearFormat ? `${month}/${year.slice(2, 4)}` : `${year.slice(2, 4)}/${month}`; }; exports.formatPeriod = formatPeriod; const getBarData = (consumptionData, colors, highlightColors) => consumptionData.map((_a) => { var { period, consumption } = _a, item = __rest(_a, ["period", "consumption"]); return (Object.assign(Object.assign({}, item), { isCurrentYear: (0, exports.isPeriodCurrentYear)(period), value: consumption, color: (0, exports.isPeriodCurrentYear)(period) ? colors.CURRENT_YEAR : colors.LAST_YEAR, clickable: true, highlightColor: (0, exports.isPeriodCurrentYear)(period) ? highlightColors.CURRENT_YEAR : highlightColors.LAST_YEAR, bimester: (0, exports.formatPeriod)(period) })); }); exports.getBarData = getBarData; const getXAxisDefinitionV0 = (consumptionData, monthYearFormat, colors) => consumptionData.map(({ period }) => ({ mainLabel: (0, exports.formatPeriod)(period, monthYearFormat), selectedLabelBackground: (0, exports.isPeriodCurrentYear)(period) ? colors.SELECTED_LABEL : colors.LAST_YEAR_SELECTED_LABEL, labelBackgroundPadding: 11, })); exports.getXAxisDefinitionV0 = getXAxisDefinitionV0; const lastYearCheck = ({ isCurrentYear, value }) => isCurrentYear === false && !!value; const currentYearCheck = ({ isCurrentYear, value }) => isCurrentYear === true && !!value; const references = (styles) => [ { id: consumptionConstants_1.LAST_YEAR, label: 'Año anterior', className: styles[consumptionConstants_1.LAST_YEAR], check: lastYearCheck, }, { id: consumptionConstants_1.CURRENT_YEAR, label: 'Año actual', className: styles[consumptionConstants_1.CURRENT_YEAR], check: currentYearCheck, }, ]; exports.references = references; const handleCheckProfile = (currentAccount, goToDashboard, getForm, openAlertDialog, notifyEventToUtility, notifyText) => { const { can_view_consumptions: canViewConsumptions } = currentAccount || {}; if (canViewConsumptions === false) { goToDashboard(); const handleOnClick = async () => { getForm(); }; openAlertDialog(handleOnClick); notifyEventToUtility(notifyText, 'info'); return false; } return true; }; exports.handleCheckProfile = handleCheckProfile; const desagregateConcepts = (bill) => { var _a; if ((0, array_1.isEmpty)(bill.concepts || [])) return {}; const concepts = {}; let totalConceptsAmount = 0; (_a = bill.concepts) === null || _a === void 0 ? void 0 : _a.forEach((item) => { concepts[item.concept] = item.amount; totalConceptsAmount += item.amount; }); return Object.assign(Object.assign({}, concepts), { totalConceptsAmount }); }; exports.desagregateConcepts = desagregateConcepts; const generateCarbonFootprintData = (consumption, coefficients) => { if (!coefficients) return {}; const { km_per_kilowatt_hour: kmPerKilowattHour, trees_per_kilowatt_hour: treesPerKilowattHour, sheets_per_kilowatt_hour: sheetsPerKilowattHour, carbon_dioxide_per_kilowatt_hour: carbonDioxidePerKilowattHour, } = coefficients; return { carbonFootprint: (consumption || 0) * carbonDioxidePerKilowattHour, kmPerKilowattHour: (consumption || 0) * kmPerKilowattHour, treesPerKilowattHour: (consumption || 0) * treesPerKilowattHour, sheetsPerKilowattHour: (consumption || 0) * sheetsPerKilowattHour, }; }; exports.generateCarbonFootprintData = generateCarbonFootprintData; const getConcepts = (history) => { if ((0, array_1.isEmpty)(history)) return []; const concepts = []; history.forEach((bill) => { var _a; if ((0, array_1.isEmpty)(bill.concepts || [])) return; const keys = (_a = bill.concepts) === null || _a === void 0 ? void 0 : _a.map((item) => item.concept); if (keys) { concepts.push(...keys); } }); return [...new Set(concepts)]; }; exports.getConcepts = getConcepts; const generateCarbonFootprintTotalConsumption = (periodConsumptionType, carbonFootprintCoefficient) => { var _a, _b; return periodConsumptionType.push({ metric: 'carbonFootprint', values: [ { magnitude: 'huella de carbono', type: 'total', unit: 'kgCO2', value: (((_b = (_a = periodConsumptionType .find((consumption) => consumption.metric === consumptionConstants_1.METRICS.ENERGY)) === null || _a === void 0 ? void 0 : _a.values.find((consumptionValue) => consumptionValue.type === consumptionConstants_1.TOTAL)) === null || _b === void 0 ? void 0 : _b.value) || 0) * carbonFootprintCoefficient, }, ], }); }; exports.generateCarbonFootprintTotalConsumption = generateCarbonFootprintTotalConsumption; const isCurrentPeriod = (periodEndDate) => (0, dayjs_1.default)(periodEndDate).tz().isSameOrAfter((0, dayjs_1.default)().tz(), 'day'); exports.isCurrentPeriod = isCurrentPeriod; const getMostRecentYear = (chartData) => `${Object.keys(chartData) .map((key) => parseInt(key, 10)) .reduce((acc, current) => Math.max(acc, current), 0)}`; exports.getMostRecentYear = getMostRecentYear; const getAvailableYears = (chartData) => Object.keys(chartData).map((year) => ({ value: year, label: year })); exports.getAvailableYears = getAvailableYears; const hasPreviousNonSmartDataCheck = ({ lastYearIsSmart, value, isCurrentYear, }) => isCurrentYear === false && lastYearIsSmart === false && !!value; exports.hasPreviousNonSmartDataCheck = hasPreviousNonSmartDataCheck; const hasPreviousSmartDataCheck = ({ lastYearIsSmart, value, isCurrentYear, }) => isCurrentYear === false && lastYearIsSmart === true && !!value; exports.hasPreviousSmartDataCheck = hasPreviousSmartDataCheck; const hasCurrentSmartDataCheck = ({ isSmart, value, isCurrentYear, }) => isCurrentYear === true && isSmart === true && !!value; exports.hasCurrentSmartDataCheck = hasCurrentSmartDataCheck; const hasCurrentNonSmartDataCheck = ({ isSmart, value, isCurrentYear, }) => isCurrentYear === true && isSmart === false && !!value; exports.hasCurrentNonSmartDataCheck = hasCurrentNonSmartDataCheck; const hasCurrentAverageTemperatureCheck = ({ value, isCurrentYear, }) => isCurrentYear === true && !!value; exports.hasCurrentAverageTemperatureCheck = hasCurrentAverageTemperatureCheck; const hasPreviousAverageTemperatureCheck = ({ value, isCurrentYear, }) => isCurrentYear === false && !!value; exports.hasPreviousAverageTemperatureCheck = hasPreviousAverageTemperatureCheck; const hasHolidaysCheck = ({ highlighted }) => highlighted; exports.hasHolidaysCheck = hasHolidaysCheck; const hasExceededPowerCheck = ({ overHiredPower }) => overHiredPower; exports.hasExceededPowerCheck = hasExceededPowerCheck; const hasAmount = (id) => ({ id: ownId, value }) => ownId === id && !!value; exports.hasAmount = hasAmount; const getMetricByType = (currentPeriod, consumptionType, consumptionMetric, metricType) => { var _a, _b, _c; return ((_c = (_b = (_a = currentPeriod === null || currentPeriod === void 0 ? void 0 : currentPeriod[consumptionType]) === null || _a === void 0 ? void 0 : _a.find((consumption) => consumption.metric === consumptionMetric)) === null || _b === void 0 ? void 0 : _b.values) === null || _c === void 0 ? void 0 : _c.find((metric) => metric.type === metricType)) || 0; }; exports.getMetricByType = getMetricByType; const noValues = (data, isArray) => !data.some((periodData) => (isArray ? !(0, array_1.isEmpty)(periodData.values || []) : periodData.value >= 0)); exports.noValues = noValues; const noImportAmountValues = (data) => !data.some((periodData) => periodData.current || periodData.projected); exports.noImportAmountValues = noImportAmountValues; const getCurrentPeriod = (chartData, selectedYear, selectedPeriod) => { var _a; const yearData = chartData[selectedYear]; return (_a = yearData === null || yearData === void 0 ? void 0 : yearData.periods) === null || _a === void 0 ? void 0 : _a.find((p) => p.period === selectedPeriod); }; exports.getCurrentPeriod = getCurrentPeriod; const linearScaler = (domain, range) => d3.scaleLinear().domain(domain).range(range); exports.linearScaler = linearScaler; const getStartAngle = (elem, numOfElements) => (elem / numOfElements) * 2 * Math.PI; exports.getStartAngle = getStartAngle; const getEndAngle = (elem, numOfElements) => ((elem + 1) / numOfElements) * 2 * Math.PI; exports.getEndAngle = getEndAngle; const hasPeriodFinished = (period) => (0, dayjs_1.default)() >= (0, dayjs_1.default)(period.end_date).tz().endOf('day'); exports.hasPeriodFinished = hasPeriodFinished; const isFuturePeriod = (period) => (0, dayjs_1.default)() <= (0, dayjs_1.default)(period.start_date).tz().startOf('day'); exports.isFuturePeriod = isFuturePeriod; const getpercentageOfPeriod = (period) => { if ((0, exports.hasPeriodFinished)(period)) return 100; const totalDuration = (0, exports.getPeriodDuration)(period.start_date, period.end_date); const daysPassed = (0, exports.getPeriodDuration)(period.start_date, (0, dayjs_1.default)().tz().format()); return (daysPassed / totalDuration) * 100; }; exports.getpercentageOfPeriod = getpercentageOfPeriod; const percentage = (percent, total) => percent && total ? (percent * 100) / total : 0; exports.percentage = percentage; const getConsumptionPercentage = ({ highestConsumptionAmount, hiredPowerValue, isOverHired, }) => { const referenceValue = isOverHired ? highestConsumptionAmount : hiredPowerValue; const comparatorValue = isOverHired ? hiredPowerValue : highestConsumptionAmount; return referenceValue ? (comparatorValue * 100) / referenceValue : 0; }; exports.getConsumptionPercentage = getConsumptionPercentage; const getDaysFromData = (chartData, currentYear, currentPeriod) => { var _a; const periods = ((_a = chartData === null || chartData === void 0 ? void 0 : chartData[currentYear]) === null || _a === void 0 ? void 0 : _a.periods) || []; const period = periods.find((p) => p.period === currentPeriod); if (period) { return period.days; } return []; }; exports.getDaysFromData = getDaysFromData; const getInitialValues = (granularity, currentYear, currentPeriod, currentDay) => { switch (granularity) { case YEAR: return { label: currentYear, value: currentYear }; case PERIOD: return { label: currentPeriod, value: currentPeriod }; case DAY: return { label: currentDay, value: currentDay }; } }; exports.getInitialValues = getInitialValues; const granularitySelectionOptions = (chartData, selectedYear, periods = [], selectedPeriod, days = [], returnToGranularity, enableSelection) => (Object.assign(Object.assign({ [YEAR]: [ ...(enableSelection.year ? [ { selectable: true, options: (0, exports.getAvailableYears)(chartData), }, ] : []), ] }, (selectedYear ? { [PERIOD]: [ ...(enableSelection.year ? [ { selectable: false, value: selectedYear, onClick: () => returnToGranularity && returnToGranularity(YEAR, selectedYear), }, ] : []), ...(enableSelection.period ? [ { selectable: true, options: periods .filter((period) => period.smart) .map((period) => ({ value: period.period, label: `${period.period < 10 ? '0' : ''}${period.period}/${period.year % 2000}`, })), }, ] : []), ], } : {})), (selectedYear && selectedPeriod ? { [DAY]: [ ...(enableSelection.year ? [ { selectable: false, value: selectedYear, onClick: () => returnToGranularity && returnToGranularity(YEAR, selectedYear), }, ] : []), { selectable: false, value: `${selectedPeriod < 10 ? '0' : ''}${selectedPeriod}/${Number(selectedYear) % 2000}`, onClick: () => returnToGranularity && returnToGranularity(PERIOD, selectedPeriod), }, { selectable: true, options: days.map((day) => ({ label: (0, dayjs_1.default)(day.day).tz().format('DD/MM/YY').toUpperCase(), value: day.day, })), }, ], } : {}))); exports.granularitySelectionOptions = granularitySelectionOptions; const getBreadCrumbsOptions = (chartData, currentYear, currentPeriod, granularity, returnToGranularity, enableSelection) => { var _a; const periods = ((_a = chartData === null || chartData === void 0 ? void 0 : chartData[currentYear]) === null || _a === void 0 ? void 0 : _a.periods) || []; const days = (0, exports.getDaysFromData)(chartData, currentYear, currentPeriod); const breadcrumbsOptions = (0, exports.granularitySelectionOptions)(chartData, currentYear, periods, currentPeriod, days, returnToGranularity, enableSelection)[granularity]; return breadcrumbsOptions; }; exports.getBreadCrumbsOptions = getBreadCrumbsOptions; const changeValue = (indexOfCurrentValue, options, handleOnChange, nextValue) => { var _a, _b; return handleOnChange(nextValue ? (_a = options[indexOfCurrentValue + 1]) === null || _a === void 0 ? void 0 : _a.value : (_b = options[indexOfCurrentValue - 1]) === null || _b === void 0 ? void 0 : _b.value); }; exports.changeValue = changeValue;