@autofleet/sadot 0.12.0 → 0.13.0-beta.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.
Files changed (124) hide show
  1. package/package.json +3 -1
  2. package/src/api/v1/index.ts +2 -0
  3. package/src/api/v1/validator/index.ts +127 -0
  4. package/src/api/v1/validator/validations.ts +39 -0
  5. package/src/events/index.ts +1 -1
  6. package/src/hooks/hooks.ts +304 -0
  7. package/src/hooks/index.ts +10 -5
  8. package/src/index.ts +6 -0
  9. package/src/models/CustomValidator.ts +76 -0
  10. package/src/models/index.ts +7 -2
  11. package/src/repository/validator.ts +91 -0
  12. package/src/tests/helpers/commonHooks.ts +9 -2
  13. package/src/tests/helpers/index.ts +7 -2
  14. package/src/types/index.ts +1 -0
  15. package/src/utils/validations/schema/README.md +93 -0
  16. package/src/utils/validations/schema/validator-schema.ts +103 -0
  17. package/dist/api/index.d.ts +0 -3
  18. package/dist/api/index.js +0 -12
  19. package/dist/api/v1/definition/index.d.ts +0 -3
  20. package/dist/api/v1/definition/index.js +0 -116
  21. package/dist/api/v1/definition/validations.d.ts +0 -2
  22. package/dist/api/v1/definition/validations.js +0 -77
  23. package/dist/api/v1/errors.d.ts +0 -4
  24. package/dist/api/v1/errors.js +0 -12
  25. package/dist/api/v1/index.d.ts +0 -3
  26. package/dist/api/v1/index.js +0 -11
  27. package/dist/errors/index.d.ts +0 -24
  28. package/dist/errors/index.js +0 -66
  29. package/dist/events/index.d.ts +0 -4
  30. package/dist/events/index.js +0 -50
  31. package/dist/hooks/create.d.ts +0 -10
  32. package/dist/hooks/create.js +0 -95
  33. package/dist/hooks/enrich.d.ts +0 -30
  34. package/dist/hooks/enrich.js +0 -159
  35. package/dist/hooks/find.d.ts +0 -1
  36. package/dist/hooks/find.js +0 -29
  37. package/dist/hooks/index.d.ts +0 -6
  38. package/dist/hooks/index.js +0 -18
  39. package/dist/hooks/update.d.ts +0 -10
  40. package/dist/hooks/update.js +0 -49
  41. package/dist/hooks/utils/updateInstanceValues.d.ts +0 -15
  42. package/dist/hooks/utils/updateInstanceValues.js +0 -50
  43. package/dist/hooks/workaround.d.ts +0 -10
  44. package/dist/hooks/workaround.js +0 -37
  45. package/dist/index.d.ts +0 -13
  46. package/dist/index.js +0 -67
  47. package/dist/models/CustomFieldDefinition.d.ts +0 -25
  48. package/dist/models/CustomFieldDefinition.js +0 -192
  49. package/dist/models/CustomFieldEntries.d.ts +0 -15
  50. package/dist/models/CustomFieldEntries.js +0 -123
  51. package/dist/models/CustomFieldValue.d.ts +0 -16
  52. package/dist/models/CustomFieldValue.js +0 -151
  53. package/dist/models/index.d.ts +0 -17
  54. package/dist/models/index.js +0 -113
  55. package/dist/models/tests/AssociatedTestModel.d.ts +0 -12
  56. package/dist/models/tests/AssociatedTestModel.js +0 -71
  57. package/dist/models/tests/TestModel.d.ts +0 -12
  58. package/dist/models/tests/TestModel.js +0 -69
  59. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +0 -10
  60. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +0 -53
  61. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +0 -13
  62. package/dist/models/tests/contextAwareModels/ContextTestModel.js +0 -47
  63. package/dist/repository/definition.d.ts +0 -36
  64. package/dist/repository/definition.js +0 -121
  65. package/dist/repository/entries.d.ts +0 -13
  66. package/dist/repository/entries.js +0 -92
  67. package/dist/repository/utils/formatValues.d.ts +0 -3
  68. package/dist/repository/utils/formatValues.js +0 -16
  69. package/dist/repository/value.d.ts +0 -28
  70. package/dist/repository/value.js +0 -124
  71. package/dist/scopes/filter.d.ts +0 -30
  72. package/dist/scopes/filter.js +0 -75
  73. package/dist/scopes/helpers/filter.helpers.d.ts +0 -42
  74. package/dist/scopes/helpers/filter.helpers.js +0 -204
  75. package/dist/scopes/index.d.ts +0 -2
  76. package/dist/scopes/index.js +0 -6
  77. package/dist/tests/api/test-api.d.ts +0 -2
  78. package/dist/tests/api/test-api.js +0 -38
  79. package/dist/tests/functional/searching/index.d.ts +0 -8
  80. package/dist/tests/functional/searching/index.js +0 -44
  81. package/dist/tests/helpers/commonHooks.d.ts +0 -5
  82. package/dist/tests/helpers/commonHooks.js +0 -55
  83. package/dist/tests/helpers/database-config.d.ts +0 -16
  84. package/dist/tests/helpers/database-config.js +0 -17
  85. package/dist/tests/helpers/index.d.ts +0 -7
  86. package/dist/tests/helpers/index.js +0 -29
  87. package/dist/tests/mocks/definition.mock.d.ts +0 -48
  88. package/dist/tests/mocks/definition.mock.js +0 -78
  89. package/dist/tests/mocks/events.mock.d.ts +0 -4
  90. package/dist/tests/mocks/events.mock.js +0 -21
  91. package/dist/tests/mocks/testModel.d.ts +0 -12
  92. package/dist/tests/mocks/testModel.js +0 -35
  93. package/dist/types/definition/index.d.ts +0 -25
  94. package/dist/types/definition/index.js +0 -2
  95. package/dist/types/entries/index.d.ts +0 -25
  96. package/dist/types/entries/index.js +0 -2
  97. package/dist/types/index.d.ts +0 -34
  98. package/dist/types/index.js +0 -2
  99. package/dist/types/value/index.d.ts +0 -15
  100. package/dist/types/value/index.js +0 -2
  101. package/dist/utils/constants/index.d.ts +0 -19
  102. package/dist/utils/constants/index.js +0 -22
  103. package/dist/utils/db/index.d.ts +0 -4
  104. package/dist/utils/db/index.js +0 -24
  105. package/dist/utils/helpers/index.d.ts +0 -26
  106. package/dist/utils/helpers/index.js +0 -40
  107. package/dist/utils/init.d.ts +0 -7
  108. package/dist/utils/init.js +0 -109
  109. package/dist/utils/logger/index.d.ts +0 -3
  110. package/dist/utils/logger/index.js +0 -42
  111. package/dist/utils/scopeAttributes.d.ts +0 -2
  112. package/dist/utils/scopeAttributes.js +0 -11
  113. package/dist/utils/validations/index.d.ts +0 -8
  114. package/dist/utils/validations/index.js +0 -41
  115. package/dist/utils/validations/schema/custom-fields.d.ts +0 -3
  116. package/dist/utils/validations/schema/custom-fields.js +0 -9
  117. package/dist/utils/validations/type.d.ts +0 -15
  118. package/dist/utils/validations/type.js +0 -2
  119. package/dist/utils/validations/validators/index.d.ts +0 -14
  120. package/dist/utils/validations/validators/index.js +0 -40
  121. package/dist/utils/validations/validators/select.validator.d.ts +0 -5
  122. package/dist/utils/validations/validators/select.validator.js +0 -12
  123. package/dist/utils/validations/validators/status.validator.d.ts +0 -12
  124. package/dist/utils/validations/validators/status.validator.js +0 -15
