@autofleet/sadot 0.6.6 → 0.6.7-beta.1

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 (38) hide show
  1. package/dist/api/v1/definition/validations.js +4 -21
  2. package/dist/hooks/create.d.ts +1 -1
  3. package/dist/hooks/enrich.d.ts +1 -1
  4. package/dist/hooks/update.d.ts +1 -1
  5. package/dist/index.d.ts +3 -2
  6. package/dist/index.js +4 -2
  7. package/dist/models/CustomFieldDefinition.d.ts +1 -1
  8. package/dist/models/CustomFieldDefinition.js +6 -11
  9. package/dist/models/CustomFieldValue.js +8 -3
  10. package/dist/repository/definition.d.ts +2 -2
  11. package/dist/repository/value.d.ts +2 -2
  12. package/dist/scopes/filter.d.ts +2 -7
  13. package/dist/scopes/filter.js +19 -38
  14. package/dist/tests/mocks/definition.mock.d.ts +3 -3
  15. package/dist/tests/mocks/definition.mock.js +10 -8
  16. package/dist/types/index.d.ts +2 -2
  17. package/dist/utils/constants/index.d.ts +0 -13
  18. package/dist/utils/constants/index.js +2 -15
  19. package/dist/utils/helpers/index.d.ts +3 -3
  20. package/dist/utils/helpers/index.js +3 -3
  21. package/dist/utils/validations/{schema/custom-fields.js → custom-fields.js} +1 -0
  22. package/dist/utils/validations/custom.d.ts +15 -0
  23. package/dist/utils/validations/custom.js +42 -0
  24. package/dist/utils/validations/index.d.ts +2 -2
  25. package/dist/utils/validations/index.js +15 -15
  26. package/dist/utils/validations/type.d.ts +14 -10
  27. package/dist/utils/validations/type.js +48 -0
  28. package/dist/utils/validations/validators.d.ts +12 -0
  29. package/dist/utils/validations/validators.js +33 -0
  30. package/package.json +2 -2
  31. package/src/scopes/filter.ts +10 -13
  32. package/dist/utils/validations/validators/index.d.ts +0 -14
  33. package/dist/utils/validations/validators/index.js +0 -33
  34. package/dist/utils/validations/validators/select.validator.d.ts +0 -5
  35. package/dist/utils/validations/validators/select.validator.js +0 -9
  36. package/dist/utils/validations/validators/status.validator.d.ts +0 -12
  37. package/dist/utils/validations/validators/status.validator.js +0 -9
  38. /package/dist/utils/validations/{schema/custom-fields.d.ts → custom-fields.d.ts} +0 -0
@@ -5,34 +5,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.validateCustomFieldDefinitionUpdate = exports.validateCustomFieldDefinitionCreation = void 0;
7
7
  const joi_1 = __importDefault(require("joi"));
8
- const constants_1 = require("../../../utils/constants");
9
- const statusValidationObjectSchema = joi_1.default.array().items(joi_1.default.object({
10
- value: joi_1.default.string().required(),
11
- color: joi_1.default.string().required(),
12
- })).min(1).unique('value');
13
- /**
14
- * Schema for the validation of custom field definition
15
- * The only custom validation is for
16
- * {@link CustomFieldDefinitionType.SELECT SELECT}
17
- * and
18
- * {@link CustomFieldDefinitionType.STATUS STATUS}
19
- * field types.
20
- * The rest of the field types are validated by Joi
21
- */
8
+ const type_1 = require("../../../utils/validations/type");
22
9
  const ValidationSchema = joi_1.default.when('fieldType', {
23
- is: constants_1.CustomFieldDefinitionType.SELECT,
10
+ is: type_1.CustomFieldDefinitionType.SELECT,
24
11
  then: joi_1.default.array().items(joi_1.default.string()).min(1).unique(),
25
12
  otherwise: joi_1.default.any(),
26
- }).when('fieldType', {
27
- is: constants_1.CustomFieldDefinitionType.STATUS,
28
- then: statusValidationObjectSchema,
29
- otherwise: joi_1.default.any(),
30
13
  });
31
14
  const CustomFieldDefinitionCreationSchema = joi_1.default.object({
32
15
  name: joi_1.default.string().required(),
33
16
  displayName: joi_1.default.string().required(),
34
17
  validation: ValidationSchema,
35
- fieldType: joi_1.default.string().valid(...Object.values(constants_1.CustomFieldDefinitionType)).required(),
18
+ fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)).required(),
36
19
  entityId: joi_1.default.string().guid().required(),
37
20
  entityType: joi_1.default.string().required(),
38
21
  description: joi_1.default.string(),
