@monadsag/productive-mcp 1.2.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/NOTICE +6 -0
- package/README.md +353 -0
- package/build/api/bookings-client.js +249 -0
- package/build/api/capacity.js +279 -0
- package/build/api/client.js +1296 -0
- package/build/api/errors.js +50 -0
- package/build/api/invoice-time-entries.js +256 -0
- package/build/api/pages-tree.js +106 -0
- package/build/api/time-entry-notes.js +75 -0
- package/build/api/types.js +1 -0
- package/build/auth/logo.js +21 -0
- package/build/auth/self-resolver.js +61 -0
- package/build/config/index.js +24 -0
- package/build/index.js +15 -0
- package/build/prompts/timesheet.js +285 -0
- package/build/server.js +55 -0
- package/build/tools/absences.js +502 -0
- package/build/tools/activities.js +140 -0
- package/build/tools/bookings.js +531 -0
- package/build/tools/budget-services.js +168 -0
- package/build/tools/budgets.js +276 -0
- package/build/tools/capacity.js +281 -0
- package/build/tools/changeset.js +41 -0
- package/build/tools/comments.js +469 -0
- package/build/tools/companies.js +73 -0
- package/build/tools/custom-field-resolver.js +92 -0
- package/build/tools/custom-fields.js +155 -0
- package/build/tools/folders.js +516 -0
- package/build/tools/include-resolver.js +45 -0
- package/build/tools/invoice-actions.js +476 -0
- package/build/tools/invoice-defaults.js +65 -0
- package/build/tools/invoice-time-entries.js +320 -0
- package/build/tools/invoices.js +657 -0
- package/build/tools/my-tasks.js +100 -0
- package/build/tools/page-children.js +129 -0
- package/build/tools/pages.js +466 -0
- package/build/tools/people.js +147 -0
- package/build/tools/projects.js +77 -0
- package/build/tools/recent-updates.js +112 -0
- package/build/tools/registry.js +409 -0
- package/build/tools/subtasks.js +245 -0
- package/build/tools/task-backlog.js +106 -0
- package/build/tools/task-dependencies.js +244 -0
- package/build/tools/task-list-move.js +65 -0
- package/build/tools/task-lists.js +535 -0
- package/build/tools/task-reposition.js +199 -0
- package/build/tools/task-status.js +178 -0
- package/build/tools/tasks.js +738 -0
- package/build/tools/time-entries.js +736 -0
- package/build/tools/time-entry-approval.js +103 -0
- package/build/tools/time-entry-delete.js +72 -0
- package/build/tools/time-entry-update.js +126 -0
- package/build/tools/timers.js +195 -0
- package/build/tools/todos.js +342 -0
- package/build/tools/tool-helpers.js +114 -0
- package/build/tools/toolsets.js +153 -0
- package/build/tools/whoami.js +64 -0
- package/build/tools/workflow-statuses.js +81 -0
- package/build/utils/errors.js +67 -0
- package/build/utils/mentions.js +98 -0
- package/npm-shrinkwrap.json +1159 -0
- package/package.json +79 -0
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `absence_type` on an event: an absence category is either real time off or
|
|
3
|
+
* remote work (working from home). Documented in
|
|
4
|
+
* docs/api-spec/resources/events.yaml.
|
|
5
|
+
*
|
|
6
|
+
* Deliberately not a literal union on ProductiveEvent -- responses are not
|
|
7
|
+
* validated, so a third value the API adds later would become a type lie.
|
|
8
|
+
*/
|
|
9
|
+
export const ABSENCE_TYPE = {
|
|
10
|
+
TIME_OFF: 'time_off',
|
|
11
|
+
REMOTE_WORK: 'remote_work',
|
|
12
|
+
};
|
|
13
|
+
/** booking_method_id values as documented by the API. */
|
|
14
|
+
export const BOOKING_METHOD = {
|
|
15
|
+
HOURS_PER_DAY: 1,
|
|
16
|
+
PERCENTAGE: 2,
|
|
17
|
+
TOTAL_HOURS: 3,
|
|
18
|
+
};
|
|
19
|
+
/** approval_status is a *filter* parameter only -- it is not a response field. */
|
|
20
|
+
export const APPROVAL_STATUS_FILTER = {
|
|
21
|
+
approved: 1,
|
|
22
|
+
pending: 2,
|
|
23
|
+
rejected: 3,
|
|
24
|
+
canceled: 5,
|
|
25
|
+
};
|
|
26
|
+
/** person_type filter: 3 selects placeholder resources rather than real users. */
|
|
27
|
+
export const PERSON_TYPE = {
|
|
28
|
+
USER: 1,
|
|
29
|
+
CONTACT: 2,
|
|
30
|
+
PLACEHOLDER: 3,
|
|
31
|
+
AGENT: 4,
|
|
32
|
+
};
|
|
33
|
+
/** Largest page the bookings endpoint is asked for. */
|
|
34
|
+
export const MAX_PAGE_SIZE = 200;
|
|
35
|
+
/**
|
|
36
|
+
* Hard ceiling on bookings pages fetched for one capacity overview.
|
|
37
|
+
*
|
|
38
|
+
* 10 x 200 = 2000 bookings. Productive allows 100 requests per 10s
|
|
39
|
+
* (docs/api-spec/guides/rate-limits.md) and Workers caps subrequests per
|
|
40
|
+
* request, so an unbounded loop would eventually break both.
|
|
41
|
+
*/
|
|
42
|
+
export const MAX_BOOKING_PAGES = 10;
|
|
43
|
+
/**
|
|
44
|
+
* Build the query string shared by every bookings list call.
|
|
45
|
+
*
|
|
46
|
+
* `include` is always requested: absence and capacity bookings can only be told
|
|
47
|
+
* apart by which relationship carries data, and without `approval_statuses` the
|
|
48
|
+
* API returns that relationship as a stub, which would make every booking look
|
|
49
|
+
* like it has no approvers.
|
|
50
|
+
*/
|
|
51
|
+
export function buildBookingQuery(params = {}) {
|
|
52
|
+
const q = new URLSearchParams();
|
|
53
|
+
q.append('include', 'person,event,service,approval_statuses');
|
|
54
|
+
if (params.after)
|
|
55
|
+
q.append('filter[after]', params.after);
|
|
56
|
+
if (params.before)
|
|
57
|
+
q.append('filter[before]', params.before);
|
|
58
|
+
if (params.person_id)
|
|
59
|
+
q.append('filter[person_id]', params.person_id);
|
|
60
|
+
if (params.event_id)
|
|
61
|
+
q.append('filter[event_id]', params.event_id);
|
|
62
|
+
if (params.project_id)
|
|
63
|
+
q.append('filter[project_id]', params.project_id);
|
|
64
|
+
if (params.budget_id)
|
|
65
|
+
q.append('filter[budget_id]', params.budget_id);
|
|
66
|
+
if (params.approval_status) {
|
|
67
|
+
q.append('filter[approval_status]', String(APPROVAL_STATUS_FILTER[params.approval_status]));
|
|
68
|
+
}
|
|
69
|
+
if (params.person_type !== undefined) {
|
|
70
|
+
q.append('filter[person_type]', String(params.person_type));
|
|
71
|
+
}
|
|
72
|
+
if (params.with_draft)
|
|
73
|
+
q.append('filter[with_draft]', 'true');
|
|
74
|
+
if (params.canceled)
|
|
75
|
+
q.append('filter[canceled]', 'true');
|
|
76
|
+
if (params.limit)
|
|
77
|
+
q.append('page[size]', String(params.limit));
|
|
78
|
+
if (params.page)
|
|
79
|
+
q.append('page[number]', String(params.page));
|
|
80
|
+
// Without a fixed sort the order across pages is not guaranteed, which makes
|
|
81
|
+
// rows duplicate or go missing at the page boundaries. Documented sort keys
|
|
82
|
+
// for this endpoint: docs/api-spec/resources/bookings.yaml (sort_booking).
|
|
83
|
+
if (params.sort)
|
|
84
|
+
q.append('sort', params.sort);
|
|
85
|
+
return q.toString();
|
|
86
|
+
}
|
|
87
|
+
/** True when the booking represents an absence (event set, service empty). */
|
|
88
|
+
export function isAbsenceBooking(booking) {
|
|
89
|
+
return Boolean(booking.relationships?.event?.data?.id);
|
|
90
|
+
}
|
|
91
|
+
/** True when the booking represents planned project capacity (service set). */
|
|
92
|
+
export function isCapacityBooking(booking) {
|
|
93
|
+
return Boolean(booking.relationships?.service?.data?.id);
|
|
94
|
+
}
|
|
95
|
+
/** True only for events the API explicitly marks as remote work. */
|
|
96
|
+
export function isRemoteWorkEvent(event) {
|
|
97
|
+
return event.attributes.absence_type === ABSENCE_TYPE.REMOTE_WORK;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* IDs of the sideloaded events that stand for remote work.
|
|
101
|
+
*
|
|
102
|
+
* Every bookings request sideloads `event` (see buildBookingQuery), so the
|
|
103
|
+
* `absence_type` needed to tell working from home apart from real time off is
|
|
104
|
+
* already in the response -- no extra call.
|
|
105
|
+
*/
|
|
106
|
+
export function remoteWorkEventIds(included) {
|
|
107
|
+
const ids = new Set();
|
|
108
|
+
for (const resource of included ?? []) {
|
|
109
|
+
if (resource.type !== 'events')
|
|
110
|
+
continue;
|
|
111
|
+
const absenceType = resource.attributes?.absence_type;
|
|
112
|
+
if (absenceType === ABSENCE_TYPE.REMOTE_WORK)
|
|
113
|
+
ids.add(resource.id);
|
|
114
|
+
}
|
|
115
|
+
return ids;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Which bucket a booking belongs to.
|
|
119
|
+
*
|
|
120
|
+
* Only an event positively identified as remote work counts as such: without
|
|
121
|
+
* the set, or with the event not sideloaded, an absence stays an absence. The
|
|
122
|
+
* error therefore always points the same way -- capacity is reported too low
|
|
123
|
+
* rather than too high. Guessing the other way would turn somebody's sick leave
|
|
124
|
+
* into free capacity.
|
|
125
|
+
*/
|
|
126
|
+
export function classifyBooking(booking, remoteEventIds) {
|
|
127
|
+
const eventId = booking.relationships?.event?.data?.id;
|
|
128
|
+
if (!eventId)
|
|
129
|
+
return 'project';
|
|
130
|
+
return remoteEventIds?.has(eventId) ? 'remote_work' : 'time_off';
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Pick a sensible booking_method_id for an absence type.
|
|
134
|
+
*
|
|
135
|
+
* Types that allow half days need per-day granularity; the rest are booked as
|
|
136
|
+
* one total block. Both branches are verified against the live API, but callers
|
|
137
|
+
* may always override -- this is a default, not an API-enforced rule.
|
|
138
|
+
*/
|
|
139
|
+
export function defaultBookingMethod(event) {
|
|
140
|
+
return event.attributes.half_day_bookings
|
|
141
|
+
? BOOKING_METHOD.HOURS_PER_DAY
|
|
142
|
+
: BOOKING_METHOD.TOTAL_HOURS;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Map a requested amount onto the attribute(s) the chosen method expects.
|
|
146
|
+
*
|
|
147
|
+
* @param method booking_method_id
|
|
148
|
+
* @param hoursPerDay hours per working day (methods 1 and 3)
|
|
149
|
+
* @param percentage allocation percentage (method 2)
|
|
150
|
+
* @param workingDays number of working days, needed to total up method 3
|
|
151
|
+
*/
|
|
152
|
+
export function buildQuantity(method, opts) {
|
|
153
|
+
if (method === BOOKING_METHOD.PERCENTAGE) {
|
|
154
|
+
if (opts.percentage === undefined) {
|
|
155
|
+
throw new Error('booking_method_id 2 (percentage) requires a percentage value');
|
|
156
|
+
}
|
|
157
|
+
return { percentage: opts.percentage };
|
|
158
|
+
}
|
|
159
|
+
if (opts.hoursPerDay === undefined) {
|
|
160
|
+
throw new Error(`booking_method_id ${method} requires hours_per_day`);
|
|
161
|
+
}
|
|
162
|
+
if (method === BOOKING_METHOD.HOURS_PER_DAY) {
|
|
163
|
+
// `hours` can arrive as an average over an uneven week; `time` (minutes) is
|
|
164
|
+
// the field the API actually settles on, so only the display value rounds.
|
|
165
|
+
return {
|
|
166
|
+
hours: Math.round(opts.hoursPerDay * 100) / 100,
|
|
167
|
+
time: Math.round(opts.hoursPerDay * 60),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const days = opts.workingDays ?? 1;
|
|
171
|
+
return { total_time: Math.round(opts.hoursPerDay * 60 * days) };
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Count working days (Mon-Fri) inclusive between two ISO dates.
|
|
175
|
+
*
|
|
176
|
+
* Public holidays are not subtracted -- the API recomputes total_working_days
|
|
177
|
+
* itself, so this only needs to be good enough to size a method-3 request.
|
|
178
|
+
*/
|
|
179
|
+
export function countWorkingDays(startIso, endIso) {
|
|
180
|
+
const start = new Date(`${startIso}T00:00:00Z`);
|
|
181
|
+
const end = new Date(`${endIso}T00:00:00Z`);
|
|
182
|
+
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end < start)
|
|
183
|
+
return 0;
|
|
184
|
+
let days = 0;
|
|
185
|
+
for (const d = new Date(start); d <= end; d.setUTCDate(d.getUTCDate() + 1)) {
|
|
186
|
+
const weekday = d.getUTCDay();
|
|
187
|
+
if (weekday !== 0 && weekday !== 6)
|
|
188
|
+
days += 1;
|
|
189
|
+
}
|
|
190
|
+
return days;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Human-readable approval state derived from the response fields.
|
|
194
|
+
*
|
|
195
|
+
* `rejected_reason` is free text written about a specific person's absence and
|
|
196
|
+
* can carry the same health detail as `note` -- "still signed off sick" -- so it
|
|
197
|
+
* stays behind the same opt-in rather than riding along in every listing.
|
|
198
|
+
*/
|
|
199
|
+
export function describeApprovalState(booking, opts = {}) {
|
|
200
|
+
const a = booking.attributes;
|
|
201
|
+
if (a.canceled)
|
|
202
|
+
return 'Canceled';
|
|
203
|
+
if (a.rejected) {
|
|
204
|
+
return opts.includeReason && a.rejected_reason ? `Rejected (${a.rejected_reason})` : 'Rejected';
|
|
205
|
+
}
|
|
206
|
+
if (a.approved)
|
|
207
|
+
return 'Approved';
|
|
208
|
+
const pending = booking.relationships?.approval_statuses?.data?.length ?? 0;
|
|
209
|
+
return pending > 0 ? `Pending approval (${pending} approver(s))` : 'Pending approval';
|
|
210
|
+
}
|
|
211
|
+
/** Minutes rendered as "7h 30m" / "8h" / "45m". */
|
|
212
|
+
export function formatMinutes(totalMinutes) {
|
|
213
|
+
const rounded = Math.round(totalMinutes);
|
|
214
|
+
const hours = Math.floor(rounded / 60);
|
|
215
|
+
const minutes = rounded % 60;
|
|
216
|
+
if (hours > 0)
|
|
217
|
+
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
|
218
|
+
return `${minutes}m`;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Resolve a user-supplied absence type name against the live event list.
|
|
222
|
+
*
|
|
223
|
+
* Matching is case-insensitive and accepts a unique partial match, so callers
|
|
224
|
+
* never need a hardcoded mapping table. Returns null when nothing matches;
|
|
225
|
+
* throws only when the input is genuinely ambiguous.
|
|
226
|
+
*/
|
|
227
|
+
export function resolveAbsenceType(events, needle, opts = {}) {
|
|
228
|
+
const wanted = needle.trim().toLowerCase();
|
|
229
|
+
if (!wanted)
|
|
230
|
+
return null;
|
|
231
|
+
// Archived types cannot be booked, but they still have history: a read that
|
|
232
|
+
// refuses to name last year's "Sabbatical" reports "unknown type" for
|
|
233
|
+
// bookings the same tool lists happily when unfiltered.
|
|
234
|
+
const active = opts.includeArchived ? events : events.filter((e) => !e.attributes.archived_at);
|
|
235
|
+
const exact = active.filter((e) => e.attributes.name?.toLowerCase() === wanted);
|
|
236
|
+
if (exact.length === 1)
|
|
237
|
+
return exact[0];
|
|
238
|
+
if (exact.length > 1) {
|
|
239
|
+
throw new Error(`Absence type "${needle}" is ambiguous -- use the event ID instead.`);
|
|
240
|
+
}
|
|
241
|
+
const partial = active.filter((e) => e.attributes.name?.toLowerCase().includes(wanted));
|
|
242
|
+
if (partial.length === 1)
|
|
243
|
+
return partial[0];
|
|
244
|
+
if (partial.length > 1) {
|
|
245
|
+
const names = partial.map((e) => e.attributes.name).join(', ');
|
|
246
|
+
throw new Error(`Absence type "${needle}" matches several types: ${names}. Be more specific.`);
|
|
247
|
+
}
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { classifyBooking } from './bookings-client.js';
|
|
2
|
+
/** Parse `YYYY-MM-DD` into a UTC date, or null when unusable. */
|
|
3
|
+
function toUtcDate(iso) {
|
|
4
|
+
const d = new Date(`${iso}T00:00:00Z`);
|
|
5
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
6
|
+
}
|
|
7
|
+
function toIso(date) {
|
|
8
|
+
return date.toISOString().slice(0, 10);
|
|
9
|
+
}
|
|
10
|
+
/** Monday = 0 ... Sunday = 6, matching how the pattern array is laid out. */
|
|
11
|
+
function patternIndex(date) {
|
|
12
|
+
return (date.getUTCDay() + 6) % 7;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parse the `availabilities` attribute, which arrives as a JSON *string*.
|
|
16
|
+
*
|
|
17
|
+
* Returns an empty array for missing or malformed input rather than throwing --
|
|
18
|
+
* a person without a usable pattern should degrade to "unknown", not break the
|
|
19
|
+
* whole overview.
|
|
20
|
+
*/
|
|
21
|
+
export function parseAvailabilities(raw) {
|
|
22
|
+
const parsed = decodeAvailabilities(raw);
|
|
23
|
+
if (!Array.isArray(parsed))
|
|
24
|
+
return [];
|
|
25
|
+
const slices = [];
|
|
26
|
+
for (const entry of parsed) {
|
|
27
|
+
if (!Array.isArray(entry))
|
|
28
|
+
continue;
|
|
29
|
+
// Two shapes in the wild: the live API answers with time-sliced entries
|
|
30
|
+
// ([from, to, pattern, calendarId]), while the official spec's own example
|
|
31
|
+
// (docs/api-spec/resources/people.yaml) shows a bare pattern array. Accept
|
|
32
|
+
// both rather than silently reporting "no working pattern" for everyone if
|
|
33
|
+
// the response ever takes the documented form.
|
|
34
|
+
if (entry.every((value) => typeof value === 'number')) {
|
|
35
|
+
if (entry.length >= 7)
|
|
36
|
+
slices.push({ from: '1970-01-01', to: null, pattern: entry });
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (entry.length < 3)
|
|
40
|
+
continue;
|
|
41
|
+
const [from, to, pattern] = entry;
|
|
42
|
+
if (typeof from !== 'string' || !Array.isArray(pattern))
|
|
43
|
+
continue;
|
|
44
|
+
if (!pattern.every((n) => typeof n === 'number'))
|
|
45
|
+
continue;
|
|
46
|
+
// Same floor as the bare-array branch. A shorter pattern reads as zero
|
|
47
|
+
// hours on every weekday, which would come out as a contracted 0m and an
|
|
48
|
+
// OVERBOOKED flag instead of "the pattern could not be read".
|
|
49
|
+
if (pattern.length < 7)
|
|
50
|
+
continue;
|
|
51
|
+
slices.push({ from, to: typeof to === 'string' ? to : null, pattern });
|
|
52
|
+
}
|
|
53
|
+
return slices;
|
|
54
|
+
}
|
|
55
|
+
/** The raw value as an array, whether it arrived as one or as a JSON string. */
|
|
56
|
+
function decodeAvailabilities(raw) {
|
|
57
|
+
if (Array.isArray(raw))
|
|
58
|
+
return raw;
|
|
59
|
+
if (typeof raw !== 'string' || raw.trim() === '')
|
|
60
|
+
return null;
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(raw);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* True when the field carried something but no slice could be read out of it.
|
|
70
|
+
*
|
|
71
|
+
* Lets a caller distinguish "this person has no working pattern on file" from
|
|
72
|
+
* "the pattern is there but in a shape this code does not understand" -- the
|
|
73
|
+
* two need different answers, and reporting the second as the first hides a
|
|
74
|
+
* bug behind a plausible-looking result.
|
|
75
|
+
*/
|
|
76
|
+
export function hasUnreadableAvailabilities(raw) {
|
|
77
|
+
const parsed = decodeAvailabilities(raw);
|
|
78
|
+
if (parsed === null || parsed === undefined)
|
|
79
|
+
return typeof raw === 'string' && raw.trim() !== '';
|
|
80
|
+
if (Array.isArray(parsed) && parsed.length === 0)
|
|
81
|
+
return false;
|
|
82
|
+
return parseAvailabilities(raw).length === 0;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Pick the slice covering a date.
|
|
86
|
+
*
|
|
87
|
+
* People accumulate several slices as their contract changes over time, so
|
|
88
|
+
* picking the first or last one silently produces wrong numbers for any
|
|
89
|
+
* historical or future range.
|
|
90
|
+
*/
|
|
91
|
+
export function sliceForDate(slices, isoDate) {
|
|
92
|
+
const covering = slices.filter((s) => s.from <= isoDate && (s.to === null || s.to >= isoDate));
|
|
93
|
+
if (covering.length === 0)
|
|
94
|
+
return null;
|
|
95
|
+
// Latest start wins when slices overlap.
|
|
96
|
+
return covering.reduce((best, s) => (s.from > best.from ? s : best));
|
|
97
|
+
}
|
|
98
|
+
/** Contracted hours per week = the two-week pattern halved. */
|
|
99
|
+
export function weeklyHours(slice) {
|
|
100
|
+
const total = slice.pattern.reduce((sum, h) => sum + h, 0);
|
|
101
|
+
return slice.pattern.length >= 14 ? total / 2 : total;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Contracted hours on one specific date, read from the matching weekday.
|
|
105
|
+
*
|
|
106
|
+
* Positions matter: a pattern of four eight-hour days is 32h/week, not 40. An
|
|
107
|
+
* average across the worked days would silently inflate exactly those
|
|
108
|
+
* compressed part-time contracts. Where the two weeks of the rotation differ,
|
|
109
|
+
* they are averaged -- the alternation has no documented anchor date, so
|
|
110
|
+
* averaging is the honest approximation.
|
|
111
|
+
*/
|
|
112
|
+
export function hoursOnDate(slice, isoDate) {
|
|
113
|
+
const date = toUtcDate(isoDate);
|
|
114
|
+
if (!date)
|
|
115
|
+
return 0;
|
|
116
|
+
const index = patternIndex(date);
|
|
117
|
+
const { pattern } = slice;
|
|
118
|
+
if (pattern.length >= 14)
|
|
119
|
+
return (pattern[index] + pattern[index + 7]) / 2;
|
|
120
|
+
if (pattern.length >= 7)
|
|
121
|
+
return pattern[index];
|
|
122
|
+
return 0;
|
|
123
|
+
}
|
|
124
|
+
/** Walk every date in an inclusive range. */
|
|
125
|
+
function* datesInRange(startIso, endIso) {
|
|
126
|
+
const start = toUtcDate(startIso);
|
|
127
|
+
const end = toUtcDate(endIso);
|
|
128
|
+
if (!start || !end || end < start)
|
|
129
|
+
return;
|
|
130
|
+
for (const d = new Date(start); d <= end; d.setUTCDate(d.getUTCDate() + 1)) {
|
|
131
|
+
yield new Date(d);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Contracted minutes across a date range.
|
|
136
|
+
*
|
|
137
|
+
* Evaluated day by day, so a range spanning a contract change picks up each
|
|
138
|
+
* slice where it actually applies. Returns null only when no day in the range
|
|
139
|
+
* is covered by any slice.
|
|
140
|
+
*/
|
|
141
|
+
export function contractedMinutes(slices, startIso, endIso) {
|
|
142
|
+
if (slices.length === 0)
|
|
143
|
+
return null;
|
|
144
|
+
let hours = 0;
|
|
145
|
+
let covered = false;
|
|
146
|
+
for (const date of datesInRange(startIso, endIso)) {
|
|
147
|
+
const iso = toIso(date);
|
|
148
|
+
const slice = sliceForDate(slices, iso);
|
|
149
|
+
if (!slice)
|
|
150
|
+
continue;
|
|
151
|
+
covered = true;
|
|
152
|
+
hours += hoursOnDate(slice, iso);
|
|
153
|
+
}
|
|
154
|
+
return covered ? Math.round(hours * 60) : null;
|
|
155
|
+
}
|
|
156
|
+
/** The part of a booking that falls inside the queried range, or null. */
|
|
157
|
+
export function overlapRange(booking, startIso, endIso) {
|
|
158
|
+
const from = booking.attributes.started_on > startIso ? booking.attributes.started_on : startIso;
|
|
159
|
+
const to = booking.attributes.ended_on < endIso ? booking.attributes.ended_on : endIso;
|
|
160
|
+
return from <= to ? { from, to } : null;
|
|
161
|
+
}
|
|
162
|
+
/** Days in a range that the person is actually contracted to work. */
|
|
163
|
+
function contractedDays(slices, startIso, endIso) {
|
|
164
|
+
let days = 0;
|
|
165
|
+
for (const date of datesInRange(startIso, endIso)) {
|
|
166
|
+
const iso = toIso(date);
|
|
167
|
+
const slice = sliceForDate(slices, iso);
|
|
168
|
+
if (slice && hoursOnDate(slice, iso) > 0)
|
|
169
|
+
days += 1;
|
|
170
|
+
}
|
|
171
|
+
return days;
|
|
172
|
+
}
|
|
173
|
+
/** Weekdays in a range, used when the person has no pattern to go by. */
|
|
174
|
+
function weekdaysInRange(startIso, endIso) {
|
|
175
|
+
let days = 0;
|
|
176
|
+
for (const date of datesInRange(startIso, endIso)) {
|
|
177
|
+
const weekday = date.getUTCDay();
|
|
178
|
+
if (weekday !== 0 && weekday !== 6)
|
|
179
|
+
days += 1;
|
|
180
|
+
}
|
|
181
|
+
return days;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Days in a range that count as working days *for this person*.
|
|
185
|
+
*
|
|
186
|
+
* The person's own pattern decides; calendar Mon-Fri is only the fallback for
|
|
187
|
+
* someone with no pattern on file. Sizing a booking by calendar weekdays would
|
|
188
|
+
* charge a four-day contract for the fifth day -- a normal week of leave for an
|
|
189
|
+
* 80% contract would be written as 40h and then reported back as overbooked.
|
|
190
|
+
*/
|
|
191
|
+
export function workingDaysInRange(slices, startIso, endIso) {
|
|
192
|
+
const contracted = contractedDays(slices, startIso, endIso);
|
|
193
|
+
return contracted > 0 ? contracted : weekdaysInRange(startIso, endIso);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Minutes a booking contributes *within the queried range*.
|
|
197
|
+
*
|
|
198
|
+
* The API's date filters match on overlap, so a six-month booking comes back in
|
|
199
|
+
* a one-week query. Counting its full length against one week's contracted time
|
|
200
|
+
* would report absurd overbooking, so everything is prorated onto the overlap.
|
|
201
|
+
*/
|
|
202
|
+
export function bookedMinutes(booking, slices, startIso, endIso) {
|
|
203
|
+
const overlap = overlapRange(booking, startIso, endIso);
|
|
204
|
+
if (!overlap)
|
|
205
|
+
return 0;
|
|
206
|
+
const a = booking.attributes;
|
|
207
|
+
const workingDays = (from, to) => workingDaysInRange(slices, from, to);
|
|
208
|
+
const overlapDays = workingDays(overlap.from, overlap.to);
|
|
209
|
+
if (overlapDays === 0)
|
|
210
|
+
return 0;
|
|
211
|
+
if (typeof a.percentage === 'number' && a.percentage > 0 && !a.total_time && !a.time) {
|
|
212
|
+
const contracted = contractedMinutes(slices, overlap.from, overlap.to);
|
|
213
|
+
return contracted === null ? 0 : Math.round((contracted * a.percentage) / 100);
|
|
214
|
+
}
|
|
215
|
+
if (typeof a.total_time === 'number' && a.total_time > 0) {
|
|
216
|
+
// Both sides of the ratio have to be counted the same way. Taking the
|
|
217
|
+
// numerator from the person's pattern and the denominator from the API's
|
|
218
|
+
// total_working_days mixes two calendars: whenever they disagree (a public
|
|
219
|
+
// holiday inside the booking, say) a booking that lies entirely inside the
|
|
220
|
+
// window stops adding up to its own total_time.
|
|
221
|
+
const bookingDays = workingDays(a.started_on, a.ended_on);
|
|
222
|
+
if (bookingDays === 0)
|
|
223
|
+
return 0;
|
|
224
|
+
return Math.round(a.total_time * (overlapDays / bookingDays));
|
|
225
|
+
}
|
|
226
|
+
if (typeof a.time === 'number' && a.time > 0)
|
|
227
|
+
return a.time * overlapDays;
|
|
228
|
+
if (typeof a.hours === 'number' && a.hours > 0)
|
|
229
|
+
return Math.round(a.hours * 60) * overlapDays;
|
|
230
|
+
if (typeof a.percentage === 'number' && a.percentage > 0) {
|
|
231
|
+
const contracted = contractedMinutes(slices, overlap.from, overlap.to);
|
|
232
|
+
return contracted === null ? 0 : Math.round((contracted * a.percentage) / 100);
|
|
233
|
+
}
|
|
234
|
+
return 0;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Aggregate one person's bookings for a range into a capacity summary.
|
|
238
|
+
*
|
|
239
|
+
* Absences reduce available time; project bookings consume it. Overbooking is
|
|
240
|
+
* reported, never blocked -- that is a warning, not a validation rule.
|
|
241
|
+
*/
|
|
242
|
+
export function summariseCapacity(bookings, availabilities, startIso, endIso, remoteEventIds) {
|
|
243
|
+
const contracted = contractedMinutes(availabilities, startIso, endIso);
|
|
244
|
+
let projectMinutes = 0;
|
|
245
|
+
let absenceMinutes = 0;
|
|
246
|
+
let remoteMinutes = 0;
|
|
247
|
+
for (const booking of bookings) {
|
|
248
|
+
// Cancelled and rejected bookings never consume capacity.
|
|
249
|
+
if (booking.attributes.canceled || booking.attributes.rejected)
|
|
250
|
+
continue;
|
|
251
|
+
const minutes = bookedMinutes(booking, availabilities, startIso, endIso);
|
|
252
|
+
switch (classifyBooking(booking, remoteEventIds)) {
|
|
253
|
+
case 'project':
|
|
254
|
+
projectMinutes += minutes;
|
|
255
|
+
break;
|
|
256
|
+
case 'remote_work':
|
|
257
|
+
remoteMinutes += minutes;
|
|
258
|
+
break;
|
|
259
|
+
default:
|
|
260
|
+
absenceMinutes += minutes;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// Remote work stays out: somebody working from home is available, and
|
|
264
|
+
// subtracting it would report a fully staffed week as booked solid.
|
|
265
|
+
const plannedMinutes = projectMinutes + absenceMinutes;
|
|
266
|
+
const freeMinutes = contracted === null ? null : contracted - plannedMinutes;
|
|
267
|
+
const share = (part) => contracted === null || contracted === 0 ? null : Math.round((part / contracted) * 1000) / 10;
|
|
268
|
+
return {
|
|
269
|
+
contractedMinutes: contracted,
|
|
270
|
+
projectMinutes,
|
|
271
|
+
absenceMinutes,
|
|
272
|
+
remoteMinutes,
|
|
273
|
+
plannedMinutes,
|
|
274
|
+
freeMinutes,
|
|
275
|
+
utilisationPercent: share(projectMinutes),
|
|
276
|
+
plannedPercent: share(plannedMinutes),
|
|
277
|
+
overbooked: freeMinutes !== null && freeMinutes < 0,
|
|
278
|
+
};
|
|
279
|
+
}
|