@autofleet/sadot 0.6.2-temp-file-6 → 0.6.3-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 (63) hide show
  1. package/dist/api/v1/definition/validations.js +4 -17
  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 +10 -1
  13. package/dist/scopes/filter.js +21 -1
  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 -14
  18. package/dist/utils/constants/index.js +2 -16
  19. package/dist/utils/helpers/index.d.ts +3 -3
  20. package/dist/utils/helpers/index.js +3 -3
  21. package/dist/utils/init.js +3 -0
  22. package/dist/utils/validations/{schema/custom-fields.js → custom-fields.js} +1 -0
  23. package/dist/utils/validations/custom.d.ts +15 -0
  24. package/dist/utils/validations/custom.js +42 -0
  25. package/dist/utils/validations/index.d.ts +2 -2
  26. package/dist/utils/validations/index.js +15 -15
  27. package/dist/utils/validations/type.d.ts +14 -10
  28. package/dist/utils/validations/type.js +48 -0
  29. package/dist/utils/validations/validators.d.ts +12 -0
  30. package/dist/utils/validations/validators.js +33 -0
  31. package/package.json +9 -9
  32. package/src/api/v1/definition/index.ts +1 -1
  33. package/src/api/v1/definition/validations.ts +1 -14
  34. package/src/hooks/create.ts +1 -1
  35. package/src/hooks/enrich.ts +4 -4
  36. package/src/hooks/update.ts +1 -1
  37. package/src/index.ts +3 -2
  38. package/src/models/CustomFieldDefinition.ts +5 -7
  39. package/src/models/CustomFieldValue.ts +5 -1
  40. package/src/repository/definition.ts +5 -2
  41. package/src/repository/value.ts +2 -2
  42. package/src/scopes/filter.ts +26 -1
  43. package/src/tests/functional/searching/index.ts +1 -1
  44. package/src/tests/mocks/definition.mock.ts +8 -6
  45. package/src/types/index.ts +2 -2
  46. package/src/utils/constants/index.ts +1 -15
  47. package/src/utils/helpers/index.ts +5 -5
  48. package/src/utils/init.ts +4 -1
  49. package/src/utils/validations/{schema/custom-fields.ts → custom-fields.ts} +1 -0
  50. package/src/utils/validations/custom.ts +39 -0
  51. package/src/utils/validations/index.ts +15 -18
  52. package/src/utils/validations/type.ts +40 -14
  53. package/src/utils/validations/validators.ts +34 -0
  54. package/dist/utils/validations/validators/index.d.ts +0 -14
  55. package/dist/utils/validations/validators/index.js +0 -40
  56. package/dist/utils/validations/validators/select.validator.d.ts +0 -5
  57. package/dist/utils/validations/validators/select.validator.js +0 -9
  58. package/dist/utils/validations/validators/status.validator.d.ts +0 -12
  59. package/dist/utils/validations/validators/status.validator.js +0 -9
  60. package/src/utils/validations/validators/index.ts +0 -38
  61. package/src/utils/validations/validators/select.validator.ts +0 -11
  62. package/src/utils/validations/validators/status.validator.ts +0 -18
  63. /package/dist/utils/validations/{schema/custom-fields.d.ts → custom-fields.d.ts} +0 -0
@@ -5,30 +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
- /**
10
- * Schema for the validation of custom field definition
11
- * The only custom validation is for
12
- * {@link CustomFieldDefinitionType.SELECT SELECT}
13
- * and
14
- * {@link CustomFieldDefinitionType.STATUS STATUS}
15
- * field types.
16
- * The rest of the field types are validated by Joi
17
- */
8
+ const type_1 = require("../../../utils/validations/type");
18
9
  const ValidationSchema = joi_1.default.when('fieldType', {
19
- is: constants_1.CustomFieldDefinitionType.SELECT,
10
+ is: type_1.CustomFieldDefinitionType.SELECT,
20
11
  then: joi_1.default.array().items(joi_1.default.string()).min(1).unique(),
21
12
  otherwise: joi_1.default.any(),
22
- }).when('fieldType', {
23
- is: constants_1.CustomFieldDefinitionType.STATUS,
24
- then: joi_1.default.string().min(1).required(),
25
- otherwise: joi_1.default.any(),
26
13
  });
