@autofleet/sadot 1.6.18-beta.2 → 1.6.18-beta.21

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 (162) hide show
  1. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs +11 -0
  2. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js +10 -0
  3. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs +8 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js +7 -0
  5. package/dist/_virtual/rolldown_runtime.cjs +43 -0
  6. package/dist/{chunk-DJulfCLt.js → _virtual/rolldown_runtime.js} +1 -2
  7. package/dist/api/index.cjs +12 -0
  8. package/dist/api/index.js +11 -0
  9. package/dist/api/v1/definition/index.cjs +113 -0
  10. package/dist/api/v1/definition/index.js +112 -0
  11. package/dist/api/v1/definition/validations.cjs +128 -0
  12. package/dist/api/v1/definition/validations.js +125 -0
  13. package/dist/api/v1/errors.cjs +14 -0
  14. package/dist/api/v1/errors.js +13 -0
  15. package/dist/api/v1/field-policies/index.cjs +104 -0
  16. package/dist/api/v1/field-policies/index.js +103 -0
  17. package/dist/api/v1/index.cjs +16 -0
  18. package/dist/api/v1/index.js +15 -0
  19. package/dist/api/v1/validator/index.cjs +132 -0
  20. package/dist/api/v1/validator/index.js +131 -0
  21. package/dist/api/v1/validator/validations.cjs +40 -0
  22. package/dist/api/v1/validator/validations.d.cts +22 -0
  23. package/dist/api/v1/validator/validations.d.ts +22 -0
  24. package/dist/api/v1/validator/validations.js +38 -0
  25. package/dist/errors/index.cjs +62 -0
  26. package/dist/errors/index.js +55 -0
  27. package/dist/events/index.cjs +52 -0
  28. package/dist/events/index.js +50 -0
  29. package/dist/hooks/enrich.cjs +175 -0
  30. package/dist/hooks/enrich.js +175 -0
  31. package/dist/hooks/find.cjs +22 -0
  32. package/dist/hooks/find.js +22 -0
  33. package/dist/hooks/hooks.cjs +310 -0
  34. package/dist/hooks/hooks.js +302 -0
  35. package/dist/hooks/index.cjs +3 -0
  36. package/dist/hooks/index.js +5 -0
  37. package/dist/hooks/utils/updateInstanceValues.cjs +27 -0
  38. package/dist/hooks/utils/updateInstanceValues.js +27 -0
  39. package/dist/index.cjs +48 -33508
  40. package/dist/index.d.cts +13 -396
  41. package/dist/index.d.ts +14 -394
  42. package/dist/index.js +21 -33435
  43. package/dist/init-state.cjs +56 -0
  44. package/dist/init-state.d.cts +35 -0
  45. package/dist/init-state.d.ts +35 -0
  46. package/dist/init-state.js +55 -0
  47. package/dist/mat-path-state.cjs +10 -0
  48. package/dist/mat-path-state.js +9 -0
  49. package/dist/migrations/001-create-core-tables.cjs +70 -0
  50. package/dist/migrations/001-create-core-tables.js +68 -0
  51. package/dist/migrations/002-create-custom-field-entries.cjs +27 -0
  52. package/dist/migrations/002-create-custom-field-entries.js +25 -0
  53. package/dist/migrations/003-create-custom-field-model-type-map.cjs +35 -0
  54. package/dist/migrations/003-create-custom-field-model-type-map.js +33 -0
  55. package/dist/migrations/004-create-field-policy-tables.cjs +29 -0
  56. package/dist/migrations/004-create-field-policy-tables.js +27 -0
  57. package/dist/migrations/005-add-entity-type-to-field-policies.cjs +20 -0
  58. package/dist/migrations/005-add-entity-type-to-field-policies.js +18 -0
  59. package/dist/migrations/index.cjs +94 -0
  60. package/dist/migrations/index.js +95 -0
  61. package/dist/models/CustomFieldDefinition.cjs +147 -0
  62. package/dist/models/CustomFieldDefinition.d.cts +40 -0
  63. package/dist/models/CustomFieldDefinition.d.ts +40 -0
  64. package/dist/models/CustomFieldDefinition.js +146 -0
  65. package/dist/models/CustomFieldEntries.cjs +71 -0
  66. package/dist/models/CustomFieldEntries.d.cts +15 -0
  67. package/dist/models/CustomFieldEntries.d.ts +15 -0
  68. package/dist/models/CustomFieldEntries.js +70 -0
  69. package/dist/models/CustomFieldModelTypeMap.cjs +62 -0
  70. package/dist/models/CustomFieldModelTypeMap.d.cts +14 -0
  71. package/dist/models/CustomFieldModelTypeMap.d.ts +14 -0
  72. package/dist/models/CustomFieldModelTypeMap.js +61 -0
  73. package/dist/models/CustomFieldValue.cjs +109 -0
  74. package/dist/models/CustomFieldValue.d.cts +20 -0
  75. package/dist/models/CustomFieldValue.d.ts +20 -0
  76. package/dist/models/CustomFieldValue.js +108 -0
  77. package/dist/models/CustomValidator.cjs +68 -0
  78. package/dist/models/CustomValidator.d.cts +18 -0
  79. package/dist/models/CustomValidator.d.ts +18 -0
  80. package/dist/models/CustomValidator.js +67 -0
  81. package/dist/models/FieldPolicy.cjs +54 -0
  82. package/dist/models/FieldPolicy.d.cts +25 -0
  83. package/dist/models/FieldPolicy.d.ts +25 -0
  84. package/dist/models/FieldPolicy.js +53 -0
  85. package/dist/models/index.cjs +163 -0
  86. package/dist/models/index.d.ts +11 -0
  87. package/dist/models/index.js +161 -0
  88. package/dist/models/tests/AssociatedTestModel.cjs +51 -0
  89. package/dist/models/tests/AssociatedTestModel.d.ts +2 -0
  90. package/dist/models/tests/AssociatedTestModel.js +50 -0
  91. package/dist/models/tests/TestModel.cjs +43 -0
  92. package/dist/models/tests/TestModel.d.ts +2 -0
  93. package/dist/models/tests/TestModel.js +42 -0
  94. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +35 -0
  95. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +2 -0
  96. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +34 -0
  97. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +33 -0
  98. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +1 -0
  99. package/dist/models/tests/contextAwareModels/ContextTestModel.js +32 -0
  100. package/dist/repository/definition.cjs +221 -0
  101. package/dist/repository/definition.js +212 -0
  102. package/dist/repository/entries.cjs +69 -0
  103. package/dist/repository/entries.js +67 -0
  104. package/dist/repository/field-policy.cjs +69 -0
  105. package/dist/repository/field-policy.d.cts +35 -0
  106. package/dist/repository/field-policy.d.ts +35 -0
  107. package/dist/repository/field-policy.js +59 -0
  108. package/dist/repository/utils/formatValues.cjs +14 -0
  109. package/dist/repository/utils/formatValues.js +14 -0
  110. package/dist/repository/validator.cjs +85 -0
  111. package/dist/repository/validator.js +78 -0
  112. package/dist/repository/value.cjs +77 -0
  113. package/dist/repository/value.js +76 -0
  114. package/dist/scopes/filter.cjs +56 -0
  115. package/dist/scopes/filter.d.cts +22 -0
  116. package/dist/scopes/filter.d.ts +22 -0
  117. package/dist/scopes/filter.js +54 -0
  118. package/dist/scopes/helpers/filter.helpers.cjs +152 -0
  119. package/dist/scopes/helpers/filter.helpers.d.cts +16 -0
  120. package/dist/scopes/helpers/filter.helpers.d.ts +16 -0
  121. package/dist/scopes/helpers/filter.helpers.js +147 -0
  122. package/dist/scopes/index.cjs +1 -0
  123. package/dist/scopes/index.js +3 -0
  124. package/dist/types/index.d.cts +75 -0
  125. package/dist/types/index.d.ts +76 -0
  126. package/dist/utils/constants/index.cjs +32 -0
  127. package/dist/utils/constants/index.d.cts +23 -0
  128. package/dist/utils/constants/index.d.ts +23 -0
  129. package/dist/utils/constants/index.js +29 -0
  130. package/dist/utils/db/index.cjs +15 -0
  131. package/dist/utils/db/index.js +14 -0
  132. package/dist/utils/helpers/index.cjs +23 -0
  133. package/dist/utils/helpers/index.d.cts +30 -0
  134. package/dist/utils/helpers/index.d.ts +30 -0
  135. package/dist/utils/helpers/index.js +21 -0
  136. package/dist/utils/init.cjs +115 -0
  137. package/dist/utils/init.js +111 -0
  138. package/dist/utils/logger/index.cjs +15 -0
  139. package/dist/utils/logger/index.js +12 -0
  140. package/dist/utils/scopeAttributes.cjs +12 -0
  141. package/dist/utils/scopeAttributes.js +11 -0
  142. package/dist/utils/validations/index.cjs +34 -0
  143. package/dist/utils/validations/index.js +32 -0
  144. package/dist/utils/validations/schema/custom-fields.cjs +9 -0
  145. package/dist/utils/validations/schema/custom-fields.d.cts +6 -0
  146. package/dist/utils/validations/schema/custom-fields.d.ts +6 -0
  147. package/dist/utils/validations/schema/custom-fields.js +7 -0
  148. package/dist/utils/validations/schema/validator-schema.cjs +102 -0
  149. package/dist/utils/validations/schema/validator-schema.js +99 -0
  150. package/dist/utils/validations/validators/index.cjs +45 -0
  151. package/dist/utils/validations/validators/index.js +42 -0
  152. package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs +7 -0
  153. package/dist/utils/validations/validators/multi-select-dropdown.validator.js +7 -0
  154. package/dist/utils/validations/validators/multi-select-status.validator.cjs +10 -0
  155. package/dist/utils/validations/validators/multi-select-status.validator.js +10 -0
  156. package/dist/utils/validations/validators/multi-select.helpers.cjs +12 -0
  157. package/dist/utils/validations/validators/multi-select.helpers.js +10 -0
  158. package/dist/utils/validations/validators/select.validator.cjs +12 -0
  159. package/dist/utils/validations/validators/select.validator.js +10 -0
  160. package/dist/utils/validations/validators/status.validator.cjs +12 -0
  161. package/dist/utils/validations/validators/status.validator.js +10 -0
  162. package/package.json +4 -4