@@ -1,92 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.updateEntries = exports.findEntriesByModelIds = exports.findEntriesByModelId = void 0;
30
- const models_1 = require("../models");
31
- const logger_1 = __importDefault(require("../utils/logger"));
32
- const errors_1 = require("../errors");
33
- const DefinitionRepo = __importStar(require("./definition"));
34
- const formatValues_1 = require("./utils/formatValues");
35
- const findEntriesByModelId = async (modelId, options = {}) => {
36
- const { transaction } = options;
37
- return models_1.CustomFieldEntries.findOne({
38
- where: { modelId },
39
- transaction,
40
- });
41
- };
42
- exports.findEntriesByModelId = findEntriesByModelId;
43
- const findEntriesByModelIds = async (modelIds, options = {}) => {
44
- const { transaction } = options;
45
- return models_1.CustomFieldEntries.findAll({
46
- where: { modelId: modelIds },
47
- transaction,
48
- });
49
- };
50
- exports.findEntriesByModelIds = findEntriesByModelIds;
51
- const updateEntries = async (modelId, modelType, customFields, identifiers, options = {}) => {
52
- const customFieldsNames = Object.keys(customFields);
53
- logger_1.default.debug(`custom-fields: updating entries for ${modelType} ${modelId}`, {
54
- customFieldsNames,
55
- optionsKeys: options ? Object.keys(options) : null,
56
- customFields,
57
- identifiers,
58
- });
59
- const { modelOptions, transaction } = options;
60
- const where = {
61
- modelType,
62
- name: customFieldsNames,
63
- ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),
64
- };
65
- const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions.include?.(identifiers) }) ?? [];
66
- const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
67
- if (fieldDefinitions.length !== customFieldsNames.length) {
68
- logger_1.default.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names: customFieldsNames, fieldDefinitions });
69
- const missingDefinitions = customFieldsNames.filter((name) => !fieldDefinitions.some((def) => def.name === name));
70
- throw new errors_1.MissingDefinitionError(missingDefinitions);
71
- }
72
- const disabledNames = disabledDefinitions?.map((def) => def.name) || [];
73
- const valuesWithDisabledDefinitions = customFieldsNames.filter((name) => disabledNames.includes(name));
74
- if (valuesWithDisabledDefinitions?.length > 0) {
75
- logger_1.default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);
76
- }
77
- const definitionsByName = Object.fromEntries(fieldDefinitions.map((definition) => [definition.name, definition]));
78
- // If we need to format the value before we save it
79
- Object.entries(customFields)
80
- .filter(([definitionName]) => formatValues_1.formatFunctions[definitionsByName[definitionName].fieldType])
81
- .forEach(([definitionName, value]) => {
82
- const { fieldType } = definitionsByName[definitionName];
83
- customFields[definitionName] = formatValues_1.formatFunctions[fieldType](value);
84
- });
85
- return models_1.CustomFieldEntries.upsert({
86
- modelId,
87
- entityId: fieldDefinitions[0].entityId,
88
- modelType,
89
- customFields,
90
- }, options);
91
- };
92
- exports.updateEntries = updateEntries;
@@ -1,3 +0,0 @@
1
- export declare const formatFunctions: {
2
- date: (value: any) => string;
3
- };
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatFunctions = void 0;
4
- const constants_1 = require("../../utils/constants");
5
- exports.formatFunctions = {
6
- [constants_1.CustomFieldDefinitionType.DATE]: (value) => {
7
- if (value) {
8
- const date = new Date(value);
9
- if (date.toString() === 'Invalid Date') {
10
- throw new Error(`Invalid date value: ${value}`);
11
- }
12
- return date.toISOString();
13
- }
14
- return null;
15
- },
16
- };
@@ -1,28 +0,0 @@
1
- import type { FindOptions } from 'sequelize';
2
- import { CustomFieldValue } from '../models';
3
- import type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
4
- import type { ModelOptions } from '../types';
5
- export declare const findByModelIdAndDefinition: (modelId: string, customFieldDefinitionId: string) => Promise<CustomFieldValue[]>;
6
- export declare const create: (data: CreateCustomFieldValue, withAssociations?: boolean) => Promise<CustomFieldValue>;
7
- export declare const findAllValues: () => Promise<CustomFieldValue[]>;
8
- /**
9
- * Get all values for model instance id (with their definitions)
10
- * @param modelId
11
- * @returns CustomFieldValue[]
12
- */
13
- export declare const findValuesByModelId: (modelId: string) => Promise<CustomFieldValue[]>;
14
- /**
15
- * Retrieves custom field values for given model IDs
16
- * @param modelIds - An array of model IDs to query custom field values for.
17
- * @param options - Optional configuration object.
18
- */
19
- export declare const findValuesByModelIds: (modelIds: string[], options?: any) => Promise<CustomFieldValue[]>;
20
- /**
21
- * Try to update custom field values for a model instance.
22
- * Create new value record if not exists, but fails if value's definition not exist.
23
- * Return the updated values
24
- */
25
- export declare const updateValues: (modelType: string, modelId: string, identifiers: string[], valuesToUpdate: ValuesToUpdate, options?: FindOptions & {
26
- modelOptions?: ModelOptions;
27
- }) => Promise<CustomFieldValue[]>;
28
- export declare const deleteValue: (id: string, options?: any) => Promise<any>;
@@ -1,124 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.deleteValue = exports.updateValues = exports.findValuesByModelIds = exports.findValuesByModelId = exports.findAllValues = exports.create = exports.findByModelIdAndDefinition = void 0;
30
- const models_1 = require("../models");
31
- const DefinitionRepo = __importStar(require("./definition"));
32
- const logger_1 = __importDefault(require("../utils/logger"));
33
- const errors_1 = require("../errors");
34
- const formatValues_1 = require("./utils/formatValues");
35
- const findByModelIdAndDefinition = async (modelId, customFieldDefinitionId) => models_1.CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [models_1.CustomFieldDefinition] });
36
- exports.findByModelIdAndDefinition = findByModelIdAndDefinition;
37
- const create = async (data, withAssociations = false) => {
38
- const created = await models_1.CustomFieldValue.create(data);
39
- if (withAssociations) {
40
- const createdWithAssociations = await (0, exports.findByModelIdAndDefinition)(created.modelId, created.customFieldDefinitionId);
41
- return createdWithAssociations?.[0];
42
- }
43
- return created;
44
- };
45
- exports.create = create;
46
- const findAllValues = async () => models_1.CustomFieldValue.findAll({ include: [models_1.CustomFieldDefinition] });
47
- exports.findAllValues = findAllValues;
48
- /**
49
- * Get all values for model instance id (with their definitions)
50
- * @param modelId
51
- * @returns CustomFieldValue[]
52
- */
53
- const findValuesByModelId = async (modelId) => models_1.CustomFieldValue.findAll({ where: { modelId }, include: [models_1.CustomFieldDefinition] });
54
- exports.findValuesByModelId = findValuesByModelId;
55
- /**
56
- * Retrieves custom field values for given model IDs
57
- * @param modelIds - An array of model IDs to query custom field values for.
58
- * @param options - Optional configuration object.
59
- */
60
- const findValuesByModelIds = async (modelIds, options) => {
61
- const { transaction } = options;
62
- return models_1.CustomFieldValue.findAll({
63
- where: { modelId: modelIds },
64
- transaction,
65
- raw: true,
66
- nest: true,
67
- });
68
- };
69
- exports.findValuesByModelIds = findValuesByModelIds;
70
- /**
71
- * Try to update custom field values for a model instance.
72
- * Create new value record if not exists, but fails if value's definition not exist.
73
- * Return the updated values
74
- */
75
- const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
76
- const names = Object.keys(valuesToUpdate);
77
- logger_1.default.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {
78
- names,
79
- optionsKeys: options ? Object.keys(options) : null,
80
- valuesToUpdate,
81
- identifiers,
82
- });
83
- const { modelOptions, transaction } = options;
84
- const where = {
85
- modelType,
86
- name: names,
87
- ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),
88
- };
89
- const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions.include?.(identifiers) }) ?? [];
90
- const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
91
- if (fieldDefinitions.length !== names.length) {
92
- logger_1.default.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });
93
- const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));
94
- throw new errors_1.MissingDefinitionError(missingDefinitions);
95
- }
96
- const disabledNames = disabledDefinitions?.map((def) => def.name) || [];
97
- const valuesWithDisabledDefinitions = names.filter((name) => disabledNames.includes(name));
98
- if (valuesWithDisabledDefinitions?.length > 0) {
99
- logger_1.default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);
100
- }
101
- const values = names.map((name) => {
102
- const fieldDefinition = fieldDefinitions.find((def) => def.name === name);
103
- const formatFunction = formatValues_1.formatFunctions[fieldDefinition.fieldType];
104
- const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];
105
- return {
106
- modelId,
107
- updatedAt: new Date(),
108
- customFieldDefinitionId: fieldDefinition.id,
109
- value: value !== undefined ? value : fieldDefinition.defaultValue,
110
- };
111
- });
112
- return Promise.all(values.map(async (value) => {
113
- const [cfv] = await models_1.CustomFieldValue.upsert(value, {
114
- transaction: options.transaction,
115
- });
116
- return cfv;
117
- }));
118
- };
119
- exports.updateValues = updateValues;
120
- const deleteValue = (id, options = {}) => models_1.CustomFieldValue.update({ deletedAt: new Date() }, {
121
- where: { id },
122
- transaction: options.transaction,
123
- });
124
- exports.deleteValue = deleteValue;
@@ -1,30 +0,0 @@
1
- import type { CustomFieldOptions } from '../types';
2
- import { type ConditionValue, type CustomFieldFilterOptions } from './helpers/filter.helpers';
3
- type customFieldsFilterScopeParams = {
4
- replacementsMap: Record<string, string>;
5
- scopeValue: Record<string, ConditionValue>;
6
- };
7
- /**
8
- * A Sequelize scope for filtering models by custom fields.
9
- * This scope builds a WHERE clause to be applied on the main query.
10
- *
11
- * @param name - The model type name used to join custom_field_definitions.
12
- * @returns A function that takes conditions and returns the Sequelize options object.
13
- */
14
- export declare const customFieldsFilterScope: (name: string, options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>) => ({ replacementsMap: replacements, scopeValue: conditions }: customFieldsFilterScopeParams) => CustomFieldFilterOptions;
15
- export declare const scopeName: "filterByCustomFields";
16
- export declare const customFieldsSortScope: (name: string, options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>) => ({ replacementsMap, scopeValue: sort }: {
17
- replacementsMap: any;
18
- scopeValue: any;
19
- }) => {
20
- attributes?: undefined;
21
- order?: undefined;
22
- replacements?: undefined;
23
- } | {
24
- attributes: {
25
- include: (string | import("sequelize/types/utils").Literal)[][];
26
- };
27
- order: import("sequelize/types/utils").Literal[];
28
- replacements: any;
29
- };
30
- export {};
@@ -1,75 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.customFieldsSortScope = exports.scopeName = exports.customFieldsFilterScope = void 0;
4
- /* eslint-disable import/prefer-default-export */
5
- const sequelize_1 = require("sequelize");
6
- const sequelize_typescript_1 = require("sequelize-typescript");
7
- const common_types_1 = require("@autofleet/common-types");
8
- const helpers_1 = require("../utils/helpers");
9
- const filter_helpers_1 = require("./helpers/filter.helpers");
10
- const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
11
- /**
12
- * A Sequelize scope for filtering models by custom fields.
13
- * This scope builds a WHERE clause to be applied on the main query.
14
- *
15
- * @param name - The model type name used to join custom_field_definitions.
16
- * @returns A function that takes conditions and returns the Sequelize options object.
17
- */
18
- const customFieldsFilterScope = (name, options) => ({ replacementsMap: replacements, scopeValue: conditions }) => {
19
- if (!conditions || Object.keys(conditions).length === 0) {
20
- return {};
21
- }
22
- const queryType = options?.useCustomFieldsEntries ? filter_helpers_1.SubQueryType.ENTRIES : filter_helpers_1.SubQueryType.VALUES;
23
- const reverseReplacementsMap = new Map(Object.entries(replacements).map(([key, value]) => [value, key]));
24
- // Build the WHERE clause for custom field filtering
25
- const conditionsStrings = Object.entries(conditions).map(([key, condition]) => {
26
- switch (queryType) {
27
- case filter_helpers_1.SubQueryType.ENTRIES:
28
- return (0, filter_helpers_1.formatConditionsForEntries)(key, condition, reverseReplacementsMap);
29
- case filter_helpers_1.SubQueryType.VALUES:
30
- return (0, filter_helpers_1.formatConditionsForValues)(key, condition, reverseReplacementsMap);
31
- default:
32
- return false;
33
- }
34
- }).filter(Boolean);
35
- if (conditionsStrings.length === 0) {
36
- return {};
37
- }
38
- const subQuery = (0, filter_helpers_1.getFilterCustomFieldsSubQuery)(queryType, name, conditionsStrings);
39
- return {
40
- where: {
41
- id: {
42
- [sequelize_1.Op.in]: sequelize_typescript_1.Sequelize.literal(`(${subQuery})`),
43
- },
44
- },
45
- replacements,
46
- };
47
- };
48
- exports.customFieldsFilterScope = customFieldsFilterScope;
49
- exports.scopeName = CUSTOM_FIELDS_FILTER_SCOPE;
50
- const customFieldsSortScope = (name, options) => ({ replacementsMap, scopeValue: sort }) => {
51
- if (!sort || sort.length === 0) {
52
- return {};
53
- }
54
- const queryType = options?.useCustomFieldsEntries ? filter_helpers_1.SubQueryType.ENTRIES : filter_helpers_1.SubQueryType.VALUES;
55
- const randomStr = (0, helpers_1.generateRandomString)();
56
- const includes = Object.entries(sort).map(([key]) => {
57
- const replacementKey = Object.keys(replacementsMap).find((randomString) => replacementsMap[randomString] === key);
58
- return ([
59
- sequelize_typescript_1.Sequelize.literal((0, filter_helpers_1.getSortCustomFieldsSubQuery)(queryType, name, replacementKey)),
60
- randomStr,
61
- ]);
62
- });
63
- const orders = Object.entries(sort).map(([, sortObject]) => {
64
- const direction = typeof sortObject === 'string' ? sortObject : Object.values(sortObject)[0];
65
- return sequelize_typescript_1.Sequelize.literal(`"${randomStr}" ${direction || 'ASC'}`);
66
- });
67
- return {
68
- attributes: {
69
- include: includes,
70
- },
71
- order: orders,
72
- replacements: replacementsMap,
73
- };
74
- };
75
- exports.customFieldsSortScope = customFieldsSortScope;
@@ -1,42 +0,0 @@
1
- import type { WhereOptions } from 'sequelize';
2
- /**
3
- * Type representing possible condition values.
4
- * Currently supporting strings and arrays of strings.
5
- * More types to be added (TBA).
6
- */
7
- export type ConditionWithOperator = {
8
- operator: string;
9
- value: string;
10
- };
11
- export type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
12
- export type CustomFieldSort = {
13
- field: string;
14
- direction: 'ASC' | 'DESC';
15
- };
16
- export type CustomFieldFilterOptions = {
17
- where?: WhereOptions;
18
- replacements?: Record<string, string>;
19
- };
20
- export declare enum SubQueryType {
21
- VALUES = "values",
22
- ENTRIES = "entries"
23
- }
24
- export declare const isConditionStringArray: (input: any) => input is string[];
25
- export declare const isBooleanString: (input: string) => boolean;
26
- export declare const isDate: (input: any) => input is Date;
27
- export declare const castValueToJsonb: (value: string, type: string) => string;
28
- export declare const castValueToJsonbText: (value: string) => string;
29
- export declare const castValueToJsonbBoolean: (value: string) => string;
30
- export declare const castValueToJsonbNumeric: (value: string) => string;
31
- export declare const castIfNeeded: (columnName: string, conditionValue: string) => string;
32
- export declare const AND_DELIMITER = " AND ";
33
- export declare const OR_DELIMITER = " OR ";
34
- export declare const CD_TABLE_ALIAS = "cd";
35
- export declare const CD_NAME_COLUMN = "cd.name";
36
- export declare const CV_TABLE_ALIAS = "cv";
37
- export declare const CV_VALUE_COLUMN = "cv.value";
38
- export declare const CE_TABLE_ALIAS = "ce";
39
- export declare const getFilterCustomFieldsSubQuery: (queryType: SubQueryType, modelType: string, conditionsStrings: Array<string | boolean>) => string;
40
- export declare const getSortCustomFieldsSubQuery: (queryType: SubQueryType, modelType: string, replacementKey: string) => string;
41
- export declare const formatConditionsForValues: (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>) => string | false;
42
- export declare const formatConditionsForEntries: (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>) => string | false;
@@ -1,204 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatConditionsForEntries = exports.formatConditionsForValues = exports.getSortCustomFieldsSubQuery = exports.getFilterCustomFieldsSubQuery = exports.CE_TABLE_ALIAS = exports.CV_VALUE_COLUMN = exports.CV_TABLE_ALIAS = exports.CD_NAME_COLUMN = exports.CD_TABLE_ALIAS = exports.OR_DELIMITER = exports.AND_DELIMITER = exports.castIfNeeded = exports.castValueToJsonbNumeric = exports.castValueToJsonbBoolean = exports.castValueToJsonbText = exports.castValueToJsonb = exports.isDate = exports.isBooleanString = exports.isConditionStringArray = exports.SubQueryType = void 0;
4
- var SubQueryType;
5
- (function (SubQueryType) {
6
- SubQueryType["VALUES"] = "values";
7
- SubQueryType["ENTRIES"] = "entries";
8
- })(SubQueryType || (exports.SubQueryType = SubQueryType = {}));
9
- const isConditionStringArray = (input) => Array.isArray(input) && typeof input[0] === 'string';
10
- exports.isConditionStringArray = isConditionStringArray;
11
- const isBooleanString = (input) => ['true', 'false'].includes(input.toString());
12
- exports.isBooleanString = isBooleanString;
13
- const isDate = (input) => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
14
- exports.isDate = isDate;
15
- const castValueToJsonb = (value, type) => `to_jsonb(${value}::${type})`;
16
- exports.castValueToJsonb = castValueToJsonb;
17
- const castValueToJsonbText = (value) => (0, exports.castValueToJsonb)(value, 'text');
18
- exports.castValueToJsonbText = castValueToJsonbText;
19
- const castValueToJsonbBoolean = (value) => (0, exports.castValueToJsonb)(value, 'boolean');
20
- exports.castValueToJsonbBoolean = castValueToJsonbBoolean;
21
- const castValueToJsonbNumeric = (value) => (0, exports.castValueToJsonb)(value, 'numeric');
22
- exports.castValueToJsonbNumeric = castValueToJsonbNumeric;
23
- const castIfNeeded = (columnName, conditionValue) => {
24
- if ((0, exports.isDate)(conditionValue)) {
25
- return (0, exports.castValueToJsonb)(columnName, 'timestamp');
26
- }
27
- return columnName;
28
- };
29
- exports.castIfNeeded = castIfNeeded;
30
- exports.AND_DELIMITER = ' AND ';
31
- exports.OR_DELIMITER = ' OR ';
32
- exports.CD_TABLE_ALIAS = 'cd';
33
- exports.CD_NAME_COLUMN = `${exports.CD_TABLE_ALIAS}.name`;
34
- exports.CV_TABLE_ALIAS = 'cv';
35
- exports.CV_VALUE_COLUMN = `${exports.CV_TABLE_ALIAS}.value`;
36
- exports.CE_TABLE_ALIAS = 'ce';
37
- const getSingleConditionWithOperator = (value, operator, replacementKey, reverseReplacementsMap) => {
38
- let type = 'text';
39
- if ((0, exports.isDate)(value)) {
40
- type = 'date';
41
- }
42
- else if (!Number.isNaN(Number(value))) {
43
- type = 'numeric';
44
- }
45
- else if ((0, exports.isBooleanString)(value)) {
46
- type = 'boolean';
47
- }
48
- const replacedValue = reverseReplacementsMap.get(value);
49
- return `(jsonb_extract_path_text(${exports.CE_TABLE_ALIAS}.custom_fields, :${replacementKey})::${type}) ${operator} :${replacedValue}`;
50
- };
51
- const getFormattedValue = (value) => {
52
- let formattedValue = value;
53
- if ((0, exports.isBooleanString)(value)) {
54
- formattedValue = value === 'true';
55
- }
56
- else if (!Number.isNaN(Number(value))) {
57
- formattedValue = Number(value);
58
- }
59
- return formattedValue;
60
- };
61
- const getJSONSubQuery = (value, key) => {
62
- const formattedValue = getFormattedValue(value);
63
- const jsonQuery = JSON.stringify({ [key]: formattedValue });
64
- let jsonQueryWithStringBoolean;
65
- if ((0, exports.isBooleanString)(value)) {
66
- jsonQueryWithStringBoolean = `${exports.CE_TABLE_ALIAS}.custom_fields @> '${JSON.stringify({ [key]: value })}'`;
67
- }
68
- return `
69
- (
70
- ${jsonQueryWithStringBoolean ? `${jsonQueryWithStringBoolean} OR` : ''}
71
- ${exports.CE_TABLE_ALIAS}.custom_fields @> '${jsonQuery}'
72
- )
73
- `;
74
- };
75
- const getFilterCustomFieldsSubQuery = (queryType, modelType, conditionsStrings) => {
76
- switch (queryType) {
77
- case SubQueryType.VALUES:
78
- return `
79
- SELECT ${exports.CV_TABLE_ALIAS}.model_id
80
- FROM custom_field_values AS ${exports.CV_TABLE_ALIAS}
81
- INNER JOIN custom_field_definitions AS ${exports.CD_TABLE_ALIAS} ON ${exports.CV_TABLE_ALIAS}.custom_field_definition_id = ${exports.CD_TABLE_ALIAS}.id
82
- ${exports.AND_DELIMITER}${exports.CD_TABLE_ALIAS}.model_type = '${modelType}'
83
- WHERE ${conditionsStrings.join(exports.OR_DELIMITER)}
84
- ${exports.AND_DELIMITER}${exports.CV_TABLE_ALIAS}.deleted_at IS NULL${exports.AND_DELIMITER}${exports.CD_TABLE_ALIAS}.deleted_at IS NULL
85
- GROUP BY ${exports.CV_TABLE_ALIAS}.model_id
86
- HAVING COUNT(DISTINCT ${exports.CV_TABLE_ALIAS}.custom_field_definition_id) = ${conditionsStrings.length}
87
- `.replace(/\n/g, '');
88
- case SubQueryType.ENTRIES:
89
- return `
90
- SELECT ce.model_id
91
- FROM custom_field_entries ce
92
- JOIN custom_field_definitions cfd
93
- ON ce.model_type = cfd.model_type
94
- AND ce.entity_id = cfd.entity_id
95
- WHERE
96
- cfd.deleted_at IS NULL AND
97
- ${conditionsStrings.join(exports.AND_DELIMITER)}
98
- `;
99
- default:
100
- throw new Error('Invalid query type');
101
- }
102
- };
103
- exports.getFilterCustomFieldsSubQuery = getFilterCustomFieldsSubQuery;
104
- const getSortCustomFieldsSubQuery = (queryType, modelType, replacementKey) => {
105
- switch (queryType) {
106
- case SubQueryType.VALUES:
107
- return `(
108
- SELECT value
109
- FROM (SELECT cv.model_id, cv.value
110
- FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
111
- ON cv.custom_field_definition_id = cd.id
112
- ${exports.AND_DELIMITER}cd.model_type = '${modelType}'
113
- WHERE cv.model_id = "${modelType}"."id"
114
- ${exports.AND_DELIMITER}cd.name = :${replacementKey}
115
- ) AS CustomFieldAggregation
116
- )
117
- `;
118
- case SubQueryType.ENTRIES:
119
- return `(
120
- SELECT
121
- customFields.value
122
- FROM
123
- custom_field_entries AS ${exports.CE_TABLE_ALIAS},
124
- jsonb_each_text(custom_fields) AS customFields
125
- WHERE
126
- customFields.key = :${replacementKey}${exports.AND_DELIMITER}
127
- ${exports.CE_TABLE_ALIAS}.model_type = '${modelType}'${exports.AND_DELIMITER}
128
- ${exports.CE_TABLE_ALIAS}.model_id = "${modelType}"."id"
129
- )
130
- `;
131
- default:
132
- throw new Error('Invalid query type');
133
- }
134
- };
135
- exports.getSortCustomFieldsSubQuery = getSortCustomFieldsSubQuery;
136
- const formatConditionsForValues = (key, condition, reverseReplacementsMap) => {
137
- const replacementKey = reverseReplacementsMap.get(key);
138
- if (!replacementKey) {
139
- return false;
140
- }
141
- const columnCondition = `(${exports.CD_NAME_COLUMN} = :${replacementKey})`;
142
- if (Array.isArray(condition)) {
143
- if (condition.length === 0) {
144
- // if empty array, the condition is ignored
145
- return false;
146
- }
147
- if ((0, exports.isConditionStringArray)(condition)) {
148
- const values = condition.flatMap((v) => {
149
- const valRandom = reverseReplacementsMap.get(v);
150
- if ((0, exports.isBooleanString)(v)) {
151
- return [(0, exports.castValueToJsonbText)(`:${valRandom}`), (0, exports.castValueToJsonbBoolean)(`:${valRandom}`)];
152
- }
153
- if (!Number.isNaN(Number(v))) {
154
- return (0, exports.castValueToJsonbNumeric)(`:${valRandom}`);
155
- }
156
- return (0, exports.castValueToJsonbText)(`:${valRandom}`);
157
- }).join(',');
158
- return `(${columnCondition}${exports.AND_DELIMITER}${exports.CV_VALUE_COLUMN} IN (${values}))`;
159
- }
160
- return condition.map((c) => {
161
- const valRep = reverseReplacementsMap.get(c.value);
162
- const valueAsJsonb = (0, exports.castValueToJsonbText)(`:${valRep}`);
163
- return `(${columnCondition}${exports.AND_DELIMITER}${(0, exports.castIfNeeded)(exports.CV_VALUE_COLUMN, c.value)} ${c.operator} ${valueAsJsonb})`;
164
- }).join(exports.AND_DELIMITER);
165
- }
166
- if (typeof condition === 'string' || typeof condition === 'number') {
167
- const conditionRep = reverseReplacementsMap.get(condition);
168
- const valueAsJsonb = !Number.isNaN(Number(condition)) ? (0, exports.castValueToJsonbNumeric)(`:${conditionRep}`) : (0, exports.castValueToJsonbText)(`:${conditionRep}`);
169
- const valueAsJsonbBoolean = (0, exports.isBooleanString)(condition) ? `${exports.OR_DELIMITER}${exports.CV_VALUE_COLUMN} = ${(0, exports.castValueToJsonbBoolean)(`:${conditionRep}`)}` : '';
170
- return `(${columnCondition}${exports.AND_DELIMITER}(${(0, exports.castIfNeeded)(exports.CV_VALUE_COLUMN, condition)} = ${valueAsJsonb}${valueAsJsonbBoolean}))`;
171
- }
172
- if (condition?.operator) {
173
- const valueRep = reverseReplacementsMap.get(condition.value);
174
- const valueAsJsonb = (0, exports.castValueToJsonbText)(`:${valueRep}`);
175
- return `( ${columnCondition}${exports.AND_DELIMITER}${(0, exports.castIfNeeded)(exports.CV_VALUE_COLUMN, condition.value)} ${condition.operator} ${valueAsJsonb})`;
176
- }
177
- return false;
178
- };
179
- exports.formatConditionsForValues = formatConditionsForValues;
180
- const formatConditionsForEntries = (key, condition, reverseReplacementsMap) => {
181
- const replacementKey = reverseReplacementsMap.get(key);
182
- if (!replacementKey) {
183
- return false;
184
- }
185
- if (Array.isArray(condition)) {
186
- if (condition.length === 0) {
187
- // if empty array, the condition is ignored
188
- return false;
189
- }
190
- if ((0, exports.isConditionStringArray)(condition)) {
191
- const values = condition.map((value) => getJSONSubQuery(value, key)).join(`${exports.OR_DELIMITER}\n`);
192
- return `( ${values})`;
193
- }
194
- return condition.map((c) => getSingleConditionWithOperator(c.value, c.operator, replacementKey, reverseReplacementsMap)).join(exports.AND_DELIMITER);
195
- }
196
- if (typeof condition === 'string' || typeof condition === 'number') {
197
- return getJSONSubQuery(condition, key);
198
- }
199
- if (condition?.operator) {
200
- return getSingleConditionWithOperator(condition.value, condition.operator, replacementKey, reverseReplacementsMap);
201
- }
202
- return false;
203
- };
204
- exports.formatConditionsForEntries = formatConditionsForEntries;
@@ -1,2 +0,0 @@
1
- import { customFieldsFilterScope } from './filter';
2
- export { customFieldsFilterScope, };
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.customFieldsFilterScope = void 0;
4
- /* eslint-disable import/prefer-default-export */
5
- const filter_1 = require("./filter");
6
- Object.defineProperty(exports, "customFieldsFilterScope", { enumerable: true, get: function () { return filter_1.customFieldsFilterScope; } });
@@ -1,2 +0,0 @@
1
- declare const app: import("express-serve-static-core").Express;
2
- export default app;