@@ -42,7 +25,7 @@ const CustomFieldDefinitionCreationSchema = joi_1.default.object({
42
25
  const CustomFieldDefinitionUpdateSchema = joi_1.default.object({
43
26
  displayName: joi_1.default.string(),
44
27
  validation: ValidationSchema,
45
- fieldType: joi_1.default.string().valid(...Object.values(constants_1.CustomFieldDefinitionType)),
28
+ fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)),
46
29
  description: joi_1.default.string().allow(null),
47
30
  required: joi_1.default.boolean(),
48
31
  disabled: joi_1.default.boolean(),
@@ -1,4 +1,4 @@
1
- import type { ModelOptions } from '../types';
1
+ import { ModelOptions } from '../types';
2
2
  /**
3
3
  * A hook to create the custom fields when updating a model (more then one instance).
4
4
  */
@@ -1,4 +1,4 @@
1
- import type { ModelOptions } from '../types';
1
+ import { ModelOptions } from '../types';
2
2
  type SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';
3
3
  /**
4
4
  * A hook to attach the custom fields when fetching a model instances.
@@ -1,4 +1,4 @@
1
- import type { ModelOptions } from '../types';
1
+ import { ModelOptions } from '../types';
2
2
  /**
3
3
  * A hook to update the custom fields when updating a model (more then one instance).
4
4
  */
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { Application } from 'express';
2
- import type { Sequelize } from 'sequelize-typescript';
2
+ import { Sequelize } from 'sequelize-typescript';
3
3
  import type { CustomFieldOptions, ModelFetcher } from './types';
4
- export * from './utils/validations/schema/custom-fields';
4
+ export * from './utils/validations/custom-fields';
5
5
  export * from './utils/constants';
6
6
  export * from './utils/helpers';
7
+ export { CustomFieldDefinitionType } from './utils/validations/type';
7
8
  /**
8
9
  * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
9
10
  * @see {@link 'custom-fields/config'} for configurations
package/dist/index.js CHANGED
@@ -17,15 +17,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.disableCustomFields = void 0;
20
+ exports.disableCustomFields = exports.CustomFieldDefinitionType = void 0;
21
21
  const models_1 = require("./models");
22
22
  const api_1 = __importDefault(require("./api"));
23
23
  const db_1 = __importDefault(require("./utils/db"));
24
24
  const logger_1 = __importDefault(require("./utils/logger"));
25
25
  const init_1 = require("./utils/init");
26
- __exportStar(require("./utils/validations/schema/custom-fields"), exports);
26
+ __exportStar(require("./utils/validations/custom-fields"), exports);
27
27
  __exportStar(require("./utils/constants"), exports);
28
28
  __exportStar(require("./utils/helpers"), exports);
29
+ var type_1 = require("./utils/validations/type");
30
+ Object.defineProperty(exports, "CustomFieldDefinitionType", { enumerable: true, get: function () { return type_1.CustomFieldDefinitionType; } });
29
31
  /**
30
32
  * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
31
33
  * @see {@link 'custom-fields/config'} for configurations
@@ -1,5 +1,5 @@
1
1
  import { Model } from 'sequelize-typescript';
2
- import { CustomFieldDefinitionType } from '../utils/constants';
2
+ import { CustomFieldDefinitionType } from '../utils/validations/type';
3
3
  import { CustomFieldValue } from '.';
4
4
  declare class CustomFieldDefinition extends Model {
5
5
  id: string;
@@ -8,17 +8,15 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ /* eslint-disable @typescript-eslint/no-unused-vars */
13
+ /* eslint-disable indent */
15
14
  const sequelize_typescript_1 = require("sequelize-typescript");
16
- const constants_1 = require("../utils/constants");
17
- const validators_1 = require("../utils/validations/validators");
15
+ const custom_1 = require("../utils/validations/custom");
16
+ const type_1 = require("../utils/validations/type");
18
17
  const _1 = require(".");
19
18
  const events_1 = require("../events");
20
19
  const errors_1 = require("../errors");
21
- const logger_1 = __importDefault(require("../utils/logger"));
22
20
  let CustomFieldDefinition = class CustomFieldDefinition extends sequelize_typescript_1.Model {
23
21
  static displayNameDefaultValue(instance) {
24
22
  if (!instance?.displayName) {
@@ -59,7 +57,7 @@ __decorate([
59
57
  ], CustomFieldDefinition.prototype, "displayName", void 0);
60
58
  __decorate([
61
59
  (0, sequelize_typescript_1.Is)('SupportedType', (value) => {
62
- if (!Object.values(constants_1.CustomFieldDefinitionType).includes(value)) {
60
+ if (!Object.values(type_1.CustomFieldDefinitionType).includes(value)) {
63
61
  throw new errors_1.UnsupportedCustomFieldTypeError(`"${value}" is not a supported type.`);
64
62
  }
65
63
  }),
@@ -157,10 +155,7 @@ CustomFieldDefinition = __decorate([
157
155
  timestamps: true,
158
156
  validate: {
159
157
  validationByType() {
160
- // Verify the validation is provided if needed
161
- if (!this.validation && validators_1.CustomValidationTypes[this.fieldType]) {
162
- // TODO: enforce the validation-object schema based on the fieldType
163
- logger_1.default.error(`No custom validation for custom field type ${this.fieldType} found`);
158
+ if (!(0, custom_1.validateValidation)(this.fieldType, this.validation)) {
164
159
  throw new errors_1.UnsupportedCustomValidationError(`Validation provided for "${this.fieldType}" is not supported`);
165
160
  }
166
161
  },
@@ -31,11 +31,16 @@ var __importStar = (this && this.__importStar) || function (mod) {
31
31
  var __metadata = (this && this.__metadata) || function (k, v) {
32
32
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33
33
  };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
34
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
+ /* eslint-disable @typescript-eslint/no-unused-vars */
39
+ /* eslint-disable indent */
35
40
  const sequelize_typescript_1 = require("sequelize-typescript");
36
41
  const events_1 = require("../events");
37
42
  const _1 = require(".");
38
- const validations_1 = require("../utils/validations");
43
+ const validations_1 = __importDefault(require("../utils/validations"));
39
44
  const CustomFieldDefinitionRepo = __importStar(require("../repository/definition"));
40
45
  const errors_1 = require("../errors");
41
46
  let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Model {
@@ -49,7 +54,7 @@ let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Mod
49
54
  instances.forEach((instance) => {
50
55
  const { validation, fieldType, } = definitions
51
56
  .find((definition) => definition.id === instance.customFieldDefinitionId);
52
- const isValid = (0, validations_1.validateValue)(instance.value, fieldType, validation);
57
+ const isValid = (0, validations_1.default)(instance.value, fieldType, validation);
53
58
  if (!isValid) {
54
59
  throw new errors_1.InvalidValueError(instance.value, fieldType);
55
60
  }
@@ -60,7 +65,7 @@ let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Mod
60
65
  // eslint-disable-next-line max-len
61
66
  const cfd = await CustomFieldDefinitionRepo.findById(customFieldDefinitionId, { withDisabled: true });
62
67
  const { validation, fieldType } = cfd;
63
- const isValid = (0, validations_1.validateValue)(instance.value, fieldType, validation);
68
+ const isValid = (0, validations_1.default)(instance.value, fieldType, validation);
64
69
  if (!isValid) {
65
70
  throw new errors_1.InvalidValueError(instance.value, fieldType);
66
71
  }
@@ -1,7 +1,7 @@
1
- import { type FindOptions, type WhereOptions } from 'sequelize';
1
+ import { FindOptions, WhereOptions } from 'sequelize';
2
2
  import { CustomFieldDefinition } from '../models';
3
3
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
4
- import type { ModelOptions } from '../types';
4
+ import { ModelOptions } from '../types';
5
5
  export declare const create: (data: CreateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
6
6
  export declare const findAll: (where: WhereOptions, options?: any) => Promise<CustomFieldDefinition[]>;
7
7
  export declare const findByIds: (ids: string[], options?: any) => Promise<CustomFieldDefinition[]>;
@@ -1,7 +1,7 @@
1
1
  import type { FindOptions } from 'sequelize';
2
2
  import { CustomFieldValue } from '../models';
3
- import type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
4
- import type { ModelOptions } from '../types';
3
+ import { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
4
+ import { ModelOptions } from '../types';
5
5
  export declare const findByModelIdAndDefinition: (modelId: string, customFieldDefinitionId: string) => Promise<CustomFieldValue[]>;
6
6
  export declare const create: (data: CreateCustomFieldValue, withAssociations?: boolean) => Promise<CustomFieldValue>;
7
7
  export declare const findAllValues: () => Promise<CustomFieldValue[]>;
@@ -1,14 +1,10 @@
1
- import { type WhereOptions } from 'sequelize';
1
+ import { WhereOptions } from 'sequelize';
2
2
  /**
3
3
  * Type representing possible condition values.
4
4
  * Currently supporting strings and arrays of strings.
5
5
  * More types to be added (TBA).
6
6
  */
7
- type ConditionWithOperator = {
8
- operator: string;
9
- value: string;
10
- };
11
- export type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
7
+ export type ConditionValue = string | string[];
12
8
  export type CustomFieldSort = {
13
9
  field: string;
14
10
  direction: 'ASC' | 'DESC';
@@ -34,4 +30,3 @@ export declare const customFieldsSortScope: (name: string) => (sort: CustomField
34
30
  };
35
31
  order: import("sequelize/types/utils").Literal[];
36
32
  };
37
- export {};
@@ -6,13 +6,6 @@ const sequelize_1 = require("sequelize");
6
6
  const sequelize_typescript_1 = require("sequelize-typescript");
7
7
  const common_types_1 = require("@autofleet/common-types");
8
8
  const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
9
- const castIfNeeded = (conditionValue) => {
10
- if (!Number.isNaN(Date.parse(conditionValue))) {
11
- return '::timestamp';
12
- }
13
- return '';
14
- };
15
- const AND_DELIMETER = ' AND ';
16
9
  /**
17
10
  * A Sequelize scope for filtering models by custom fields.
18
11
  * This scope builds a WHERE clause to be applied on the main query.
@@ -26,39 +19,30 @@ const customFieldsFilterScope = (name) => (conditions) => {
26
19
  }
27
20
  // Build the WHERE clause for custom field filtering
28
21
  const conditionsStrings = Object.entries(conditions)
29
- .map(([key, condition]) => {
30
- if (Array.isArray(condition)) {
31
- if (condition.length === 0) {
22
+ .map(([key, value]) => {
23
+ if (Array.isArray(value)) {
24
+ if (value.length === 0) {
32
25
  // if empty array, the condition is ignored
33
26
  return false;
34
27
  }
35
- if (typeof condition[0] === 'string') {
36
- const values = condition.map((v) => `'${v}'`).join(',');
37
- return `(custom_fields->>'${key}') IN (${values})`;
38
- }
39
- return condition
40
- .map((c) => `(custom_fields->>'${key}')${castIfNeeded(c.value)} ${c.operator} '${c.value}'`).join(AND_DELIMETER);
41
- }
42
- if (typeof condition === 'string') {
43
- return `(custom_fields->>'${key}')${castIfNeeded(condition)} = '${condition}'`;
44
- }
45
- if (condition?.operator) {
46
- return `(custom_fields->>'${key}')${castIfNeeded(condition.value)} ${condition.operator} '${condition.value}'`;
28
+ const values = value.map((v) => `'${v}'`).join(',');
29
+ return `custom_fields->>'${key}' IN (${values})`;
47
30
  }
48
- return false;
31
+ return `custom_fields->>'${key}' = '${value}'`;
49
32
  })
50
33
  .filter(Boolean);
51
34
  if (conditionsStrings.length === 0) {
52
35
  return {};
53
36
  }
54
- const customFieldConditions = conditionsStrings.join(AND_DELIMETER);
37
+ const customFieldConditions = conditionsStrings.join(' AND ');
55
38
  const subQuery = `${'SELECT model_id FROM ('
56
39
  + 'SELECT cv.model_id, jsonb_object_agg(cd.name, cv.value) AS custom_fields '
57
40
  + 'FROM custom_field_values AS cv '
58
41
  + 'INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id '
59
42
  + `AND cd.model_type = '${name}' `
60
43
  + 'GROUP BY cv.model_id'
61
- + ') AS CustomFieldAggregation WHERE '}${customFieldConditions}`;
44
+ + ') AS CustomFieldAggregation '
45
+ + 'WHERE '}${customFieldConditions}`;
62
46
  return {
63
47
  where: {
64
48
  id: {
@@ -75,19 +59,16 @@ const customFieldsSortScope = (name) => (sort) => {
75
59
  }
76
60
  const includes = Object.entries(sort).map(([key]) => ([
77
61
  sequelize_typescript_1.Sequelize.literal(`(
78
- SELECT custom_fields->>'${key}'
79
- FROM (
80
- SELECT
81
- cv.model_id,
82
- jsonb_object_agg(cd.name, cv.value) AS custom_fields
83
- FROM custom_field_values AS cv
84
- INNER JOIN custom_field_definitions AS cd
85
- ON cv.custom_field_definition_id = cd.id
86
- AND cd.model_type = '${name}'
87
- WHERE cv.model_id = "${name}"."id"
88
- GROUP BY cv.model_id
89
- ) AS CustomFieldAggregation
90
- )`),
62
+ SELECT value
63
+ FROM (SELECT cv.model_id, cv.value
64
+ FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
65
+ ON cv.custom_field_definition_id = cd.id
66
+ AND cd.model_type = '${name}'
67
+ WHERE cv.model_id = "${name}"."id"
68
+ AND cd.name = '${key}'
69
+ ) AS CustomFieldAggregation
70
+ )
71
+ `),
91
72
  `customFields_${key}`,
92
73
  ]));
93
74
  const orders = Object.entries(sort).map(([key, value]) => sequelize_typescript_1.Sequelize.literal(`"customFields_${key}" ${value}`));
@@ -1,4 +1,4 @@
1
- import type { CreateCustomFieldDefinition, CustomFieldDefinitionDTO } from '../../types/definition';
1
+ import { CreateCustomFieldDefinition, CustomFieldDefinitionDTO } from '../../types/definition';
2
2
  export declare const contextAwareFieldDefinition: {
3
3
  name: string;
4
4
  modelType: string;
@@ -37,7 +37,7 @@ export declare const coolFieldDefinition3: {
37
37
  modelType: string;
38
38
  };
39
39
  export declare const booleanField: (modelType: string) => CreateCustomFieldDefinition;
40
- export declare const selectField: (modelType: string, options: any) => CreateCustomFieldDefinition;
41
- export declare const statusField: (modelType: string, options: any) => CreateCustomFieldDefinition;
40
+ export declare const enumField: (modelType: string, options: any) => CreateCustomFieldDefinition;
41
+ export declare const rangeField: (modelType: string) => CreateCustomFieldDefinition;
42
42
  export declare const createDefinition: (defaults: Partial<CustomFieldDefinitionDTO>) => CreateCustomFieldDefinition;
43
43
  export declare const createDefinitions: (defaults: Partial<CustomFieldDefinitionDTO>, length?: number) => CreateCustomFieldDefinition[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDefinitions = exports.createDefinition = exports.statusField = exports.selectField = exports.booleanField = exports.coolFieldDefinition3 = exports.coolFieldDefinition2 = exports.coolFieldDefinition = exports.contextAwareFieldDefinition = void 0;
3
+ exports.createDefinitions = exports.createDefinition = exports.rangeField = exports.enumField = exports.booleanField = exports.coolFieldDefinition3 = exports.coolFieldDefinition2 = exports.coolFieldDefinition = exports.contextAwareFieldDefinition = void 0;
4
4
  const uuid_1 = require("uuid");
5
5
  exports.contextAwareFieldDefinition = {
6
6
  name: 'cool field',
@@ -31,7 +31,7 @@ const booleanField = (modelType) => ({
31
31
  entityType: 'fleetId',
32
32
  });
33
33
  exports.booleanField = booleanField;
34
- const selectField = (modelType, options) => ({
34
+ const enumField = (modelType, options) => ({
35
35
  name: 'choices',
36
36
  modelType,
37
37
  fieldType: 'select',
@@ -39,16 +39,18 @@ const selectField = (modelType, options) => ({
39
39
  entityId: (0, uuid_1.v4)(),
40
40
  entityType: 'fleetId',
41
41
  });
42
- exports.selectField = selectField;
43
- const statusField = (modelType, options) => ({
44
- name: 'lifecycle',
42
+ exports.enumField = enumField;
43
+ const rangeField = (modelType) => ({
44
+ name: 'ranges',
45
45
  modelType,
46
- fieldType: 'status',
47
- validation: options,
46
+ fieldType: 'number',
47
+ validation: {
48
+ between: [10, 12],
49
+ },
48
50
  entityId: (0, uuid_1.v4)(),
49
51
  entityType: 'fleetId',
50
52
  });
51
- exports.statusField = statusField;
53
+ exports.rangeField = rangeField;
52
54
  // eslint-disable-next-line max-len
53
55
  const createDefinition = (defaults) => ({
54
56
  name: defaults?.name || `def_${(0, uuid_1.v4)()}`,
@@ -1,5 +1,5 @@
1
- import type { IncludeOptions } from 'sequelize';
2
- import type { ModelCtor } from 'sequelize-typescript';
1
+ import { IncludeOptions } from 'sequelize';
2
+ import { ModelCtor } from 'sequelize-typescript';
3
3
  export type ModelFetcher = (name: string) => any;
4
4
  export type ModelOptions = {
5
5
  /**
@@ -1,18 +1,5 @@
1
1
  declare const CUSTOM_FIELDS_FILTER_SCOPE: string;
2
2
  export declare const supportedEntities: string[];
3
- /**
4
- * Supported custom field types
5
- */
6
- export declare enum CustomFieldDefinitionType {
7
- NUMBER = "number",
8
- BOOLEAN = "boolean",
9
- DATE = "date",
10
- DATETIME = "datetime",
11
- TEXT = "text",
12
- IMAGE = "image",
13
- SELECT = "select",
14
- STATUS = "status"
15
- }
16
3
  export {
17
4
  /** @deprecated Use the value from `@autofleet/common-types` instead */
18
5
  CUSTOM_FIELDS_FILTER_SCOPE, };
@@ -1,21 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CUSTOM_FIELDS_FILTER_SCOPE = exports.CustomFieldDefinitionType = exports.supportedEntities = void 0;
3
+ exports.CUSTOM_FIELDS_FILTER_SCOPE = exports.supportedEntities = void 0;
4
4
  const common_types_1 = require("@autofleet/common-types");
5
5
  const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
6
6
  exports.CUSTOM_FIELDS_FILTER_SCOPE = CUSTOM_FIELDS_FILTER_SCOPE;
7
+ // eslint-disable-next-line import/prefer-default-export
7
8
  exports.supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'];
8
- /**
9
- * Supported custom field types
10
- */
11
- var CustomFieldDefinitionType;
12
- (function (CustomFieldDefinitionType) {
13
- CustomFieldDefinitionType["NUMBER"] = "number";
14
- CustomFieldDefinitionType["BOOLEAN"] = "boolean";
15
- CustomFieldDefinitionType["DATE"] = "date";
16
- CustomFieldDefinitionType["DATETIME"] = "datetime";
17
- CustomFieldDefinitionType["TEXT"] = "text";
18
- CustomFieldDefinitionType["IMAGE"] = "image";
19
- CustomFieldDefinitionType["SELECT"] = "select";
20
- CustomFieldDefinitionType["STATUS"] = "status";
21
- })(CustomFieldDefinitionType || (exports.CustomFieldDefinitionType = CustomFieldDefinitionType = {}));
@@ -1,6 +1,6 @@
1
- import { type WhereOptions, type BindOrReplacements } from 'sequelize';
2
- import { type ModelStatic } from 'sequelize-typescript';
3
- import { CustomFieldDefinitionType } from '../constants';
1
+ import { WhereOptions, BindOrReplacements } from 'sequelize';
2
+ import { ModelStatic } from 'sequelize-typescript';
3
+ import { CustomFieldDefinitionType } from '../validations/type';
4
4
  /**
5
5
  * Builds a WHERE clause and replacements for free-text search by custom fields.
6
6
  *
@@ -4,10 +4,10 @@ exports.generateCustomFieldSearchQueryPayload = void 0;
4
4
  /* eslint-disable import/prefer-default-export */
5
5
  const sequelize_1 = require("sequelize");
6
6
  const sequelize_typescript_1 = require("sequelize-typescript");
7
- const constants_1 = require("../constants");
7
+ const type_1 = require("../validations/type");
8
8
  const generateCustomFieldSearchQueryPayload = (searchTerm, model, entityId, customFieldsTypesToExclude = [
9
- constants_1.CustomFieldDefinitionType.DATETIME,
10
- constants_1.CustomFieldDefinitionType.DATE,
9
+ type_1.CustomFieldDefinitionType.DATETIME,
10
+ type_1.CustomFieldDefinitionType.DATE,
11
11
  ]) => {
12
12
  const excludedTypesString = customFieldsTypesToExclude.map((type) => `'${type}'`).join(',');
13
13
  const subQuery = 'EXISTS ('
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.CustomFieldsSchema = void 0;
7
+ /* eslint-disable import/prefer-default-export */
7
8
  const joi_1 = __importDefault(require("joi"));
8
9
  const CustomFieldsSchema = joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.any());
9
10
  exports.CustomFieldsSchema = CustomFieldsSchema;
@@ -0,0 +1,15 @@
1
+ export declare const mustHaveCustomValidation: {
2
+ select: boolean;
3
+ };
4
+ /**
5
+ * Validates the given validations object against the supported field types and their validators.
6
+ * @return true if the validation is valid, false otherwise.
7
+ */
8
+ export declare const validateValidation: (valueType: any, validation: any) => boolean;
9
+ /**
10
+ * Validates the given value against the custom validation rules for the specified field type.
11
+ * If no custom validation rules are provided, it falls back to the default validation.
12
+ * @returns true if the value is valid according to the validation rules, false otherwise.
13
+ */
14
+ declare const customValidation: (value: any, valueType: any, validation: any) => boolean;
15
+ export default customValidation;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateValidation = exports.mustHaveCustomValidation = void 0;
7
+ /* eslint-disable no-shadow */
8
+ const logger_1 = __importDefault(require("../logger"));
9
+ const type_1 = require("./type");
10
+ const validators_1 = __importDefault(require("./validators"));
11
+ exports.mustHaveCustomValidation = {
12
+ [type_1.CustomFieldDefinitionType.SELECT]: true,
13
+ };
14
+ /**
15
+ * Validates the given validations object against the supported field types and their validators.
16
+ * @return true if the validation is valid, false otherwise.
17
+ */
18
+ const validateValidation = (valueType, validation) => {
19
+ if (!validation) {
20
+ if (exports.mustHaveCustomValidation[valueType]) {
21
+ logger_1.default.error(`No custom validation for custom field type ${valueType} found`);
22
+ return false;
23
+ }
24
+ return true;
25
+ }
26
+ return true;
27
+ };
28
+ exports.validateValidation = validateValidation;
29
+ /**
30
+ * Validates the given value against the custom validation rules for the specified field type.
31
+ * If no custom validation rules are provided, it falls back to the default validation.
32
+ * @returns true if the value is valid according to the validation rules, false otherwise.
33
+ */
34
+ const customValidation = (value, valueType, validation) => {
35
+ const validator = validators_1.default?.[valueType];
36
+ if (!validation || !validator) {
37
+ return (0, exports.validateValidation)(valueType, validation);
38
+ }
39
+ // Always allow null values
40
+ return value === null || validator(value, validation);
41
+ };
42
+ exports.default = customValidation;
@@ -1,2 +1,2 @@
1
- import type { CustomFieldDefinitionType } from '../constants';
2
- export declare const validateValue: (value: unknown, valueType: CustomFieldDefinitionType, validation?: unknown) => boolean;
1
+ declare const validateValue: (value: any, valueType: any, customValidations: any) => boolean;
2
+ export default validateValue;
@@ -1,20 +1,20 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateValue = void 0;
4
- const validators_1 = require("./validators");
5
- const validateValue = (value, valueType, validation) => {
6
- const validator = validators_1.validators[valueType];
7
- if (!validator) {
8
- // Unsupported field type
6
+ const custom_1 = __importDefault(require("./custom"));
7
+ const type_1 = __importDefault(require("./type"));
8
+ const validateValue = (value, valueType, customValidations) => {
9
+ if (!(0, type_1.default)(value, valueType)) {
9
10
  return false;
10
11
  }
11
- // Always allow null values
12
- return value === null || validator(value, validation);
13
- /** TODO: Add validation for required fields
14
- * @example
15
- * if (validations.required && !value) {
16
- * return false;
17
- * }
18
- */
12
+ if (customValidations) {
13
+ return (0, custom_1.default)(value, valueType, customValidations);
14
+ }
15
+ // if (validations.required && !value) {
16
+ // return false;
17
+ // }
18
+ return true;
19
19
  };
20
- exports.validateValue = validateValue;
20
+ exports.default = validateValue;
@@ -1,14 +1,18 @@
1
- import type { CustomFieldDefinitionType } from '../constants';
2
1
  /**
3
- * Validator is a function that validates a custom-field `value`,
4
- * against a custom-field definition `validation object`.
5
- * @returns `true` if the value is valid, `false` otherwise.
2
+ * Supported custom field types
6
3
  */
7
- export type Validator<Value, DefinitionValidationObject> = (value: Value, validation?: DefinitionValidationObject) => boolean;
4
+ export declare enum CustomFieldDefinitionType {
5
+ NUMBER = "number",
6
+ BOOLEAN = "boolean",
7
+ DATE = "date",
8
+ DATETIME = "datetime",
9
+ TEXT = "text",
10
+ IMAGE = "image",
11
+ SELECT = "select"
12
+ }
8
13
  /**
9
- * Validators is a map of custom-field types to their respective validators.
10
- * The key is the custom-field type, and the value is the validator function.
14
+ * Validate that the given value is really of type "valueType"
15
+ * TODO: verify that required field not set to null
11
16
  */
12
- export type Validators = {
13
- [K in CustomFieldDefinitionType]: Validator<unknown, unknown>;
14
- };
17
+ declare const validateValueType: (value: unknown, valueType: CustomFieldDefinitionType) => boolean;
18
+ export default validateValueType;
@@ -1,2 +1,50 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CustomFieldDefinitionType = void 0;
7
+ const joi_1 = __importDefault(require("joi"));
8
+ /**
9
+ * Supported custom field types
10
+ */
11
+ // eslint-disable-next-line no-shadow
12
+ var CustomFieldDefinitionType;
13
+ (function (CustomFieldDefinitionType) {
14
+ CustomFieldDefinitionType["NUMBER"] = "number";
15
+ CustomFieldDefinitionType["BOOLEAN"] = "boolean";
16
+ CustomFieldDefinitionType["DATE"] = "date";
17
+ CustomFieldDefinitionType["DATETIME"] = "datetime";
18
+ CustomFieldDefinitionType["TEXT"] = "text";
19
+ CustomFieldDefinitionType["IMAGE"] = "image";
20
+ CustomFieldDefinitionType["SELECT"] = "select";
21
+ })(CustomFieldDefinitionType || (exports.CustomFieldDefinitionType = CustomFieldDefinitionType = {}));
22
+ /**
23
+ * Validate that the given value is really of type "valueType"
24
+ * TODO: verify that required field not set to null
25
+ */
26
+ const validateValueType = (value, valueType) => {
27
+ if (value === null) {
28
+ // Null is always allowed
29
+ return true;
30
+ }
31
+ switch (valueType) {
32
+ case CustomFieldDefinitionType.TEXT:
33
+ return typeof value === 'string';
34
+ case CustomFieldDefinitionType.NUMBER:
35
+ return typeof value === 'number';
36
+ case CustomFieldDefinitionType.BOOLEAN:
37
+ return typeof value === 'boolean';
38
+ case CustomFieldDefinitionType.DATE:
39
+ case CustomFieldDefinitionType.DATETIME:
40
+ return !joi_1.default.date().validate(value).error;
41
+ case CustomFieldDefinitionType.SELECT:
42
+ return true; // custom validation
43
+ case CustomFieldDefinitionType.IMAGE:
44
+ return !joi_1.default.array().min(1).unique().items(joi_1.default.string().uri())
45
+ .validate(value).error;
46
+ default:
47
+ return false;
48
+ }
49
+ };
50
+ exports.default = validateValueType;
@@ -0,0 +1,12 @@
1
+ export declare enum CustomValidations {
2
+ SELECT = "select",
3
+ RANGE = "between"
4
+ }
5
+ type Validator = (value: any, validation: any) => boolean;
6
+ /**
7
+ * Validators for custom fields
8
+ */
9
+ declare const validators: {
10
+ [key: string]: Validator;
11
+ };
12
+ export default validators;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CustomValidations = void 0;
4
+ // eslint-disable-next-line no-shadow
5
+ var CustomValidations;
6
+ (function (CustomValidations) {
7
+ CustomValidations["SELECT"] = "select";
8
+ CustomValidations["RANGE"] = "between";
9
+ })(CustomValidations || (exports.CustomValidations = CustomValidations = {}));
10
+ /**
11
+ * Validate {@link CustomValidations.ENUM Enum}
12
+ */
13
+ const validateEnum = (value, enumValues) => (Array.isArray(enumValues)
14
+ && enumValues.length > 0
15
+ && enumValues.includes(value));
16
+ /**
17
+ * Validate {@link CustomValidations.RANGE Range}
18
+ */
19
+ const validateRange = (value, range) => {
20
+ const [min, max] = range;
21
+ if (min === undefined || max === undefined) {
22
+ return false;
23
+ }
24
+ return value >= range.min && value <= range.max;
25
+ };
26
+ /**
27
+ * Validators for custom fields
28
+ */
29
+ const validators = {
30
+ [CustomValidations.SELECT]: validateEnum,
31
+ [CustomValidations.RANGE]: validateRange,
32
+ };
33
+ exports.default = validators;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/sadot",
3
- "version": "0.6.6",
3
+ "version": "0.6.7-beta.1",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -9,7 +9,7 @@
9
9
  "linter": "./node_modules/.bin/eslint .",
10
10
  "test": "jest --forceExit --runInBand",
11
11
  "coverage": "jest --coverage --forceExit --runInBand && rm -rf ./coverage",
12
- "build-to-local-repo": "npm run build && cp -r dist/* ../$REPO/node_modules/$npm_package_name/dist",
12
+ "build-to-local-repo": "npm run build && cp -r dist/* ../task-ms/node_modules/@autofleet/sadot/dist",
13
13
  "dev": "nodemon",
14
14
  "watch": "npm-watch build-to-local-repo",
15
15
  "publish-dev": "npm run build && npm publish --tag dev"
@@ -104,19 +104,16 @@ export const customFieldsSortScope = (
104
104
  const includes = Object.entries(sort).map(([key]) =>
105
105
  ([
106
106
  Sequelize.literal(`(
107
- SELECT custom_fields->>'${key}'
108
- FROM (
109
- SELECT
110
- cv.model_id,
111
- jsonb_object_agg(cd.name, cv.value) AS custom_fields
112
- FROM custom_field_values AS cv
113
- INNER JOIN custom_field_definitions AS cd
114
- ON cv.custom_field_definition_id = cd.id
115
- AND cd.model_type = '${name}'
116
- WHERE cv.model_id = "${name}"."id"
117
- GROUP BY cv.model_id
118
- ) AS CustomFieldAggregation
119
- )`),
107
+ SELECT value
108
+ FROM (SELECT cv.model_id, cv.value
109
+ FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
110
+ ON cv.custom_field_definition_id = cd.id
111
+ AND cd.model_type = '${name}'
112
+ WHERE cv.model_id = "${name}"."id"
113
+ AND cd.name = '${key}'
114
+ ) AS CustomFieldAggregation
115
+ )
116
+ `),
120
117
  `customFields_${key}`,
121
118
  ]));
122
119
 
@@ -1,14 +0,0 @@
1
- import { CustomFieldDefinitionType } from '../../constants';
2
- import type { Validators } from '../type';
3
- /**
4
- * Custom field types that must have custom validation.
5
- * TODO: remove this after moving to schema-based validation
6
- */
7
- export declare const CustomValidationTypes: {
8
- readonly select: CustomFieldDefinitionType.SELECT;
9
- readonly status: CustomFieldDefinitionType.STATUS;
10
- };
11
- /**
12
- * Validators for custom fields
13
- */
14
- export declare const validators: Validators;
@@ -1,33 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.validators = exports.CustomValidationTypes = void 0;
7
- const joi_1 = __importDefault(require("joi"));
8
- const constants_1 = require("../../constants");
9
- const select_validator_1 = require("./select.validator");
10
- const status_validator_1 = require("./status.validator");
11
- /**
12
- * Custom field types that must have custom validation.
13
- * TODO: remove this after moving to schema-based validation
14
- */
15
- exports.CustomValidationTypes = {
16
- [constants_1.CustomFieldDefinitionType.SELECT]: constants_1.CustomFieldDefinitionType.SELECT,
17
- [constants_1.CustomFieldDefinitionType.STATUS]: constants_1.CustomFieldDefinitionType.STATUS,
18
- };
19
- /**
20
- * Validators for custom fields
21
- */
22
- exports.validators = {
23
- [constants_1.CustomFieldDefinitionType.SELECT]: select_validator_1.validateSelect,
24
- [constants_1.CustomFieldDefinitionType.STATUS]: status_validator_1.validateStatus,
25
- [constants_1.CustomFieldDefinitionType.TEXT]: (value) => (typeof value === 'string'),
26
- [constants_1.CustomFieldDefinitionType.NUMBER]: (value) => (typeof value === 'number'),
27
- [constants_1.CustomFieldDefinitionType.BOOLEAN]: (value) => (typeof value === 'boolean'),
28
- [constants_1.CustomFieldDefinitionType.DATE]: (value) => (!joi_1.default.date().validate(value).error),
29
- [constants_1.CustomFieldDefinitionType.DATETIME]: (value) => (!joi_1.default.date().validate(value).error),
30
- [constants_1.CustomFieldDefinitionType.IMAGE]: (value) => (!joi_1.default.array().min(1).unique()
31
- .items(joi_1.default.string().uri())
32
- .validate(value).error),
33
- };
@@ -1,5 +0,0 @@
1
- import type { Validator } from '../type';
2
- /**
3
- * Validate that the value is one of the select values
4
- */
5
- export declare const validateSelect: Validator<string, string[]>;
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateSelect = void 0;
4
- /**
5
- * Validate that the value is one of the select values
6
- */
7
- const validateSelect = (value, selectValues) => (Array.isArray(selectValues)
8
- && selectValues.includes(value));
9
- exports.validateSelect = validateSelect;
@@ -1,12 +0,0 @@
1
- import type { Validator } from '../type';
2
- type StatusColor = string | null;
3
- type StatusValue = string;
4
- type StatusOption = {
5
- value: StatusValue;
6
- color: StatusColor;
7
- };
8
- /**
9
- * Validate that the value is one of the status values
10
- */
11
- export declare const validateStatus: Validator<StatusValue, StatusOption[]>;
12
- export {};
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateStatus = void 0;
4
- /**
5
- * Validate that the value is one of the status values
6
- */
7
- const validateStatus = (value, statusValues) => (Array.isArray(statusValues)
8
- && statusValues.some((status) => status.value === value));
9
- exports.validateStatus = validateStatus;