@autofleet/sadot 0.6.4-beta.1 → 0.6.5

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 (62) hide show
  1. package/dist/api/v1/definition/validations.js +21 -4
  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 +2 -3
  6. package/dist/index.js +2 -4
  7. package/dist/models/CustomFieldDefinition.d.ts +1 -1
  8. package/dist/models/CustomFieldDefinition.js +11 -6
  9. package/dist/models/CustomFieldValue.js +3 -8
  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 +8 -3
  13. package/dist/scopes/filter.js +36 -27
  14. package/dist/tests/mocks/definition.mock.d.ts +3 -3
  15. package/dist/tests/mocks/definition.mock.js +8 -10
  16. package/dist/types/index.d.ts +2 -2
  17. package/dist/utils/constants/index.d.ts +13 -0
  18. package/dist/utils/constants/index.js +15 -2
  19. package/dist/utils/helpers/index.d.ts +3 -3
  20. package/dist/utils/helpers/index.js +3 -3
  21. package/dist/utils/validations/index.d.ts +2 -2
  22. package/dist/utils/validations/index.js +15 -15
  23. package/dist/utils/validations/{custom-fields.js → schema/custom-fields.js} +0 -1
  24. package/dist/utils/validations/type.d.ts +10 -14
  25. package/dist/utils/validations/type.js +0 -48
  26. package/dist/utils/validations/validators/index.d.ts +14 -0
  27. package/dist/utils/validations/validators/index.js +33 -0
  28. package/dist/utils/validations/validators/select.validator.d.ts +5 -0
  29. package/dist/utils/validations/validators/select.validator.js +9 -0
  30. package/dist/utils/validations/validators/status.validator.d.ts +12 -0
  31. package/dist/utils/validations/validators/status.validator.js +9 -0
  32. package/package.json +9 -8
  33. package/src/api/v1/definition/index.ts +1 -1
  34. package/src/api/v1/definition/validations.ts +20 -1
  35. package/src/hooks/create.ts +1 -1
  36. package/src/hooks/enrich.ts +4 -4
  37. package/src/hooks/update.ts +1 -1
  38. package/src/index.ts +2 -3
  39. package/src/models/CustomFieldDefinition.ts +7 -5
  40. package/src/models/CustomFieldValue.ts +1 -5
  41. package/src/repository/definition.ts +2 -5
  42. package/src/repository/value.ts +2 -2
  43. package/src/scopes/filter.ts +43 -30
  44. package/src/tests/functional/searching/index.ts +1 -1
  45. package/src/tests/mocks/definition.mock.ts +6 -8
  46. package/src/types/index.ts +2 -2
  47. package/src/utils/constants/index.ts +14 -1
  48. package/src/utils/helpers/index.ts +5 -5
  49. package/src/utils/init.ts +1 -1
  50. package/src/utils/validations/index.ts +18 -15
  51. package/src/utils/validations/{custom-fields.ts → schema/custom-fields.ts} +0 -1
  52. package/src/utils/validations/type.ts +14 -40
  53. package/src/utils/validations/validators/index.ts +31 -0
  54. package/src/utils/validations/validators/select.validator.ts +11 -0
  55. package/src/utils/validations/validators/status.validator.ts +18 -0
  56. package/dist/utils/validations/custom.d.ts +0 -15
  57. package/dist/utils/validations/custom.js +0 -42
  58. package/dist/utils/validations/validators.d.ts +0 -12
  59. package/dist/utils/validations/validators.js +0 -33
  60. package/src/utils/validations/custom.ts +0 -39
  61. package/src/utils/validations/validators.ts +0 -34
  62. /package/dist/utils/validations/{custom-fields.d.ts → schema/custom-fields.d.ts} +0 -0
@@ -5,17 +5,34 @@ 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 type_1 = require("../../../utils/validations/type");
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
+ */
9
22
  const ValidationSchema = joi_1.default.when('fieldType', {
10
- is: type_1.CustomFieldDefinitionType.SELECT,
23
+ is: constants_1.CustomFieldDefinitionType.SELECT,
11
24
  then: joi_1.default.array().items(joi_1.default.string()).min(1).unique(),
12
25
  otherwise: joi_1.default.any(),
26
+ }).when('fieldType', {
27
+ is: constants_1.CustomFieldDefinitionType.STATUS,
28
+ then: statusValidationObjectSchema,
29
+ otherwise: joi_1.default.any(),
13
30
  });
