@autofleet/sadot 0.5.4-beta.17 → 0.5.4-beta.19

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 (45) hide show
  1. package/dist/api/v1/definition/index.js +0 -4
  2. package/dist/hooks/create.d.ts +2 -1
  3. package/dist/hooks/create.js +9 -8
  4. package/dist/hooks/enrich.d.ts +2 -1
  5. package/dist/hooks/enrich.js +13 -4
  6. package/dist/hooks/update.d.ts +2 -1
  7. package/dist/hooks/update.js +6 -2
  8. package/dist/index.js +2 -2
  9. package/dist/models/index.d.ts +4 -2
  10. package/dist/models/index.js +15 -15
  11. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +10 -0
  12. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +55 -0
  13. package/dist/models/tests/contextAwareModels/ContextModel.d.ts +13 -0
  14. package/dist/models/tests/contextAwareModels/ContextModel.js +47 -0
  15. package/dist/repository/definition.d.ts +2 -2
  16. package/dist/repository/definition.js +14 -11
  17. package/dist/repository/value.js +9 -2
  18. package/dist/tests/helpers/database-config.d.ts +1 -0
  19. package/dist/tests/helpers/database-config.js +1 -0
  20. package/dist/tests/helpers/index.js +2 -0
  21. package/dist/tests/mocks/definition.mock.d.ts +6 -0
  22. package/dist/tests/mocks/definition.mock.js +7 -1
  23. package/dist/tests/mocks/testModel.d.ts +1 -1
  24. package/dist/tests/mocks/testModel.js +1 -1
  25. package/dist/types/index.d.ts +5 -4
  26. package/dist/utils/init.d.ts +4 -4
  27. package/dist/utils/init.js +6 -7
  28. package/package.json +2 -2
  29. package/src/api/v1/definition/index.ts +1 -5
  30. package/src/hooks/create.ts +12 -5
  31. package/src/hooks/enrich.ts +17 -3
  32. package/src/hooks/find.ts +1 -0
  33. package/src/hooks/update.ts +8 -3
  34. package/src/index.ts +2 -2
  35. package/src/models/index.ts +14 -14
  36. package/src/models/tests/contextAwareModels/ContextAwareTestModel.ts +45 -0
  37. package/src/models/tests/contextAwareModels/ContextModel.ts +38 -0
  38. package/src/repository/definition.ts +16 -16
  39. package/src/repository/value.ts +12 -5
  40. package/src/tests/helpers/database-config.ts +1 -0
  41. package/src/tests/helpers/index.ts +5 -1
  42. package/src/tests/mocks/definition.mock.ts +7 -0
  43. package/src/tests/mocks/testModel.ts +1 -1
  44. package/src/types/index.ts +5 -5
  45. package/src/utils/init.ts +12 -11
