/** * GanttProject files (.gan): XML with a root holding the calendar * (which weekdays are off, and holidays), nested elements with their * start date and duration in working days, links (), resources and * allocations. * * Read as MPXJ's GanttProjectReader reads them (see README.md): unique IDs * are GanttProject's IDs plus one; a task's finish is its start plus its * duration in working days of the project calendar (8:00-12:00 and * 13:00-17:00 on working days); a task with no duration is a milestone; * link types 1-4 are SS, FS, FF and SF with the lag in days; priorities * 0-4 are Low, Normal, High, Lowest and Highest. Added here: task notes, * custom task columns, a "Start No Earlier Than" constraint only where * GanttProject marks the date as one (thirdDate-constraint="1"), and each * resource's vacations as days off in its own calendar. */ import { Assignment, CalendarDay, CalendarException, Project, ProjectCalendar, Relation, RelationType, Resource, Task, emptyTask, updateStructure } from './model'; import { XmlNode, child, children, parseXml } from './xml'; /** A .gan file: XML whose root element is a lower-case holding . */ export function isGan(src: string): boolean { const head = src.slice(0, 4000); return /^\s*(?:<\?[\s\S]*?\?>\s*)?(?:\s*)*]/.test(head) && /<(?:tasks|calendars|description)[\s/>]/.test(src.slice(0, 200000)); } const RELATIONS: (RelationType | null)[] = [null, 'SS', 'FS', 'FF', 'SF']; const PRIORITIES = [400, 500, 600, 100, 900]; const DAY = 86400000; /** MPXJ's default working day. */ const HOURS = [{ start: 480, end: 720 }, { start: 780, end: 1020 }]; const WEEK_ATTRS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; /** "2026-03-04" as a UTC midnight. */ function day(v: string | undefined): number | null { const m = /^(\d{4})-(\d\d)-(\d\d)/.exec(v ?? ''); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; } function num(v: string | undefined): number | null { return v === undefined || v.trim() === '' || !Number.isFinite(Number(v)) ? null : Number(v); } export interface GanCalendar { working: boolean[]; /** Days that differ from the week, by UTC midnight: true working, false not. */ dates: Map; } /** Whether a day works, by the week and the dated exceptions. */ export function isWorkingDay(cal: GanCalendar, d: number): boolean { return cal.dates.get(d) ?? cal.working[new Date(d).getUTCDay()]; } /** The longest a task's duration is taken to be, in working days (about a hundred years). */ const MAX_SPAN_DAYS = 36600; /** The most calendar days a span is counted through, for a calendar that hardly works. */ const SPAN_LIMIT = 100000; const datedCache = new WeakMap, number[]>(); /** The calendar's dated exceptions, in order. */ function datedDays(cal: GanCalendar): number[] { // Made once per calendar (a plan has thousands of tasks), again if days were added since. let list = datedCache.get(cal.dates); if (!list || list.length !== cal.dates.size) datedCache.set(cal.dates, (list = [...cal.dates.keys()].sort((a, b) => a - b))); return list; } /** Where the first of `sorted` at or after `d` is (sorted.length when none is). */ function firstAtOrAfter(sorted: number[], d: number): number { let lo = 0, hi = sorted.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (sorted[mid] < d) lo = mid + 1; else hi = mid; } return lo; } /** * A task's start and finish: from 8:00 on its first working day to 17:00 on * the day its duration in working days runs out. A duration of 0 is a point * at 8:00. A part day (GanttProject writes whole days, but be safe) ends * that share of the way through the working hours. */ export function ganSpan(cal: GanCalendar, start: number, days: number): { start: number; finish: number } { let d = start; // A plan with no working days at all would never end. if (!cal.working.some(Boolean) && ![...cal.dates.values()].some(Boolean)) return { start: start + 480 * 60000, finish: start + 480 * 60000 }; for (let i = 0; i < 3660 && !isWorkingDay(cal, d); i++) d += DAY; const s = d + 480 * 60000; if (days <= 0) return { start: s, finish: s }; // A hundred years of working days at most: a file asking for more would take minutes to work out. let left = Math.min(days, MAX_SPAN_DAYS); const perWeek = cal.working.filter(Boolean).length; const dated = datedDays(cal); for (let i = 0; i < SPAN_LIMIT; ) { // Whole weeks with no dated exception in them are counted at once, stopping short of the last day. if (perWeek && left > perWeek) { const next = dated[firstAtOrAfter(dated, d)]; const free = next === undefined ? Infinity : Math.floor((next - d) / (7 * DAY)); const weeks = Math.min(free, Math.ceil(left / perWeek) - 1, Math.floor((SPAN_LIMIT - i) / 7)); if (weeks > 0) { d += weeks * 7 * DAY; i += weeks * 7; left -= weeks * perWeek; continue; } } i++; if (isWorkingDay(cal, d)) { if (left <= 1) { const minutes = Math.round(left * 480); // Through the morning (4 hours), then the afternoon. const end = minutes <= 240 ? 480 + minutes : 780 + (minutes - 240); return { start: s, finish: d + end * 60000 }; } left -= 1; } d += DAY; } return { start: s, finish: d + 1020 * 60000 }; } export function readGan(src: string): Project { const doc = parseXml(src); const root = child(doc, 'project'); if (!root) throw new Error('This XML file is not a GanttProject file.'); const warnings: string[] = []; // The calendar: the default week (0 = working, 1 = weekend) and dated exceptions; yearly holidays (no year) as MPXJ leaves them out. const cals = child(root, 'calendars'); const week = child(child(cals, 'day-types'), 'default-week'); const working = WEEK_ATTRS.map((a, i) => (week && week.attrs[a] !== undefined ? week.attrs[a] === '0' : i !== 0 && i !== 6)); const dates = new Map(); const exceptions: CalendarException[] = []; let yearly = 0; for (const d of children(cals, 'date')) { if (!d.attrs['year']) { yearly++; continue; } const at = Date.UTC(Number(d.attrs['year']), Number(d.attrs['month']) - 1, Number(d.attrs['date'])); if (!Number.isFinite(at)) continue; const works = d.attrs['type'] === 'WORKING_DAY'; dates.set(at, works); exceptions.push({ name: d.text.trim(), from: at, to: at, hours: works ? HOURS.map((h) => ({ ...h })) : [], recurrence: '', dates: null }); } if (yearly) warnings.push(`${yearly} holiday${yearly === 1 ? '' : 's'} set to repeat every year ${yearly === 1 ? 'is' : 'are'} not shown as days off; tasks keep the dates GanttProject saved.`); exceptions.sort((a, b) => a.from - b.from); const cal: GanCalendar = { working, dates }; const days: CalendarDay[] = working.map((w) => (w ? { type: 'working', hours: HOURS.map((h) => ({ ...h })) } : { type: 'nonworking', hours: [] })); const calendars: ProjectCalendar[] = [{ uniqueId: 1, name: 'Standard', parent: null, resource: null, days, exceptions, weeks: [] }]; // Custom task columns: their names by ID. const tasksNode = child(root, 'tasks'); const props = new Map(); for (const p of children(child(tasksNode, 'taskproperties'), 'taskproperty')) { if (p.attrs['type'] === 'custom' && p.attrs['id']) props.set(p.attrs['id'], p.attrs['name'] || p.attrs['id']); } const tasks: Task[] = []; const links: { from: XmlNode; task: Task }[] = []; let id = 0; const walk = (nodes: XmlNode[], level: number) => { for (const n of nodes) { const gid = num(n.attrs['id']); if (gid === null) continue; const t = emptyTask(gid + 1); t.id = ++id; t.name = n.attrs['name'] ?? ''; t.outlineLevel = level; t.percentComplete = Math.max(0, Math.min(100, num(n.attrs['complete']) ?? 0)); const pr = num(n.attrs['priority']); t.priority = pr !== null && pr >= 0 && pr < PRIORITIES.length ? PRIORITIES[pr] : 500; const dur = num(n.attrs['duration']) ?? 0; const start = day(n.attrs['start']); t.milestone = dur === 0 || n.attrs['meeting'] === 'true'; t.duration = { value: t.milestone ? 0 : dur, units: 'd' }; if (start !== null) { const span = ganSpan(cal, start, t.milestone ? 0 : dur); t.start = span.start; t.finish = span.finish; } const third = day(n.attrs['thirdDate']); if (third !== null && n.attrs['thirdDate-constraint'] === '1') { t.constraint = 'Start No Earlier Than'; t.constraintDate = third + 480 * 60000; } t.notes = (child(n, 'notes')?.text ?? '').trim(); if (n.attrs['webLink']) t.extra['HYPERLINK'] = decodeURIComponentSafe(n.attrs['webLink']); for (const c of children(n, 'customproperty')) { const name = props.get(c.attrs['taskproperty-id'] ?? ''); const v = c.attrs['value']; if (name && v !== undefined && v !== '') t.extra[name.toUpperCase().replace(/\s+/g, '_')] = Number.isFinite(Number(v)) && /^-?\d/.test(v) ? Number(v) : v; } tasks.push(t); links.push({ from: n, task: t }); walk(children(n, 'task'), level + 1); } }; walk(children(tasksNode, 'task'), 1); updateStructure(tasks); // A sits on the predecessor and names the successor. const byUid = new Map(tasks.map((t) => [t.uniqueId, t])); for (const { from, task } of links) { for (const d of children(from, 'depend')) { const succ = byUid.get((num(d.attrs['id']) ?? -2) + 1); if (!succ) continue; const type = RELATIONS[num(d.attrs['type']) ?? 2] ?? 'FS'; const lag = num(d.attrs['difference']); const rel: Relation = { task: task.uniqueId, type, lag: lag ? { value: lag, units: 'd' } : null }; succ.predecessors.push(rel); } } // Resources: roles are their group; a rate is per day. const roles = new Map([['Default:1', 'project manager']]); for (const r of children(root, 'roles')) { if (r.attrs['roleset-name'] === 'Default') continue; for (const role of children(r, 'role')) if (role.attrs['id']) roles.set(role.attrs['id'], role.attrs['name'] ?? ''); } const resources: Resource[] = []; children(child(root, 'resources'), 'resource').forEach((r, i) => { const rid = num(r.attrs['id']); if (rid === null) return; const rate = num(child(r, 'rate')?.attrs['value']); resources.push({ uniqueId: rid + 1, id: i + 1, name: r.attrs['name'] ?? '', initials: '', group: roles.get(r.attrs['function'] ?? '') ?? '', email: r.attrs['contacts'] ?? '', type: 'Work', maxUnits: 1, standardRate: rate, rateUnits: 'd', cost: null, work: null, notes: r.attrs['phone'] ? `Phone: ${r.attrs['phone']}` : '', calendar: null, }); }); const resByUid = new Map(resources.map((r) => [r.uniqueId, r])); // Vacations: days off in the resource's own calendar. let calId = 2; for (const v of children(child(root, 'vacations'), 'vacation')) { const res = resByUid.get((num(v.attrs['resourceid']) ?? -2) + 1); const from = day(v.attrs['start']); const to = day(v.attrs['end']); if (!res || from === null || to === null) continue; let c = calendars.find((k) => k.resource === res.uniqueId); if (!c) { c = { uniqueId: calId++, name: res.name, parent: 1, resource: res.uniqueId, days: Array.from({ length: 7 }, () => ({ type: 'default' as const, hours: [] })), exceptions: [], weeks: [] }; calendars.push(c); res.calendar = c.uniqueId; } // GanttProject's end date is the last day off. c.exceptions.push({ name: 'Vacation', from, to: Math.max(from, to), hours: [], recurrence: '', dates: null }); } const assignments: Assignment[] = []; const names = new Map(); for (const a of children(child(root, 'allocations'), 'allocation')) { const task = byUid.get((num(a.attrs['task-id']) ?? -2) + 1); const res = resByUid.get((num(a.attrs['resource-id']) ?? -2) + 1); if (!task || !res) continue; const load = num(a.attrs['load']); assignments.push({ task: task.uniqueId, resource: res.uniqueId, units: load === null ? 1 : load / 100, work: null, cost: null, start: task.start, finish: task.finish }); const list = names.get(task.uniqueId); if (list) list.push(res.name); else names.set(task.uniqueId, [res.name]); } for (const t of tasks) t.resourceNames = (names.get(t.uniqueId) ?? []).join(', '); const starts = tasks.map((t) => t.start).filter((v): v is number => v !== null); const finishes = tasks.map((t) => t.finish).filter((v): v is number => v !== null); return { format: 'GanttProject (.gan)', title: root.attrs['name'] ?? '', subject: '', author: '', manager: '', company: root.attrs['company'] ?? '', comments: (child(root, 'description')?.text ?? '').trim(), start: starts.length ? starts.reduce((a, b) => Math.min(a, b)) : null, finish: finishes.length ? finishes.reduce((a, b) => Math.max(a, b)) : null, statusDate: null, currencySymbol: '', minutesPerDay: 480, minutesPerWeek: 480 * working.filter(Boolean).length || 2400, daysPerMonth: 20, summary: null, tasks, resources, assignments, calendars, calendar: 1, warnings, }; } function decodeURIComponentSafe(v: string): string { try { return decodeURIComponent(v); } catch { return v; } }