@autofleet/sadot 1.1.2 → 1.1.3-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 +391 -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 +21 -0
  63. package/dist/repository/validator.js +62 -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 +111 -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 +40 -42
  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 +482 -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 +104 -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 +120 -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.97.0/helpers/decorate.cjs +0 -1
  187. package/dist/_virtual/_@oxc-project_runtime@0.97.0/helpers/decorate.js +0 -1
  188. package/dist/_virtual/_@oxc-project_runtime@0.97.0/helpers/decorateMetadata.cjs +0 -1
  189. package/dist/_virtual/_@oxc-project_runtime@0.97.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,2 +1,124 @@
1
- import e from"../utils/logger/index.js";import{MissingDefinitionError as t}from"../errors/index.js";import{findAll as n}from"./definition.js";import r from"../models/CustomFieldValue.js";import"../models/index.js";import{formatFunctions as i}from"./utils/formatValues.js";const a=async(e,t)=>{let{transaction:n}=t;return r.findAll({where:{modelId:e},transaction:n,raw:!0,nest:!0})},o=async(a,o,s,c,l={})=>{let u=Object.keys(c);e.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=await n({modelType:a,name:u,...!l.modelOptions?.useEntityIdFromInclude&&{entityId:s}},{withDisabled:!0,transaction:f,include:d.include?.(s)})??[],m=p.filter(e=>e.disabled);if(p.length!==u.length)throw e.warn(`custom-fields: missing definitions for ${a} ${o}`,{names:u,fieldDefinitions:p}),new t(u.filter(e=>!p.some(t=>t.name===e)));let h=m?.map(e=>e.name)||[],g=u.filter(e=>h.includes(e));g?.length>0&&e.warn(`custom-fields: trying to update disabled values: ${g.join(`, `)}`);let _=u.map(e=>{let t=p.find(t=>t.name===e),n=i[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(_.map(async e=>{let[t]=await r.upsert(e,{transaction:l.transaction});return t}))};export{a as findValuesByModelIds,o as updateValues};
2
- //# sourceMappingURL=value.js.map
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.deleteValue = exports.updateValues = exports.findValuesByModelIds = exports.findValuesByModelId = exports.findAllValues = exports.create = exports.findByModelIdAndDefinition = void 0;
30
+ const models_1 = require("../models");
31
+ const DefinitionRepo = __importStar(require("./definition"));
32
+ const logger_1 = __importDefault(require("../utils/logger"));
33
+ const errors_1 = require("../errors");
34
+ const formatValues_1 = require("./utils/formatValues");
35
+ const findByModelIdAndDefinition = async (modelId, customFieldDefinitionId) => models_1.CustomFieldValue.findAll({ where: { modelId, customFieldDefinitionId }, include: [models_1.CustomFieldDefinition] });
36
+ exports.findByModelIdAndDefinition = findByModelIdAndDefinition;
37
+ const create = async (data, withAssociations = false) => {
38
+ const created = await models_1.CustomFieldValue.create(data);
39
+ if (withAssociations) {
40
+ const createdWithAssociations = await (0, exports.findByModelIdAndDefinition)(created.modelId, created.customFieldDefinitionId);
41
+ return createdWithAssociations?.[0];
42
+ }
43
+ return created;
44
+ };
45
+ exports.create = create;
46
+ const findAllValues = async () => models_1.CustomFieldValue.findAll({ include: [models_1.CustomFieldDefinition] });
47
+ exports.findAllValues = findAllValues;
48
+ /**
49
+ * Get all values for model instance id (with their definitions)
50
+ * @param modelId
51
+ * @returns CustomFieldValue[]
52
+ */
53
+ const findValuesByModelId = async (modelId) => models_1.CustomFieldValue.findAll({ where: { modelId }, include: [models_1.CustomFieldDefinition] });
54
+ exports.findValuesByModelId = findValuesByModelId;
55
+ /**
56
+ * Retrieves custom field values for given model IDs
57
+ * @param modelIds - An array of model IDs to query custom field values for.
58
+ * @param options - Optional configuration object.
59
+ */
60
+ const findValuesByModelIds = async (modelIds, options) => {
61
+ const { transaction } = options;
62
+ return models_1.CustomFieldValue.findAll({
63
+ where: { modelId: modelIds },
64
+ transaction,
65
+ raw: true,
66
+ nest: true,
67
+ });
68
+ };
69
+ exports.findValuesByModelIds = findValuesByModelIds;
70
+ /**
71
+ * Try to update custom field values for a model instance.
72
+ * Create new value record if not exists, but fails if value's definition not exist.
73
+ * Return the updated values
74
+ */
75
+ const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
76
+ const names = Object.keys(valuesToUpdate);
77
+ logger_1.default.debug(`custom-fields: updating values for ${modelType} ${modelId}`, {
78
+ names,
79
+ optionsKeys: options ? Object.keys(options) : null,
80
+ valuesToUpdate,
81
+ identifiers,
82
+ });
83
+ const { modelOptions, transaction } = options;
84
+ const where = {
85
+ modelType,
86
+ name: names,
87
+ ...(!options.modelOptions?.useEntityIdFromInclude && { entityId: identifiers }),
88
+ };
89
+ const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions.include?.(identifiers) }) ?? [];
90
+ const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
91
+ if (fieldDefinitions.length !== names.length) {
92
+ logger_1.default.warn(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });
93
+ const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));
94
+ throw new errors_1.MissingDefinitionError(missingDefinitions);
95
+ }
96
+ const disabledNames = disabledDefinitions?.map((def) => def.name) || [];
97
+ const valuesWithDisabledDefinitions = names.filter((name) => disabledNames.includes(name));
98
+ if (valuesWithDisabledDefinitions?.length > 0) {
99
+ logger_1.default.warn(`custom-fields: trying to update disabled values: ${valuesWithDisabledDefinitions.join(', ')}`);
100
+ }
101
+ const values = names.map((name) => {
102
+ const fieldDefinition = fieldDefinitions.find((def) => def.name === name);
103
+ const formatFunction = formatValues_1.formatFunctions[fieldDefinition.fieldType];
104
+ const value = formatFunction ? formatFunction(valuesToUpdate[name]) : valuesToUpdate[name];
105
+ return {
106
+ modelId,
107
+ updatedAt: new Date(),
108
+ customFieldDefinitionId: fieldDefinition.id,
109
+ value: value !== undefined ? value : fieldDefinition.defaultValue,
110
+ };
111
+ });
112
+ return Promise.all(values.map(async (value) => {
113
+ const [cfv] = await models_1.CustomFieldValue.upsert(value, {
114
+ transaction: options.transaction,
115
+ });
116
+ return cfv;
117
+ }));
118
+ };
119
+ exports.updateValues = updateValues;
120
+ const deleteValue = (id, options = {}) => models_1.CustomFieldValue.update({ deletedAt: new Date() }, {
121
+ where: { id },
122
+ transaction: options.transaction,
123
+ });
124
+ exports.deleteValue = deleteValue;
@@ -1,23 +1,30 @@
1
- import { CustomFieldOptions } from "../types/index.js";
2
- import { ConditionValue } from "./helpers/filter.helpers.js";
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>;
1
+ import type { CustomFieldOptions } from '../types';
2
+ import { type ConditionValue, type CustomFieldFilterOptions } from './helpers/filter.helpers';
3
+ type customFieldsFilterScopeParams = {
4
+ replacementsMap: Record<string, string>;
5
+ scopeValue: Record<string, ConditionValue>;
6
+ };
7
+ /**
8
+ * A Sequelize scope for filtering models by custom fields.
9
+ * This scope builds a WHERE clause to be applied on the main query.
10
+ *
11
+ * @param name - The model type name used to join custom_field_definitions.
12
+ * @returns A function that takes conditions and returns the Sequelize options object.
13
+ */
14
+ export declare const customFieldsFilterScope: (name: string, options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>) => ({ replacementsMap: replacements, scopeValue: conditions }: customFieldsFilterScopeParams) => CustomFieldFilterOptions;
15
+ export declare const scopeName: "filterByCustomFields";
16
+ export declare const customFieldsSortScope: (name: string, options?: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>) => ({ replacementsMap, scopeValue: sort }: {
17
+ replacementsMap: any;
18
+ scopeValue: any;
14
19
  }) => {
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.ts.map
20
+ attributes?: undefined;
21
+ order?: undefined;
22
+ replacements?: undefined;
23
+ } | {
24
+ attributes: {
25
+ include: (string | import("sequelize/types/utils").Literal)[][];
26
+ };
27
+ order: import("sequelize/types/utils").Literal[];
28
+ replacements: any;
29
+ };
30
+ export {};
@@ -1,2 +1,75 @@
1
- import{generateRandomString as e}from"../utils/helpers/index.js";import{SubQueryType as t,formatConditionsForEntries as n,formatConditionsForValues as r,getFilterCustomFieldsSubQuery as i,getSortCustomFieldsSubQuery as a}from"./helpers/filter.helpers.js";import{Op as o}from"sequelize";import{Sequelize as s}from"sequelize-typescript";import{customFields as c}from"@autofleet/common-types";const l=(e,a)=>({replacementsMap:c,scopeValue:l})=>{if(!l||Object.keys(l).length===0)return{};let u=a?.useCustomFieldsEntries?t.ENTRIES:t.VALUES,d=new Map(Object.entries(c).map(([e,t])=>[t,e])),f=Object.entries(l).map(([e,i])=>{switch(u){case t.ENTRIES:return n(e,i,d);case t.VALUES:return r(e,i,d);default:return!1}}).filter(Boolean);if(f.length===0)return{};let p=i(u,e,f);return{where:{id:{[o.in]:s.literal(`(${p})`)}},replacements:c}};c.CUSTOM_FIELDS_FILTER_SCOPE;const u=(n,r)=>({replacementsMap:i,scopeValue:o})=>{if(!o||o.length===0)return{};let c=r?.useCustomFieldsEntries?t.ENTRIES:t.VALUES,l=e(),u=Object.entries(o).map(([e])=>{let t=Object.keys(i).find(t=>i[t]===e);return[s.literal(a(c,n,t)),l]}),d=Object.entries(o).map(([,e])=>{let t=typeof e==`string`?e:Object.values(e)[0];return s.literal(`"${l}" ${t||`ASC`}`)});return{attributes:{include:u},order:d,replacements:i}};export{l as customFieldsFilterScope,u as customFieldsSortScope};
2
- //# sourceMappingURL=filter.js.map
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.customFieldsSortScope = exports.scopeName = exports.customFieldsFilterScope = void 0;
4
+ /* eslint-disable import/prefer-default-export */
5
+ const sequelize_1 = require("sequelize");
6
+ const sequelize_typescript_1 = require("sequelize-typescript");
7
+ const common_types_1 = require("@autofleet/common-types");
8
+ const helpers_1 = require("../utils/helpers");
9
+ const filter_helpers_1 = require("./helpers/filter.helpers");
10
+ const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
11
+ /**
12
+ * A Sequelize scope for filtering models by custom fields.
13
+ * This scope builds a WHERE clause to be applied on the main query.
14
+ *
15
+ * @param name - The model type name used to join custom_field_definitions.
16
+ * @returns A function that takes conditions and returns the Sequelize options object.
17
+ */
18
+ const customFieldsFilterScope = (name, options) => ({ replacementsMap: replacements, scopeValue: conditions }) => {
19
+ if (!conditions || Object.keys(conditions).length === 0) {
20
+ return {};
21
+ }
22
+ const queryType = options?.useCustomFieldsEntries ? filter_helpers_1.SubQueryType.ENTRIES : filter_helpers_1.SubQueryType.VALUES;
23
+ const reverseReplacementsMap = new Map(Object.entries(replacements).map(([key, value]) => [value, key]));
24
+ // Build the WHERE clause for custom field filtering
25
+ const conditionsStrings = Object.entries(conditions).map(([key, condition]) => {
26
+ switch (queryType) {
27
+ case filter_helpers_1.SubQueryType.ENTRIES:
28
+ return (0, filter_helpers_1.formatConditionsForEntries)(key, condition, reverseReplacementsMap);
29
+ case filter_helpers_1.SubQueryType.VALUES:
30
+ return (0, filter_helpers_1.formatConditionsForValues)(key, condition, reverseReplacementsMap);
31
+ default:
32
+ return false;
33
+ }
34
+ }).filter(Boolean);
35
+ if (conditionsStrings.length === 0) {
36
+ return {};
37
+ }
38
+ const subQuery = (0, filter_helpers_1.getFilterCustomFieldsSubQuery)(queryType, name, conditionsStrings);
39
+ return {
40
+ where: {
41
+ id: {
42
+ [sequelize_1.Op.in]: sequelize_typescript_1.Sequelize.literal(`(${subQuery})`),
43
+ },
44
+ },
45
+ replacements,
46
+ };
47
+ };
48
+ exports.customFieldsFilterScope = customFieldsFilterScope;
49
+ exports.scopeName = CUSTOM_FIELDS_FILTER_SCOPE;
50
+ const customFieldsSortScope = (name, options) => ({ replacementsMap, scopeValue: sort }) => {
51
+ if (!sort || sort.length === 0) {
52
+ return {};
53
+ }
54
+ const queryType = options?.useCustomFieldsEntries ? filter_helpers_1.SubQueryType.ENTRIES : filter_helpers_1.SubQueryType.VALUES;
55
+ const randomStr = (0, helpers_1.generateRandomString)();
56
+ const includes = Object.entries(sort).map(([key]) => {
57
+ const replacementKey = Object.keys(replacementsMap).find((randomString) => replacementsMap[randomString] === key);
58
+ return ([
59
+ sequelize_typescript_1.Sequelize.literal((0, filter_helpers_1.getSortCustomFieldsSubQuery)(queryType, name, replacementKey)),
60
+ randomStr,
61
+ ]);
62
+ });
63
+ const orders = Object.entries(sort).map(([, sortObject]) => {
64
+ const direction = typeof sortObject === 'string' ? sortObject : Object.values(sortObject)[0];
65
+ return sequelize_typescript_1.Sequelize.literal(`"${randomStr}" ${direction || 'ASC'}`);
66
+ });
67
+ return {
68
+ attributes: {
69
+ include: includes,
70
+ },
71
+ order: orders,
72
+ replacements: replacementsMap,
73
+ };
74
+ };
75
+ exports.customFieldsSortScope = customFieldsSortScope;
@@ -1,17 +1,42 @@
1
- import { WhereOptions } from "sequelize";
2
-
3
- //#region src/scopes/helpers/filter.helpers.d.ts
4
-
1
+ import type { WhereOptions } from 'sequelize';
5
2
  /**
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;
3
+ * Type representing possible condition values.
4
+ * Currently supporting strings and arrays of strings.
5
+ * More types to be added (TBA).
6
+ */
7
+ export type ConditionWithOperator = {
8
+ operator: string;
9
+ value: string;
10
+ };
11
+ export type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
12
+ export type CustomFieldSort = {
13
+ field: string;
14
+ direction: 'ASC' | 'DESC';
15
+ };
16
+ export type CustomFieldFilterOptions = {
17
+ where?: WhereOptions;
18
+ replacements?: Record<string, string>;
19
+ };
20
+ export declare enum SubQueryType {
21
+ VALUES = "values",
22
+ ENTRIES = "entries"
13
23
  }