14
31
  const CustomFieldDefinitionCreationSchema = joi_1.default.object({
15
32
  name: joi_1.default.string().required(),
16
33
  displayName: joi_1.default.string().required(),
17
34
  validation: ValidationSchema,
18
- fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)).required(),
35
+ fieldType: joi_1.default.string().valid(...Object.values(constants_1.CustomFieldDefinitionType)).required(),
19
36
  entityId: joi_1.default.string().guid().required(),
20
37
  entityType: joi_1.default.string().required(),
21
38
  description: joi_1.default.string(),
@@ -25,7 +42,7 @@ const CustomFieldDefinitionCreationSchema = joi_1.default.object({
25
42
  const CustomFieldDefinitionUpdateSchema = joi_1.default.object({
26
43
  displayName: joi_1.default.string(),
27
44
  validation: ValidationSchema,
28
- fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)),
45
+ fieldType: joi_1.default.string().valid(...Object.values(constants_1.CustomFieldDefinitionType)),
29
46
  description: joi_1.default.string().allow(null),
30
47
  required: joi_1.default.boolean(),
31
48
  disabled: joi_1.default.boolean(),
@@ -1,4 +1,4 @@
1
- import { ModelOptions } from '../types';
1
+ import type { 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 { ModelOptions } from '../types';
1
+ import type { 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 { ModelOptions } from '../types';
1
+ import type { 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,10 +1,9 @@
1
1
  import type { Application } from 'express';
2
- import { Sequelize } from 'sequelize-typescript';
2
+ import type { Sequelize } from 'sequelize-typescript';
3
3
  import type { CustomFieldOptions, ModelFetcher } from './types';
4
- export * from './utils/validations/custom-fields';
4
+ export * from './utils/validations/schema/custom-fields';
5
5
  export * from './utils/constants';
6
6
  export * from './utils/helpers';
7
- export { CustomFieldDefinitionType } from './utils/validations/type';
8
7
  /**
9
8
  * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
10
9
  * @see {@link 'custom-fields/config'} for configurations
package/dist/index.js CHANGED
@@ -17,17 +17,15 @@ 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 = exports.CustomFieldDefinitionType = void 0;
20
+ exports.disableCustomFields = 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/custom-fields"), exports);
26
+ __exportStar(require("./utils/validations/schema/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; } });
31
29
  /**
32
30
  * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
33
31
  * @see {@link 'custom-fields/config'} for configurations
@@ -1,5 +1,5 @@
1
1
  import { Model } from 'sequelize-typescript';
2
- import { CustomFieldDefinitionType } from '../utils/validations/type';
2
+ import { CustomFieldDefinitionType } from '../utils/constants';
3
3
  import { CustomFieldValue } from '.';
4
4
  declare class CustomFieldDefinition extends Model {
5
5
  id: string;
@@ -8,15 +8,17 @@ 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
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
- /* eslint-disable @typescript-eslint/no-unused-vars */
13
- /* eslint-disable indent */
14
15
  const sequelize_typescript_1 = require("sequelize-typescript");
15
- const custom_1 = require("../utils/validations/custom");
16
- const type_1 = require("../utils/validations/type");
16
+ const constants_1 = require("../utils/constants");
17
+ const validators_1 = require("../utils/validations/validators");
17
18
  const _1 = require(".");
18
19
  const events_1 = require("../events");
19
20
  const errors_1 = require("../errors");
21
+ const logger_1 = __importDefault(require("../utils/logger"));
20
22
  let CustomFieldDefinition = class CustomFieldDefinition extends sequelize_typescript_1.Model {
21
23
  static displayNameDefaultValue(instance) {
22
24
  if (!instance?.displayName) {
@@ -57,7 +59,7 @@ __decorate([
57
59
  ], CustomFieldDefinition.prototype, "displayName", void 0);
58
60
  __decorate([
59
61
  (0, sequelize_typescript_1.Is)('SupportedType', (value) => {
60
- if (!Object.values(type_1.CustomFieldDefinitionType).includes(value)) {
62
+ if (!Object.values(constants_1.CustomFieldDefinitionType).includes(value)) {
61
63
  throw new errors_1.UnsupportedCustomFieldTypeError(`"${value}" is not a supported type.`);
62
64
  }
63
65
  }),
@@ -155,7 +157,10 @@ CustomFieldDefinition = __decorate([
155
157
  timestamps: true,
156
158
  validate: {
157
159
  validationByType() {
158
- if (!(0, custom_1.validateValidation)(this.fieldType, this.validation)) {
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`);
159
164
  throw new errors_1.UnsupportedCustomValidationError(`Validation provided for "${this.fieldType}" is not supported`);
160
165
  }
161
166
  },
@@ -31,16 +31,11 @@ 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
- };
37
34
  Object.defineProperty(exports, "__esModule", { value: true });
38
- /* eslint-disable @typescript-eslint/no-unused-vars */
39
- /* eslint-disable indent */
40
35
  const sequelize_typescript_1 = require("sequelize-typescript");
41
36
  const events_1 = require("../events");
42
37
  const _1 = require(".");
43
- const validations_1 = __importDefault(require("../utils/validations"));
38
+ const validations_1 = require("../utils/validations");
44
39
  const CustomFieldDefinitionRepo = __importStar(require("../repository/definition"));
45
40
  const errors_1 = require("../errors");
46
41
  let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Model {
@@ -54,7 +49,7 @@ let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Mod
54
49
  instances.forEach((instance) => {
55
50
  const { validation, fieldType, } = definitions
56
51
  .find((definition) => definition.id === instance.customFieldDefinitionId);
57
- const isValid = (0, validations_1.default)(instance.value, fieldType, validation);
52
+ const isValid = (0, validations_1.validateValue)(instance.value, fieldType, validation);
58
53
  if (!isValid) {
59
54
  throw new errors_1.InvalidValueError(instance.value, fieldType);
60
55
  }
@@ -65,7 +60,7 @@ let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Mod
65
60
  // eslint-disable-next-line max-len
66
61
  const cfd = await CustomFieldDefinitionRepo.findById(customFieldDefinitionId, { withDisabled: true });
67
62
  const { validation, fieldType } = cfd;
68
- const isValid = (0, validations_1.default)(instance.value, fieldType, validation);
63
+ const isValid = (0, validations_1.validateValue)(instance.value, fieldType, validation);
69
64
  if (!isValid) {
70
65
  throw new errors_1.InvalidValueError(instance.value, fieldType);
71
66
  }
@@ -1,7 +1,7 @@
1
- import { FindOptions, WhereOptions } from 'sequelize';
1
+ import { type FindOptions, type WhereOptions } from 'sequelize';
2
2
  import { CustomFieldDefinition } from '../models';
3
3
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
4
- import { ModelOptions } from '../types';
4
+ import type { 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 { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
4
- import { ModelOptions } from '../types';
3
+ import type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
4
+ import type { 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,10 +1,14 @@
1
- import { WhereOptions } from 'sequelize';
1
+ import { type 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
- export type ConditionValue = string | string[];
7
+ type ConditionWithOperator = {
8
+ operator: string;
9
+ value: string;
10
+ };
11
+ export type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
8
12
  export type CustomFieldSort = {
9
13
  field: string;
10
14
  direction: 'ASC' | 'DESC';
@@ -26,7 +30,8 @@ export declare const customFieldsSortScope: (name: string) => (sort: CustomField
26
30
  order?: undefined;
27
31
  } | {
28
32
  attributes: {
29
- include: (string | import("sequelize/types/utils").Literal)[][];
33
+ include: import("sequelize/types/utils").Literal[];
30
34
  };
31
35
  order: import("sequelize/types/utils").Literal[];
32
36
  };
37
+ export {};
@@ -6,6 +6,13 @@ 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 ';
9
16
  /**
10
17
  * A Sequelize scope for filtering models by custom fields.
11
18
  * This scope builds a WHERE clause to be applied on the main query.
@@ -19,30 +26,39 @@ const customFieldsFilterScope = (name) => (conditions) => {
19
26
  }
20
27
  // Build the WHERE clause for custom field filtering
21
28
  const conditionsStrings = Object.entries(conditions)
22
- .map(([key, value]) => {
23
- if (Array.isArray(value)) {
24
- if (value.length === 0) {
29
+ .map(([key, condition]) => {
30
+ if (Array.isArray(condition)) {
31
+ if (condition.length === 0) {
25
32
  // if empty array, the condition is ignored
26
33
  return false;
27
34
  }
28
- const values = value.map((v) => `'${v}'`).join(',');
29
- return `custom_fields->>'${key}' IN (${values})`;
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}'`;
30
47
  }
31
- return `custom_fields->>'${key}' = '${value}'`;
48
+ return false;
32
49
  })
33
50
  .filter(Boolean);
34
51
  if (conditionsStrings.length === 0) {
35
52
  return {};
36
53
  }
37
- const customFieldConditions = conditionsStrings.join(' AND ');
54
+ const customFieldConditions = conditionsStrings.join(AND_DELIMETER);
38
55
  const subQuery = `${'SELECT model_id FROM ('
39
56
  + 'SELECT cv.model_id, jsonb_object_agg(cd.name, cv.value) AS custom_fields '
40
57
  + 'FROM custom_field_values AS cv '
41
58
  + 'INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id '
42
59
  + `AND cd.model_type = '${name}' `
43
60
  + 'GROUP BY cv.model_id'
44
- + ') AS CustomFieldAggregation '
45
- + 'WHERE '}${customFieldConditions}`;
61
+ + ') AS CustomFieldAggregation WHERE '}${customFieldConditions}`;
46
62
  return {
47
63
  where: {
48
64
  id: {
@@ -57,24 +73,17 @@ const customFieldsSortScope = (name) => (sort) => {
57
73
  if (!sort || sort.length === 0) {
58
74
  return {};
59
75
  }
60
- const includes = Object.entries(sort).map(([key]) => ([
61
- sequelize_typescript_1.Sequelize.literal(`(
62
- SELECT custom_fields->>'${key}'
63
- FROM (
64
- SELECT
65
- cv.model_id,
66
- jsonb_object_agg(cd.name, cv.value) AS custom_fields
67
- FROM custom_field_values AS cv
68
- INNER JOIN custom_field_definitions AS cd
69
- ON cv.custom_field_definition_id = cd.id
70
- AND cd.model_type = '${name}'
71
- WHERE cv.model_id = "${name}"."id"
72
- GROUP BY cv.model_id
73
- ) AS CustomFieldAggregation
74
- )`),
75
- `customFields_${key}`,
76
- ]));
77
- const orders = Object.entries(sort).map(([key, value]) => sequelize_typescript_1.Sequelize.literal(`"customFields_${key}" ${value}`));
76
+ console.log('sort', sort);
77
+ console.log('name', name);
78
+ console.log('Object.entries(sort)', Object.entries(sort));
79
+ const includes = Object.entries(sort).map(([key]) => sequelize_typescript_1.Sequelize.literal(`(select CustomFieldAggregation.custom_fields->>'${key}'
80
+ from (SELECT cv.model_id, jsonb_object_agg(cd.name, cv.value) AS custom_fields
81
+ FROM custom_field_values AS cv
82
+ INNER JOIN custom_field_definitions AS cd
83
+ ON cv.custom_field_definition_id = cd.id AND cd.model_type = '${name}'
84
+ where cv.model_id = "${name}"."id"
85
+ GROUP BY cv.model_id) AS CustomFieldAggregation) as "customFields.${key}"`));
86
+ const orders = Object.entries(sort).map(([key, value]) => sequelize_typescript_1.Sequelize.literal(`"customFields.${key}" ${value}`));
78
87
  return {
79
88
  attributes: {
80
89
  include: includes,
@@ -1,4 +1,4 @@
1
- import { CreateCustomFieldDefinition, CustomFieldDefinitionDTO } from '../../types/definition';
1
+ import type { 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 enumField: (modelType: string, options: any) => CreateCustomFieldDefinition;
41
- export declare const rangeField: (modelType: string) => CreateCustomFieldDefinition;
40
+ export declare const selectField: (modelType: string, options: any) => CreateCustomFieldDefinition;
41
+ export declare const statusField: (modelType: string, options: any) => 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.rangeField = exports.enumField = exports.booleanField = exports.coolFieldDefinition3 = exports.coolFieldDefinition2 = exports.coolFieldDefinition = exports.contextAwareFieldDefinition = void 0;
3
+ exports.createDefinitions = exports.createDefinition = exports.statusField = exports.selectField = 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 enumField = (modelType, options) => ({
34
+ const selectField = (modelType, options) => ({
35
35
  name: 'choices',
36
36
  modelType,
37
37
  fieldType: 'select',
@@ -39,18 +39,16 @@ const enumField = (modelType, options) => ({
39
39
  entityId: (0, uuid_1.v4)(),
40
40
  entityType: 'fleetId',
41
41
  });
42
- exports.enumField = enumField;
43
- const rangeField = (modelType) => ({
44
- name: 'ranges',
42
+ exports.selectField = selectField;
43
+ const statusField = (modelType, options) => ({
44
+ name: 'lifecycle',
45
45
  modelType,
46
- fieldType: 'number',
47
- validation: {
48
- between: [10, 12],
49
- },
46
+ fieldType: 'status',
47
+ validation: options,
50
48
  entityId: (0, uuid_1.v4)(),
51
49
  entityType: 'fleetId',
52
50
  });
53
- exports.rangeField = rangeField;
51
+ exports.statusField = statusField;
54
52
  // eslint-disable-next-line max-len
55
53
  const createDefinition = (defaults) => ({
56
54
  name: defaults?.name || `def_${(0, uuid_1.v4)()}`,
@@ -1,5 +1,5 @@
1
- import { IncludeOptions } from 'sequelize';
2
- import { ModelCtor } from 'sequelize-typescript';
1
+ import type { IncludeOptions } from 'sequelize';
2
+ import type { ModelCtor } from 'sequelize-typescript';
3
3
  export type ModelFetcher = (name: string) => any;
4
4
  export type ModelOptions = {
5
5
  /**
@@ -1,5 +1,18 @@
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
+ }
3
16
  export {
4
17
  /** @deprecated Use the value from `@autofleet/common-types` instead */
5
18
  CUSTOM_FIELDS_FILTER_SCOPE, };
@@ -1,8 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CUSTOM_FIELDS_FILTER_SCOPE = exports.supportedEntities = void 0;
3
+ exports.CUSTOM_FIELDS_FILTER_SCOPE = exports.CustomFieldDefinitionType = 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
8
7
  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 { WhereOptions, BindOrReplacements } from 'sequelize';
2
- import { ModelStatic } from 'sequelize-typescript';
3
- import { CustomFieldDefinitionType } from '../validations/type';
1
+ import { type WhereOptions, type BindOrReplacements } from 'sequelize';
2
+ import { type ModelStatic } from 'sequelize-typescript';
3
+ import { CustomFieldDefinitionType } from '../constants';
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 type_1 = require("../validations/type");
7
+ const constants_1 = require("../constants");
8
8
  const generateCustomFieldSearchQueryPayload = (searchTerm, model, entityId, customFieldsTypesToExclude = [
9
- type_1.CustomFieldDefinitionType.DATETIME,
10
- type_1.CustomFieldDefinitionType.DATE,
9
+ constants_1.CustomFieldDefinitionType.DATETIME,
10
+ constants_1.CustomFieldDefinitionType.DATE,
11
11
  ]) => {
12
12
  const excludedTypesString = customFieldsTypesToExclude.map((type) => `'${type}'`).join(',');
13
13
  const subQuery = 'EXISTS ('
@@ -1,2 +1,2 @@
1
- declare const validateValue: (value: any, valueType: any, customValidations: any) => boolean;
2
- export default validateValue;
1
+ import type { CustomFieldDefinitionType } from '../constants';
2
+ export declare const validateValue: (value: unknown, valueType: CustomFieldDefinitionType, validation?: unknown) => boolean;
@@ -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
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
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)) {
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
10
9
  return false;
11
10
  }
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;
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
+ */
19
19
  };
20
- exports.default = validateValue;
20
+ exports.validateValue = validateValue;
@@ -4,7 +4,6 @@ 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 */
8
7
  const joi_1 = __importDefault(require("joi"));
9
8
  const CustomFieldsSchema = joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.any());
10
9
  exports.CustomFieldsSchema = CustomFieldsSchema;
@@ -1,18 +1,14 @@
1
+ import type { CustomFieldDefinitionType } from '../constants';
1
2
  /**
2
- * Supported custom field types
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.
3
6
  */
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
- }
7
+ export type Validator<Value, DefinitionValidationObject> = (value: Value, validation?: DefinitionValidationObject) => boolean;
13
8
  /**
14
- * Validate that the given value is really of type "valueType"
15
- * TODO: verify that required field not set to null
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.
16
11
  */
17
- declare const validateValueType: (value: unknown, valueType: CustomFieldDefinitionType) => boolean;
18
- export default validateValueType;
12
+ export type Validators = {
13
+ [K in CustomFieldDefinitionType]: Validator<unknown, unknown>;
14
+ };
@@ -1,50 +1,2 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  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 || (exports.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,14 @@
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;