@autofleet/sadot 1.1.6 → 1.1.7-beta

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 (331) hide show
  1. package/.nvmrc +1 -0
  2. package/dist/api/index.d.ts +3 -0
  3. package/dist/api/index.js +12 -2
  4. package/dist/api/v1/definition/index.d.ts +3 -0
  5. package/dist/api/v1/definition/index.js +116 -2
  6. package/dist/api/v1/definition/validations.d.ts +2 -0
  7. package/dist/api/v1/definition/validations.js +77 -2
  8. package/dist/api/v1/errors.d.ts +4 -0
  9. package/dist/api/v1/errors.js +12 -2
  10. package/dist/api/v1/index.d.ts +3 -0
  11. package/dist/api/v1/index.js +13 -2
  12. package/dist/api/v1/validator/index.d.ts +3 -0
  13. package/dist/api/v1/validator/index.js +143 -2
  14. package/dist/api/v1/validator/validations.d.ts +6 -23
  15. package/dist/api/v1/validator/validations.js +38 -2
  16. package/dist/errors/index.d.ts +24 -0
  17. package/dist/errors/index.js +66 -3
  18. package/dist/events/index.d.ts +5 -0
  19. package/dist/events/index.js +54 -2
  20. package/dist/hooks/create.d.ts +10 -0
  21. package/dist/hooks/create.js +95 -0
  22. package/dist/hooks/enrich.d.ts +25 -0
  23. package/dist/hooks/enrich.js +198 -2
  24. package/dist/hooks/find.d.ts +1 -0
  25. package/dist/hooks/find.js +29 -2
  26. package/dist/hooks/hooks.d.ts +17 -0
  27. package/dist/hooks/hooks.js +388 -2
  28. package/dist/hooks/index.d.ts +5 -0
  29. package/dist/hooks/index.js +17 -1
  30. package/dist/hooks/update.d.ts +10 -0
  31. package/dist/hooks/update.js +49 -0
  32. package/dist/hooks/utils/updateInstanceValues.d.ts +15 -0
  33. package/dist/hooks/utils/updateInstanceValues.js +50 -2
  34. package/dist/hooks/workaround.d.ts +10 -0
  35. package/dist/hooks/workaround.js +37 -0
  36. package/dist/index.d.ts +12 -22
  37. package/dist/index.js +67 -2
  38. package/dist/models/CustomFieldDefinition.d.ts +23 -29
  39. package/dist/models/CustomFieldDefinition.js +192 -2
  40. package/dist/models/CustomFieldEntries.d.ts +13 -14
  41. package/dist/models/CustomFieldEntries.js +123 -2
  42. package/dist/models/CustomFieldValue.d.ts +14 -20
  43. package/dist/models/CustomFieldValue.js +151 -2
  44. package/dist/models/CustomValidator.d.ts +15 -17
  45. package/dist/models/CustomValidator.js +98 -2
  46. package/dist/models/index.d.ts +18 -6
  47. package/dist/models/index.js +131 -2
  48. package/dist/models/tests/AssociatedTestModel.d.ts +12 -0
  49. package/dist/models/tests/AssociatedTestModel.js +71 -2
  50. package/dist/models/tests/TestModel.d.ts +12 -0
  51. package/dist/models/tests/TestModel.js +69 -2
  52. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +10 -0
  53. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +53 -2
  54. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +13 -0
  55. package/dist/models/tests/contextAwareModels/ContextTestModel.js +47 -2
  56. package/dist/repository/definition.d.ts +36 -0
  57. package/dist/repository/definition.js +121 -2
  58. package/dist/repository/entries.d.ts +13 -0
  59. package/dist/repository/entries.js +92 -2
  60. package/dist/repository/utils/formatValues.d.ts +3 -0
  61. package/dist/repository/utils/formatValues.js +16 -2
  62. package/dist/repository/validator.d.ts +28 -0
  63. package/dist/repository/validator.js +69 -2
  64. package/dist/repository/value.d.ts +28 -0
  65. package/dist/repository/value.js +124 -2
  66. package/dist/scopes/filter.d.ts +29 -22
  67. package/dist/scopes/filter.js +75 -2
  68. package/dist/scopes/helpers/filter.helpers.d.ts +40 -15
  69. package/dist/scopes/helpers/filter.helpers.js +183 -25
  70. package/dist/scopes/index.d.ts +2 -0
  71. package/dist/scopes/index.js +6 -1
  72. package/dist/tests/api/test-api.d.ts +2 -0
  73. package/dist/tests/api/test-api.js +38 -0
  74. package/dist/tests/functional/searching/index.d.ts +8 -0
  75. package/dist/tests/functional/searching/index.js +44 -0
  76. package/dist/tests/helpers/commonHooks.d.ts +6 -0
  77. package/dist/tests/helpers/commonHooks.js +62 -0
  78. package/dist/tests/helpers/database-config.d.ts +16 -0
  79. package/dist/tests/helpers/database-config.js +17 -0
  80. package/dist/tests/helpers/index.d.ts +7 -0
  81. package/dist/tests/helpers/index.js +33 -0
  82. package/dist/tests/mocks/definition.mock.d.ts +48 -0
  83. package/dist/tests/mocks/definition.mock.js +78 -0
  84. package/dist/tests/mocks/events.mock.d.ts +4 -0
  85. package/dist/tests/mocks/events.mock.js +21 -0
  86. package/dist/tests/mocks/testModel.d.ts +12 -0
  87. package/dist/tests/mocks/testModel.js +35 -0
  88. package/dist/types/definition/index.d.ts +25 -0
  89. package/dist/types/definition/index.js +2 -0
  90. package/dist/types/entries/index.d.ts +25 -0
  91. package/dist/types/entries/index.js +2 -0
  92. package/dist/types/index.d.ts +46 -45
  93. package/dist/types/index.js +2 -0
  94. package/dist/types/value/index.d.ts +15 -0
  95. package/dist/types/value/index.js +2 -0
  96. package/dist/utils/constants/index.d.ts +17 -20
  97. package/dist/utils/constants/index.js +22 -2
  98. package/dist/utils/db/index.d.ts +4 -0
  99. package/dist/utils/db/index.js +24 -2
  100. package/dist/utils/helpers/index.d.ts +23 -28
  101. package/dist/utils/helpers/index.js +40 -2
  102. package/dist/utils/init.d.ts +7 -0
  103. package/dist/utils/init.js +112 -2
  104. package/dist/utils/logger/index.d.ts +3 -0
  105. package/dist/utils/logger/index.js +42 -2
  106. package/dist/utils/scopeAttributes.d.ts +2 -0
  107. package/dist/utils/scopeAttributes.js +11 -2
  108. package/dist/utils/validations/index.d.ts +8 -0
  109. package/dist/utils/validations/index.js +41 -2
  110. package/dist/utils/validations/schema/custom-fields.d.ts +2 -6
  111. package/dist/utils/validations/schema/custom-fields.js +9 -2
  112. package/dist/utils/validations/schema/validator-schema.d.ts +9 -0
  113. package/dist/utils/validations/schema/validator-schema.js +95 -2
  114. package/dist/utils/validations/type.d.ts +15 -0
  115. package/dist/utils/validations/type.js +2 -0
  116. package/dist/utils/validations/validators/index.d.ts +14 -0
  117. package/dist/utils/validations/validators/index.js +40 -2
  118. package/dist/utils/validations/validators/select.validator.d.ts +5 -0
  119. package/dist/utils/validations/validators/select.validator.js +12 -2
  120. package/dist/utils/validations/validators/status.validator.d.ts +12 -0
  121. package/dist/utils/validations/validators/status.validator.js +15 -2
  122. package/package.json +39 -40
  123. package/src/api/index.ts +10 -0
  124. package/src/api/v1/definition/index.ts +104 -0
  125. package/src/api/v1/definition/validations.ts +75 -0
  126. package/src/api/v1/errors.ts +13 -0
  127. package/src/api/v1/index.ts +11 -0
  128. package/src/api/v1/validator/index.ts +141 -0
  129. package/src/api/v1/validator/validations.ts +38 -0
  130. package/src/errors/index.ts +70 -0
  131. package/src/events/index.ts +63 -0
  132. package/src/hooks/create.ts +81 -0
  133. package/src/hooks/enrich.ts +255 -0
  134. package/src/hooks/find.ts +27 -0
  135. package/src/hooks/hooks.ts +479 -0
  136. package/src/hooks/index.ts +20 -0
  137. package/src/hooks/update.ts +55 -0
  138. package/src/hooks/utils/updateInstanceValues.ts +63 -0
  139. package/src/hooks/workaround.ts +47 -0
  140. package/src/index.ts +52 -0
  141. package/src/models/CustomFieldDefinition.ts +162 -0
  142. package/src/models/CustomFieldEntries.ts +81 -0
  143. package/src/models/CustomFieldValue.ts +118 -0
  144. package/src/models/CustomValidator.ts +78 -0
  145. package/src/models/index.ts +165 -0
  146. package/src/models/tests/AssociatedTestModel.ts +57 -0
  147. package/src/models/tests/TestModel.ts +54 -0
  148. package/src/models/tests/contextAwareModels/ContextAwareTestModel.ts +43 -0
  149. package/src/models/tests/contextAwareModels/ContextTestModel.ts +38 -0
  150. package/src/repository/definition.ts +175 -0
  151. package/src/repository/entries.ts +88 -0
  152. package/src/repository/utils/formatValues.ts +14 -0
  153. package/src/repository/validator.ts +119 -0
  154. package/src/repository/value.ts +116 -0
  155. package/src/scopes/filter.ts +100 -0
  156. package/src/scopes/helpers/filter.helpers.ts +227 -0
  157. package/src/scopes/index.ts +6 -0
  158. package/src/tests/api/test-api.ts +40 -0
  159. package/src/tests/functional/searching/index.ts +39 -0
  160. package/src/tests/helpers/commonHooks.ts +43 -0
  161. package/src/tests/helpers/database-config.ts +15 -0
  162. package/src/tests/helpers/index.ts +35 -0
  163. package/src/tests/mocks/definition.mock.ts +84 -0
  164. package/src/tests/mocks/events.mock.ts +21 -0
  165. package/src/tests/mocks/testModel.ts +37 -0
  166. package/src/types/definition/index.ts +24 -0
  167. package/src/types/entries/index.ts +27 -0
  168. package/src/types/index.ts +52 -0
  169. package/src/types/value/index.ts +14 -0
  170. package/src/utils/constants/index.ts +25 -0
  171. package/src/utils/db/index.ts +21 -0
  172. package/src/utils/helpers/index.ts +66 -0
  173. package/src/utils/init.ts +122 -0
  174. package/src/utils/logger/index.ts +14 -0
  175. package/src/utils/scopeAttributes.ts +12 -0
  176. package/src/utils/validations/index.ts +46 -0
  177. package/src/utils/validations/schema/README.md +93 -0
  178. package/src/utils/validations/schema/custom-fields.ts +8 -0
  179. package/src/utils/validations/schema/validator-schema.ts +106 -0
  180. package/src/utils/validations/type.ts +20 -0
  181. package/src/utils/validations/validators/index.ts +38 -0
  182. package/src/utils/validations/validators/select.validator.ts +12 -0
  183. package/src/utils/validations/validators/status.validator.ts +22 -0
  184. package/tsconfig.build.json +7 -0
  185. package/tsconfig.json +16 -0
  186. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs +0 -1
  187. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js +0 -1
  188. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs +0 -1
  189. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js +0 -1
  190. package/dist/_virtual/rolldown_runtime.cjs +0 -1
  191. package/dist/api/index.cjs +0 -2
  192. package/dist/api/index.cjs.map +0 -1
  193. package/dist/api/index.js.map +0 -1
  194. package/dist/api/v1/definition/index.cjs +0 -2
  195. package/dist/api/v1/definition/index.cjs.map +0 -1
  196. package/dist/api/v1/definition/index.js.map +0 -1
  197. package/dist/api/v1/definition/validations.cjs +0 -2
  198. package/dist/api/v1/definition/validations.cjs.map +0 -1
  199. package/dist/api/v1/definition/validations.js.map +0 -1
  200. package/dist/api/v1/errors.cjs +0 -2
  201. package/dist/api/v1/errors.cjs.map +0 -1
  202. package/dist/api/v1/errors.js.map +0 -1
  203. package/dist/api/v1/index.cjs +0 -2
  204. package/dist/api/v1/index.cjs.map +0 -1
  205. package/dist/api/v1/index.js.map +0 -1
  206. package/dist/api/v1/validator/index.cjs +0 -2
  207. package/dist/api/v1/validator/index.cjs.map +0 -1
  208. package/dist/api/v1/validator/index.js.map +0 -1
  209. package/dist/api/v1/validator/validations.cjs +0 -2
  210. package/dist/api/v1/validator/validations.cjs.map +0 -1
  211. package/dist/api/v1/validator/validations.d.cts +0 -23
  212. package/dist/api/v1/validator/validations.js.map +0 -1
  213. package/dist/errors/index.cjs +0 -3
  214. package/dist/errors/index.cjs.map +0 -1
  215. package/dist/errors/index.js.map +0 -1
  216. package/dist/events/index.cjs +0 -2
  217. package/dist/events/index.cjs.map +0 -1
  218. package/dist/events/index.js.map +0 -1
  219. package/dist/hooks/enrich.cjs +0 -2
  220. package/dist/hooks/enrich.cjs.map +0 -1
  221. package/dist/hooks/enrich.js.map +0 -1
  222. package/dist/hooks/find.cjs +0 -2
  223. package/dist/hooks/find.cjs.map +0 -1
  224. package/dist/hooks/find.js.map +0 -1
  225. package/dist/hooks/hooks.cjs +0 -2
  226. package/dist/hooks/hooks.cjs.map +0 -1
  227. package/dist/hooks/hooks.js.map +0 -1
  228. package/dist/hooks/index.cjs +0 -1
  229. package/dist/hooks/utils/updateInstanceValues.cjs +0 -2
  230. package/dist/hooks/utils/updateInstanceValues.cjs.map +0 -1
  231. package/dist/hooks/utils/updateInstanceValues.js.map +0 -1
  232. package/dist/index.cjs +0 -2
  233. package/dist/index.cjs.map +0 -1
  234. package/dist/index.d.cts +0 -23
  235. package/dist/index.js.map +0 -1
  236. package/dist/models/CustomFieldDefinition.cjs +0 -2
  237. package/dist/models/CustomFieldDefinition.cjs.map +0 -1
  238. package/dist/models/CustomFieldDefinition.d.cts +0 -31
  239. package/dist/models/CustomFieldDefinition.js.map +0 -1
  240. package/dist/models/CustomFieldEntries.cjs +0 -2
  241. package/dist/models/CustomFieldEntries.cjs.map +0 -1
  242. package/dist/models/CustomFieldEntries.d.cts +0 -16
  243. package/dist/models/CustomFieldEntries.js.map +0 -1
  244. package/dist/models/CustomFieldValue.cjs +0 -2
  245. package/dist/models/CustomFieldValue.cjs.map +0 -1
  246. package/dist/models/CustomFieldValue.d.cts +0 -22
  247. package/dist/models/CustomFieldValue.js.map +0 -1
  248. package/dist/models/CustomValidator.cjs +0 -2
  249. package/dist/models/CustomValidator.cjs.map +0 -1
  250. package/dist/models/CustomValidator.d.cts +0 -19
  251. package/dist/models/CustomValidator.js.map +0 -1
  252. package/dist/models/index.cjs +0 -2
  253. package/dist/models/index.cjs.map +0 -1
  254. package/dist/models/index.d.cts +0 -6
  255. package/dist/models/index.js.map +0 -1
  256. package/dist/models/tests/AssociatedTestModel.cjs +0 -2
  257. package/dist/models/tests/AssociatedTestModel.cjs.map +0 -1
  258. package/dist/models/tests/AssociatedTestModel.js.map +0 -1
  259. package/dist/models/tests/TestModel.cjs +0 -2
  260. package/dist/models/tests/TestModel.cjs.map +0 -1
  261. package/dist/models/tests/TestModel.js.map +0 -1
  262. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +0 -2
  263. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +0 -1
  264. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +0 -1
  265. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +0 -2
  266. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +0 -1
  267. package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +0 -1
  268. package/dist/repository/definition.cjs +0 -2
  269. package/dist/repository/definition.cjs.map +0 -1
  270. package/dist/repository/definition.js.map +0 -1
  271. package/dist/repository/entries.cjs +0 -2
  272. package/dist/repository/entries.cjs.map +0 -1
  273. package/dist/repository/entries.js.map +0 -1
  274. package/dist/repository/utils/formatValues.cjs +0 -2
  275. package/dist/repository/utils/formatValues.cjs.map +0 -1
  276. package/dist/repository/utils/formatValues.js.map +0 -1
  277. package/dist/repository/validator.cjs +0 -2
  278. package/dist/repository/validator.cjs.map +0 -1
  279. package/dist/repository/validator.js.map +0 -1
  280. package/dist/repository/value.cjs +0 -2
  281. package/dist/repository/value.cjs.map +0 -1
  282. package/dist/repository/value.js.map +0 -1
  283. package/dist/scopes/filter.cjs +0 -2
  284. package/dist/scopes/filter.cjs.map +0 -1
  285. package/dist/scopes/filter.d.cts +0 -23
  286. package/dist/scopes/filter.js.map +0 -1
  287. package/dist/scopes/helpers/filter.helpers.cjs +0 -46
  288. package/dist/scopes/helpers/filter.helpers.cjs.map +0 -1
  289. package/dist/scopes/helpers/filter.helpers.d.cts +0 -17
  290. package/dist/scopes/helpers/filter.helpers.js.map +0 -1
  291. package/dist/scopes/index.cjs +0 -1
  292. package/dist/types/index.d.cts +0 -45
  293. package/dist/utils/constants/index.cjs +0 -2
  294. package/dist/utils/constants/index.cjs.map +0 -1
  295. package/dist/utils/constants/index.d.cts +0 -22
  296. package/dist/utils/constants/index.js.map +0 -1
  297. package/dist/utils/db/index.cjs +0 -2
  298. package/dist/utils/db/index.cjs.map +0 -1
  299. package/dist/utils/db/index.js.map +0 -1
  300. package/dist/utils/helpers/index.cjs +0 -2
  301. package/dist/utils/helpers/index.cjs.map +0 -1
  302. package/dist/utils/helpers/index.d.cts +0 -31
  303. package/dist/utils/helpers/index.js.map +0 -1
  304. package/dist/utils/init.cjs +0 -2
  305. package/dist/utils/init.cjs.map +0 -1
  306. package/dist/utils/init.js.map +0 -1
  307. package/dist/utils/logger/index.cjs +0 -2
  308. package/dist/utils/logger/index.cjs.map +0 -1
  309. package/dist/utils/logger/index.js.map +0 -1
  310. package/dist/utils/scopeAttributes.cjs +0 -2
  311. package/dist/utils/scopeAttributes.cjs.map +0 -1
  312. package/dist/utils/scopeAttributes.js.map +0 -1
  313. package/dist/utils/validations/index.cjs +0 -2
  314. package/dist/utils/validations/index.cjs.map +0 -1
  315. package/dist/utils/validations/index.js.map +0 -1
  316. package/dist/utils/validations/schema/custom-fields.cjs +0 -2
  317. package/dist/utils/validations/schema/custom-fields.cjs.map +0 -1
  318. package/dist/utils/validations/schema/custom-fields.d.cts +0 -7
  319. package/dist/utils/validations/schema/custom-fields.js.map +0 -1
  320. package/dist/utils/validations/schema/validator-schema.cjs +0 -2
  321. package/dist/utils/validations/schema/validator-schema.cjs.map +0 -1
  322. package/dist/utils/validations/schema/validator-schema.js.map +0 -1
  323. package/dist/utils/validations/validators/index.cjs +0 -2
  324. package/dist/utils/validations/validators/index.cjs.map +0 -1
  325. package/dist/utils/validations/validators/index.js.map +0 -1
  326. package/dist/utils/validations/validators/select.validator.cjs +0 -2
  327. package/dist/utils/validations/validators/select.validator.cjs.map +0 -1
  328. package/dist/utils/validations/validators/select.validator.js.map +0 -1
  329. package/dist/utils/validations/validators/status.validator.cjs +0 -2
  330. package/dist/utils/validations/validators/status.validator.cjs.map +0 -1
  331. package/dist/utils/validations/validators/status.validator.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"TestModel.js","names":["TestModel","AssociatedTestModel"],"sources":["../../../src/models/tests/TestModel.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n HasMany,\n} from 'sequelize-typescript';\nimport AssociatedTestModel from './AssociatedTestModel';\n\n@Table({\n schema: 'custom-fields', tableName: 'test_models', createdAt: false, updatedAt: false, modelName: 'TestModel',\n})\nclass TestModel extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n defaultValue: DataType.UUIDV4,\n allowNull: false,\n })\n declare id: string;\n\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n declare fleetId: string;\n\n @Column({\n type: DataType.UUID,\n allowNull: true,\n })\n declare businessModelId: string;\n\n @Column({\n type: DataType.UUID,\n allowNull: true,\n })\n declare demandSourceId: string;\n\n @Column({\n type: DataType.BOOLEAN,\n })\n coolAttribute?: boolean;\n\n @HasMany(() => AssociatedTestModel)\n declare associatedModels: AssociatedTestModel[];\n\n @Column({\n type: DataType.VIRTUAL,\n })\n customFields?: any;\n}\n\nexport default TestModel;\n"],"mappings":"mWAUA,IAAA,EAAA,cAGwB,CAAM,MAC3B,EACA,EAAO,CACN,KAAM,EAAS,KACf,aAAc,EAAS,OACvB,UAAW,GACZ,CAAC,sDAGD,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,UAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,kBAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,iBAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,QAChB,CAAC,CAAA,EAAA,cAAA,QAAA,CAAA,CAAA,EAAA,UAAA,gBAAA,IAAA,GAAA,IAGD,MAAcC,EAAoB,CAAA,EAAA,cAAA,MAAA,CAAA,CAAA,EAAA,UAAA,mBAAA,IAAA,GAAA,IAGlC,EAAO,CACN,KAAM,EAAS,QAChB,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,eAAA,IAAA,GAAA,MAxCH,EAAM,CACL,OAAQ,gBAAiB,UAAW,cAAe,UAAW,GAAO,UAAW,GAAO,UAAW,YACnG,CAAC,CAAA,CAAA,EAAA,CA0CF,IAAA,EAAe"}
