# Build a critical path report

> 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

1. Load the project data into `createGanttProject()`. It is scheduled as soon as it is created.
2. Read the critical path with `getCriticalPath()` and the finish date with `getProjectRange()`.
3. Read each task's slack, early and late dates from `getTasks()`.
4. Write the result as a table, JSON, or an xlsx file.

## Compute the report

```ts title="critical-path-report.ts"
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

```ts title="render-report.ts"
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](https://docs.birchui.com/excel/overview.md) workbook:

```ts title="report-xlsx.ts"
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:

```ts
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 `hoursPerDay` hours, not calendar days. Pass the same `hoursPerDay`, `calendars` and `timeZone` as 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: true` and gives its predecessors negative slack. List `conflicts` separately so they are not mistaken for ordinary delays.
- **Dates in Excel.** The Excel Engine writes `Date` values in UTC. See [Cells](https://docs.birchui.com/excel/writing.md#cells).

## Related

- [Slack and the critical path](https://docs.birchui.com/gantt/scheduling.md#slack-and-the-critical-path).
- [Scheduled fields](https://docs.birchui.com/gantt/tasks.md#scheduled-fields).
- [Headless engine](https://docs.birchui.com/gantt/headless.md).
- [Build a multi-sheet Excel report](https://docs.birchui.com/recipes/excel-report-workbook.md).
