-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhelpers.js
More file actions
388 lines (353 loc) · 11.1 KB
/
helpers.js
File metadata and controls
388 lines (353 loc) · 11.1 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import { produce } from "immer";
import isUndefined from "lodash/isUndefined.js";
import { isArray, isEmpty, isNull, isObject, omitBy } from "lodash";
import { useEffect } from "react";
import cronstrue from "cronstrue";
import { useSessionStore } from "../store/session-store";
import { usePermissionStore } from "../store/permission-store";
import { useProjectStore } from "../store/project-store";
import { getRenameColumnSpec } from "../ide/editor/no-code-model/helper";
const timeArray = [
{ value: "GT", label: " > " },
{ value: "GTE", label: " >= " },
{ value: "LT", label: " < " },
{ value: "LTE", label: " <= " },
];
const operators = {
default: [
{ value: "EQ", label: " == " },
{ value: "NEQ", label: " != " },
{ value: "NULL", label: "Null" },
{ value: "NOTNULL", label: "Not Null" },
],
Number: [
{ value: "GT", label: " > " },
{ value: "GTE", label: " >= " },
{ value: "LT", label: " < " },
{ value: "LTE", label: " <= " },
{ value: "BETWEEN", label: "Between" },
],
String: [
{ value: "IN", label: "In" },
{ value: "NOTIN", label: "Not In" },
{ value: "CONTAINS", label: "Contains" },
{ value: "NOTCONTAINS", label: "Not Contains" },
{ value: "STARTSWITH", label: "Starts With" },
{ value: "ENDSWITH", label: "Ends With" },
],
// Formula type: comparison and list operators (NO LIKE operators - blocked in backend)
Formula: [
{ value: "GT", label: " > " },
{ value: "GTE", label: " >= " },
{ value: "LT", label: " < " },
{ value: "LTE", label: " <= " },
{ value: "IN", label: "In" },
{ value: "NOTIN", label: "Not In" },
{ value: "BETWEEN", label: "Between" },
],
JoinString: [
{ value: "EQ", label: " == " },
{ value: "NEQ", label: " != " },
],
Boolean: [
{ value: "TRUE", label: "True" },
{ value: "FALSE", label: "False" },
{ value: "NULL", label: "Null" },
{ value: "NOTNULL", label: "Not Null" },
],
Time: [...timeArray, { value: "BETWEEN", label: "Between" }],
Date: [...timeArray, { value: "BETWEEN", label: "Between" }],
};
const getOperators = (type, dataType) => {
if (dataType === "Boolean") {
return operators[dataType];
}
if (type === "join" && dataType === "String") {
return operators["JoinString"];
}
return [...operators.default, ...(operators[dataType] ?? [])];
};
// Function to generate a unique key every time
const generateKey = () => {
const timestamp = Date.now();
const randomValue = crypto.randomUUID();
return `${timestamp}-${randomValue}`;
};
// Function to stop propagation when arrow keys are pressed
const stopPropagation = (e) => {
if ([13, 37, 38, 39, 40].includes(e.keyCode)) {
e.stopPropagation();
}
};
// Function to remove id from array of objects and omit undefined values
const removeIdFromObjects = (objects) => {
return produce(objects, (draft) => {
draft.forEach((item) => {
delete item.id;
Object.keys(item).forEach((key) => {
if (isUndefined(item[key])) {
delete item[key];
}
});
});
});
};
// Function to add id to array of objects
const addIdToObjects = (objects) => {
return produce(objects, (draft) => {
draft?.forEach((item) => {
item.id = generateKey();
});
});
};
const checkPermission = (resource, action) => {
if (!useSessionStore.getState().sessionDetails?.is_cloud) return true;
const permissions = usePermissionStore.getState().permissionDetails;
const sessionDetails = useSessionStore.getState().sessionDetails;
// Handle case when session is expired/undefined/empty (e.g., after logout)
if (!sessionDetails || Object.keys(sessionDetails).length === 0) return false;
// Always use server-returned permissions — never trust client-side role
return permissions[resource]?.[action] ?? false;
};
// Function to get filter conditions
const getFilterCondition = (data, type = "COLUMN", dataType = null) => {
const filterCondition = { type: type };
// Currently we have type COLUMN, VALUE, FORMULA
switch (type) {
case "COLUMN": {
// to handle db which doesn't have schema
const [columnName, tableName, schemaName] = data.reverse();
filterCondition.column = {
schema_name: schemaName ?? null,
table_name: tableName,
column_name: columnName,
data_type: dataType,
};
break;
}
case "VALUE": {
filterCondition.value = data;
filterCondition.type = "COLUMN";
break;
}
case "FORMULA": {
// For formula expressions (e.g., "YEAR(order_date)", "col1 * col2")
filterCondition.expression = data;
break;
}
}
return filterCondition;
};
/**
* Check if a value is a formula expression (starts with =)
* @param {string} value - The value to check
* @return {boolean} - True if the value is a formula expression
*/
const isFormulaExpression = (value) => {
return typeof value === "string" && value.trim().startsWith("=");
};
/**
* Extract formula expression from value (removes = prefix)
* @param {string} value - The value with = prefix
* @return {string} - The formula expression without = prefix
*/
const extractFormulaExpression = (value) => {
if (!isFormulaExpression(value)) return value;
return value.trim().substring(1).trim();
};
/**
* Validate a formula expression (basic frontend validation)
* @param {string} expression - The formula expression to validate
* @param {string[]} availableColumns - List of available column names
* @return {{valid: boolean, errors: string[]}} - Validation result
*/
const validateFormulaExpression = (expression, availableColumns = []) => {
const errors = [];
if (!expression || expression.trim() === "") {
errors.push("Formula expression cannot be empty");
return { valid: false, errors };
}
// Check balanced parentheses
let depth = 0;
for (const char of expression) {
if (char === "(") depth++;
if (char === ")") depth--;
if (depth < 0) {
errors.push("Unbalanced parentheses: unexpected closing parenthesis");
break;
}
}
if (depth > 0) {
errors.push("Unbalanced parentheses: missing closing parenthesis");
}
// Check for unclosed quotes
const singleQuotes = (expression.match(/'/g) || []).length;
const doubleQuotes = (expression.match(/"/g) || []).length;
if (singleQuotes % 2 !== 0) {
errors.push("Unclosed single quote");
}
if (doubleQuotes % 2 !== 0) {
errors.push("Unclosed double quote");
}
return { valid: errors.length === 0, errors };
};
const getTableFullname = (schemaName, tableName) => {
let tableFullname = tableName;
if (schemaName) {
tableFullname = schemaName + "." + tableName;
}
return tableFullname;
};
const getBaseUrl = () => {
const location = window.location.href;
const url = new URL(location).origin;
return url;
};
const handleUserLogout = () => {
localStorage.removeItem("orgid");
localStorage.removeItem("session-storage");
// Navigate directly to logout endpoint to allow SSO redirect
// (fetch() doesn't follow cross-origin redirects for SSO logout)
window.location.href = "/api/v1/logout";
};
const capitaliseString = (str) => {
return str[0].toUpperCase() + str.slice(1, str.length);
};
const renameMap = (spec, transformationId) => {
const renameColumnSpec = getRenameColumnSpec(
spec?.transform,
transformationId
);
return (
renameColumnSpec?.mappings?.reduce((acc, item) => {
acc[item.old_name] = item.new_name;
return acc;
}, {}) || {}
);
};
export const useEscapeKey = (isOpen, onEscape) => {
useEffect(() => {
const handleEscapeKey = (event) => {
if (event.key === "Escape" && isOpen) {
onEscape();
}
};
window.addEventListener("keydown", handleEscapeKey);
return () => {
window.removeEventListener("keydown", handleEscapeKey);
};
}, [isOpen, onEscape]);
};
const openNewlyGeneratedModel = (modelName) => {
const projectId = useProjectStore.getState().projectId;
const { projectDetails, setOpenedTabs } = useProjectStore.getState();
const openedTabs = projectDetails?.[projectId]?.openedTabs || [];
const key = `${useProjectStore.getState().projectName}/models/${modelName}`;
const isAlreadyOpen = openedTabs.some((tab) => tab.key === key);
if (!isAlreadyOpen) {
const newTab = {
key,
label: modelName,
type: "NO_CODE_MODEL",
extension: modelName,
};
setOpenedTabs([...openedTabs, newTab], projectId);
}
};
const getActiveModelName = (projectId, projectDetails) => {
const modelInfo = projectDetails?.[projectId]?.focussedTab;
if (!projectId || !modelInfo || Object.keys(modelInfo).length === 0) {
return null;
}
if (modelInfo.type === "NO_CODE_MODEL" && modelInfo.key) {
return modelInfo.key.split("/").pop() ?? null;
}
return modelInfo.key ?? null;
};
const removeUnwantedKeys = (data) => {
if (isArray(data)) {
const filteredArray = data.map((item) => removeUnwantedKeys(item));
return filteredArray.filter((item) => {
if (isArray(item)) {
return item.length > 0;
}
return item !== undefined;
});
}
if (isObject(data)) {
const filteredObj = omitBy(data, isNull);
for (const key in filteredObj) {
if (isObject(filteredObj[key])) {
filteredObj[key] = removeUnwantedKeys(filteredObj[key]);
}
}
const nonEmptyKeys = Object.keys(filteredObj).filter((key) => {
const value = filteredObj[key];
return (
value !== undefined &&
!(isArray(value) && value.length === 0) &&
!(isObject(value) && Object.keys(value).length === 0)
);
});
const finalObj = Object.fromEntries(
nonEmptyKeys.map((key) => [key, filteredObj[key]])
);
if (isEmpty(finalObj)) {
return {};
}
return finalObj;
}
return data;
};
const sanitizeLowercaseOnly = (value) => {
return value.replace(/[^a-z]/g, "");
};
const truncateText = (text, maxLength = 50) => {
if (!text) return "";
return text.length > maxLength ? text.slice(0, maxLength) + "..." : text;
};
const getTooltipText = (data, type) => {
if (type === "interval") {
return `every ${data.every} ${data.period}`;
}
return `${cronstrue.toString(data.cron_expression)}`;
};
const getRelativeTime = (dateString) => {
if (!dateString) return "";
const now = new Date();
const then = new Date(dateString);
const diffMs = now - then;
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 1) return "just now";
if (diffMins < 60) return `${diffMins}m ago`;
const diffHrs = Math.floor(diffMins / 60);
if (diffHrs < 24) return `${diffHrs}h ago`;
const diffDays = Math.floor(diffHrs / 24);
if (diffDays < 30) return `${diffDays}d ago`;
const diffMonths = Math.floor(diffDays / 30);
return `${diffMonths}mo ago`;
};
export {
generateKey,
stopPropagation,
removeIdFromObjects,
addIdToObjects,
getFilterCondition,
getTableFullname,
getOperators,
getBaseUrl,
handleUserLogout,
renameMap,
capitaliseString,
checkPermission,
openNewlyGeneratedModel,
getActiveModelName,
removeUnwantedKeys,
sanitizeLowercaseOnly,
truncateText,
getTooltipText,
isFormulaExpression,
extractFormulaExpression,
validateFormulaExpression,
getRelativeTime,
};