-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
287 lines (274 loc) · 8.15 KB
/
index.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
const {
input,
div,
span,
text,
script,
domReady,
style,
button,
} = 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,
jsexprToSQL,
} = require("@saltcorn/data/models/expression");
const db = require("@saltcorn/data/db");
const { getState } = require("@saltcorn/data/db/state");
const { stateFieldsToWhere } = require("@saltcorn/data/plugin-helper");
const { mergeIntoWhere } = require("@saltcorn/data/utils");
const { localeDate, localeDateTime } = require("@saltcorn/markup");
const configuration_workflow = () =>
new Workflow({
steps: [
{
name: "Statistic",
form: async (context) => {
const table = await Table.findOne({ id: context.table_id });
const fields = await table.getFields();
const statOptions = [
"Count",
"Count distinct",
"Avg",
"Sum",
"Max",
"Min",
];
fields.forEach((f) => {
if (f.type && f.type.name === "Date") {
statOptions.push(`Latest ${f.name}`);
}
});
const fieldOptions = fields.map((f) => f.name);
if (jsexprToSQL) fieldOptions.push("Formula");
const floatFVs = getState().types.Float.fieldviews;
const field_view_options = Object.entries(floatFVs)
.filter(([k, v]) => !v.isEdit && !v.isFilter)
.map(([k, v]) => k);
const fvConfigFields = [];
for (const fvnm of field_view_options) {
const cfgflds = floatFVs[fvnm].configFields || [];
const flds =
typeof cfgflds === "function"
? cfgflds({ attributes: {} }) // a fake field
: cfgflds;
//console.log({ fvnm, flds });
flds.forEach((fld) => {
fvConfigFields.push({ ...fld, showIf: { fieldview: fvnm } });
});
}
return new Form({
fields: [
{
name: "statistic",
label: "Statistic",
type: "String",
required: true,
attributes: {
options: statOptions,
},
},
{
name: "field",
label: "field",
type: "String",
required: true,
attributes: {
options: fieldOptions,
},
},
{
name: "value_fml",
label: "Value Formula",
class: "validate-expression",
type: "String",
required: false,
showIf: { field: "Formula" },
},
{
name: "fieldview",
label: "Field view",
type: "String",
required: false,
attributes: {
options: field_view_options,
},
},
...fvConfigFields,
{
name: "where_fml",
label: "Where",
sublabel: "Formula",
class: "validate-expression",
type: "String",
required: false,
},
{
name: "decimal_places",
label: "Decimal places",
type: "Integer",
required: false,
showIf: { fieldview: "" },
},
{
name: "text_style",
label: "Text Style",
type: "String",
required: true,
attributes: {
options: [
{ label: "Normal", name: "" },
{ label: "Heading 1", name: "h1" },
{ label: "Heading 2", name: "h2" },
{ label: "Heading 3", name: "h3" },
{ label: "Heading 4", name: "h4" },
{ label: "Heading 5", name: "h5" },
{ label: "Heading 6", name: "h6" },
{ label: "Bold", name: "font-weight-bold" },
{ label: "Italics", name: "font-italic" },
{ label: "Small", name: "small" },
],
},
},
{
name: "pre_text",
label: "Text before",
sublabel: "For example: currency symbol",
type: "String",
required: false,
},
{
name: "post_text",
label: "Text after",
sublabel: "For example: units",
type: "String",
required: false,
},
],
});
},
},
],
});
const get_state_fields = async (table_id, viewname, { show_view }) => {
const table = Table.findOne(table_id);
const table_fields = table.fields;
return table_fields.map((f) => {
const sf = new Field(f);
sf.required = false;
return sf;
});
};
const statisticOnField = (statistic, field) => {
if (statistic === "Count distinct") return `count(distinct ${field})`;
return `${db.sqlsanitize(statistic)}(${field})`;
};
const getStatisticsImpl = async (
table_id,
{ statistic, field, where_fml, value_fml },
state,
req
) => {
const tbl = await Table.findOne({ id: table_id });
const fields = await tbl.getFields();
const { ...qstate } = await stateFieldsToWhere({ fields, state });
mergeIntoWhere(qstate, jsexprToWhere(where_fml, { user: req.user }));
const { where, values } = db.mkWhere(qstate);
const schema = db.getTenantSchemaPrefix();
const fieldExpr =
field === "Formula" ? jsexprToSQL(value_fml) : `"${db.sqlsanitize(field)}"`;
let sql;
if (statistic.startsWith("Latest ")) {
const dateField = statistic.replace("Latest ", "");
sql = `select ${fieldExpr} as the_stat from ${schema}"${db.sqlsanitize(
tbl.name
)}"
where "${dateField}"=(select max("${dateField}") from ${schema}"${db.sqlsanitize(
tbl.name
)}" ${where ? ` and ${where}` : ""})`;
} else
sql = `select ${statisticOnField(
statistic,
fieldExpr
)} as the_stat from ${schema}"${db.sqlsanitize(tbl.name)}" ${where}`;
const { rows } = await db.query(sql, values);
return rows;
};
const run = async (
table_id,
viewname,
{
statistic,
field,
text_style,
fieldview,
decimal_places,
pre_text,
post_text,
where_fml,
value_fml,
...fvOpts
},
state,
{ req },
queriesObj
) => {
const rows = queriesObj?.statistics_query
? await queriesObj.statistics_query(state)
: await getStatisticsImpl(
table_id,
{ statistic, field, where_fml, value_fml },
state,
req
);
let the_stat = rows[0].the_stat;
if (the_stat === null && statistic == "Sum") the_stat = 0;
const wrapper = (t) =>
div(
{ class: [text_style] },
pre_text || "",
span({ class: viewname }, t),
post_text || ""
);
if (fieldview) {
const fv = getState().types.Float.fieldviews[fieldview];
return wrapper(fv.run(the_stat, req, fvOpts));
}
const show_stat =
the_stat instanceof Date
? localeDateTime(the_stat)
: typeof decimal_places === "undefined"
? the_stat
: (+the_stat).toFixed(decimal_places);
return wrapper(show_stat);
};
module.exports = {
sc_plugin_api_version: 1,
viewtemplates: [
{
name: "Statistic",
display_state_form: false,
get_state_fields,
configuration_workflow,
run,
queries: ({
table_id,
configuration: { statistic, field, where_fml, value_fml },
req,
}) => ({
async statistics_query(state) {
return await getStatisticsImpl(
table_id,
{ statistic, field, where_fml, value_fml },
state,
req
);
},
}),
},
],
};