@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.
Files changed (63) hide show
  1. package/LICENSE +190 -0
  2. package/NOTICE +6 -0
  3. package/README.md +353 -0
  4. package/build/api/bookings-client.js +249 -0
  5. package/build/api/capacity.js +279 -0
  6. package/build/api/client.js +1296 -0
  7. package/build/api/errors.js +50 -0
  8. package/build/api/invoice-time-entries.js +256 -0
  9. package/build/api/pages-tree.js +106 -0
  10. package/build/api/time-entry-notes.js +75 -0
  11. package/build/api/types.js +1 -0
  12. package/build/auth/logo.js +21 -0
  13. package/build/auth/self-resolver.js +61 -0
  14. package/build/config/index.js +24 -0
  15. package/build/index.js +15 -0
  16. package/build/prompts/timesheet.js +285 -0
  17. package/build/server.js +55 -0
  18. package/build/tools/absences.js +502 -0
  19. package/build/tools/activities.js +140 -0
  20. package/build/tools/bookings.js +531 -0
  21. package/build/tools/budget-services.js +168 -0
  22. package/build/tools/budgets.js +276 -0
  23. package/build/tools/capacity.js +281 -0
  24. package/build/tools/changeset.js +41 -0
  25. package/build/tools/comments.js +469 -0
  26. package/build/tools/companies.js +73 -0
  27. package/build/tools/custom-field-resolver.js +92 -0
  28. package/build/tools/custom-fields.js +155 -0
  29. package/build/tools/folders.js +516 -0
  30. package/build/tools/include-resolver.js +45 -0
  31. package/build/tools/invoice-actions.js +476 -0
  32. package/build/tools/invoice-defaults.js +65 -0
  33. package/build/tools/invoice-time-entries.js +320 -0
  34. package/build/tools/invoices.js +657 -0
  35. package/build/tools/my-tasks.js +100 -0
  36. package/build/tools/page-children.js +129 -0
  37. package/build/tools/pages.js +466 -0
  38. package/build/tools/people.js +147 -0
  39. package/build/tools/projects.js +77 -0
  40. package/build/tools/recent-updates.js +112 -0
  41. package/build/tools/registry.js +409 -0
  42. package/build/tools/subtasks.js +245 -0
  43. package/build/tools/task-backlog.js +106 -0
  44. package/build/tools/task-dependencies.js +244 -0
  45. package/build/tools/task-list-move.js +65 -0
  46. package/build/tools/task-lists.js +535 -0
  47. package/build/tools/task-reposition.js +199 -0
  48. package/build/tools/task-status.js +178 -0
  49. package/build/tools/tasks.js +738 -0
  50. package/build/tools/time-entries.js +736 -0
  51. package/build/tools/time-entry-approval.js +103 -0
  52. package/build/tools/time-entry-delete.js +72 -0
  53. package/build/tools/time-entry-update.js +126 -0
  54. package/build/tools/timers.js +195 -0
  55. package/build/tools/todos.js +342 -0
  56. package/build/tools/tool-helpers.js +114 -0
  57. package/build/tools/toolsets.js +153 -0
  58. package/build/tools/whoami.js +64 -0
  59. package/build/tools/workflow-statuses.js +81 -0
  60. package/build/utils/errors.js +67 -0
  61. package/build/utils/mentions.js +98 -0
  62. package/npm-shrinkwrap.json +1159 -0
  63. package/package.json +79 -0
