364 lines
12 KiB
JavaScript
364 lines
12 KiB
JavaScript
export const REPORT_TIMEOUT = 120000;
|
|
export const HIERARCHY_PARTITION = 'rapport-gennovadc';
|
|
const FIRST_REPORT_MONTH = new Date(2025, 6, 1);
|
|
|
|
const MONTH_ABBR = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
|
|
|
|
export function monthName(date) {
|
|
return date.toLocaleString('en-US', { month: 'long', year: 'numeric' });
|
|
}
|
|
|
|
export function currentMonth() {
|
|
return monthName(new Date());
|
|
}
|
|
|
|
export function reportMonths() {
|
|
const months = [];
|
|
const end = new Date();
|
|
end.setDate(1);
|
|
const cursor = new Date(FIRST_REPORT_MONTH);
|
|
while (cursor <= end) {
|
|
months.push(monthName(cursor));
|
|
cursor.setMonth(cursor.getMonth() + 1);
|
|
}
|
|
return months.reverse();
|
|
}
|
|
|
|
export function isNumeric(value) {
|
|
if (typeof value === 'number') return Number.isFinite(value);
|
|
if (typeof value !== 'string' || value.trim() === '') return false;
|
|
return Number.isFinite(Number(value));
|
|
}
|
|
|
|
function toNumber(value) {
|
|
return isNumeric(value) ? Number(value) : 0;
|
|
}
|
|
|
|
function numberFormat(value, decimals = 0) {
|
|
return Number(value).toLocaleString('en-US', {
|
|
minimumFractionDigits: decimals,
|
|
maximumFractionDigits: decimals,
|
|
});
|
|
}
|
|
|
|
export function formatCell(value, format = 'auto') {
|
|
if (value === null || value === undefined || value === '') return '';
|
|
if (!isNumeric(value)) return typeof value === 'object' ? '' : String(value);
|
|
const num = Number(value);
|
|
if (format === 'int') return numberFormat(num);
|
|
return Number.isInteger(num) ? numberFormat(num) : numberFormat(num, 2);
|
|
}
|
|
|
|
export function excelValue(value) {
|
|
if (value === null || value === undefined) return '';
|
|
if (isNumeric(value)) return Number(value);
|
|
return typeof value === 'object' ? '' : value;
|
|
}
|
|
|
|
function ucwords(text) {
|
|
return String(text).replace(/(^|\s)(\S)/g, (_, space, char) => space + char.toUpperCase());
|
|
}
|
|
|
|
function keyLabel(key) {
|
|
return ucwords(String(key).replace(/[_-]/g, ' '));
|
|
}
|
|
|
|
function percent(numerator, denominator) {
|
|
return denominator > 0 ? `${Math.round((numerator / denominator) * 100)}%` : '0%';
|
|
}
|
|
|
|
function asArray(value) {
|
|
return Array.isArray(value) ? value : [];
|
|
}
|
|
|
|
/** Lambda responses are sometimes wrapped as { body: "<json>" }. */
|
|
export function reportData(payload) {
|
|
if (!payload) return {};
|
|
if (payload.body !== undefined) {
|
|
let body = payload.body;
|
|
if (typeof body === 'string') {
|
|
try {
|
|
body = JSON.parse(body);
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
return body?.data || {};
|
|
}
|
|
return payload.data || {};
|
|
}
|
|
|
|
function cellValue(row, key, nestedKey = null) {
|
|
const value = row && typeof row === 'object' ? row[key] : undefined;
|
|
if (nestedKey === null) return value ?? '';
|
|
return value && typeof value === 'object' ? (value[nestedKey] ?? '') : '';
|
|
}
|
|
|
|
function columnsFromFirstRow(items, format) {
|
|
if (!items.length) return [];
|
|
const keys = Object.keys(items[0]);
|
|
keys.sort((a, b) => (a === 'product_name' ? -1 : b === 'product_name' ? 1 : 0));
|
|
return keys.map((key) => ({ key, label: keyLabel(key), format }));
|
|
}
|
|
|
|
function sumColumns(items, keys) {
|
|
const totals = {};
|
|
keys.forEach((key) => {
|
|
totals[key] = items.reduce((sum, item) => sum + toNumber(item?.[key]), 0);
|
|
});
|
|
return totals;
|
|
}
|
|
|
|
export function buildMonthlySummary(data) {
|
|
const items = asArray(data.item);
|
|
const columns = columnsFromFirstRow(items, 'auto');
|
|
const totals = sumColumns(items, columns.map((col) => col.key).filter((key) => key !== 'product_name'));
|
|
const total = items.length
|
|
? columns.map((col, index) => {
|
|
if (index === 0) return 'Total';
|
|
if (col.key === 'percent_ach') return percent(totals.units_ach, totals.units_plan);
|
|
return totals[col.key] ?? 0;
|
|
})
|
|
: null;
|
|
return { columns, rows: items, total };
|
|
}
|
|
|
|
export function buildWeeklySummary(data) {
|
|
const items = asArray(data.item);
|
|
const columns = columnsFromFirstRow(items, 'int');
|
|
const totals = sumColumns(items, columns.map((col) => col.key).filter((key) => key !== 'product_name'));
|
|
const total = items.length
|
|
? columns.map((col, index) => {
|
|
if (index === 0) return 'Total';
|
|
if (col.key === 'percent_ach') return percent(totals.units_ach, totals.month_plan);
|
|
return totals[col.key] ?? 0;
|
|
})
|
|
: null;
|
|
return { columns, rows: items, total };
|
|
}
|
|
|
|
export function buildCenterSummary(data) {
|
|
const items = asArray(data.item);
|
|
const apiTotal = data.total && typeof data.total === 'object' ? data.total : null;
|
|
const columns = columnsFromFirstRow(items, 'int');
|
|
const total = items.length && apiTotal
|
|
? columns.map((col, index) => {
|
|
if (index === 0) return 'Total';
|
|
if (col.key === 'percent_ach') return percent(toNumber(apiTotal.centers_ach), toNumber(apiTotal.centers_plan));
|
|
return toNumber(apiTotal[col.key]);
|
|
})
|
|
: null;
|
|
return { columns, rows: items, total };
|
|
}
|
|
|
|
/** Current month first, then the previous 11 (matches the reports API rolling window). */
|
|
function rolling12MonthColumns() {
|
|
const now = new Date();
|
|
const months = [];
|
|
for (let i = 0; i < 12; i += 1) {
|
|
const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
|
months.push({
|
|
key: `${MONTH_ABBR[date.getMonth()]}_${date.getFullYear()}`,
|
|
label: date.toLocaleString('en-US', { month: 'short', year: 'numeric' }),
|
|
});
|
|
}
|
|
return months;
|
|
}
|
|
|
|
function trendMonthKeyLabel(key) {
|
|
const match = /^([A-Z]{3})_(\d{4})$/.exec(key);
|
|
if (!match) return key;
|
|
const monthIndex = MONTH_ABBR.indexOf(match[1]);
|
|
if (monthIndex < 0) return key;
|
|
return new Date(Number(match[2]), monthIndex, 1).toLocaleString('en-US', { month: 'short', year: 'numeric' });
|
|
}
|
|
|
|
/** Use API months when present and year-aware; legacy keys like "JAN" fall back to a rolling 12 months. */
|
|
function trendMonthColumns(data) {
|
|
const months = asArray(data.months);
|
|
const firstKey = months[0]?.key || '';
|
|
if (firstKey && !/^[A-Z]{3}$/.test(firstKey)) return months;
|
|
return rolling12MonthColumns();
|
|
}
|
|
|
|
export function buildTrendSummary(data) {
|
|
const items = asArray(data.item);
|
|
const columns = [
|
|
{ key: 'product_name', label: 'Product Name', format: 'int' },
|
|
...trendMonthColumns(data)
|
|
.filter((month) => month?.key)
|
|
.map((month) => ({ key: month.key, label: month.label || trendMonthKeyLabel(month.key), format: 'int' })),
|
|
];
|
|
const apiTotal = data.total && typeof data.total === 'object' && Object.keys(data.total).length ? data.total : null;
|
|
const totals = apiTotal || sumColumns(items, columns.slice(1).map((col) => col.key));
|
|
const total = items.length
|
|
? columns.map((col, index) => (index === 0 ? 'Total' : toNumber(totals[col.key])))
|
|
: null;
|
|
return { columns, rows: items, total };
|
|
}
|
|
|
|
const WEEKS = ['Week-1', 'Week-2', 'Week-3', 'Week-4'];
|
|
|
|
export function buildTransplantPenetration(data) {
|
|
const items = asArray(data.transplant_penetration);
|
|
const flat = [
|
|
['Transplant Type', 'Transplant Type'],
|
|
['Monthly Expected no. of Transplant', 'Monthly Expected no. of Transplant'],
|
|
['Gennova Share Dennovo Plan', 'Gennova Share Denovo Plan'],
|
|
['Gennova Share Switch Plan', 'Gennova Share Switch Plan'],
|
|
['Gennova Share Graftsol Tx Plan', 'Gennova Share Graftsol Tx Plan'],
|
|
['Total Actual Transplants', 'Total Actual Transplants'],
|
|
];
|
|
const groups = [
|
|
['Gennova Share Dennovo Actual', 'Gennova Share Denovo Actual'],
|
|
['Gennova Share Switch Actual', 'Gennova Share Switch Actual'],
|
|
['Gennova Share Graftsol Tx Actual', 'Gennova Share Graftsol Tx Actual'],
|
|
];
|
|
const columns = [
|
|
...flat.map(([key, label]) => ({ key, label })),
|
|
...groups.flatMap(([key, group]) =>
|
|
WEEKS.map((week) => ({ key, nestedKey: week, label: week, group })),
|
|
),
|
|
];
|
|
return { columns, rows: items, total: null };
|
|
}
|
|
|
|
const TRANSPLANT_SUMMARY_FLAT = [
|
|
['Position Codes', 'Position Code'],
|
|
['Total Transplants Plan', 'Total Transplants Expected'],
|
|
['Total Transplants Actual', 'Total Transplants Actual'],
|
|
['Gennova Share Denovo Plan', 'Gennova Share Denovo Plan'],
|
|
['Gennova Share Denovo Actual', 'Gennova Share Denovo Actual'],
|
|
['Gennova Share Switch Plan', 'Gennova Share Switch Plan'],
|
|
['Gennova Share Switch Actual', 'Gennova Share Switch Actual'],
|
|
['Gennova Share Graftsol Tx Plan', 'Gennova Share Graftsol Tx Plan'],
|
|
['Gennova Share Graftsol Tx Actual', 'Gennova Share Graftsol Tx Actual'],
|
|
];
|
|
|
|
const TRANSPLANT_SUMMARY_GROUPS = [
|
|
{
|
|
name: 'Kidney Transplant',
|
|
columns: [
|
|
['Kidney Tx Actual', 'Kidney Tx Actual'],
|
|
['Kidney Gennova Share Denovo Actual', 'Gennova Share Denovo Actual'],
|
|
['Kidney Gennova Share Switch Actual', 'Gennova Share Switch Actual'],
|
|
['Kidney Gennova Share Graftsol Tx Actual', 'Gennova Share Graftsol Tx Actual'],
|
|
],
|
|
},
|
|
{
|
|
name: 'Liver Transplant',
|
|
columns: [
|
|
['Liver Tx Actual', 'Liver Tx Actual'],
|
|
['Liver Gennova Share Denovo Actual', 'Gennova Share Denovo Actual'],
|
|
['Liver Gennova Share Switch Actual', 'Gennova Share Switch Actual'],
|
|
['Liver Gennova Share Graftsol Tx Actual', 'Gennova Share Graftsol Tx Actual'],
|
|
],
|
|
},
|
|
{
|
|
name: 'Cardioplegia',
|
|
columns: [
|
|
['Cardioplegia Plan', 'Cardioplegia Expected'],
|
|
['Cardioplegia Actual', 'Cardioplegia Actual'],
|
|
['Gennova Share Graftsol Cardioplegia', 'Gennova Share Graftsol Cardioplegia'],
|
|
],
|
|
},
|
|
];
|
|
|
|
export function buildTransplantSummary(data) {
|
|
const items = asArray(data.transplant_summary ?? data.item);
|
|
const columns = [
|
|
...TRANSPLANT_SUMMARY_FLAT.map(([key, label], index) => ({
|
|
key,
|
|
label,
|
|
className: index === TRANSPLANT_SUMMARY_FLAT.length - 1 ? 'ts-section-end' : undefined,
|
|
})),
|
|
...TRANSPLANT_SUMMARY_GROUPS.flatMap((group) =>
|
|
group.columns.map(([key, label], index) => ({
|
|
key,
|
|
label,
|
|
group: group.name,
|
|
className: index === 0 ? 'ts-group-start' : undefined,
|
|
})),
|
|
),
|
|
];
|
|
return { columns, rows: items, total: null, bordered: true };
|
|
}
|
|
|
|
function activityLabel(text) {
|
|
return ucwords(String(text).replace(/_/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase());
|
|
}
|
|
|
|
function activityMonthTime(label) {
|
|
const match = /^([A-Za-z]{3})-(\d{2})$/.exec(label);
|
|
if (!match) return 0;
|
|
const monthIndex = MONTH_ABBR.indexOf(match[1].toUpperCase());
|
|
return monthIndex < 0 ? 0 : new Date(2000 + Number(match[2]), monthIndex, 1).getTime();
|
|
}
|
|
|
|
const ACTIVITY_HIDDEN = ['Position_id', 'Position_owner'];
|
|
const ACTIVITY_PREFERRED = ['Product Name', '8. Activity', 'Activity', 'Month Plan', 'Month Actl', 'Month Actual'];
|
|
|
|
export function buildActivitySummary(data) {
|
|
const items = asArray(data.activity_summary ?? data.item);
|
|
if (!items.length) return { columns: [], rows: [], total: null };
|
|
|
|
let flatCols = [];
|
|
const nestedCols = [];
|
|
Object.entries(items[0]).forEach(([key, value]) => {
|
|
if (ACTIVITY_HIDDEN.includes(key)) return;
|
|
if (value && typeof value === 'object') {
|
|
Object.keys(value).forEach((subKey) => {
|
|
nestedCols.push({ key, nestedKey: subKey, label: `${activityLabel(key)} - ${activityLabel(subKey)}` });
|
|
});
|
|
} else {
|
|
flatCols.push({ key, label: activityLabel(key) });
|
|
}
|
|
});
|
|
|
|
const ordered = [];
|
|
ACTIVITY_PREFERRED.forEach((label) => {
|
|
const index = flatCols.findIndex((col) => col.label === label);
|
|
if (index >= 0) {
|
|
ordered.push(flatCols[index]);
|
|
flatCols = flatCols.filter((_, i) => i !== index);
|
|
}
|
|
});
|
|
|
|
const isMonth = (col) => /^[A-Za-z]{3}-\d{2}$/.test(col.label);
|
|
const months = flatCols.filter(isMonth).sort((a, b) => activityMonthTime(b.label) - activityMonthTime(a.label));
|
|
const rest = flatCols.filter((col) => !isMonth(col));
|
|
|
|
return { columns: [...ordered, ...rest, ...months, ...nestedCols], rows: items, total: null };
|
|
}
|
|
|
|
export function rowValue(row, column) {
|
|
return cellValue(row, column.key, column.nestedKey ?? null);
|
|
}
|
|
|
|
/**
|
|
* Header rows for a table model. Columns sharing a `group` are merged under one
|
|
* top-level cell; ungrouped columns span both rows.
|
|
*/
|
|
export function headerRows(columns) {
|
|
const hasGroups = columns.some((col) => col.group);
|
|
if (!hasGroups) {
|
|
return [columns.map((col, index) => ({ label: col.label, colSpan: 1, rowSpan: 1, column: index }))];
|
|
}
|
|
const top = [];
|
|
const bottom = [];
|
|
columns.forEach((col, index) => {
|
|
if (!col.group) {
|
|
top.push({ label: col.label, colSpan: 1, rowSpan: 2, column: index });
|
|
return;
|
|
}
|
|
const last = top[top.length - 1];
|
|
if (last && last.group === col.group && last.column + last.colSpan === index) {
|
|
last.colSpan += 1;
|
|
} else {
|
|
top.push({ label: col.group, group: col.group, colSpan: 1, rowSpan: 1, column: index });
|
|
}
|
|
bottom.push({ label: col.label, colSpan: 1, rowSpan: 1, column: index });
|
|
});
|
|
return [top, bottom];
|
|
}
|