Files
bodyshop/server/utils/calculateStatusDuration.js
Dave Richer f8408908b2 - Major Progress Commit
Signed-off-by: Dave Richer <dave@imexsystems.ca>
2024-01-24 21:40:05 -05:00

80 lines
2.9 KiB
JavaScript

const durationToHumanReadable = require("./durationToHumanReadable");
const moment = require("moment");
const _ = require("lodash");
const crypto = require('crypto');
const getColor = (key) => {
const hash = crypto.createHash('sha256');
hash.update(key);
const hashedKey = hash.digest('hex');
const num = parseInt(hashedKey, 16);
return '#' + (num % 16777215).toString(16).padStart(6, '0');
};
const calculateStatusDuration = (transitions) => {
let statusDuration = {};
let totalDuration = 0;
let summations = [];
transitions.forEach((transition, index) => {
let duration = transition.duration;
totalDuration += duration;
if (!transition.prev_value) {
statusDuration[transition.value] = {
value: duration,
humanReadable: transition.duration_readable
};
} else if (!transition.next_value) {
if (statusDuration[transition.value]) {
statusDuration[transition.value].value += duration;
statusDuration[transition.value].humanReadable = transition.duration_readable;
} else {
statusDuration[transition.value] = {
value: duration,
humanReadable: transition.duration_readable
};
}
} else {
if (statusDuration[transition.value]) {
statusDuration[transition.value].value += duration;
statusDuration[transition.value].humanReadable = transition.duration_readable;
} else {
statusDuration[transition.value] = {
value: duration,
humanReadable: transition.duration_readable
};
}
}
});
// Calculate the percentage for each status
// Calculate the percentage for each status
let totalPercentage = 0;
const statusKeys = Object.keys(statusDuration);
statusKeys.forEach((status, index) => {
if (index !== statusKeys.length - 1) {
const percentage = (statusDuration[status].value / totalDuration) * 100;
totalPercentage += percentage;
statusDuration[status].percentage = percentage;
} else {
statusDuration[status].percentage = 100 - totalPercentage;
}
});
for (let [status, {value, humanReadable}] of Object.entries(statusDuration)) {
if (status !== 'total') {
summations.push({status, value, humanReadable, percentage: statusDuration[status].percentage, color: getColor(status), roundedPercentage: `${Math.round(statusDuration[status].percentage)}%`});
}
}
const humanReadableTotal = durationToHumanReadable(moment.duration(totalDuration));
return {
summations: _.orderBy(summations, ['value'], ['asc']),
totalStatuses: summations.length,
total: totalDuration,
humanReadableTotal
};
}
module.exports = calculateStatusDuration;