27
14
  const CustomFieldDefinitionCreationSchema = joi_1.default.object({
28
15
  name: joi_1.default.string().required(),
29
16
  displayName: joi_1.default.string().required(),
30
17
  validation: ValidationSchema,
31
- 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(),
32
19
  entityId: joi_1.default.string().guid().required(),
33
20
  entityType: joi_1.default.string().required(),
34
21
  description: joi_1.default.string(),
@@ -38,7 +25,7 @@ const CustomFieldDefinitionCreationSchema = joi_1.default.object({
38
25
  const CustomFieldDefinitionUpdateSchema = joi_1.default.object({
39
26
  displayName: joi_1.default.string(),
40
27
  validation: ValidationSchema,
41
- fieldType: joi_1.default.string().valid(...Object.values(constants_1.CustomFieldDefinitionType)),
28
+ fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)),
42
29
  description: joi_1.default.string().allow(null),
43
30
  required: joi_1.default.boolean(),
44
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,4 +1,4 @@
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.
@@ -21,3 +21,12 @@ export type CustomFieldFilterOptions = {
21
21
  */
22
22
  export declare const customFieldsFilterScope: (name: string) => (conditions: Record<string, ConditionValue>) => CustomFieldFilterOptions;
23
23
  export declare const scopeName = "filterByCustomFields";
24
+ export declare const customFieldsSortScope: (name: string) => (sort: CustomFieldSort[]) => {
25
+ attributes?: undefined;
26
+ order?: undefined;
27
+ } | {
28
+ attributes: {
29
+ include: import("sequelize/types/utils").Literal[];
30
+ };
31
+ order: import("sequelize/types/utils").Literal[];
32
+ };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.scopeName = exports.customFieldsFilterScope = void 0;
3
+ exports.customFieldsSortScope = exports.scopeName = exports.customFieldsFilterScope = 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");
@@ -53,3 +53,23 @@ const customFieldsFilterScope = (name) => (conditions) => {
53
53
  };
54
54
  exports.customFieldsFilterScope = customFieldsFilterScope;
55
55
  exports.scopeName = CUSTOM_FIELDS_FILTER_SCOPE;
56
+ const customFieldsSortScope = (name) => (sort) => {
57
+ if (!sort || sort.length === 0) {
58
+ return {};
59
+ }
60
+ const incluedes = Object.entries(sort).map(([key]) => sequelize_typescript_1.Sequelize.literal(`(select CustomFieldAggregation.custom_fields->>'${key}'
61
+ from (SELECT cv.model_id, jsonb_object_agg(cd.name, cv.value) AS custom_fields
62
+ FROM custom_field_values AS cv
63
+ INNER JOIN custom_field_definitions AS cd
64
+ ON cv.custom_field_definition_id = cd.id AND cd.model_type = 'Task'
65
+ where cv.model_id = "${name}"."id"
66
+ GROUP BY cv.model_id) AS CustomFieldAggregation) as "customFields.${key}"`));
67
+ const orders = Object.entries(sort).map(([key, value]) => sequelize_typescript_1.Sequelize.literal(`"customFields.${key}" ${value}`));
68
+ return {
69
+ attributes: {
70
+ include: incluedes,
71
+ },
72
+ order: orders,
73
+ };
74
+ };
75
+ exports.customFieldsSortScope = customFieldsSortScope;
@@ -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,19 +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
- FILE = "file"
16
- }
17
3
  export {
18
4
  /** @deprecated Use the value from `@autofleet/common-types` instead */
19
5
  CUSTOM_FIELDS_FILTER_SCOPE, };
@@ -1,22 +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["FILE"] = "file";
22
- })(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 ('
@@ -6,10 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.applyCustomAssociation = exports.addScopes = exports.removeHooks = exports.addHooks = void 0;
7
7
  const sequelize_1 = require("sequelize");
8
8
  const common_types_1 = require("@autofleet/common-types");
9
+ const custom_fields_1 = require("@autofleet/common-types/lib/custom-fields");
9
10
  const models_1 = require("../models");
10
11
  const hooks_1 = require("../hooks");
11
12
  const scopes_1 = require("../scopes");
12
13
  const logger_1 = __importDefault(require("./logger"));
14
+ const filter_1 = require("../scopes/filter");
13
15
  const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
14
16
  const addHooks = (models, getModel) => {
15
17
  models.forEach(async ({ name, scopeAttributes, modelOptions, }) => {
@@ -91,6 +93,7 @@ const addScopes = (models, getModel) => {
91
93
  addAssociations(model, name);
92
94
  // Add filter scope
93
95
  model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, (0, scopes_1.customFieldsFilterScope)(name));
96
+ model.addScope(custom_fields_1.CUSTOM_FIELDS_SORT_SCOPE, (0, filter_1.customFieldsSortScope)(name));
94
97
  }
95
98
  catch (e) {
96
99
  logger_1.default.error(`Could not add custom fields scopes to model ${name}. `, e);
@@ -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 || (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,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;