14
- type ConditionValue = ConditionWithOperator | ConditionWithOperator[] | string | string[];
15
- //#endregion
16
- export { ConditionValue };
17
- //# sourceMappingURL=filter.helpers.d.ts.map
24
+ export declare const isConditionStringArray: (input: any) => input is string[];
25
+ export declare const isBooleanString: (input: string) => boolean;
26
+ export declare const isDate: (input: any) => input is Date;
27
+ export declare const castValueToJsonb: (value: string, type: string) => string;
28
+ export declare const castValueToJsonbText: (value: string) => string;
29
+ export declare const castValueToJsonbBoolean: (value: string) => string;
30
+ export declare const castValueToJsonbNumeric: (value: string) => string;
31
+ export declare const castIfNeeded: (columnName: string, conditionValue: string) => string;
32
+ export declare const AND_DELIMITER = " AND ";
33
+ export declare const OR_DELIMITER = " OR ";
34
+ export declare const CD_TABLE_ALIAS = "cd";
35
+ export declare const CD_NAME_COLUMN = "cd.name";
36
+ export declare const CV_TABLE_ALIAS = "cv";
37
+ export declare const CV_VALUE_COLUMN = "cv.value";
38
+ export declare const CE_TABLE_ALIAS = "ce";
39
+ export declare const getFilterCustomFieldsSubQuery: (queryType: SubQueryType, modelType: string, conditionsStrings: Array<string | boolean>) => string;
40
+ export declare const getSortCustomFieldsSubQuery: (queryType: SubQueryType, modelType: string, replacementKey: string) => string;
41
+ export declare const formatConditionsForValues: (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>) => string | false;
42
+ export declare const formatConditionsForEntries: (key: string, condition: ConditionValue, reverseReplacementsMap: Map<string, string>) => string | false;
@@ -1,18 +1,92 @@
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=`cv.value`,f=(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}`},p=e=>{let t=e;return n(e)?t=e===`true`:Number.isNaN(Number(e))||(t=Number(e)),t},m=(e,t)=>{let r=p(e),i=JSON.stringify({[t]:r}),a;return n(e)&&(a=`ce.custom_fields @> '${JSON.stringify({[t]:e})}'`),`
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatConditionsForEntries = exports.formatConditionsForValues = exports.getSortCustomFieldsSubQuery = exports.getFilterCustomFieldsSubQuery = exports.CE_TABLE_ALIAS = exports.CV_VALUE_COLUMN = exports.CV_TABLE_ALIAS = exports.CD_NAME_COLUMN = exports.CD_TABLE_ALIAS = exports.OR_DELIMITER = exports.AND_DELIMITER = exports.castIfNeeded = exports.castValueToJsonbNumeric = exports.castValueToJsonbBoolean = exports.castValueToJsonbText = exports.castValueToJsonb = exports.isDate = exports.isBooleanString = exports.isConditionStringArray = exports.SubQueryType = void 0;
4
+ var SubQueryType;
5
+ (function (SubQueryType) {
6
+ SubQueryType["VALUES"] = "values";
7
+ SubQueryType["ENTRIES"] = "entries";
8
+ })(SubQueryType || (exports.SubQueryType = SubQueryType = {}));
9
+ const isConditionStringArray = (input) => Array.isArray(input) && typeof input[0] === 'string';
10
+ exports.isConditionStringArray = isConditionStringArray;
11
+ const isBooleanString = (input) => ['true', 'false'].includes(input.toString());
12
+ exports.isBooleanString = isBooleanString;
13
+ const isDate = (input) => input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
14
+ exports.isDate = isDate;
15
+ const castValueToJsonb = (value, type) => `to_jsonb(${value}::${type})`;
16
+ exports.castValueToJsonb = castValueToJsonb;
17
+ const castValueToJsonbText = (value) => (0, exports.castValueToJsonb)(value, 'text');
18
+ exports.castValueToJsonbText = castValueToJsonbText;
19
+ const castValueToJsonbBoolean = (value) => (0, exports.castValueToJsonb)(value, 'boolean');
20
+ exports.castValueToJsonbBoolean = castValueToJsonbBoolean;
21
+ const castValueToJsonbNumeric = (value) => (0, exports.castValueToJsonb)(value, 'numeric');
22
+ exports.castValueToJsonbNumeric = castValueToJsonbNumeric;
23
+ const castIfNeeded = (columnName, conditionValue) => {
24
+ if ((0, exports.isDate)(conditionValue)) {
25
+ return (0, exports.castValueToJsonb)(columnName, 'timestamp');
26
+ }
27
+ return columnName;
28
+ };
29
+ exports.castIfNeeded = castIfNeeded;
30
+ exports.AND_DELIMITER = ' AND ';
31
+ exports.OR_DELIMITER = ' OR ';
32
+ exports.CD_TABLE_ALIAS = 'cd';
33
+ exports.CD_NAME_COLUMN = `${exports.CD_TABLE_ALIAS}.name`;
34
+ exports.CV_TABLE_ALIAS = 'cv';
35
+ exports.CV_VALUE_COLUMN = `${exports.CV_TABLE_ALIAS}.value`;
36
+ exports.CE_TABLE_ALIAS = 'ce';
37
+ const getSingleConditionWithOperator = (value, operator, replacementKey, reverseReplacementsMap) => {
38
+ let type = 'text';
39
+ if ((0, exports.isDate)(value)) {
40
+ type = 'date';
41
+ }
42
+ else if (!Number.isNaN(Number(value))) {
43
+ type = 'numeric';
44
+ }
45
+ else if ((0, exports.isBooleanString)(value)) {
46
+ type = 'boolean';
47
+ }
48
+ const replacedValue = reverseReplacementsMap.get(value);
49
+ return `(jsonb_extract_path_text(${exports.CE_TABLE_ALIAS}.custom_fields, :${replacementKey})::${type}) ${operator} :${replacedValue}`;
50
+ };
51
+ const getFormattedValue = (value) => {
52
+ let formattedValue = value;
53
+ if ((0, exports.isBooleanString)(value)) {
54
+ formattedValue = value === 'true';
55
+ }
56
+ else if (!Number.isNaN(Number(value))) {
57
+ formattedValue = Number(value);
58
+ }
59
+ return formattedValue;
60
+ };
61
+ const getJSONSubQuery = (value, key) => {
62
+ const formattedValue = getFormattedValue(value);
63
+ const jsonQuery = JSON.stringify({ [key]: formattedValue });
64
+ let jsonQueryWithStringBoolean;
65
+ if ((0, exports.isBooleanString)(value)) {
66
+ jsonQueryWithStringBoolean = `${exports.CE_TABLE_ALIAS}.custom_fields @> '${JSON.stringify({ [key]: value })}'`;
67
+ }
68
+ return `
2
69
  (
3
- ${a?`${a} OR`:``}
4
- ce.custom_fields @> '${i}'
70
+ ${jsonQueryWithStringBoolean ? `${jsonQueryWithStringBoolean} OR` : ''}
71
+ ${exports.CE_TABLE_ALIAS}.custom_fields @> '${jsonQuery}'
5
72
  )
6
- `},h=(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`
73
+ `;
74
+ };
75
+ const getFilterCustomFieldsSubQuery = (queryType, modelType, conditionsStrings) => {
76
+ switch (queryType) {
77
+ case SubQueryType.VALUES:
78
+ return `
79
+ SELECT ${exports.CV_TABLE_ALIAS}.model_id
80
+ FROM custom_field_values AS ${exports.CV_TABLE_ALIAS}
81
+ INNER JOIN custom_field_definitions AS ${exports.CD_TABLE_ALIAS} ON ${exports.CV_TABLE_ALIAS}.custom_field_definition_id = ${exports.CD_TABLE_ALIAS}.id
82
+ ${exports.AND_DELIMITER}${exports.CD_TABLE_ALIAS}.model_type = '${modelType}'
83
+ WHERE ${conditionsStrings.join(exports.OR_DELIMITER)}
84
+ ${exports.AND_DELIMITER}${exports.CV_TABLE_ALIAS}.deleted_at IS NULL${exports.AND_DELIMITER}${exports.CD_TABLE_ALIAS}.deleted_at IS NULL
85
+ GROUP BY ${exports.CV_TABLE_ALIAS}.model_id
86
+ HAVING COUNT(DISTINCT ${exports.CV_TABLE_ALIAS}.custom_field_definition_id) = ${conditionsStrings.length}
87
+ `.replace(/\n/g, '');
88
+ case SubQueryType.ENTRIES:
89
+ return `
16
90
  SELECT ce.model_id
17
91
  FROM custom_field_entries ce
18
92
  JOIN custom_field_definitions cfd
@@ -20,27 +94,111 @@ let e=function(e){return e.VALUES=`values`,e.ENTRIES=`entries`,e}({});const t=e=
20
94
  AND ce.entity_id = cfd.entity_id
21
95
  WHERE
22
96
  cfd.deleted_at IS NULL AND
23
- ${r.join(l)}
24
- `;default:throw Error(`Invalid query type`)}},g=(t,n,r)=>{switch(t){case e.VALUES:return`(
97
+ ${conditionsStrings.join(exports.AND_DELIMITER)}
98
+ `;
99
+ default:
100
+ throw new Error('Invalid query type');
101
+ }
102
+ };
103
+ exports.getFilterCustomFieldsSubQuery = getFilterCustomFieldsSubQuery;
104
+ const getSortCustomFieldsSubQuery = (queryType, modelType, replacementKey) => {
105
+ switch (queryType) {
106
+ case SubQueryType.VALUES:
107
+ return `(
25
108
  SELECT value
26
109
  FROM (SELECT cv.model_id, cv.value
27
110
  FROM custom_field_values AS cv INNER JOIN custom_field_definitions AS cd
28
111
  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}
112
+ ${exports.AND_DELIMITER}cd.model_type = '${modelType}'
113
+ WHERE cv.model_id = "${modelType}"."id"
114
+ ${exports.AND_DELIMITER}cd.name = :${replacementKey}
32
115
  ) AS CustomFieldAggregation
33
116
  )
34
- `;case e.ENTRIES:return`(
117
+ `;
118
+ case SubQueryType.ENTRIES:
119
+ return `(
35
120
  SELECT
36
121
  customFields.value
37
122
  FROM
38
- custom_field_entries AS ce,
123
+ custom_field_entries AS ${exports.CE_TABLE_ALIAS},
39
124
  jsonb_each_text(custom_fields) AS customFields
40
125
  WHERE
41
- customFields.key = :${r}${l}
42
- ce.model_type = '${n}'${l}
43
- ce.model_id = "${n}"."id"
126
+ customFields.key = :${replacementKey}${exports.AND_DELIMITER}
127
+ ${exports.CE_TABLE_ALIAS}.model_type = '${modelType}'${exports.AND_DELIMITER}
128
+ ${exports.CE_TABLE_ALIAS}.model_id = "${modelType}"."id"
44
129
  )
45
- `;default:throw Error(`Invalid query type`)}},_=(e,r,i)=>{let f=i.get(e);if(!f)return!1;let p=`(cd.name = :${f})`;if(Array.isArray(r))return r.length===0?!1:t(r)?`(${p}${l}${d} 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`(${p}${l}${c(d,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}`),f=n(r)?`${u}${d} = ${o(`:${e}`)}`:``;return`(${p}${l}(${c(d,r)} = ${t}${f}))`}if(r?.operator){let e=a(`:${i.get(r.value)}`);return`( ${p}${l}${c(d,r.value)} ${r.operator} ${e})`}return!1},v=(e,n,r)=>{let i=r.get(e);return i?Array.isArray(n)?n.length===0?!1:t(n)?`( ${n.map(t=>m(t,e)).join(`${u}\n`)})`:n.map(e=>f(e.value,e.operator,i,r)).join(l):typeof n==`string`||typeof n==`number`?m(n,e):n?.operator?f(n.value,n.operator,i,r):!1:!1};export{e as SubQueryType,v as formatConditionsForEntries,_ as formatConditionsForValues,h as getFilterCustomFieldsSubQuery,g as getSortCustomFieldsSubQuery};
46
- //# sourceMappingURL=filter.helpers.js.map
130
+ `;
131
+ default:
132
+ throw new Error('Invalid query type');
133
+ }
134
+ };
135
+ exports.getSortCustomFieldsSubQuery = getSortCustomFieldsSubQuery;
136
+ const formatConditionsForValues = (key, condition, reverseReplacementsMap) => {
137
+ const replacementKey = reverseReplacementsMap.get(key);
138
+ if (!replacementKey) {
139
+ return false;
140
+ }
141
+ const columnCondition = `(${exports.CD_NAME_COLUMN} = :${replacementKey})`;
142
+ if (Array.isArray(condition)) {
143
+ if (condition.length === 0) {
144
+ // if empty array, the condition is ignored
145
+ return false;
146
+ }
147
+ if ((0, exports.isConditionStringArray)(condition)) {
148
+ const values = condition.flatMap((v) => {
149
+ const valRandom = reverseReplacementsMap.get(v);
150
+ if ((0, exports.isBooleanString)(v)) {
151
+ return [(0, exports.castValueToJsonbText)(`:${valRandom}`), (0, exports.castValueToJsonbBoolean)(`:${valRandom}`)];
152
+ }
153
+ if (!Number.isNaN(Number(v))) {
154
+ return (0, exports.castValueToJsonbNumeric)(`:${valRandom}`);
155
+ }
156
+ return (0, exports.castValueToJsonbText)(`:${valRandom}`);
157
+ }).join(',');
158
+ return `(${columnCondition}${exports.AND_DELIMITER}${exports.CV_VALUE_COLUMN} IN (${values}))`;
159
+ }
160
+ return condition.map((c) => {
161
+ const valRep = reverseReplacementsMap.get(c.value);
162
+ const valueAsJsonb = (0, exports.castValueToJsonbText)(`:${valRep}`);
163
+ return `(${columnCondition}${exports.AND_DELIMITER}${(0, exports.castIfNeeded)(exports.CV_VALUE_COLUMN, c.value)} ${c.operator} ${valueAsJsonb})`;
164
+ }).join(exports.AND_DELIMITER);
165
+ }
166
+ if (typeof condition === 'string' || typeof condition === 'number') {
167
+ const conditionRep = reverseReplacementsMap.get(condition);
168
+ const valueAsJsonb = !Number.isNaN(Number(condition)) ? (0, exports.castValueToJsonbNumeric)(`:${conditionRep}`) : (0, exports.castValueToJsonbText)(`:${conditionRep}`);
169
+ const valueAsJsonbBoolean = (0, exports.isBooleanString)(condition) ? `${exports.OR_DELIMITER}${exports.CV_VALUE_COLUMN} = ${(0, exports.castValueToJsonbBoolean)(`:${conditionRep}`)}` : '';
170
+ return `(${columnCondition}${exports.AND_DELIMITER}(${(0, exports.castIfNeeded)(exports.CV_VALUE_COLUMN, condition)} = ${valueAsJsonb}${valueAsJsonbBoolean}))`;
171
+ }
172
+ if (condition?.operator) {
173
+ const valueRep = reverseReplacementsMap.get(condition.value);
174
+ const valueAsJsonb = (0, exports.castValueToJsonbText)(`:${valueRep}`);
175
+ return `( ${columnCondition}${exports.AND_DELIMITER}${(0, exports.castIfNeeded)(exports.CV_VALUE_COLUMN, condition.value)} ${condition.operator} ${valueAsJsonb})`;
176
+ }
177
+ return false;
178
+ };
179
+ exports.formatConditionsForValues = formatConditionsForValues;
180
+ const formatConditionsForEntries = (key, condition, reverseReplacementsMap) => {
181
+ const replacementKey = reverseReplacementsMap.get(key);
182
+ if (!replacementKey) {
183
+ return false;
184
+ }
185
+ if (Array.isArray(condition)) {
186
+ if (condition.length === 0) {
187
+ // if empty array, the condition is ignored
188
+ return false;
189
+ }
190
+ if ((0, exports.isConditionStringArray)(condition)) {
191
+ const values = condition.map((value) => getJSONSubQuery(value, key)).join(`${exports.OR_DELIMITER}\n`);
192
+ return `( ${values})`;
193
+ }
194
+ return condition.map((c) => getSingleConditionWithOperator(c.value, c.operator, replacementKey, reverseReplacementsMap)).join(exports.AND_DELIMITER);
195
+ }
196
+ if (typeof condition === 'string' || typeof condition === 'number') {
197
+ return getJSONSubQuery(condition, key);
198
+ }
199
+ if (condition?.operator) {
200
+ return getSingleConditionWithOperator(condition.value, condition.operator, replacementKey, reverseReplacementsMap);
201
+ }
202
+ return false;
203
+ };
204
+ exports.formatConditionsForEntries = formatConditionsForEntries;
@@ -0,0 +1,2 @@
1
+ import { customFieldsFilterScope } from './filter';
2
+ export { customFieldsFilterScope, };
@@ -1 +1,6 @@
1
- import{customFieldsFilterScope as e}from"./filter.js";export{};
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.customFieldsFilterScope = void 0;
4
+ /* eslint-disable import/prefer-default-export */
5
+ const filter_1 = require("./filter");
6
+ Object.defineProperty(exports, "customFieldsFilterScope", { enumerable: true, get: function () { return filter_1.customFieldsFilterScope; } });
@@ -0,0 +1,2 @@
1
+ declare const app: import("express-serve-static-core").Express;
2
+ export default app;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const express_1 = __importDefault(require("express"));
7
+ const node_common_1 = require("@autofleet/node-common");
8
+ const logger_1 = __importDefault(require("../../utils/logger"));
9
+ const models_1 = require("../../models");
10
+ const app = (0, express_1.default)();
11
+ app.use(express_1.default.json());
12
+ const api = (0, node_common_1.Router)({ logger: logger_1.default });
13
+ api.get('/v1/test-models', async (req, res) => {
14
+ const testModels = await models_1.TestModel.findAll();
15
+ return res.json(testModels);
16
+ });
17
+ api.get('/v1/test-models/:testModelId', async (req, res) => {
18
+ const { params: { testModelId } } = req;
19
+ const testModel = await models_1.TestModel.findByPk(testModelId);
20
+ return res.json(testModel);
21
+ });
22
+ api.post('/v1/test-models', async (req, res) => {
23
+ const { body } = req;
24
+ const testModel = await models_1.TestModel.create(body);
25
+ return res.json(testModel);
26
+ });
27
+ api.patch('/v1/test-models/:testModelId', async (req, res) => {
28
+ const { body, params: { testModelId } } = req;
29
+ const testModel = await models_1.TestModel.update(body, {
30
+ where: {
31
+ id: testModelId,
32
+ },
33
+ returning: true,
34
+ });
35
+ return res.json(testModel[1][0]);
36
+ });
37
+ app.use('/api', api);
38
+ exports.default = app;
@@ -0,0 +1,8 @@
1
+ interface CustomFieldsSearchTestFlowInput {
2
+ fieldType: string;
3
+ fieldValue: string | number;
4
+ searchTerm: string;
5
+ expectedNumberOfQueryResults: number;
6
+ }
7
+ declare const customFieldsSearchTestFlow: ({ fieldType, fieldValue, searchTerm, expectedNumberOfQueryResults, }: CustomFieldsSearchTestFlowInput) => Promise<void>;
8
+ export default customFieldsSearchTestFlow;