@autofleet/sadot 0.3.2 → 0.4.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 (136) hide show
  1. package/.nvmrc +1 -0
  2. package/dist/jest.config.d.ts +12 -0
  3. package/dist/{api → src/api}/index.js +0 -1
  4. package/dist/{api → src/api}/v1/definition/index.js +19 -26
  5. package/dist/{api → src/api}/v1/definition/validations.js +0 -1
  6. package/dist/src/api/v1/errors.d.ts +2 -0
  7. package/dist/{api → src/api}/v1/errors.js +1 -2
  8. package/dist/{api → src/api}/v1/index.js +0 -1
  9. package/dist/{errors → src/errors}/index.js +0 -1
  10. package/dist/{events → src/events}/index.js +1 -2
  11. package/dist/{hooks → src/hooks}/create.js +6 -16
  12. package/dist/{hooks → src/hooks}/enrich.js +23 -27
  13. package/dist/{hooks → src/hooks}/find.js +3 -5
  14. package/dist/{hooks → src/hooks}/index.js +0 -1
  15. package/dist/{hooks → src/hooks}/update.js +3 -13
  16. package/dist/{hooks → src/hooks}/workaround.js +3 -13
  17. package/dist/{index.d.ts → src/index.d.ts} +2 -1
  18. package/dist/src/index.js +52 -0
  19. package/dist/{models → src/models}/CustomFieldDefinition.js +1 -2
  20. package/dist/{models → src/models}/CustomFieldValue.js +20 -34
  21. package/dist/{models → src/models}/index.js +13 -23
  22. package/dist/{models → src/models}/tests/AssociatedTestModel.js +0 -1
  23. package/dist/{models → src/models}/tests/TestModel.d.ts +1 -0
  24. package/dist/{models → src/models}/tests/TestModel.js +6 -1
  25. package/dist/{repository → src/repository}/definition.js +19 -33
  26. package/dist/{repository → src/repository}/value.js +18 -28
  27. package/dist/src/scopes/filter.d.ts +23 -0
  28. package/dist/src/scopes/filter.js +43 -0
  29. package/dist/src/scopes/index.d.ts +2 -0
  30. package/dist/src/scopes/index.js +6 -0
  31. package/dist/{tests → src/tests}/api/test-api.js +12 -22
  32. package/dist/{tests → src/tests}/helpers/database-config.js +0 -1
  33. package/dist/src/tests/helpers/index.js +18 -0
  34. package/dist/{tests → src/tests}/mocks/definition.mock.js +18 -13
  35. package/dist/{tests → src/tests}/mocks/events.mock.js +0 -1
  36. package/dist/{tests → src/tests}/mocks/testModel.js +4 -14
  37. package/dist/{types → src/types}/definition/index.js +0 -1
  38. package/dist/{types → src/types}/index.js +0 -1
  39. package/dist/{types → src/types}/value/index.js +0 -1
  40. package/dist/src/utils/constants/index.d.ts +2 -0
  41. package/dist/{utils → src/utils}/constants/index.js +2 -2
  42. package/dist/{utils → src/utils}/db/index.js +0 -1
  43. package/dist/src/utils/init.d.ts +4 -0
  44. package/dist/{index.js → src/utils/init.js} +41 -57
  45. package/dist/{utils → src/utils}/logger/index.js +0 -1
  46. package/dist/{utils → src/utils}/validations/custom-fields.js +0 -1
  47. package/dist/{utils → src/utils}/validations/custom.js +1 -2
  48. package/dist/{utils → src/utils}/validations/index.js +0 -1
  49. package/dist/{utils → src/utils}/validations/type.js +0 -1
  50. package/dist/{utils → src/utils}/validations/validators.js +0 -1
  51. package/package.json +2 -2
  52. package/src/api/v1/errors.ts +1 -1
  53. package/src/hooks/find.ts +1 -1
  54. package/src/index.ts +9 -65
  55. package/src/models/tests/TestModel.ts +5 -0
  56. package/src/scopes/filter.ts +63 -0
  57. package/src/scopes/index.ts +6 -0
  58. package/src/utils/constants/index.ts +2 -0
  59. package/src/utils/init.ts +101 -0
  60. package/tsconfig.json +9 -26
  61. package/dist/api/index.js.map +0 -1
  62. package/dist/api/v1/definition/index.js.map +0 -1
  63. package/dist/api/v1/definition/validations.js.map +0 -1
  64. package/dist/api/v1/errors.d.ts +0 -2
  65. package/dist/api/v1/errors.js.map +0 -1
  66. package/dist/api/v1/index.js.map +0 -1
  67. package/dist/errors/index.js.map +0 -1
  68. package/dist/events/index.js.map +0 -1
  69. package/dist/hooks/create.js.map +0 -1
  70. package/dist/hooks/enrich.js.map +0 -1
  71. package/dist/hooks/find.js.map +0 -1
  72. package/dist/hooks/index.js.map +0 -1
  73. package/dist/hooks/update.js.map +0 -1
  74. package/dist/hooks/workaround.js.map +0 -1
  75. package/dist/index.js.map +0 -1
  76. package/dist/models/CustomFieldDefinition.js.map +0 -1
  77. package/dist/models/CustomFieldValue.js.map +0 -1
  78. package/dist/models/index.js.map +0 -1
  79. package/dist/models/tests/AssociatedTestModel.js.map +0 -1
  80. package/dist/models/tests/TestModel.js.map +0 -1
  81. package/dist/repository/definition.js.map +0 -1
  82. package/dist/repository/value.js.map +0 -1
  83. package/dist/tests/api/test-api.js.map +0 -1
  84. package/dist/tests/helpers/database-config.js.map +0 -1
  85. package/dist/tests/helpers/index.js +0 -28
  86. package/dist/tests/helpers/index.js.map +0 -1
  87. package/dist/tests/mocks/definition.mock.js.map +0 -1
  88. package/dist/tests/mocks/events.mock.js.map +0 -1
  89. package/dist/tests/mocks/testModel.js.map +0 -1
  90. package/dist/tsconfig.tsbuildinfo +0 -1
  91. package/dist/types/definition/index.js.map +0 -1
  92. package/dist/types/index.js.map +0 -1
  93. package/dist/types/value/index.js.map +0 -1
  94. package/dist/utils/constants/index.d.ts +0 -1
  95. package/dist/utils/constants/index.js.map +0 -1
  96. package/dist/utils/db/index.js.map +0 -1
  97. package/dist/utils/logger/index.js.map +0 -1
  98. package/dist/utils/validations/custom-fields.js.map +0 -1
  99. package/dist/utils/validations/custom.js.map +0 -1
  100. package/dist/utils/validations/index.js.map +0 -1
  101. package/dist/utils/validations/type.js.map +0 -1
  102. package/dist/utils/validations/validators.js.map +0 -1
  103. package/dist/{api → src/api}/index.d.ts +0 -0
  104. package/dist/{api → src/api}/v1/definition/index.d.ts +0 -0
  105. package/dist/{api → src/api}/v1/definition/validations.d.ts +0 -0
  106. package/dist/{api → src/api}/v1/index.d.ts +0 -0
  107. package/dist/{errors → src/errors}/index.d.ts +0 -0
  108. package/dist/{events → src/events}/index.d.ts +0 -0
  109. package/dist/{hooks → src/hooks}/create.d.ts +0 -0
  110. package/dist/{hooks → src/hooks}/enrich.d.ts +0 -0
  111. package/dist/{hooks → src/hooks}/find.d.ts +0 -0
  112. package/dist/{hooks → src/hooks}/index.d.ts +0 -0
  113. package/dist/{hooks → src/hooks}/update.d.ts +0 -0
  114. package/dist/{hooks → src/hooks}/workaround.d.ts +0 -0
  115. package/dist/{models → src/models}/CustomFieldDefinition.d.ts +0 -0
  116. package/dist/{models → src/models}/CustomFieldValue.d.ts +0 -0
  117. package/dist/{models → src/models}/index.d.ts +0 -0
  118. package/dist/{models → src/models}/tests/AssociatedTestModel.d.ts +0 -0
  119. package/dist/{repository → src/repository}/definition.d.ts +0 -0
  120. package/dist/{repository → src/repository}/value.d.ts +0 -0
  121. package/dist/{tests → src/tests}/api/test-api.d.ts +0 -0
  122. package/dist/{tests → src/tests}/helpers/database-config.d.ts +0 -0
  123. package/dist/{tests → src/tests}/helpers/index.d.ts +0 -0
  124. package/dist/{tests → src/tests}/mocks/definition.mock.d.ts +4 -4
  125. /package/dist/{tests → src/tests}/mocks/events.mock.d.ts +0 -0
  126. /package/dist/{tests → src/tests}/mocks/testModel.d.ts +0 -0
  127. /package/dist/{types → src/types}/definition/index.d.ts +0 -0
  128. /package/dist/{types → src/types}/index.d.ts +0 -0
  129. /package/dist/{types → src/types}/value/index.d.ts +0 -0
  130. /package/dist/{utils → src/utils}/db/index.d.ts +0 -0
  131. /package/dist/{utils → src/utils}/logger/index.d.ts +0 -0
  132. /package/dist/{utils → src/utils}/validations/custom-fields.d.ts +0 -0
  133. /package/dist/{utils → src/utils}/validations/custom.d.ts +0 -0
  134. /package/dist/{utils → src/utils}/validations/index.d.ts +0 -0
  135. /package/dist/{utils → src/utils}/validations/type.d.ts +0 -0
  136. /package/dist/{utils → src/utils}/validations/validators.d.ts +0 -0
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -29,7 +20,7 @@ const testModels = [TestModel_1.default, AssociatedTestModel_1.default];
29
20
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
30
21
  const SCHEMA_VERSION = 1;