@@ -1,2 +0,0 @@
1
- const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs`),n=require(`../../../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs`),r=require(`./ContextTestModel.cjs`);let i=require(`sequelize-typescript`);var a;let o=class extends i.Model{};n.__decorate([i.PrimaryKey,(0,i.Column)({type:i.DataType.UUID,defaultValue:i.DataType.UUIDV4,allowNull:!1}),t.__decorateMetadata(`design:type`,String)],o.prototype,`id`,void 0),n.__decorate([(0,i.ForeignKey)(()=>r.default),(0,i.Column)({type:i.DataType.UUID}),t.__decorateMetadata(`design:type`,String)],o.prototype,`contextId`,void 0),n.__decorate([(0,i.Column)({type:i.DataType.BOOLEAN}),t.__decorateMetadata(`design:type`,Boolean)],o.prototype,`coolAttribute`,void 0),n.__decorate([(0,i.Column)({type:i.DataType.VIRTUAL}),t.__decorateMetadata(`design:type`,Object)],o.prototype,`customFields`,void 0),n.__decorate([(0,i.BelongsTo)(()=>r.default),t.__decorateMetadata(`design:type`,typeof(a=r.default!==void 0&&r.default)==`function`?a:Object)],o.prototype,`context`,void 0),o=n.__decorate([(0,i.Table)({createdAt:!1,updatedAt:!1,modelName:`ContextAwareTestModel`})],o);var s=o;exports.default=s;
2
- //# sourceMappingURL=ContextAwareTestModel.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ContextAwareTestModel.cjs","names":["ContextAwareTestModel","Model","PrimaryKey","DataType","ContextTestModel"],"sources":["../../../../src/models/tests/contextAwareModels/ContextAwareTestModel.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n BelongsTo,\n ForeignKey,\n} from 'sequelize-typescript';\nimport ContextTestModel from './ContextTestModel';\n\n@Table({ createdAt: false, updatedAt: false, modelName: 'ContextAwareTestModel' })\nclass ContextAwareTestModel extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n defaultValue: DataType.UUIDV4,\n allowNull: false,\n })\n declare id: string;\n\n @ForeignKey(() => ContextTestModel)\n @Column({ type: DataType.UUID })\n declare contextId: string;\n\n @Column({\n type: DataType.BOOLEAN,\n })\n coolAttribute?: boolean;\n\n @Column({\n type: DataType.VIRTUAL,\n })\n customFields?: any;\n\n @BelongsTo(() => ContextTestModel)\n declare context: ContextTestModel;\n}\n\nexport default ContextAwareTestModel;\n"],"mappings":"sTAWA,IAAA,EAAA,cACoCC,EAAAA,KAAM,iBACvCC,EAAAA,wBACO,CACN,KAAMC,EAAAA,SAAS,KACf,aAAcA,EAAAA,SAAS,OACvB,UAAW,GACZ,CAAC,yGAGgBC,EAAAA,QAAiB,cAC3B,CAAE,KAAMD,EAAAA,SAAS,KAAM,CAAC,wGAGxB,CACN,KAAMA,EAAAA,SAAS,QAChB,CAAC,CAAA,EAAA,mBAAA,cAAA,QAAA,CAAA,CAAA,EAAA,UAAA,gBAAA,IAAA,GAAA,4BAGM,CACN,KAAMA,EAAAA,SAAS,QAChB,CAAC,CAAA,EAAA,mBAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,eAAA,IAAA,GAAA,mCAGeC,EAAAA,QAAiB,CAAA,EAAA,mBAAA,cAAA,OAAA,EAAA,EAAA,UAAA,QAAA,EAAA,UAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,UAAA,IAAA,GAAA,6BAxB7B,CAAE,UAAW,GAAO,UAAW,GAAO,UAAW,wBAAyB,CAAC,CAAA,CAAA,EAAA,CA4BlF,IAAA,EAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ContextAwareTestModel.js","names":["ContextAwareTestModel","ContextTestModel"],"sources":["../../../../src/models/tests/contextAwareModels/ContextAwareTestModel.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n BelongsTo,\n ForeignKey,\n} from 'sequelize-typescript';\nimport ContextTestModel from './ContextTestModel';\n\n@Table({ createdAt: false, updatedAt: false, modelName: 'ContextAwareTestModel' })\nclass ContextAwareTestModel extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n defaultValue: DataType.UUIDV4,\n allowNull: false,\n })\n declare id: string;\n\n @ForeignKey(() => ContextTestModel)\n @Column({ type: DataType.UUID })\n declare contextId: string;\n\n @Column({\n type: DataType.BOOLEAN,\n })\n coolAttribute?: boolean;\n\n @Column({\n type: DataType.VIRTUAL,\n })\n customFields?: any;\n\n @BelongsTo(() => ContextTestModel)\n declare context: ContextTestModel;\n}\n\nexport default ContextAwareTestModel;\n"],"mappings":"8XAWA,IAAA,EAAA,cACoC,CAAM,MACvC,EACA,EAAO,CACN,KAAM,EAAS,KACf,aAAc,EAAS,OACvB,UAAW,GACZ,CAAC,sDAGD,MAAiBC,EAAiB,CAClC,EAAO,CAAE,KAAM,EAAS,KAAM,CAAC,6DAG/B,EAAO,CACN,KAAM,EAAS,QAChB,CAAC,CAAA,EAAA,cAAA,QAAA,CAAA,CAAA,EAAA,UAAA,gBAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,QAChB,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,eAAA,IAAA,GAAA,IAGD,MAAgBA,EAAiB,CAAA,EAAA,cAAA,OAAA,EAAA,IAAA,QAAA,IAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,UAAA,IAAA,GAAA,MAxBnC,EAAM,CAAE,UAAW,GAAO,UAAW,GAAO,UAAW,wBAAyB,CAAC,CAAA,CAAA,EAAA,CA4BlF,IAAA,EAAe"}
@@ -1,2 +0,0 @@
1
- const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs`),n=require(`../../../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs`);let r=require(`sequelize-typescript`);var i=function(e){return e.BUSINESS_MODEL=`businessModel`,e.CONTEXT=`context`,e.DEMAND_SOURCE=`demandSource`,e.FLEET=`fleet`,e}(i||{});let a=class extends r.Model{};n.__decorate([r.PrimaryKey,(0,r.Column)({defaultValue:r.DataType.UUIDV4,type:r.DataType.UUID}),t.__decorateMetadata(`design:type`,String)],a.prototype,`id`,void 0),n.__decorate([(0,r.Column)({type:r.DataType.UUID}),t.__decorateMetadata(`design:type`,String)],a.prototype,`entityId`,void 0),n.__decorate([(0,r.Column)({type:r.DataType.ENUM(...Object.values(i))}),t.__decorateMetadata(`design:type`,String)],a.prototype,`entityType`,void 0),a=n.__decorate([(0,r.Table)({createdAt:!1,updatedAt:!1,modelName:`ContextTestModel`})],a);var o=a;exports.default=o;
2
- //# sourceMappingURL=ContextTestModel.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ContextTestModel.cjs","names":["ContextTestModel","Model","PrimaryKey","DataType"],"sources":["../../../../src/models/tests/contextAwareModels/ContextTestModel.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n} from 'sequelize-typescript';\n\nenum EEntityTypes {\n BUSINESS_MODEL = 'businessModel',\n CONTEXT = 'context',\n DEMAND_SOURCE = 'demandSource',\n FLEET = 'fleet',\n}\n\n@Table({ createdAt: false, updatedAt: false, modelName: 'ContextTestModel' })\nclass ContextTestModel extends Model {\n @PrimaryKey\n @Column({\n defaultValue: DataType.UUIDV4,\n type: DataType.UUID,\n })\n declare id: string;\n\n @Column({\n type: DataType.UUID,\n })\n declare entityId: string;\n\n @Column({\n type: DataType.ENUM(...Object.values(EEntityTypes)),\n })\n declare entityType: EEntityTypes;\n}\n\nexport default ContextTestModel;\n"],"mappings":"4QAQA,IAAK,EAAA,SAAA,EAAL,OACE,GAAA,eAAA,gBACA,EAAA,QAAA,UACA,EAAA,cAAA,eACA,EAAA,MAAA,WAJG,GAAA,EAAA,CAAA,CAOL,IAAA,EAAA,cAC+BC,EAAAA,KAAM,iBAClCC,EAAAA,wBACO,CACN,aAAcC,EAAAA,SAAS,OACvB,KAAMA,EAAAA,SAAS,KAChB,CAAC,iGAGM,CACN,KAAMA,EAAAA,SAAS,KAChB,CAAC,CAAA,EAAA,mBAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,WAAA,IAAA,GAAA,4BAGM,CACN,KAAMA,EAAAA,SAAS,KAAK,GAAG,OAAO,OAAO,EAAa,CAAC,CACpD,CAAC,CAAA,EAAA,mBAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,aAAA,IAAA,GAAA,6BAhBG,CAAE,UAAW,GAAO,UAAW,GAAO,UAAW,mBAAoB,CAAC,CAAA,CAAA,EAAA,CAoB7E,IAAA,EAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ContextTestModel.js","names":["ContextTestModel"],"sources":["../../../../src/models/tests/contextAwareModels/ContextTestModel.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n} from 'sequelize-typescript';\n\nenum EEntityTypes {\n BUSINESS_MODEL = 'businessModel',\n CONTEXT = 'context',\n DEMAND_SOURCE = 'demandSource',\n FLEET = 'fleet',\n}\n\n@Table({ createdAt: false, updatedAt: false, modelName: 'ContextTestModel' })\nclass ContextTestModel extends Model {\n @PrimaryKey\n @Column({\n defaultValue: DataType.UUIDV4,\n type: DataType.UUID,\n })\n declare id: string;\n\n @Column({\n type: DataType.UUID,\n })\n declare entityId: string;\n\n @Column({\n type: DataType.ENUM(...Object.values(EEntityTypes)),\n })\n declare entityType: EEntityTypes;\n}\n\nexport default ContextTestModel;\n"],"mappings":"oTAQA,IAAK,EAAA,SAAA,EAAL,OACE,GAAA,eAAA,gBACA,EAAA,QAAA,UACA,EAAA,cAAA,eACA,EAAA,MAAA,WAJG,GAAA,EAAA,CAAA,CAOL,IAAA,EAAA,cAC+B,CAAM,MAClC,EACA,EAAO,CACN,aAAc,EAAS,OACvB,KAAM,EAAS,KAChB,CAAC,sDAGD,EAAO,CACN,KAAM,EAAS,KAChB,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,WAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,KAAK,GAAG,OAAO,OAAO,EAAa,CAAC,CACpD,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,aAAA,IAAA,GAAA,MAhBH,EAAM,CAAE,UAAW,GAAO,UAAW,GAAO,UAAW,mBAAoB,CAAC,CAAA,CAAA,EAAA,CAoB7E,IAAA,EAAe"}
@@ -1,2 +0,0 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../errors/index.cjs`),n=require(`../models/CustomFieldDefinition.cjs`);require(`../models/index.cjs`);let r=require(`sequelize`);const i=e=>n.default.create(e),a=(e,t={withDisabled:!1})=>(t.withDisabled?n.default.unscoped():n.default).scope(`userScope`).findAll({where:e,transaction:t.transaction,raw:!0,include:t.include}),o=(e,t={withDisabled:!1})=>a({id:{[r.Op.in]:e}},t),s=(e,t={withDisabled:!1})=>{let{withDisabled:r}=t;return r?n.default.unscoped().scope(`userScope`).findByPk(e):n.default.scope(`userScope`).findByPk(e)},c=async(e,t,i={})=>{let{include:a,useEntityIdFromInclude:o}=i.modelOptions,s={modelType:e,...!o&&{entityId:{[r.Op.in]:t}}};return n.default.findAll({where:s,transaction:i.transaction,include:a?.(t),raw:!0})},l=e=>n.default.scope(`userScope`).findOne({where:e}),u=async(e,t)=>(await n.default.scope(`userScope`).update(t,{where:{id:e},returning:!0,individualHooks:!0}))[1][0],d=async(e,{findAll:n,modelOptions:i={},withDisabled:o=!1,...s}={withDisabled:!1,modelOptions:{}})=>{let{modelType:c}=e[0]?.dataValues??{},l=new Set,u=[],d=new Set;e.forEach(e=>{let{dataValues:{modelId:t,entityId:n,customFields:r}}=e;u.push(t),d.add(n),Object.keys(r??{}).forEach(e=>{l.add(e)})});let f={modelType:c,entityId:{[r.Op.in]:Array.from(d)},name:{[r.Op.in]:Array.from(l)}},p=await(n??a)(f,{withDisabled:o,modelOptions:i,...s}),m=p.filter(e=>l.has(e.name)),h=Object.fromEntries(m.map(e=>[e.name,e]));if(!p?.length||m.length!==l.size)throw new t.MissingDefinitionError(Array.from(l).filter(e=>!h[e]));return h};exports.create=i,exports.findAll=a,exports.findByEntityIds=c,exports.findById=s,exports.findByIds=o,exports.findByWhere=l,exports.getCustomFieldDefinitionsDictionary=d,exports.update=u;
2
- //# sourceMappingURL=definition.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"definition.cjs","names":["CustomFieldDefinition","Op","where: WhereOptions","MissingDefinitionError"],"sources":["../../src/repository/definition.ts"],"sourcesContent":["import {\n Op,\n type Includeable, type Transaction, type FindOptions, type WhereOptions, type Transactionable,\n} from 'sequelize';\nimport { CustomFieldDefinition, type CustomFieldEntries } from '../models';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';\nimport type { ModelOptions } from '../types';\nimport { MissingDefinitionError } from '../errors';\n\nexport const create = (data: CreateCustomFieldDefinition): Promise<CustomFieldDefinition> =>\n CustomFieldDefinition.create(data);\n\ninterface SadotFindOptions {\n withDisabled?: boolean;\n transaction?: Transaction | null;\n include?: Includeable | Includeable[];\n}\n\ntype SadotGetDefinitionsByEntityIdsOptions = FindOptions & { modelOptions?: ModelOptions; findAll?: typeof findAll; } & Pick<SadotFindOptions, 'withDisabled'>;\n\nexport const findAll = (\n where: WhereOptions,\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => {\n const queryModel = options.withDisabled\n ? CustomFieldDefinition.unscoped()\n : CustomFieldDefinition;\n\n return queryModel.scope('userScope').findAll({\n where,\n transaction: options.transaction,\n raw: true,\n include: options.include,\n });\n};\n\nexport const findByIds = (\n ids: string[],\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => findAll({ id: { [Op.in]: ids } }, options);\n\nexport const findById = (\n id: string,\n options: Pick<SadotFindOptions, 'withDisabled'> = { withDisabled: false },\n): Promise<CustomFieldDefinition | null> => {\n const { withDisabled } = options;\n if (withDisabled) {\n return CustomFieldDefinition.unscoped().scope('userScope').findByPk(id);\n }\n return CustomFieldDefinition.scope('userScope').findByPk(id);\n};\n\nexport const findByEntityIds = async (\n modelType: string,\n entityIds: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldDefinition[]> => {\n const { include, useEntityIdFromInclude } = options.modelOptions!;\n const where: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n return CustomFieldDefinition.findAll({\n where,\n transaction: options.transaction,\n include: include?.(entityIds),\n raw: true,\n });\n};\n\nexport const findByWhere = (where: WhereOptions<CustomFieldDefinition>): Promise<CustomFieldDefinition | null> =>\n CustomFieldDefinition.scope('userScope').findOne({\n where,\n });\n\nexport const findDefinitionsByModels = async (\n modelTypes: string[],\n options?: Transactionable,\n): Promise<CustomFieldDefinition[]> => {\n const query: WhereOptions<CreateCustomFieldDefinition> = { modelType: { [Op.in]: modelTypes } };\n return CustomFieldDefinition.findAll({\n where: query,\n transaction: options?.transaction,\n });\n};\n\nexport const update = async (\n id: string,\n data: UpdateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const updatedDefinition = (await CustomFieldDefinition.scope('userScope').update(data, {\n where: { id },\n returning: true,\n individualHooks: true,\n }))[1][0];\n return updatedDefinition;\n};\n\nexport const disable = (id: string): Promise<[affectedCount: number]> =>\n CustomFieldDefinition.update(\n { disabled: true },\n { where: { id } },\n );\n\nexport const destroy = (id: string): Promise<number> =>\n CustomFieldDefinition.destroy({ where: { id } });\n\n/**\n * Return the names of the required fields for a given model\n */\nexport const getRequiredFields = async (\n modelType: string,\n modelId: string | string[],\n entityId: string | string[],\n modelOptions: ModelOptions = {},\n): Promise<string[]> => {\n const entityIds = Array.isArray(entityId) ? entityId : [entityId];\n const { include, useEntityIdFromInclude } = modelOptions;\n\n const where: WhereOptions = {\n modelType,\n required: true,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n const requiredFields = await CustomFieldDefinition.findAll({\n where,\n include: include?.(entityIds),\n logging: true,\n });\n const requiredFieldsNames = requiredFields.map(definition => definition.name);\n return [...new Set(requiredFieldsNames)];\n};\n\n/**\n * @returns A promise resolving with a dictionary of custom field definitions by name.\n * @throws A {@link MissingDefinitionError} if any of the custom fields doesn't have a definition.\n */\nexport const getCustomFieldDefinitionsDictionary = async (\n instances: CustomFieldEntries[],\n {\n findAll: _findAll,\n modelOptions = {},\n withDisabled = false,\n ...options\n }: SadotGetDefinitionsByEntityIdsOptions = { withDisabled: false, modelOptions: {} },\n): Promise<Record<string, CustomFieldDefinition>> => {\n const { modelType } = instances[0]?.dataValues ?? {};\n const customFields = new Set<string>();\n const modelIds = [];\n const entityIds = new Set<string>();\n instances.forEach((instance) => {\n const { dataValues: { modelId, entityId, customFields: instanceCustomFields } } = instance;\n modelIds.push(modelId);\n entityIds.add(entityId);\n\n Object.keys(instanceCustomFields ?? {}).forEach((fieldName) => {\n customFields.add(fieldName);\n });\n });\n\n const where: WhereOptions = {\n modelType,\n entityId: { [Op.in]: Array.from(entityIds) },\n name: { [Op.in]: Array.from(customFields) },\n };\n\n const findAllToUse = _findAll ?? findAll;\n\n // @ts-expect-error findAll doesn't expect modelOptions at all.\n const definitions = await findAllToUse(where, { withDisabled, modelOptions, ...options });\n\n const matchedDefinitions = definitions.filter(def => customFields.has(def.name));\n const matchedDefinitionsByName = Object.fromEntries(matchedDefinitions.map(definition => [definition.name, definition]));\n\n if (!definitions?.length || matchedDefinitions.length !== customFields.size) {\n const unmatchedCustomFields = Array.from(customFields).filter(customField => !matchedDefinitionsByName[customField]);\n throw new MissingDefinitionError(unmatchedCustomFields);\n }\n\n return matchedDefinitionsByName;\n};\n"],"mappings":"gMASA,MAAa,EAAU,GACrBA,EAAAA,QAAsB,OAAO,EAAK,CAUvB,GACX,EACA,EAA4B,CAAE,aAAc,GAAO,IAEhC,EAAQ,aACvBA,EAAAA,QAAsB,UAAU,CAChCA,EAAAA,SAEc,MAAM,YAAY,CAAC,QAAQ,CAC3C,QACA,YAAa,EAAQ,Y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EAAU,IAAI,EAAS,CAEvB,OAAO,KAAK,GAAwB,EAAE,CAAC,CAAC,QAAS,GAAc,CAC7D,EAAa,IAAI,EAAU,EAC3B,EACF,CAEF,IAAME,EAAsB,CAC1B,YACA,SAAU,EAAGD,EAAAA,GAAG,IAAK,MAAM,KAAK,EAAU,CAAE,CAC5C,KAAM,EAAGA,EAAAA,GAAG,IAAK,MAAM,KAAK,EAAa,CAAE,CAC5C,CAKK,EAAc,MAHC,GAAY,GAGM,EAAO,CAAE,eAAc,eAAc,GAAG,EAAS,CAAC,CAEnF,EAAqB,EAAY,OAAO,GAAO,EAAa,IAAI,EAAI,KAAK,CAAC,CAC1E,EAA2B,OAAO,YAAY,EAAmB,IAAI,GAAc,CAAC,EAAW,KAAM,EAAW,CAAC,CAAC,CAExH,GAAI,CAAC,GAAa,QAAU,EAAmB,SAAW,EAAa,KAErE,MAAM,IAAIE,EAAAA,uBADoB,MAAM,KAAK,EAAa,CAAC,OAAO,GAAe,CAAC,EAAyB,GAAa,CAC7D,CAGzD,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"definition.js","names":["CustomFieldDefinition","where: WhereOptions"],"sources":["../../src/repository/definition.ts"],"sourcesContent":["import {\n Op,\n type Includeable, type Transaction, type FindOptions, type WhereOptions, type Transactionable,\n} from 'sequelize';\nimport { CustomFieldDefinition, type CustomFieldEntries } from '../models';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';\nimport type { ModelOptions } from '../types';\nimport { MissingDefinitionError } from '../errors';\n\nexport const create = (data: CreateCustomFieldDefinition): Promise<CustomFieldDefinition> =>\n CustomFieldDefinition.create(data);\n\ninterface SadotFindOptions {\n withDisabled?: boolean;\n transaction?: Transaction | null;\n include?: Includeable | Includeable[];\n}\n\ntype SadotGetDefinitionsByEntityIdsOptions = FindOptions & { modelOptions?: ModelOptions; findAll?: typeof findAll; } & Pick<SadotFindOptions, 'withDisabled'>;\n\nexport const findAll = (\n where: WhereOptions,\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => {\n const queryModel = options.withDisabled\n ? CustomFieldDefinition.unscoped()\n : CustomFieldDefinition;\n\n return queryModel.scope('userScope').findAll({\n where,\n transaction: options.transaction,\n raw: true,\n include: options.include,\n });\n};\n\nexport const findByIds = (\n ids: string[],\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => findAll({ id: { [Op.in]: ids } }, options);\n\nexport const findById = (\n id: string,\n options: Pick<SadotFindOptions, 'withDisabled'> = { withDisabled: false },\n): Promise<CustomFieldDefinition | null> => {\n const { withDisabled } = options;\n if (withDisabled) {\n return CustomFieldDefinition.unscoped().scope('userScope').findByPk(id);\n }\n return CustomFieldDefinition.scope('userScope').findByPk(id);\n};\n\nexport const findByEntityIds = async (\n modelType: string,\n entityIds: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldDefinition[]> => {\n const { include, useEntityIdFromInclude } = options.modelOptions!;\n const where: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n return CustomFieldDefinition.findAll({\n where,\n transaction: options.transaction,\n include: include?.(entityIds),\n raw: true,\n });\n};\n\nexport const findByWhere = (where: WhereOptions<CustomFieldDefinition>): Promise<CustomFieldDefinition | null> =>\n CustomFieldDefinition.scope('userScope').findOne({\n where,\n });\n\nexport const findDefinitionsByModels = async (\n modelTypes: string[],\n options?: Transactionable,\n): Promise<CustomFieldDefinition[]> => {\n const query: WhereOptions<CreateCustomFieldDefinition> = { modelType: { [Op.in]: modelTypes } };\n return CustomFieldDefinition.findAll({\n where: query,\n transaction: options?.transaction,\n });\n};\n\nexport const update = async (\n id: string,\n data: UpdateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const updatedDefinition = (await CustomFieldDefinition.scope('userScope').update(data, {\n where: { id },\n returning: true,\n individualHooks: true,\n }))[1][0];\n return updatedDefinition;\n};\n\nexport const disable = (id: string): Promise<[affectedCount: number]> =>\n CustomFieldDefinition.update(\n { disabled: true },\n { where: { id } },\n );\n\nexport const destroy = (id: string): Promise<number> =>\n CustomFieldDefinition.destroy({ where: { id } });\n\n/**\n * Return the names of the required fields for a given model\n */\nexport const getRequiredFields = async (\n modelType: string,\n modelId: string | string[],\n entityId: string | string[],\n modelOptions: ModelOptions = {},\n): Promise<string[]> => {\n const entityIds = Array.isArray(entityId) ? entityId : [entityId];\n const { include, useEntityIdFromInclude } = modelOptions;\n\n const where: WhereOptions = {\n modelType,\n required: true,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n const requiredFields = await CustomFieldDefinition.findAll({\n where,\n include: include?.(entityIds),\n logging: true,\n });\n const requiredFieldsNames = requiredFields.map(definition => definition.name);\n return [...new Set(requiredFieldsNames)];\n};\n\n/**\n * @returns A promise resolving with a dictionary of custom field definitions by name.\n * @throws A {@link MissingDefinitionError} if any of the custom fields doesn't have a definition.\n */\nexport const getCustomFieldDefinitionsDictionary = async (\n instances: CustomFieldEntries[],\n {\n findAll: _findAll,\n modelOptions = {},\n withDisabled = false,\n ...options\n }: SadotGetDefinitionsByEntityIdsOptions = { withDisabled: false, modelOptions: {} },\n): Promise<Record<string, CustomFieldDefinition>> => {\n const { modelType } = instances[0]?.dataValues ?? {};\n const customFields = new Set<string>();\n const modelIds = [];\n const entityIds = new Set<string>();\n instances.forEach((instance) => {\n const { dataValues: { modelId, entityId, customFields: instanceCustomFields } } = instance;\n modelIds.push(modelId);\n entityIds.add(entityId);\n\n Object.keys(instanceCustomFields ?? {}).forEach((fieldName) => {\n customFields.add(fieldName);\n });\n });\n\n const where: WhereOptions = {\n modelType,\n entityId: { [Op.in]: Array.from(entityIds) },\n name: { [Op.in]: Array.from(customFields) },\n };\n\n const findAllToUse = _findAll ?? findAll;\n\n // @ts-expect-error findAll doesn't expect modelOptions at all.\n const definitions = await findAllToUse(where, { withDisabled, modelOptions, ...options });\n\n const matchedDefinitions = definitions.filter(def => customFields.has(def.name));\n const matchedDefinitionsByName = Object.fromEntries(matchedDefinitions.map(definition => [definition.name, definition]));\n\n if (!definitions?.length || matchedDefinitions.length !== customFields.size) {\n const unmatchedCustomFields = Array.from(customFields).filter(customField => !matchedDefinitionsByName[customField]);\n throw new MissingDefinitionError(unmatchedCustomFields);\n }\n\n return matchedDefinitionsByName;\n};\n"],"mappings":"wKASA,MAAa,EAAU,GACrBA,EAAsB,OAAO,EAAK,CAUvB,GACX,EACA,EAA4B,CAAE,aAAc,GAAO,IAEhC,EAAQ,aACvBA,EAAsB,UAAU,CAChCA,GAEc,MAAM,YAAY,CAAC,QAAQ,CAC3C,QACA,YAAa,EAAQ,YACrB,IAAK,GACL,QAAS,EAAQ,QAClB,CAAC,CAGS,GACX,EACA,EAA4B,CAAE,aAAc,GAAO,GACd,EAAQ,CAAE,GAAI,EAAG,EAAG,IAAK,EAAK,CAAE,CAAE,EAAQ,CAEpE,GACX,EACA,EAAkD,CAAE,aAAc,GAAO,GAC/B,CAC1C,GAAM,CAAE,gBAAiB,EAIzB,OAHI,EACKA,EAAsB,UAAU,CAAC,MAAM,YAAY,CAAC,SAAS,EAAG,CAElEA,EAAsB,MAAM,YAAY,CAAC,SAAS,EAAG,EAGjD,EAAkB,MAC7B,EACA,EACA,EAA0D,EAAE,GACvB,CACrC,GAAM,CAAE,UAAS,0BAA2B,EAAQ,aAC9CC,EAAsB,CAC1B,YACA,GAAI,CAAC,GAA0B,CAAE,SAAU,EAAG,EAAG,IAAK,EAAW,CAAE,CACpE,CAED,OAAOD,EAAsB,QAAQ,CACnC,QACA,YAAa,EAAQ,YACrB,QAAS,IAAU,EAAU,CAC7B,IAAK,GACN,CAAC,EAGS,EAAe,GAC1BA,EAAsB,MAAM,YAAY,CAAC,QAAQ,CAC/C,QACD,CAAC,CAaS,EAAS,MACpB,EACA,KAE2B,MAAMA,EAAsB,MAAM,YAAY,CAAC,OAAO,EAAM,CACrF,MAAO,CAAE,KAAI,CACb,UAAW,GACX,gBAAiB,GAClB,CAAC,EAAE,GAAG,GA4CI,EAAsC,MACjD,EACA,CACE,QAAS,EACT,eAAe,EAAE,CACjB,eAAe,GACf,GAAG,GACsC,CAAE,aAAc,GAAO,aAAc,EAAE,CAAE,GACjC,CACnD,GAAM,CAAE,aAAc,EAAU,IAAI,YAAc,EAAE,CAC9C,EAAe,IAAI,IACnB,EAAW,EAAE,CACb,EAAY,IAAI,IACtB,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,WAAY,CAAE,UAAS,WAAU,aAAc,IAA2B,EAClF,EAAS,KAAK,EAAQ,CACtB,EAAU,IAAI,EAAS,CAEvB,OAAO,KAAK,GAAwB,EAAE,CAAC,CAAC,QAAS,GAAc,CAC7D,EAAa,IAAI,EAAU,EAC3B,EACF,CAEF,IAAMC,EAAsB,CAC1B,YACA,SAAU,EAAG,EAAG,IAAK,MAAM,KAAK,EAAU,CAAE,CAC5C,KAAM,EAAG,EAAG,IAAK,MAAM,KAAK,EAAa,CAAE,CAC5C,CAKK,EAAc,MAHC,GAAY,GAGM,EAAO,CAAE,eAAc,eAAc,GAAG,EAAS,CAAC,CAEnF,EAAqB,EAAY,OAAO,GAAO,EAAa,IAAI,EAAI,KAAK,CAAC,CAC1E,EAA2B,OAAO,YAAY,EAAmB,IAAI,GAAc,CAAC,EAAW,KAAM,EAAW,CAAC,CAAC,CAExH,GAAI,CAAC,GAAa,QAAU,EAAmB,SAAW,EAAa,KAErE,MAAM,IAAI,EADoB,MAAM,KAAK,EAAa,CAAC,OAAO,GAAe,CAAC,EAAyB,GAAa,CAC7D,CAGzD,OAAO"}
@@ -1,2 +0,0 @@
1
- const e=require(`../utils/logger/index.cjs`),t=require(`../errors/index.cjs`),n=require(`./definition.cjs`),r=require(`../models/CustomFieldEntries.cjs`);require(`../models/index.cjs`);const i=require(`./utils/formatValues.cjs`),a=async(e,t={})=>{let{transaction:n}=t;return r.default.findOne({where:{modelId:e},transaction:n})},o=async(e,t={})=>{let{transaction:n}=t;return r.default.findAll({where:{modelId:e},transaction:n})},s=async(a,o,s,c,l={})=>{let u=Object.keys(s);e.default.debug(`custom-fields: updating entries for ${o} ${a}`,{customFieldsNames:u,optionsKeys:l?Object.keys(l):null,customFields:s,identifiers:c});let{modelOptions:d,transaction:f}=l,p={modelType:o,name:u,...!l.modelOptions?.useEntityIdFromInclude&&{entityId:c}},m=await n.findAll(p,{withDisabled:!0,transaction:f,include:d.include?.(c)})??[],h=m.filter(e=>e.disabled);if(m.length!==u.length)throw e.default.warn(`custom-fields: missing definitions for ${o} ${a}`,{names:u,fieldDefinitions:m}),new t.MissingDefinitionError(u.filter(e=>!m.some(t=>t.name===e)));let g=h?.map(e=>e.name)||[],_=u.filter(e=>g.includes(e));_?.length>0&&e.default.warn(`custom-fields: trying to update disabled values: ${_.join(`, `)}`);let v=Object.fromEntries(m.map(e=>[e.name,e]));return Object.entries(s).filter(([e])=>i.formatFunctions[v[e].fieldType]).forEach(([e,t])=>{let{fieldType:n}=v[e];s[e]=i.formatFunctions[n](t)}),r.default.upsert({modelId:a,entityId:m[0].entityId,modelType:o,customFields:s},l)};exports.findEntriesByModelId=a,exports.findEntriesByModelIds=o,exports.updateEntries=s;
2
- //# sourceMappingURL=entries.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"entries.cjs","names":["CustomFieldEntries","where: WhereOptions","MissingDefinitionError","formatFunctions"],"sources":["../../src/repository/entries.ts"],"sourcesContent":["import type {\n FindOptions,\n Includeable,\n Transaction,\n WhereOptions,\n} from 'sequelize';\nimport { CustomFieldEntries } from '../models';\nimport type { ModelOptions } from '../types';\nimport logger from '../utils/logger';\nimport { MissingDefinitionError } from '../errors';\nimport * as DefinitionRepo from './definition';\nimport { formatFunctions } from './utils/formatValues';\n\ntype CustomFieldEntriesModelOptions = ModelOptions & { include?: Includeable; transaction?: Transaction | null; };\n\nexport const findEntriesByModelId = async (modelId: string, options: CustomFieldEntriesModelOptions = {}): Promise<CustomFieldEntries | null> => {\n const { transaction } = options;\n return CustomFieldEntries.findOne({\n where: { modelId },\n transaction,\n });\n};\n\nexport const findEntriesByModelIds = async (modelIds: string[], options: CustomFieldEntriesModelOptions = {}): Promise<CustomFieldEntries[]> => {\n const { transaction } = options;\n return CustomFieldEntries.findAll({\n where: { modelId: modelIds },\n transaction,\n });\n};\n\nexport const updateEntries = async (\n modelId: string,\n modelType: string,\n customFields: Record<string, any>,\n identifiers: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<[CustomFieldEntries, boolean | null]> => {\n const customFieldsNames = Object.keys(customFields);\n logger.debug(`custom-fields: updating entries for ${modelType} ${modelId}`, {\n customFieldsNames,\n optionsKeys: options ? Object.keys(options) : null,\n customFields,\n identifiers,\n });\n const { modelOptions, transaction } = options;\n\n const where: WhereOptions = {\n modelType,\n name: customFieldsNames,\n ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions!.include?.(identifiers) }) ?? [];\n\n const disabledDefinitions = fieldDefinitions.filter(def => def.disabled);\n if (fieldDefinitions.length !== customFieldsNames.length) {\n logger.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names: customFieldsNames, fieldDefinitions });\n const missingDefinitions = customFieldsNames.filter(name => !fieldDefinitions.some(def => def.name === name));\n throw new MissingDefinitionError(missingDefinitions);\n }\n\n const disabledNames = disabledDefinitions?.map(def => def.name) || [];\n const valuesWithDisabledDefinitions = customFieldsNames.filter(name => disabledNames.includes(name));\n if (valuesWithDisabledDefinitions?.length > 0) {\n logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);\n }\n\n const definitionsByName = Object.fromEntries(fieldDefinitions.map(definition => [definition.name, definition]));\n // If we need to format the value before we save it\n Object.entries(customFields)\n .filter(([definitionName]) => formatFunctions[definitionsByName[definitionName].fieldType])\n .forEach(([definitionName, value]) => {\n const { fieldType } = definitionsByName[definitionName];\n customFields[definitionName] = formatFunctions[fieldType]!(value);\n });\n\n return CustomFieldEntries.upsert(\n {\n modelId,\n entityId: fieldDefinitions[0].entityId,\n modelType,\n customFields,\n },\n options,\n );\n};\n"],"mappings":"qOAea,EAAuB,MAAO,EAAiB,EAA0C,EAAE,GAAyC,CAC/I,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAAA,QAAmB,QAAQ,CAChC,MAAO,CAAE,UAAS,CAClB,cACD,CAAC,EAGS,EAAwB,MAAO,EAAoB,EAA0C,EAAE,GAAoC,CAC9I,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAAA,QAAmB,QAAQ,CAChC,MAAO,CAAE,QAAS,EAAU,CAC5B,cACD,CAAC,EAGS,EAAgB,MAC3B,EACA,EACA,EACA,EACA,EAA0D,EAAE,GACV,CAClD,IAAM,EAAoB,OAAO,KAAK,EAAa,CACnD,EAAA,QAAO,MAAM,uCAAuC,EAAU,GAAG,IAAW,CAC1E,oBACA,YAAa,EAAU,OAAO,KAAK,EAAQ,CAAG,KAC9C,eACA,cACD,CAAC,CACF,GAAM,CAAE,eAAc,eAAgB,EAEhCC,EAAsB,CAC1B,YACA,KAAM,EACN,GAAI,CAAC,EAAQ,cAAc,wBAA0B,CAAE,SAAU,EAAa,CAC/E,CAEK,EAAmB,MAAA,EAAA,QAA6B,EAAO,CAAE,aAAc,GAAM,cAAa,QAAS,EAAc,UAAU,EAAY,CAAE,CAAC,EAAI,EAAE,CAEhJ,EAAsB,EAAiB,OAAO,GAAO,EAAI,SAAS,CACxE,GAAI,EAAiB,SAAW,EAAkB,OAGhD,MAFA,EAAA,QAAO,KAAK,0CAA0C,EAAU,GAAG,IAAW,CAAE,MAAO,EAAmB,mBAAkB,CAAC,CAEvH,IAAIC,EAAAA,uBADiB,EAAkB,OAAO,GAAQ,CAAC,EAAiB,KAAK,GAAO,EAAI,OAAS,EAAK,CAAC,CACzD,CAGtD,IAAM,EAAgB,GAAqB,IAAI,GAAO,EAAI,KAAK,EAAI,EAAE,CAC/D,EAAgC,EAAkB,OAAO,GAAQ,EAAc,SAAS,EAAK,CAAC,CAChG,GAA+B,OAAS,GAC1C,EAAA,QAAO,KAAK,oDAAoD,EAA8B,KAAK,KAAK,GAAG,CAG7G,IAAM,EAAoB,OAAO,YAAY,EAAiB,IAAI,GAAc,CAAC,EAAW,KAAM,EAAW,CAAC,CAAC,CAS/G,OAPA,OAAO,QAAQ,EAAa,CACzB,QAAQ,CAAC,KAAoBC,EAAAA,gBAAgB,EAAkB,GAAgB,WAAW,CAC1F,SAAS,CAAC,EAAgB,KAAW,CACpC,GAAM,CAAE,aAAc,EAAkB,GACxC,EAAa,GAAkBA,EAAAA,gBAAgB,GAAY,EAAM,EACjE,CAEGH,EAAAA,QAAmB,OACxB,CACE,UACA,SAAU,EAAiB,GAAG,SAC9B,YACA,eACD,CACD,EACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"entries.js","names":["CustomFieldEntries","where: WhereOptions","DefinitionRepo.findAll"],"sources":["../../src/repository/entries.ts"],"sourcesContent":["import type {\n FindOptions,\n Includeable,\n Transaction,\n WhereOptions,\n} from 'sequelize';\nimport { CustomFieldEntries } from '../models';\nimport type { ModelOptions } from '../types';\nimport logger from '../utils/logger';\nimport { MissingDefinitionError } from '../errors';\nimport * as DefinitionRepo from './definition';\nimport { formatFunctions } from './utils/formatValues';\n\ntype CustomFieldEntriesModelOptions = ModelOptions & { include?: Includeable; transaction?: Transaction | null; };\n\nexport const findEntriesByModelId = async (modelId: string, options: CustomFieldEntriesModelOptions = {}): Promise<CustomFieldEntries | null> => {\n const { transaction } = options;\n return CustomFieldEntries.findOne({\n where: { modelId },\n transaction,\n });\n};\n\nexport const findEntriesByModelIds = async (modelIds: string[], options: CustomFieldEntriesModelOptions = {}): Promise<CustomFieldEntries[]> => {\n const { transaction } = options;\n return CustomFieldEntries.findAll({\n where: { modelId: modelIds },\n transaction,\n });\n};\n\nexport const updateEntries = async (\n modelId: string,\n modelType: string,\n customFields: Record<string, any>,\n identifiers: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<[CustomFieldEntries, boolean | null]> => {\n const customFieldsNames = Object.keys(customFields);\n logger.debug(`custom-fields: updating entries for ${modelType} ${modelId}`, {\n customFieldsNames,\n optionsKeys: options ? Object.keys(options) : null,\n customFields,\n identifiers,\n });\n const { modelOptions, transaction } = options;\n\n const where: WhereOptions = {\n modelType,\n name: customFieldsNames,\n ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions!.include?.(identifiers) }) ?? [];\n\n const disabledDefinitions = fieldDefinitions.filter(def => def.disabled);\n if (fieldDefinitions.length !== customFieldsNames.length) {\n logger.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names: customFieldsNames, fieldDefinitions });\n const missingDefinitions = customFieldsNames.filter(name => !fieldDefinitions.some(def => def.name === name));\n throw new MissingDefinitionError(missingDefinitions);\n }\n\n const disabledNames = disabledDefinitions?.map(def => def.name) || [];\n const valuesWithDisabledDefinitions = customFieldsNames.filter(name => disabledNames.includes(name));\n if (valuesWithDisabledDefinitions?.length > 0) {\n logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);\n }\n\n const definitionsByName = Object.fromEntries(fieldDefinitions.map(definition => [definition.name, definition]));\n // If we need to format the value before we save it\n Object.entries(customFields)\n .filter(([definitionName]) => formatFunctions[definitionsByName[definitionName].fieldType])\n .forEach(([definitionName, value]) => {\n const { fieldType } = definitionsByName[definitionName];\n customFields[definitionName] = formatFunctions[fieldType]!(value);\n });\n\n return CustomFieldEntries.upsert(\n {\n modelId,\n entityId: fieldDefinitions[0].entityId,\n modelType,\n customFields,\n },\n options,\n );\n};\n"],"mappings":"kRAeA,MAAa,EAAuB,MAAO,EAAiB,EAA0C,EAAE,GAAyC,CAC/I,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAm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AAgB,EAAkB,GAAgB,WAAW,CAC1F,SAAS,CAAC,EAAgB,KAAW,CACpC,GAAM,CAAE,aAAc,EAAkB,GACxC,EAAa,GAAkB,EAAgB,GAAY,EAAM,EACjE,CAEGF,EAAmB,OACxB,CACE,UACA,SAAU,EAAiB,GAAG,SAC9B,YACA,eACD,CACD,EACD"}
@@ -1,2 +0,0 @@
1
- const e=require(`../../utils/constants/index.cjs`),t={[e.CustomFieldDefinitionType.DATE]:e=>{if(e){let t=new Date(e);if(t.toString()===`Invalid Date`)throw Error(`Invalid date value: ${e}`);return t.toISOString()}return null}};exports.formatFunctions=t;
2
- //# sourceMappingURL=formatValues.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"formatValues.cjs","names":["formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>>","CustomFieldDefinitionType"],"sources":["../../../src/repository/utils/formatValues.ts"],"sourcesContent":["import { CustomFieldDefinitionType } from '../../utils/constants';\n\nexport const formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>> = {\n [CustomFieldDefinitionType.DATE]: (value) => {\n if (value) {\n const date = new Date(value);\n if (date.toString() === 'Invalid Date') {\n throw new Error(`Invalid date value: ${value}`);\n }\n return date.toISOString();\n }\n return null;\n },\n};\n"],"mappings":"mDAEaA,EAA6F,EACvGC,EAAAA,0BAA0B,MAAQ,GAAU,CAC3C,GAAI,EAAO,CACT,IAAM,EAAO,IAAI,KAAK,EAAM,CAC5B,GAAI,EAAK,UAAU,GAAK,eACtB,MAAU,MAAM,uBAAuB,IAAQ,CAEjD,OAAO,EAAK,aAAa,CAE3B,OAAO,MAEV"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"formatValues.js","names":["formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>>"],"sources":["../../../src/repository/utils/formatValues.ts"],"sourcesContent":["import { CustomFieldDefinitionType } from '../../utils/constants';\n\nexport const formatFunctions: Partial<Record<CustomFieldDefinitionType, (value: any) => string | null>> = {\n [CustomFieldDefinitionType.DATE]: (value) => {\n if (value) {\n const date = new Date(value);\n if (date.toString() === 'Invalid Date') {\n throw new Error(`Invalid date value: ${value}`);\n }\n return date.toISOString();\n }\n return null;\n },\n};\n"],"mappings":"2EAEA,MAAaA,EAA6F,EACvG,EAA0B,MAAQ,GAAU,CAC3C,GAAI,EAAO,CACT,IAAM,EAAO,IAAI,KAAK,EAAM,CAC5B,GAAI,EAAK,UAAU,GAAK,eACtB,MAAU,MAAM,uBAAuB,IAAQ,CAEjD,OAAO,EAAK,aAAa,CAE3B,OAAO,MAEV"}
@@ -1,2 +0,0 @@
1
- const e=require(`../utils/logger/index.cjs`),t=require(`../models/CustomValidator.cjs`);require(`../models/index.cjs`);const n=async(n,r={})=>(e.default.debug(`custom-validator - create validator`),await t.default.create(n,r)),r=async(n={},r={})=>{e.default.debug(`custom-validator - find all validators`);let{transaction:i,withDisabled:a,include:o,attributes:s,raw:c}=r,l;return l=a?await t.default.unscoped().scope(`userScope`).findAll({where:n,transaction:i,include:o,attributes:s,raw:c}):await t.default.scope([`defaultScope`,`userScope`]).findAll({where:n,transaction:i,include:o,attributes:s,raw:c}),l},i=async(t,n,i={})=>(e.default.debug(`custom-validator - find all validators by model type`),r({modelType:t,...!i?.modelOptions?.useEntityIdFromInclude&&{entityId:n}},{...i,include:i?.modelOptions?.include?.(n)})),a=async(n,r,i)=>(e.default.debug(`custom-validator - update validator`),t.default.update(r,{where:{id:n},returning:!0,...i})),o=async(t,n)=>(e.default.debug(`custom-validator - disable validator`),a(t,{disabled:!0},n));exports.create=n,exports.disable=o,exports.findAll=r,exports.findAllByModelType=i,exports.update=a;
2
- //# sourceMappingURL=validator.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"validator.cjs","names":["CustomValidator"],"sources":["../../src/repository/validator.ts"],"sourcesContent":["import type { FindOptions, IncludeOptions, Transactionable } from 'sequelize';\nimport logger from '../utils/logger';\nimport { CustomValidator } from '../models';\nimport type { ModelOptions } from '../types';\n\nexport interface FindValidatorOptions extends Transactionable {\n withDisabled?: boolean;\n attributes?: string[];\n raw?: boolean;\n include?: IncludeOptions[];\n}\n\n// Make sure this interface is compatible with the Sequelize model\nexport interface ValidatorAttributes {\n entityId: string;\n entityType: string;\n modelType: string;\n schema: CustomValidator['schema'];\n disabled?: boolean;\n [key: string]: unknown; // Add index signature for Sequelize compatibility\n}\n\nexport const create = async (\n validatorAttributes: ValidatorAttributes,\n options: Transactionable = {},\n): Promise<CustomValidator> => {\n logger.debug('custom-validator - create validator');\n\n // Use unknown type to bypass TypeScript errors while maintaining compatibility\n const validator = await CustomValidator.create(validatorAttributes as Record<string, unknown>, options);\n\n return validator;\n};\n\nexport const findAll = async (\n where = {},\n options: FindOptions & {\n modelOptions?: ModelOptions;\n withDisabled?: boolean;\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators');\n\n const {\n transaction, withDisabled, include, attributes, raw,\n } = options;\n\n let validators;\n if (withDisabled) {\n // If withDisabled is true, use unscoped to ignore the default scope that filters disabled items\n // Apply the userScope separately to maintain permission filtering\n validators = await CustomValidator.unscoped().scope('userScope').findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n } else {\n // Use defaultScope and userScope to filter both disabled and by permissions\n // The defaultScope keeps only non-disabled validators\n validators = await CustomValidator.scope(['defaultScope', 'userScope']).findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n }\n\n return validators;\n};\n\nexport const findAllByModelType = async (\n modelType: string,\n entityId: string,\n options: FindOptions & {\n modelOptions?: ModelOptions;\n withDisabled?: boolean;\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators by model type');\n return findAll(\n {\n modelType,\n ...(!options?.modelOptions?.useEntityIdFromInclude && { entityId }),\n },\n {\n ...options,\n include: options?.modelOptions?.include?.(entityId),\n },\n );\n};\n\nexport const update = async (\n id: string,\n updates: Partial<ValidatorAttributes>,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - update validator');\n\n return CustomValidator.update(\n updates,\n {\n where: { id },\n returning: true,\n ...options,\n },\n );\n};\n\nexport const disable = async (\n id: string,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - disable validator');\n\n return update(id, { disabled: true }, options);\n};\n"],"mappings":"uHAsBA,MAAa,EAAS,MACpB,EACA,EAA2B,EAAE,IAE7B,EAAA,QAAO,MAAM,sCAAsC,CAGjC,MAAMA,EAAAA,QAAgB,OAAO,EAAgD,EAAQ,EAK5F,EAAU,MACrB,EAAQ,EAAE,CACV,EAGI,EAAE,GACyB,CAC/B,EAAA,QAAO,MAAM,yCAAyC,CAEtD,GAAM,CACJ,cAAa,eAAc,UAAS,aAAY,OAC9C,EAEA,EAuBJ,MAtBA,CAaE,EAbE,EAGW,MAAMA,EAAAA,QAAgB,UAAU,CAAC,MAAM,YAAY,CAAC,QAAQ,CACvE,QACA,cACA,UACA,aACA,MACD,CAAC,CAIW,MAAMA,EAAAA,QAAgB,MAAM,CAAC,eAAgB,YAAY,CAAC,CAAC,QAAQ,CAC9E,QACA,cACA,UACA,aACA,MACD,CAAC,CAGG,GAGI,EAAqB,MAChC,EACA,EACA,EAGI,EAAE,IAEN,EAAA,QAAO,MAAM,uDAAuD,CAC7D,EACL,CACE,YACA,GAAI,CAAC,GAAS,cAAc,wBAA0B,CAAE,WAAU,CACnE,CACD,CACE,GAAG,EACH,QAAS,GAAS,cAAc,UAAU,EAAS,CACpD,CACF,EAGU,EAAS,MACpB,EACA,EACA,KAEA,EAAA,QAAO,MAAM,sCAAsC,CAE5CA,EAAAA,QAAgB,OACrB,EACA,CACE,MAAO,CAAE,KAAI,CACb,UAAW,GACX,GAAG,EACJ,CACF,EAGU,EAAU,MACrB,EACA,KAEA,EAAA,QAAO,MAAM,uCAAuC,CAE7C,EAAO,EAAI,CAAE,SAAU,GAAM,CAAE,EAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"validator.js","names":["CustomValidator"],"sources":["../../src/repository/validator.ts"],"sourcesContent":["import type { FindOptions, IncludeOptions, Transactionable } from 'sequelize';\nimport logger from '../utils/logger';\nimport { CustomValidator } from '../models';\nimport type { ModelOptions } from '../types';\n\nexport interface FindValidatorOptions extends Transactionable {\n withDisabled?: boolean;\n attributes?: string[];\n raw?: boolean;\n include?: IncludeOptions[];\n}\n\n// Make sure this interface is compatible with the Sequelize model\nexport interface ValidatorAttributes {\n entityId: string;\n entityType: string;\n modelType: string;\n schema: CustomValidator['schema'];\n disabled?: boolean;\n [key: string]: unknown; // Add index signature for Sequelize compatibility\n}\n\nexport const create = async (\n validatorAttributes: ValidatorAttributes,\n options: Transactionable = {},\n): Promise<CustomValidator> => {\n logger.debug('custom-validator - create validator');\n\n // Use unknown type to bypass TypeScript errors while maintaining compatibility\n const validator = await CustomValidator.create(validatorAttributes as Record<string, unknown>, options);\n\n return validator;\n};\n\nexport const findAll = async (\n where = {},\n options: FindOptions & {\n modelOptions?: ModelOptions;\n withDisabled?: boolean;\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators');\n\n const {\n transaction, withDisabled, include, attributes, raw,\n } = options;\n\n let validators;\n if (withDisabled) {\n // If withDisabled is true, use unscoped to ignore the default scope that filters disabled items\n // Apply the userScope separately to maintain permission filtering\n validators = await CustomValidator.unscoped().scope('userScope').findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n } else {\n // Use defaultScope and userScope to filter both disabled and by permissions\n // The defaultScope keeps only non-disabled validators\n validators = await CustomValidator.scope(['defaultScope', 'userScope']).findAll({\n where,\n transaction,\n include,\n attributes,\n raw,\n });\n }\n\n return validators;\n};\n\nexport const findAllByModelType = async (\n modelType: string,\n entityId: string,\n options: FindOptions & {\n modelOptions?: ModelOptions;\n withDisabled?: boolean;\n } = {},\n): Promise<CustomValidator[]> => {\n logger.debug('custom-validator - find all validators by model type');\n return findAll(\n {\n modelType,\n ...(!options?.modelOptions?.useEntityIdFromInclude && { entityId }),\n },\n {\n ...options,\n include: options?.modelOptions?.include?.(entityId),\n },\n );\n};\n\nexport const update = async (\n id: string,\n updates: Partial<ValidatorAttributes>,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - update validator');\n\n return CustomValidator.update(\n updates,\n {\n where: { id },\n returning: true,\n ...options,\n },\n );\n};\n\nexport const disable = async (\n id: string,\n options?: Transactionable,\n): Promise<[number, CustomValidator[]]> => {\n logger.debug('custom-validator - disable validator');\n\n return update(id, { disabled: true }, options);\n};\n"],"mappings":"+GAsBA,MAAa,EAAS,MACpB,EACA,EAA2B,EAAE,IAE7B,EAAO,MAAM,sCAAsC,CAGjC,MAAMA,EAAgB,OAAO,EAAgD,EAAQ,EAK5F,EAAU,MACrB,EAAQ,EAAE,CACV,EAGI,EAAE,GACyB,CAC/B,EAAO,MAAM,yCAAyC,CAEtD,GAAM,CACJ,cAAa,eAAc,UAAS,aAAY,OAC9C,EAEA,EAuBJ,MAtBA,CAaE,EAbE,EAGW,MAAMA,EAAgB,UAAU,CAAC,MAAM,YAAY,CAAC,QAAQ,CACvE,QACA,cACA,UACA,aACA,MACD,CAAC,CAIW,MAAMA,EAAgB,MAAM,CAAC,eAAgB,YAAY,CAAC,CAAC,QAAQ,CAC9E,QACA,cACA,UACA,aACA,MACD,CAAC,CAGG,GAGI,EAAqB,MAChC,EACA,EACA,EAGI,EAAE,IAEN,EAAO,MAAM,uDAAuD,CAC7D,EACL,CACE,YACA,GAAI,CAAC,GAAS,cAAc,wBAA0B,CAAE,WAAU,CACnE,CACD,CACE,GAAG,EACH,QAAS,GAAS,cAAc,UAAU,EAAS,CACpD,CACF,EAGU,EAAS,MACpB,EACA,EACA,KAEA,EAAO,MAAM,sCAAsC,CAE5CA,EAAgB,OACrB,EACA,CACE,MAAO,CAAE,KAAI,CACb,UAAW,GACX,GAAG,EACJ,CACF,EAGU,EAAU,MACrB,EACA,KAEA,EAAO,MAAM,uCAAuC,CAE7C,EAAO,EAAI,CAAE,SAAU,GAAM,CAAE,EAAQ"}
@@ -1,2 +0,0 @@
1
- const e=require(`../utils/logger/index.cjs`),t=require(`../errors/index.cjs`),n=require(`./definition.cjs`),r=require(`../models/CustomFieldValue.cjs`);require(`../models/index.cjs`);const i=require(`./utils/formatValues.cjs`),a=async(e,t)=>{let{transaction:n}=t;return r.default.findAll({where:{modelId:e},transaction:n,raw:!0,nest:!0})},o=async(a,o,s,c,l={})=>{let u=Object.keys(c);e.default.debug(`custom-fields: updating values for ${a} ${o}`,{names:u,optionsKeys:l?Object.keys(l):null,valuesToUpdate:c,identifiers:s});let{modelOptions:d,transaction:f}=l,p={modelType:a,name:u,...!l.modelOptions?.useEntityIdFromInclude&&{entityId:s}},m=await n.findAll(p,{withDisabled:!0,transaction:f,include:d.include?.(s)})??[],h=m.filter(e=>e.disabled);if(m.length!==u.length)throw e.default.warn(`custom-fields: missing definitions for ${a} ${o}`,{names:u,fieldDefinitions:m}),new t.MissingDefinitionError(u.filter(e=>!m.some(t=>t.name===e)));let g=h?.map(e=>e.name)||[],_=u.filter(e=>g.includes(e));_?.length>0&&e.default.warn(`custom-fields: trying to update disabled values: ${_.join(`, `)}`);let v=u.map(e=>{let t=m.find(t=>t.name===e),n=i.formatFunctions[t.fieldType],r=n?n(c[e]):c[e];return{modelId:o,updatedAt:new Date,customFieldDefinitionId:t.id,value:r===void 0?t.defaultValue:r}});return Promise.all(v.map(async e=>{let[t]=await r.default.upsert(e,{transaction:l.transaction});return t}))};exports.findValuesByModelIds=a,exports.updateValues=o;
2
- //# sourceMappingURL=value.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"value.cjs","names":["CustomFieldValue","where: WhereOptions","MissingDefinitionError","values: CreateCustomFieldValue[]","formatFunctions"],"sources":["../../src/repository/value.ts"],"sourcesContent":["import type { FindOptions, Transactionable, WhereOptions } from 'sequelize';\nimport { CustomFieldValue, CustomFieldDefinition } from '../models';\nimport * as DefinitionRepo from './definition';\nimport type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';\nimport logger from '../utils/logger';\nimport { MissingDefinitionError } from '../errors';\nimport type { ModelOptions } from '../types';\nimport { formatFunctions } from './utils/formatValues';\n\nexport const findByModelIdAndDefinition = async (modelId: string, customFieldDefinitionId: string): Promise<CustomFieldValue[]> =>\n CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [CustomFieldDefinition] });\n\nexport const create = async (data: CreateCustomFieldValue, withAssociations = false): Promise<CustomFieldValue> => {\n const created = await CustomFieldValue.create(data);\n if (withAssociations) {\n const createdWithAssociations = await findByModelIdAndDefinition(created.modelId, created.customFieldDefinitionId);\n return createdWithAssociations?.[0];\n }\n return created;\n};\n\nexport const findAllValues = async (): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ include: [CustomFieldDefinition] });\n/**\n * Get all values for model instance id (with their definitions)\n * @param modelId\n * @returns CustomFieldValue[]\n */\nexport const findValuesByModelId = async (modelId: string): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ where: { modelId }, include: [CustomFieldDefinition] });\n\n/**\n* Retrieves custom field values for given model IDs\n* @param modelIds - An array of model IDs to query custom field values for.\n* @param options - Optional configuration object.\n*/\nexport const findValuesByModelIds = async (modelIds: string[], options?: Transactionable): Promise<CustomFieldValue[]> => {\n const { transaction } = options!;\n return CustomFieldValue.findAll({\n where: { modelId: modelIds },\n transaction,\n raw: true,\n nest: true,\n });\n};\n\n/**\n * Try to update custom field values for a model instance.\n * Create new value record if not exists, but fails if value's definition not exist.\n * Return the updated values\n */\nexport const updateValues = async (\n modelType: string,\n modelId: string,\n identifiers: string[],\n valuesToUpdate: ValuesToUpdate,\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldValue[]> => {\n const names = Object.keys(valuesToUpdate);\n logger.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {\n names,\n optionsKeys: options ? Object.keys(options) : null,\n valuesToUpdate,\n identifiers,\n });\n const { modelOptions, transaction } = options;\n\n const where: WhereOptions = {\n modelType,\n name: names,\n ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions!.include?.(identifiers) }) ?? [];\n\n const disabledDefinitions = fieldDefinitions.filter(def => def.disabled);\n if (fieldDefinitions.length !== names.length) {\n logger.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });\n const missingDefinitions = names.filter(name => !fieldDefinitions.some(def => def.name === name));\n throw new MissingDefinitionError(missingDefinitions);\n }\n\n const disabledNames = disabledDefinitions?.map(def => def.name) || [];\n const valuesWithDisabledDefinitions = names.filter(name => disabledNames.includes(name));\n if (valuesWithDisabledDefinitions?.length > 0) {\n logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);\n }\n\n const values: CreateCustomFieldValue[] = names.map((name) => {\n const fieldDefinition = fieldDefinitions.find(def => def.name === name)!;\n const formatFunction = formatFunctions[fieldDefinition.fieldType];\n const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];\n return {\n modelId,\n updatedAt: new Date(),\n customFieldDefinitionId: fieldDefinition.id,\n value: value !== undefined ? value : fieldDefinition.defaultValue,\n };\n });\n\n return Promise.all(values.map(async (value) => {\n const [cfv] = await CustomFieldValue.upsert(value, {\n transaction: options.transaction,\n });\n return cfv;\n }));\n};\n\nexport const deleteValue = (\n id: string,\n options: any = {},\n): Promise<any> => CustomFieldValue.update(\n { deletedAt: new Date() },\n {\n where: { id },\n transaction: options.transaction,\n },\n);\n"],"mappings":"mOAkCa,EAAuB,MAAO,EAAoB,IAA2D,CACxH,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAAA,QAAiB,QAAQ,CAC9B,MAAO,CAAE,QAAS,EAAU,CAC5B,cACA,IAAK,GACL,KAAM,GACP,CAAC,EAQS,EAAe,MAC1B,EACA,EACA,EACA,EACA,EAA0D,EAAE,GAC5B,CAChC,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AAMJ,EAAAA,QAAiB,OAAO,EAAO,CACjD,YAAa,EAAQ,YACtB,CAAC,CACF,OAAO,GACP,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"value.js","names":["CustomFieldValue","where: WhereOptions","DefinitionRepo.findAll","values: CreateCustomFieldValue[]"],"sources":["../../src/repository/value.ts"],"sourcesContent":["import type { FindOptions, Transactionable, WhereOptions } from 'sequelize';\nimport { CustomFieldValue, CustomFieldDefinition } from '../models';\nimport * as DefinitionRepo from './definition';\nimport type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';\nimport logger from '../utils/logger';\nimport { MissingDefinitionError } from '../errors';\nimport type { ModelOptions } from '../types';\nimport { formatFunctions } from './utils/formatValues';\n\nexport const findByModelIdAndDefinition = async (modelId: string, customFieldDefinitionId: string): Promise<CustomFieldValue[]> =>\n CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [CustomFieldDefinition] });\n\nexport const create = async (data: CreateCustomFieldValue, withAssociations = false): Promise<CustomFieldValue> => {\n const created = await CustomFieldValue.create(data);\n if (withAssociations) {\n const createdWithAssociations = await findByModelIdAndDefinition(created.modelId, created.customFieldDefinitionId);\n return createdWithAssociations?.[0];\n }\n return created;\n};\n\nexport const findAllValues = async (): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ include: [CustomFieldDefinition] });\n/**\n * Get all values for model instance id (with their definitions)\n * @param modelId\n * @returns CustomFieldValue[]\n */\nexport const findValuesByModelId = async (modelId: string): Promise<CustomFieldValue[]> => CustomFieldValue.findAll({ where: { modelId }, include: [CustomFieldDefinition] });\n\n/**\n* Retrieves custom field values for given model IDs\n* @param modelIds - An array of model IDs to query custom field values for.\n* @param options - Optional configuration object.\n*/\nexport const findValuesByModelIds = async (modelIds: string[], options?: Transactionable): Promise<CustomFieldValue[]> => {\n const { transaction } = options!;\n return CustomFieldValue.findAll({\n where: { modelId: modelIds },\n transaction,\n raw: true,\n nest: true,\n });\n};\n\n/**\n * Try to update custom field values for a model instance.\n * Create new value record if not exists, but fails if value's definition not exist.\n * Return the updated values\n */\nexport const updateValues = async (\n modelType: string,\n modelId: string,\n identifiers: string[],\n valuesToUpdate: ValuesToUpdate,\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldValue[]> => {\n const names = Object.keys(valuesToUpdate);\n logger.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {\n names,\n optionsKeys: options ? Object.keys(options) : null,\n valuesToUpdate,\n identifiers,\n });\n const { modelOptions, transaction } = options;\n\n const where: WhereOptions = {\n modelType,\n name: names,\n ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions!.include?.(identifiers) }) ?? [];\n\n const disabledDefinitions = fieldDefinitions.filter(def => def.disabled);\n if (fieldDefinitions.length !== names.length) {\n logger.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });\n const missingDefinitions = names.filter(name => !fieldDefinitions.some(def => def.name === name));\n throw new MissingDefinitionError(missingDefinitions);\n }\n\n const disabledNames = disabledDefinitions?.map(def => def.name) || [];\n const valuesWithDisabledDefinitions = names.filter(name => disabledNames.includes(name));\n if (valuesWithDisabledDefinitions?.length > 0) {\n logger.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);\n }\n\n const values: CreateCustomFieldValue[] = names.map((name) => {\n const fieldDefinition = fieldDefinitions.find(def => def.name === name)!;\n const formatFunction = formatFunctions[fieldDefinition.fieldType];\n const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];\n return {\n modelId,\n updatedAt: new Date(),\n customFieldDefinitionId: fieldDefinition.id,\n value: value !== undefined ? value : fieldDefinition.defaultValue,\n };\n });\n\n return Promise.all(values.map(async (value) => {\n const [cfv] = await CustomFieldValue.upsert(value, {\n transaction: options.transaction,\n });\n return cfv;\n }));\n};\n\nexport const deleteValue = (\n id: string,\n options: any = {},\n): Promise<any> => CustomFieldValue.update(\n { deletedAt: new Date() },\n {\n where: { id },\n transaction: options.transaction,\n },\n);\n"],"mappings":"gRAkCA,MAAa,EAAuB,MAAO,EAAoB,IAA2D,CACxH,GAAM,CAAE,eAAgB,EACxB,OAAOA,EAAiB,QAAQ,CAC9B,MAAO,CAAE,QAAS,EAAU,CAC5B,cACA,IAAK,GACL,KAAM,GACP,CAAC,EAQS,EAAe,MAC1B,EACA,EACA,EACA,EACA,EAA0D,EAAE,GAC5B,CAChC,IAAM,EAAQ,OAAO,KAAK,EAAe,CACzC,EAAO,MAAM,sCAAsC,EAAU,GAAG,IAAW,CACzE,QACA,YAAa,EAAU,OAAO,KAAK,EAAQ,CAAG,KAC9C,iBACA,cACD,CAAC,CACF,GAAM,CAAE,eAAc,eAAgB,EAQhC,EAAmB,MAAME,EANH,CAC1B,YACA,KAAM,EACN,GAAI,CAAC,EAAQ,cAAc,wBAA0B,CAAE,SAAU,EAAa,CAC/E,CAE4D,CAAE,aAAc,GAAM,cAAa,QAAS,EAAc,UAAU,EAAY,CAAE,CAAC,EAAI,EAAE,CAEhJ,EAAsB,EAAiB,OAAO,GAAO,EAAI,SAAS,CACxE,GAAI,EAAiB,SAAW,EAAM,OAGpC,MAFA,EAAO,KAAK,0CAA0C,EAAU,GAAG,IAAW,CAAE,QAAO,mBAAkB,CAAC,CAEpG,IAAI,EADiB,EAAM,OAAO,GAAQ,CAAC,EAAiB,KAAK,GAAO,EAAI,OAAS,EAAK,CAAC,CAC7C,CAGtD,IAAM,EAAgB,GAAqB,IAAI,GAAO,EAAI,KAAK,EAAI,EAAE,CAC/D,EAAgC,EAAM,OAAO,GAAQ,EAAc,SAAS,EAAK,CAAC,CACpF,GAA+B,OAAS,GAC1C,EAAO,KAAK,oDAAoD,EAA8B,KAAK,KAAK,GAAG,CAG7G,IAAMC,EAAmC,EAAM,IAAK,GAAS,CAC3D,IAAM,EAAkB,EAAiB,KAAK,GAAO,EAAI,OAAS,EAAK,CACjE,EAAiB,EAAgB,EAAgB,WACjD,EAAQ,EAAiB,EAAe,EAAe,GAAM,CAAG,EAAe,GACrF,MAAO,CACL,UACA,UAAW,IAAI,KACf,wBAAyB,EAAgB,GACzC,MAAO,IAAU,IAAA,GAAoB,EAAgB,aAAxB,EAC9B,EACD,CAEF,OAAO,QAAQ,IAAI,EAAO,IAAI,KAAO,IAAU,CAC7C,GAAM,CAAC,GAAO,MAAMH,EAAiB,OAAO,EAAO,CACjD,YAAa,EAAQ,YACtB,CAAC,CACF,OAAO,GACP,CAAC"}
@@ -1,2 +0,0 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/helpers/index.cjs`),n=require(`./helpers/filter.helpers.cjs`);let r=require(`sequelize`),i=require(`sequelize-typescript`),a=require(`@autofleet/common-types`);const o=(e,t)=>({replacementsMap:a,scopeValue:o})=>{if(!o||Object.keys(o).length===0)return{};let s=t?.useCustomFieldsEntries?n.SubQueryType.ENTRIES:n.SubQueryType.VALUES,c=new Map(Object.entries(a).map(([e,t])=>[t,e])),l=Object.entries(o).map(([e,t])=>{switch(s){case n.SubQueryType.ENTRIES:return n.formatConditionsForEntries(e,t,c);case n.SubQueryType.VALUES:return n.formatConditionsForValues(e,t,c);default:return!1}}).filter(Boolean);if(l.length===0)return{};let u=n.getFilterCustomFieldsSubQuery(s,e,l);return{where:{id:{[r.Op.in]:i.Sequelize.literal(`(${u})`)}},replacements:a}},s=a.customFields.CUSTOM_FIELDS_FILTER_SCOPE,c=(e,r)=>({replacementsMap:a,scopeValue:o})=>{if(!o||o.length===0)return{};let s=r?.useCustomFieldsEntries?n.SubQueryType.ENTRIES:n.SubQueryType.VALUES,c=t.generateRandomString(),l=Object.entries(o).map(([t])=>{let r=Object.keys(a).find(e=>a[e]===t);return[i.Sequelize.literal(n.getSortCustomFieldsSubQuery(s,e,r)),c]}),u=Object.entries(o).map(([,e])=>{let t=typeof e==`string`?e:Object.values(e)[0];return i.Sequelize.literal(`"${c}" ${t||`ASC`}`)});return{attributes:{include:l},order:u,replacements:a}};exports.customFieldsFilterScope=o,exports.customFieldsSortScope=c;
2
- //# sourceMappingURL=filter.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"filter.cjs","names":["SubQueryType","formatConditionsForEntries","formatConditionsForValues","getFilterCustomFieldsSubQuery","Op","Sequelize","scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE","customFields","generateRandomString","getSortCustomFieldsSubQuery"],"sources":["../../src/scopes/filter.ts"],"sourcesContent":["import { Op } from 'sequelize';\nimport type { Literal } from 'sequelize/types/utils';\nimport { Sequelize } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { generateRandomString } from '../utils/helpers';\nimport type { CustomFieldOptions } from '../types';\nimport {\n formatConditionsForEntries,\n formatConditionsForValues,\n getFilterCustomFieldsSubQuery,\n getSortCustomFieldsSubQuery,\n SubQueryType,\n type ConditionValue,\n type CustomFieldFilterOptions,\n} from './helpers/filter.helpers';\n\ninterface customFieldsFilterScopeParams {\n replacementsMap: Record<string, string>;\n scopeValue: Record<string, ConditionValue>;\n}\n\n/**\n * A Sequelize scope for filtering models by custom fields.\n * This scope builds a WHERE clause to be applied on the main query.\n *\n * @param name - The model type name used to join custom_field_definitions.\n * @returns A function that takes conditions and returns the Sequelize options object.\n */\nexport const customFieldsFilterScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap: replacements, scopeValue: conditions }: customFieldsFilterScopeParams): CustomFieldFilterOptions => {\n if (!conditions || Object.keys(conditions).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const reverseReplacementsMap = new Map(Object.entries(replacements).map(([key, value]) => [value, key]));\n // Build the WHERE clause for custom field filtering\n const conditionsStrings = Object.entries(conditions).map(([key, condition]) => {\n switch (queryType) {\n case SubQueryType.ENTRIES:\n return formatConditionsForEntries(key, condition, reverseReplacementsMap);\n case SubQueryType.VALUES:\n return formatConditionsForValues(key, condition, reverseReplacementsMap);\n default:\n return false;\n }\n }).filter(Boolean);\n if (conditionsStrings.length === 0) {\n return {};\n }\n const subQuery = getFilterCustomFieldsSubQuery(queryType, name, conditionsStrings);\n\n return {\n where: {\n id: {\n [Op.in]: Sequelize.literal(`(${subQuery})`),\n },\n },\n replacements,\n };\n};\n\nexport const scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport const customFieldsSortScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap, scopeValue: sort }: { replacementsMap: Record<string, string>; scopeValue: Record<string, ConditionValue>; }): {\n attributes: { include: (string | Literal)[][]; };\n order: Literal[];\n replacements: Record<string, string>;\n} | Record<string, never> => {\n if (!sort || (sort as unknown as any[]).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const randomStr = generateRandomString();\n const includes = Object.entries(sort).map(([key]) => {\n const replacementKey = Object.keys(replacementsMap).find(\n randomString => replacementsMap[randomString] === key,\n );\n return ([\n Sequelize.literal(getSortCustomFieldsSubQuery(queryType, name, replacementKey!)),\n randomStr,\n ]);\n });\n\n const orders = Object.entries(sort).map(([, sortObject]) => {\n const direction = typeof sortObject === 'string' ? sortObject : Object.values(sortObject)[0];\n return Sequelize.literal(`\"${randomStr}\" ${direction || 'ASC'}`);\n });\n return {\n attributes: {\n include: includes,\n },\n order: orders,\n replacements: replacementsMap,\n };\n};\n"],"mappings":"wOA4BA,MAAa,GACX,EACA,KACI,CAAE,gBAAiB,EAAc,WAAY,KAA0E,CAC3H,GAAI,CAAC,GAAc,OAAO,KAAK,EAAW,CAAC,SAAW,EACpD,MAAO,EAAE,CAGX,IAAM,EAAY,GAAS,uBAAyBA,EAAAA,aAAa,QAAUA,EAAAA,aAAa,OAClF,EA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Aa,QAAQ,EAChE,CACF,MAAO,CACL,WAAY,CACV,QAAS,EACV,CACD,MAAO,EACP,aAAc,EACf"}
@@ -1,23 +0,0 @@
1
- import { CustomFieldOptions } from "../types/index.cjs";
2
- import { ConditionValue } from "./helpers/filter.helpers.cjs";
3
- import { customFields } from "@autofleet/common-types";
4
- import { Literal } from "sequelize/types/utils";
5
-
6
- //#region src/scopes/filter.d.ts
7
-
8
- declare const customFieldsSortScope: (name: string, options?: Pick<CustomFieldOptions, "useCustomFieldsEntries">) => ({
9
- replacementsMap,
10
- scopeValue: sort
11
- }: {
12
- replacementsMap: Record<string, string>;
13
- scopeValue: Record<string, ConditionValue>;
14
- }) => {
15
- attributes: {
16
- include: (string | Literal)[][];
17
- };
18
- order: Literal[];
19
- replacements: Record<string, string>;
20
- } | Record<string, never>;
21
- //#endregion
22
- export { customFieldsSortScope };
23
- //# sourceMappingURL=filter.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"filter.js","names":["scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE"],"sources":["../../src/scopes/filter.ts"],"sourcesContent":["import { Op } from 'sequelize';\nimport type { Literal } from 'sequelize/types/utils';\nimport { Sequelize } from 'sequelize-typescript';\nimport { customFields } from '@autofleet/common-types';\nimport { generateRandomString } from '../utils/helpers';\nimport type { CustomFieldOptions } from '../types';\nimport {\n formatConditionsForEntries,\n formatConditionsForValues,\n getFilterCustomFieldsSubQuery,\n getSortCustomFieldsSubQuery,\n SubQueryType,\n type ConditionValue,\n type CustomFieldFilterOptions,\n} from './helpers/filter.helpers';\n\ninterface customFieldsFilterScopeParams {\n replacementsMap: Record<string, string>;\n scopeValue: Record<string, ConditionValue>;\n}\n\n/**\n * A Sequelize scope for filtering models by custom fields.\n * This scope builds a WHERE clause to be applied on the main query.\n *\n * @param name - The model type name used to join custom_field_definitions.\n * @returns A function that takes conditions and returns the Sequelize options object.\n */\nexport const customFieldsFilterScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap: replacements, scopeValue: conditions }: customFieldsFilterScopeParams): CustomFieldFilterOptions => {\n if (!conditions || Object.keys(conditions).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const reverseReplacementsMap = new Map(Object.entries(replacements).map(([key, value]) => [value, key]));\n // Build the WHERE clause for custom field filtering\n const conditionsStrings = Object.entries(conditions).map(([key, condition]) => {\n switch (queryType) {\n case SubQueryType.ENTRIES:\n return formatConditionsForEntries(key, condition, reverseReplacementsMap);\n case SubQueryType.VALUES:\n return formatConditionsForValues(key, condition, reverseReplacementsMap);\n default:\n return false;\n }\n }).filter(Boolean);\n if (conditionsStrings.length === 0) {\n return {};\n }\n const subQuery = getFilterCustomFieldsSubQuery(queryType, name, conditionsStrings);\n\n return {\n where: {\n id: {\n [Op.in]: Sequelize.literal(`(${subQuery})`),\n },\n },\n replacements,\n };\n};\n\nexport const scopeName: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport const customFieldsSortScope = (\n name: string,\n options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n) => ({ replacementsMap, scopeValue: sort }: { replacementsMap: Record<string, string>; scopeValue: Record<string, ConditionValue>; }): {\n attributes: { include: (string | Literal)[][]; };\n order: Literal[];\n replacements: Record<string, string>;\n} | Record<string, never> => {\n if (!sort || (sort as unknown as any[]).length === 0) {\n return {};\n }\n\n const queryType = options?.useCustomFieldsEntries ? SubQueryType.ENTRIES : SubQueryType.VALUES;\n const randomStr = generateRandomString();\n const includes = Object.entries(sort).map(([key]) => {\n const replacementKey = Object.keys(replacementsMap).find(\n randomString => replacementsMap[randomString] === key,\n );\n return ([\n Sequelize.literal(getSortCustomFieldsSubQuery(queryType, name, replacementKey!)),\n randomStr,\n ]);\n });\n\n const orders = Object.entries(sort).map(([, sortObject]) => {\n const direction = typeof sortObject === 'string' ? sortObject : Object.values(sortObject)[0];\n return Sequelize.literal(`\"${randomStr}\" ${direction || 'ASC'}`);\n });\n return {\n attributes: {\n include: includes,\n },\n order: orders,\n replacements: replacementsMap,\n };\n};\n"],"mappings":"sYA4BA,MAAa,GACX,EACA,KACI,CAAE,gBAAiB,EAAc,WAAY,KAA0E,CAC3H,GAAI,CAAC,GAAc,OAAO,KAAK,EAAW,CAAC,SAAW,EACpD,MAAO,EAAE,CAGX,IAAM,EAAY,GAAS,uBAAyB,EAAa,QAAU,EAAa,OAClF,EAAyB,IAAI,IAAI,OAAO,QAAQ,EAAa,CAAC,KAAK,CAAC,EAAK,KAAW,CAAC,EAAO,EAAI,CAAC,CAAC,CAElG,EAAoB,OAAO,QAAQ,EAAW,CAAC,KAAK,CAAC,EAAK,KAAe,CAC7E,OAAQ,EAAR,CACE,KAAK,EAAa,QAChB,OAAO,EAA2B,EAAK,EAAW,EAAuB,CAC3E,KAAK,EAAa,OAChB,OAAO,EAA0B,EAAK,EAAW,EAAuB,CAC1E,QACE,MAAO,KAEX,CAAC,OAAO,QAAQ,CAClB,GAAI,EAAkB,SAAW,EAC/B,MAAO,EAAE,CAEX,IAAM,EAAW,EAA8B,EAAW,EAAM,EAAkB,CAElF,MAAO,CACL,MAAO,CACL,GAAI,EACD,EAAG,IAAK,EAAU,QAAQ,IAAI,EAAS,GAAG,CAC5C,CACF,CACD,eACD,EAGsE,EAAa,2BAEtF,MAAa,GACX,EACA,KACI,CAAE,kBAAiB,WAAY,KAIR,CAC3B,GAAI,CAAC,GAAS,EAA0B,SAAW,EACjD,MAAO,EAAE,CAGX,IAAM,EAAY,GAAS,uBAAyB,EAAa,QAAU,EAAa,OAClF,EAAY,GAAsB,CAClC,EAAW,OAAO,QAAQ,EAAK,CAAC,KAAK,CAAC,KAAS,CACnD,IAAM,EAAiB,OAAO,KAAK,EAAgB,CAAC,KAClD,GAAgB,EAAgB,KAAkB,EACnD,CACD,MAAQ,CACN,EAAU,QAAQ,EAA4B,EAAW,EAAM,EAAgB,CAAC,CAChF,EACD,EACD,CAEI,EAAS,OAAO,QAAQ,EAAK,CAAC,KAAK,EAAG,KAAgB,CAC1D,IAAM,EAAY,OAAO,GAAe,SAAW,EAAa,OAAO,OAAO,EAAW,CAAC,GAC1F,OAAO,EAAU,QAAQ,IAAI,EAAU,IAAI,GAAa,QAAQ,EAChE,CACF,MAAO,CACL,WAAY,CACV,QAAS,EACV,CACD,MAAO,EACP,aAAc,EACf"}
@@ -1,46 +0,0 @@
1
- let e=function(e){return e.VALUES=`values`,e.ENTRIES=`entries`,e}({});const t=e=>Array.isArray(e)&&typeof e[0]==`string`,n=e=>[`true`,`false`].includes(e.toString()),r=e=>e instanceof Date||Object.prototype.toString.call(e)===`[object Date]`,i=(e,t)=>`to_jsonb(${e}::${t})`,a=e=>i(e,`text`),o=e=>i(e,`boolean`),s=e=>i(e,`numeric`),c=(e,t)=>r(t)?i(e,`timestamp`):e,l=` AND `,u=` OR `,d=`cd`,f=`cd.name`,p=`cv`,m=`cv.value`,h=`ce`,g=(e,t,i,a)=>{let o=`text`;r(e)?o=`date`:Number.isNaN(Number(e))?n(e)&&(o=`boolean`):o=`numeric`;let s=a.get(e);return`(jsonb_extract_path_text(ce.custom_fields, :${i})::${o}) ${t} :${s}`},_=e=>{let t=e;return n(e)?t=e===`true`:Number.isNaN(Number(e))||(t=Number(e)),t},v=(e,t)=>{let r=_(e),i=JSON.stringify({[t]:r}),a;return n(e)&&(a=`ce.custom_fields @> '${JSON.stringify({[t]:e})}'`),`
2
- (
3
- ${a?`${a} OR`:``}
4
- ce.custom_fields @> '${i}'
5
- )
6
- `},y=(t,n,r)=>{switch(t){case e.VALUES:return`
7
- SELECT cv.model_id
8
- FROM custom_field_values AS cv
9
- INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id
10
- ${l}cd.model_type = '${n}'
11
- WHERE ${r.join(u)}
12
- ${l}cv.deleted_at IS NULL${l}cd.deleted_at IS NULL
13
- GROUP BY cv.model_id
14
- HAVING COUNT(DISTINCT cv.custom_field_definition_id) = ${r.length}
15
- `.replace(/\n/g,``);case e.ENTRIES:return`
16
- SELECT ce.model_id
17
- FROM custom_field_entries ce
18
- JOIN custom_field_definitions cfd
19
- ON ce.model_type = cfd.model_type
20
- AND ce.entity_id = cfd.entity_id
21
- WHERE
22
- cfd.deleted_at IS NULL AND
23
- ${r.join(l)}
24
- `;default:throw Error(`Invalid query type`)}},b=(t,n,r)=>{switch(t){case e.VALUES:return`(
25
- SELECT value
26
- FROM (SELECT cv.model_id, cv.value
27
- FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
28
- ON cv.custom_field_definition_id = cd.id
29
- ${l}cd.model_type = '${n}'
30
- WHERE cv.model_id = "${n}"."id"
31
- ${l}cd.name = :${r}
32
- ) AS CustomFieldAggregation
33
- )
34
- `;case e.ENTRIES:return`(
35
- SELECT
36
- customFields.value
37
- FROM
38
- custom_field_entries AS ce,
39
- jsonb_each_text(custom_fields) AS customFields
40
- WHERE
41
- customFields.key = :${r}${l}
42
- ce.model_type = '${n}'${l}
43
- ce.model_id = "${n}"."id"
44
- )
45
- `;default:throw Error(`Invalid query type`)}},x=(e,r,i)=>{let d=i.get(e);if(!d)return!1;let f=`(cd.name = :${d})`;if(Array.isArray(r))return r.length===0?!1:t(r)?`(${f}${l}${m} IN (${r.flatMap(e=>{let t=i.get(e);return n(e)?[a(`:${t}`),o(`:${t}`)]:Number.isNaN(Number(e))?a(`:${t}`):s(`:${t}`)}).join(`,`)}))`:r.map(e=>{let t=a(`:${i.get(e.value)}`);return`(${f}${l}${c(m,e.value)} ${e.operator} ${t})`}).join(l);if(typeof r==`string`||typeof r==`number`){let e=i.get(r),t=Number.isNaN(Number(r))?a(`:${e}`):s(`:${e}`),d=n(r)?`${u}${m} = ${o(`:${e}`)}`:``;return`(${f}${l}(${c(m,r)} = ${t}${d}))`}if(r?.operator){let e=a(`:${i.get(r.value)}`);return`( ${f}${l}${c(m,r.value)} ${r.operator} ${e})`}return!1},S=(e,n,r)=>{let i=r.get(e);return i?Array.isArray(n)?n.length===0?!1:t(n)?`( ${n.map(t=>v(t,e)).join(`${u}\n`)})`:n.map(e=>g(e.value,e.operator,i,r)).join(l):typeof n==`string`||typeof n==`number`?v(n,e):n?.operator?g(n.value,n.operator,i,r):!1:!1};exports.SubQueryType=e,exports.formatConditionsForEntries=S,exports.formatConditionsForValues=x,exports.getFilterCustomFieldsSubQuery=y,exports.getSortCustomFieldsSubQuery=b;
46
- //# sourceMappingURL=filter.helpers.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"filter.helpers.cjs","names":["CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name`","CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value`","formattedValue: string | number | boolean"],"sources":["../../../src/scopes/helpers/filter.helpers.ts"],"sourcesContent":["import type { WhereOptions } from 'sequelize';\n\n/**\n * Type representing possible condition values.\n * Currently supporting strings and arrays of strings.\n * More types to be added (TBA).\n */\nexport interface ConditionWithOperator {\n operator: string;\n value: string;\n}\nexport type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];\n\nexport interface CustomFieldSort {\n field: string;\n direction: 'ASC' | 'DESC';\n}\n\nexport interface CustomFieldFilterOptions {\n where?: WhereOptions;\n replacements?: Record<string, string>;\n}\n\nexport enum SubQueryType {\n VALUES = 'values',\n ENTRIES = 'entries',\n}\n\nexport const isConditionStringArray = (input: any): input is string[] => Array.isArray(input) && typeof input[0] === 'string';\nexport const isBooleanString = (input: string): boolean => ['true', 'false'].includes(input.toString());\nexport const isDate = (input: any): input is Date => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';\n\nexport const castValueToJsonb = (value: string, type: string) => `to_jsonb(${value}::${type})`;\nexport const castValueToJsonbText = (value: string): string => castValueToJsonb(value, 'text');\nexport const castValueToJsonbBoolean = (value: string): string => castValueToJsonb(value, 'boolean');\nexport const castValueToJsonbNumeric = (value: string): string => castValueToJsonb(value, 'numeric');\nexport const castIfNeeded = (columnName: string, conditionValue: string): string => {\n if (isDate(conditionValue)) {\n return castValueToJsonb(columnName, 'timestamp');\n }\n return columnName;\n};\n\nexport const AND_DELIMITER = ' AND ';\nexport const OR_DELIMITER = ' OR ';\nexport const CD_TABLE_ALIAS = 'cd';\nexport const CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name` = `${CD_TABLE_ALIAS}.name`;\nexport const CV_TABLE_ALIAS = 'cv';\nexport const CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value` = `${CV_TABLE_ALIAS}.value`;\nexport const CE_TABLE_ALIAS = 'ce';\n\nconst getSingleConditionWithOperator = (value: any, operator: string, replacementKey: string, reverseReplacementsMap: Map<string, string>) => {\n let type = 'text';\n if (isDate(value)) {\n type = 'date';\n } else if (!Number.isNaN(Number(value))) {\n type = 'numeric';\n } else if (isBooleanString(value)) {\n type = 'boolean';\n }\n const replacedValue = reverseReplacementsMap.get(value);\n\n return `(jsonb_extract_path_text(${CE_TABLE_ALIAS}.custom_fields, :${replacementKey})::${type}) ${operator} :${replacedValue}`;\n};\n\nconst getFormattedValue = (value: string) => {\n let formattedValue: string | number | boolean = value;\n if (isBooleanString(value)) {\n formattedValue = value === 'true';\n } else if (!Number.isNaN(Number(value))) {\n formattedValue = Number(value);\n }\n\n return formattedValue;\n};\n\nconst getJSONSubQuery = (value: string, key: string) => {\n const formattedValue = getFormattedValue(value);\n const jsonQuery = JSON.stringify({ [key]: formattedValue });\n let jsonQueryWithStringBoolean;\n if (isBooleanString(value)) {\n jsonQueryWithStringBoolean = `${CE_TABLE_ALIAS}.custom_fields @> '${JSON.stringify({ [key]: value })}'`;\n }\n return `\n (\n ${jsonQueryWithStringBoolean ? `${jsonQueryWithStringBoolean} OR` : ''}\n ${CE_TABLE_ALIAS}.custom_fields @> '${jsonQuery}'\n )\n `;\n};\n\nexport const getFilterCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, conditionsStrings: (string | boolean)[]): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `\n SELECT ${CV_TABLE_ALIAS}.model_id\n FROM custom_field_values AS ${CV_TABLE_ALIAS}\n INNER JOIN custom_field_definitions AS ${CD_TABLE_ALIAS} ON ${CV_TABLE_ALIAS}.custom_field_definition_id = ${CD_TABLE_ALIAS}.id\n ${AND_DELIMITER}${CD_TABLE_ALIAS}.model_type = '${modelType}'\n WHERE ${conditionsStrings.join(OR_DELIMITER)}\n ${AND_DELIMITER}${CV_TABLE_ALIAS}.deleted_at IS NULL${AND_DELIMITER}${CD_TABLE_ALIAS}.deleted_at IS NULL\n GROUP BY ${CV_TABLE_ALIAS}.model_id\n HAVING COUNT(DISTINCT ${CV_TABLE_ALIAS}.custom_field_definition_id) = ${conditionsStrings.length}\n `.replace(/\\n/g, '');\n case SubQueryType.ENTRIES:\n return `\n SELECT ce.model_id\n FROM custom_field_entries ce\n JOIN custom_field_definitions cfd\n ON ce.model_type = cfd.model_type\n AND ce.entity_id = cfd.entity_id\n WHERE\n cfd.deleted_at IS NULL AND\n ${conditionsStrings.join(AND_DELIMITER)}\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const getSortCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, replacementKey: string): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `(\n SELECT value\n FROM (SELECT cv.model_id, cv.value\n FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd\n ON cv.custom_field_definition_id = cd.id\n ${AND_DELIMITER}cd.model_type = '${modelType}'\n WHERE cv.model_id = \"${modelType}\".\"id\"\n ${AND_DELIMITER}cd.name = :${replacementKey}\n ) AS CustomFieldAggregation\n )\n `;\n case SubQueryType.ENTRIES:\n return `(\n SELECT\n customFields.value\n FROM\n custom_field_entries AS ${CE_TABLE_ALIAS},\n jsonb_each_text(custom_fields) AS customFields\n WHERE\n customFields.key = :${replacementKey}${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_type = '${modelType}'${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_id = \"${modelType}\".\"id\"\n )\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const formatConditionsForValues = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n const columnCondition = `(${CD_NAME_COLUMN} = :${replacementKey})`;\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.flatMap((v) => {\n const valRandom = reverseReplacementsMap.get(v);\n if (isBooleanString(v)) {\n return [castValueToJsonbText(`:${valRandom}`), castValueToJsonbBoolean(`:${valRandom}`)];\n }\n if (!Number.isNaN(Number(v))) {\n return castValueToJsonbNumeric(`:${valRandom}`);\n }\n return castValueToJsonbText(`:${valRandom}`);\n }).join(',');\n return `(${columnCondition}${AND_DELIMITER}${CV_VALUE_COLUMN} IN (${values}))`;\n }\n return condition.map((c) => {\n const valRep = reverseReplacementsMap.get(c.value);\n const valueAsJsonb = castValueToJsonbText(`:${valRep}`);\n\n return `(${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, c.value)} ${c.operator} ${valueAsJsonb})`;\n }).join(AND_DELIMITER);\n }\n if (typeof condition === 'string' || typeof condition === 'number') {\n const conditionRep = reverseReplacementsMap.get(condition);\n const valueAsJsonb = !Number.isNaN(Number(condition)) ? castValueToJsonbNumeric(`:${conditionRep}`) : castValueToJsonbText(`:${conditionRep}`);\n const valueAsJsonbBoolean = isBooleanString(condition) ? `${OR_DELIMITER}${CV_VALUE_COLUMN} = ${castValueToJsonbBoolean(`:${conditionRep}`)}` : '';\n return `(${columnCondition}${AND_DELIMITER}(${castIfNeeded(CV_VALUE_COLUMN, condition)} = ${valueAsJsonb}${valueAsJsonbBoolean}))`;\n }\n if (condition?.operator) {\n const valueRep = reverseReplacementsMap.get(condition.value);\n const valueAsJsonb = castValueToJsonbText(`:${valueRep}`);\n return `( ${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, condition.value)} ${condition.operator} ${valueAsJsonb})`;\n }\n return false;\n};\n\nexport const formatConditionsForEntries = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.map(value => getJSONSubQuery(value, key)).join(`${OR_DELIMITER}\\n`);\n return `( ${values})`;\n }\n return condition.map(c => getSingleConditionWithOperator(c.value, c.operator, replacementKey, reverseReplacementsMap)).join(AND_DELIMITER);\n }\n\n if (typeof condition === 'string' || typeof condition === 'number') {\n return getJSONSubQuery(condition, key);\n }\n\n if (condition?.operator) {\n return getSingleConditionWithOperator(condition.value, condition.operator, replacementKey, reverseReplacementsMap);\n }\n return false;\n};\n"],"mappings":"AAuBA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,iBAGF,MAAa,EAA0B,GAAkC,MAAM,QAAQ,EAAM,EAAI,OAAO,EAAM,IAAO,SACxG,EAAmB,GAA2B,CAAC,OAAQ,QAAQ,CAAC,SAAS,EAAM,UAAU,CAAC,CAC1F,EAAU,GAA8B,aAAiB,MAAQ,OAAO,UAAU,SAAS,KAAK,EAAM,GAAK,gBAE3G,GAAoB,EAAe,IAAiB,YAAY,EAAM,IAAI,EAAK,GAC/E,EAAwB,GAA0B,EAAiB,EAAO,OAAO,CACjF,EAA2B,GAA0B,EAAiB,EAAO,UAAU,CACvF,EAA2B,GAA0B,EAAiB,EAAO,UAAU,CACvF,GAAgB,EAAoB,IAC3C,EAAO,EAAe,CACjB,EAAiB,EAAY,YAAY,CAE3C,EAGI,EAAgB,QAChB,EAAe,OACf,EAAiB,KACjBA,EAAkD,UAClD,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AuB,IAAI,EAAU,MAAM,GACH,CACzD,MAAO,KAAK,IAAkB,IAAgB,EAAa,EAAiB,EAAU,MAAM,CAAC,GAAG,EAAU,SAAS,GAAG,EAAa,GAErI,MAAO,IAGI,GAA8B,EAAa,EAA2B,IAAgE,CACjJ,IAAM,EAAiB,EAAuB,IAAI,EAAI,CAyBtD,OAxBK,EAID,MAAM,QAAQ,EAAU,CACtB,EAAU,SAAW,EAEhB,GAGL,EAAuB,EAAU,CAE5B,KADQ,EAAU,IAAI,GAAS,EAAgB,EAAO,EAAI,CAAC,CAAC,KAAK,GAAG,EAAa,IAAI,CACzE,GAEd,EAAU,IAAI,GAAK,EAA+B,EAAE,MAAO,EAAE,SAAU,EAAgB,EAAuB,CAAC,CAAC,KAAK,EAAc,CAGxI,OAAO,GAAc,UAAY,OAAO,GAAc,SACjD,EAAgB,EAAW,EAAI,CAGpC,GAAW,SACN,EAA+B,EAAU,MAAO,EAAU,SAAU,EAAgB,EAAuB,CAE7G,GAvBE"}
@@ -1,17 +0,0 @@
1
- import { WhereOptions } from "sequelize";
2
-
3
- //#region src/scopes/helpers/filter.helpers.d.ts
4
-
5
- /**
6
- * Type representing possible condition values.
7
- * Currently supporting strings and arrays of strings.
8
- * More types to be added (TBA).
9
- */
10
- interface ConditionWithOperator {
11
- operator: string;
12
- value: string;
13
- }
14
- type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
15
- //#endregion
16
- export { ConditionValue };
17
- //# sourceMappingURL=filter.helpers.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"filter.helpers.js","names":["CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name`","CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value`","formattedValue: string | number | boolean"],"sources":["../../../src/scopes/helpers/filter.helpers.ts"],"sourcesContent":["import type { WhereOptions } from 'sequelize';\n\n/**\n * Type representing possible condition values.\n * Currently supporting strings and arrays of strings.\n * More types to be added (TBA).\n */\nexport interface ConditionWithOperator {\n operator: string;\n value: string;\n}\nexport type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];\n\nexport interface CustomFieldSort {\n field: string;\n direction: 'ASC' | 'DESC';\n}\n\nexport interface CustomFieldFilterOptions {\n where?: WhereOptions;\n replacements?: Record<string, string>;\n}\n\nexport enum SubQueryType {\n VALUES = 'values',\n ENTRIES = 'entries',\n}\n\nexport const isConditionStringArray = (input: any): input is string[] => Array.isArray(input) && typeof input[0] === 'string';\nexport const isBooleanString = (input: string): boolean => ['true', 'false'].includes(input.toString());\nexport const isDate = (input: any): input is Date => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';\n\nexport const castValueToJsonb = (value: string, type: string) => `to_jsonb(${value}::${type})`;\nexport const castValueToJsonbText = (value: string): string => castValueToJsonb(value, 'text');\nexport const castValueToJsonbBoolean = (value: string): string => castValueToJsonb(value, 'boolean');\nexport const castValueToJsonbNumeric = (value: string): string => castValueToJsonb(value, 'numeric');\nexport const castIfNeeded = (columnName: string, conditionValue: string): string => {\n if (isDate(conditionValue)) {\n return castValueToJsonb(columnName, 'timestamp');\n }\n return columnName;\n};\n\nexport const AND_DELIMITER = ' AND ';\nexport const OR_DELIMITER = ' OR ';\nexport const CD_TABLE_ALIAS = 'cd';\nexport const CD_NAME_COLUMN: `${typeof CD_TABLE_ALIAS}.name` = `${CD_TABLE_ALIAS}.name`;\nexport const CV_TABLE_ALIAS = 'cv';\nexport const CV_VALUE_COLUMN: `${typeof CV_TABLE_ALIAS}.value` = `${CV_TABLE_ALIAS}.value`;\nexport const CE_TABLE_ALIAS = 'ce';\n\nconst getSingleConditionWithOperator = (value: any, operator: string, replacementKey: string, reverseReplacementsMap: Map<string, string>) => {\n let type = 'text';\n if (isDate(value)) {\n type = 'date';\n } else if (!Number.isNaN(Number(value))) {\n type = 'numeric';\n } else if (isBooleanString(value)) {\n type = 'boolean';\n }\n const replacedValue = reverseReplacementsMap.get(value);\n\n return `(jsonb_extract_path_text(${CE_TABLE_ALIAS}.custom_fields, :${replacementKey})::${type}) ${operator} :${replacedValue}`;\n};\n\nconst getFormattedValue = (value: string) => {\n let formattedValue: string | number | boolean = value;\n if (isBooleanString(value)) {\n formattedValue = value === 'true';\n } else if (!Number.isNaN(Number(value))) {\n formattedValue = Number(value);\n }\n\n return formattedValue;\n};\n\nconst getJSONSubQuery = (value: string, key: string) => {\n const formattedValue = getFormattedValue(value);\n const jsonQuery = JSON.stringify({ [key]: formattedValue });\n let jsonQueryWithStringBoolean;\n if (isBooleanString(value)) {\n jsonQueryWithStringBoolean = `${CE_TABLE_ALIAS}.custom_fields @> '${JSON.stringify({ [key]: value })}'`;\n }\n return `\n (\n ${jsonQueryWithStringBoolean ? `${jsonQueryWithStringBoolean} OR` : ''}\n ${CE_TABLE_ALIAS}.custom_fields @> '${jsonQuery}'\n )\n `;\n};\n\nexport const getFilterCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, conditionsStrings: (string | boolean)[]): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `\n SELECT ${CV_TABLE_ALIAS}.model_id\n FROM custom_field_values AS ${CV_TABLE_ALIAS}\n INNER JOIN custom_field_definitions AS ${CD_TABLE_ALIAS} ON ${CV_TABLE_ALIAS}.custom_field_definition_id = ${CD_TABLE_ALIAS}.id\n ${AND_DELIMITER}${CD_TABLE_ALIAS}.model_type = '${modelType}'\n WHERE ${conditionsStrings.join(OR_DELIMITER)}\n ${AND_DELIMITER}${CV_TABLE_ALIAS}.deleted_at IS NULL${AND_DELIMITER}${CD_TABLE_ALIAS}.deleted_at IS NULL\n GROUP BY ${CV_TABLE_ALIAS}.model_id\n HAVING COUNT(DISTINCT ${CV_TABLE_ALIAS}.custom_field_definition_id) = ${conditionsStrings.length}\n `.replace(/\\n/g, '');\n case SubQueryType.ENTRIES:\n return `\n SELECT ce.model_id\n FROM custom_field_entries ce\n JOIN custom_field_definitions cfd\n ON ce.model_type = cfd.model_type\n AND ce.entity_id = cfd.entity_id\n WHERE\n cfd.deleted_at IS NULL AND\n ${conditionsStrings.join(AND_DELIMITER)}\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const getSortCustomFieldsSubQuery = (queryType: SubQueryType, modelType: string, replacementKey: string): string => {\n switch (queryType) {\n case SubQueryType.VALUES:\n return `(\n SELECT value\n FROM (SELECT cv.model_id, cv.value\n FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd\n ON cv.custom_field_definition_id = cd.id\n ${AND_DELIMITER}cd.model_type = '${modelType}'\n WHERE cv.model_id = \"${modelType}\".\"id\"\n ${AND_DELIMITER}cd.name = :${replacementKey}\n ) AS CustomFieldAggregation\n )\n `;\n case SubQueryType.ENTRIES:\n return `(\n SELECT\n customFields.value\n FROM\n custom_field_entries AS ${CE_TABLE_ALIAS},\n jsonb_each_text(custom_fields) AS customFields\n WHERE\n customFields.key = :${replacementKey}${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_type = '${modelType}'${AND_DELIMITER}\n ${CE_TABLE_ALIAS}.model_id = \"${modelType}\".\"id\"\n )\n `;\n default:\n throw new Error('Invalid query type');\n }\n};\n\nexport const formatConditionsForValues = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n const columnCondition = `(${CD_NAME_COLUMN} = :${replacementKey})`;\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.flatMap((v) => {\n const valRandom = reverseReplacementsMap.get(v);\n if (isBooleanString(v)) {\n return [castValueToJsonbText(`:${valRandom}`), castValueToJsonbBoolean(`:${valRandom}`)];\n }\n if (!Number.isNaN(Number(v))) {\n return castValueToJsonbNumeric(`:${valRandom}`);\n }\n return castValueToJsonbText(`:${valRandom}`);\n }).join(',');\n return `(${columnCondition}${AND_DELIMITER}${CV_VALUE_COLUMN} IN (${values}))`;\n }\n return condition.map((c) => {\n const valRep = reverseReplacementsMap.get(c.value);\n const valueAsJsonb = castValueToJsonbText(`:${valRep}`);\n\n return `(${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, c.value)} ${c.operator} ${valueAsJsonb})`;\n }).join(AND_DELIMITER);\n }\n if (typeof condition === 'string' || typeof condition === 'number') {\n const conditionRep = reverseReplacementsMap.get(condition);\n const valueAsJsonb = !Number.isNaN(Number(condition)) ? castValueToJsonbNumeric(`:${conditionRep}`) : castValueToJsonbText(`:${conditionRep}`);\n const valueAsJsonbBoolean = isBooleanString(condition) ? `${OR_DELIMITER}${CV_VALUE_COLUMN} = ${castValueToJsonbBoolean(`:${conditionRep}`)}` : '';\n return `(${columnCondition}${AND_DELIMITER}(${castIfNeeded(CV_VALUE_COLUMN, condition)} = ${valueAsJsonb}${valueAsJsonbBoolean}))`;\n }\n if (condition?.operator) {\n const valueRep = reverseReplacementsMap.get(condition.value);\n const valueAsJsonb = castValueToJsonbText(`:${valueRep}`);\n return `( ${columnCondition}${AND_DELIMITER}${castIfNeeded(CV_VALUE_COLUMN, condition.value)} ${condition.operator} ${valueAsJsonb})`;\n }\n return false;\n};\n\nexport const formatConditionsForEntries = (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>): false | string => {\n const replacementKey = reverseReplacementsMap.get(key);\n if (!replacementKey) {\n return false;\n }\n\n if (Array.isArray(condition)) {\n if (condition.length === 0) {\n // if empty array, the condition is ignored\n return false;\n }\n\n if (isConditionStringArray(condition)) {\n const values = condition.map(value => getJSONSubQuery(value, key)).join(`${OR_DELIMITER}\\n`);\n return `( ${values})`;\n }\n return condition.map(c => getSingleConditionWithOperator(c.value, c.operator, replacementKey, reverseReplacementsMap)).join(AND_DELIMITER);\n }\n\n if (typeof condition === 'string' || typeof condition === 'number') {\n return getJSONSubQuery(condition, key);\n }\n\n if (condition?.operator) {\n return getSingleConditionWithOperator(condition.value, condition.operator, replacementKey, reverseReplacementsMap);\n }\n return false;\n};\n"],"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Definition.cjs";
2
- import { ModelCtor, Sequelize } from "sequelize-typescript";
3
- import { IncludeOptions } from "sequelize";
4
- import { getUser } from "@autofleet/zehut";
5
-
6
- //#region src/types/index.d.ts
7
- type ModelFetcher = (name: string) => any;
8
- interface ModelOptions {
9
- /**
10
- * Include options for the model
11
- */
12
- include?: (entityIds: string | string[]) => IncludeOptions[];
13
- /**
14
- * Custom association for the model
15
- * @param model - The model to associate with
16
- */
17
- customAssociation?: (model: ModelCtor) => void;
18
- /**
19
- * Whether to use the entity id from the instance per scope attribute
20
- */
21
- useEntityIdFromInclude?: boolean;
22
- /**
23
- * Which attributes to include in the model
24
- */
25
- attributes?: string[];
26
- }
27
- interface Models {
28
- name: string;
29
- scopeAttributes: any[];
30
- modelOptions?: ModelOptions;
31
- creationWebhookHandler?: (instance: any) => any;
32
- updateWebhookHandler?: (instance: any) => any;
33
- deletionWebhookHandler?: (instance: any) => any;
34
- }
35
- interface CustomFieldOptions {
36
- models: Models[];
37
- databaseConfig: any;
38
- getUser: typeof getUser;
39
- sequelize?: Sequelize;
40
- useCustomFieldsEntries?: boolean;
41
- useValidators?: boolean;
42
- }
43
- //#endregion
44
- export { CustomFieldOptions, ModelFetcher, Models };
45
- //# sourceMappingURL=index.d.cts.map
@@ -1,2 +0,0 @@
1
- const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/common-types`);const n=[`businessModelId`,`fleetId`,`demandSourceId`];let r=function(e){return e.NUMBER=`number`,e.BOOLEAN=`boolean`,e.DATE=`date`,e.DATETIME=`datetime`,e.TEXT=`text`,e.IMAGE=`image`,e.SELECT=`select`,e.STATUS=`status`,e.FILE=`file`,e}({});const i=t.customFields.CUSTOM_FIELDS_FILTER_SCOPE;exports.CUSTOM_FIELDS_FILTER_SCOPE=i,exports.CustomFieldDefinitionType=r,exports.supportedEntities=n;
2
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE","customFields"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n}\n\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"gGAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,cAGF,MAAMA,EAA6EC,EAAAA,aAAa"}
@@ -1,22 +0,0 @@
1
- import { customFields } from "@autofleet/common-types";
2
-
3
- //#region src/utils/constants/index.d.ts
4
- declare const supportedEntities: readonly ["businessModelId", "fleetId", "demandSourceId"];
5
- /**
6
- * Supported custom field types
7
- */
8
- declare enum CustomFieldDefinitionType {
9
- NUMBER = "number",
10
- BOOLEAN = "boolean",
11
- DATE = "date",
12
- DATETIME = "datetime",
13
- TEXT = "text",
14
- IMAGE = "image",
15
- SELECT = "select",
16
- STATUS = "status",
17
- FILE = "file",
18
- }
19
- declare const CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE;
20
- //#endregion
21
- export { CUSTOM_FIELDS_FILTER_SCOPE, CustomFieldDefinitionType, supportedEntities };
22
- //# sourceMappingURL=index.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n}\n\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"uDAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,cAGF,MAAMA,EAA6E,EAAa"}
@@ -1,2 +0,0 @@
1
- const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`sequelize`),n=require(`sequelize-typescript`);var r=e=>{let t=e[process.env.NODE_ENV||`test`],r;return r=t.use_env_variable?new n.Sequelize(process.env[t.use_env_variable],t):new n.Sequelize(t.database,t.username,t.password,t),r};exports.default=r;
2
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["sequelize: Sequelize","Sequelize","sequelize"],"sources":["../../../src/utils/db/index.ts"],"sourcesContent":["import { Sequelize } from 'sequelize-typescript';\nimport { QueryTypes } from 'sequelize';\n\nexport default (databaseConfig: any): Sequelize => {\n const ENV_DEV = 'test';\n const env: string = process.env.NODE_ENV || ENV_DEV;\n const config = databaseConfig[env];\n let sequelize: Sequelize;\n if (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable]!, config);\n } else {\n sequelize = new Sequelize(config.database, config.username, config.password, config);\n }\n return sequelize;\n};\n\nexport const createSequelizeMeta = (sequelize: Sequelize): Promise<{ name: string; }[]> => sequelize.query(`\nCREATE TABLE IF NOT EXISTS \"SequelizeMeta\" (\n name character varying(255) PRIMARY KEY\n);\n`, { type: QueryTypes.SELECT });\n"],"mappings":"oHAGA,IAAA,EAAgB,GAAmC,CAGjD,IAAM,EAAS,EADK,QAAQ,IAAI,UADhB,QAGZA,EAMJ,MALA,CAGE,EAHE,EAAO,iBACG,IAAIC,EAAAA,UAAU,QAAQ,IAAI,EAAO,kBAAoB,EAAO,CAE5D,IAAIA,EAAAA,UAAU,EAAO,SAAU,EAAO,SAAU,EAAO,SAAU,EAAO,CAE/EC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["sequelize: Sequelize"],"sources":["../../../src/utils/db/index.ts"],"sourcesContent":["import { Sequelize } from 'sequelize-typescript';\nimport { QueryTypes } from 'sequelize';\n\nexport default (databaseConfig: any): Sequelize => {\n const ENV_DEV = 'test';\n const env: string = process.env.NODE_ENV || ENV_DEV;\n const config = databaseConfig[env];\n let sequelize: Sequelize;\n if (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable]!, config);\n } else {\n sequelize = new Sequelize(config.database, config.username, config.password, config);\n }\n return sequelize;\n};\n\nexport const createSequelizeMeta = (sequelize: Sequelize): Promise<{ name: string; }[]> => sequelize.query(`\nCREATE TABLE IF NOT EXISTS \"SequelizeMeta\" (\n name character varying(255) PRIMARY KEY\n);\n`, { type: QueryTypes.SELECT });\n"],"mappings":"mEAGA,IAAA,EAAgB,GAAmC,CAGjD,IAAM,EAAS,EADK,QAAQ,IAAI,UADhB,QAGZA,EAMJ,MALA,CAGE,EAHE,EAAO,iBACG,IAAI,EAAU,QAAQ,IAAI,EAAO,kBAAoB,EAAO,CAE5D,IAAI,EAAU,EAAO,SAAU,EAAO,SAAU,EAAO,SAAU,EAAO,CAE/E"}
@@ -1,2 +0,0 @@
1
- const e=require(`../../_virtual/rolldown_runtime.cjs`),t=require(`../constants/index.cjs`);let n=require(`sequelize`),r=require(`sequelize-typescript`),i=require(`node:crypto`);const a=(e=5)=>Array.from({length:e},()=>`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.charAt((0,i.randomInt)(52))).join(``),o=(e,i,a,o=[t.CustomFieldDefinitionType.DATETIME,t.CustomFieldDefinitionType.DATE])=>{let s=o.map(e=>`'${e}'`).join(`,`),c=`EXISTS ( SELECT 1 FROM "custom_field_values" AS "cv" INNER JOIN custom_field_definitions AS cd ON cd.entity_id = '${a}' AND cv.custom_field_definition_id = cd.id AND cd.model_type = '${i.name}' ${s?`AND cd.field_type NOT IN (${s})`:``} WHERE "cv"."deleted_at" IS NULL AND "cv"."model_id" = "${i.name}"."id" AND CAST("cv"."value" AS TEXT) ILIKE :searchTerm)`;return{where:{[n.Op.or]:[r.Sequelize.where(r.Sequelize.literal(c),!0)]},replacements:{searchTerm:`%${e}%`}}};exports.generateCustomFieldSearchQueryPayload=o,exports.generateRandomString=a;
2
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["CustomFieldDefinitionType","Op","Sequelize"],"sources":["../../../src/utils/helpers/index.ts"],"sourcesContent":["import { type WhereOptions, Op, type BindOrReplacements } from 'sequelize';\nimport { type ModelStatic, Sequelize } from 'sequelize-typescript';\nimport { randomInt } from 'node:crypto';\nimport { CustomFieldDefinitionType } from '../constants';\n\n/**\n * Builds a WHERE clause and replacements for free-text search by custom fields.\n *\n * This function constructs a WHERE clause and replacement bindings that allow searching\n * for a given term within custom fields associated with a specific model type and entity ID.\n * The WHERE clause and replacements are designed to be added to the main query.\n *\n * @param {string} searchTerm - The term to search for within custom fields.\n * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.\n * @param {string} entityId - The entity ID to filter the custom fields by.\n * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types\n * to exclude from the search\n *\n * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements\n * for Sequelize.\n */\n\ninterface CustomFieldsSearchPayload {\n where: WhereOptions;\n replacements: BindOrReplacements;\n}\n\nexport const generateRandomString = (length = 5): string => {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n return Array.from({ length }, () => characters.charAt(randomInt(characters.length))).join('');\n};\n\nexport const generateCustomFieldSearchQueryPayload = (\n searchTerm: string,\n model: ModelStatic,\n entityId: string,\n customFieldsTypesToExclude: CustomFieldDefinitionType[] = [\n CustomFieldDefinitionType.DATETIME,\n CustomFieldDefinitionType.DATE,\n ],\n): CustomFieldsSearchPayload => {\n const excludedTypesString = customFieldsTypesToExclude.map(type => `'${type}'`).join(',');\n\n const subQuery = 'EXISTS ('\n + ' SELECT 1'\n + ' FROM \"custom_field_values\" AS \"cv\"'\n + ' INNER JOIN custom_field_definitions AS cd '\n + ` ON cd.entity_id = '${entityId}'`\n + ' AND cv.custom_field_definition_id = cd.id'\n + ` AND cd.model_type = '${model.name}'`\n + ` ${excludedTypesString ? `AND cd.field_type NOT IN (${excludedTypesString})` : ''}`\n + ' WHERE'\n + ' \"cv\".\"deleted_at\" IS NULL'\n + ` AND \"cv\".\"model_id\" = \"${model.name}\".\"id\"`\n + ' AND CAST(\"cv\".\"value\" AS TEXT) ILIKE :searchTerm)';\n\n return {\n where: {\n [Op.or]: [\n Sequelize.where(Sequelize.literal(subQuery), true),\n ],\n },\n replacements: { searchTerm: `%${searchTerm}%` },\n };\n};\n"],"mappings":"iLA2BA,MAAa,GAAwB,EAAS,IAErC,MAAM,KAAK,CAAE,SAAQ,KAAQ,uDAAW,QAAA,EAAA,EAAA,WAAiB,GAAkB,CAAC,CAAC,CAAC,KAAK,GAAG,CAGlF,GACX,EACA,EACA,EACA,EAA0D,CACxDA,EAAAA,0BAA0B,SAC1BA,EAAAA,0BAA0B,KAC3B,GAC6B,CAC9B,IAAM,EAAsB,EAA2B,IAAI,GAAQ,IAAI,EAAK,GAAG,CAAC,KAAK,IAAI,CAEnF,EAAW,sHAIU,EAAS,mEAEP,EAAM,KAAK,IAChC,EAAsB,6BAA6B,EAAoB,GAAK,GAAA,0DAGrD,EAAM,KAAK,0DAG1C,MAAO,CACL,MAAO,EACJC,EAAAA,GAAG,IAAK,CACPC,EAAAA,UAAU,MAAMA,EAAAA,UAAU,QAAQ,EAAS,CAAE,GAAK,CACnD,CACF,CACD,aAAc,CAAE,WAAY,IAAI,EAAW,GAAI,CAChD"}
@@ -1,31 +0,0 @@
1
- import { CustomFieldDefinitionType } from "../constants/index.cjs";
2
- import { ModelStatic } from "sequelize-typescript";
3
- import { BindOrReplacements, WhereOptions } from "sequelize";
4
-
5
- //#region src/utils/helpers/index.d.ts
6
-
7
- /**
8
- * Builds a WHERE clause and replacements for free-text search by custom fields.
9
- *
10
- * This function constructs a WHERE clause and replacement bindings that allow searching
11
- * for a given term within custom fields associated with a specific model type and entity ID.
12
- * The WHERE clause and replacements are designed to be added to the main query.
13
- *
14
- * @param {string} searchTerm - The term to search for within custom fields.
15
- * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.
16
- * @param {string} entityId - The entity ID to filter the custom fields by.
17
- * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types
18
- * to exclude from the search
19
- *
20
- * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements
21
- * for Sequelize.
22
- */
23
- interface CustomFieldsSearchPayload {
24
- where: WhereOptions;
25
- replacements: BindOrReplacements;
26
- }
27
- declare const generateRandomString: (length?: number) => string;
28
- declare const generateCustomFieldSearchQueryPayload: (searchTerm: string, model: ModelStatic, entityId: string, customFieldsTypesToExclude?: CustomFieldDefinitionType[]) => CustomFieldsSearchPayload;
29
- //#endregion
30
- export { generateCustomFieldSearchQueryPayload, generateRandomString };
31
- //# sourceMappingURL=index.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/utils/helpers/index.ts"],"sourcesContent":["import { type WhereOptions, Op, type BindOrReplacements } from 'sequelize';\nimport { type ModelStatic, Sequelize } from 'sequelize-typescript';\nimport { randomInt } from 'node:crypto';\nimport { CustomFieldDefinitionType } from '../constants';\n\n/**\n * Builds a WHERE clause and replacements for free-text search by custom fields.\n *\n * This function constructs a WHERE clause and replacement bindings that allow searching\n * for a given term within custom fields associated with a specific model type and entity ID.\n * The WHERE clause and replacements are designed to be added to the main query.\n *\n * @param {string} searchTerm - The term to search for within custom fields.\n * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.\n * @param {string} entityId - The entity ID to filter the custom fields by.\n * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types\n * to exclude from the search\n *\n * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements\n * for Sequelize.\n */\n\ninterface CustomFieldsSearchPayload {\n where: WhereOptions;\n replacements: BindOrReplacements;\n}\n\nexport const generateRandomString = (length = 5): string => {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n return Array.from({ length }, () => characters.charAt(randomInt(characters.length))).join('');\n};\n\nexport const generateCustomFieldSearchQueryPayload = (\n searchTerm: string,\n model: ModelStatic,\n entityId: string,\n customFieldsTypesToExclude: CustomFieldDefinitionType[] = [\n CustomFieldDefinitionType.DATETIME,\n CustomFieldDefinitionType.DATE,\n ],\n): CustomFieldsSearchPayload => {\n const excludedTypesString = customFieldsTypesToExclude.map(type => `'${type}'`).join(',');\n\n const subQuery = 'EXISTS ('\n + ' SELECT 1'\n + ' FROM \"custom_field_values\" AS \"cv\"'\n + ' INNER JOIN custom_field_definitions AS cd '\n + ` ON cd.entity_id = '${entityId}'`\n + ' AND cv.custom_field_definition_id = cd.id'\n + ` AND cd.model_type = '${model.name}'`\n + ` ${excludedTypesString ? `AND cd.field_type NOT IN (${excludedTypesString})` : ''}`\n + ' WHERE'\n + ' \"cv\".\"deleted_at\" IS NULL'\n + ` AND \"cv\".\"model_id\" = \"${model.name}\".\"id\"`\n + ' AND CAST(\"cv\".\"value\" AS TEXT) ILIKE :searchTerm)';\n\n return {\n where: {\n [Op.or]: [\n Sequelize.where(Sequelize.literal(subQuery), true),\n ],\n },\n replacements: { searchTerm: `%${searchTerm}%` },\n };\n};\n"],"mappings":"0LA2BA,MAAa,GAAwB,EAAS,IAErC,MAAM,KAAK,CAAE,SAAQ,KAAQ,uDAAW,OAAO,EAAU,GAAkB,CAAC,CAAC,CAAC,KAAK,GAAG,CAGlF,GACX,EACA,EACA,EACA,EAA0D,CACxD,EAA0B,SAC1B,EAA0B,KAC3B,GAC6B,CAC9B,IAAM,EAAsB,EAA2B,IAAI,GAAQ,IAAI,EAAK,GAAG,CAAC,KAAK,IAAI,CAEnF,EAAW,sHAIU,EAAS,mEAEP,EAAM,KAAK,IAChC,EAAsB,6BAA6B,EAAoB,GAAK,GAAA,0DAGrD,EAAM,KAAK,0DAG1C,MAAO,CACL,MAAO,EACJ,EAAG,IAAK,CACP,EAAU,MAAM,EAAU,QAAQ,EAAS,CAAE,GAAK,CACnD,CACF,CACD,aAAc,CAAE,WAAY,IAAI,EAAW,GAAI,CAChD"}