suppa-mcp-2 1.0.0

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.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Name normalization and semantic mapping for Suppa 1.0 → 2.0 migration.
3
+ *
4
+ * Faithful 1:1 port of the Python `suppa_mcp/tools/name_map.py`.
5
+ *
6
+ * Entities → PascalCase, fields → camelCase. Non-English domain names are mapped
7
+ * through a small semantic dictionary (e.g. Zakaz → Order). Cyrillic is
8
+ * transliterated to Latin as a fallback.
9
+ */
10
+ // ---------------------------------------------------------------------------
11
+ // Semantic dictionary: Suppa 1.0 domain name (lowercased) -> Suppa 2.0 English
12
+ // Extend this with project-specific terms. Matching is whole-token, case-insensitive.
13
+ // ---------------------------------------------------------------------------
14
+ export const SEMANTIC_DICT = {
15
+ zakaz: "Order",
16
+ zakazy: "Orders",
17
+ klient: "Customer",
18
+ klienty: "Customers",
19
+ tovar: "Product",
20
+ tovary: "Products",
21
+ dokument: "Document",
22
+ dokumenty: "Documents",
23
+ schet: "Invoice",
24
+ schyot: "Invoice",
25
+ postavshchik: "Supplier",
26
+ postachalnyk: "Supplier",
27
+ sklad: "Warehouse",
28
+ tsena: "Price",
29
+ tsina: "Price",
30
+ kolichestvo: "Quantity",
31
+ kilkist: "Quantity",
32
+ data: "Date",
33
+ nazva: "Name",
34
+ naimenovanie: "Name",
35
+ opys: "Description",
36
+ opisanie: "Description",
37
+ status: "Status",
38
+ summa: "Amount",
39
+ suma: "Amount",
40
+ };
41
+ // ---------------------------------------------------------------------------
42
+ // Cyrillic → Latin transliteration (Ukrainian + Russian coverage)
43
+ // ---------------------------------------------------------------------------
44
+ const _TRANSLIT = {
45
+ а: "a", б: "b", в: "v", г: "h", ґ: "g", д: "d", е: "e",
46
+ є: "ie", ж: "zh", з: "z", и: "y", і: "i", ї: "i", й: "i",
47
+ к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r",
48
+ с: "s", т: "t", у: "u", ф: "f", х: "kh", ц: "ts", ч: "ch",
49
+ ш: "sh", щ: "shch", ь: "", ю: "iu", я: "ia", ы: "y", э: "e",
50
+ ё: "e", ъ: "",
51
+ };
52
+ /** Python str.capitalize(): first char upper, rest lower. */
53
+ function capitalize(text) {
54
+ if (!text)
55
+ return text;
56
+ return text[0].toUpperCase() + text.slice(1).toLowerCase();
57
+ }
58
+ /** Transliterate Cyrillic characters to Latin; leave others untouched. */
59
+ export function transliterate(text) {
60
+ const out = [];
61
+ for (const ch of text) {
62
+ const lower = ch.toLowerCase();
63
+ if (Object.prototype.hasOwnProperty.call(_TRANSLIT, lower)) {
64
+ const mapped = _TRANSLIT[lower];
65
+ // Mirror Python: mapped.capitalize() if ch.isupper() else mapped.
66
+ out.push(ch !== lower && ch === ch.toUpperCase() ? capitalize(mapped) : mapped);
67
+ }
68
+ else {
69
+ out.push(ch);
70
+ }
71
+ }
72
+ return out.join("");
73
+ }
74
+ /** Split an identifier into word tokens (handles snake, kebab, camel, spaces). */
75
+ function _tokenize(name) {
76
+ // Transliterate first so Cyrillic becomes splittable Latin.
77
+ name = transliterate(name);
78
+ // Insert boundaries at camelCase humps.
79
+ name = name.replace(/([a-z0-9])(?=[A-Z])/g, "$1 ");
80
+ // Insert boundary between an acronym run and a following Word (NPSFeedback -> NPS Feedback).
81
+ name = name.replace(/([A-Z])(?=[A-Z][a-z])/g, "$1 ");
82
+ // Split on non-alphanumerics.
83
+ const tokens = name.split(/[^A-Za-z0-9]+/);
84
+ return tokens.filter((t) => t);
85
+ }
86
+ /** Replace whole tokens that match the semantic dictionary. */
87
+ function _applySemantics(tokens) {
88
+ const result = [];
89
+ for (const t of tokens) {
90
+ const repl = SEMANTIC_DICT[t.toLowerCase()];
91
+ result.push(repl ? repl : t);
92
+ }
93
+ return result;
94
+ }
95
+ /** Capitalize a token (acronyms like NPS become 'Nps' for clean PascalCase). */
96
+ function _pascalToken(token) {
97
+ return token.slice(0, 1).toUpperCase() + token.slice(1).toLowerCase();
98
+ }
99
+ /** Suppa 1.0 entity name → PascalCase Suppa 2.0 name. */
100
+ export function normalizeEntityName(v1Name) {
101
+ const tokens = _applySemantics(_tokenize(v1Name));
102
+ if (tokens.length === 0) {
103
+ return v1Name;
104
+ }
105
+ return tokens.map((t) => _pascalToken(t)).join("");
106
+ }
107
+ /** Suppa 1.0 field name → camelCase Suppa 2.0 name. */
108
+ export function normalizeFieldName(v1Name) {
109
+ const tokens = _applySemantics(_tokenize(v1Name));
110
+ if (tokens.length === 0) {
111
+ return v1Name;
112
+ }
113
+ const first = tokens[0];
114
+ // Keep a short acronym (e.g. NPS) as-is; otherwise lowercase the leading word.
115
+ const isUpper = first === first.toUpperCase() && first !== first.toLowerCase();
116
+ const head = isUpper && first.length <= 3 ? first : first.toLowerCase();
117
+ const rest = tokens
118
+ .slice(1)
119
+ .map((t) => _pascalToken(t))
120
+ .join("");
121
+ return head + rest;
122
+ }
123
+ /** Produce a reviewable name-mapping fragment for one entity. */
124
+ export function buildNameMap(v1Entity, v1Fields = null) {
125
+ const fields = {};
126
+ for (const f of v1Fields ?? []) {
127
+ fields[f] = normalizeFieldName(f);
128
+ }
129
+ return {
130
+ v1_name: v1Entity,
131
+ v2_name: normalizeEntityName(v1Entity),
132
+ fields,
133
+ };
134
+ }
@@ -0,0 +1,423 @@
1
+ /**
2
+ * Tasks, Comments, Workflows, Stages, Users tools.
3
+ *
4
+ * Faithful 1:1 port of the Python `suppa_mcp/tools/tasks.py`.
5
+ *
6
+ * The mutating tools (updateTask, deleteTask, moveTask, closeTask) perform their
7
+ * writes UNCONDITIONALLY, exactly like the Python source. Approval-gating for
8
+ * mutations lives one layer up (server.ts, mirroring server.py) — NOT here.
9
+ */
10
+ import { searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
11
+ import { makeFilter, parseDeadline, wrapHtml, jsonResponse } from "../utils.js";
12
+ import * as tenants from "../tenants.js";
13
+ // ---------------------------------------------------------------------------
14
+ // Field projections
15
+ // ---------------------------------------------------------------------------
16
+ export const TASK_LIST_FIELDS = {
17
+ id: true,
18
+ title: true,
19
+ shortID: true,
20
+ deadline: true,
21
+ createdAt: true,
22
+ updatedAt: true,
23
+ estimatedDuration: true,
24
+ assignedTo: { id: true, firstName: true, lastName: true, fullName: true },
25
+ author: { id: true, fullName: true },
26
+ project: { id: true, title: true },
27
+ parent: { id: true, title: true },
28
+ stage: {
29
+ id: true,
30
+ name: true,
31
+ color: true,
32
+ workflow: { id: true, name: true },
33
+ status: { value: true },
34
+ },
35
+ workflow: { id: true, name: true },
36
+ priority: { id: true, title: true, name: true, value: true },
37
+ type: { id: true, title: true, color: true },
38
+ tags: { id: true, name: true },
39
+ };
40
+ export const TASK_DETAIL_FIELDS = {
41
+ ...TASK_LIST_FIELDS,
42
+ htmlDescription: true,
43
+ plainDescription: true,
44
+ closedAt: true,
45
+ closedBy: { id: true, fullName: true },
46
+ editors: { id: true, fullName: true },
47
+ watchers: { id: true, fullName: true },
48
+ children: { id: true, title: true },
49
+ attachments: { id: true, fileName: true, filePath: true },
50
+ };
51
+ const _ACTIVE_STATES = ["active", "inprogress"];
52
+ /** Build the Tasks filter list shared by searchTasks and countTasks. */
53
+ function _taskFilters(my = false, active = false, overdue = false, dueToday = false, projectId = null, workflowId = null, stageId = null, assignedToId = null) {
54
+ const filters = [];
55
+ if (my) {
56
+ filters.push(makeFilter("assignedTo", "$current-user"));
57
+ }
58
+ if (active) {
59
+ filters.push(makeFilter("stage.status.value", _ACTIVE_STATES, "in"));
60
+ }
61
+ if (overdue) {
62
+ filters.push(makeFilter("deadline", isoNowUtc(), "<"));
63
+ filters.push(makeFilter("stage.status.value", _ACTIVE_STATES, "in"));
64
+ }
65
+ if (dueToday) {
66
+ filters.push(makeFilter("deadline", isoStartOfDayUtc(), ">="));
67
+ filters.push(makeFilter("deadline", isoEndOfDayUtc(), "<="));
68
+ }
69
+ if (projectId) {
70
+ filters.push(makeFilter("project", { id: projectId }));
71
+ }
72
+ if (workflowId) {
73
+ filters.push(makeFilter("workflow", { id: workflowId }));
74
+ }
75
+ if (stageId) {
76
+ filters.push(makeFilter("stage", { id: stageId }));
77
+ }
78
+ if (assignedToId) {
79
+ filters.push(makeFilter("assignedTo", { id: assignedToId }));
80
+ }
81
+ return filters;
82
+ }
83
+ // Datetime helpers mirroring the Python datetime.now(timezone.utc)... .isoformat()
84
+ // output shape: "YYYY-MM-DDTHH:MM:SS+00:00" (microseconds zeroed).
85
+ function pad2(n) {
86
+ return n < 10 ? "0" + n : String(n);
87
+ }
88
+ function isoNowUtc() {
89
+ const d = new Date();
90
+ return (`${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}` +
91
+ `T${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())}:${pad2(d.getUTCSeconds())}+00:00`);
92
+ }
93
+ function isoStartOfDayUtc() {
94
+ const d = new Date();
95
+ return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}T00:00:00+00:00`;
96
+ }
97
+ function isoEndOfDayUtc() {
98
+ const d = new Date();
99
+ return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}T23:59:59+00:00`;
100
+ }
101
+ // ---------------------------------------------------------------------------
102
+ // Tools
103
+ // ---------------------------------------------------------------------------
104
+ /** Get the current authenticated user's profile. */
105
+ export async function getMe() {
106
+ const result = await selectEntity("Users", [makeFilter("id", "$current-user")], {
107
+ id: true,
108
+ firstName: true,
109
+ lastName: true,
110
+ fullName: true,
111
+ position: true,
112
+ avatar: { id: true, fileName: true },
113
+ createdAt: true,
114
+ roles: { id: true, name: true },
115
+ });
116
+ return jsonResponse(result);
117
+ }
118
+ /**
119
+ * Search tasks with filters. Use 'my' for current user's tasks, 'active' for open tasks.
120
+ *
121
+ * Returns {"tasks": [...], "returned": N, "has_more": bool, "next_offset": int|null}.
122
+ */
123
+ export async function searchTasks(search = "", my = false, active = false, overdue = false, dueToday = false, projectId = null, workflowId = null, stageId = null, assignedToId = null, limit = 20, offset = 0) {
124
+ const filters = _taskFilters(my, active, overdue, dueToday, projectId, workflowId, stageId, assignedToId);
125
+ limit = Math.max(1, Math.min(limit, 500)); // cap a page; deeper results come via offset paging
126
+ // Fetch one extra row so the agent learns whether another page exists.
127
+ const rows = await searchEntity("Tasks", filters, TASK_LIST_FIELDS, limit + 1, offset, null, search);
128
+ const hasMore = rows.length > limit;
129
+ return jsonResponse({
130
+ tasks: rows.slice(0, limit),
131
+ returned: Math.min(rows.length, limit),
132
+ has_more: hasMore,
133
+ next_offset: hasMore ? offset + limit : null,
134
+ });
135
+ }
136
+ /** Count tasks matching filters without returning full data. */
137
+ export async function countTasks(my = false, active = false, projectId = null, workflowId = null, search = "", overdue = false, dueToday = false) {
138
+ const filters = _taskFilters(my, active, overdue, dueToday, projectId, workflowId);
139
+ // The platform has no count endpoint and ignores an `aggregates` request
140
+ // (the search endpoint always returns a bare list of rows, and rejects
141
+ // limit=0 with "limit must be a positive number"). So count by paging the
142
+ // ids until a short page, capping the work for very large result sets.
143
+ const PAGE = 200;
144
+ const MAX_PAGES = 50; // safety cap: up to 10 000 rows
145
+ let total = 0;
146
+ for (let page = 0; page < MAX_PAGES; page++) {
147
+ const rows = await searchEntity("Tasks", filters, { id: true }, PAGE, page * PAGE, null, search);
148
+ total += rows.length;
149
+ if (rows.length < PAGE) {
150
+ return jsonResponse({ count: total });
151
+ }
152
+ }
153
+ return jsonResponse({
154
+ count: total,
155
+ capped: true,
156
+ note: `stopped after ${MAX_PAGES * PAGE} rows — there may be more`,
157
+ });
158
+ }
159
+ /** Get full details of a single task by ID. */
160
+ export async function getTask(taskId) {
161
+ const result = await selectEntity("Tasks", [makeFilter("id", taskId)], TASK_DETAIL_FIELDS);
162
+ return jsonResponse(result);
163
+ }
164
+ /** Create a new task. Description supports HTML. Deadline accepts 'today', 'tomorrow', '+3d', or ISO datetime. */
165
+ export async function createTask(title, description = "", assignedToId = null, projectId = null, workflowId = null, stageId = null, typeId = null, priorityId = null, deadline = null, parentId = null) {
166
+ if (!title || !title.trim()) {
167
+ return jsonResponse({ error: "Task title must not be empty." });
168
+ }
169
+ const fields = { title: title.trim() };
170
+ if (description) {
171
+ fields.htmlDescription = wrapHtml(description);
172
+ }
173
+ if (assignedToId) {
174
+ fields.assignedTo = { id: assignedToId };
175
+ }
176
+ if (projectId) {
177
+ fields.project = { id: projectId };
178
+ }
179
+ if (workflowId) {
180
+ fields.workflow = { id: workflowId };
181
+ }
182
+ if (stageId) {
183
+ fields.stage = { id: stageId };
184
+ }
185
+ if (typeId) {
186
+ fields.type = { id: typeId };
187
+ }
188
+ if (priorityId) {
189
+ fields.priority = { id: priorityId };
190
+ }
191
+ if (deadline) {
192
+ try {
193
+ fields.deadline = parseDeadline(deadline);
194
+ }
195
+ catch (e) {
196
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
197
+ }
198
+ }
199
+ if (parentId) {
200
+ fields.parent = { id: parentId };
201
+ }
202
+ const result = await insertEntity("Tasks", [fields]);
203
+ return jsonResponse(result.length ? result[0] : null);
204
+ }
205
+ /** Update fields on an existing task. */
206
+ export async function updateTask(taskId, title = null, description = null, assignedToId = null, projectId = null, workflowId = null, stageId = null, typeId = null, priorityId = null, deadline = null) {
207
+ const fields = {};
208
+ if (title !== null) {
209
+ fields.title = title;
210
+ }
211
+ if (description !== null) {
212
+ fields.htmlDescription = wrapHtml(description);
213
+ }
214
+ if (assignedToId !== null) {
215
+ fields.assignedTo = { id: assignedToId };
216
+ }
217
+ if (projectId !== null) {
218
+ fields.project = { id: projectId };
219
+ }
220
+ if (workflowId !== null) {
221
+ fields.workflow = { id: workflowId };
222
+ }
223
+ if (stageId !== null) {
224
+ fields.stage = { id: stageId };
225
+ }
226
+ if (typeId !== null) {
227
+ fields.type = { id: typeId };
228
+ }
229
+ if (priorityId !== null) {
230
+ fields.priority = { id: priorityId };
231
+ }
232
+ if (deadline !== null) {
233
+ try {
234
+ fields.deadline = parseDeadline(deadline);
235
+ }
236
+ catch (e) {
237
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
238
+ }
239
+ }
240
+ if (Object.keys(fields).length === 0) {
241
+ return jsonResponse({ error: "No fields to update" });
242
+ }
243
+ const result = await updateEntity("Tasks", taskId, fields);
244
+ return jsonResponse(result);
245
+ }
246
+ /** Soft-delete a task by ID. */
247
+ export async function deleteTask(taskId) {
248
+ const result = await removeEntity("Tasks", [makeFilter("id", taskId)]);
249
+ return jsonResponse(result);
250
+ }
251
+ /** Move a task to a different stage. */
252
+ export async function moveTask(taskId, stageId) {
253
+ const result = await updateEntity("Tasks", taskId, { stage: { id: stageId } });
254
+ return jsonResponse(result);
255
+ }
256
+ /** Close a task by moving it to the workflow's completed stage. */
257
+ export async function closeTask(taskId) {
258
+ // Get task's workflow
259
+ const task = await selectEntity("Tasks", [makeFilter("id", taskId)], {
260
+ id: true,
261
+ workflow: { id: true, name: true },
262
+ stage: { id: true, name: true, status: { id: true, value: true } },
263
+ });
264
+ if (!task || !task.workflow) {
265
+ return jsonResponse({ error: "Task has no workflow — cannot close" });
266
+ }
267
+ const wfId = task.workflow.id;
268
+ // Find the completed stage
269
+ const stages = await searchEntity("StageWorkflows", [makeFilter("workflow", { id: wfId }), makeFilter("status.value", "completed")], { id: true, name: true, status: { id: true, value: true } }, 5);
270
+ if (!stages.length) {
271
+ return jsonResponse({ error: `No completed stage found in workflow ${wfId}` });
272
+ }
273
+ const closedStageId = stages[0].id;
274
+ const result = await updateEntity("Tasks", taskId, { stage: { id: closedStageId } });
275
+ return jsonResponse(result);
276
+ }
277
+ // Resolved current-user ids, keyed by (host, access token). The token key means
278
+ // a re-login as a different account naturally misses the cache; bounded so
279
+ // rotating tokens can't grow it without limit.
280
+ const _userIdCache = new Map();
281
+ /** Resolve (and cache) the numeric id of the authenticated user. */
282
+ async function _resolveCurrentUserId() {
283
+ const ctx = tenants.current();
284
+ const key = `${ctx.host}${ctx.getToken()}`;
285
+ const cached = _userIdCache.get(key);
286
+ if (cached !== undefined) {
287
+ return cached;
288
+ }
289
+ const me = await selectEntity("Users", [makeFilter("id", "$current-user")], {
290
+ id: true,
291
+ fullName: true,
292
+ });
293
+ if (me && typeof me === "object" && me.id != null) {
294
+ const uid = Number(me.id);
295
+ if (_userIdCache.size > 32) {
296
+ _userIdCache.clear();
297
+ }
298
+ _userIdCache.set(key, uid);
299
+ return uid;
300
+ }
301
+ throw new Error("Could not resolve current user id");
302
+ }
303
+ /** Add a comment to a task. Content supports HTML. mention_ids: comma-separated 'id:Name' pairs. */
304
+ export async function addComment(taskId, content, mentionIds = null) {
305
+ let html = content;
306
+ // Process mentions (prepended, matching platform format)
307
+ if (mentionIds) {
308
+ for (let part of mentionIds.split(",")) {
309
+ part = part.trim();
310
+ if (part.includes(":")) {
311
+ const idx = part.indexOf(":");
312
+ const uid = part.slice(0, idx).trim();
313
+ const name = part.slice(idx + 1).trim();
314
+ const mentionTag = `<a class="mention-user" id="mention-${uid}" ` +
315
+ `data-id="${uid}">@${name}</a>&nbsp;`;
316
+ html = mentionTag + html;
317
+ }
318
+ }
319
+ }
320
+ if (!html.replace(/^\s+/, "").startsWith("<")) {
321
+ html = wrapHtml(html);
322
+ }
323
+ const fields = {
324
+ owner: { id: taskId },
325
+ user: { id: await _resolveCurrentUserId() },
326
+ content: html,
327
+ };
328
+ const result = await insertEntity("TasksComments", [fields]);
329
+ return jsonResponse(result.length ? result[0] : null);
330
+ }
331
+ /**
332
+ * Get the latest N comments for a task, oldest-first.
333
+ *
334
+ * Fetches newest-first then reverses: on a long thread the *latest* comments
335
+ * are what matters — ascending fetch would return only the oldest N.
336
+ */
337
+ export async function getComments(taskId, limit = 30) {
338
+ const results = await searchEntity("TasksComments", [makeFilter("owner.id", taskId)], {
339
+ id: true,
340
+ content: true,
341
+ createdAt: true,
342
+ updatedAt: true,
343
+ user: { id: true, fullName: true },
344
+ }, limit, 0, [{ field: "createdAt", order: "desc" }]);
345
+ return jsonResponse([...results].reverse());
346
+ }
347
+ /** Upload a file and attach it to a task. Provide the absolute file path. */
348
+ export async function attachFile(taskId, filePath) {
349
+ // Lazy import mirrors the Python in-function `from suppa_mcp.tools import entity`
350
+ // and avoids a hard build-time dependency (entity.ts is a sibling module).
351
+ const entity = (await import("./entity.js"));
352
+ return entity.attachFileToRecord("Tasks", taskId, filePath, "attachments");
353
+ }
354
+ /**
355
+ * List workflows with their stages, grouped per workflow.
356
+ *
357
+ * The name filter matches the *workflow* name (filtering the bare "name"
358
+ * field here would match stage names — a different thing entirely).
359
+ */
360
+ export async function listWorkflows(name = null) {
361
+ const filters = [];
362
+ if (name) {
363
+ filters.push(makeFilter("workflow.name", `%${name}%`, "like"));
364
+ }
365
+ const rows = await searchEntity("StageWorkflows", filters, {
366
+ id: true,
367
+ name: true,
368
+ workflow: { id: true, name: true },
369
+ status: { id: true, value: true },
370
+ order: true,
371
+ }, 500, 0, [{ field: "order", order: "asc" }]);
372
+ // Group the stage rows into one entry per workflow (stages keep their order).
373
+ const grouped = new Map();
374
+ for (const r of rows) {
375
+ if (!r || typeof r !== "object" || Array.isArray(r)) {
376
+ continue;
377
+ }
378
+ const row = r;
379
+ const wf = row.workflow || {};
380
+ const wfId = wf.id;
381
+ if (wfId === undefined || wfId === null) {
382
+ continue;
383
+ }
384
+ let entryVal = grouped.get(wfId);
385
+ if (entryVal === undefined) {
386
+ entryVal = { id: wfId, name: wf.name, stages: [] };
387
+ grouped.set(wfId, entryVal);
388
+ }
389
+ entryVal.stages.push({
390
+ id: row.id,
391
+ name: row.name,
392
+ status: row.status,
393
+ order: row.order,
394
+ });
395
+ }
396
+ return jsonResponse({ workflows: Array.from(grouped.values()) });
397
+ }
398
+ /** List all stages in a workflow. */
399
+ export async function listStages(workflowId) {
400
+ const results = await searchEntity("StageWorkflows", [makeFilter("workflow", { id: workflowId })], { id: true, name: true, status: { id: true, value: true }, order: true }, 100, 0, [{ field: "order", order: "asc" }]);
401
+ return jsonResponse(results);
402
+ }
403
+ /** List all available task types. */
404
+ export async function listTaskTypes() {
405
+ const results = await searchEntity("TasksTypes", [], { id: true, title: true }, 100);
406
+ return jsonResponse(results);
407
+ }
408
+ /** Search users by name. */
409
+ export async function searchUsers(name = "", limit = 20) {
410
+ const filters = [];
411
+ if (name) {
412
+ filters.push(makeFilter("fullName", `%${name}%`, "like"));
413
+ }
414
+ const results = await searchEntity("Users", filters, {
415
+ id: true,
416
+ fullName: true,
417
+ firstName: true,
418
+ lastName: true,
419
+ position: true,
420
+ avatar: { id: true, fileName: true },
421
+ }, limit);
422
+ return jsonResponse(results);
423
+ }
Binary file
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Workspace and navigation-menu tools (Suppa 2.0).
3
+ *
4
+ * Faithful 1:1 port of the Python `suppa_mcp/tools/workspace.py`.
5
+ *
6
+ * Creates `Workspace` records and `NavigationMenu` items via the instance API.
7
+ * Field shapes were verified live on a 2.0 tenant:
8
+ *
9
+ * Workspace: name(text), alias(text), defaultRout(text),
10
+ * sidebarForm(->Forms), filterForm(->Forms)
11
+ * NavigationMenu: name(multi-language), href(text), icon(text), order(numeric),
12
+ * type(text), isActive(bool), isDefault(bool), form(->Forms),
13
+ * parent(->NavigationMenu, self-referential), accessRoles(->Roles)
14
+ *
15
+ * Relations are written as `{"id": N}`. The sidebar "menuPanel" form is built
16
+ * separately (suppa_create_form) and bound here by id — there is no generic
17
+ * menuPanel auto-builder, since its schema is platform/tenant-specific.
18
+ */
19
+ import { insertEntity } from "../httpClient.js";
20
+ import { jsonResponse } from "../utils.js";
21
+ /** snake_case slug for a workspace alias / route segment. */
22
+ function slug(text) {
23
+ const s = (text || "")
24
+ .trim()
25
+ .toLowerCase()
26
+ .replace(/[^a-z0-9]+/g, "_")
27
+ .replace(/^_+|_+$/g, "");
28
+ return s || "workspace";
29
+ }
30
+ /**
31
+ * Create a NavigationMenu item (a sidebar/menu entry).
32
+ *
33
+ * Provide `href` (a route, e.g. '/workspace/sales') OR `entity` (links to
34
+ * that entity's list; href defaults to '/entity/<Entity>'). `parentId` nests
35
+ * it under another menu item, `formId` binds a Form, `order` sorts it.
36
+ * NavigationMenu.name is multi-language, so the name is stored as {"en": ...}.
37
+ */
38
+ export async function addMenuItem(name, href, entity, icon, order, parentId, menuType, formId, isActive = true) {
39
+ if (!href && entity) {
40
+ href = `/entity/${entity}`;
41
+ }
42
+ const record = { name: { en: name }, isActive };
43
+ if (href) {
44
+ record.href = href;
45
+ }
46
+ if (icon) {
47
+ record.icon = icon;
48
+ }
49
+ if (order !== undefined && order !== null) {
50
+ record.order = order;
51
+ }
52
+ if (menuType) {
53
+ record.type = menuType;
54
+ }
55
+ if (parentId !== undefined && parentId !== null) {
56
+ record.parent = { id: parentId };
57
+ }
58
+ if (formId !== undefined && formId !== null) {
59
+ record.form = { id: formId };
60
+ }
61
+ const result = await insertEntity("NavigationMenu", [record], {
62
+ id: true,
63
+ href: true,
64
+ });
65
+ return jsonResponse({
66
+ created: "NavigationMenu",
67
+ item: Array.isArray(result) && result.length ? result[0] : result,
68
+ sent: record,
69
+ });
70
+ }
71
+ /**
72
+ * Create a Workspace and (by default) a NavigationMenu item linking to it.
73
+ *
74
+ * `alias` defaults to a snake_case slug of `name`; `defaultRoute`
75
+ * defaults to '/workspace/<alias>'. `sidebarFormId` / `filterFormId`
76
+ * bind existing Forms (build the sidebar menuPanel form with suppa_create_form
77
+ * first, then pass its id). When `addNavItem` is true a NavigationMenu
78
+ * entry pointing at the workspace route is created (optionally under
79
+ * `parentMenuId`).
80
+ */
81
+ export async function createWorkspace(name, alias, defaultRoute, sidebarFormId, filterFormId, addNavItem = true, parentMenuId, order) {
82
+ alias = alias || slug(name);
83
+ const route = defaultRoute || `/workspace/${alias}`;
84
+ const ws = {
85
+ name,
86
+ alias,
87
+ defaultRout: route,
88
+ };
89
+ if (sidebarFormId !== undefined && sidebarFormId !== null) {
90
+ ws.sidebarForm = { id: sidebarFormId };
91
+ }
92
+ if (filterFormId !== undefined && filterFormId !== null) {
93
+ ws.filterForm = { id: filterFormId };
94
+ }
95
+ const wsResult = await insertEntity("Workspace", [ws], {
96
+ id: true,
97
+ alias: true,
98
+ name: true,
99
+ });
100
+ const workspace = Array.isArray(wsResult) && wsResult.length ? wsResult[0] : wsResult;
101
+ let nav = null;
102
+ if (addNavItem) {
103
+ const navRecord = {
104
+ name: { en: name },
105
+ href: route,
106
+ isActive: true,
107
+ };
108
+ if (order !== undefined && order !== null) {
109
+ navRecord.order = order;
110
+ }
111
+ if (parentMenuId !== undefined && parentMenuId !== null) {
112
+ navRecord.parent = { id: parentMenuId };
113
+ }
114
+ const navRes = await insertEntity("NavigationMenu", [navRecord], {
115
+ id: true,
116
+ href: true,
117
+ });
118
+ nav = Array.isArray(navRes) && navRes.length ? navRes[0] : navRes;
119
+ }
120
+ return jsonResponse({ workspace, nav_item: nav });
121
+ }