import { requiredKeys } from '../../keys/required';
/**
* Calculate co2_kwh, pp_kwh and use_pct for all tariffs
* @module
* @since 1.2.21
*/
/**
* calculate co2_kwh and pp_kwh for a single tariff
* @param {struct} tariff tariff with co2_kwh, pp_kwh, vat_pct and use_pct minimum
* @returns {struct}
*/
const calculateSingleTariffUsage = (tariff) => ({
co2_kwh: tariff.co2_kwh * (tariff.use_pct / 100),
pp_kwh: tariff.pp_kwh * (tariff.use_pct / 100),
vat_pct: tariff.vat_pct * (tariff.use_pct / 100),
use_pct: parseFloat(tariff.use_pct),
});
/**
* calculate co2_kwh and pp_kwh for a single tariff
* @param {struct} tariff tariff with co2_kwh, pp_kwh, vat_pct and use_pct minimum
* @param {struct} skv_return result object for consecutive calculations
* @returns {struct}
*/
const calculateTariff = (tariff, skv_return) => {
const rst_calculation = calculateSingleTariffUsage(tariff);
const skv_calculated_tariff = {
co2_kwh: rst_calculation.co2_kwh,
pp_kwh: rst_calculation.pp_kwh,
vat_pct: rst_calculation.vat_pct,
use_pct: rst_calculation.use_pct,
};
const skv_result = {
skv_return,
calculated_tariff: skv_calculated_tariff,
};
skv_result.skv_return.co2_kwh += skv_calculated_tariff.co2_kwh;
skv_result.skv_return.pp_kwh += skv_calculated_tariff.pp_kwh;
skv_result.skv_return.vat_pct += skv_calculated_tariff.vat_pct;
return skv_result;
};
/**
* calculate co2_kwh and pp_kwh for all tariffs
* @param {array} arr_tariffs array of user selected tariffs with usage percentages
* @returns {struct}
*/
const calculateUsages = (arr_tariffs) => {
let skv_return = {
co2_kwh: 0,
pp_kwh: 0,
vat_pct: 0,
};
let num_use_pct = 0;
const arr_usage_tariffs = arr_tariffs;
// Skip first tariff as percentage will be assigned to remaining pecentage
for (let i = 1; i < arr_usage_tariffs.length; i += 1) {
const tariff = arr_usage_tariffs[i];
const required_keys = ['pp_kwh', 'co2_kwh', 'vat_pct', 'use_pct'];
// Check required keys are present
const rst_required_keys = requiredKeys(tariff, required_keys);
if (!rst_required_keys.success) {
throw new Error(`Tariff at index ${i} is missing required keys ${rst_required_keys.data}`);
}
// Calculate collective co2_kwh and pp_kwh for all tariffs
const rst_calculation = calculateTariff(tariff, skv_return);
skv_return = rst_calculation.skv_return;
arr_usage_tariffs[i].calculated = rst_calculation.calculated_tariff;
num_use_pct += arr_usage_tariffs[i].calculated.use_pct;
}
if (num_use_pct > 100) {
throw new Error(`Total use percentage exceeds 100% by ${num_use_pct - 100}, please review your tariffs`);
}
// Assign remaining percentage to first tariff
arr_usage_tariffs[0].use_pct = 100 - num_use_pct < 0 ? 0 : 100 - num_use_pct;
const rst_calculation = calculateTariff(arr_usage_tariffs[0], skv_return);
skv_return = rst_calculation.skv_return;
arr_usage_tariffs[0].calculated = rst_calculation.calculated_tariff;
skv_return.arr_tariffs = arr_usage_tariffs;
return skv_return;
};
export {
calculateUsages,
calculateTariff,
calculateSingleTariffUsage,
};