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

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 +1 -1
  3. package/dist/hooks/create.js +10 -8
  4. package/dist/hooks/enrich.d.ts +1 -1
  5. package/dist/hooks/enrich.js +17 -4
  6. package/dist/hooks/update.d.ts +1 -1
  7. package/dist/hooks/update.js +7 -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 +5 -4
  16. package/dist/repository/definition.js +18 -12
  17. package/dist/repository/value.js +10 -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 +8 -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 +14 -5
  31. package/src/hooks/enrich.ts +21 -3
  32. package/src/hooks/find.ts +1 -0
  33. package/src/hooks/update.ts +11 -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 +22 -15
  39. package/src/repository/value.ts +13 -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 +9 -4
  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({
@@ -6,4 +6,4 @@ export declare const beforeBulkCreate: (options: any) => void;
6
6
  * A hook to create the custom fields when updating a model instance.
7
7
  * TODO - cleanup if update fail
8
8
  */
9
- export declare const beforeCreate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
9
+ export declare const beforeCreate: (scopeAttributes: string[], identifiersReplacer: any) => (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");
@@ -35,6 +31,7 @@ const errors_1 = require("../errors");
35
31
  * A hook to create the custom fields when updating a model (more then one instance).
36
32
  */
37
33
  const beforeBulkCreate = (options) => {
34
+ console.log('hooks - before bulk create');
38
35
  // This will activate the beforeCreate hook on each updating instance.
39
36
  // eslint-disable-next-line no-param-reassign
40
37
  options.individualHooks = true;
@@ -44,11 +41,14 @@ exports.beforeBulkCreate = beforeBulkCreate;
44
41
  * A hook to create the custom fields when updating a model instance.
45
42
  * TODO - cleanup if update fail
46
43
  */
47
- const beforeCreate = (scopeAttributes) => async (instance, options) => {
48
- logger_1.default.debug('sadot - before create hook');
44
+ const beforeCreate = (scopeAttributes, identifiersReplacer) => async (instance, options) => {
49
45
  const { fields } = options;
50
46
  const modelType = instance.constructor.name;
51
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
47
+ console.log('hooks - before create');
48
+ let identifiers = scopeAttributes.map((attribute) => instance[attribute]);
49
+ if (identifiersReplacer) {
50
+ identifiers = await identifiersReplacer(identifiers);
51
+ }
52
52
  // get all model's required definitions
53
53
  const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers);
54
54
  const customFieldsIdx = fields.indexOf('customFields');
@@ -59,7 +59,9 @@ const beforeCreate = (scopeAttributes) => async (instance, options) => {
59
59
  if (missingFields?.length > 0) {
60
60
  throw new errors_1.MissingRequiredCustomFieldError(missingFields);
61
61
  }
62
- await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
62
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, {
63
+ transaction: options.transaction,
64
+ });
63
65
  // eslint-disable-next-line no-param-reassign
64
66
  fields.splice(customFieldsIdx, 1);
65
67
  }
@@ -2,5 +2,5 @@ type SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';
2
2
  /**
3
3
  * A hook to attach the custom fields when fetching a model instances.
4
4
  */
5
- declare const enrichResults: (modelType: string, scopeAttributes: string[], hookType?: SupportedHookTypes) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
5
+ declare const enrichResults: (modelType: string, scopeAttributes: string[], getScope: any, hookType?: SupportedHookTypes, identifiersReplacer?: any) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
6
6
  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, identifiersReplacer) => async (instancesOrInstance, options) => {
48
+ console.log('hooks - enrichResults', modelType);
44
49
  if (options.originalAttributes?.length > 0
45
50
  && !options.originalAttributes?.includes?.('customFields')) {
46
51
  return;
@@ -50,20 +55,25 @@ 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 (identifiersReplacer) {
61
+ identifiers = await identifiersReplacer(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
+ console.log({ identifierCustomFieldDefinitionsMapping });
70
+ const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction, getScope });
61
71
  const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
62
72
  ...map,
63
73
  [definition.id]: definition,
64
74
  }), {});
65
75
  customFieldDefinitions.forEach((cfd) => {
66
- identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
76
+ identifierCustomFieldDefinitionsMapping[cfd.entityId]?.push(cfd);
67
77
  });
68
78
  // Get the values per instates ids:
69
79
  const instancesIds = instances.map((i) => i[primaryKey]);
@@ -88,6 +98,9 @@ const enrichResults = (modelType, scopeAttributes, hookType) => async (instances
88
98
  }
89
99
  scopeAttributes.forEach((attribute) => {
90
100
  const identifier = instance[attribute];
101
+ console.log({
102
+ identifier, attribute, instance, identifierCustomFieldDefinitionsMapping,
103
+ });
91
104
  const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
92
105
  if (entityCustomFieldDefinitions?.length > 0) {
93
106
  entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
@@ -6,4 +6,4 @@ export declare const beforeBulkUpdate: (options: any) => void;
6
6
  * A hook to update the custom fields when updating a model instance.
7
7
  * TODO - cleanup if update fail
8
8
  */
9
- export declare const beforeUpdate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
9
+ export declare const beforeUpdate: (scopeAttributes: string[], identifiersReplacer: any) => (instance: any, options: any) => Promise<void>;
@@ -33,6 +33,7 @@ const ValueRepo = __importStar(require("../repository/value"));
33
33
  * A hook to update the custom fields when updating a model (more then one instance).
34
34
  */
35
35
  const beforeBulkUpdate = (options) => {
36
+ console.log('hooks - beforeBulkUpdate');
36
37
  // This will activate the beforeUpdate hook on each updating instance.
37
38
  // eslint-disable-next-line no-param-reassign
38
39
  options.individualHooks = true;
@@ -42,11 +43,15 @@ exports.beforeBulkUpdate = beforeBulkUpdate;
42
43
  * A hook to update the custom fields when updating a model instance.
43
44
  * TODO - cleanup if update fail
44
45
  */
45
- const beforeUpdate = (scopeAttributes) => async (instance, options) => {
46
+ const beforeUpdate = (scopeAttributes, identifiersReplacer) => async (instance, options) => {
46
47
  logger_1.default.debug('sadot - before update hook');
48
+ console.log('hooks - beforeUpdate');
47
49
  const { fields } = options;
48
50
  const modelType = instance.constructor.name;
49
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
51
+ let identifiers = scopeAttributes.map((attribute) => instance[attribute]);
52
+ if (identifiersReplacer) {
53
+ identifiers = await identifiersReplacer(identifiers);
54
+ }
50
55
  const customFieldsIdx = fields.indexOf('customFields');
51
56
  if (customFieldsIdx > -1) {
52
57
  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,11 +1,12 @@
1
+ import { WhereOptions } from 'sequelize';
1
2
  import { CustomFieldDefinition } from '../models';
2
3
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
4
+ import { ModelOptions } from '../types';
3
5
  export declare const create: (data: CreateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
4
- export declare const findAll: (where: any, options?: any) => Promise<CustomFieldDefinition[]>;
6
+ export declare const findAll: (where: WhereOptions, options?: any) => Promise<CustomFieldDefinition[]>;
5
7
  export declare const findByIds: (ids: string[], options?: any) => Promise<CustomFieldDefinition[]>;
6
8
  export declare const findById: (id: string, options?: any) => Promise<CustomFieldDefinition | null>;
7
- export declare const findByEntityId: (entityId: string, options?: any) => Promise<CustomFieldDefinition[]>;
8
- export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: any) => Promise<CustomFieldDefinition[]>;
9
+ export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: any, modelOptions?: ModelOptions) => Promise<CustomFieldDefinition[]>;
9
10
  export declare const findByWhere: (where: any) => Promise<CustomFieldDefinition | null>;
10
11
  export declare const findDefinitionsByModels: (modelTypes: string[], options?: any) => Promise<CustomFieldDefinition[]>;
11
12
  export declare const update: (id: string, data: UpdateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
@@ -14,4 +15,4 @@ export declare const destroy: (id: string) => Promise<any>;
14
15
  /**
15
16
  * Return the names of the required fields for a given model
16
17
  */
17
- export declare const getRequiredFields: (modelType: string, modelId: string | string[], entityId: string | string[]) => Promise<string[]>;
18
+ export declare const getRequiredFields: (modelType: string, modelId: string | string[], entityId: string | string[], modelOptions?: ModelOptions) => Promise<string[]>;
@@ -1,19 +1,24 @@
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
20
  logging: console.log,
21
+ include: options.include,
17
22
  });
18
23
  };
19
24
  exports.findAll = findAll;
@@ -27,23 +32,19 @@ const findById = (id, options = { withDisabled: false }) => {
27
32
  return models_1.CustomFieldDefinition.scope('userScope').findByPk(id);
28
33
  };
29
34
  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
- const findByEntityIds = async (modelType, entityIds, options = {}) => models_1.CustomFieldDefinition.findAll({
35
+ const findByEntityIds = async (modelType, entityIds, options = {}, modelOptions = {}) => models_1.CustomFieldDefinition.findAll({
36
36
  where: {
37
37
  modelType,
38
38
  entityId: entityIds,
39
+ ...modelOptions?.customEntityMapper?.(entityIds),
39
40
  },
40
41
  transaction: options.transaction,
42
+ include: options.include,
41
43
  raw: true,
42
44
  });
43
45
  exports.findByEntityIds = findByEntityIds;
44
46
  const findByWhere = (where) => models_1.CustomFieldDefinition.scope('userScope').findOne({
45
47
  where,
46
- logging: console.log,
47
48
  });
48
49
  exports.findByWhere = findByWhere;
49
50
  const findDefinitionsByModels = async (modelTypes, options) => {
@@ -70,10 +71,15 @@ exports.destroy = destroy;
70
71
  /**
71
72
  * Return the names of the required fields for a given model
72
73
  */
73
- const getRequiredFields = async (modelType, modelId, entityId) => {
74
+ const getRequiredFields = async (modelType, modelId, entityId, modelOptions = {}) => {
74
75
  const entityIds = Array.isArray(entityId) ? entityId : [entityId];
75
76
  const requiredFields = await models_1.CustomFieldDefinition.findAll({
76
- where: { required: true, modelType, entityId: { [sequelize_1.Op.in]: entityIds } },
77
+ where: {
78
+ required: true,
79
+ modelType,
80
+ entityId: { [sequelize_1.Op.in]: entityIds },
81
+ ...modelOptions?.customEntityMapper?.(entityIds),
82
+ },
77
83
  logging: true,
78
84
  });
79
85
  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
  }
@@ -95,6 +102,7 @@ const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, opt
95
102
  return Promise.all(values.map(async (value) => {
96
103
  const [cfv] = await models_1.CustomFieldValue.upsert(value, {
97
104
  transaction: options.transaction,
105
+ logging: console.log,
98
106
  });
99
107
  return cfv;
100
108
  }));
@@ -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 = [];