31
22
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
32
- const initTables = (sequelize, getUser) => __awaiter(void 0, void 0, void 0, function* () {
23
+ const initTables = async (sequelize, getUser) => {
33
24
  logger_1.default.info('custom-fields: initialize custom-fields tables');
34
25
  // Detect models and import them to the orm
35
26
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -39,7 +30,7 @@ const initTables = (sequelize, getUser) => __awaiter(void 0, void 0, void 0, fun
39
30
  sequelize.addModels(productionModels);
40
31
  CustomFieldDefinition_1.default.addScope('userScope', () => {
41
32
  const user = getUser();
42
- if (user === null || user === void 0 ? void 0 : user.permissions) {
33
+ if (user?.permissions) {
43
34
  return {
44
35
  where: {
45
36
  entityId: [
@@ -66,19 +57,19 @@ const initTables = (sequelize, getUser) => __awaiter(void 0, void 0, void 0, fun
66
57
  timestamps: false,
67
58
  schema: 'public',
68
59
  });
69
- const migrations = yield SequelizeMeta.findAll({ raw: true });
60
+ const migrations = await SequelizeMeta.findAll({ raw: true });
70
61
  const currentSadotSchemaVersion = migrations
71
62
  .reverse().find((m) => m.name.includes(SADOT_MIGRATION_PREFIX));
72
63
  if (!currentSadotSchemaVersion
73
64
  || currentSadotSchemaVersion.name !== CUSTOM_FIELDS_SCHEMA_VERSION) {
74
- yield CustomFieldDefinition_1.default.sync({ alter: true });
75
- yield CustomFieldValue_1.default.sync({ alter: true });
76
- yield SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
65
+ await CustomFieldDefinition_1.default.sync({ alter: true });
66
+ await CustomFieldValue_1.default.sync({ alter: true });
67
+ await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
77
68
  logger_1.default.info('custom-fields: models synced');
78
69
  }
79
- });
70
+ };
80
71
  exports.initTables = initTables;
81
- const initTestModels = (sequelize) => __awaiter(void 0, void 0, void 0, function* () {
72
+ const initTestModels = async (sequelize) => {
82
73
  logger_1.default.info('custom-fields: initialize custom-fields test models');
83
74
  // Detect models and import them to the orm
84
75
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -86,12 +77,11 @@ const initTestModels = (sequelize) => __awaiter(void 0, void 0, void 0, function
86
77
  throw new Error('sequelize instance must have addModels function');
87
78
  }
88
79
  sequelize.addModels(testModels);
89
- yield sequelize.dropSchema('custom-fields', { logging: false });
90
- yield sequelize.createSchema('custom-fields', { logging: false });
80
+ await sequelize.dropSchema('custom-fields', { logging: false });
81
+ await sequelize.createSchema('custom-fields', { logging: false });
91
82
  logger_1.default.info('custom-fields: test models added');
92
- yield TestModel_1.default.sync({ alter: true });
93
- yield AssociatedTestModel_1.default.sync({ alter: true });
83
+ await TestModel_1.default.sync({ alter: true });
84
+ await AssociatedTestModel_1.default.sync({ alter: true });
94
85
  logger_1.default.info('custom-fields: test models synced');
95
- });
86
+ };
96
87
  exports.initTestModels = initTestModels;
97
- //# sourceMappingURL=index.js.map
@@ -69,4 +69,3 @@ AssociatedTestModel = __decorate([
69
69
  (0, sequelize_typescript_1.Table)({ schema: 'custom-fields', createdAt: false, updatedAt: false })
70
70
  ], AssociatedTestModel);
71
71
  exports.default = AssociatedTestModel;
72
- //# sourceMappingURL=AssociatedTestModel.js.map
@@ -7,5 +7,6 @@ declare class TestModel extends Model {
7
7
  demandSourceId: string;
8
8
  coolAttribute?: boolean;
9
9
  associatedModels: AssociatedTestModel[];
10
+ customFields?: any;
10
11
  }
11
12
  export default TestModel;
@@ -57,8 +57,13 @@ __decorate([
57
57
  (0, sequelize_typescript_1.HasMany)(() => AssociatedTestModel_1.default),
58
58
  __metadata("design:type", Array)
59
59
  ], TestModel.prototype, "associatedModels", void 0);
60
+ __decorate([
61
+ (0, sequelize_typescript_1.Column)({
62
+ type: sequelize_typescript_1.DataType.VIRTUAL,
63
+ }),
64
+ __metadata("design:type", Object)
65
+ ], TestModel.prototype, "customFields", void 0);
60
66
  TestModel = __decorate([
61
67
  (0, sequelize_typescript_1.Table)({ schema: 'custom-fields', createdAt: false, updatedAt: false })
62
68
  ], TestModel);
63
69
  exports.default = TestModel;
64
- //# sourceMappingURL=TestModel.js.map
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
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;
13
4
  const sequelize_1 = require("sequelize");
@@ -35,44 +26,40 @@ const findById = (id, options = { withDisabled: false }) => {
35
26
  return models_1.CustomFieldDefinition.scope('userScope').findByPk(id);
36
27
  };
37
28
  exports.findById = findById;
38
- const findByEntityId = (entityId, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
39
- return models_1.CustomFieldDefinition.findAll({
40
- where: { entityId },
41
- transaction: options.transaction,
42
- });
29
+ const findByEntityId = async (entityId, options = {}) => models_1.CustomFieldDefinition.findAll({
30
+ where: { entityId },
31
+ transaction: options.transaction,
43
32
  });
44
33
  exports.findByEntityId = findByEntityId;
45
- const findByEntityIds = (modelType, entityIds, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
46
- return models_1.CustomFieldDefinition.findAll({
47
- where: {
48
- modelType,
49
- entityId: entityIds,
50
- },
51
- transaction: options.transaction,
52
- raw: true,
53
- });
34
+ const findByEntityIds = async (modelType, entityIds, options = {}) => models_1.CustomFieldDefinition.findAll({
35
+ where: {
36
+ modelType,
37
+ entityId: entityIds,
38
+ },
39
+ transaction: options.transaction,
40
+ raw: true,
54
41
  });
55
42
  exports.findByEntityIds = findByEntityIds;
56
43
  const findByWhere = (where) => models_1.CustomFieldDefinition.scope('userScope').findOne({
57
44
  where,
58
45
  });
59
46
  exports.findByWhere = findByWhere;
60
- const findDefinitionsByModels = (modelTypes, options) => __awaiter(void 0, void 0, void 0, function* () {
47
+ const findDefinitionsByModels = async (modelTypes, options) => {
61
48
  const query = { modelType: { [sequelize_1.Op.in]: modelTypes } };
62
49
  return models_1.CustomFieldDefinition.findAll({
63
50
  where: query,
64
- transaction: options === null || options === void 0 ? void 0 : options.transaction,
51
+ transaction: options?.transaction,
65
52
  });
66
- });
53
+ };
67
54
  exports.findDefinitionsByModels = findDefinitionsByModels;
68
- const update = (id, data) => __awaiter(void 0, void 0, void 0, function* () {
69
- const updatedDefinition = (yield models_1.CustomFieldDefinition.scope('userScope').update(data, {
55
+ const update = async (id, data) => {
56
+ const updatedDefinition = (await models_1.CustomFieldDefinition.scope('userScope').update(data, {
70
57
  where: { id },
71
58
  returning: true,
72
59
  individualHooks: true,
73
60
  }))[1][0];
74
61
  return updatedDefinition;
75
- });
62
+ };
76
63
  exports.update = update;
77
64
  const disable = (id) => models_1.CustomFieldDefinition.update({ disabled: true }, { where: { id } });
78
65
  exports.disable = disable;
@@ -81,14 +68,13 @@ exports.destroy = destroy;
81
68
  /**
82
69
  * Return the names of the required fields for a given model
83
70
  */
84
- const getRequiredFields = (modelType, modelId, entityId) => __awaiter(void 0, void 0, void 0, function* () {
71
+ const getRequiredFields = async (modelType, modelId, entityId) => {
85
72
  const entityIds = Array.isArray(entityId) ? entityId : [entityId];
86
- const requiredFields = yield models_1.CustomFieldDefinition.findAll({
73
+ const requiredFields = await models_1.CustomFieldDefinition.findAll({
87
74
  where: { required: true, modelType, entityId: { [sequelize_1.Op.in]: entityIds } },
88
75
  logging: true,
89
76
  });
90
77
  const requiredFieldsNames = requiredFields.map((definition) => definition.name);
91
78
  return [...new Set(requiredFieldsNames)];
92
- });
79
+ };
93
80
  exports.getRequiredFields = getRequiredFields;
94
- //# sourceMappingURL=definition.js.map
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -41,32 +32,32 @@ const models_1 = require("../models");
41
32
  const DefinitionRepo = __importStar(require("./definition"));
42
33
  const logger_1 = __importDefault(require("../utils/logger"));
43
34
  const errors_1 = require("../errors");
44
- const findByModelIdAndDefinition = (modelId, customFieldDefinitionId) => __awaiter(void 0, void 0, void 0, function* () { return models_1.CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [models_1.CustomFieldDefinition] }); });
35
+ const findByModelIdAndDefinition = async (modelId, customFieldDefinitionId) => models_1.CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [models_1.CustomFieldDefinition] });
45
36
  exports.findByModelIdAndDefinition = findByModelIdAndDefinition;
46
- const create = (data, withAssociations = false) => __awaiter(void 0, void 0, void 0, function* () {
47
- const created = yield models_1.CustomFieldValue.create(data);
37
+ const create = async (data, withAssociations = false) => {
38
+ const created = await models_1.CustomFieldValue.create(data);
48
39
  if (withAssociations) {
49
- const createdWithAssociations = yield (0, exports.findByModelIdAndDefinition)(created.modelId, created.customFieldDefinitionId);
50
- return createdWithAssociations === null || createdWithAssociations === void 0 ? void 0 : createdWithAssociations[0];
40
+ const createdWithAssociations = await (0, exports.findByModelIdAndDefinition)(created.modelId, created.customFieldDefinitionId);
41
+ return createdWithAssociations?.[0];
51
42
  }
52
43
  return created;
53
- });
44
+ };
54
45
  exports.create = create;
55
- const findAllValues = () => __awaiter(void 0, void 0, void 0, function* () { return models_1.CustomFieldValue.findAll({ include: [models_1.CustomFieldDefinition] }); });
46
+ const findAllValues = async () => models_1.CustomFieldValue.findAll({ include: [models_1.CustomFieldDefinition] });
56
47
  exports.findAllValues = findAllValues;
57
48
  /**
58
49
  * Get all values for model instance id (with their definitions)
59
50
  * @param modelId
60
51
  * @returns CustomFieldValue[]
61
52
  */
62
- const findValuesByModelId = (modelId) => __awaiter(void 0, void 0, void 0, function* () { return models_1.CustomFieldValue.findAll({ where: { modelId }, include: [models_1.CustomFieldDefinition] }); });
53
+ const findValuesByModelId = async (modelId) => models_1.CustomFieldValue.findAll({ where: { modelId }, include: [models_1.CustomFieldDefinition] });
63
54
  exports.findValuesByModelId = findValuesByModelId;
64
55
  /**
65
56
  * Retrieves custom field values for given model IDs
66
57
  * @param modelIds - An array of model IDs to query custom field values for.
67
58
  * @param options - Optional configuration object.
68
59
  */
69
- const findValuesByModelIds = (modelIds, options) => __awaiter(void 0, void 0, void 0, function* () {
60
+ const findValuesByModelIds = async (modelIds, options) => {
70
61
  const { transaction } = options;
71
62
  return models_1.CustomFieldValue.findAll({
72
63
  where: { modelId: modelIds },
@@ -74,25 +65,25 @@ const findValuesByModelIds = (modelIds, options) => __awaiter(void 0, void 0, vo
74
65
  raw: true,
75
66
  nest: true,
76
67
  });
77
- });
68
+ };
78
69
  exports.findValuesByModelIds = findValuesByModelIds;
79
70
  /**
80
71
  * Try to update custom field values for a model instance.
81
72
  * Create new value record if not exists, but fails if value's definition not exist.
82
73
  * Return the updated values
83
74
  */
84
- const updateValues = (modelType, modelId, identifiers, valuesToUpdate, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
75
+ const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
85
76
  logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, { valuesToUpdate });
86
77
  const names = Object.keys(valuesToUpdate);
87
- const fieldDefinitions = (yield DefinitionRepo.findAll({ modelType, name: names, entityId: identifiers }, { withDisabled: true, transaction: options.transaction })) || [];
78
+ const fieldDefinitions = await DefinitionRepo.findAll({ modelType, name: names, entityId: identifiers }, { withDisabled: true, transaction: options.transaction }) || [];
88
79
  const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
89
80
  if (fieldDefinitions.length !== names.length) {
90
81
  const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));
91
82
  throw new errors_1.MissingDefinitionError(missingDefinitions);
92
83
  }
93
- const disabledNames = (disabledDefinitions === null || disabledDefinitions === void 0 ? void 0 : disabledDefinitions.map((def) => def.name)) || [];
84
+ const disabledNames = disabledDefinitions?.map((def) => def.name) || [];
94
85
  const valuesWithDisabledDefinitions = names.filter((name) => disabledNames.includes(name));
95
- if ((valuesWithDisabledDefinitions === null || valuesWithDisabledDefinitions === void 0 ? void 0 : valuesWithDisabledDefinitions.length) > 0) {
86
+ if (valuesWithDisabledDefinitions?.length > 0) {
96
87
  logger_1.default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);
97
88
  }
98
89
  const values = names.map((name) => ({
@@ -101,17 +92,16 @@ const updateValues = (modelType, modelId, identifiers, valuesToUpdate, options =
101
92
  updatedAt: new Date(),
102
93
  customFieldDefinitionId: fieldDefinitions.find((def) => def.name === name).id,
103
94
  }));
104
- return Promise.all(values.map((value) => __awaiter(void 0, void 0, void 0, function* () {
105
- const [cfv] = yield models_1.CustomFieldValue.upsert(value, {
95
+ return Promise.all(values.map(async (value) => {
96
+ const [cfv] = await models_1.CustomFieldValue.upsert(value, {
106
97
  transaction: options.transaction,
107
98
  });
108
99
  return cfv;
109
- })));
110
- });
100
+ }));
101
+ };
111
102
  exports.updateValues = updateValues;
112
103
  const deleteValue = (id, options = {}) => models_1.CustomFieldValue.update({ deletedAt: new Date() }, {
113
104
  where: { id },
114
105
  transaction: options.transaction,
115
106
  });
116
107
  exports.deleteValue = deleteValue;
117
- //# sourceMappingURL=value.js.map
@@ -0,0 +1,23 @@
1
+ import { WhereOptions } from 'sequelize';
2
+ /**
3
+ * Type representing possible condition values.
4
+ * Currently supporting strings and arrays of strings.
5
+ * More types to be added (TBA).
6
+ */
7
+ export type ConditionValue = string | string[];
8
+ export type CustomFieldSort = {
9
+ field: string;
10
+ direction: 'ASC' | 'DESC';
11
+ };
12
+ export type CustomFieldFilterOptions = {
13
+ where?: WhereOptions;
14
+ };
15
+ /**
16
+ * A Sequelize scope for filtering models by custom fields.
17
+ * This scope builds a WHERE clause to be applied on the main query.
18
+ *
19
+ * @param {string} name - The model type name used to join custom_field_definitions.
20
+ * @returns {Function} - A function that takes conditions and returns the Sequelize options object.
21
+ */
22
+ export declare const customFieldsFilterScope: (name: string) => (conditions: Record<string, ConditionValue>) => CustomFieldFilterOptions;
23
+ export declare const scopeName = "filterByCustomFields";
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scopeName = exports.customFieldsFilterScope = void 0;
4
+ /* eslint-disable import/prefer-default-export */
5
+ const sequelize_1 = require("sequelize");
6
+ const sequelize_typescript_1 = require("sequelize-typescript");
7
+ const constants_1 = require("../utils/constants");
8
+ /**
9
+ * A Sequelize scope for filtering models by custom fields.
10
+ * This scope builds a WHERE clause to be applied on the main query.
11
+ *
12
+ * @param {string} name - The model type name used to join custom_field_definitions.
13
+ * @returns {Function} - A function that takes conditions and returns the Sequelize options object.
14
+ */
15
+ const customFieldsFilterScope = (name) => (conditions) => {
16
+ // Build the WHERE clause for custom field filtering
17
+ const customFieldConditions = Object.entries(conditions)
18
+ .map(([key, value]) => {
19
+ if (Array.isArray(value)) {
20
+ const values = value.map((v) => `'${v}'`).join(',');
21
+ return `custom_fields->>'${key}' IN (${values})`;
22
+ }
23
+ return `custom_fields->>'${key}' = '${value}'`;
24
+ })
25
+ .join(' AND ');
26
+ const subQuery = `${'SELECT model_id FROM ('
27
+ + 'SELECT cv.model_id, jsonb_object_agg(cd.name, cv.value) AS custom_fields '
28
+ + 'FROM custom_field_values AS cv '
29
+ + 'INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id '
30
+ + `AND cd.model_type = '${name}' `
31
+ + 'GROUP BY cv.model_id'
32
+ + ') AS CustomFieldAggregation '
33
+ + 'WHERE '}${customFieldConditions}`;
34
+ return {
35
+ where: {
36
+ id: {
37
+ [sequelize_1.Op.in]: sequelize_typescript_1.Sequelize.literal(`(${subQuery})`),
38
+ },
39
+ },
40
+ };
41
+ };
42
+ exports.customFieldsFilterScope = customFieldsFilterScope;
43
+ exports.scopeName = constants_1.CUSTOM_FIELDS_FILTER_SCOPE;
@@ -0,0 +1,2 @@
1
+ import { customFieldsFilterScope } from './filter';
2
+ export { customFieldsFilterScope, };
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.customFieldsFilterScope = void 0;
4
+ /* eslint-disable import/prefer-default-export */
5
+ const filter_1 = require("./filter");
6
+ Object.defineProperty(exports, "customFieldsFilterScope", { enumerable: true, get: function () { return filter_1.customFieldsFilterScope; } });
@@ -22,45 +22,35 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  Object.defineProperty(exports, "__esModule", { value: true });
35
26
  const express_1 = __importStar(require("express"));
36
27
  const models_1 = require("../../models");
37
28
  const app = (0, express_1.default)();
38
29
  app.use(express_1.default.json());
39
30
  const api = (0, express_1.Router)();
40
- api.get('/v1/test-models', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
41
- const testModels = yield models_1.TestModel.findAll();
31
+ api.get('/v1/test-models', async (req, res) => {
32
+ const testModels = await models_1.TestModel.findAll();
42
33
  return res.json(testModels);
43
- }));
44
- api.get('/v1/test-models/:testModelId', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
34
+ });
35
+ api.get('/v1/test-models/:testModelId', async (req, res) => {
45
36
  const { params: { testModelId } } = req;
46
- const testModel = yield models_1.TestModel.findByPk(testModelId);
37
+ const testModel = await models_1.TestModel.findByPk(testModelId);
47
38
  return res.json(testModel);
48
- }));
49
- api.post('/v1/test-models', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
39
+ });
40
+ api.post('/v1/test-models', async (req, res) => {
50
41
  const { body } = req;
51
- const testModel = yield models_1.TestModel.create(body);
42
+ const testModel = await models_1.TestModel.create(body);
52
43
  return res.json(testModel);
53
- }));
54
- api.patch('/v1/test-models/:testModelId', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
44
+ });
45
+ api.patch('/v1/test-models/:testModelId', async (req, res) => {
55
46
  const { body, params: { testModelId } } = req;
56
- const testModel = yield models_1.TestModel.update(body, {
47
+ const testModel = await models_1.TestModel.update(body, {
57
48
  where: {
58
49
  id: testModelId,
59
50
  },
60
51
  returning: true,
61
52
  });
62
53
  return res.json(testModel[1][0]);
63
- }));
54
+ });
64
55
  app.use('/api', api);
65
56
  exports.default = app;
66
- //# sourceMappingURL=test-api.js.map
@@ -14,4 +14,3 @@ exports.default = {
14
14
  logging: false,
15
15
  },
16
16
  };
17
- //# sourceMappingURL=database-config.js.map
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getModel = exports.cleanup = void 0;
4
+ const models_1 = require("../../models");
5
+ // eslint-disable-next-line import/prefer-default-export
6
+ const cleanup = async () => {
7
+ if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
8
+ await models_1.CustomFieldDefinition.unscoped().destroy({ where: {} });
9
+ await models_1.TestModel.destroy({ where: {} });
10
+ }
11
+ };
12
+ exports.cleanup = cleanup;
13
+ const getModel = (name) => {
14
+ // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
15
+ const models = require('../../models');
16
+ return models[name];
17
+ };
18
+ exports.getModel = getModel;
@@ -9,8 +9,14 @@ exports.coolFieldDefinition = {
9
9
  entityId: (0, uuid_1.v4)(),
10
10
  entityType: 'fleetId',
11
11
  };
12
- exports.coolFieldDefinition2 = Object.assign(Object.assign({}, exports.coolFieldDefinition), { name: 'cool field2' });
13
- exports.coolFieldDefinition3 = Object.assign(Object.assign({}, exports.coolFieldDefinition), { name: 'cool field3' });
12
+ exports.coolFieldDefinition2 = {
13
+ ...exports.coolFieldDefinition,
14
+ name: 'cool field2',
15
+ };
16
+ exports.coolFieldDefinition3 = {
17
+ ...exports.coolFieldDefinition,
18
+ name: 'cool field3',
19
+ };
14
20
  const booleanField = (modelType) => ({
15
21
  name: 'shapeless',
16
22
  modelType,
@@ -41,19 +47,18 @@ const rangeField = (modelType) => ({
41
47
  exports.rangeField = rangeField;
42
48
  // eslint-disable-next-line max-len
43
49
  const createDefinition = (defaults) => ({
44
- name: (defaults === null || defaults === void 0 ? void 0 : defaults.name) || `def_${(0, uuid_1.v4)()}`,
45
- modelType: (defaults === null || defaults === void 0 ? void 0 : defaults.modelType) || 'TestModel',
46
- fieldType: (defaults === null || defaults === void 0 ? void 0 : defaults.fieldType) || 'boolean',
47
- entityId: (defaults === null || defaults === void 0 ? void 0 : defaults.entityId) || (0, uuid_1.v4)(),
48
- entityType: (defaults === null || defaults === void 0 ? void 0 : defaults.entityType) || 'fleetId',
50
+ name: defaults?.name || `def_${(0, uuid_1.v4)()}`,
51
+ modelType: defaults?.modelType || 'TestModel',
52
+ fieldType: defaults?.fieldType || 'boolean',
53
+ entityId: defaults?.entityId || (0, uuid_1.v4)(),
54
+ entityType: defaults?.entityType || 'fleetId',
49
55
  });
50
56
  exports.createDefinition = createDefinition;
51
57
  const createDefinitions = (defaults, length = 1) => (Array(length).fill({}).map((_) => ({
52
- name: (defaults === null || defaults === void 0 ? void 0 : defaults.name) || `def_${(0, uuid_1.v4)()}`,
53
- modelType: (defaults === null || defaults === void 0 ? void 0 : defaults.modelType) || 'TestModel',
54
- fieldType: (defaults === null || defaults === void 0 ? void 0 : defaults.fieldType) || 'boolean',
55
- entityId: (defaults === null || defaults === void 0 ? void 0 : defaults.entityId) || (0, uuid_1.v4)(),
56
- entityType: (defaults === null || defaults === void 0 ? void 0 : defaults.entityType) || 'fleetId',
58
+ name: defaults?.name || `def_${(0, uuid_1.v4)()}`,
59
+ modelType: defaults?.modelType || 'TestModel',
60
+ fieldType: defaults?.fieldType || 'boolean',
61
+ entityId: defaults?.entityId || (0, uuid_1.v4)(),
62
+ entityType: defaults?.entityType || 'fleetId',
57
63
  })));
58
64
  exports.createDefinitions = createDefinitions;
59
- //# sourceMappingURL=definition.mock.js.map
@@ -17,4 +17,3 @@ const mockDimCustomFieldDefinitionEvent = (events, numberOfEvents) => (0, export
17
17
  exports.mockDimCustomFieldDefinitionEvent = mockDimCustomFieldDefinitionEvent;
18
18
  const mockDimCustomFieldValueEvent = (events, numberOfEvents) => (0, exports.mockEvent)(events, 'dim_custom_field_value', numberOfEvents);
19
19
  exports.mockDimCustomFieldValueEvent = mockDimCustomFieldValueEvent;
20
- //# sourceMappingURL=events.mock.js.map
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.getTestModelWithAssociation = exports.createTestModelWithAssociation = exports.updateTestModel = exports.getSomeTestModels = exports.getTestModel = exports.destroyTestModels = exports.upsertTestModel = exports.createTestModels = exports.createTestModel = void 0;
13
4
  const models_1 = require("../../models");
@@ -32,14 +23,13 @@ exports.getSomeTestModels = getSomeTestModels;
32
23
  const updateTestModel = (payload, query) => models_1.TestModel.update(payload, query);
33
24
  exports.updateTestModel = updateTestModel;
34
25
  // Associations
35
- const createTestModelWithAssociation = () => __awaiter(void 0, void 0, void 0, function* () {
36
- const model = yield models_1.TestModel.create({});
37
- yield models_1.AssociatedTestModel.create({ testModelId: model.id });
26
+ const createTestModelWithAssociation = async () => {
27
+ const model = await models_1.TestModel.create({});
28
+ await models_1.AssociatedTestModel.create({ testModelId: model.id });
38
29
  return model;
39
- });
30
+ };
40
31
  exports.createTestModelWithAssociation = createTestModelWithAssociation;
41
32
  const getTestModelWithAssociation = (limit = 1) => models_1.TestModel.findAll({
42
33
  limit, include: [models_1.AssociatedTestModel],
43
34
  });
44
35
  exports.getTestModelWithAssociation = getTestModelWithAssociation;
45
- //# sourceMappingURL=testModel.js.map
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=index.js.map
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=index.js.map
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ export declare const supportedEntities: string[];
2
+ export declare const CUSTOM_FIELDS_FILTER_SCOPE = "filterByCustomFields";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.supportedEntities = void 0;
3
+ exports.CUSTOM_FIELDS_FILTER_SCOPE = exports.supportedEntities = void 0;
4
4
  // eslint-disable-next-line import/prefer-default-export
5
5
  exports.supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'];
6
- //# sourceMappingURL=index.js.map
6
+ exports.CUSTOM_FIELDS_FILTER_SCOPE = 'filterByCustomFields';
@@ -22,4 +22,3 @@ CREATE TABLE IF NOT EXISTS "SequelizeMeta" (
22
22
  );
23
23
  `, { type: sequelize_1.QueryTypes.SELECT });
24
24
  exports.createSequelizeMeta = createSequelizeMeta;
25
- //# sourceMappingURL=index.js.map
@@ -0,0 +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;