@autofleet/sadot 0.10.2 → 0.10.3

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,227 @@
1
+ import type { WhereOptions } from 'sequelize';
2
+
3
+ /**
4
+ * Type representing possible condition values.
5
+ * Currently supporting strings and arrays of strings.
6
+ * More types to be added (TBA).
7
+ */
8
+ export type ConditionWithOperator = {
9
+ operator: string;
10
+ value: string;
11
+ };
12
+ export type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
13
+
14
+ export type CustomFieldSort = {
15
+ field: string;
16
+ direction: 'ASC' | 'DESC';
17
+ }
18
+
19
+ export type CustomFieldFilterOptions = {
20
+ where?: WhereOptions;
21
+ replacements?: Record<string, string>;
22
+ }
23
+
24
+ export enum SubQueryType {
25
+ VALUES = 'values',
26
+ ENTRIES = 'entries',
27
+ }
28
+
29
+ export const isConditionStringArray = (input: any): input is string[] => Array.isArray(input) && typeof input[0] === 'string';
30
+ export const isBooleanString = (input: string): boolean => ['true', 'false'].includes(input.toString());
31
+ export const isDate = (input: any): input is Date => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
32
+
33
+ export const castValueToJsonb = (value: string, type: string) => `to_jsonb(${value}::${type})`;
34
+ export const castValueToJsonbText = (value: string) => castValueToJsonb(value, 'text');
35
+ export const castValueToJsonbBoolean = (value: string) => castValueToJsonb(value, 'boolean');
36
+ export const castValueToJsonbNumeric = (value: string) => castValueToJsonb(value, 'numeric');
37
+ export const castIfNeeded = (columnName: string, conditionValue: string): string => {
38
+ if (isDate(conditionValue)) {
39
+ return castValueToJsonb(columnName, 'timestamp');
40
+ }
41
+ return columnName;
42
+ };
43
+
44
+ export const AND_DELIMITER = ' AND ';
45
+ export const OR_DELIMITER = ' OR ';
46
+ export const CD_TABLE_ALIAS = 'cd';
47
+ export const CD_NAME_COLUMN = `${CD_TABLE_ALIAS}.name`;
48
+ export const CV_TABLE_ALIAS = 'cv';
49
+ export const CV_VALUE_COLUMN = `${CV_TABLE_ALIAS}.value`;
50
+ export const CE_TABLE_ALIAS = 'ce';
51
+
52
+ const getSingleConditionWithOperator = (value: any, operator: string, replacementKey: string, reverseReplacementsMap: Map<string, string>) => {
53
+ let type = 'text';
54
+ if (isDate(value)) {
55
+ type = 'date';
56
+ } else if (!Number.isNaN(Number(value))) {
57
+ type = 'numeric';
58
+ } else if (isBooleanString(value)) {
59
+ type = 'boolean';
60
+ }
61
+ const replacedValue = reverseReplacementsMap.get(value);
62
+
63
+ return `(jsonb_extract_path_text(${CE_TABLE_ALIAS}.custom_fields, :${replacementKey})::${type}) ${operator} :${replacedValue}`;
64
+ };
65
+
66
+ const getFormattedValue = (value: string) => {
67
+ let formattedValue: string | number | boolean = value;
68
+ if (isBooleanString(value)) {
69
+ formattedValue = value === 'true';
70
+ } else if (!Number.isNaN(Number(value))) {
71
+ formattedValue = Number(value);
72
+ }
73
+
74
+ return formattedValue;
75
+ };
76
+
77
+ const getJSONSubQuery = (value: string, key: string) => {
78
+ const formattedValue = getFormattedValue(value);
79
+ const jsonQuery = JSON.stringify({ [key]: formattedValue });
80
+ let jsonQueryWithStringBoolean;
81
+ if (isBooleanString(value)) {
82
+ jsonQueryWithStringBoolean = `${CE_TABLE_ALIAS}.custom_fields @> '${JSON.stringify({ [key]: value })}'`;
83
+ }
84
+ return `
85
+ (
86
+ ${jsonQueryWithStringBoolean ? `${jsonQueryWithStringBoolean} OR` : ''}
87
+ ${CE_TABLE_ALIAS}.custom_fields @> '${jsonQuery}'
88
+ )
89
+ `;
90
+ };
91
+
92
+ export const getFilterCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, conditionsStrings: Array<string | boolean>): string => {
93
+ switch (queryType) {
94
+ case SubQueryType.VALUES:
95
+ return `
96
+ SELECT ${CV_TABLE_ALIAS}.model_id
97
+ FROM custom_field_values AS ${CV_TABLE_ALIAS}
98
+ INNER JOIN custom_field_definitions AS ${CD_TABLE_ALIAS} ON ${CV_TABLE_ALIAS}.custom_field_definition_id = ${CD_TABLE_ALIAS}.id
99
+ ${AND_DELIMITER}${CD_TABLE_ALIAS}.model_type = '${modelType}'
100
+ WHERE ${conditionsStrings.join(OR_DELIMITER)}
101
+ ${AND_DELIMITER}${CV_TABLE_ALIAS}.deleted_at IS NULL${AND_DELIMITER}${CD_TABLE_ALIAS}.deleted_at IS NULL
102
+ GROUP BY ${CV_TABLE_ALIAS}.model_id
103
+ HAVING COUNT(DISTINCT ${CV_TABLE_ALIAS}.custom_field_definition_id) = ${conditionsStrings.length}
104
+ `.replace(/\n/g, '');
105
+ case SubQueryType.ENTRIES:
106
+ return `
107
+ SELECT ce.model_id
108
+ FROM custom_field_entries ce
109
+ JOIN custom_field_definitions cfd
110
+ ON ce.model_type = cfd.model_type
111
+ AND ce.entity_id = cfd.entity_id
112
+ WHERE
113
+ cfd.deleted_at IS NULL AND
114
+ ${conditionsStrings.join(AND_DELIMITER)}
115
+ `;
116
+ default:
117
+ throw new Error('Invalid query type');
118
+ }
119
+ };
120
+
121
+ export const getSortCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, replacementKey: string): string => {
122
+ switch (queryType) {
123
+ case SubQueryType.VALUES:
124
+ return `(
125
+ SELECT value
126
+ FROM (SELECT cv.model_id, cv.value
127
+ FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
128
+ ON cv.custom_field_definition_id = cd.id
129
+ ${AND_DELIMITER}cd.model_type = '${modelType}'
130
+ WHERE cv.model_id = "${modelType}"."id"
131
+ ${AND_DELIMITER}cd.name = :${replacementKey}
132
+ ) AS CustomFieldAggregation
133
+ )
134
+ `;
135
+ case SubQueryType.ENTRIES:
136
+ return `(
137
+ SELECT
138
+ customFields.value
139
+ FROM
140
+ custom_field_entries AS ${CE_TABLE_ALIAS},
141
+ jsonb_each_text(custom_fields) AS customFields
142
+ WHERE
143
+ customFields.key = :${replacementKey}${AND_DELIMITER}
144
+ ${CE_TABLE_ALIAS}.model_type = '${modelType}'${AND_DELIMITER}
145
+ ${CE_TABLE_ALIAS}.model_id = "${modelType}"."id"
146
+ )
147
+ `;
148
+ default:
149
+ throw new Error('Invalid query type');
150
+ }
151
+ };
152
+
153
+ export const formatConditionsForValues = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>) => {
154
+ const replacementKey = reverseReplacementsMap.get(key);
155
+ if (!replacementKey) {
156
+ return false;
157
+ }
158
+
159
+ const columnCondition = `(${CD_NAME_COLUMN} = :${replacementKey})`;
160
+ if (Array.isArray(condition)) {
161
+ if (condition.length === 0) {
162
+ // if empty array, the condition is ignored
163
+ return false;
164
+ }
165
+
166
+ if (isConditionStringArray(condition)) {
167
+ const values = condition.flatMap((v) => {
168
+ const valRandom = reverseReplacementsMap.get(v);
169
+ if (isBooleanString(v)) {
170
+ return [castValueToJsonbText(`:${valRandom}`), castValueToJsonbBoolean(`:${valRandom}`)];
171
+ }
172
+ if (!Number.isNaN(Number(v))) {
173
+ return castValueToJsonbNumeric(`:${valRandom}`);
174
+ }
175
+ return castValueToJsonbText(`:${valRandom}`);
176
+ }).join(',');
177
+ return `(${columnCondition}${AND_DELIMITER}${CV_VALUE_COLUMN} IN (${values}))`;
178
+ }
179
+ return condition.map((c) => {
180
+ const valRep = reverseReplacementsMap.get(c.value);
181
+ const valueAsJsonb = castValueToJsonbText(`:${valRep}`);
182
+
183
+ return `(${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, c.value)} ${c.operator} ${valueAsJsonb})`;
184
+ }).join(AND_DELIMITER);
185
+ }
186
+ if (typeof condition === 'string' || typeof condition === 'number') {
187
+ const conditionRep = reverseReplacementsMap.get(condition);
188
+ const valueAsJsonb = !Number.isNaN(Number(condition)) ? castValueToJsonbNumeric(`:${conditionRep}`) : castValueToJsonbText(`:${conditionRep}`);
189
+ const valueAsJsonbBoolean = isBooleanString(condition) ? `${OR_DELIMITER}${CV_VALUE_COLUMN} = ${castValueToJsonbBoolean(`:${conditionRep}`)}` : '';
190
+ return `(${columnCondition}${AND_DELIMITER}(${castIfNeeded(CV_VALUE_COLUMN, condition)} = ${valueAsJsonb}${valueAsJsonbBoolean}))`;
191
+ }
192
+ if (condition?.operator) {
193
+ const valueRep = reverseReplacementsMap.get(condition.value);
194
+ const valueAsJsonb = castValueToJsonbText(`:${valueRep}`);
195
+ return `( ${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, condition.value)} ${condition.operator} ${valueAsJsonb})`;
196
+ }
197
+ return false;
198
+ };
199
+
200
+ export const formatConditionsForEntries = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>) => {
201
+ const replacementKey = reverseReplacementsMap.get(key);
202
+ if (!replacementKey) {
203
+ return false;
204
+ }
205
+
206
+ if (Array.isArray(condition)) {
207
+ if (condition.length === 0) {
208
+ // if empty array, the condition is ignored
209
+ return false;
210
+ }
211
+
212
+ if (isConditionStringArray(condition)) {
213
+ const values = condition.map((value) => getJSONSubQuery(value, key)).join(`${OR_DELIMITER}\n`);
214
+ return `( ${values})`;
215
+ }
216
+ return condition.map((c) => getSingleConditionWithOperator(c.value, c.operator, replacementKey, reverseReplacementsMap)).join(AND_DELIMITER);
217
+ }
218
+
219
+ if (typeof condition === 'string' || typeof condition === 'number') {
220
+ return getJSONSubQuery(condition, key);
221
+ }
222
+
223
+ if (condition?.operator) {
224
+ return getSingleConditionWithOperator(condition.value, condition.operator, replacementKey, reverseReplacementsMap);
225
+ }
226
+ return false;
227
+ };
package/src/utils/init.ts CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  } from '../hooks';
17
17
  import { customFieldsFilterScope } from '../scopes';