@@ -41,7 +41,6 @@ const toPascalCase = (str) => str.replace(/(^\w|-\w)/g, (subStr) => subStr.repla
41
41
  router.post('/', async (req, res) => {
42
42
  const { modelName } = req.params;
43
43
  const modelType = toPascalCase(modelName);
44
- logger_1.default.info('sadot Creating custom field definition', { modelName });
45
44
  try {
46
45
  const validatedPayload = await (0, validations_1.validateCustomFieldDefinitionCreation)(req.body);
47
46
  const customFieldDefinition = await DefinitionRepo.create({
@@ -84,9 +83,7 @@ router.get('/', async (req, res) => {
84
83
  if (entityIds?.length > 0) {
85
84
  where.entityId = entityIds;
86
85
  }
87
- logger_1.default.info('sadot Fetching custom field definitions', { modelType, entityIds, where });
88
86
  const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true });
89
- logger_1.default.info('sadot Fetched custom field definitions customFieldDefinitions', { customFieldDefinitions });
90
87
  return res.json(customFieldDefinitions);
91
88
  }
92
89
  catch (err) {
@@ -101,7 +98,6 @@ router.patch('/:customFieldDefinitionId', async (req, res) => {
101
98
  const { customFieldDefinitionId, modelName } = req.params;
102
99
  const modelType = toPascalCase(modelName);
103
100
  try {
104
- logger_1.default.info('sadot Updating custom field definition', { customFieldDefinitionId, modelType });
105
101
  // eslint-disable-next-line max-len
106
102
  const validatedPayload = await (0, validations_1.validateCustomFieldDefinitionUpdate)(req.body);
107
103
  const customFieldDefinition = await DefinitionRepo.findByWhere({
@@ -1,3 +1,4 @@
1
+ import { ModelOptions } from '../types';
1
2
  /**
2
3
  * A hook to create the custom fields when updating a model (more then one instance).
3
4
  */
@@ -6,4 +7,4 @@ export declare const beforeBulkCreate: (options: any) => void;
6
7
  * A hook to create the custom fields when updating a model instance.
7
8
  * TODO - cleanup if update fail
8
9
  */
9
- export declare const beforeCreate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
10
+ export declare const beforeCreate: (scopeAttributes: string[], modelOptions: ModelOptions) => (instance: any, options: any) => Promise<void>;
@@ -22,12 +22,8 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
25
  Object.defineProperty(exports, "__esModule", { value: true });
29
26
  exports.beforeCreate = exports.beforeBulkCreate = void 0;
30
- const logger_1 = __importDefault(require("../utils/logger"));
31
27
  const ValueRepo = __importStar(require("../repository/value"));
32
28
  const DefinitionRepo = __importStar(require("../repository/definition"));
33
29
  const errors_1 = require("../errors");
@@ -44,11 +40,14 @@ exports.beforeBulkCreate = beforeBulkCreate;
44
40
  * A hook to create the custom fields when updating a model instance.
45
41
  * TODO - cleanup if update fail
46
42
  */
47
- const beforeCreate = (scopeAttributes) => async (instance, options) => {
48
- logger_1.default.debug('sadot - before create hook');
43
+ const beforeCreate = (scopeAttributes, modelOptions) => async (instance, options) => {
49
44
  const { fields } = options;
50
45
  const modelType = instance.constructor.name;
51
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
46
+ const { scopeAttributeReplacer } = modelOptions;
47
+ let identifiers = scopeAttributes.map((attribute) => instance[attribute]);
48
+ if (scopeAttributeReplacer) {
49
+ identifiers = await scopeAttributeReplacer(identifiers);
50
+ }
52
51
  // get all model's required definitions
53
52
  const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers);
54
53
  const customFieldsIdx = fields.indexOf('customFields');
@@ -59,7 +58,9 @@ const beforeCreate = (scopeAttributes) => async (instance, options) => {
59
58
  if (missingFields?.length > 0) {
60
59
  throw new errors_1.MissingRequiredCustomFieldError(missingFields);
61
60
  }
62
- await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
61
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, {
62
+ transaction: options.transaction,
63
+ });
63
64
  // eslint-disable-next-line no-param-reassign
64
65
  fields.splice(customFieldsIdx, 1);
65
66
  }
@@ -1,6 +1,7 @@
1
+ import { ModelOptions } from '../types';
1
2
  type SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';
2
3
  /**
3
4
  * A hook to attach the custom fields when fetching a model instances.
4
5
  */
5
- declare const enrichResults: (modelType: string, scopeAttributes: string[], hookType?: SupportedHookTypes) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
6
+ declare const enrichResults: (modelType: string, scopeAttributes: string[], getScope: any, hookType?: SupportedHookTypes, modelOptions?: ModelOptions) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
6
7
  export default enrichResults;
@@ -22,10 +22,14 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
25
28
  Object.defineProperty(exports, "__esModule", { value: true });
26
29
  /* eslint-disable no-param-reassign */
27
30
  const ValueRepo = __importStar(require("../repository/value"));
28
31
  const DefinitionRepo = __importStar(require("../repository/definition"));
32
+ const logger_1 = __importDefault(require("../utils/logger"));
29
33
  /**
30
34
  * Serialize custom fields value into the format of {[name] -> [fieldData]}
31
35
  */
@@ -40,7 +44,8 @@ const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) =>
40
44
  /**
41
45
  * A hook to attach the custom fields when fetching a model instances.
42
46
  */
43
- const enrichResults = (modelType, scopeAttributes, hookType) => async (instancesOrInstance, options) => {
47
+ const enrichResults = (modelType, scopeAttributes, getScope, hookType, modelOptions) => async (instancesOrInstance, options) => {
48
+ const { scopeAttributeReplacer } = modelOptions;
44
49
  if (options.originalAttributes?.length > 0
45
50
  && !options.originalAttributes?.includes?.('customFields')) {
46
51
  return;
@@ -50,20 +55,24 @@ const enrichResults = (modelType, scopeAttributes, hookType) => async (instances
50
55
  ? instancesOrInstance
51
56
  : [instancesOrInstance];
52
57
  instances = instances.filter(Boolean);
53
- const identifiers = instances.map((instance) => scopeAttributes
58
+ let identifiers = instances.map((instance) => scopeAttributes
54
59
  .map((attr) => instance[attr])).flat();
60
+ if (scopeAttributeReplacer) {
61
+ identifiers = await scopeAttributeReplacer(identifiers);
62
+ }
63
+ logger_1.default.info('enrichResults - sadot - indentifiers: ', identifiers);
55
64
  const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
56
65
  const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
57
66
  ...map,
58
67
  [identifier]: [],
59
68
  }), {});
60
- const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction });
69
+ const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction, getScope });
61
70
  const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
62
71
  ...map,
63
72
  [definition.id]: definition,
64
73
  }), {});
65
74
  customFieldDefinitions.forEach((cfd) => {
66
- identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
75
+ identifierCustomFieldDefinitionsMapping[cfd.entityId]?.push(cfd);
67
76
  });
68
77
  // Get the values per instates ids:
69
78
  const instancesIds = instances.map((i) => i[primaryKey]);
@@ -1,3 +1,4 @@
1
+ import { ModelOptions } from '../types';
1
2
  /**
2
3
  * A hook to update the custom fields when updating a model (more then one instance).
3
4
  */
@@ -6,4 +7,4 @@ export declare const beforeBulkUpdate: (options: any) => void;
6
7
  * A hook to update the custom fields when updating a model instance.
7
8
  * TODO - cleanup if update fail
8
9
  */
9
- export declare const beforeUpdate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
10
+ export declare const beforeUpdate: (scopeAttributes: string[], modelOptions: ModelOptions) => (instance: any, options: any) => Promise<void>;
@@ -42,11 +42,15 @@ exports.beforeBulkUpdate = beforeBulkUpdate;
42
42
  * A hook to update the custom fields when updating a model instance.
43
43
  * TODO - cleanup if update fail
44
44
  */
45
- const beforeUpdate = (scopeAttributes) => async (instance, options) => {
45
+ const beforeUpdate = (scopeAttributes, modelOptions) => async (instance, options) => {
46
46
  logger_1.default.debug('sadot - before update hook');
47
47
  const { fields } = options;
48
+ const { scopeAttributeReplacer } = modelOptions;
48
49
  const modelType = instance.constructor.name;
49
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
50
+ let identifiers = scopeAttributes.map((attribute) => instance[attribute]);
51
+ if (scopeAttributeReplacer) {
52
+ identifiers = await scopeAttributeReplacer(identifiers);
53
+ }
50
54
  const customFieldsIdx = fields.indexOf('customFields');
51
55
  if (customFieldsIdx > -1) {
52
56
  const { customFields } = instance;
package/dist/index.js CHANGED
@@ -32,7 +32,7 @@ __exportStar(require("./utils/constants"), exports);
32
32
  const useCustomFields = async (app, getModel, options) => {
33
33
  const { models } = options;
34
34
  if (app) {
35
- app.use('/api', options.middleware, api_1.default);
35
+ app.use('/api', api_1.default);
36
36
  }
37
37
  const sequelize = (0, db_1.default)(options.databaseConfig);
38
38
  if (process.env.NODE_ENV === 'test') {
@@ -40,7 +40,7 @@ const useCustomFields = async (app, getModel, options) => {
40
40
  }
41
41
  // The order is important
42
42
  (0, init_1.addHooks)(models, getModel);
43
- await (0, models_1.initTables)(sequelize, options.getUser, options.enrichUserPermissions);
43
+ await (0, models_1.initTables)(sequelize, options.getUser);
44
44
  (0, init_1.addScopes)(models, getModel);
45
45
  logger_1.default.debug('sadot - custom fields finished initializing with models', models);
46
46
  return sequelize;
@@ -2,7 +2,9 @@ import type { Sequelize } from 'sequelize-typescript';
2
2
  import CustomFieldDefinition from './CustomFieldDefinition';
3
3
  import CustomFieldValue from './CustomFieldValue';
4
4
  import TestModel from './tests/TestModel';
5
+ import ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';
6
+ import ContextModel from './tests/contextAwareModels/ContextModel';
5
7
  import AssociatedTestModel from './tests/AssociatedTestModel';
6
- declare const initTables: (sequelize: Sequelize, getUser: any, enrichUserPermissions: any) => Promise<void>;
8
+ declare const initTables: (sequelize: Sequelize, getUser: any) => Promise<void>;
7
9
  declare const initTestModels: (sequelize: Sequelize) => Promise<void>;
8
- export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, initTables, initTestModels, };
10
+ export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, ContextAwareTestModel, ContextModel, initTables, initTestModels, };
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.initTestModels = exports.initTables = exports.AssociatedTestModel = exports.TestModel = exports.CustomFieldDefinition = exports.CustomFieldValue = void 0;
6
+ exports.initTestModels = exports.initTables = exports.ContextModel = exports.ContextAwareTestModel = exports.AssociatedTestModel = exports.TestModel = exports.CustomFieldDefinition = exports.CustomFieldValue = void 0;
7
7
  /* eslint-disable no-param-reassign */
8
8
  const sequelize_1 = require("sequelize");
9
9
  const logger_1 = __importDefault(require("../utils/logger"));
@@ -13,14 +13,18 @@ const CustomFieldValue_1 = __importDefault(require("./CustomFieldValue"));
13
13
  exports.CustomFieldValue = CustomFieldValue_1.default;
14
14
  const TestModel_1 = __importDefault(require("./tests/TestModel"));
15
15
  exports.TestModel = TestModel_1.default;
16
+ const ContextAwareTestModel_1 = __importDefault(require("./tests/contextAwareModels/ContextAwareTestModel"));
17
+ exports.ContextAwareTestModel = ContextAwareTestModel_1.default;
18
+ const ContextModel_1 = __importDefault(require("./tests/contextAwareModels/ContextModel"));
19
+ exports.ContextModel = ContextModel_1.default;
16
20
  const AssociatedTestModel_1 = __importDefault(require("./tests/AssociatedTestModel"));
17
21
  exports.AssociatedTestModel = AssociatedTestModel_1.default;
18
22
  const productionModels = [CustomFieldDefinition_1.default, CustomFieldValue_1.default];
19
- const testModels = [TestModel_1.default, AssociatedTestModel_1.default];
23
+ const testModels = [TestModel_1.default, AssociatedTestModel_1.default, ContextAwareTestModel_1.default, ContextModel_1.default];
20
24
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
21
25
  const SCHEMA_VERSION = 1;
22
26
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
23
- const initTables = async (sequelize, getUser, enrichUserPermissions) => {
27
+ const initTables = async (sequelize, getUser) => {
24
28
  logger_1.default.info('custom-fields: initialize custom-fields tables');
25
29
  // Detect models and import them to the orm
26
30
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -28,22 +32,16 @@ const initTables = async (sequelize, getUser, enrichUserPermissions) => {
28
32
  throw new Error('sequelize instance must have addModels function');
29
33
  }
30
34
  sequelize.addModels(productionModels);
31
- CustomFieldDefinition_1.default.addScope('userScope', (entityIds) => {
35
+ CustomFieldDefinition_1.default.addScope('userScope', () => {
32
36
  const user = getUser();
33
37
  if (user?.permissions) {
34
- logger_1.default.info('custom fields scope added', { entityIds, permissions: user.permissions, enrichUserPermissions: !!enrichUserPermissions });
35
- const entityId = [
36
- ...Object.keys(user.permissions.fleets),
37
- ...Object.keys(user.permissions.businessModels),
38
- ...Object.keys(user.permissions.demandSources),
39
- ];
40
- if (enrichUserPermissions && entityIds && Array.isArray(entityIds)) {
41
- entityId.push(...entityIds);
42
- }
43
- logger_1.default.info('custom fields scope added updated entity:', { entityId });
44
38
  return {
45
39
  where: {
46
- entityId,
40
+ entityId: [
41
+ ...Object.keys(user.permissions.fleets),
42
+ ...Object.keys(user.permissions.businessModels),
43
+ ...Object.keys(user.permissions.demandSources),
44
+ ],
47
45
  },
48
46
  };
49
47
  }
@@ -88,6 +86,8 @@ const initTestModels = async (sequelize) => {
88
86
  logger_1.default.info('custom-fields: test models added');
89
87
  await TestModel_1.default.sync({ alter: true });
90
88
  await AssociatedTestModel_1.default.sync({ alter: true });
89
+ await ContextModel_1.default.sync({ alter: true });
90
+ await ContextAwareTestModel_1.default.sync({ alter: true });
91
91
  logger_1.default.info('custom-fields: test models synced');
92
92
  };
93
93
  exports.initTestModels = initTestModels;
@@ -0,0 +1,10 @@
1
+ import { Model } from 'sequelize-typescript';
2
+ import ContextModel from './ContextModel';
3
+ declare class ContextAwareTestModel extends Model {
4
+ id: string;
5
+ contextId: string;
6
+ coolAttribute?: boolean;
7
+ customFields?: any;
8
+ context: ContextModel;
9
+ }
10
+ export default ContextAwareTestModel;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ /* eslint-disable @typescript-eslint/no-unused-vars */
16
+ const sequelize_typescript_1 = require("sequelize-typescript");
17
+ const ContextModel_1 = __importDefault(require("./ContextModel"));
18
+ let ContextAwareTestModel = class ContextAwareTestModel extends sequelize_typescript_1.Model {
19
+ };
20
+ __decorate([
21
+ sequelize_typescript_1.PrimaryKey,
22
+ (0, sequelize_typescript_1.Column)({
23
+ type: sequelize_typescript_1.DataType.UUID,
24
+ defaultValue: sequelize_typescript_1.DataType.UUIDV4,
25
+ allowNull: false,
26
+ }),
27
+ __metadata("design:type", String)
28
+ ], ContextAwareTestModel.prototype, "id", void 0);
29
+ __decorate([
30
+ (0, sequelize_typescript_1.ForeignKey)(() => ContextModel_1.default),
31
+ (0, sequelize_typescript_1.Column)({
32
+ type: sequelize_typescript_1.DataType.UUID,
33
+ }),
34
+ __metadata("design:type", String)
35
+ ], ContextAwareTestModel.prototype, "contextId", void 0);
36
+ __decorate([
37
+ (0, sequelize_typescript_1.Column)({
38
+ type: sequelize_typescript_1.DataType.BOOLEAN,
39
+ }),
40
+ __metadata("design:type", Boolean)
41
+ ], ContextAwareTestModel.prototype, "coolAttribute", void 0);
42
+ __decorate([
43
+ (0, sequelize_typescript_1.Column)({
44
+ type: sequelize_typescript_1.DataType.VIRTUAL,
45
+ }),
46
+ __metadata("design:type", Object)
47
+ ], ContextAwareTestModel.prototype, "customFields", void 0);
48
+ __decorate([
49
+ (0, sequelize_typescript_1.BelongsTo)(() => ContextModel_1.default),
50
+ __metadata("design:type", ContextModel_1.default)
51
+ ], ContextAwareTestModel.prototype, "context", void 0);
52
+ ContextAwareTestModel = __decorate([
53
+ (0, sequelize_typescript_1.Table)({ createdAt: false, updatedAt: false })
54
+ ], ContextAwareTestModel);
55
+ exports.default = ContextAwareTestModel;
@@ -0,0 +1,13 @@
1
+ import { Model } from 'sequelize-typescript';
2
+ declare enum EEntityTypes {
3
+ BUSINESS_MODEL = "businessModel",
4
+ CONTEXT = "context",
5
+ DEMAND_SOURCE = "demandSource",
6
+ FLEET = "fleet"
7
+ }
8
+ declare class ContextModel extends Model {
9
+ id: string;
10
+ entityId: string;
11
+ entityType: EEntityTypes;
12
+ }
13
+ export default ContextModel;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ /* eslint-disable @typescript-eslint/no-unused-vars */
13
+ const sequelize_typescript_1 = require("sequelize-typescript");
14
+ // eslint-disable-next-line no-shadow
15
+ var EEntityTypes;
16
+ (function (EEntityTypes) {
17
+ EEntityTypes["BUSINESS_MODEL"] = "businessModel";
18
+ EEntityTypes["CONTEXT"] = "context";
19
+ EEntityTypes["DEMAND_SOURCE"] = "demandSource";
20
+ EEntityTypes["FLEET"] = "fleet";
21
+ })(EEntityTypes || (EEntityTypes = {}));
22
+ let ContextModel = class ContextModel extends sequelize_typescript_1.Model {
23
+ };
24
+ __decorate([
25
+ sequelize_typescript_1.PrimaryKey,
26
+ (0, sequelize_typescript_1.Column)({
27
+ defaultValue: sequelize_typescript_1.DataType.UUIDV4,
28
+ type: sequelize_typescript_1.DataType.UUID,
29
+ }),
30
+ __metadata("design:type", String)
31
+ ], ContextModel.prototype, "id", void 0);
32
+ __decorate([
33
+ (0, sequelize_typescript_1.Column)({
34
+ type: sequelize_typescript_1.DataType.UUID,
35
+ }),
36
+ __metadata("design:type", String)
37
+ ], ContextModel.prototype, "entityId", void 0);
38
+ __decorate([
39
+ (0, sequelize_typescript_1.Column)({
40
+ type: sequelize_typescript_1.DataType.ENUM(...Object.values(EEntityTypes)),
41
+ }),
42
+ __metadata("design:type", String)
43
+ ], ContextModel.prototype, "entityType", void 0);
44
+ ContextModel = __decorate([
45
+ (0, sequelize_typescript_1.Table)({ createdAt: false, updatedAt: false })
46
+ ], ContextModel);
47
+ exports.default = ContextModel;
@@ -1,10 +1,10 @@
1
+ import { WhereOptions } from 'sequelize';
1
2
  import { CustomFieldDefinition } from '../models';
2
3
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
3
4
  export declare const create: (data: CreateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
4
- export declare const findAll: (where: any, options?: any) => Promise<CustomFieldDefinition[]>;
5
+ export declare const findAll: (where: WhereOptions, options?: any) => Promise<CustomFieldDefinition[]>;
5
6
  export declare const findByIds: (ids: string[], options?: any) => Promise<CustomFieldDefinition[]>;
6
7
  export declare const findById: (id: string, options?: any) => Promise<CustomFieldDefinition | null>;
7
- export declare const findByEntityId: (entityId: string, options?: any) => Promise<CustomFieldDefinition[]>;
8
8
  export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: any) => Promise<CustomFieldDefinition[]>;
9
9
  export declare const findByWhere: (where: any) => Promise<CustomFieldDefinition | null>;
10
10
  export declare const findDefinitionsByModels: (modelTypes: string[], options?: any) => Promise<CustomFieldDefinition[]>;
@@ -1,19 +1,23 @@
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.getRequiredFields = exports.destroy = exports.disable = exports.update = exports.findDefinitionsByModels = exports.findByWhere = exports.findByEntityIds = exports.findByEntityId = exports.findById = exports.findByIds = exports.findAll = exports.create = void 0;
6
+ exports.getRequiredFields = exports.destroy = exports.disable = exports.update = exports.findDefinitionsByModels = exports.findByWhere = exports.findByEntityIds = exports.findById = exports.findByIds = exports.findAll = exports.create = void 0;
4
7
  const sequelize_1 = require("sequelize");
5
8
  const models_1 = require("../models");
9
+ const logger_1 = __importDefault(require("../utils/logger"));
6
10
  const create = (data) => models_1.CustomFieldDefinition.create(data);
7
11
  exports.create = create;
8
12
  const findAll = (where, options = { withDisabled: false }) => {
9
13
  const queryModel = options.withDisabled
10
14
  ? models_1.CustomFieldDefinition.unscoped()
11
15
  : models_1.CustomFieldDefinition;
12
- return queryModel.scope({ method: ['userScope', where.entityId] }).findAll({
16
+ logger_1.default.info('sadot - whereQuery', { options });
17
+ return queryModel.scope('userScope').findAll({
13
18
  where,
14
- transaction: options.transaction,
15
19
  raw: true,
16
- logging: console.log,
20
+ logging: true,
17
21
  });
18
22
  };
19
23
  exports.findAll = findAll;
@@ -27,23 +31,18 @@ const findById = (id, options = { withDisabled: false }) => {
27
31
  return models_1.CustomFieldDefinition.scope('userScope').findByPk(id);
28
32
  };
29
33
  exports.findById = findById;
30
- const findByEntityId = async (entityId, options = {}) => models_1.CustomFieldDefinition.findAll({
31
- where: { entityId },
32
- transaction: options.transaction,
33
- });
34
- exports.findByEntityId = findByEntityId;
35
34
  const findByEntityIds = async (modelType, entityIds, options = {}) => models_1.CustomFieldDefinition.findAll({
36
35
  where: {
37
36
  modelType,
38
37
  entityId: entityIds,
39
38
  },
40
39
  transaction: options.transaction,
40
+ include: options.include,
41
41
  raw: true,
42
42
  });
43
43
  exports.findByEntityIds = findByEntityIds;
44
44
  const findByWhere = (where) => models_1.CustomFieldDefinition.scope('userScope').findOne({
45
45
  where,
46
- logging: console.log,
47
46
  });
48
47
  exports.findByWhere = findByWhere;
49
48
  const findDefinitionsByModels = async (modelTypes, options) => {
@@ -73,7 +72,11 @@ exports.destroy = destroy;
73
72
  const getRequiredFields = async (modelType, modelId, entityId) => {
74
73
  const entityIds = Array.isArray(entityId) ? entityId : [entityId];
75
74
  const requiredFields = await models_1.CustomFieldDefinition.findAll({
76
- where: { required: true, modelType, entityId: { [sequelize_1.Op.in]: entityIds } },
75
+ where: {
76
+ required: true,
77
+ modelType,
78
+ entityId: { [sequelize_1.Op.in]: entityIds },
79
+ },
77
80
  logging: true,
78
81
  });
79
82
  const requiredFieldsNames = requiredFields.map((definition) => definition.name);
@@ -73,11 +73,18 @@ exports.findValuesByModelIds = findValuesByModelIds;
73
73
  * Return the updated values
74
74
  */
75
75
  const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
76
- logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, { valuesToUpdate });
77
76
  const names = Object.keys(valuesToUpdate);
78
- const fieldDefinitions = await DefinitionRepo.findAll({ modelType, name: names, entityId: identifiers }, { withDisabled: true, transaction: options.transaction }) || [];
77
+ logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, {
78
+ names, options, valuesToUpdate, entityId: identifiers,
79
+ });
80
+ const fieldDefinitions = (await DefinitionRepo.findAll({
81
+ modelType,
82
+ name: names,
83
+ entityId: identifiers,
84
+ }, { withDisabled: true, transaction: options.transaction })) || [];
79
85
  const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
80
86
  if (fieldDefinitions.length !== names.length) {
87
+ logger_1.default.info(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });
81
88
  const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));
82
89
  throw new errors_1.MissingDefinitionError(missingDefinitions);
83
90
  }
@@ -4,6 +4,7 @@ declare const _default: {
4
4
  password: string;
5
5
  database: string;
6
6
  host: string;
7
+ port: string | number;
7
8
  dialect: string;
8
9
  define: {
9
10
  underscored: boolean;
@@ -6,6 +6,7 @@ exports.default = {
6
6
  password: process.env.DB_PASSWORD || null,
7
7
  database: process.env.DB_NAME || 'sadot_package_test',
8
8
  host: process.env.DB_HOST || '127.0.0.1',
9
+ port: process.env.DB_PORT || 5432,
9
10
  dialect: process.env.DB_TYPE || 'postgres',
10
11
  define: {
11
12
  underscored: true,
@@ -7,6 +7,8 @@ const cleanup = async () => {
7
7
  if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
8
8
  await models_1.CustomFieldDefinition.unscoped().destroy({ where: {} });
9
9
  await models_1.TestModel.destroy({ where: {} });
10
+ await models_1.ContextAwareTestModel.destroy({ where: {} });
11
+ await models_1.ContextModel.destroy({ where: {} });
10
12
  }
11
13
  };
12
14
  exports.cleanup = cleanup;
@@ -1,4 +1,10 @@
1
1
  import { CreateCustomFieldDefinition, CustomFieldDefinitionDTO } from '../../types/definition';
2
+ export declare const contextAwareFieldDefinition: {
3
+ name: string;
4
+ modelType: string;
5
+ fieldType: string;
6
+ entityType: string;
7
+ };
2
8
  export declare const coolFieldDefinition: CreateCustomFieldDefinition;
3
9
  export declare const coolFieldDefinition2: {
4
10
  name: string;
@@ -1,7 +1,13 @@
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 = 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
+ exports.contextAwareFieldDefinition = {
6
+ name: 'cool field',
7
+ modelType: 'ContextAwareTestModel',
8
+ fieldType: 'number',
9
+ entityType: 'fleetId',
10
+ };
5
11
  exports.coolFieldDefinition = {
6
12
  name: 'cool field',
7
13
  modelType: 'TestModel',
@@ -1,5 +1,5 @@
1
1
  import { TestModel } from '../../models';
2
- export declare const createTestModel: (payload?: {}) => Promise<TestModel>;
2
+ export declare const createTestModel: (payload?: {}, model?: any) => any;
3
3
  export declare const createTestModels: (fleetId: any, total: number) => Promise<TestModel[]>;
4
4
  export declare const upsertTestModel: (payload: any) => Promise<[TestModel, boolean]>;
5
5
  export declare const destroyTestModels: () => Promise<number>;
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getTestModelWithAssociation = exports.createTestModelWithAssociation = exports.updateTestModel = exports.getSomeTestModels = exports.getTestModel = exports.destroyTestModels = exports.upsertTestModel = exports.createTestModels = exports.createTestModel = void 0;
4
4
  const models_1 = require("../../models");
5
- const createTestModel = (payload = {}) => models_1.TestModel.create(payload);
5
+ const createTestModel = (payload = {}, model = models_1.TestModel) => model.create(payload);
6
6
  exports.createTestModel = createTestModel;
7
7
  const createTestModels = (fleetId, total) => {
8
8
  const models = [];
@@ -1,16 +1,17 @@
1
- import { RequestHandler } from 'express';
2
1
  export type ModelFetcher = (name: string) => any;
3
2
  export type ModelOptions = {
3
+ scopeAttributeReplacer?: (attributes?: string[]) => Promise<any>;
4
+ };
5
+ export type Models = {
4
6
  name: string;
5
7
  scopeAttributes: string[];
8
+ modelOptions?: ModelOptions;
6
9
  creationWebhookHandler?: (instance: any) => any;
7
10
  updateWebhookHandler?: (instance: any) => any;
8
11
  deletionWebhookHandler?: (instance: any) => any;
9
12
  };
10
13
  export type CustomFieldOptions = {
11
- models: ModelOptions[];
14
+ models: Models[];
12
15
  databaseConfig: any;
13
16
  getUser: () => any;
14
- enrichUserPermissions?: (entityIds: string[]) => any;
15
- middleware?: RequestHandler;
16
17
  };
@@ -1,4 +1,4 @@
1
- import type { ModelFetcher, ModelOptions } from '../types';
2
- export declare const addHooks: (models: ModelOptions[], getModel: ModelFetcher) => void;
3
- export declare const removeHooks: (models: ModelOptions[], getModel: ModelFetcher) => void;
4
- export declare const addScopes: (models: ModelOptions[], getModel: ModelFetcher) => void;
1
+ import type { ModelFetcher, Models } from '../types';
2
+ export declare const addHooks: (models: Models[], getModel: ModelFetcher) => void;
3
+ export declare const removeHooks: (models: Models[], getModel: ModelFetcher) => void;
4
+ export declare const addScopes: (models: Models[], getModel: ModelFetcher) => void;