-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathedit-nton.js
369 lines (358 loc) · 11.4 KB
/
edit-nton.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
const {
span,
button,
i,
a,
script,
domReady,
di,
select,
option,
style,
} = require("@saltcorn/markup/tags");
const View = require("@saltcorn/data/models/view");
const Workflow = require("@saltcorn/data/models/workflow");
const Table = require("@saltcorn/data/models/table");
const Form = require("@saltcorn/data/models/form");
const Field = require("@saltcorn/data/models/field");
const {
jsexprToWhere,
eval_expression,
} = require("@saltcorn/data/models/expression");
const db = require("@saltcorn/data/db");
const {
stateFieldsToWhere,
picked_fields_to_query,
} = require("@saltcorn/data/plugin-helper");
const { features } = require("@saltcorn/data/db/state");
const bs5 = features && features.bootstrap5;
const configuration_workflow = () =>
new Workflow({
steps: [
{
name: "Many-to-many relation",
form: async (context) => {
const table = await Table.findOne({ id: context.table_id });
const mytable = table;
const fields = await table.getFields();
const { child_field_list, child_relations } =
await table.get_child_relations();
var agg_field_opts = [];
for (const { table, key_field } of child_relations) {
const keyFields = table.fields.filter(
(f) =>
f.type === "Key" && !["_sc_files"].includes(f.reftable_name)
);
for (const kf of keyFields) {
const joined_table = await Table.findOne({
name: kf.reftable_name,
});
if (!joined_table) continue;
await joined_table.getFields();
joined_table.fields.forEach((jf) => {
agg_field_opts.push({
label: `${table.name}.${key_field.name}→${kf.name}→${jf.name}`,
name: `${table.name}.${key_field.name}.${kf.name}.${jf.name}`,
});
});
}
}
return new Form({
blurb: "Choose the relation that will be edited",
fields: [
{
name: "relation",
label: "Relation",
type: "String",
sublabel:
"Only many-to-many relations (JoinTable.foreignKey→keyToTableWithLabels→LabelField) are supported ",
required: true,
attributes: {
options: agg_field_opts,
},
},
{
name: "maxHeight",
label: "max-height px",
type: "Integer",
},
{
name: "where",
label: "Where",
type: "String",
class: "validate-expression",
},
{
name: "placeholder",
label: "Placeholder",
type: "String",
},
{
name: "ajax",
label: "Ajax fetch options",
type: "Bool",
},
{
name: "field_values_formula",
label: "Row values formula",
class: "validate-expression",
sublabel:
"Optional. A formula for field values set when creating a new join table row. For example <code>{name: manager}</code>",
type: "String",
fieldview: "textarea",
},
{
name: "disabled",
label: "Disabled",
type: "Bool",
},
{
name: "stay_open_on_select",
label: "Stay open",
sublabel: "Do not close on select",
type: "Bool",
},
],
});
},
},
],
});
const get_state_fields = async (table_id, viewname, { columns }) => [
{
name: "id",
type: "Integer",
required: true,
},
];
const run = async (
table_id,
viewname,
{
relation,
maxHeight,
where,
disabled,
ajax,
stay_open_on_select,
placeholder,
},
state,
extra,
{ get_rows_query }
) => {
const { id } = state;
if (!id) return "need id";
if (!relation) {
throw new Error(
`Select2 many-to-many view ${viewname} incorrectly configured. No relation chosen`
);
}
const relSplit = relation.split(".");
if (relSplit.length < 4) {
throw new Error(
`Select2 many-to-many view ${viewname} incorrectly configured. No relation chosen`
);
}
const rndid = `bs${Math.round(Math.random() * 100000)}`;
const [relTableNm, relField, joinFieldNm, valField] = relSplit;
const relTable = await Table.findOne({ name: relTableNm });
await relTable.getFields();
const joinField = relTable.fields.find((f) => f.name === joinFieldNm);
const joinedTable = await Table.findOne({ name: joinField.reftable_name });
const { rows, possibles } = await get_rows_query(id);
if (!rows[0]) return "No row selected";
possibles.sort((a, b) => {
const fa = a?.toLowerCase?.();
const fb = b?.toLowerCase?.();
return fa > fb ? 1 : fb > fa ? -1 : 0;
});
const selected = new Set(rows[0]._selected || []);
return (
select(
{ id: rndid, multiple: "multiple", class: "no-form-change" },
possibles.map((p) => option({ selected: selected.has(p) }, p))
) +
script(
domReady(
`const isWeb = typeof window.parent.saltcorn?.mobileApp === "undefined";
let url = "/api/${joinedTable.name}";
if (!isWeb) {
const { server_path } = parent.saltcorn.data.state.getState().mobileConfig;
url = server_path + "/api/${joinedTable.name}";
}
$('#${rndid}').select2({
width: '100%',
${disabled ? "disabled: true," : ""}
${stay_open_on_select ? "closeOnSelect: false," : ""}
dropdownParent: $('#${rndid}').parent(),
dropdownCssClass: "select2-dd-${rndid}",
${placeholder ? `placeholder: "${placeholder}",` : ""}
${
ajax
? ` minimumInputLength: 2,
minimumResultsForSearch: 10,
ajax: {
url: url,
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
${valField}: params.term,
approximate: true
}
if (!isWeb) {
const { jwt } = parent.saltcorn.data.state.getState().mobileConfig;
queryParameters.jwt = jwt;
}
return queryParameters;
},
processResults: function (data) {
if(!data || !data.success) return [];
return {
results: $.map(data.success, function (item) {
return {
text: item.${valField},
id: item.${valField}
}
})
};
}},`
: ""
}
});
$('#${rndid}').on('select2:unselect', function (e) {
view_post('${viewname}', 'remove', {id:'${id}', value: e.params.data.id});
});
$('#${rndid}').on('select2:select', function (e) {
view_post('${viewname}', 'add', {id:'${id}', value: e.params.data.id});
});`
)
) +
(maxHeight
? style(
`.select2-container--default .select2-dd-${rndid} .select2-results>.select2-results__options {max-height: ${maxHeight}px;}`
)
: "")
);
};
const remove = async (table_id, viewname, { relation }, { id, value }) => {
const relSplit = relation.split(".");
const [joinTableNm, relField, joinFieldNm, valField] = relSplit;
const joinTable = await Table.findOne({ name: joinTableNm });
await joinTable.getFields();
const joinField = joinTable.fields.find((f) => f.name === joinFieldNm);
const schema = db.getTenantSchema();
await db.query(
`delete from "${schema}"."${db.sqlsanitize(joinTable.name)}"
where "${db.sqlsanitize(relField)}"=$1 and
"${db.sqlsanitize(joinFieldNm)}" in
(select id from
"${schema}"."${db.sqlsanitize(joinField.reftable_name)}"
where "${db.sqlsanitize(valField)}"=$2)`,
[id, value]
);
return { json: { success: "ok" } };
};
const add = async (
table_id,
viewname,
{ relation, field_values_formula },
{ id, value },
{ req }
) => {
const table = await Table.findOne({ id: table_id });
const rows = await table.getJoinedRows({
where: { id },
forPublic: !req.user || req.user.role_id === 100, // TODO in mobile set user null for public
forUser: req.user,
});
if (!rows[0]) return { json: { error: "Row not found" } };
let extra = {};
if (field_values_formula) {
extra = eval_expression(field_values_formula, rows[0], req.user);
}
const relSplit = relation.split(".");
const [joinTableNm, relField, joinFieldNm, valField] = relSplit;
const joinTable = await Table.findOne({ name: joinTableNm });
await joinTable.getFields();
const joinField = joinTable.fields.find((f) => f.name === joinFieldNm);
const joinedTable = await Table.findOne({ name: joinField.reftable_name });
const joinedRow = await joinedTable.getRow({ [valField]: value });
const result = {};
await joinTable.insertRow(
{
[relField]: id,
[joinFieldNm]: joinedRow.id,
...extra,
},
req.user || { role_id: 100 },
result
);
return { json: { success: "ok", ...result } };
};
const queries = ({
table_id,
configuration: {
relation,
maxHeight,
where,
disabled,
ajax,
stay_open_on_select,
},
req,
}) => ({
async get_rows_query(id) {
const [relTableNm, relField, joinFieldNm, valField] = relation.split(".");
const relTable = Table.findOne({ name: relTableNm });
await relTable.getFields();
const joinField = relTable.fields.find((f) => f.name === joinFieldNm);
const table = Table.findOne({ id: table_id });
const joinedTable = Table.findOne({ name: joinField.reftable_name });
const rows = await table.getJoinedRows({
where: { id },
forPublic: !req.user || req.user.role_id === 100, // TODO in mobile set user null for public
forUser: req.user,
aggregations: {
_selected: {
table: joinField.reftable_name,
ref: "id",
subselect: {
field: joinFieldNm,
table: { name: db.sqlsanitize(relTable.name) }, //legacy, workaround insufficient escape
whereField: relField,
},
field: valField,
aggregate: "ARRAY_AGG",
},
},
});
if (!rows[0]) return { rows: [], possibles: [] };
let possibles = [];
if (!ajax) {
possibles = await joinedTable.distinctValues(
valField,
where
? jsexprToWhere(
where,
{ ...rows[0], user: req.user },
joinedTable.getFields()
)
: undefined
);
} else {
possibles = rows[0]._selected || [];
}
return { rows, possibles };
},
});
module.exports = {
name: "Select2 many-to-many",
display_state_form: false,
get_state_fields,
configuration_workflow,
run,
queries,
routes: { remove, add },
};