@@ -0,0 +1,1296 @@
1
+ import { buildBookingQuery } from './bookings-client.js';
2
+ import { ProductiveApiError, formatProductiveErrors, } from './errors.js';
3
+ export class ProductiveAPIClient {
4
+ config;
5
+ constructor(config) {
6
+ this.config = config;
7
+ }
8
+ getHeaders() {
9
+ return {
10
+ 'X-Auth-Token': this.config.PRODUCTIVE_API_TOKEN,
11
+ 'X-Organization-Id': this.config.PRODUCTIVE_ORG_ID,
12
+ 'Content-Type': 'application/vnd.api+json',
13
+ };
14
+ }
15
+ /**
16
+ * Turn a failed response into a ProductiveApiError carrying its HTTP status.
17
+ *
18
+ * The JSON parse is guarded deliberately: a 502 from a proxy answers with an
19
+ * HTML page and a throttled request can answer with nothing at all, and an
20
+ * unguarded `response.json()` surfaces a SyntaxError instead of the failure
21
+ * that actually happened.
22
+ */
23
+ async errorFrom(response) {
24
+ let errors = [];
25
+ try {
26
+ const body = (await response.json());
27
+ errors = body.errors ?? [];
28
+ }
29
+ catch {
30
+ /* non-JSON error body -- the status still says what went wrong */
31
+ }
32
+ const message = formatProductiveErrors(errors) || `API request failed with status ${response.status}`;
33
+ return new ProductiveApiError(message, response.status, errors);
34
+ }
35
+ async makeRequest(path, options) {
36
+ const url = `${this.config.PRODUCTIVE_API_BASE_URL}${path}`;
37
+ const response = await fetch(url, {
38
+ ...options,
39
+ headers: {
40
+ ...this.getHeaders(),
41
+ ...options?.headers,
42
+ },
43
+ });
44
+ if (!response.ok) {
45
+ throw await this.errorFrom(response);
46
+ }
47
+ return (await response.json());
48
+ }
49
+ async makeVoidRequest(path, options) {
50
+ const url = `${this.config.PRODUCTIVE_API_BASE_URL}${path}`;
51
+ const response = await fetch(url, {
52
+ ...options,
53
+ headers: {
54
+ ...this.getHeaders(),
55
+ ...options?.headers,
56
+ },
57
+ });
58
+ if (!response.ok) {
59
+ throw await this.errorFrom(response);
60
+ }
61
+ }
62
+ async listCompanies(params) {
63
+ const statusMap = { active: '1', archived: '2' };
64
+ const queryParams = new URLSearchParams();
65
+ if (params?.status) {
66
+ queryParams.append('filter[status]', statusMap[params.status]);
67
+ }
68
+ if (params?.limit) {
69
+ queryParams.append('page[size]', params.limit.toString());
70
+ }
71
+ if (params?.page) {
72
+ queryParams.append('page[number]', params.page.toString());
73
+ }
74
+ const queryString = queryParams.toString();
75
+ const path = `companies${queryString ? `?${queryString}` : ''}`;
76
+ return this.makeRequest(path);
77
+ }
78
+ async listProjects(params) {
79
+ const queryParams = new URLSearchParams();
80
+ queryParams.append('include', 'company');
81
+ if (params?.status) {
82
+ // Convert status string to integer: active = 1, archived = 2
83
+ const statusValue = params.status === 'active' ? '1' : '2';
84
+ queryParams.append('filter[status]', statusValue);
85
+ }
86
+ if (params?.company_id) {
87
+ queryParams.append('filter[company_id]', params.company_id);
88
+ }
89
+ if (params?.limit) {
90
+ queryParams.append('page[size]', params.limit.toString());
91
+ }
92
+ if (params?.page) {
93
+ queryParams.append('page[number]', params.page.toString());
94
+ }
95
+ const queryString = queryParams.toString();
96
+ const path = `projects${queryString ? `?${queryString}` : ''}`;
97
+ return this.makeRequest(path);
98
+ }
99
+ async listTasks(params) {
100
+ const queryParams = new URLSearchParams();
101
+ // Include assignee and workflow status so we can resolve names
102
+ queryParams.append('include', 'assignee,workflow_status,project');
103
+ if (params?.project_id) {
104
+ queryParams.append('filter[project_id]', params.project_id);
105
+ }
106
+ if (params?.parent_task_id) {
107
+ queryParams.append('filter[parent_task_id]', params.parent_task_id);
108
+ }
109
+ if (params?.assignee_id) {
110
+ queryParams.append('filter[assignee_id]', params.assignee_id);
111
+ }
112
+ if (params?.status) {
113
+ // Convert status names to integers: open = 1, closed = 2
114
+ const statusValue = params.status === 'open' ? '1' : '2';
115
+ queryParams.append('filter[status]', statusValue);
116
+ }
117
+ if (params?.limit) {
118
+ queryParams.append('page[size]', params.limit.toString());
119
+ }
120
+ if (params?.page) {
121
+ queryParams.append('page[number]', params.page.toString());
122
+ }
123
+ const queryString = queryParams.toString();
124
+ const path = `tasks${queryString ? `?${queryString}` : ''}`;
125
+ return this.makeRequest(path);
126
+ }
127
+ async createTask(taskData) {
128
+ return this.makeRequest('tasks', {
129
+ method: 'POST',
130
+ body: JSON.stringify(taskData),
131
+ });
132
+ }
133
+ async listTaskLists(params) {
134
+ const queryParams = new URLSearchParams();
135
+ if (params?.board_id) {
136
+ // The board/folder filter on task lists is `folder_id` -- `filter[board_id]`
137
+ // is rejected with 422 (verified live), same folders-vs-boards split as the
138
+ // `/api/v2/folders` route itself.
139
+ queryParams.append('filter[folder_id]', params.board_id);
140
+ }
141
+ if (params?.project_id) {
142
+ queryParams.append('filter[project_id]', params.project_id);
143
+ }
144
+ if (params?.limit) {
145
+ queryParams.append('page[size]', params.limit.toString());
146
+ }
147
+ if (params?.page) {
148
+ queryParams.append('page[number]', params.page.toString());
149
+ }
150
+ const queryString = queryParams.toString();
151
+ const path = `task_lists${queryString ? `?${queryString}` : ''}`;
152
+ return this.makeRequest(path);
153
+ }
154
+ async createTaskList(taskListData) {
155
+ return this.makeRequest('task_lists', {
156
+ method: 'POST',
157
+ body: JSON.stringify(taskListData),
158
+ });
159
+ }
160
+ async listPeople(params) {
161
+ const queryParams = new URLSearchParams();
162
+ if (params?.company_id) {
163
+ queryParams.append('filter[company_id]', params.company_id);
164
+ }
165
+ if (params?.project_id) {
166
+ queryParams.append('filter[project_id]', params.project_id);
167
+ }
168
+ if (params?.is_active !== undefined) {
169
+ // Productive's /people endpoint has no `is_active` filter -- there is no
170
+ // such attribute at all (a person carries `deactivated_at`). The
171
+ // documented filter is `filter[status]` (1: active, 2: deactivated).
172
+ queryParams.append('filter[status]', params.is_active ? '1' : '2');
173
+ }
174
+ if (params?.email) {
175
+ queryParams.append('filter[email]', params.email);
176
+ }
177
+ if (params?.limit) {
178
+ queryParams.append('page[size]', params.limit.toString());
179
+ }
180
+ if (params?.page) {
181
+ queryParams.append('page[number]', params.page.toString());
182
+ }
183
+ const queryString = queryParams.toString();
184
+ const path = `people${queryString ? `?${queryString}` : ''}`;
185
+ return this.makeRequest(path);
186
+ }
187
+ async getPerson(personId) {
188
+ return this.makeRequest(`people/${personId}`);
189
+ }
190
+ /**
191
+ * The memberships of the token owner. The endpoint is scoped to the
192
+ * authenticated user, not to what the token may see: an admin token gets its
193
+ * own membership only (verified against the sandbox, where the same token
194
+ * reads all 17 salaries). `include=person` is required, without it the person
195
+ * relationship comes back as a stub with no id.
196
+ *
197
+ * The filter takes an integer, so only the numeric prefix of an org ID such
198
+ * as `12345-company-name` is sent -- the slug answers `unsupported_filter_value_type`.
199
+ */
200
+ async listOwnOrganizationMemberships(signal) {
201
+ const queryParams = new URLSearchParams({ include: 'person' });
202
+ const numericOrgId = /^\d+/.exec(this.config.PRODUCTIVE_ORG_ID)?.[0];
203
+ if (numericOrgId) {
204
+ queryParams.append('filter[organization_id]', numericOrgId);
205
+ }
206
+ return this.makeRequest(`organization_memberships?${queryParams.toString()}`, { signal });
207
+ }
208
+ async getTask(taskId) {
209
+ return this.makeRequest(`tasks/${taskId}?include=task_list,assignee,workflow_status,project`);
210
+ }
211
+ async getProject(projectId) {
212
+ return this.makeRequest(`projects/${projectId}?include=workflow`);
213
+ }
214
+ async updateTask(taskId, taskData) {
215
+ return this.makeRequest(`tasks/${taskId}`, {
216
+ method: 'PATCH',
217
+ body: JSON.stringify(taskData),
218
+ });
219
+ }
220
+ async listActivities(params) {
221
+ const queryParams = new URLSearchParams();
222
+ if (params?.task_id) {
223
+ queryParams.append('filter[task_id]', params.task_id);
224
+ }
225
+ if (params?.project_id) {
226
+ queryParams.append('filter[project_id]', params.project_id);
227
+ }
228
+ if (params?.person_id) {
229
+ queryParams.append('filter[person_id]', params.person_id);
230
+ }
231
+ if (params?.item_type) {
232
+ queryParams.append('filter[item_type]', params.item_type);
233
+ }
234
+ if (params?.event) {
235
+ queryParams.append('filter[event]', params.event);
236
+ }
237
+ if (params?.after) {
238
+ queryParams.append('filter[after]', params.after);
239
+ }
240
+ if (params?.before) {
241
+ queryParams.append('filter[before]', params.before);
242
+ }
243
+ if (params?.limit) {
244
+ queryParams.append('page[size]', params.limit.toString());
245
+ }
246
+ if (params?.page) {
247
+ queryParams.append('page[number]', params.page.toString());
248
+ }
249
+ const queryString = queryParams.toString();
250
+ const path = `activities${queryString ? `?${queryString}` : ''}`;
251
+ return this.makeRequest(path);
252
+ }
253
+ async createComment(commentData) {
254
+ return this.makeRequest('comments', {
255
+ method: 'POST',
256
+ body: JSON.stringify(commentData),
257
+ });
258
+ }
259
+ async listWorkflowStatuses(params) {
260
+ const queryParams = new URLSearchParams();
261
+ if (params?.workflow_id) {
262
+ queryParams.append('filter[workflow_id]', params.workflow_id);
263
+ }
264
+ if (params?.category_id) {
265
+ queryParams.append('filter[category_id]', params.category_id.toString());
266
+ }
267
+ if (params?.limit) {
268
+ queryParams.append('page[size]', params.limit.toString());
269
+ }
270
+ if (params?.page) {
271
+ queryParams.append('page[number]', params.page.toString());
272
+ }
273
+ const queryString = queryParams.toString();
274
+ const path = `workflow_statuses${queryString ? `?${queryString}` : ''}`;
275
+ return this.makeRequest(path);
276
+ }
277
+ /**
278
+ * List time entries with optional filters
279
+ *
280
+ * @param params - Filter parameters for time entries
281
+ * @param params.date - Filter by specific date (ISO format: YYYY-MM-DD)
282
+ * @param params.after - Filter entries after this date (ISO format: YYYY-MM-DD)
283
+ * @param params.before - Filter entries before this date (ISO format: YYYY-MM-DD)
284
+ * @param params.person_id - Filter by person ID
285
+ * @param params.project_id - Filter by project ID
286
+ * @param params.task_id - Filter by task ID
287
+ * @param params.service_id - Filter by service ID
288
+ * @param params.approved - Filter by approval state (true/false)
289
+ * @param params.approver_id - Filter by the ID of the person who approved the entry
290
+ * @param params.limit - Number of results per page
291
+ * @param params.page - Page number for pagination
292
+ * @returns Promise resolving to paginated time entries response
293
+ *
294
+ * @example
295
+ * // Get time entries for a specific person and date range
296
+ * const entries = await client.listTimeEntries({
297
+ * person_id: "123",
298
+ * after: "2023-01-01",
299
+ * before: "2023-01-31"
300
+ * });
301
+ */
302
+ async listTimeEntries(params) {
303
+ const queryParams = new URLSearchParams();
304
+ // Include relationships by default
305
+ queryParams.append('include', 'person,service,task,approver');
306
+ if (params?.date) {
307
+ queryParams.append('filter[date]', params.date);
308
+ }
309
+ if (params?.after) {
310
+ queryParams.append('filter[after]', params.after);
311
+ }
312
+ if (params?.before) {
313
+ queryParams.append('filter[before]', params.before);
314
+ }
315
+ if (params?.person_id) {
316
+ queryParams.append('filter[person_id]', params.person_id);
317
+ }
318
+ if (params?.project_id) {
319
+ queryParams.append('filter[project_id]', params.project_id);
320
+ }
321
+ if (params?.task_id) {
322
+ queryParams.append('filter[task_id]', params.task_id);
323
+ }
324
+ if (params?.service_id) {
325
+ queryParams.append('filter[service_id]', params.service_id);
326
+ }
327
+ if (params?.invoice_id) {
328
+ // Live-verified to actually filter (2582 rows unfiltered, 70 for one
329
+ // invoice, 0 for an id that does not exist) -- worth stating because a
330
+ // documented filter can answer 200 and ignore its value, as
331
+ // filter[booking_type] does. Accepts a comma-separated list.
332
+ //
333
+ // Two traps this does NOT cover. `filter[invoice_id][not_eq]` is not
334
+ // "uninvoiced": it matches only inside entries that already carry an
335
+ // attribution, so negating one invoice answers 2081 rather than
336
+ // 2582 - 70. Use filter[invoiced] for that. And the response carries no
337
+ // `invoice_id` attribute at all -- only `invoice_attribution_id` and
338
+ // `invoiced` -- so the filter is the only way to establish the link and a
339
+ // returned row cannot be re-checked against the invoice that was asked for.
340
+ queryParams.append('filter[invoice_id]', params.invoice_id);
341
+ }
342
+ if (params?.approved !== undefined) {
343
+ // approved/rejected/submitted are response attributes, not filter keys --
344
+ // filter[approved]=true 422s live. The real filter is filter[status]
345
+ // (undocumented enum, live-confirmed: 1=approved). not_eq robustly covers
346
+ // every other code for approved:false, not just the confirmed value 2.
347
+ if (params.approved) {
348
+ queryParams.append('filter[status]', '1');
349
+ }
350
+ else {
351
+ queryParams.append('filter[status][not_eq]', '1');
352
+ }
353
+ }
354
+ if (params?.approver_id) {
355
+ queryParams.append('filter[approver_id]', params.approver_id);
356
+ }
357
+ if (params?.sort) {
358
+ // Only `date` and `-date` are live-verified here; `id`, `created_at` and
359
+ // the compound `date,id` all answer 400. Note that `spec:impact` checks
360
+ // filter[...] keys only and would not catch a bad sort key, so do not
361
+ // pass one that has not been tried against the API.
362
+ queryParams.append('sort', params.sort);
363
+ }
364
+ if (params?.limit) {
365
+ queryParams.append('page[size]', params.limit.toString());
366
+ }
367
+ if (params?.page) {
368
+ queryParams.append('page[number]', params.page.toString());
369
+ }
370
+ const queryString = queryParams.toString();
371
+ const path = `time_entries${queryString ? `?${queryString}` : ''}`;
372
+ return this.makeRequest(path);
373
+ }
374
+ /**
375
+ * Create a new time entry
376
+ *
377
+ * @param timeEntryData - Time entry creation data
378
+ * @returns Promise resolving to the created time entry
379
+ *
380
+ * @example
381
+ * // Create a time entry for a task
382
+ * const timeEntry = await client.createTimeEntry({
383
+ * data: {
384
+ * type: 'time_entries',
385
+ * attributes: {
386
+ * date: '2023-01-15',
387
+ * time: 120, // 2 hours in minutes
388
+ * note: 'Working on feature implementation'
389
+ * },
390
+ * relationships: {
391
+ * person: { data: { id: '123', type: 'people' } },
392
+ * service: { data: { id: '456', type: 'services' } },
393
+ * task: { data: { id: '789', type: 'tasks' } }
394
+ * }
395
+ * }
396
+ * });
397
+ */
398
+ async createTimeEntry(timeEntryData) {
399
+ return this.makeRequest('time_entries', {
400
+ method: 'POST',
401
+ body: JSON.stringify(timeEntryData),
402
+ });
403
+ }
404
+ /**
405
+ * List deals/budgets for a specific project
406
+ *
407
+ * @param params - Filter parameters for deals
408
+ * @param params.project_id - Filter by project ID (required)
409
+ * @param params.budget_type - Filter by budget type (1: deal, 2: budget)
410
+ * @param params.limit - Number of results per page
411
+ * @param params.page - Page number for pagination
412
+ * @returns Promise resolving to paginated deals response
413
+ *
414
+ * @example
415
+ * // Get all deals/budgets for a project
416
+ * const deals = await client.listProjectDeals({
417
+ * project_id: '123',
418
+ * budget_type: 2 // Only budgets
419
+ * });
420
+ */
421
+ async listProjectDeals(params) {
422
+ const queryParams = new URLSearchParams();
423
+ // Include project relationship
424
+ queryParams.append('include', 'project');
425
+ // Filter by project - deals endpoint expects array format
426
+ queryParams.append('filter[project_id]', params.project_id);
427
+ if (params.budget_type) {
428
+ // Productive's /deals endpoint has no `budget_type` filter -- `budget_type`
429
+ // is only a response attribute. The documented filter is `filter[type]`
430
+ // (1: deal, 2: budget).
431
+ queryParams.append('filter[type]', params.budget_type.toString());
432
+ }
433
+ if (params.limit) {
434
+ queryParams.append('page[size]', params.limit.toString());
435
+ }
436
+ if (params.page) {
437
+ queryParams.append('page[number]', params.page.toString());
438
+ }
439
+ const queryString = queryParams.toString();
440
+ const path = `deals${queryString ? `?${queryString}` : ''}`;
441
+ return this.makeRequest(path);
442
+ }
443
+ /**
444
+ * List services available for a specific deal/budget
445
+ *
446
+ * @param params - Filter parameters for services
447
+ * @param params.deal_id - Filter by deal/budget ID
448
+ * @param params.limit - Number of results per page
449
+ * @param params.page - Page number for pagination
450
+ * @returns Promise resolving to paginated services response
451
+ *
452
+ * @example
453
+ * // Get services for a specific deal/budget
454
+ * const services = await client.listDealServices({
455
+ * deal_id: '456'
456
+ * });
457
+ */
458
+ async listDealServices(params) {
459
+ const queryParams = new URLSearchParams();
460
+ // Filter by deal/budget
461
+ queryParams.append('filter[deal_id]', params.deal_id);
462
+ if (params.limit) {
463
+ queryParams.append('page[size]', params.limit.toString());
464
+ }
465
+ if (params.page) {
466
+ queryParams.append('page[number]', params.page.toString());
467
+ }
468
+ const queryString = queryParams.toString();
469
+ const path = `services${queryString ? `?${queryString}` : ''}`;
470
+ return this.makeRequest(path);
471
+ }
472
+ /**
473
+ * List services available for time tracking
474
+ *
475
+ * @param params - Filter parameters for services
476
+ * @param params.company_id - Filter by company ID
477
+ * @param params.limit - Number of results per page
478
+ * @param params.page - Page number for pagination
479
+ * @returns Promise resolving to paginated services response
480
+ *
481
+ * @example
482
+ * // Get all services
483
+ * const services = await client.listServices({
484
+ * company_id: '123'
485
+ * });
486
+ */
487
+ async listServices(params) {
488
+ const queryParams = new URLSearchParams();
489
+ if (params?.company_id) {
490
+ queryParams.append('filter[company_id]', params.company_id);
491
+ }
492
+ if (params?.budget_status) {
493
+ queryParams.append('filter[budget_status]', params.budget_status.toString());
494
+ }
495
+ if (params?.limit) {
496
+ queryParams.append('page[size]', params.limit.toString());
497
+ }
498
+ if (params?.page) {
499
+ queryParams.append('page[number]', params.page.toString());
500
+ }
501
+ const queryString = queryParams.toString();
502
+ const path = `services${queryString ? `?${queryString}` : ''}`;
503
+ return this.makeRequest(path);
504
+ }
505
+ /**
506
+ * Get a specific time entry by ID
507
+ *
508
+ * @param timeEntryId - The ID of the time entry to retrieve
509
+ * @returns Promise resolving to the time entry
510
+ *
511
+ * @example
512
+ * const timeEntry = await client.getTimeEntry('123');
513
+ */
514
+ async getTimeEntry(timeEntryId) {
515
+ return this.makeRequest(`time_entries/${timeEntryId}`);
516
+ }
517
+ /**
518
+ * Update an existing time entry's attributes
519
+ *
520
+ * @param timeEntryId - The ID of the time entry to update
521
+ * @param timeEntryData - The update payload
522
+ * @returns Promise resolving to the updated time entry
523
+ */
524
+ async updateTimeEntry(timeEntryId, timeEntryData) {
525
+ return this.makeRequest(`time_entries/${timeEntryId}`, {
526
+ method: 'PATCH',
527
+ body: JSON.stringify(timeEntryData),
528
+ });
529
+ }
530
+ async deleteTimeEntry(id) {
531
+ return this.makeVoidRequest(`time_entries/${id}`, { method: 'DELETE' });
532
+ }
533
+ /**
534
+ * Approve a time entry
535
+ */
536
+ async approveTimeEntry(timeEntryId) {
537
+ return this.makeRequest(`time_entries/${timeEntryId}/approve`, { method: 'PATCH' });
538
+ }
539
+ /**
540
+ * Unapprove a time entry (reverse approval)
541
+ */
542
+ async unapproveTimeEntry(timeEntryId) {
543
+ return this.makeRequest(`time_entries/${timeEntryId}/unapprove`, { method: 'PATCH' });
544
+ }
545
+ /**
546
+ * Reject a time entry
547
+ */
548
+ async rejectTimeEntry(timeEntryId, rejectedReason) {
549
+ return this.makeRequest(`time_entries/${timeEntryId}/reject`, {
550
+ method: 'PATCH',
551
+ body: rejectedReason
552
+ ? JSON.stringify({
553
+ data: {
554
+ type: 'time_entries',
555
+ id: timeEntryId,
556
+ attributes: { rejected_reason: rejectedReason },
557
+ },
558
+ })
559
+ : undefined,
560
+ });
561
+ }
562
+ /**
563
+ * Unreject a time entry (reverse rejection)
564
+ */
565
+ async unrejectTimeEntry(timeEntryId) {
566
+ return this.makeRequest(`time_entries/${timeEntryId}/unreject`, { method: 'PATCH' });
567
+ }
568
+ /**
569
+ * Get a timer by ID
570
+ */
571
+ async getTimer(timerId) {
572
+ return this.makeRequest(`timers/${timerId}`);
573
+ }
574
+ /**
575
+ * Get a timer by ID with time_entry relationship included
576
+ */
577
+ async getTimerWithTimeEntry(timerId) {
578
+ return this.makeRequest(`timers/${timerId}?include=time_entry`);
579
+ }
580
+ /**
581
+ * Create and start a new timer
582
+ */
583
+ async createTimer(timerData) {
584
+ return this.makeRequest('timers', {
585
+ method: 'POST',
586
+ body: JSON.stringify(timerData),
587
+ });
588
+ }
589
+ /**
590
+ * Stop a running timer
591
+ */
592
+ async stopTimer(timerId) {
593
+ return this.makeRequest(`timers/${timerId}/stop`, {
594
+ method: 'PATCH',
595
+ });
596
+ }
597
+ /**
598
+ * Helper method to get time entries for a specific date range
599
+ * Convenience wrapper around listTimeEntries with date filtering
600
+ *
601
+ * @param startDate - Start date in ISO format (YYYY-MM-DD)
602
+ * @param endDate - End date in ISO format (YYYY-MM-DD)
603
+ * @param additionalParams - Additional filter parameters
604
+ * @returns Promise resolving to paginated time entries response
605
+ *
606
+ * @example
607
+ * // Get all time entries for last week
608
+ * const entries = await client.getTimeEntriesInDateRange(
609
+ * '2023-01-01',
610
+ * '2023-01-07',
611
+ * { person_id: '123' }
612
+ * );
613
+ */
614
+ async getTimeEntriesInDateRange(startDate, endDate, additionalParams) {
615
+ return this.listTimeEntries({
616
+ after: startDate,
617
+ before: endDate,
618
+ ...additionalParams,
619
+ });
620
+ }
621
+ /**
622
+ * Helper method to get time entries for today
623
+ * Convenience wrapper for getting current day's time entries
624
+ *
625
+ * @param additionalParams - Additional filter parameters
626
+ * @returns Promise resolving to paginated time entries response
627
+ *
628
+ * @example
629
+ * // Get today's time entries for a specific person
630
+ * const todayEntries = await client.getTodayTimeEntries({
631
+ * person_id: '123'
632
+ * });
633
+ */
634
+ async getTodayTimeEntries(additionalParams) {
635
+ const today = new Date().toISOString().split('T')[0]; // Get YYYY-MM-DD format
636
+ return this.listTimeEntries({
637
+ date: today,
638
+ ...additionalParams,
639
+ });
640
+ }
641
+ async listDocumentTypes(params) {
642
+ const queryParams = new URLSearchParams();
643
+ if (params?.limit) {
644
+ queryParams.append('page[size]', params.limit.toString());
645
+ }
646
+ const queryString = queryParams.toString();
647
+ const path = `document_types${queryString ? `?${queryString}` : ''}`;
648
+ return this.makeRequest(path);
649
+ }
650
+ async listTaxRates(params) {
651
+ const queryParams = new URLSearchParams();
652
+ if (params?.limit) {
653
+ queryParams.append('page[size]', params.limit.toString());
654
+ }
655
+ const queryString = queryParams.toString();
656
+ const path = `tax_rates${queryString ? `?${queryString}` : ''}`;
657
+ return this.makeRequest(path);
658
+ }
659
+ async listInvoices(params) {
660
+ const queryParams = new URLSearchParams();
661
+ queryParams.append('include', 'company');
662
+ if (params?.company_id)
663
+ queryParams.append('filter[company_id]', params.company_id);
664
+ if (params?.project_id)
665
+ queryParams.append('filter[project_id]', params.project_id);
666
+ if (params?.deal_id)
667
+ queryParams.append('filter[deal_id]', params.deal_id);
668
+ if (params?.invoice_state)
669
+ queryParams.append('filter[invoice_state]', params.invoice_state.toString());
670
+ if (params?.invoice_status)
671
+ queryParams.append('filter[invoice_status]', params.invoice_status.toString());
672
+ if (params?.payment_status)
673
+ queryParams.append('filter[payment_status]', params.payment_status.toString());
674
+ // The invoice number a human reads off the document ("20260035"), not the
675
+ // internal id. The spec lists `contains` among this key's operators, so a
676
+ // caller matching on identity must still compare the returned `number`
677
+ // rather than trusting that one row came back.
678
+ if (params?.number)
679
+ queryParams.append('filter[number]', params.number);
680
+ // Invoices have no `after`/`before` filter (both 422 live). The invoice date
681
+ // is `invoiced_on` -- the same field this endpoint already sorts by. Bounds are
682
+ // inclusive so a range covers its edge days.
683
+ if (params?.after)
684
+ queryParams.append('filter[invoiced_on][gt_eq]', params.after);
685
+ if (params?.before)
686
+ queryParams.append('filter[invoiced_on][lt_eq]', params.before);
687
+ if (params?.full_query)
688
+ queryParams.append('filter[full_query]', params.full_query);
689
+ if (params?.limit)
690
+ queryParams.append('page[size]', params.limit.toString());
691
+ if (params?.page)
692
+ queryParams.append('page[number]', params.page.toString());
693
+ queryParams.append('sort', '-invoiced_on');
694
+ const queryString = queryParams.toString();
695
+ const path = `invoices${queryString ? `?${queryString}` : ''}`;
696
+ return this.makeRequest(path);
697
+ }
698
+ async getInvoice(id) {
699
+ return this.makeRequest(`invoices/${id}?include=company`);
700
+ }
701
+ async listLineItems(params) {
702
+ const queryParams = new URLSearchParams();
703
+ queryParams.append('filter[invoice_id]', params.invoice_id);
704
+ if (params.limit)
705
+ queryParams.append('page[size]', params.limit.toString());
706
+ return this.makeRequest(`line_items?${queryParams.toString()}`);
707
+ }
708
+ async createInvoice(data) {
709
+ return this.makeRequest('invoices', {
710
+ method: 'POST',
711
+ body: JSON.stringify(data),
712
+ });
713
+ }
714
+ async updateInvoice(id, data) {
715
+ return this.makeRequest(`invoices/${id}`, {
716
+ method: 'PATCH',
717
+ body: JSON.stringify(data),
718
+ });
719
+ }
720
+ async generateLineItems(data) {
721
+ return this.makeRequest('line_items/generate', {
722
+ method: 'POST',
723
+ body: JSON.stringify(data),
724
+ });
725
+ }
726
+ async finalizeInvoice(id) {
727
+ return this.makeRequest(`invoices/${id}/finalize`, {
728
+ method: 'PATCH',
729
+ body: JSON.stringify({ data: { type: 'invoices', attributes: {} } }),
730
+ });
731
+ }
732
+ async listSubsidiaries() {
733
+ return this.makeRequest('subsidiaries');
734
+ }
735
+ async listDealStatuses() {
736
+ return this.makeRequest('deal_statuses');
737
+ }
738
+ async listCompanyBudgets(params) {
739
+ const queryParams = new URLSearchParams();
740
+ queryParams.append('filter[type]', '2');
741
+ // Productive's /deals endpoint has no `status` filter for open/closed --
742
+ // the documented filter is `filter[budget_status]` (1: open, 2: closed).
743
+ if (params.status)
744
+ queryParams.append('filter[budget_status]', params.status.toString());
745
+ queryParams.append('filter[company_id]', params.company_id);
746
+ queryParams.append('include', 'project');
747
+ if (params.limit)
748
+ queryParams.append('page[size]', params.limit.toString());
749
+ return this.makeRequest(`deals?${queryParams.toString()}`);
750
+ }
751
+ async createDeal(data) {
752
+ return this.makeRequest('deals', {
753
+ method: 'POST',
754
+ body: JSON.stringify(data),
755
+ });
756
+ }
757
+ async updateDeal(id, data) {
758
+ return this.makeRequest(`deals/${id}`, {
759
+ method: 'PATCH',
760
+ body: JSON.stringify(data),
761
+ });
762
+ }
763
+ async createDealFromOrigin(data) {
764
+ return this.makeRequest('deals/create_from_origin', {
765
+ method: 'POST',
766
+ body: JSON.stringify(data),
767
+ });
768
+ }
769
+ async listDealsByOriginId(originDealId) {
770
+ const queryParams = new URLSearchParams();
771
+ queryParams.append('filter[origin_deal_id]', originDealId);
772
+ queryParams.append('filter[type]', '2');
773
+ return this.makeRequest(`deals?${queryParams.toString()}`);
774
+ }
775
+ async deleteDeal(id) {
776
+ return this.makeVoidRequest(`deals/${id}`, { method: 'DELETE' });
777
+ }
778
+ async createService(data) {
779
+ return this.makeRequest('services', {
780
+ method: 'POST',
781
+ body: JSON.stringify(data),
782
+ });
783
+ }
784
+ async updateService(id, data) {
785
+ return this.makeRequest(`services/${id}`, {
786
+ method: 'PATCH',
787
+ body: JSON.stringify(data),
788
+ });
789
+ }
790
+ async deleteService(id) {
791
+ return this.makeVoidRequest(`services/${id}`, { method: 'DELETE' });
792
+ }
793
+ async deleteInvoice(id) {
794
+ // Was a hand-rolled fetch carrying its own copy of the error parsing.
795
+ return this.makeVoidRequest(`invoices/${id}`, { method: 'DELETE' });
796
+ }
797
+ async createPayment(data) {
798
+ return this.makeRequest('payments', {
799
+ method: 'POST',
800
+ body: JSON.stringify(data),
801
+ });
802
+ }
803
+ /**
804
+ * Reposition a task in a task list
805
+ *
806
+ * @param taskId - ID of the task to reposition
807
+ * @param attributes - Positioning attributes (move_before_id and/or move_after_id)
808
+ * @returns Promise resolving to the task response
809
+ *
810
+ * @example
811
+ * // Position task 1 after task 2
812
+ * await client.repositionTask('1', { move_after_id: '2' });
813
+ *
814
+ * // Position task 3 between tasks 1 and 2
815
+ * await client.repositionTask('3', { move_after_id: '1', move_before_id: '2' });
816
+ */
817
+ async repositionTask(taskId, attributes) {
818
+ const requestBody = {
819
+ data: {
820
+ type: 'tasks',
821
+ attributes: { ...attributes },
822
+ },
823
+ };
824
+ // The reposition endpoint returns 204 No Content on success
825
+ const url = `${this.config.PRODUCTIVE_API_BASE_URL}tasks/${taskId}/reposition`;
826
+ try {
827
+ const response = await fetch(url, {
828
+ method: 'PATCH',
829
+ // getHeaders() rather than a hand-written copy: this method used to
830
+ // rebuild the three headers itself and would silently miss any change
831
+ // made there.
832
+ headers: this.getHeaders(),
833
+ body: JSON.stringify(requestBody),
834
+ });
835
+ if (!response.ok) {
836
+ const apiError = await this.errorFrom(response);
837
+ // Productive's 404 here means either "no such task" or "this task cannot
838
+ // be repositioned", and its own message says neither. Keep the clearer
839
+ // wording, but as a ProductiveApiError so the status still maps.
840
+ if (response.status === 404) {
841
+ throw new ProductiveApiError(`Task ${taskId} not found or cannot be repositioned.`, 404, apiError.errors);
842
+ }
843
+ throw apiError;
844
+ }
845
+ // If 204 No Content (success), return a minimal success response
846
+ if (response.status === 204) {
847
+ return {
848
+ success: true,
849
+ taskId: taskId,
850
+ message: `Task ${taskId} repositioned successfully`,
851
+ };
852
+ }
853
+ // For any other success response with content, try to parse JSON
854
+ try {
855
+ return await response.json();
856
+ }
857
+ catch (e) {
858
+ // If parsing fails but status was success, return a minimal success object
859
+ return {
860
+ success: true,
861
+ taskId: taskId,
862
+ message: `Task ${taskId} repositioned successfully`,
863
+ };
864
+ }
865
+ }
866
+ catch (error) {
867
+ console.error('Error repositioning task:', error);
868
+ throw error;
869
+ }
870
+ }
871
+ // ---- Board methods ----
872
+ // Productive's UI/tool-facing name for this resource is "folder" (see
873
+ // src/tools/folders.ts). All nine methods below deliberately hit the
874
+ // literal path "folders" -- this tenant's live API 404s on "boards"
875
+ // (verified) despite that being the API's relationship-level vocabulary
876
+ // (ProductiveTask.board / ProductiveTaskList.board both use type 'boards').
877
+ async listBoards(params) {
878
+ const q = new URLSearchParams();
879
+ q.append('include', 'project');
880
+ if (params?.project_id)
881
+ q.append('filter[project_id]', params.project_id);
882
+ if (params?.status)
883
+ q.append('filter[status]', params.status.toString());
884
+ if (params?.limit)
885
+ q.append('page[size]', params.limit.toString());
886
+ if (params?.page)
887
+ q.append('page[number]', params.page.toString());
888
+ return this.makeRequest(`folders?${q.toString()}`);
889
+ }
890
+ async getBoard(boardId) {
891
+ return this.makeRequest(`folders/${boardId}?include=project`);
892
+ }
893
+ async createBoard(data) {
894
+ return this.makeRequest('folders', {
895
+ method: 'POST',
896
+ body: JSON.stringify(data),
897
+ });
898
+ }
899
+ async updateBoard(boardId, data) {
900
+ return this.makeRequest(`folders/${boardId}`, {
901
+ method: 'PATCH',
902
+ body: JSON.stringify(data),
903
+ });
904
+ }
905
+ async archiveBoard(boardId) {
906
+ return this.makeVoidRequest(`folders/${boardId}/archive`, {
907
+ method: 'PATCH',
908
+ body: JSON.stringify({ data: { type: 'folders' } }),
909
+ });
910
+ }
911
+ async restoreBoard(boardId) {
912
+ return this.makeVoidRequest(`folders/${boardId}/restore`, {
913
+ method: 'PATCH',
914
+ body: JSON.stringify({ data: { type: 'folders' } }),
915
+ });
916
+ }
917
+ async moveBoard(boardId, projectId) {
918
+ return this.makeVoidRequest(`folders/${boardId}/move`, {
919
+ method: 'PATCH',
920
+ body: JSON.stringify({
921
+ data: { type: 'folders', attributes: { project_id: projectId } },
922
+ }),
923
+ });
924
+ }
925
+ async repositionBoard(boardId, moveBeforeId) {
926
+ return this.makeVoidRequest(`folders/${boardId}/reposition`, {
927
+ method: 'PATCH',
928
+ body: JSON.stringify({
929
+ data: { type: 'folders', attributes: { move_before_id: moveBeforeId } },
930
+ }),
931
+ });
932
+ }
933
+ async copyBoard(params) {
934
+ return this.makeRequest('folders/copy', {
935
+ method: 'POST',
936
+ body: JSON.stringify({
937
+ data: {
938
+ type: 'folders',
939
+ attributes: {
940
+ name: params.name,
941
+ template_id: params.template_id,
942
+ project_id: params.project_id,
943
+ },
944
+ },
945
+ }),
946
+ });
947
+ }
948
+ // ---- Task List extended methods ----
949
+ async getTaskList(taskListId) {
950
+ return this.makeRequest(`task_lists/${taskListId}`);
951
+ }
952
+ async updateTaskList(taskListId, data) {
953
+ return this.makeRequest(`task_lists/${taskListId}`, {
954
+ method: 'PATCH',
955
+ body: JSON.stringify(data),
956
+ });
957
+ }
958
+ async archiveTaskList(taskListId) {
959
+ return this.makeVoidRequest(`task_lists/${taskListId}/archive`, { method: 'PATCH' });
960
+ }
961
+ async restoreTaskList(taskListId) {
962
+ return this.makeVoidRequest(`task_lists/${taskListId}/restore`, { method: 'PATCH' });
963
+ }
964
+ async copyTaskList(params) {
965
+ return this.makeRequest('task_lists/copy', {
966
+ method: 'POST',
967
+ body: JSON.stringify({
968
+ data: {
969
+ type: 'task_lists',
970
+ attributes: {
971
+ name: params.name,
972
+ template_id: params.template_id,
973
+ project_id: params.project_id,
974
+ board_id: params.board_id,
975
+ copy_open_tasks: params.copy_open_tasks,
976
+ copy_assignees: params.copy_assignees,
977
+ },
978
+ },
979
+ }),
980
+ });
981
+ }
982
+ async moveTaskList(taskListId, boardId) {
983
+ return this.makeVoidRequest(`task_lists/${taskListId}/move`, {
984
+ method: 'PATCH',
985
+ body: JSON.stringify({
986
+ data: { type: 'task_lists', attributes: { board_id: boardId } },
987
+ }),
988
+ });
989
+ }
990
+ async repositionTaskList(taskListId, moveBeforeId) {
991
+ return this.makeVoidRequest(`task_lists/${taskListId}/reposition`, {
992
+ method: 'PATCH',
993
+ body: JSON.stringify({
994
+ data: { type: 'task_lists', attributes: { move_before_id: moveBeforeId } },
995
+ }),
996
+ });
997
+ }
998
+ // ---- Task extended methods ----
999
+ async deleteTask(taskId) {
1000
+ return this.makeVoidRequest(`tasks/${taskId}`, { method: 'DELETE' });
1001
+ }
1002
+ // ---- Comment extended methods ----
1003
+ async listComments(params) {
1004
+ const q = new URLSearchParams();
1005
+ q.append('include', 'creator');
1006
+ if (params?.task_id)
1007
+ q.append('filter[task_id]', params.task_id);
1008
+ if (params?.project_id)
1009
+ q.append('filter[project_id]', params.project_id);
1010
+ if (params?.discussion_id)
1011
+ q.append('filter[discussion_id]', params.discussion_id);
1012
+ if (params?.page_id)
1013
+ q.append('filter[page_id]', params.page_id);
1014
+ if (params?.limit)
1015
+ q.append('page[size]', params.limit.toString());
1016
+ if (params?.page)
1017
+ q.append('page[number]', params.page.toString());
1018
+ const qs = q.toString();
1019
+ return this.makeRequest(`comments${qs ? `?${qs}` : ''}`);
1020
+ }
1021
+ async getComment(commentId) {
1022
+ return this.makeRequest(`comments/${commentId}?include=creator`);
1023
+ }
1024
+ async updateComment(commentId, data) {
1025
+ return this.makeRequest(`comments/${commentId}`, {
1026
+ method: 'PATCH',
1027
+ body: JSON.stringify(data),
1028
+ });
1029
+ }
1030
+ async deleteComment(commentId) {
1031
+ return this.makeVoidRequest(`comments/${commentId}`, { method: 'DELETE' });
1032
+ }
1033
+ async pinComment(commentId) {
1034
+ return this.makeVoidRequest(`comments/${commentId}/pin`, { method: 'PATCH' });
1035
+ }
1036
+ async unpinComment(commentId) {
1037
+ return this.makeVoidRequest(`comments/${commentId}/unpin`, { method: 'PATCH' });
1038
+ }
1039
+ async addCommentReaction(commentId, reaction) {
1040
+ return this.makeVoidRequest(`comments/${commentId}/add_reaction`, {
1041
+ method: 'PATCH',
1042
+ body: JSON.stringify({
1043
+ data: { type: 'comments', attributes: { reaction } },
1044
+ }),
1045
+ });
1046
+ }
1047
+ // ---- Todo methods ----
1048
+ async listTodos(params) {
1049
+ const q = new URLSearchParams();
1050
+ q.append('include', 'assignee,task,deal');
1051
+ if (params?.task_id)
1052
+ q.append('filter[task_id]', params.task_id);
1053
+ if (params?.deal_id)
1054
+ q.append('filter[deal_id]', params.deal_id);
1055
+ if (params?.assignee_id)
1056
+ q.append('filter[assignee_id]', params.assignee_id);
1057
+ if (params?.status)
1058
+ q.append('filter[status]', params.status.toString());
1059
+ if (params?.limit)
1060
+ q.append('page[size]', params.limit.toString());
1061
+ if (params?.page)
1062
+ q.append('page[number]', params.page.toString());
1063
+ const qs = q.toString();
1064
+ return this.makeRequest(`todos${qs ? `?${qs}` : ''}`);
1065
+ }
1066
+ async getTodo(todoId) {
1067
+ return this.makeRequest(`todos/${todoId}?include=assignee,task,deal`);
1068
+ }
1069
+ async createTodo(data) {
1070
+ return this.makeRequest('todos', {
1071
+ method: 'POST',
1072
+ body: JSON.stringify(data),
1073
+ });
1074
+ }
1075
+ async updateTodo(todoId, data) {
1076
+ return this.makeRequest(`todos/${todoId}`, {
1077
+ method: 'PATCH',
1078
+ body: JSON.stringify(data),
1079
+ });
1080
+ }
1081
+ async deleteTodo(todoId) {
1082
+ return this.makeVoidRequest(`todos/${todoId}`, { method: 'DELETE' });
1083
+ }
1084
+ // ---- Page methods ----
1085
+ /**
1086
+ * `parent_page_id` selects the direct children of a page, `root_page_id`
1087
+ * every page in a Doc -- at any depth, since a grandchild still carries the
1088
+ * top Doc's id, not its parent's (verified live: a 3-level fixture answered
1089
+ * `filter[root_page_id]=<doc>` with both the child and the grandchild).
1090
+ * Neither filter returns the page itself: a root Doc has `root_page_id: null`.
1091
+ */
1092
+ async listPages(params) {
1093
+ const q = new URLSearchParams();
1094
+ if (params?.project_id)
1095
+ q.append('filter[project_id]', params.project_id);
1096
+ if (params?.creator_id)
1097
+ q.append('filter[creator_id]', params.creator_id);
1098
+ if (params?.parent_page_id)
1099
+ q.append('filter[parent_page_id]', params.parent_page_id);
1100
+ if (params?.root_page_id)
1101
+ q.append('filter[root_page_id]', params.root_page_id);
1102
+ if (params?.fields?.length)
1103
+ q.append('fields[pages]', params.fields.join(','));
1104
+ if (params?.sort)
1105
+ q.append('sort', params.sort);
1106
+ if (params?.limit)
1107
+ q.append('page[size]', params.limit.toString());
1108
+ if (params?.page)
1109
+ q.append('page[number]', params.page.toString());
1110
+ const qs = q.toString();
1111
+ return this.makeRequest(`pages${qs ? `?${qs}` : ''}`);
1112
+ }
1113
+ /**
1114
+ * No sparse fieldset here on purpose: `fields[pages]` is silently ignored on
1115
+ * this endpoint (measured -- all 18 attributes including the full `body` come
1116
+ * back either way, with or without `include`), even though the *collection*
1117
+ * endpoint honours it. Adding the parameter would only promise an
1118
+ * optimisation it does not deliver.
1119
+ */
1120
+ async getPage(pageId) {
1121
+ return this.makeRequest(`pages/${pageId}?include=creator,project`);
1122
+ }
1123
+ /**
1124
+ * `POST /pages` returns a 500 when given a `body` string -- pages store a
1125
+ * Productive Document Format document, so content has to go through the
1126
+ * markdown proxy route.
1127
+ */
1128
+ async createPage(data) {
1129
+ return this.makeRequest('pages/create_with_markdown', {
1130
+ method: 'POST',
1131
+ body: JSON.stringify(data),
1132
+ });
1133
+ }
1134
+ /** Replaces a page's whole body. Flat payload -- no JSON:API envelope. */
1135
+ async replacePageBody(pageId, markdown) {
1136
+ return this.makeRequest(`pages/${pageId}/replace_body_with_markdown`, { method: 'PATCH', body: JSON.stringify({ markdown }) });
1137
+ }
1138
+ /** Appends to a page's body. Flat payload -- no JSON:API envelope. */
1139
+ async appendPageBody(pageId, markdown) {
1140
+ return this.makeRequest(`pages/${pageId}/append_markdown`, { method: 'PATCH', body: JSON.stringify({ markdown }) });
1141
+ }
1142
+ async updatePage(pageId, data) {
1143
+ return this.makeRequest(`pages/${pageId}`, {
1144
+ method: 'PATCH',
1145
+ body: JSON.stringify(data),
1146
+ });
1147
+ }
1148
+ async deletePage(pageId) {
1149
+ return this.makeVoidRequest(`pages/${pageId}`, { method: 'DELETE' });
1150
+ }
1151
+ async movePage(pageId, targetDocId) {
1152
+ return this.makeVoidRequest(`pages/${pageId}/move`, {
1153
+ method: 'PATCH',
1154
+ body: JSON.stringify({
1155
+ data: { type: 'pages', attributes: { target_doc_id: targetDocId } },
1156
+ }),
1157
+ });
1158
+ }
1159
+ async copyPage(templateId, projectId) {
1160
+ const attributes = { template_id: templateId };
1161
+ if (projectId)
1162
+ attributes.project_id = projectId;
1163
+ return this.makeRequest('pages/copy', {
1164
+ method: 'POST',
1165
+ body: JSON.stringify({
1166
+ data: { type: 'pages', attributes },
1167
+ }),
1168
+ });
1169
+ }
1170
+ // ---- Task Dependency methods ----
1171
+ async listTaskDependencies(params) {
1172
+ const q = new URLSearchParams();
1173
+ q.append('include', 'task,dependent_task');
1174
+ if (params?.task_id)
1175
+ q.append('filter[task_id]', params.task_id);
1176
+ if (params?.dependent_task_id)
1177
+ q.append('filter[dependent_task_id]', params.dependent_task_id);
1178
+ if (params?.type_id)
1179
+ q.append('filter[type_id]', params.type_id.toString());
1180
+ if (params?.limit)
1181
+ q.append('page[size]', params.limit.toString());
1182
+ if (params?.page)
1183
+ q.append('page[number]', params.page.toString());
1184
+ const qs = q.toString();
1185
+ return this.makeRequest(`task_dependencies${qs ? `?${qs}` : ''}`);
1186
+ }
1187
+ async getTaskDependency(dependencyId) {
1188
+ return this.makeRequest(`task_dependencies/${dependencyId}?include=task,dependent_task`);
1189
+ }
1190
+ async createTaskDependency(data) {
1191
+ return this.makeRequest('task_dependencies', {
1192
+ method: 'POST',
1193
+ body: JSON.stringify(data),
1194
+ });
1195
+ }
1196
+ async deleteTaskDependency(dependencyId) {
1197
+ return this.makeVoidRequest(`task_dependencies/${dependencyId}`, { method: 'DELETE' });
1198
+ }
1199
+ // ---- Custom Field methods ----
1200
+ /**
1201
+ * List custom field definitions.
1202
+ *
1203
+ * NOTE: there is no documented id-based filter for this endpoint, so this
1204
+ * always fetches a page (default size 200) — callers should filter
1205
+ * client-side if they need to narrow down to specific IDs.
1206
+ */
1207
+ async listCustomFields(params) {
1208
+ const q = new URLSearchParams();
1209
+ if (params?.name)
1210
+ q.append('filter[name]', params.name);
1211
+ if (params?.projectId)
1212
+ q.append('filter[project_id]', params.projectId);
1213
+ if (params?.customizableType)
1214
+ q.append('filter[customizable_type]', params.customizableType);
1215
+ if (params?.archived !== undefined)
1216
+ q.append('filter[archived]', params.archived.toString());
1217
+ if (params?.global !== undefined)
1218
+ q.append('filter[global]', params.global.toString());
1219
+ q.append('page[size]', (params?.limit ?? 200).toString());
1220
+ return this.makeRequest(`custom_fields?${q.toString()}`);
1221
+ }
1222
+ /**
1223
+ * List the options available for a given custom field (e.g. dropdown/multi-select choices).
1224
+ *
1225
+ * NOTE: the API defaults `page[size]` to 30 (max 200) for this endpoint if
1226
+ * unset, so — like listCustomFields — this always requests a full page
1227
+ * (default size 200) to avoid silently truncating fields with >30 options.
1228
+ */
1229
+ async listCustomFieldOptions(params) {
1230
+ const q = new URLSearchParams();
1231
+ q.append('filter[custom_field_id]', params.customFieldId);
1232
+ if (params.archived !== undefined)
1233
+ q.append('filter[archived]', params.archived.toString());
1234
+ q.append('page[size]', (params.limit ?? 200).toString());
1235
+ return this.makeRequest(`custom_field_options?${q.toString()}`);
1236
+ }
1237
+ // --- Resource Management: bookings, events, availabilities ------------------
1238
+ // Bookings cover both absences (event_id) and project capacity (service_id).
1239
+ // See docs/resource-management-spec.md for the field mapping.
1240
+ /**
1241
+ * List the org's configured absence types.
1242
+ *
1243
+ * Tools must read these at runtime rather than shipping a hardcoded list of
1244
+ * categories -- names and IDs differ per organisation and change over time.
1245
+ */
1246
+ async listEvents(params) {
1247
+ const q = new URLSearchParams();
1248
+ q.append('page[size]', String(params?.limit ?? 200));
1249
+ return this.makeRequest(`events?${q.toString()}`);
1250
+ }
1251
+ /**
1252
+ * List bookings (absences and project capacity alike).
1253
+ *
1254
+ * What comes back depends on the calling token: a regular user token returns
1255
+ * only that user's own bookings, so an empty result never proves that none
1256
+ * exist org-wide.
1257
+ */
1258
+ async listBookings(params) {
1259
+ const queryString = buildBookingQuery(params);
1260
+ return this.makeRequest(`bookings${queryString ? `?${queryString}` : ''}`);
1261
+ }
1262
+ /** Fetch a single booking, including the relationships needed to classify it. */
1263
+ async getBooking(bookingId) {
1264
+ return this.makeRequest(`bookings/${bookingId}?include=person,event,service,approval_statuses`);
1265
+ }
1266
+ /**
1267
+ * Create a booking.
1268
+ *
1269
+ * The payload puts person_id/event_id/service_id in `attributes`, not in
1270
+ * `relationships` -- the JSON:API form used elsewhere in this client is
1271
+ * rejected here with 422. Whether the result needs approval depends on the
1272
+ * booked person's approval policy, so always read `approved` from the result.
1273
+ */
1274
+ async createBooking(bookingData) {
1275
+ return this.makeRequest('bookings?include=approval_statuses', {
1276
+ method: 'POST',
1277
+ body: JSON.stringify(bookingData),
1278
+ });
1279
+ }
1280
+ /** Update an existing booking (dates, amounts, note). */
1281
+ async updateBooking(bookingId, bookingData) {
1282
+ return this.makeRequest(`bookings/${bookingId}`, {
1283
+ method: 'PATCH',
1284
+ body: JSON.stringify(bookingData),
1285
+ });
1286
+ }
1287
+ /**
1288
+ * Delete a booking outright.
1289
+ *
1290
+ * Unlike an event type, a booking needs no archiving first -- the endpoint
1291
+ * answers 204 straight away.
1292
+ */
1293
+ async deleteBooking(bookingId) {
1294
+ return this.makeVoidRequest(`bookings/${bookingId}`, { method: 'DELETE' });
1295
+ }
1296
+ }