@autofleet/sadot 0.7.1 → 0.7.3-beta-4c642ed9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,7 @@ declare class CustomFieldDefinition extends Model {
13
13
  description?: string;
14
14
  required?: boolean;
15
15
  disabled?: boolean;
16
+ defaultValue?: any;
16
17
  createdAt?: Date;
17
18
  updatedAt?: Date;
18
19
  deletedAt?: Date;
@@ -19,12 +19,19 @@ const _1 = require(".");
19
19
  const events_1 = require("../events");
20
20
  const errors_1 = require("../errors");
21
21
  const logger_1 = __importDefault(require("../utils/logger"));
22
+ const validations_1 = require("../utils/validations");
22
23
  let CustomFieldDefinition = class CustomFieldDefinition extends sequelize_typescript_1.Model {
23
24
  static displayNameDefaultValue(instance) {
24
25
  if (!instance?.displayName) {
25
26
  // eslint-disable-next-line no-param-reassign
26
27
  instance.displayName = instance.name;
27
28
  }
29
+ if (instance.defaultValue !== null) {
30
+ const isValid = (0, validations_1.validateValue)(instance.defaultValue, instance.fieldType, instance.validation);
31
+ if (!isValid) {
32
+ throw new errors_1.InvalidValueError(instance.defaultValue, instance.fieldType);
33
+ }
34
+ }
28
35
  }
29
36
  static afterSaveHandler(instance, options) {
30
37
  if (options.transaction) {
@@ -116,6 +123,13 @@ __decorate([
116
123
  }),
117
124
  __metadata("design:type", Boolean)
118
125
  ], CustomFieldDefinition.prototype, "disabled", void 0);
126
+ __decorate([
127
+ (0, sequelize_typescript_1.Column)({
128
+ type: sequelize_typescript_1.DataType.JSONB,
129
+ allowNull: true,
130
+ }),
131
+ __metadata("design:type", Object)
132
+ ], CustomFieldDefinition.prototype, "defaultValue", void 0);
119
133
  __decorate([
120
134
  sequelize_typescript_1.Column,
121
135
  __metadata("design:type", Date)
@@ -22,7 +22,7 @@ exports.AssociatedTestModel = AssociatedTestModel_1.default;
22
22
  const productionModels = [CustomFieldDefinition_1.default, CustomFieldValue_1.default];
23
23
  const testModels = [TestModel_1.default, AssociatedTestModel_1.default, ContextAwareTestModel_1.default, ContextTestModel_1.default];
24
24
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
25
- const SCHEMA_VERSION = 1;
25
+ const SCHEMA_VERSION = 2;
26
26
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
27
27
  const initTables = async (sequelize, getUser) => {
28
28
  logger_1.default.info('custom-fields: initialize custom-fields tables');
@@ -31,6 +31,7 @@ const models_1 = require("../models");
31
31
  const DefinitionRepo = __importStar(require("./definition"));
32
32
  const logger_1 = __importDefault(require("../utils/logger"));
33
33
  const errors_1 = require("../errors");
34
+ const constants_1 = require("../utils/constants");
34
35
  const findByModelIdAndDefinition = async (modelId, customFieldDefinitionId) => models_1.CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [models_1.CustomFieldDefinition] });
35
36
  exports.findByModelIdAndDefinition = findByModelIdAndDefinition;
36
37
  const create = async (data, withAssociations = false) => {
@@ -66,6 +67,18 @@ const findValuesByModelIds = async (modelIds, options) => {
66
67
  });
67
68
  };
68
69
  exports.findValuesByModelIds = findValuesByModelIds;
70
+ const formatFunctions = {
71
+ [constants_1.CustomFieldDefinitionType.DATE]: (value) => {
72
+ if (value) {
73
+ const date = new Date(value);
74
+ if (date.toString() === 'Invalid Date') {
75
+ throw new Error(`Invalid date value: ${value}`);
76
+ }
77
+ return date.toISOString();
78
+ }
79
+ return null;
80
+ },
81
+ };
69
82
  /**
70
83
  * Try to update custom field values for a model instance.
71
84
  * Create new value record if not exists, but fails if value's definition not exist.
@@ -99,12 +112,16 @@ const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, opt
99
112
  if (valuesWithDisabledDefinitions?.length > 0) {
100
113
  logger_1.default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);
101
114
  }
102
- const values = names.map((name) => ({
103
- modelId,
104
- value: valuesToUpdate[name],
105
- updatedAt: new Date(),
106
- customFieldDefinitionId: fieldDefinitions.find((def) => def.name === name).id,
107
- }));
115
+ const values = names.map((name) => {
116
+ const fieldDefinition = fieldDefinitions.find((def) => def.name === name);
117
+ const formatFunction = formatFunctions[fieldDefinition.fieldType];
118
+ return {
119
+ modelId,
120
+ value: (formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name]) ?? fieldDefinition.defaultValue,
121
+ updatedAt: new Date(),
122
+ customFieldDefinitionId: fieldDefinition.id,
123
+ };
124
+ });
108
125
  return Promise.all(values.map(async (value) => {
109
126
  const [cfv] = await models_1.CustomFieldValue.upsert(value, {
110
127
  transaction: options.transaction,
@@ -14,6 +14,7 @@ export declare const coolFieldDefinition2: {
14
14
  createdAt?: Date;
15
15
  updatedAt?: Date;
16
16
  deletedAt?: Date;
17
+ defaultValue?: any;
17
18
  displayName?: string;
18
19
  validation?: any;
19
20
  fieldType: string;
@@ -29,6 +30,7 @@ export declare const coolFieldDefinition3: {
29
30
  createdAt?: Date;
30
31
  updatedAt?: Date;
31
32
  deletedAt?: Date;
33
+ defaultValue?: any;
32
34
  displayName?: string;
33
35
  validation?: any;
34
36
  fieldType: string;
@@ -56,6 +56,7 @@ const createDefinition = (defaults) => ({
56
56
  fieldType: defaults?.fieldType || 'boolean',
57
57
  entityId: defaults?.entityId || (0, uuid_1.v4)(),
58
58
  entityType: defaults?.entityType || 'fleetId',
59
+ ...(defaults?.defaultValue && { defaultValue: defaults.defaultValue }),
59
60
  });
60
61
  exports.createDefinition = createDefinition;
61
62
  const createDefinitions = (defaults, length = 1) => (Array(length).fill({}).map((_) => ({
@@ -3,6 +3,7 @@ export interface CustomFieldDefinitionDTO {
3
3
  name: string;
4
4
  displayName?: string;
5
5
  validation?: any;
6
+ defaultValue?: any;
6
7
  fieldType: string;
7
8
  entityId: string;
8
9
  entityType: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/sadot",
3
- "version": "0.7.1",
3
+ "version": "0.7.3-beta-4c642ed9.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -14,8 +14,9 @@ import { CustomFieldDefinitionType } from '../utils/constants';
14
14
  import { CustomValidationTypes } from '../utils/validations/validators';
15
15
  import { CustomFieldValue } from '.';
16
16
  import { sendDimEvent } from '../events';
17
- import { UnsupportedCustomFieldTypeError, UnsupportedCustomValidationError } from '../errors';
17
+ import { InvalidValueError, UnsupportedCustomFieldTypeError, UnsupportedCustomValidationError } from '../errors';
18
18
  import logger from '../utils/logger';
19
+ import { validateValue } from '../utils/validations';
19
20
 
20
21
  @DefaultScope(() => ({ where: { disabled: false } }))
21
22
  @Table({
@@ -109,6 +110,12 @@ class CustomFieldDefinition extends Model {
109
110
  })
110
111
  disabled?: boolean;
111
112
 
113
+ @Column({
114
+ type: DataType.JSONB,
115
+ allowNull: true,
116
+ })
117
+ defaultValue?: any;
118
+
112
119
  @Column
113
120
  createdAt?: Date;
114
121
 
@@ -127,6 +134,12 @@ class CustomFieldDefinition extends Model {
127
134
  // eslint-disable-next-line no-param-reassign
128
135
  instance.displayName = instance.name;
129
136
  }
137
+ if (instance.defaultValue !== null) {
138
+ const isValid = validateValue(instance.defaultValue, instance.fieldType, instance.validation);
139
+ if (!isValid) {
140
+ throw new InvalidValueError(instance.defaultValue, instance.fieldType);
141
+ }
142
+ }
130
143
  }
131
144
 
132
145
  @AfterSave
@@ -13,7 +13,7 @@ const productionModels = [CustomFieldDefinition, CustomFieldValue];
13
13
  const testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];
14
14
 
15
15
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
16
- const SCHEMA_VERSION = 1;
16
+ const SCHEMA_VERSION = 2;
17
17
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
18
18
 
19
19
  const initTables = async (sequelize: Sequelize, getUser): Promise<void> => {
@@ -6,6 +6,7 @@ import type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
6
6
  import logger from '../utils/logger';
7
7
  import { MissingDefinitionError } from '../errors';
8
8
  import type { ModelOptions } from '../types';
9
+ import { CustomFieldDefinitionType } from '../utils/constants';
9
10
 
10
11
  export const findByModelIdAndDefinition = async (modelId: string, customFieldDefinitionId: string) =>
11
12
  CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [CustomFieldDefinition] });
@@ -42,6 +43,19 @@ export const findValuesByModelIds = async (modelIds: string[], options?): Promis
42
43
  });
43
44
  };
44
45
 
46
+ const formatFunctions = {
47
+ [CustomFieldDefinitionType.DATE]: (value) => {
48
+ if (value) {
49
+ const date = new Date(value);
50
+ if (date.toString() === 'Invalid Date') {
51
+ throw new Error(`Invalid date value: ${value}`);
52
+ }
53
+ return date.toISOString();
54
+ }
55
+ return null;
56
+ },
57
+ };
58
+
45
59
  /**
46
60
  * Try to update custom field values for a model instance.
47
61
  * Create new value record if not exists, but fails if value's definition not exist.
@@ -86,12 +100,16 @@ export const updateValues = async (
86
100
  logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);
87
101
  }
88
102
 
89
- const values: CreateCustomFieldValue[] = names.map((name) => ({
90
- modelId,
91
- value: valuesToUpdate[name],
92
- updatedAt: new Date(),
93
- customFieldDefinitionId: fieldDefinitions.find((def) => def.name === name).id,
94
- }));
103
+ const values: CreateCustomFieldValue[] = names.map((name) => {
104
+ const fieldDefinition = fieldDefinitions.find((def) => def.name === name);
105
+ const formatFunction = formatFunctions[fieldDefinition.fieldType];
106
+ return {
107
+ modelId,
108
+ value: (formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name]) ?? fieldDefinition.defaultValue,
109
+ updatedAt: new Date(),
110
+ customFieldDefinitionId: fieldDefinition.id,
111
+ };
112
+ });
95
113
 
96
114
  return Promise.all(values.map(async (value) => {
97
115
  const [cfv] = await CustomFieldValue.upsert(value, {
@@ -59,6 +59,7 @@ export const createDefinition = (defaults: Partial<CustomFieldDefinitionDTO>): C
59
59
  fieldType: defaults?.fieldType || 'boolean',
60
60
  entityId: defaults?.entityId || uuidv4(),
61
61
  entityType: defaults?.entityType || 'fleetId',
62
+ ...(defaults?.defaultValue && { defaultValue: defaults.defaultValue }),
62
63
  });
63
64
 
64
65
  export const createDefinitions = (
@@ -3,6 +3,7 @@ export interface CustomFieldDefinitionDTO {
3
3
  name: string;
4
4
  displayName?: string;
5
5
  validation?: any;
6
+ defaultValue?: any;
6
7
  fieldType: string;
7
8
  entityId: string;
8
9
  entityType: string;