18
18
  import logger from './logger';
19
- import type { ModelFetcher, Models } from '../types';
19
+ import type { CustomFieldOptions, ModelFetcher, Models } from '../types';
20
20
  import { customFieldsSortScope } from '../scopes/filter';
21
21
 
22
22
  const { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;
@@ -49,9 +49,9 @@ export const addHooks = (
49
49
  model.addHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate', beforeBulkUpdate);
50
50
  model.addHook('beforeCreate', 'sadot-beforeCreate', beforeCreate(scopeAttributes, modelOptions, sadotOptions));
51
51
  model.addHook('beforeUpdate', 'sadot-beforeUpdate', beforeUpdate(scopeAttributes, modelOptions, sadotOptions));
52
- model.addHook('afterFind', 'sadot-afterFind', enrichResults(name, scopeAttributes, 'afterFind', modelOptions));
53
- model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(name, scopeAttributes, null, modelOptions));
54
- model.addHook('afterCreate', 'sadot-afterCreate', enrichResults(name, scopeAttributes, null, modelOptions));
52
+ model.addHook('afterFind', 'sadot-afterFind', enrichResults(name, scopeAttributes, 'afterFind', modelOptions, sadotOptions));
53
+ model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(name, scopeAttributes, null, modelOptions, sadotOptions));
54
+ model.addHook('afterCreate', 'sadot-afterCreate', enrichResults(name, scopeAttributes, null, modelOptions, sadotOptions));
55
55
  } catch (e) {
56
56
  logger.error(`Could not add custom fields hook to model ${name}. `, e);
57
57
  }
@@ -90,7 +90,7 @@ const addAssociations = (model: ModelCtor, modelName: string): void => {
90
90
  CustomFieldValue.belongsTo(model, { foreignKey: 'modelId', as: modelName });
91
91
  };
92
92
 
93
- export const addScopes = (models: Models[], getModel: ModelFetcher): void => {
93
+ export const addScopes = (models: Models[], getModel: ModelFetcher, options: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false }): void => {
94
94
  models.forEach(async ({ name, scopeAttributes }) => {
95
95
  try {
96
96
  const model = getModel(name);
@@ -104,8 +104,8 @@ export const addScopes = (models: Models[], getModel: ModelFetcher): void => {
104
104
  // Necessary associations for the filtering scope
105
105
  addAssociations(model, name);
106
106
  // Add filter scope
107
- model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, customFieldsFilterScope(name));
108
- model.addScope(CUSTOM_FIELDS_SORT_SCOPE, customFieldsSortScope(name));
107
+ model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, customFieldsFilterScope(name, options));
108
+ model.addScope(CUSTOM_FIELDS_SORT_SCOPE, customFieldsSortScope(name, options));
109
109
  } catch (e) {
110
110
  logger.error(`Could not add custom fields scopes to model ${name}. `, e);
111
111
  }