@@ -0,0 +1,67 @@
1
+ import logger_default from "../utils/logger/index.js";
2
+ import { MissingDefinitionError } from "../errors/index.js";
3
+ import { findAll } from "./definition.js";
4
+ import CustomFieldEntries_default from "../models/CustomFieldEntries.js";
5
+ import "../models/index.js";
6
+ import { formatFunctions } from "./utils/formatValues.js";
7
+
8
+ //#region src/repository/entries.ts
9
+ const findEntriesByModelId = async (modelId, options = {}) => {
10
+ const { transaction } = options;
11
+ return CustomFieldEntries_default.findOne({
12
+ where: { modelId },
13
+ transaction
14
+ });
15
+ };
16
+ const findEntriesByModelIds = async (modelIds, options = {}) => {
17
+ const { transaction } = options;
18
+ return CustomFieldEntries_default.findAll({
19
+ where: { modelId: modelIds },
20
+ transaction
21
+ });
22
+ };
23
+ const updateEntries = async (modelId, modelType, customFields, identifiers, options = {}) => {
24
+ const customFieldsNames = Object.keys(customFields);
25
+ logger_default.debug(`custom-fields: updating entries for ${modelType} ${modelId}`, {
26
+ customFieldsNames,
27
+ optionsKeys: options ? Object.keys(options) : null,
28
+ customFields,
29
+ identifiers
30
+ });
31
+ const { modelOptions, transaction } = options;
32
+ const where = {
33
+ modelType,
34
+ name: customFieldsNames,
35
+ ...!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }
36
+ };
37
+ const fieldDefinitions = await findAll(where, {
38
+ withDisabled: true,
39
+ transaction,
40
+ include: modelOptions.include?.(identifiers)
41
+ }) ?? [];
42
+ const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
43
+ if (fieldDefinitions.length !== customFieldsNames.length) {
44
+ logger_default.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, {
45
+ names: customFieldsNames,
46
+ fieldDefinitions
47
+ });
48
+ throw new MissingDefinitionError(customFieldsNames.filter((name) => !fieldDefinitions.some((def) => def.name === name)));
49
+ }
50
+ const disabledNames = disabledDefinitions?.map((def) => def.name) || [];
51
+ const valuesWithDisabledDefinitions = customFieldsNames.filter((name) => disabledNames.includes(name));
52
+ if (valuesWithDisabledDefinitions?.length > 0) logger_default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(", ")}`);
53
+ const definitionsByName = Object.fromEntries(fieldDefinitions.map((definition) => [definition.name, definition]));
54
+ Object.entries(customFields).filter(([definitionName]) => formatFunctions[definitionsByName[definitionName].fieldType]).forEach(([definitionName, value]) => {
55
+ const { fieldType } = definitionsByName[definitionName];
56
+ customFields[definitionName] = formatFunctions[fieldType](value);
57
+ });
58
+ return CustomFieldEntries_default.upsert({
59
+ modelId,
60
+ entityId: fieldDefinitions[0].entityId,
61
+ modelType,
62
+ customFields
63
+ }, options);
64
+ };
65
+
66
+ //#endregion
67
+ export { findEntriesByModelId, findEntriesByModelIds, updateEntries };
@@ -0,0 +1,69 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_mat_path_state = require('../mat-path-state.cjs');
3
+ const require_FieldPolicy = require('../models/FieldPolicy.cjs');
4
+ let sequelize = require("sequelize");
5
+
6
+ //#region src/repository/field-policy.ts
7
+ var field_policy_exports = /* @__PURE__ */ require_rolldown_runtime.__export({
8
+ create: () => create,
9
+ findAll: () => findAll,
10
+ findAllByContext: () => findAllByContext,
11
+ findAllByContextIds: () => findAllByContextIds,
12
+ findByContextAndName: () => findByContextAndName,
13
+ findById: () => findById,
14
+ findEffectivePolicy: () => findEffectivePolicy,
15
+ remove: () => remove,
16
+ update: () => update
17
+ });
18
+ const findByContextAndName = (contextId, name) => require_FieldPolicy.default.findOne({ where: {
19
+ contextId,
20
+ name
21
+ } });
22
+ const findById = (id) => require_FieldPolicy.default.findByPk(id);
23
+ const findAllByContext = (contextId) => require_FieldPolicy.default.findAll({ where: { contextId } });
24
+ const findAll = () => require_FieldPolicy.default.findAll();
25
+ const findAllByContextIds = (contextIds) => require_FieldPolicy.default.findAll({ where: { contextId: contextIds } });
26
+ const create = ({ contextId, name, entityType, fields, models }) => require_FieldPolicy.default.create({
27
+ contextId,
28
+ name,
29
+ entityType,
30
+ fields,
31
+ models
32
+ });
33
+ const update = async (id, data) => {
34
+ const policy = await require_FieldPolicy.default.findByPk(id);
35
+ if (!policy) return null;
36
+ return policy.update(data);
37
+ };
38
+ const remove = (id) => require_FieldPolicy.default.destroy({ where: { id } });
39
+ const findEffectivePolicy = (entityType) => {
40
+ const tableName = require_FieldPolicy.default.getTableName();
41
+ const EFFECTIVE_POLICY_QUERY = `
42
+ SELECT fp.*
43
+ FROM "${tableName}" fp
44
+ LEFT JOIN context_entity_path cep ON cep.deleted_at IS NULL
45
+ AND cep.entity_id = fp.context_id
46
+ AND cep.entity_type = 'context'
47
+ AND cep.path @> ANY(current_setting('mat_path.paths', true)::ltree[])
48
+ WHERE fp.entity_type = $1
49
+ ORDER BY COALESCE(nlevel(cep.path), 0) DESC
50
+ LIMIT 1`;
51
+ return require_mat_path_state.matPathState.withMatPath(tableName, (transaction) => require_FieldPolicy.default.sequelize.query(EFFECTIVE_POLICY_QUERY, {
52
+ bind: [entityType],
53
+ type: sequelize.QueryTypes.SELECT,
54
+ transaction
55
+ }));
56
+ };
57
+
58
+ //#endregion
59
+ exports.create = create;
60
+ Object.defineProperty(exports, 'field_policy_exports', {
61
+ enumerable: true,
62
+ get: function () {
63
+ return field_policy_exports;
64
+ }
65
+ });
66
+ exports.findAll = findAll;
67
+ exports.findEffectivePolicy = findEffectivePolicy;
68
+ exports.remove = remove;
69
+ exports.update = update;
@@ -0,0 +1,35 @@
1
+ import { EntityType, FieldPolicy, ModelInclusion } from "../models/FieldPolicy.cjs";
2
+
3
+ //#region src/repository/field-policy.d.ts
4
+ declare namespace field_policy_d_exports {
5
+ export { CreateFieldPolicyData, UpdateFieldPolicyData, create, findAll, findAllByContext, findAllByContextIds, findByContextAndName, findById, findEffectivePolicy, remove, update };
6
+ }
7
+ interface CreateFieldPolicyData {
8
+ contextId: string;
9
+ name: string;
10
+ entityType?: EntityType;
11
+ fields?: string[];
12
+ models?: ModelInclusion[];
13
+ }
14
+ interface UpdateFieldPolicyData {
15
+ entityType?: EntityType;
16
+ fields?: string[];
17
+ models?: ModelInclusion[];
18
+ }
19
+ declare const findByContextAndName: (contextId: string, name: string) => Promise<FieldPolicy | null>;
20
+ declare const findById: (id: string) => Promise<FieldPolicy | null>;
21
+ declare const findAllByContext: (contextId: string) => Promise<FieldPolicy[]>;
22
+ declare const findAll: () => Promise<FieldPolicy[]>;
23
+ declare const findAllByContextIds: (contextIds: string[]) => Promise<FieldPolicy[]>;
24
+ declare const create: ({
25
+ contextId,
26
+ name,
27
+ entityType,
28
+ fields,
29
+ models
30
+ }: CreateFieldPolicyData) => Promise<FieldPolicy>;
31
+ declare const update: (id: string, data: UpdateFieldPolicyData) => Promise<FieldPolicy | null>;
32
+ declare const remove: (id: string) => Promise<number>;
33
+ declare const findEffectivePolicy: (entityType: string) => Promise<Record<string, unknown>[]>;
34
+ //#endregion
35
+ export { field_policy_d_exports };
@@ -0,0 +1,35 @@
1
+ import { EntityType, FieldPolicy, ModelInclusion } from "../models/FieldPolicy.js";
2
+
3
+ //#region src/repository/field-policy.d.ts
4
+ declare namespace field_policy_d_exports {
5
+ export { CreateFieldPolicyData, UpdateFieldPolicyData, create, findAll, findAllByContext, findAllByContextIds, findByContextAndName, findById, findEffectivePolicy, remove, update };
6
+ }
7
+ interface CreateFieldPolicyData {
8
+ contextId: string;
9
+ name: string;
10
+ entityType?: EntityType;
11
+ fields?: string[];
12
+ models?: ModelInclusion[];
13
+ }
14
+ interface UpdateFieldPolicyData {
15
+ entityType?: EntityType;
16
+ fields?: string[];
17
+ models?: ModelInclusion[];
18
+ }
19
+ declare const findByContextAndName: (contextId: string, name: string) => Promise<FieldPolicy | null>;
20
+ declare const findById: (id: string) => Promise<FieldPolicy | null>;
21
+ declare const findAllByContext: (contextId: string) => Promise<FieldPolicy[]>;
22
+ declare const findAll: () => Promise<FieldPolicy[]>;
23
+ declare const findAllByContextIds: (contextIds: string[]) => Promise<FieldPolicy[]>;
24
+ declare const create: ({
25
+ contextId,
26
+ name,
27
+ entityType,
28
+ fields,
29
+ models
30
+ }: CreateFieldPolicyData) => Promise<FieldPolicy>;
31
+ declare const update: (id: string, data: UpdateFieldPolicyData) => Promise<FieldPolicy | null>;
32
+ declare const remove: (id: string) => Promise<number>;
33
+ declare const findEffectivePolicy: (entityType: string) => Promise<Record<string, unknown>[]>;
34
+ //#endregion
35
+ export { field_policy_d_exports };
@@ -0,0 +1,59 @@
1
+ import { __export } from "../_virtual/rolldown_runtime.js";
2
+ import { matPathState } from "../mat-path-state.js";
3
+ import FieldPolicy_default from "../models/FieldPolicy.js";
4
+ import { QueryTypes } from "sequelize";
5
+
6
+ //#region src/repository/field-policy.ts
7
+ var field_policy_exports = /* @__PURE__ */ __export({
8
+ create: () => create,
9
+ findAll: () => findAll,
10
+ findAllByContext: () => findAllByContext,
11
+ findAllByContextIds: () => findAllByContextIds,
12
+ findByContextAndName: () => findByContextAndName,
13
+ findById: () => findById,
14
+ findEffectivePolicy: () => findEffectivePolicy,
15
+ remove: () => remove,
16
+ update: () => update
17
+ });
18
+ const findByContextAndName = (contextId, name) => FieldPolicy_default.findOne({ where: {
19
+ contextId,
20
+ name
21
+ } });
22
+ const findById = (id) => FieldPolicy_default.findByPk(id);
23
+ const findAllByContext = (contextId) => FieldPolicy_default.findAll({ where: { contextId } });
24
+ const findAll = () => FieldPolicy_default.findAll();
25
+ const findAllByContextIds = (contextIds) => FieldPolicy_default.findAll({ where: { contextId: contextIds } });
26
+ const create = ({ contextId, name, entityType, fields, models }) => FieldPolicy_default.create({
27
+ contextId,
28
+ name,
29
+ entityType,
30
+ fields,
31
+ models
32
+ });
33
+ const update = async (id, data) => {
34
+ const policy = await FieldPolicy_default.findByPk(id);
35
+ if (!policy) return null;
36
+ return policy.update(data);
37
+ };
38
+ const remove = (id) => FieldPolicy_default.destroy({ where: { id } });
39
+ const findEffectivePolicy = (entityType) => {
40
+ const tableName = FieldPolicy_default.getTableName();
41
+ const EFFECTIVE_POLICY_QUERY = `
42
+ SELECT fp.*
43
+ FROM "${tableName}" fp
44
+ LEFT JOIN context_entity_path cep ON cep.deleted_at IS NULL
45
+ AND cep.entity_id = fp.context_id
46
+ AND cep.entity_type = 'context'
47
+ AND cep.path @> ANY(current_setting('mat_path.paths', true)::ltree[])
48
+ WHERE fp.entity_type = $1
49
+ ORDER BY COALESCE(nlevel(cep.path), 0) DESC
50
+ LIMIT 1`;
51
+ return matPathState.withMatPath(tableName, (transaction) => FieldPolicy_default.sequelize.query(EFFECTIVE_POLICY_QUERY, {
52
+ bind: [entityType],
53
+ type: QueryTypes.SELECT,
54
+ transaction
55
+ }));
56
+ };
57
+
58
+ //#endregion
59
+ export { create, field_policy_exports, findAll, findEffectivePolicy, remove, update };
@@ -0,0 +1,14 @@
1
+ const require_index = require('../../utils/constants/index.cjs');
2
+
3
+ //#region src/repository/utils/formatValues.ts
4
+ const formatFunctions = { [require_index.CustomFieldDefinitionType.DATE]: (value) => {
5
+ if (value) {
6
+ const date = new Date(value);
7
+ if (date.toString() === "Invalid Date") throw new Error(`Invalid date value: ${value}`);
8
+ return date.toISOString();
9
+ }
10
+ return null;
11
+ } };
12
+
13
+ //#endregion
14
+ exports.formatFunctions = formatFunctions;
@@ -0,0 +1,14 @@
1
+ import { CustomFieldDefinitionType } from "../../utils/constants/index.js";
2
+
3
+ //#region src/repository/utils/formatValues.ts
4
+ const formatFunctions = { [CustomFieldDefinitionType.DATE]: (value) => {
5
+ if (value) {
6
+ const date = new Date(value);
7
+ if (date.toString() === "Invalid Date") throw new Error(`Invalid date value: ${value}`);
8
+ return date.toISOString();
9
+ }
10
+ return null;
11
+ } };
12
+
13
+ //#endregion
14
+ export { formatFunctions };
@@ -0,0 +1,85 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_index = require('../utils/logger/index.cjs');
3
+ const require_CustomValidator = require('../models/CustomValidator.cjs');
4
+ require('../models/index.cjs');
5
+ let sequelize_lib_sequelize = require("sequelize/lib/sequelize");
6
+ sequelize_lib_sequelize = require_rolldown_runtime.__toESM(sequelize_lib_sequelize);
7
+
8
+ //#region src/repository/validator.ts
9
+ const create = async (validatorAttributes, options = {}) => {
10
+ require_index.default.debug("custom-validator - create validator");
11
+ return await require_CustomValidator.default.create(validatorAttributes, options);
12
+ };
13
+ const findAll = async (where = {}, options = {}) => {
14
+ require_index.default.debug("custom-validator - find all validators");
15
+ const { transaction, withDisabled, include, attributes, raw } = options;
16
+ let validators;
17
+ if (withDisabled) validators = await require_CustomValidator.default.unscoped().scope("userScope").findAll({
18
+ where,
19
+ transaction,
20
+ include,
21
+ attributes,
22
+ raw
23
+ });
24
+ else validators = await require_CustomValidator.default.scope(["defaultScope", "userScope"]).findAll({
25
+ where,
26
+ transaction,
27
+ include,
28
+ attributes,
29
+ raw
30
+ });
31
+ return validators;
32
+ };
33
+ const findAllByModelType = async (modelType, entityId, options = {}) => {
34
+ require_index.default.debug("custom-validator - find all validators by model type");
35
+ return findAll({
36
+ modelType,
37
+ ...!options?.modelOptions?.useEntityIdFromInclude && { entityId }
38
+ }, {
39
+ ...options,
40
+ include: options?.modelOptions?.include?.(entityId)
41
+ });
42
+ };
43
+ const update = async (id, updates, options) => {
44
+ require_index.default.debug("custom-validator - update validator");
45
+ return require_CustomValidator.default.update(updates, {
46
+ where: { id },
47
+ returning: true,
48
+ ...options
49
+ });
50
+ };
51
+ const disable = async (id, options) => {
52
+ require_index.default.debug("custom-validator - disable validator");
53
+ return update(id, { disabled: true }, options);
54
+ };
55
+ const findEffective = async (entityType = "Vehicle", requestPath) => {
56
+ const QUERY = `
57
+ SELECT DISTINCT ON (cv.model_type) cv.*, cep.path
58
+ FROM custom_validators cv
59
+ LEFT JOIN context_entity_path cep ON cep.deleted_at IS NULL
60
+ AND cep.entity_id = cv.entity_id
61
+ AND cep.entity_type = cv.entity_type
62
+ AND cep.path @> ANY(ARRAY['${requestPath}']::ltree[])
63
+ WHERE cv.model_type IN ($1) AND cv.disabled = false
64
+ ORDER BY cv.model_type, COALESCE(nlevel(cep.path), 0) DESC;`;
65
+ try {
66
+ await sequelize_lib_sequelize.default.query(QUERY, {
67
+ bind: [entityType],
68
+ type: sequelize_lib_sequelize.default.QueryTypes.SELECT
69
+ });
70
+ return {
71
+ ...result.schema.properties.after,
72
+ path: result.path
73
+ };
74
+ } catch (err) {
75
+ throw err;
76
+ }
77
+ };
78
+
79
+ //#endregion
80
+ exports.create = create;
81
+ exports.disable = disable;
82
+ exports.findAll = findAll;
83
+ exports.findAllByModelType = findAllByModelType;
84
+ exports.findEffective = findEffective;
85
+ exports.update = update;
@@ -0,0 +1,78 @@
1
+ import logger_default from "../utils/logger/index.js";
2
+ import CustomValidator_default from "../models/CustomValidator.js";
3
+ import "../models/index.js";
4
+ import sequelize from "sequelize/lib/sequelize";
5
+
6
+ //#region src/repository/validator.ts
7
+ const create = async (validatorAttributes, options = {}) => {
8
+ logger_default.debug("custom-validator - create validator");
9
+ return await CustomValidator_default.create(validatorAttributes, options);
10
+ };
11
+ const findAll = async (where = {}, options = {}) => {
12
+ logger_default.debug("custom-validator - find all validators");
13
+ const { transaction, withDisabled, include, attributes, raw } = options;
14
+ let validators;
15
+ if (withDisabled) validators = await CustomValidator_default.unscoped().scope("userScope").findAll({
16
+ where,
17
+ transaction,
18
+ include,
19
+ attributes,
20
+ raw
21
+ });
22
+ else validators = await CustomValidator_default.scope(["defaultScope", "userScope"]).findAll({
23
+ where,
24
+ transaction,
25
+ include,
26
+ attributes,
27
+ raw
28
+ });
29
+ return validators;
30
+ };
31
+ const findAllByModelType = async (modelType, entityId, options = {}) => {
32
+ logger_default.debug("custom-validator - find all validators by model type");
33
+ return findAll({
34
+ modelType,
35
+ ...!options?.modelOptions?.useEntityIdFromInclude && { entityId }
36
+ }, {
37
+ ...options,
38
+ include: options?.modelOptions?.include?.(entityId)
39
+ });
40
+ };
41
+ const update = async (id, updates, options) => {
42
+ logger_default.debug("custom-validator - update validator");
43
+ return CustomValidator_default.update(updates, {
44
+ where: { id },
45
+ returning: true,
46
+ ...options
47
+ });
48
+ };
49
+ const disable = async (id, options) => {
50
+ logger_default.debug("custom-validator - disable validator");
51
+ return update(id, { disabled: true }, options);
52
+ };
53
+ const findEffective = async (entityType = "Vehicle", requestPath) => {
54
+ const QUERY = `
55
+ SELECT DISTINCT ON (cv.model_type) cv.*, cep.path
56
+ FROM custom_validators cv
57
+ LEFT JOIN context_entity_path cep ON cep.deleted_at IS NULL
58
+ AND cep.entity_id = cv.entity_id
59
+ AND cep.entity_type = cv.entity_type
60
+ AND cep.path @> ANY(ARRAY['${requestPath}']::ltree[])
61
+ WHERE cv.model_type IN ($1) AND cv.disabled = false
62
+ ORDER BY cv.model_type, COALESCE(nlevel(cep.path), 0) DESC;`;
63
+ try {
64
+ await sequelize.query(QUERY, {
65
+ bind: [entityType],
66
+ type: sequelize.QueryTypes.SELECT
67
+ });
68
+ return {
69
+ ...result.schema.properties.after,
70
+ path: result.path
71
+ };
72
+ } catch (err) {
73
+ throw err;
74
+ }
75
+ };
76
+
77
+ //#endregion
78
+ export { create, disable, findAll, findAllByModelType, findEffective, update };
@@ -0,0 +1,77 @@
1
+ const require_index = require('../utils/logger/index.cjs');
2
+ const require_index$1 = require('../errors/index.cjs');
3
+ const require_definition = require('./definition.cjs');
4
+ const require_CustomFieldValue = require('../models/CustomFieldValue.cjs');
5
+ require('../models/index.cjs');
6
+ const require_formatValues = require('./utils/formatValues.cjs');
7
+
8
+ //#region src/repository/value.ts
9
+ /**
10
+ * Retrieves custom field values for given model IDs
11
+ * @param modelIds - An array of model IDs to query custom field values for.
12
+ * @param options - Optional configuration object.
13
+ */
14
+ const findValuesByModelIds = async (modelIds, options) => {
15
+ const { transaction } = options;
16
+ return require_CustomFieldValue.default.findAll({
17
+ where: { modelId: modelIds },
18
+ transaction,
19
+ raw: true,
20
+ nest: true
21
+ });
22
+ };
23
+ /**
24
+ * Try to update custom field values for a model instance.
25
+ * Create new value record if not exists, but fails if value's definition not exist.
26
+ * Return the updated values
27
+ */
28
+ const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
29
+ const names = Object.keys(valuesToUpdate);
30
+ require_index.default.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {
31
+ names,
32
+ optionsKeys: options ? Object.keys(options) : null,
33
+ valuesToUpdate,
34
+ identifiers
35
+ });
36
+ const { modelOptions, transaction } = options;
37
+ const where = {
38
+ modelType,
39
+ name: names,
40
+ ...!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }
41
+ };
42
+ const fieldDefinitions = await require_definition.findAll(where, {
43
+ withDisabled: true,
44
+ transaction,
45
+ include: modelOptions.include?.(identifiers)
46
+ }) ?? [];
47
+ const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
48
+ if (fieldDefinitions.length !== names.length) {
49
+ require_index.default.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, {
50
+ names,
51
+ fieldDefinitions
52
+ });
53
+ throw new require_index$1.MissingDefinitionError(names.filter((name) => !fieldDefinitions.some((def) => def.name === name)));
54
+ }
55
+ const disabledNames = disabledDefinitions?.map((def) => def.name) || [];
56
+ const valuesWithDisabledDefinitions = names.filter((name) => disabledNames.includes(name));
57
+ if (valuesWithDisabledDefinitions?.length > 0) require_index.default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(", ")}`);
58
+ const values = names.map((name) => {
59
+ const fieldDefinition = fieldDefinitions.find((def) => def.name === name);
60
+ const formatFunction = require_formatValues.formatFunctions[fieldDefinition.fieldType];
61
+ const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];
62
+ return {
63
+ modelId,
64
+ updatedAt: /* @__PURE__ */ new Date(),
65
+ customFieldDefinitionId: fieldDefinition.id,
66
+ value: value !== void 0 ? value : fieldDefinition.defaultValue
67
+ };
68
+ });
69
+ return Promise.all(values.map(async (value) => {
70
+ const [cfv] = await require_CustomFieldValue.default.upsert(value, { transaction: options.transaction });
71
+ return cfv;
72
+ }));
73
+ };
74
+
75
+ //#endregion
76
+ exports.findValuesByModelIds = findValuesByModelIds;
77
+ exports.updateValues = updateValues;
@@ -0,0 +1,76 @@
1
+ import logger_default from "../utils/logger/index.js";
2
+ import { MissingDefinitionError } from "../errors/index.js";
3
+ import { findAll } from "./definition.js";
4
+ import CustomFieldValue_default from "../models/CustomFieldValue.js";
5
+ import "../models/index.js";
6
+ import { formatFunctions } from "./utils/formatValues.js";
7
+
8
+ //#region src/repository/value.ts
9
+ /**
10
+ * Retrieves custom field values for given model IDs
11
+ * @param modelIds - An array of model IDs to query custom field values for.
12
+ * @param options - Optional configuration object.
13
+ */
14
+ const findValuesByModelIds = async (modelIds, options) => {
15
+ const { transaction } = options;
16
+ return CustomFieldValue_default.findAll({
17
+ where: { modelId: modelIds },
18
+ transaction,
19
+ raw: true,
20
+ nest: true
21
+ });
22
+ };
23
+ /**
24
+ * Try to update custom field values for a model instance.
25
+ * Create new value record if not exists, but fails if value's definition not exist.
26
+ * Return the updated values
27
+ */
28
+ const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
29
+ const names = Object.keys(valuesToUpdate);
30
+ logger_default.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {
31
+ names,
32
+ optionsKeys: options ? Object.keys(options) : null,
33
+ valuesToUpdate,
34
+ identifiers
35
+ });
36
+ const { modelOptions, transaction } = options;
37
+ const where = {
38
+ modelType,
39
+ name: names,
40
+ ...!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }
41
+ };
42
+ const fieldDefinitions = await findAll(where, {
43
+ withDisabled: true,
44
+ transaction,
45
+ include: modelOptions.include?.(identifiers)
46
+ }) ?? [];
47
+ const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
48
+ if (fieldDefinitions.length !== names.length) {
49
+ logger_default.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, {
50
+ names,
51
+ fieldDefinitions
52
+ });
53
+ throw new MissingDefinitionError(names.filter((name) => !fieldDefinitions.some((def) => def.name === name)));
54
+ }
55
+ const disabledNames = disabledDefinitions?.map((def) => def.name) || [];
56
+ const valuesWithDisabledDefinitions = names.filter((name) => disabledNames.includes(name));
57
+ if (valuesWithDisabledDefinitions?.length > 0) logger_default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(", ")}`);
58
+ const values = names.map((name) => {
59
+ const fieldDefinition = fieldDefinitions.find((def) => def.name === name);
60
+ const formatFunction = formatFunctions[fieldDefinition.fieldType];
61
+ const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];
62
+ return {
63
+ modelId,
64
+ updatedAt: /* @__PURE__ */ new Date(),
65
+ customFieldDefinitionId: fieldDefinition.id,
66
+ value: value !== void 0 ? value : fieldDefinition.defaultValue
67
+ };
68
+ });
69
+ return Promise.all(values.map(async (value) => {
70
+ const [cfv] = await CustomFieldValue_default.upsert(value, { transaction: options.transaction });
71
+ return cfv;
72
+ }));
73
+ };
74
+
75
+ //#endregion
76
+ export { findValuesByModelIds, updateValues };
@@ -0,0 +1,56 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_index = require('../utils/helpers/index.cjs');
3
+ const require_filter_helpers = require('./helpers/filter.helpers.cjs');
4
+ let sequelize = require("sequelize");
5
+ let sequelize_typescript = require("sequelize-typescript");
6
+ let _autofleet_common_types = require("@autofleet/common-types");
7
+
8
+ //#region src/scopes/filter.ts
9
+ /**
10
+ * A Sequelize scope for filtering models by custom fields.
11
+ * This scope builds a WHERE clause to be applied on the main query.
12
+ *
13
+ * @param name - The model type name used to join custom_field_definitions.
14
+ * @returns A function that takes conditions and returns the Sequelize options object.
15
+ */
16
+ const customFieldsFilterScope = (name, options) => ({ replacementsMap: replacements, scopeValue: conditions }) => {
17
+ if (!conditions || Object.keys(conditions).length === 0) return {};
18
+ const queryType = options?.useCustomFieldsEntries ? require_filter_helpers.SubQueryType.ENTRIES : require_filter_helpers.SubQueryType.VALUES;
19
+ const reverseReplacementsMap = new Map(Object.entries(replacements).map(([key, value]) => [value, key]));
20
+ const conditionsStrings = Object.entries(conditions).map(([key, condition]) => {
21
+ switch (queryType) {
22
+ case require_filter_helpers.SubQueryType.ENTRIES: return require_filter_helpers.formatConditionsForEntries(key, condition, reverseReplacementsMap);
23
+ case require_filter_helpers.SubQueryType.VALUES: return require_filter_helpers.formatConditionsForValues(key, condition, reverseReplacementsMap);
24
+ default: return false;
25
+ }
26
+ }).filter(Boolean);
27
+ if (conditionsStrings.length === 0) return {};
28
+ const subQuery = require_filter_helpers.getFilterCustomFieldsSubQuery(queryType, name, conditionsStrings);
29
+ return {
30
+ where: { id: { [sequelize.Op.in]: sequelize_typescript.Sequelize.literal(`(${subQuery})`) } },
31
+ replacements
32
+ };
33
+ };
34
+ const scopeName = _autofleet_common_types.customFields.CUSTOM_FIELDS_FILTER_SCOPE;
35
+ const customFieldsSortScope = (name, options) => ({ replacementsMap, scopeValue: sort }) => {
36
+ if (!sort || sort.length === 0) return {};
37
+ const queryType = options?.useCustomFieldsEntries ? require_filter_helpers.SubQueryType.ENTRIES : require_filter_helpers.SubQueryType.VALUES;
38
+ const randomStr = require_index.generateRandomString();
39
+ const includes = Object.entries(sort).map(([key]) => {
40
+ const replacementKey = Object.keys(replacementsMap).find((randomString) => replacementsMap[randomString] === key);
41
+ return [sequelize_typescript.Sequelize.literal(require_filter_helpers.getSortCustomFieldsSubQuery(queryType, name, replacementKey)), randomStr];
42
+ });
43
+ const orders = Object.entries(sort).map(([, sortObject]) => {
44
+ const direction = typeof sortObject === "string" ? sortObject : Object.values(sortObject)[0];
45
+ return sequelize_typescript.Sequelize.literal(`"${randomStr}" ${direction || "ASC"}`);
46
+ });
47
+ return {
48
+ attributes: { include: includes },
49
+ order: orders,
50
+ replacements: replacementsMap
51
+ };
52
+ };
53
+
54
+ //#endregion
55
+ exports.customFieldsFilterScope = customFieldsFilterScope;
56
+ exports.customFieldsSortScope = customFieldsSortScope;