Build a critical path reportGantt
Use the headless Gantt engine to compute the critical path, slack and constraint conflicts of a project, and render them as a report or an Excel file.
Steering meetings ask the same questions every week: when do we finish, which tasks drive that date, and how much room do the others have? This recipe answers them with createGanttProject(), the Gantt's scheduling engine without a user interface, so the report runs in a browser, a worker or a nightly job on a server.
Steps#
- Load the project data into
createGanttProject(). It is scheduled as soon as it is created. - Read the critical path with
getCriticalPath()and the finish date withgetProjectRange(). - Read each task's slack, early and late dates from
getTasks(). - Write the result as a table, JSON, or an xlsx file.
Compute the report#
import { createGanttProject, type ProjectData } from '@birchui/gantt';
export interface CriticalPathRow {
wbs: string;
name: string;
start: Date;
end: Date;
totalSlackDays: number;
freeSlackDays: number;
isCritical: boolean;
hasConflict: boolean;
}
export function criticalPathReport(data: ProjectData, timeZone = 'Europe/London') {
const warnings: string[] = [];
const project = createGanttProject({ ...data, timeZone, warn: (message) => warnings.push(message) });
const { taskIds } = project.getCriticalPath();
const range = project.getProjectRange();
const conflicts = project.lastResult?.conflicts ?? [];
const rows: CriticalPathRow[] = project
.getTasks()
.filter((task) => task.type !== 'summary')
.map((task) => ({
wbs: task.wbs,
name: task.name,
start: task.start,
end: task.end,
totalSlackDays: Math.round(task.totalSlack * 10) / 10,
freeSlackDays: Math.round(task.freeSlack * 10) / 10,
isCritical: task.isCritical,
hasConflict: task.hasConflict === true,
}))
.sort((a, b) => a.totalSlackDays - b.totalSlackDays || a.start.getTime() - b.start.getTime());
return {
name: data.name ?? 'Project',
start: range.start,
finish: range.end,
criticalTasks: taskIds.map((id) => project.getTask(id)?.name ?? id),
conflicts: conflicts.map((id) => project.getTask(id)?.name ?? id),
rows,
warnings,
};
}Sorting by total slack puts the critical tasks first, followed by the tasks closest to becoming critical. Tasks with negative slack, which are already late for a constraint, sort above everything else.
Render it#
const day = new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
export function renderReport(host: HTMLElement, report: ReturnType<typeof criticalPathReport>) {
host.innerHTML = '';
const heading = document.createElement('h2');
heading.textContent = `${report.name}: finish ${day.format(report.finish)}`;
const table = document.createElement('table');
table.innerHTML = '<thead><tr><th>WBS</th><th>Task</th><th>Start</th><th>Finish</th><th>Total slack (days)</th></tr></thead>';
const body = table.createTBody();
for (const row of report.rows) {
const tr = body.insertRow();
tr.className = row.isCritical ? 'is-critical' : '';
for (const text of [row.wbs, row.name, day.format(row.start), day.format(row.end), String(row.totalSlackDays)]) {
tr.insertCell().textContent = text;
}
}
host.append(heading, table);
}Export to Excel#
The rows map directly onto an Excel Engine workbook:
import { writeXlsx, type XlsxWorkbook } from '@birchui/excel';
export function reportWorkbook(report: ReturnType<typeof criticalPathReport>): Promise<Uint8Array> {
const header = { bold: true, fill: '#E8EEF7' };
const workbook: XlsxWorkbook = {
title: `${report.name} critical path`,
sheets: [
{
name: 'Critical path',
freeze: { rows: 1 },
autoFilter: true,
columns: [
{ width: 8 },
{ width: 36 },
{ width: 14, style: { numFmt: 'dd mmm yyyy' } },
{ width: 14, style: { numFmt: 'dd mmm yyyy' } },
{ width: 12, style: { numFmt: '0.0' } },
{ width: 10 },
],
rows: [
['WBS', 'Task', 'Start', 'Finish', 'Total slack', 'Critical'].map((value) => ({ value, style: header })),
...report.rows.map((row) => ({
cells: [row.wbs, row.name, row.start, row.end, row.totalSlackDays, row.isCritical],
style: row.isCritical ? { color: '#B42318' } : undefined,
})),
],
},
],
};
return writeXlsx(workbook);
}Answer "what if" questions#
Edits on the headless project reschedule it like the widget does, so the report can compare scenarios:
const project = createGanttProject({ ...data, timeZone: 'Europe/London' });
const before = project.getProjectRange().end;
project.transaction('Steel delivery slips one week', () => {
project.updateTask('steel-delivery', { duration: 15 });
});
const after = project.getProjectRange().end;
const slipDays = (after.getTime() - before.getTime()) / 86_400_000;
project.undo();transaction() makes several edits one scheduling run and one undo step, and undo() restores the original plan for the next scenario.
Pitfalls#
- Slack is in working days of
hoursPerDayhours, not calendar days. Pass the samehoursPerDay,calendarsandtimeZoneas the Gantt your users see, or the numbers will differ. - Summaries. Summary tasks roll up their children; filter them out of task-level tables as above.
- Constraint conflicts. A task whose constraint overrides its links has
hasConflict: trueand gives its predecessors negative slack. Listconflictsseparately so they are not mistaken for ordinary delays. - Dates in Excel. The Excel Engine writes
Datevalues in UTC. See Cells.