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,550 @@
1
+ /**
2
+ * Forms management tools — faithful 1:1 port of the Python
3
+ * `suppa_mcp/tools/forms.py` (the verified suppa-forms skill).
4
+ *
5
+ * The Suppa `Forms` entity stores the layout in a JSON `data` field with the
6
+ * keys `formShema` (list of field objects), `formSettings` (dict) and
7
+ * `formModul` (optional JS module string). The original platform spelling of
8
+ * `formShema` / `formModul` is intentional and must be preserved.
9
+ */
10
+ import { randomUUID } from "node:crypto";
11
+ import { makeRequest, searchEntity, selectEntity, insertEntity } from "../httpClient.js";
12
+ import { makeFilter, jsonResponse, parseJsonParam } from "../utils.js";
13
+ // ---------------------------------------------------------------------------
14
+ // Constants
15
+ // ---------------------------------------------------------------------------
16
+ export const ENTITY_FORMS = "Forms";
17
+ export const FORM_LIST_FIELDS = {
18
+ id: true,
19
+ name: true,
20
+ type: true,
21
+ alias: true,
22
+ isPublic: true,
23
+ entity: { id: true, name: true },
24
+ lockedBy: { id: true, firstName: true, lastName: true },
25
+ createdAt: true,
26
+ updatedAt: true,
27
+ };
28
+ export const FORM_DETAIL_FIELDS = { ...FORM_LIST_FIELDS, data: true };
29
+ export const DEFAULT_FORM_SETTINGS = {
30
+ id: 0,
31
+ size: "md",
32
+ type: "form",
33
+ method: "POST",
34
+ formKey: "",
35
+ endpoint: "",
36
+ entityId: "",
37
+ formType: "elementForm",
38
+ multilingual: false,
39
+ useTransaction: true,
40
+ showSubmitButton: false,
41
+ validateOnChange: true,
42
+ validateOnSubmit: true,
43
+ };
44
+ // Entity backend type -> [form field type, extra props]
45
+ export const ENTITY_TYPE_MAP = {
46
+ Integer: ["text", { inputType: "number", rules: ["numeric"] }],
47
+ Number: ["text", { inputType: "number", rules: ["numeric"] }],
48
+ Float: ["text", { inputType: "number", rules: ["numeric"] }],
49
+ Decimal: ["text", { inputType: "number", rules: ["numeric"] }],
50
+ String: ["text", { inputType: "text" }],
51
+ Text: ["text", { inputType: "text" }],
52
+ UUID: ["text", { inputType: "text" }],
53
+ Boolean: ["toogle", {}],
54
+ DateTime: ["date", { typeDate: "dateTime" }],
55
+ Timestamp: ["date", { typeDate: "dateTime" }],
56
+ Date: ["date", { typeDate: "date" }],
57
+ Time: ["date", { typeDate: "time" }],
58
+ JSON: ["json", {}],
59
+ File: ["files", {}],
60
+ Files: ["files", {}],
61
+ attachment: ["files", {}],
62
+ icon: ["icon", {}],
63
+ };
64
+ // Form field types exposed by the platform.
65
+ export const FORM_FIELD_TYPES = [
66
+ "text", "textarea", "richtext", "date", "checkbox", "radio", "select",
67
+ "userSelect", "toogle", "files", "signature", "static", "button",
68
+ "group", "flexGroup", "tabs", "steps", "widget", "icon", "json",
69
+ ];
70
+ // ---------------------------------------------------------------------------
71
+ // Schema field generation
72
+ // ---------------------------------------------------------------------------
73
+ function newId() {
74
+ return randomUUID();
75
+ }
76
+ /** Generate a single form field schema object with required properties. */
77
+ export function makeField(fieldType, name, label, _columns = 1, _rows = 1, kwargs = {}) {
78
+ // Python signature: make_field(field_type, name, label, columns=1, rows=1, **kwargs).
79
+ // Only `columns`/`rows` positionals reach the schema below; every other keyword
80
+ // (including field_id/position) is threaded through `kwargs`.
81
+ const extra = { ...kwargs };
82
+ const posRaw = extra.position;
83
+ delete extra.position;
84
+ const pos = posRaw != null ? posRaw : { x: 1, y: 1 };
85
+ const fieldIdRaw = extra.field_id;
86
+ delete extra.field_id;
87
+ const fieldId = fieldIdRaw !== undefined ? fieldIdRaw : name;
88
+ const field = {
89
+ id: newId(),
90
+ fieldId,
91
+ name,
92
+ type: fieldType,
93
+ label: typeof label === "string" ? { en: label } : label,
94
+ position: { lg: pos, sm: pos, default: pos },
95
+ columns: { lg: { container: _columns } },
96
+ rows: { lg: { container: _rows } },
97
+ };
98
+ Object.assign(field, extra);
99
+ return field;
100
+ }
101
+ /** Apply grid auto-layout, positioning fields sequentially. */
102
+ export function autoLayout(fields, columnsNumber = 1) {
103
+ let currentRow = 1;
104
+ let currentCol = 1;
105
+ for (const field of fields) {
106
+ let fieldCols = 1;
107
+ const cols = field.columns;
108
+ if (cols && "lg" in cols && cols.lg) {
109
+ fieldCols = cols.lg.container ?? 1;
110
+ }
111
+ if (currentCol + fieldCols - 1 > columnsNumber) {
112
+ currentRow += 1;
113
+ currentCol = 1;
114
+ }
115
+ const pos = { x: currentCol, y: currentRow };
116
+ field.position = { lg: pos, sm: pos, default: pos };
117
+ currentCol += fieldCols;
118
+ if (currentCol > columnsNumber) {
119
+ currentRow += 1;
120
+ currentCol = 1;
121
+ }
122
+ }
123
+ return fields;
124
+ }
125
+ /** Convert a backend entity property to a form schema field. */
126
+ export function convertEntityProp(prop, entityName) {
127
+ const propType = prop.type ?? "text";
128
+ const propName = prop.name ?? "field";
129
+ const propTitle = prop.title ?? {};
130
+ const subType = prop.subType || prop.sub_type || "";
131
+ const relationTarget = prop.relationTarget ?? "";
132
+ const representative = prop.representativeField ?? {};
133
+ const repFieldName = representative && typeof representative === "object" && !Array.isArray(representative)
134
+ ? representative.name ?? "title"
135
+ : String(representative || "title");
136
+ const isRelation = ["many-to-one", "one-to-many", "many-to-many", "relation"].includes(propType);
137
+ const isMany = ["many-to-many", "one-to-many"].includes(propType);
138
+ const propTypeLower = propType.toLowerCase();
139
+ let formType;
140
+ if (isRelation) {
141
+ formType = relationTarget === "Users" ? "userSelect" : "select";
142
+ }
143
+ else if (["enum", "custom_enum", "Enum"].includes(propType)) {
144
+ formType = "select";
145
+ }
146
+ else if (propType === "text") {
147
+ if (subType === "html_text" || propName.toLowerCase().includes("html")) {
148
+ formType = "richtext";
149
+ }
150
+ else if (subType === "icon") {
151
+ formType = "icon";
152
+ }
153
+ else if (subType === "ucid_prefix") {
154
+ formType = "ucidPrefix";
155
+ }
156
+ else {
157
+ formType = "text";
158
+ }
159
+ }
160
+ else if (["timestamp", "Timestamp", "DateTime", "date", "Date", "time", "Time"].includes(propType)) {
161
+ formType = "date";
162
+ }
163
+ else if (propType in ENTITY_TYPE_MAP) {
164
+ formType = ENTITY_TYPE_MAP[propType][0];
165
+ }
166
+ else if (["integer", "number", "float", "decimal"].includes(propTypeLower)) {
167
+ formType = "text";
168
+ }
169
+ else if (propTypeLower === "boolean") {
170
+ formType = "toogle";
171
+ }
172
+ else if (["json"].includes(propTypeLower)) {
173
+ formType = "json";
174
+ }
175
+ else if (["file", "files", "attachment"].includes(propTypeLower)) {
176
+ formType = "files";
177
+ }
178
+ else {
179
+ formType = "text";
180
+ }
181
+ let label;
182
+ if (propTitle && typeof propTitle === "object" && !Array.isArray(propTitle) && Object.keys(propTitle).length) {
183
+ label = propTitle;
184
+ }
185
+ else if (typeof propTitle === "string" && propTitle) {
186
+ label = { en: propTitle };
187
+ }
188
+ else {
189
+ label = { en: propName };
190
+ }
191
+ const field = makeField(formType, propName, label, 1, 1, { field_id: propName });
192
+ if (formType === "text" && propType in ENTITY_TYPE_MAP) {
193
+ Object.assign(field, ENTITY_TYPE_MAP[propType][1]);
194
+ }
195
+ else if (formType === "text" && ["integer", "number", "float", "decimal"].includes(propTypeLower)) {
196
+ field.inputType = "number";
197
+ field.rules = (field.rules ?? []).concat(["numeric"]);
198
+ }
199
+ else if (formType === "date") {
200
+ if (["timestamp", "Timestamp", "DateTime"].includes(propType) ||
201
+ ["timestamp", "DateTime"].includes(subType)) {
202
+ field.typeDate = "dateTime";
203
+ }
204
+ else if (["time", "Time"].includes(propType) || ["time", "Time"].includes(subType)) {
205
+ field.typeDate = "time";
206
+ }
207
+ else {
208
+ field.typeDate = "date";
209
+ }
210
+ }
211
+ else if (formType === "userSelect") {
212
+ field.items = {
213
+ targetEntityName: relationTarget || "Users",
214
+ targetValueField: "id",
215
+ targetLabelField: repFieldName || "fullName",
216
+ };
217
+ field.options = { multiple: isMany };
218
+ field.additionalRequestFields = ["firstName", "lastName", "fullName", "avatar", "position"];
219
+ }
220
+ else if (formType === "select" && isRelation) {
221
+ field.items = {
222
+ targetEntityName: relationTarget,
223
+ targetValueField: "id",
224
+ targetLabelField: repFieldName || "title",
225
+ };
226
+ field.options = { valueIsObject: true, usePreLoadItemsFunction: true, multiple: isMany };
227
+ }
228
+ else if (formType === "select" && ["enum", "custom_enum", "Enum"].includes(propType)) {
229
+ const customEnum = prop.custom_enum ?? {};
230
+ field.items = {
231
+ enum_id: customEnum.enum_id ?? `${entityName}.${propName}`,
232
+ targetType: "internal",
233
+ targetEntityName: "Enums",
234
+ targetValueField: "id",
235
+ targetLabelField: "title",
236
+ };
237
+ field.options = { valueIsObject: true, multiple: prop.isArray ?? false };
238
+ }
239
+ else if (formType === "files") {
240
+ field.options = { multiple: prop.isArray !== undefined ? prop.isArray : true };
241
+ }
242
+ const rules = field.rules ?? [];
243
+ if (prop.required === "always" || prop.notNull) {
244
+ if (!rules.includes("required")) {
245
+ rules.push("required");
246
+ }
247
+ }
248
+ if (subType === "email") {
249
+ rules.push("email");
250
+ }
251
+ const maxLength = prop.maxLength ?? prop.max_length;
252
+ if (maxLength) {
253
+ rules.push(`maxLength:${maxLength}`);
254
+ }
255
+ const precision = prop.decimalPlaces ?? prop.precision;
256
+ if (precision) {
257
+ rules.push(`decimalPlaces:${precision}`);
258
+ }
259
+ if (prop.isOnlyPositive || prop.only_positive) {
260
+ rules.push("isOnlyPositive");
261
+ }
262
+ if (rules.length) {
263
+ field.rules = rules;
264
+ }
265
+ return field;
266
+ }
267
+ async function getEntitySchema(entityName) {
268
+ return makeRequest("GET", `/api/core/schema/${entityName}`);
269
+ }
270
+ /** Fetch an entity schema and build [schema_list, settings_dict]. */
271
+ async function generateSchemaFromEntity(entityName, fieldNames = null, columnsNumber = 1) {
272
+ const schemaData = await getEntitySchema(entityName);
273
+ if (!schemaData) {
274
+ return [null, null];
275
+ }
276
+ let props = [];
277
+ if (schemaData && typeof schemaData === "object" && !Array.isArray(schemaData)) {
278
+ const sd = schemaData;
279
+ const raw = sd.properties ?? sd.fields ?? [];
280
+ if (Array.isArray(raw)) {
281
+ props = raw;
282
+ }
283
+ else if (raw && typeof raw === "object") {
284
+ // A dict of props keyed by name — matches the `isinstance(props, dict)` branch.
285
+ props = Object.entries(raw).map(([k, v]) => {
286
+ const vv = (v ?? {});
287
+ return { ...vv, name: vv.name ?? k };
288
+ });
289
+ }
290
+ }
291
+ else if (Array.isArray(schemaData)) {
292
+ props = schemaData;
293
+ }
294
+ if (fieldNames) {
295
+ const propMap = {};
296
+ for (const p of props) {
297
+ propMap[p.name] = p;
298
+ }
299
+ props = fieldNames.filter((n) => n in propMap).map((n) => propMap[n]);
300
+ }
301
+ else {
302
+ props = props.filter((p) => !p.system && p.initiator === "client");
303
+ }
304
+ const fields = [];
305
+ for (const prop of props) {
306
+ const field = convertEntityProp(prop, entityName);
307
+ const ftype = field.type ?? "";
308
+ if (columnsNumber > 1 &&
309
+ ["richtext", "textarea", "group", "flexGroup", "tabs", "steps", "table", "files"].includes(ftype)) {
310
+ field.columns = { lg: { container: columnsNumber } };
311
+ }
312
+ else {
313
+ field.columns = { lg: { container: 1 } };
314
+ }
315
+ fields.push(field);
316
+ }
317
+ autoLayout(fields, columnsNumber);
318
+ const settings = { ...DEFAULT_FORM_SETTINGS, columnsNumber };
319
+ return [fields, settings];
320
+ }
321
+ // ---------------------------------------------------------------------------
322
+ // Tools
323
+ // ---------------------------------------------------------------------------
324
+ /** List forms. Optionally filter by entity name or form type (e.g. 'elementForm'). */
325
+ export async function listForms(entityName = null, formType = null, limit = 50) {
326
+ const filters = [];
327
+ if (entityName) {
328
+ filters.push(makeFilter("entity.name", entityName));
329
+ }
330
+ if (formType) {
331
+ filters.push(makeFilter("type", formType));
332
+ }
333
+ const results = await searchEntity(ENTITY_FORMS, filters, FORM_LIST_FIELDS, limit);
334
+ return jsonResponse(results);
335
+ }
336
+ /** Get a form by ID including its full schema (data.formShema) and settings. */
337
+ export async function getForm(formId) {
338
+ const result = await selectEntity(ENTITY_FORMS, [makeFilter("id", formId)], FORM_DETAIL_FIELDS);
339
+ return jsonResponse(result);
340
+ }
341
+ /**
342
+ * Create a new form.
343
+ *
344
+ * Provide a layout in one of three ways:
345
+ * - schemaJson: a JSON array of field objects (or an object with 'formShema').
346
+ * - generateFromEntity=true with entityName: auto-build fields from the
347
+ * entity schema (optionally limit to comma-separated 'fields').
348
+ * - neither: an empty form.
349
+ * settingsJson overrides default form settings. moduleCode is optional JS.
350
+ */
351
+ export async function createForm(name, formType = "elementForm", entityName = null, alias = null, isPublic = false, schemaJson = null, settingsJson = null, generateFromEntity = false, fields = null, columns = 1, moduleCode = null) {
352
+ let schema = [];
353
+ const settings = { ...DEFAULT_FORM_SETTINGS };
354
+ if (schemaJson) {
355
+ let parsed;
356
+ try {
357
+ parsed = parseJsonParam(schemaJson, "schema_json");
358
+ }
359
+ catch (e) {
360
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
361
+ }
362
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
363
+ const p = parsed;
364
+ schema = (p.formShema ?? p.schema ?? []);
365
+ if ("formSettings" in p) {
366
+ Object.assign(settings, p.formSettings);
367
+ }
368
+ }
369
+ else if (Array.isArray(parsed)) {
370
+ schema = parsed;
371
+ }
372
+ }
373
+ else if (generateFromEntity && entityName) {
374
+ const fieldNames = fields ? fields.split(",").map((f) => f.trim()) : null;
375
+ const [genSchema, genSettings] = await generateSchemaFromEntity(entityName, fieldNames, columns);
376
+ if (genSchema === null) {
377
+ return jsonResponse({ error: `Entity '${entityName}' not found` });
378
+ }
379
+ schema = genSchema;
380
+ Object.assign(settings, genSettings);
381
+ }
382
+ // Apply the scalar args first, THEN the explicit settings_json — an explicit
383
+ // settings object must win, not be clobbered by the args' defaults.
384
+ settings.columnsNumber = columns;
385
+ settings.formType = formType;
386
+ if (entityName) {
387
+ settings.entityId = entityName;
388
+ }
389
+ if (settingsJson) {
390
+ try {
391
+ Object.assign(settings, parseJsonParam(settingsJson, "settings_json", "object"));
392
+ }
393
+ catch (e) {
394
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
395
+ }
396
+ }
397
+ const formView = {
398
+ name,
399
+ type: formType,
400
+ isPublic,
401
+ data: {
402
+ formShema: schema,
403
+ formSettings: settings,
404
+ formModul: moduleCode,
405
+ },
406
+ };
407
+ if (alias) {
408
+ formView.alias = alias;
409
+ }
410
+ if (entityName) {
411
+ const entSchema = await getEntitySchema(entityName);
412
+ if (entSchema && typeof entSchema === "object" && !Array.isArray(entSchema) && entSchema.id) {
413
+ formView.entity = { id: parseInt(String(entSchema.id), 10) };
414
+ }
415
+ }
416
+ const result = await insertEntity(ENTITY_FORMS, [formView], { id: true, name: true, type: true });
417
+ return jsonResponse(result.length ? result[0] : null);
418
+ }
419
+ /** Update a form's name, schema (data.formShema), settings, or module code. */
420
+ export async function updateForm(formId, name = null, schemaJson = null, settingsJson = null, moduleCode = null) {
421
+ const existing = await selectEntity(ENTITY_FORMS, [makeFilter("id", formId)], FORM_DETAIL_FIELDS);
422
+ if (!existing) {
423
+ return jsonResponse({ error: `Form ${formId} not found` });
424
+ }
425
+ const data = { ...(existing.data || {}) };
426
+ let changed = false;
427
+ const updateFields = {};
428
+ if (name !== null) {
429
+ updateFields.name = name;
430
+ }
431
+ if (schemaJson !== null) {
432
+ let parsed;
433
+ try {
434
+ parsed = parseJsonParam(schemaJson, "schema_json");
435
+ }
436
+ catch (e) {
437
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
438
+ }
439
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
440
+ const p = parsed;
441
+ data.formShema = p.formShema ?? p.schema ?? [];
442
+ if ("formSettings" in p) {
443
+ data.formSettings = p.formSettings;
444
+ }
445
+ }
446
+ else if (Array.isArray(parsed)) {
447
+ data.formShema = parsed;
448
+ }
449
+ changed = true;
450
+ }
451
+ if (settingsJson !== null) {
452
+ let newSettings;
453
+ try {
454
+ newSettings = parseJsonParam(settingsJson, "settings_json", "object");
455
+ }
456
+ catch (e) {
457
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
458
+ }
459
+ const current = { ...(data.formSettings || {}) };
460
+ Object.assign(current, newSettings);
461
+ data.formSettings = current;
462
+ changed = true;
463
+ }
464
+ if (moduleCode !== null) {
465
+ data.formModul = moduleCode;
466
+ changed = true;
467
+ }
468
+ if (changed) {
469
+ updateFields.data = data;
470
+ }
471
+ if (Object.keys(updateFields).length === 0) {
472
+ return jsonResponse({ error: "No fields to update" });
473
+ }
474
+ const result = await makeRequest("POST", `/api/core/data/${ENTITY_FORMS}/update/${formId}`, {
475
+ fields: updateFields,
476
+ });
477
+ return jsonResponse(result);
478
+ }
479
+ /**
480
+ * Generate a form schema (formShema + formSettings) from an entity's fields.
481
+ *
482
+ * 'fields': optional comma-separated list to limit/order the included fields.
483
+ * Returns a JSON object you can pass to createForm via schemaJson.
484
+ */
485
+ export async function generateFormSchema(entityName, columns = 1, fields = null) {
486
+ const fieldNames = fields ? fields.split(",").map((f) => f.trim()) : null;
487
+ const [schema, settings] = await generateSchemaFromEntity(entityName, fieldNames, columns);
488
+ if (schema === null) {
489
+ return jsonResponse({ error: `Entity '${entityName}' not found` });
490
+ }
491
+ return jsonResponse({ formShema: schema, formSettings: settings });
492
+ }
493
+ /**
494
+ * Append a single field to an existing form's schema (data.formShema).
495
+ *
496
+ * Only the new field is positioned (on a fresh row below the existing layout);
497
+ * existing fields keep their positions — re-running auto-layout over the whole
498
+ * form would silently destroy a manually arranged layout.
499
+ */
500
+ export async function addFieldToForm(formId, fieldName, fieldType = "text", label = null, required = false, extraJson = null) {
501
+ const existing = await selectEntity(ENTITY_FORMS, [makeFilter("id", formId)], FORM_DETAIL_FIELDS);
502
+ if (!existing) {
503
+ return jsonResponse({ error: `Form ${formId} not found` });
504
+ }
505
+ const data = { ...(existing.data || {}) };
506
+ const schema = [...(data.formShema || [])];
507
+ let extra;
508
+ try {
509
+ extra = extraJson ? parseJsonParam(extraJson, "extra_json", "object") : {};
510
+ }
511
+ catch (e) {
512
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
513
+ }
514
+ const rules = extra.rules ?? [];
515
+ delete extra.rules;
516
+ if (required && !rules.includes("required")) {
517
+ rules.push("required");
518
+ }
519
+ if (rules.length) {
520
+ extra.rules = rules;
521
+ }
522
+ let maxY = 0;
523
+ for (const f of schema) {
524
+ if (f && typeof f === "object" && !Array.isArray(f)) {
525
+ const pos = f.position || {};
526
+ const lg = pos.lg || {};
527
+ const y = lg.y ?? 0;
528
+ if (typeof y === "number") {
529
+ maxY = Math.max(maxY, Math.trunc(y));
530
+ }
531
+ }
532
+ }
533
+ if (!("position" in extra)) {
534
+ extra.position = { x: 1, y: maxY + 1 };
535
+ }
536
+ const newField = makeField(fieldType, fieldName, label ?? fieldName, 1, 1, {
537
+ field_id: fieldName,
538
+ ...extra,
539
+ });
540
+ schema.push(newField);
541
+ data.formShema = schema;
542
+ const result = await makeRequest("POST", `/api/core/data/${ENTITY_FORMS}/update/${formId}`, {
543
+ fields: { data },
544
+ });
545
+ return jsonResponse(result);
546
+ }
547
+ /** List the available form field types. */
548
+ export async function listFormFieldTypes() {
549
+ return jsonResponse(FORM_FIELD_TYPES);
550
+ }