rez_core 7.1.4 → 7.1.5

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 (455) hide show
  1. package/.claude/settings.local.json +26 -0
  2. package/.idea/250218_nodejs_core.iml +9 -0
  3. package/.idea/codeStyles/Project.xml +58 -58
  4. package/.idea/codeStyles/codeStyleConfig.xml +4 -4
  5. package/.idea/copilot.data.migration.agent.xml +6 -0
  6. package/.idea/copilot.data.migration.ask.xml +6 -0
  7. package/.idea/copilot.data.migration.ask2agent.xml +6 -0
  8. package/.idea/copilot.data.migration.edit.xml +6 -0
  9. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  10. package/.idea/misc.xml +6 -0
  11. package/.idea/modules.xml +7 -7
  12. package/.idea/prettier.xml +6 -0
  13. package/.idea/vcs.xml +5 -5
  14. package/.prettierrc +3 -3
  15. package/README.md +99 -99
  16. package/dist/module/filter/repository/saved-filter.repository.js +0 -2
  17. package/dist/module/filter/repository/saved-filter.repository.js.map +1 -1
  18. package/dist/module/filter/service/filter.service.js +28 -33
  19. package/dist/module/filter/service/filter.service.js.map +1 -1
  20. package/dist/module/integration/examples/usage.example.js +9 -9
  21. package/dist/module/integration/service/integration.service.d.ts +1 -6
  22. package/dist/module/integration/service/integration.service.js +2 -14
  23. package/dist/module/integration/service/integration.service.js.map +1 -1
  24. package/dist/module/integration/service/oauth.service.js +0 -2
  25. package/dist/module/integration/service/oauth.service.js.map +1 -1
  26. package/dist/module/integration/service/wrapper.service.js +0 -1
  27. package/dist/module/integration/service/wrapper.service.js.map +1 -1
  28. package/dist/module/integration/strategies/email/gmail-api.strategy.js +7 -23
  29. package/dist/module/integration/strategies/email/gmail-api.strategy.js.map +1 -1
  30. package/dist/module/integration/strategies/email/sendgrid-api.strategy.js +5 -8
  31. package/dist/module/integration/strategies/email/sendgrid-api.strategy.js.map +1 -1
  32. package/dist/module/listmaster/controller/list-master.controller.d.ts +21 -6
  33. package/dist/module/listmaster/controller/list-master.controller.js +17 -6
  34. package/dist/module/listmaster/controller/list-master.controller.js.map +1 -1
  35. package/dist/module/listmaster/service/list-master.service.d.ts +9 -4
  36. package/dist/module/listmaster/service/list-master.service.js +54 -45
  37. package/dist/module/listmaster/service/list-master.service.js.map +1 -1
  38. package/dist/module/meta/controller/media.controller.d.ts +0 -3
  39. package/dist/module/meta/controller/media.controller.js +0 -27
  40. package/dist/module/meta/controller/media.controller.js.map +1 -1
  41. package/dist/module/meta/entity/media-data.entity.d.ts +0 -1
  42. package/dist/module/meta/entity/media-data.entity.js +0 -4
  43. package/dist/module/meta/entity/media-data.entity.js.map +1 -1
  44. package/dist/module/meta/repository/attribute-master.repository.js +14 -14
  45. package/dist/module/meta/service/entity-dynamic.service.js +16 -16
  46. package/dist/module/meta/service/entity-dynamic.service.js.map +1 -1
  47. package/dist/module/meta/service/entity-master.service.js +20 -20
  48. package/dist/module/meta/service/media-data.service.d.ts +0 -2
  49. package/dist/module/meta/service/media-data.service.js +0 -8
  50. package/dist/module/meta/service/media-data.service.js.map +1 -1
  51. package/dist/module/meta/service/resolver.service.js +13 -23
  52. package/dist/module/meta/service/resolver.service.js.map +1 -1
  53. package/dist/module/notification/notification.module.js +0 -2
  54. package/dist/module/notification/notification.module.js.map +1 -1
  55. package/dist/module/notification/service/notification.service.d.ts +1 -3
  56. package/dist/module/notification/service/notification.service.js +40 -27
  57. package/dist/module/notification/service/notification.service.js.map +1 -1
  58. package/dist/module/workflow/controller/workflow.controller.js +1 -1
  59. package/dist/module/workflow/controller/workflow.controller.js.map +1 -1
  60. package/dist/module/workflow/repository/action-data.repository.js +3 -10
  61. package/dist/module/workflow/repository/action-data.repository.js.map +1 -1
  62. package/dist/module/workflow/repository/action.repository.js +2 -2
  63. package/dist/module/workflow/repository/activity-log.repository.js +4 -4
  64. package/dist/module/workflow/repository/activity-log.repository.js.map +1 -1
  65. package/dist/module/workflow/repository/comm-template.repository.js +4 -4
  66. package/dist/module/workflow/repository/comm-template.repository.js.map +1 -1
  67. package/dist/module/workflow/repository/stage.repository.js +8 -8
  68. package/dist/module/workflow/repository/task.repository.js +4 -4
  69. package/dist/module/workflow/repository/task.repository.js.map +1 -1
  70. package/dist/module/workflow/service/action-template-mapping.service.js +2 -2
  71. package/dist/module/workflow/service/action.service.js +5 -5
  72. package/dist/module/workflow/service/comm-template.service.js +1 -1
  73. package/dist/module/workflow/service/comm-template.service.js.map +1 -1
  74. package/dist/module/workflow/service/entity-modification.service.d.ts +1 -4
  75. package/dist/module/workflow/service/entity-modification.service.js +5 -9
  76. package/dist/module/workflow/service/entity-modification.service.js.map +1 -1
  77. package/dist/module/workflow/service/populate-workflow.service.d.ts +1 -1
  78. package/dist/module/workflow/service/populate-workflow.service.js +24 -24
  79. package/dist/module/workflow/service/populate-workflow.service.js.map +1 -1
  80. package/dist/module/workflow/service/task.service.js +11 -10
  81. package/dist/module/workflow/service/task.service.js.map +1 -1
  82. package/dist/module/workflow/service/workflow-list-master.service.js +2 -2
  83. package/dist/module/workflow/service/workflow-list-master.service.js.map +1 -1
  84. package/dist/module/workflow-automation/service/schedule-handler.service.js +9 -9
  85. package/dist/module/workflow-automation/service/workflow-automation.service.js +6 -8
  86. package/dist/module/workflow-automation/service/workflow-automation.service.js.map +1 -1
  87. package/dist/tsconfig.build.tsbuildinfo +1 -1
  88. package/dist/utils/service/reflection-helper.service.js +2 -2
  89. package/docs/modules/event-driven-integration-design.md +91 -91
  90. package/docs/modules/integration.md +250 -250
  91. package/eslint.config.mjs +34 -34
  92. package/nest-cli.json +14 -14
  93. package/package.json +128 -128
  94. package/server.log +850 -0
  95. package/src/app.controller.ts +12 -12
  96. package/src/app.module.ts +62 -62
  97. package/src/app.service.ts +8 -8
  98. package/src/config/bull.config.ts +72 -72
  99. package/src/config/config.module.ts +17 -17
  100. package/src/config/database.config.ts +48 -48
  101. package/src/config/redis.config.ts +55 -55
  102. package/src/constant/attribute.constant.ts +8 -8
  103. package/src/constant/db-data-type.constant.ts +160 -160
  104. package/src/constant/entity.constant.ts +3 -3
  105. package/src/constant/global.constant.ts +67 -67
  106. package/src/constant/status.constant.ts +3 -3
  107. package/src/core.module.ts +96 -96
  108. package/src/decorators/roles.decorator.ts +7 -7
  109. package/src/dtos/response.dto.ts +6 -6
  110. package/src/dtos/response.ts +5 -5
  111. package/src/index.ts +1 -1
  112. package/src/module/auth/auth.module.ts +65 -65
  113. package/src/module/auth/controller/auth.controller.ts +28 -28
  114. package/src/module/auth/dto/user.dto.ts +56 -56
  115. package/src/module/auth/guards/google-auth.guard.ts +9 -9
  116. package/src/module/auth/guards/jwt.guard.ts +22 -22
  117. package/src/module/auth/services/auth.service.ts +56 -56
  118. package/src/module/auth/services/jwt.service.ts +11 -11
  119. package/src/module/auth/strategies/google.strategy.ts +54 -54
  120. package/src/module/auth/strategies/jwt.strategy.ts +65 -65
  121. package/src/module/auth/strategies/local.strategy.ts +13 -13
  122. package/src/module/dashboard/controller/dashboard.controller.ts +38 -38
  123. package/src/module/dashboard/dashboard.module.ts +19 -19
  124. package/src/module/dashboard/entity/dashboard_page_data.entity.ts +23 -23
  125. package/src/module/dashboard/entity/widget_master.entity.ts +15 -15
  126. package/src/module/dashboard/repository/dashboard.repository.ts +49 -49
  127. package/src/module/dashboard/service/dashboard.service.ts +69 -69
  128. package/src/module/eav/EAV_USAGE_GUIDE.md +351 -351
  129. package/src/module/eav/controller/eav.controller.ts +119 -119
  130. package/src/module/eav/dto/eav-operation.dto.ts +62 -62
  131. package/src/module/eav/eav.module.ts +79 -79
  132. package/src/module/eav/entity/eav-boolean.entity.ts +25 -25
  133. package/src/module/eav/entity/eav-date.entity.ts +24 -24
  134. package/src/module/eav/entity/eav-decimal.entity.ts +24 -24
  135. package/src/module/eav/entity/eav-int.entity.ts +24 -24
  136. package/src/module/eav/entity/eav-json.entity.ts +24 -24
  137. package/src/module/eav/entity/eav-text.entity.ts +24 -24
  138. package/src/module/eav/entity/eav-time.entity.ts +24 -24
  139. package/src/module/eav/entity/eav-timestamp.entity.ts +24 -24
  140. package/src/module/eav/entity/eav-varchar.entity.ts +24 -24
  141. package/src/module/eav/interface/eav-strategy.interface.ts +32 -32
  142. package/src/module/eav/repository/eav-boolean.repository.ts +67 -67
  143. package/src/module/eav/repository/eav-date.repository.ts +67 -67
  144. package/src/module/eav/repository/eav-decimal.repository.ts +67 -67
  145. package/src/module/eav/repository/eav-int.repository.ts +67 -67
  146. package/src/module/eav/repository/eav-json.repository.ts +67 -67
  147. package/src/module/eav/repository/eav-text.repository.ts +67 -67
  148. package/src/module/eav/repository/eav-time.repository.ts +67 -67
  149. package/src/module/eav/repository/eav-timestamp.repository.ts +67 -67
  150. package/src/module/eav/repository/eav-varchar.repository.ts +67 -67
  151. package/src/module/eav/service/eav-boolean.service.ts +64 -64
  152. package/src/module/eav/service/eav-date.service.ts +64 -64
  153. package/src/module/eav/service/eav-decimal.service.ts +64 -64
  154. package/src/module/eav/service/eav-factory.service.ts +93 -93
  155. package/src/module/eav/service/eav-int.service.ts +64 -64
  156. package/src/module/eav/service/eav-json.service.ts +64 -64
  157. package/src/module/eav/service/eav-text.service.ts +64 -64
  158. package/src/module/eav/service/eav-time.service.ts +64 -64
  159. package/src/module/eav/service/eav-timestamp.service.ts +64 -64
  160. package/src/module/eav/service/eav-varchar.service.ts +65 -65
  161. package/src/module/eav/service/eav.service.ts +116 -116
  162. package/src/module/entity_json/controller/entity_json.controller.ts +75 -75
  163. package/src/module/entity_json/docs/FlatJson_Filterin_System.md +2803 -2803
  164. package/src/module/entity_json/entity/entityJson.entity.ts +42 -42
  165. package/src/module/entity_json/entity_json.module.ts +22 -22
  166. package/src/module/entity_json/service/entityJson.repository.ts +37 -37
  167. package/src/module/entity_json/service/entity_json.service.ts +492 -492
  168. package/src/module/export/controller/export.controller.ts +83 -83
  169. package/src/module/export/export.module.ts +14 -14
  170. package/src/module/export/service/export.service.ts +107 -107
  171. package/src/module/filter/controller/filter.controller.ts +214 -214
  172. package/src/module/filter/dto/filter-request.dto.ts +41 -41
  173. package/src/module/filter/entity/saved-filter-detail.entity.ts +37 -37
  174. package/src/module/filter/entity/saved-filter-master.entity.ts +30 -30
  175. package/src/module/filter/filter.module.ts +33 -33
  176. package/src/module/filter/repository/saved-filter.repository.ts +247 -249
  177. package/src/module/filter/repository/saved.filter-detail.repository.ts +19 -19
  178. package/src/module/filter/service/filter-evaluator.service.ts +82 -82
  179. package/src/module/filter/service/filter.service.ts +1722 -1752
  180. package/src/module/filter/service/saved-filter.service.ts +164 -164
  181. package/src/module/ics/controller/ics.controller.ts +21 -21
  182. package/src/module/ics/dto/ics.dto.ts +55 -55
  183. package/src/module/ics/ics.module.ts +13 -13
  184. package/src/module/ics/service/ics.service.ts +57 -57
  185. package/src/module/integration/controller/calender-event.controller.ts +31 -31
  186. package/src/module/integration/controller/integration.controller.ts +662 -662
  187. package/src/module/integration/controller/wrapper.controller.ts +37 -37
  188. package/src/module/integration/dto/create-config.dto.ts +526 -526
  189. package/src/module/integration/entity/integration-config.entity.ts +112 -112
  190. package/src/module/integration/entity/integration-entity-mapper.entity.ts +14 -14
  191. package/src/module/integration/entity/integration-source.entity.ts +17 -17
  192. package/src/module/integration/entity/user-integration.entity.ts +71 -71
  193. package/src/module/integration/examples/usage.example.ts +338 -338
  194. package/src/module/integration/factories/base.factory.ts +7 -7
  195. package/src/module/integration/factories/email.factory.ts +49 -49
  196. package/src/module/integration/factories/integration.factory.ts +121 -121
  197. package/src/module/integration/factories/sms.factory.ts +51 -51
  198. package/src/module/integration/factories/telephone.factory.ts +41 -41
  199. package/src/module/integration/factories/whatsapp.factory.ts +56 -56
  200. package/src/module/integration/integration.module.ts +110 -110
  201. package/src/module/integration/service/calendar-event.service.ts +118 -118
  202. package/src/module/integration/service/integration-entity-mapper.service.ts +17 -17
  203. package/src/module/integration/service/integration-queue.service.ts +229 -229
  204. package/src/module/integration/service/integration.service.ts +2632 -2651
  205. package/src/module/integration/service/oauth.service.ts +224 -226
  206. package/src/module/integration/service/wrapper.service.ts +753 -754
  207. package/src/module/integration/strategies/email/gmail-api.strategy.ts +281 -307
  208. package/src/module/integration/strategies/email/outlook-api.strategy.ts +44 -44
  209. package/src/module/integration/strategies/email/outlook.strategy.ts +64 -64
  210. package/src/module/integration/strategies/email/sendgrid-api.strategy.ts +260 -263
  211. package/src/module/integration/strategies/integration.strategy.ts +97 -97
  212. package/src/module/integration/strategies/sms/gupshup-sms.strategy.ts +146 -146
  213. package/src/module/integration/strategies/sms/msg91-sms.strategy.ts +164 -164
  214. package/src/module/integration/strategies/sms/tubelight-sms.strategy.ts +163 -163
  215. package/src/module/integration/strategies/telephone/ozonetel-voice.strategy.ts +238 -238
  216. package/src/module/integration/strategies/telephone/tubelight-voice.strategy.ts +210 -210
  217. package/src/module/integration/strategies/whatsapp/gupshup-whatsapp.strategy.ts +359 -359
  218. package/src/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.ts +372 -372
  219. package/src/module/integration/strategies/whatsapp/whatsapp-cloud.strategy.ts +403 -403
  220. package/src/module/integration/strategies/whatsapp/whatsapp.strategy.ts +57 -57
  221. package/src/module/layout/controller/layout.controller.ts +38 -38
  222. package/src/module/layout/entity/header-items.entity.ts +28 -28
  223. package/src/module/layout/entity/header-section.entity.ts +13 -13
  224. package/src/module/layout/layout.module.ts +20 -20
  225. package/src/module/layout/repository/header-items.repository.ts +18 -18
  226. package/src/module/layout/repository/header-section.repository.ts +16 -16
  227. package/src/module/layout/service/header-section.service.ts +25 -25
  228. package/src/module/layout_preference/controller/layout_preference.controller.ts +76 -76
  229. package/src/module/layout_preference/entity/layout_preference.entity.ts +28 -28
  230. package/src/module/layout_preference/layout_preference.module.ts +22 -22
  231. package/src/module/layout_preference/repository/layout_preference.repository.ts +65 -65
  232. package/src/module/layout_preference/service/layout_preference.service.ts +191 -191
  233. package/src/module/linked_attributes/controller/linked_attributes.controller.ts +137 -137
  234. package/src/module/linked_attributes/dto/create-linked-attribute-smart.dto.ts +54 -54
  235. package/src/module/linked_attributes/entity/linked_attribute.entity.ts +51 -51
  236. package/src/module/linked_attributes/linked_attributes.module.ts +23 -23
  237. package/src/module/linked_attributes/repository/linked_attribute.repository.ts +12 -12
  238. package/src/module/linked_attributes/service/linked_attributes.service.ts +650 -650
  239. package/src/module/linked_attributes/test/linked-attributes.service.spec.ts +244 -244
  240. package/src/module/listmaster/controller/list-master.controller.ts +226 -215
  241. package/src/module/listmaster/entity/list-master-items.entity.ts +30 -30
  242. package/src/module/listmaster/entity/list-master.entity.ts +25 -25
  243. package/src/module/listmaster/listmaster.module.ts +46 -46
  244. package/src/module/listmaster/repository/list-master-items.repository.ts +262 -262
  245. package/src/module/listmaster/repository/list-master.repository.ts +60 -60
  246. package/src/module/listmaster/service/list-master-engine.ts +19 -19
  247. package/src/module/listmaster/service/list-master-extension.interface.ts +4 -4
  248. package/src/module/listmaster/service/list-master-item.service.ts +382 -382
  249. package/src/module/listmaster/service/list-master-registry.ts +15 -15
  250. package/src/module/listmaster/service/list-master.service.ts +760 -774
  251. package/src/module/mapper/controller/field-mapper.controller.ts +76 -76
  252. package/src/module/mapper/controller/mapper.controller.ts +20 -20
  253. package/src/module/mapper/dto/field-mapper.dto.ts +14 -14
  254. package/src/module/mapper/entity/field-lovs.entity.ts +15 -15
  255. package/src/module/mapper/entity/field-mapper.entity.ts +49 -49
  256. package/src/module/mapper/entity/mapper.entity.ts +9 -9
  257. package/src/module/mapper/mapper.module.ts +35 -35
  258. package/src/module/mapper/repository/field-lovs.repository.ts +35 -35
  259. package/src/module/mapper/repository/field-mapper.repository.ts +42 -42
  260. package/src/module/mapper/repository/mapper.repository.ts +32 -32
  261. package/src/module/mapper/service/field-mapper.service.ts +268 -268
  262. package/src/module/mapper/service/mapper.service.ts +80 -80
  263. package/src/module/master/controller/master.controller.ts +71 -71
  264. package/src/module/master/service/master.service.ts +460 -460
  265. package/src/module/master/service/poupulate-meta.service.ts +210 -210
  266. package/src/module/meta/controller/attribute-master.controller.ts +83 -83
  267. package/src/module/meta/controller/entity-dynamic.controller.ts +123 -123
  268. package/src/module/meta/controller/entity-master.controller.ts +41 -41
  269. package/src/module/meta/controller/entity-relation.controller.ts +36 -36
  270. package/src/module/meta/controller/entity.controller.ts +301 -301
  271. package/src/module/meta/controller/entity.public.controller.ts +76 -76
  272. package/src/module/meta/controller/media.controller.ts +135 -162
  273. package/src/module/meta/controller/meta.controller.ts +80 -80
  274. package/src/module/meta/controller/view-master.controller.ts +79 -79
  275. package/src/module/meta/dto/entity-list-data.dto.ts +6 -6
  276. package/src/module/meta/dto/entity-tab.dto.ts +4 -4
  277. package/src/module/meta/dto/entity-table.dto.ts +12 -12
  278. package/src/module/meta/entity/attribute-master.entity.ts +62 -62
  279. package/src/module/meta/entity/base-entity.entity.ts +52 -52
  280. package/src/module/meta/entity/dynamic.entity.ts +5 -5
  281. package/src/module/meta/entity/entity-master.entity.ts +53 -53
  282. package/src/module/meta/entity/entity-relation-data.entity.ts +24 -24
  283. package/src/module/meta/entity/entity-relation.entity.ts +18 -18
  284. package/src/module/meta/entity/entity-table-column.entity.ts +56 -56
  285. package/src/module/meta/entity/entity-table.entity.ts +45 -45
  286. package/src/module/meta/entity/media-data.entity.ts +32 -35
  287. package/src/module/meta/entity/preference.entity.ts +57 -57
  288. package/src/module/meta/entity/view-master.entity.ts +36 -36
  289. package/src/module/meta/entity.module.ts +153 -153
  290. package/src/module/meta/repository/attribute-master.repository.ts +206 -206
  291. package/src/module/meta/repository/entity-attribute-update.repository.ts +48 -48
  292. package/src/module/meta/repository/entity-master.repository.ts +120 -120
  293. package/src/module/meta/repository/entity-relation.repository.ts +36 -36
  294. package/src/module/meta/repository/entity-table-column.repository.ts +39 -39
  295. package/src/module/meta/repository/entity-table.repository.ts +53 -53
  296. package/src/module/meta/repository/media-data.repository.ts +50 -50
  297. package/src/module/meta/repository/preference.repository.ts +20 -20
  298. package/src/module/meta/repository/user-app-mapping.repository.ts +28 -28
  299. package/src/module/meta/repository/view-master.repository.ts +42 -42
  300. package/src/module/meta/service/attribute-master.service.ts +329 -329
  301. package/src/module/meta/service/common.service.ts +9 -9
  302. package/src/module/meta/service/entity-attribute-update.service.ts +26 -26
  303. package/src/module/meta/service/entity-dynamic.service.ts +1037 -1038
  304. package/src/module/meta/service/entity-master.service.ts +288 -288
  305. package/src/module/meta/service/entity-realation-data.service.ts +9 -9
  306. package/src/module/meta/service/entity-relation.service.ts +85 -85
  307. package/src/module/meta/service/entity-service-impl.service.ts +390 -390
  308. package/src/module/meta/service/entity-table-column.service.ts +26 -26
  309. package/src/module/meta/service/entity-table.service.ts +144 -144
  310. package/src/module/meta/service/entity-validation.service.ts +187 -187
  311. package/src/module/meta/service/entity.service.ts +48 -48
  312. package/src/module/meta/service/field-group.service.ts +103 -103
  313. package/src/module/meta/service/media-data.service.ts +385 -397
  314. package/src/module/meta/service/preference.service.ts +16 -16
  315. package/src/module/meta/service/resolver.service.ts +260 -293
  316. package/src/module/meta/service/section-master.service.ts +104 -104
  317. package/src/module/meta/service/update-form-json.service.ts +22 -22
  318. package/src/module/meta/service/user-app-mapping.service.ts +17 -17
  319. package/src/module/meta/service/view-master.service.ts +127 -127
  320. package/src/module/microservice-client/microservice-clients.module.ts +13 -13
  321. package/src/module/microservice-client/service/microservice-client-factory.ts +37 -37
  322. package/src/module/microservice-client/service/microservice-clients.ts +4 -4
  323. package/src/module/notification/controller/notification.controller.ts +58 -58
  324. package/src/module/notification/entity/notification.entity.ts +76 -76
  325. package/src/module/notification/entity/otp.entity.ts +28 -28
  326. package/src/module/notification/firebase-admin.config.ts +22 -22
  327. package/src/module/notification/notification.module.ts +63 -65
  328. package/src/module/notification/repository/otp.repository.ts +27 -27
  329. package/src/module/notification/service/email.service.ts +142 -142
  330. package/src/module/notification/service/notification.service.ts +163 -145
  331. package/src/module/preference_master/entity/preference.entity.ts +25 -25
  332. package/src/module/preference_master/preference.service.ts +27 -27
  333. package/src/module/preference_master/repo/preference.repository.ts +36 -36
  334. package/src/module/third-party-module/entity/third-party-api-registry.entity.ts +52 -52
  335. package/src/module/third-party-module/repository/third-party-api-registry.repository.ts +20 -20
  336. package/src/module/third-party-module/service/api-registry.service.ts +13 -13
  337. package/src/module/third-party-module/third-party.module.ts +12 -12
  338. package/src/module/workflow/controller/action-category.controller.ts +54 -54
  339. package/src/module/workflow/controller/action-resource-mapping.controller.ts +23 -23
  340. package/src/module/workflow/controller/action-template-mapping.controller.ts +35 -35
  341. package/src/module/workflow/controller/action.controller.ts +111 -111
  342. package/src/module/workflow/controller/activity-log.controller.ts +55 -55
  343. package/src/module/workflow/controller/comm-template.controller.ts +43 -43
  344. package/src/module/workflow/controller/entity-modification.controller.ts +35 -35
  345. package/src/module/workflow/controller/form-master.controller.ts +43 -43
  346. package/src/module/workflow/controller/stage-group.controller.ts +49 -49
  347. package/src/module/workflow/controller/stage.controller.ts +51 -51
  348. package/src/module/workflow/controller/task.controller.ts +77 -77
  349. package/src/module/workflow/controller/workflow-list-master.controller.ts +44 -44
  350. package/src/module/workflow/controller/workflow-meta.controller.ts +80 -80
  351. package/src/module/workflow/controller/workflow.controller.ts +66 -66
  352. package/src/module/workflow/entity/action-category.entity.ts +33 -33
  353. package/src/module/workflow/entity/action-data.entity.ts +51 -51
  354. package/src/module/workflow/entity/action-resources-mapping.entity.ts +21 -21
  355. package/src/module/workflow/entity/action-template-mapping.entity.ts +12 -12
  356. package/src/module/workflow/entity/action.entity.ts +48 -48
  357. package/src/module/workflow/entity/activity-log.entity.ts +39 -39
  358. package/src/module/workflow/entity/comm-template.entity.ts +38 -38
  359. package/src/module/workflow/entity/entity-modification.entity.ts +33 -33
  360. package/src/module/workflow/entity/form.entity.ts +21 -21
  361. package/src/module/workflow/entity/stage-action-mapping.entity.ts +12 -12
  362. package/src/module/workflow/entity/stage-group.entity.ts +18 -18
  363. package/src/module/workflow/entity/stage-movement-data.entity.ts +33 -33
  364. package/src/module/workflow/entity/stage.entity.ts +15 -15
  365. package/src/module/workflow/entity/task-data.entity.ts +84 -84
  366. package/src/module/workflow/entity/template-attach-mapper.entity.ts +30 -30
  367. package/src/module/workflow/entity/workflow-data.entity.ts +6 -6
  368. package/src/module/workflow/entity/workflow-level-mapping.entity.ts +18 -18
  369. package/src/module/workflow/entity/workflow.entity.ts +15 -15
  370. package/src/module/workflow/repository/action-category.repository.ts +78 -78
  371. package/src/module/workflow/repository/action-data.repository.ts +345 -353
  372. package/src/module/workflow/repository/action.repository.ts +339 -339
  373. package/src/module/workflow/repository/activity-log.repository.ts +148 -148
  374. package/src/module/workflow/repository/comm-template.repository.ts +157 -157
  375. package/src/module/workflow/repository/form-master.repository.ts +50 -50
  376. package/src/module/workflow/repository/stage-group.repository.ts +186 -186
  377. package/src/module/workflow/repository/stage-movement.repository.ts +217 -217
  378. package/src/module/workflow/repository/stage.repository.ts +160 -160
  379. package/src/module/workflow/repository/task.repository.ts +154 -156
  380. package/src/module/workflow/repository/workflow.repository.ts +42 -42
  381. package/src/module/workflow/service/action-category.service.ts +32 -32
  382. package/src/module/workflow/service/action-data.service.ts +62 -62
  383. package/src/module/workflow/service/action-resources-mapping.service.ts +10 -10
  384. package/src/module/workflow/service/action-template-mapping.service.ts +137 -137
  385. package/src/module/workflow/service/action.service.ts +300 -300
  386. package/src/module/workflow/service/activity-log.service.ts +106 -106
  387. package/src/module/workflow/service/comm-template.service.ts +179 -179
  388. package/src/module/workflow/service/entity-modification.service.ts +55 -63
  389. package/src/module/workflow/service/form-master.service.ts +35 -35
  390. package/src/module/workflow/service/populate-workflow.service.ts +313 -313
  391. package/src/module/workflow/service/stage-action-mapping.service.ts +5 -5
  392. package/src/module/workflow/service/stage-group.service.ts +325 -325
  393. package/src/module/workflow/service/stage.service.ts +196 -196
  394. package/src/module/workflow/service/task.service.ts +547 -546
  395. package/src/module/workflow/service/workflow-list-master.service.ts +68 -68
  396. package/src/module/workflow/service/workflow-meta.service.ts +638 -638
  397. package/src/module/workflow/service/workflow.service.ts +212 -212
  398. package/src/module/workflow/workflow.module.ts +180 -180
  399. package/src/module/workflow-automation/SCHEDULING_GUIDE.md +145 -145
  400. package/src/module/workflow-automation/controller/workflow-automation.controller.ts +43 -43
  401. package/src/module/workflow-automation/entity/workflow-automation-action.entity.ts +26 -26
  402. package/src/module/workflow-automation/entity/workflow-automation.entity.ts +35 -35
  403. package/src/module/workflow-automation/interface/action.decorator.ts +7 -7
  404. package/src/module/workflow-automation/interface/action.interface.ts +5 -5
  405. package/src/module/workflow-automation/service/action-registery.service.ts +35 -35
  406. package/src/module/workflow-automation/service/schedule-handler.service.ts +167 -167
  407. package/src/module/workflow-automation/service/workflow-automation-engine.service.ts +219 -219
  408. package/src/module/workflow-automation/service/workflow-automation.service.ts +486 -486
  409. package/src/module/workflow-automation/workflow-automation.module.ts +55 -55
  410. package/src/module/workflow-schedule/INSTALLATION.md +244 -244
  411. package/src/module/workflow-schedule/MULTI_PROJECT_GUIDE.md +196 -196
  412. package/src/module/workflow-schedule/README.md +422 -422
  413. package/src/module/workflow-schedule/constants/schedule.constants.ts +48 -48
  414. package/src/module/workflow-schedule/controller/workflow-schedule.controller.ts +253 -253
  415. package/src/module/workflow-schedule/docs/CLAUDE_CODE_GUIDE.md +510 -510
  416. package/src/module/workflow-schedule/docs/CLAUDE_CODE_PROMPT.md +362 -362
  417. package/src/module/workflow-schedule/docs/RUN_CLAUDE_CODE.sh +68 -68
  418. package/src/module/workflow-schedule/dto/create-schedule.dto.ts +147 -147
  419. package/src/module/workflow-schedule/dto/get-execution-logs.dto.ts +119 -119
  420. package/src/module/workflow-schedule/dto/update-schedule.dto.ts +96 -96
  421. package/src/module/workflow-schedule/entities/scheduled-workflow.entity.ts +148 -148
  422. package/src/module/workflow-schedule/entities/workflow-execution-log.entity.ts +154 -154
  423. package/src/module/workflow-schedule/interfaces/schedule-job-data.interface.ts +51 -51
  424. package/src/module/workflow-schedule/interfaces/workflow-schedule-options.interface.ts +12 -12
  425. package/src/module/workflow-schedule/processors/schedule.processor.ts +616 -616
  426. package/src/module/workflow-schedule/service/workflow-schedule.service.ts +588 -588
  427. package/src/module/workflow-schedule/workflow-schedule.module.ts +67 -67
  428. package/src/resources/dev.properties.yaml +33 -33
  429. package/src/resources/local.properties.yaml +27 -27
  430. package/src/resources/properties.module.ts +12 -12
  431. package/src/resources/properties.yaml.ts +11 -11
  432. package/src/resources/uat.properties.yaml +31 -31
  433. package/src/table.config.ts +123 -123
  434. package/src/utils/dto/excel-data.dto.ts +14 -14
  435. package/src/utils/dto/excelsheet-data.dto.ts +5 -5
  436. package/src/utils/service/base64util.service.ts +18 -18
  437. package/src/utils/service/clockIDGenUtil.service.ts +21 -21
  438. package/src/utils/service/codeGenerator.service.ts +22 -22
  439. package/src/utils/service/dateUtil.service.ts +17 -17
  440. package/src/utils/service/encryptUtil.service.ts +97 -97
  441. package/src/utils/service/excel-helper.service.ts +72 -72
  442. package/src/utils/service/excelUtil.service.ts +15 -15
  443. package/src/utils/service/file-util.service.ts +11 -11
  444. package/src/utils/service/json-util.service.ts +23 -23
  445. package/src/utils/service/loggingUtil.service.ts +88 -88
  446. package/src/utils/service/reflection-helper.service.ts +62 -62
  447. package/src/utils/service/wbsCodeGen.service.ts +8 -8
  448. package/src/utils/utils.module.ts +27 -27
  449. package/tsconfig.build.json +4 -4
  450. package/tsconfig.json +24 -24
  451. package/.idea/250218_ether_core.iml +0 -12
  452. package/dist/module/notification/repository/notification.repository.d.ts +0 -7
  453. package/dist/module/notification/repository/notification.repository.js +0 -43
  454. package/dist/module/notification/repository/notification.repository.js.map +0 -1
  455. package/src/module/notification/repository/notification.repository.ts +0 -33
@@ -1,650 +1,650 @@
1
- import { Injectable, Inject, BadRequestException, NotFoundException } from '@nestjs/common';
2
- import { EntityServiceImpl } from 'src/module/meta/service/entity-service-impl.service';
3
- import { BaseEntity, DataSource } from 'typeorm';
4
- import { LinkedAttributes } from '../entity/linked_attribute.entity';
5
- import { EntityMasterService } from 'src/module/meta/service/entity-master.service';
6
- import { AttributeMasterService } from 'src/module/meta/service/attribute-master.service';
7
- import { SavedFilterService } from 'src/module/filter/service/saved-filter.service';
8
- import { SavedFilterDetailRepository } from 'src/module/filter/repository/saved.filter-detail.repository';
9
- import { EntityJSONService } from 'src/module/entity_json/service/entity_json.service';
10
- import { CreateLinkedAttributeSmartDto } from '../dto/create-linked-attribute-smart.dto';
11
- import { EntityJson } from 'src/module/entity_json/entity/entityJson.entity';
12
- import { FilterService } from 'src/module/filter/service/filter.service';
13
-
14
- @Injectable()
15
- export class LinkedAttributesService extends EntityServiceImpl {
16
- constructor(
17
- private readonly dataSource: DataSource,
18
- @Inject('EntityMasterService')
19
- protected readonly entityMasterService: EntityMasterService,
20
- @Inject('AttributeMasterService')
21
- private readonly attributeMasterService: AttributeMasterService,
22
- @Inject('SavedFilterService')
23
- private readonly savedFilterService: SavedFilterService,
24
- private readonly entityJsonService: EntityJSONService,
25
- private readonly filterService: FilterService,
26
- ) {
27
- super();
28
- }
29
-
30
- async createEntity(payload: any, loggedInUser: any): Promise<any> {
31
- console.warn(
32
- '[DEPRECATED] Use createLinkedAttributeSmart() instead of createEntity()',
33
- );
34
-
35
- // Auto-generate attribute_key if missing OR empty
36
- if (!payload.attribute_key || payload.attribute_key.trim() === '') {
37
- payload.attribute_key = payload.field_name
38
- .trim()
39
- .toLowerCase()
40
- .replace(/\s+/g, '_');
41
- }
42
-
43
- // Pass to base class create method
44
- return super.createEntity(payload, loggedInUser);
45
- }
46
-
47
- async getAllLinkedAttributes(loggedInUser: any) {
48
- const entId = loggedInUser.enterprise_id;
49
-
50
- return this.dataSource
51
- .getRepository(LinkedAttributes)
52
- .createQueryBuilder('fla')
53
- .where('fla.enterprise_id = :entId', { entId })
54
- .getMany();
55
- }
56
-
57
- async upsertLinkedAttributes(payloadList: any[], loggedInUser: any) {
58
- const entId = loggedInUser.enterprise_id;
59
-
60
- // Step 1: Delete all existing rows for this organization
61
- await this.dataSource
62
- .createQueryBuilder()
63
- .delete()
64
- .from(LinkedAttributes)
65
- .where('enterprise_id = :entId', { entId })
66
- .execute();
67
-
68
- // Step 2: Normalize & prepare payloads
69
- const newPayloads = payloadList.map((item) => ({
70
- ...item,
71
- enterprise_id: entId,
72
- attribute_key: item.attribute_key
73
- ? item.attribute_key.trim().toLowerCase().replace(/\s+/g, '_')
74
- : item.field_name.trim().toLowerCase().replace(/\s+/g, '_'),
75
- }));
76
-
77
- // Step 3: Bulk Insert
78
- const insertResult = await this.dataSource
79
- .createQueryBuilder()
80
- .insert()
81
- .into(LinkedAttributes)
82
- .values(newPayloads)
83
- .execute();
84
-
85
- // Step 4: Return inserted list
86
- const ids = insertResult.identifiers.map((i) => i.id);
87
-
88
- return await this.dataSource
89
- .getRepository(LinkedAttributes)
90
- .createQueryBuilder('la')
91
- .where('la.id IN (:...ids)', { ids })
92
- .andWhere('la.enterprise_id = :entId', { entId })
93
- .getMany();
94
- }
95
-
96
- async getEntityListing(entity_type: string, loggedInUser: any) {
97
- const entId = loggedInUser.enterprise_id;
98
-
99
- // check if is_flag_json is true for the entity_type
100
-
101
- const entityMasterRepo =
102
- this.reflectionHelper.getRepoService('EntityMaster');
103
-
104
- const isFlagJson = await entityMasterRepo.findOne({
105
- where: {
106
- mapped_entity_type: entity_type,
107
- enterprise_id: entId,
108
- is_flag_json: true,
109
- },
110
- });
111
-
112
- if (isFlagJson?.is_flag_json) {
113
- // If is_flag_json is true, return getAllLinkedAttributes
114
- return await this.getAllLinkedAttributes(loggedInUser);
115
- }
116
-
117
- // Otherwise, return filter result
118
- return await this.filterService.applyFilterWrapper({
119
- entity_type,
120
- loggedInUser,
121
- });
122
- }
123
-
124
- /**
125
- * Generate the next sequence number for a linked attribute
126
- * @param mapped_entity_type - Main entity type (e.g., "LEAD")
127
- * @param applicable_entity_type - Source 1:M entity (e.g., "LFMG")
128
- * @param applicable_attribute_key - Source attribute (e.g., "name")
129
- * @param organization_id - Organization ID
130
- * @returns Next available sequence number
131
- */
132
- private async generateNextSequence(
133
- mapped_entity_type: string,
134
- applicable_entity_type: string,
135
- applicable_attribute_key: string,
136
- organization_id: number,
137
- ): Promise<number> {
138
- const result = await this.dataSource
139
- .getRepository(LinkedAttributes)
140
- .createQueryBuilder('fla')
141
- .select('MAX(fla.sequence)', 'max_sequence')
142
- .where('fla.mapped_entity_type = :mapped_entity_type', {
143
- mapped_entity_type,
144
- })
145
- .andWhere('fla.applicable_entity_type = :applicable_entity_type', {
146
- applicable_entity_type,
147
- })
148
- .andWhere('fla.applicable_attribute_key = :applicable_attribute_key', {
149
- applicable_attribute_key,
150
- })
151
- .andWhere('fla.organization_id = :organization_id', { organization_id })
152
- .getRawOne();
153
-
154
- const maxSequence = result?.max_sequence;
155
-
156
- // If no records exist or max is null, return 1; otherwise return max + 1
157
- return maxSequence ? maxSequence + 1 : 1;
158
- }
159
-
160
- /**
161
- * Generate a flatjson attribute key in format: ENTITY__attribute__N
162
- * @param applicable_entity_type - Entity code (e.g., "LFMG")
163
- * @param applicable_attribute_key - Attribute key (e.g., "name")
164
- * @param sequence - Sequence number (e.g., 1)
165
- * @returns Generated key (e.g., "LFMG__name__1")
166
- * @example generateAttributeKey('LFMG', 'name', 1) => 'LFMG__name__1'
167
- */
168
- public generateAttributeKey(
169
- applicable_entity_type: string,
170
- applicable_attribute_key: string,
171
- sequence: number,
172
- ): string {
173
- // Validate inputs
174
- if (!applicable_entity_type || applicable_entity_type.trim() === '') {
175
- throw new Error('applicable_entity_type is required and cannot be empty');
176
- }
177
-
178
- if (!applicable_attribute_key || applicable_attribute_key.trim() === '') {
179
- throw new Error(
180
- 'applicable_attribute_key is required and cannot be empty',
181
- );
182
- }
183
-
184
- if (!sequence || sequence < 1 || !Number.isInteger(sequence)) {
185
- throw new Error('sequence must be a positive integer greater than 0');
186
- }
187
-
188
- // Generate and return formatted key
189
- return `${applicable_entity_type}__${applicable_attribute_key}__${sequence}`;
190
- }
191
-
192
- /**
193
- * Create a SavedFilter for a linked attribute
194
- * @param entity_type - Entity type to filter (e.g., "LFMG")
195
- * @param conditions - Array of filter conditions
196
- * @param attribute_key - Linked attribute key (for naming)
197
- * @param loggedInUser - Current user context
198
- * @returns Generated filter code
199
- */
200
- private async createFilterForLinkedAttribute(
201
- entity_type: string,
202
- conditions: Array<{
203
- filter_attribute: string;
204
- filter_operator: string;
205
- filter_value: any;
206
- }>,
207
- attribute_key: string,
208
- loggedInUser: any,
209
- ): Promise<string> {
210
- return await this.dataSource.transaction(async (transactionManager) => {
211
- // Step 1: Generate unique filter code
212
- const timestamp = Date.now();
213
- const filterCode = `LA_${entity_type}_${attribute_key}_${timestamp}`;
214
-
215
- // Step 2: Create SavedFilterMaster
216
- const filterMasterData = {
217
- name: `Auto Filter - ${attribute_key}`,
218
- code: filterCode,
219
- mapped_entity_type: entity_type,
220
- filter_scope: 'FILTER' as const,
221
- organization_id: loggedInUser.organization_id,
222
- level_type: loggedInUser.level_type,
223
- level_id: loggedInUser.level_id,
224
- user_id: loggedInUser.id,
225
- };
226
-
227
- const filterMaster = await this.savedFilterService.createEntity(
228
- filterMasterData,
229
- loggedInUser,
230
- );
231
-
232
- // Step 3: Create SavedFilterDetail records
233
- const detailPromises = conditions.map((condition) => {
234
- const detailData = {
235
- mapped_filter_code: filterMaster.code,
236
- filter_entity_type: entity_type,
237
- filter_attribute: condition.filter_attribute,
238
- filter_operator: condition.filter_operator,
239
- filter_value: String(condition.filter_value),
240
- organization_id: loggedInUser.organization_id,
241
- level_type: loggedInUser.level_type,
242
- level_id: loggedInUser.level_id,
243
- };
244
-
245
- return transactionManager.save('SavedFilterDetail', detailData);
246
- });
247
-
248
- await Promise.all(detailPromises);
249
-
250
- // Step 4: Return the generated filter code
251
- return filterMaster.code;
252
- });
253
- }
254
-
255
- /**
256
- * Smart creation of linked attribute with auto-generation
257
- * @param payload - Linked attribute data
258
- * @param loggedInUser - Current user context
259
- * @returns Created LinkedAttribute entity
260
- */
261
- async createLinkedAttributeSmart(
262
- payload: CreateLinkedAttributeSmartDto,
263
- loggedInUser: any,
264
- ): Promise<LinkedAttributes> {
265
- // Step 1: Validate input
266
- const validation = await this.validateLinkedAttribute(
267
- {
268
- field_name: payload.field_name,
269
- mapped_entity_type: payload.mapped_entity_type,
270
- applicable_entity_type: payload.applicable_entity_type,
271
- applicable_attribute_key: payload.applicable_attribute_key,
272
- organization_id: loggedInUser.organization_id,
273
- },
274
- loggedInUser,
275
- );
276
-
277
- if (!validation.valid) {
278
- throw new BadRequestException(validation.errors.join(', '));
279
- }
280
-
281
- // Step 2: Generate sequence number
282
- const sequence = await this.generateNextSequence(
283
- payload.mapped_entity_type,
284
- payload.applicable_entity_type,
285
- payload.applicable_attribute_key,
286
- loggedInUser.organization_id,
287
- );
288
-
289
- // Step 3: Generate attribute_key
290
- const attribute_key = this.generateAttributeKey(
291
- payload.applicable_entity_type,
292
- payload.applicable_attribute_key,
293
- sequence,
294
- );
295
-
296
- // Step 4: Create saved filter if conditions provided
297
- let saved_filter_code: string | null = payload.saved_filter_code || null;
298
- // if (payload.filter_conditions && payload.filter_conditions.length > 0) {
299
- // saved_filter_code = await this.createFilterForLinkedAttribute(
300
- // payload.applicable_entity_type,
301
- // payload.filter_conditions,
302
- // attribute_key,
303
- // loggedInUser,
304
- // );
305
- // }
306
-
307
- // Step 5: Create LinkedAttribute entity
308
- let linkedAttrData:any = {
309
- field_name: payload.field_name,
310
- attribute_key,
311
- applicable_entity_type: payload.applicable_entity_type,
312
- applicable_attribute_key: payload.applicable_attribute_key,
313
- mapped_entity_type: payload.mapped_entity_type,
314
- saved_filter_code,
315
- sequence,
316
- organization_id: loggedInUser.organization_id,
317
- level_type: loggedInUser.level_type,
318
- level_id: loggedInUser.level_id,
319
- entity_type:'LNATR'
320
- };
321
-
322
- const linkedAttribute = (await super.createEntity(
323
- linkedAttrData,
324
- loggedInUser,
325
- )) as LinkedAttributes;
326
-
327
- // Step 6: Trigger backfill if requested (async, don't await)
328
- if (payload.backfill) {
329
- this.backfillLinkedAttribute(linkedAttribute.id, loggedInUser).catch(
330
- (err) =>
331
- console.error(
332
- `Backfill failed for linked attribute ${linkedAttribute.id}:`,
333
- err,
334
- ),
335
- );
336
- }
337
-
338
- return linkedAttribute;
339
- }
340
-
341
- /**
342
- * Validate linked attribute payload before creation
343
- * @param payload - Linked attribute data to validate
344
- * @param loggedInUser - Current user context
345
- * @returns Validation result with errors array
346
- */
347
- async validateLinkedAttribute(
348
- payload: {
349
- field_name: string;
350
- mapped_entity_type: string;
351
- applicable_entity_type: string;
352
- applicable_attribute_key: string;
353
- attribute_key?: string;
354
- organization_id: number;
355
- },
356
- loggedInUser: any,
357
- ): Promise<{ valid: boolean; errors: string[] }> {
358
- const errors: string[] = [];
359
-
360
- // Run all validations in parallel
361
- const [
362
- duplicateError,
363
- mappedEntityError,
364
- applicableEntityError,
365
- attributeError,
366
- ] = await Promise.all([
367
- this.checkDuplicateAttributeKey(
368
- payload.attribute_key,
369
- payload.organization_id,
370
- ),
371
- this.validateEntityTypeExists(
372
- payload.mapped_entity_type,
373
- loggedInUser,
374
- ),
375
- this.validateEntityTypeExists(
376
- payload.applicable_entity_type,
377
- loggedInUser,
378
- ),
379
- this.validateAttributeKeyExists(
380
- payload.applicable_entity_type,
381
- payload.applicable_attribute_key,
382
- loggedInUser,
383
- ),
384
- ]);
385
-
386
- // Collect errors
387
- if (duplicateError) errors.push(duplicateError);
388
- if (mappedEntityError) errors.push(mappedEntityError);
389
- if (applicableEntityError) errors.push(applicableEntityError);
390
- if (attributeError) errors.push(attributeError);
391
-
392
- // Validate required fields
393
- this.validateRequiredFields(payload, errors);
394
-
395
- return { valid: errors.length === 0, errors };
396
- }
397
-
398
- /**
399
- * Validate that all required fields are present and not empty
400
- * @param payload - Payload to validate
401
- * @param errors - Array to collect error messages
402
- */
403
- private validateRequiredFields(
404
- payload: {
405
- field_name: string;
406
- mapped_entity_type: string;
407
- applicable_entity_type: string;
408
- applicable_attribute_key: string;
409
- },
410
- errors: string[],
411
- ): void {
412
- const requiredFields = [
413
- { field: 'field_name', value: payload.field_name },
414
- { field: 'mapped_entity_type', value: payload.mapped_entity_type },
415
- { field: 'applicable_entity_type', value: payload.applicable_entity_type },
416
- { field: 'applicable_attribute_key', value: payload.applicable_attribute_key },
417
- ];
418
-
419
- for (const { field, value } of requiredFields) {
420
- if (!value || (typeof value === 'string' && value.trim() === '')) {
421
- errors.push(`Required field '${field}' is missing or empty`);
422
- }
423
- }
424
- }
425
-
426
- /**
427
- * Check if attribute_key already exists for the organization
428
- * @param attribute_key - Attribute key to check
429
- * @param organization_id - Organization ID
430
- * @returns Error message if duplicate exists, null otherwise
431
- */
432
- private async checkDuplicateAttributeKey(
433
- attribute_key: string | undefined,
434
- organization_id: number,
435
- ): Promise<string | null> {
436
- // Skip check if attribute_key is not provided (will be auto-generated)
437
- if (!attribute_key || attribute_key.trim() === '') {
438
- return null;
439
- }
440
-
441
- const existing = await this.dataSource
442
- .getRepository(LinkedAttributes)
443
- .createQueryBuilder('fla')
444
- .where('fla.attribute_key = :attribute_key', { attribute_key })
445
- .andWhere('fla.organization_id = :organization_id', { organization_id })
446
- .getOne();
447
-
448
- if (existing) {
449
- return `Attribute key '${attribute_key}' already exists for this organization`;
450
- }
451
-
452
- return null;
453
- }
454
-
455
- /**
456
- * Validate that entity type exists in frm_entity_master
457
- * @param entity_type - Entity type to validate
458
- * @param loggedInUser - Current user context
459
- * @returns Error message if entity doesn't exist, null otherwise
460
- */
461
- private async validateEntityTypeExists(
462
- entity_type: string,
463
- loggedInUser: any,
464
- ): Promise<string | null> {
465
- if (!entity_type || entity_type.trim() === '') {
466
- return null; // Will be caught by required field validation
467
- }
468
-
469
- try {
470
- await this.entityMasterService.getEntityData(entity_type, loggedInUser);
471
- return null; // Entity exists
472
- } catch (error) {
473
- return `Entity type '${entity_type}' does not exist`;
474
- }
475
- }
476
-
477
- /**
478
- * Validate that attribute exists in frm_attribute_master for the given entity
479
- * @param entity_type - Entity type
480
- * @param attribute_key - Attribute key to validate
481
- * @param loggedInUser - Current user context
482
- * @returns Error message if attribute doesn't exist, null otherwise
483
- */
484
- private async validateAttributeKeyExists(
485
- entity_type: string,
486
- attribute_key: string,
487
- loggedInUser: any,
488
- ): Promise<string | null> {
489
- if (!entity_type || !attribute_key) {
490
- return null; // Will be caught by required field validation
491
- }
492
-
493
- try {
494
- const attributes =
495
- await this.attributeMasterService.findAttributesByMappedEntityType(
496
- entity_type,
497
- loggedInUser,
498
- );
499
-
500
- const attributeExists = attributes.some(
501
- (attr) => attr.attribute_key === attribute_key,
502
- );
503
-
504
- if (!attributeExists) {
505
- return `Attribute '${attribute_key}' does not exist in entity '${entity_type}'`;
506
- }
507
-
508
- return null;
509
- } catch (error) {
510
- return `Error validating attribute '${attribute_key}' in entity '${entity_type}': ${error.message}`;
511
- }
512
- }
513
-
514
- /**
515
- * Backfill existing entities with a new linked attribute
516
- * @param linked_attribute_id - ID of the linked attribute to backfill
517
- * @param loggedInUser - Current user context
518
- * @returns Summary of backfill operation
519
- */
520
- async backfillLinkedAttribute(
521
- linked_attribute_id: number,
522
- loggedInUser: any,
523
- ): Promise<{
524
- total: number;
525
- updated: number;
526
- failed: number;
527
- errors: Array<{ entity_id: number; error: string }>;
528
- }> {
529
- // Step 1: Load linked attribute
530
- const linkedAttr = await this.dataSource
531
- .getRepository(LinkedAttributes)
532
- .findOne({ where: { id: linked_attribute_id } });
533
-
534
- if (!linkedAttr) {
535
- throw new NotFoundException(
536
- `LinkedAttribute with ID ${linked_attribute_id} not found`,
537
- );
538
- }
539
-
540
- // Step 2: Get all entities of this type
541
- const entityJsonRecords = await this.dataSource
542
- .getRepository(EntityJson)
543
- .createQueryBuilder('ej')
544
- .select(['ej.entity_id'])
545
- .where('ej.entity_type = :entityType', {
546
- entityType: linkedAttr.mapped_entity_type,
547
- })
548
- .andWhere('ej.organization_id = :orgId', {
549
- orgId: loggedInUser.organization_id,
550
- })
551
- .getMany();
552
-
553
- // Step 3: Process in batches
554
- const batchSize = 100;
555
- const results = {
556
- total: entityJsonRecords.length,
557
- updated: 0,
558
- failed: 0,
559
- errors: [] as Array<{ entity_id: number; error: string }>,
560
- };
561
-
562
- for (let i = 0; i < entityJsonRecords.length; i += batchSize) {
563
- const batch = entityJsonRecords.slice(i, i + batchSize);
564
-
565
- for (const record of batch) {
566
- try {
567
- await this.entityJsonService.updateEntityJSON(
568
- linkedAttr.mapped_entity_type,
569
- record.entity_id,
570
- loggedInUser,
571
- );
572
- results.updated++;
573
- } catch (error) {
574
- results.failed++;
575
- results.errors.push({
576
- entity_id: record.entity_id,
577
- error: error.message,
578
- });
579
- console.error(
580
- `Failed to update entity ${record.entity_id}:`,
581
- error,
582
- );
583
- }
584
- }
585
-
586
- // Log progress
587
- console.log(
588
- `Backfill progress: ${Math.min(i + batchSize, results.total)}/${results.total}`,
589
- );
590
- }
591
-
592
- return results;
593
- }
594
-
595
- /**
596
- * Backfill all linked attributes for an entity type
597
- * @param mapped_entity_type - Entity type to backfill
598
- * @param loggedInUser - Current user context
599
- * @returns Summary of backfill operation
600
- */
601
- async backfillAllForEntity(
602
- mapped_entity_type: string,
603
- loggedInUser: any,
604
- ): Promise<{ updated: number; failed: number }> {
605
- // Get all entities of this type
606
- const entityJsonRecords = await this.dataSource
607
- .getRepository(EntityJson)
608
- .createQueryBuilder('ej')
609
- .select(['ej.entity_id'])
610
- .where('ej.entity_type = :entityType', { entityType: mapped_entity_type })
611
- .andWhere('ej.organization_id = :orgId', {
612
- orgId: loggedInUser.organization_id,
613
- })
614
- .getMany();
615
-
616
- const batchSize = 100;
617
- const results = {
618
- updated: 0,
619
- failed: 0,
620
- };
621
-
622
- for (let i = 0; i < entityJsonRecords.length; i += batchSize) {
623
- const batch = entityJsonRecords.slice(i, i + batchSize);
624
-
625
- for (const record of batch) {
626
- try {
627
- await this.entityJsonService.updateEntityJSON(
628
- mapped_entity_type,
629
- record.entity_id,
630
- loggedInUser,
631
- );
632
- results.updated++;
633
- } catch (error) {
634
- results.failed++;
635
- console.error(
636
- `Failed to update entity ${record.entity_id}:`,
637
- error,
638
- );
639
- }
640
- }
641
-
642
- // Log progress
643
- console.log(
644
- `Backfill all progress: ${Math.min(i + batchSize, entityJsonRecords.length)}/${entityJsonRecords.length}`,
645
- );
646
- }
647
-
648
- return results;
649
- }
650
- }
1
+ import { Injectable, Inject, BadRequestException, NotFoundException } from '@nestjs/common';
2
+ import { EntityServiceImpl } from 'src/module/meta/service/entity-service-impl.service';
3
+ import { BaseEntity, DataSource } from 'typeorm';
4
+ import { LinkedAttributes } from '../entity/linked_attribute.entity';
5
+ import { EntityMasterService } from 'src/module/meta/service/entity-master.service';
6
+ import { AttributeMasterService } from 'src/module/meta/service/attribute-master.service';
7
+ import { SavedFilterService } from 'src/module/filter/service/saved-filter.service';
8
+ import { SavedFilterDetailRepository } from 'src/module/filter/repository/saved.filter-detail.repository';
9
+ import { EntityJSONService } from 'src/module/entity_json/service/entity_json.service';
10
+ import { CreateLinkedAttributeSmartDto } from '../dto/create-linked-attribute-smart.dto';
11
+ import { EntityJson } from 'src/module/entity_json/entity/entityJson.entity';
12
+ import { FilterService } from 'src/module/filter/service/filter.service';
13
+
14
+ @Injectable()
15
+ export class LinkedAttributesService extends EntityServiceImpl {
16
+ constructor(
17
+ private readonly dataSource: DataSource,
18
+ @Inject('EntityMasterService')
19
+ protected readonly entityMasterService: EntityMasterService,
20
+ @Inject('AttributeMasterService')
21
+ private readonly attributeMasterService: AttributeMasterService,
22
+ @Inject('SavedFilterService')
23
+ private readonly savedFilterService: SavedFilterService,
24
+ private readonly entityJsonService: EntityJSONService,
25
+ private readonly filterService: FilterService,
26
+ ) {
27
+ super();
28
+ }
29
+
30
+ async createEntity(payload: any, loggedInUser: any): Promise<any> {
31
+ console.warn(
32
+ '[DEPRECATED] Use createLinkedAttributeSmart() instead of createEntity()',
33
+ );
34
+
35
+ // Auto-generate attribute_key if missing OR empty
36
+ if (!payload.attribute_key || payload.attribute_key.trim() === '') {
37
+ payload.attribute_key = payload.field_name
38
+ .trim()
39
+ .toLowerCase()
40
+ .replace(/\s+/g, '_');
41
+ }
42
+
43
+ // Pass to base class create method
44
+ return super.createEntity(payload, loggedInUser);
45
+ }
46
+
47
+ async getAllLinkedAttributes(loggedInUser: any) {
48
+ const entId = loggedInUser.enterprise_id;
49
+
50
+ return this.dataSource
51
+ .getRepository(LinkedAttributes)
52
+ .createQueryBuilder('fla')
53
+ .where('fla.enterprise_id = :entId', { entId })
54
+ .getMany();
55
+ }
56
+
57
+ async upsertLinkedAttributes(payloadList: any[], loggedInUser: any) {
58
+ const entId = loggedInUser.enterprise_id;
59
+
60
+ // Step 1: Delete all existing rows for this organization
61
+ await this.dataSource
62
+ .createQueryBuilder()
63
+ .delete()
64
+ .from(LinkedAttributes)
65
+ .where('enterprise_id = :entId', { entId })
66
+ .execute();
67
+
68
+ // Step 2: Normalize & prepare payloads
69
+ const newPayloads = payloadList.map((item) => ({
70
+ ...item,
71
+ enterprise_id: entId,
72
+ attribute_key: item.attribute_key
73
+ ? item.attribute_key.trim().toLowerCase().replace(/\s+/g, '_')
74
+ : item.field_name.trim().toLowerCase().replace(/\s+/g, '_'),
75
+ }));
76
+
77
+ // Step 3: Bulk Insert
78
+ const insertResult = await this.dataSource
79
+ .createQueryBuilder()
80
+ .insert()
81
+ .into(LinkedAttributes)
82
+ .values(newPayloads)
83
+ .execute();
84
+
85
+ // Step 4: Return inserted list
86
+ const ids = insertResult.identifiers.map((i) => i.id);
87
+
88
+ return await this.dataSource
89
+ .getRepository(LinkedAttributes)
90
+ .createQueryBuilder('la')
91
+ .where('la.id IN (:...ids)', { ids })
92
+ .andWhere('la.enterprise_id = :entId', { entId })
93
+ .getMany();
94
+ }
95
+
96
+ async getEntityListing(entity_type: string, loggedInUser: any) {
97
+ const entId = loggedInUser.enterprise_id;
98
+
99
+ // check if is_flag_json is true for the entity_type
100
+
101
+ const entityMasterRepo =
102
+ this.reflectionHelper.getRepoService('EntityMaster');
103
+
104
+ const isFlagJson = await entityMasterRepo.findOne({
105
+ where: {
106
+ mapped_entity_type: entity_type,
107
+ enterprise_id: entId,
108
+ is_flag_json: true,
109
+ },
110
+ });
111
+
112
+ if (isFlagJson?.is_flag_json) {
113
+ // If is_flag_json is true, return getAllLinkedAttributes
114
+ return await this.getAllLinkedAttributes(loggedInUser);
115
+ }
116
+
117
+ // Otherwise, return filter result
118
+ return await this.filterService.applyFilterWrapper({
119
+ entity_type,
120
+ loggedInUser,
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Generate the next sequence number for a linked attribute
126
+ * @param mapped_entity_type - Main entity type (e.g., "LEAD")
127
+ * @param applicable_entity_type - Source 1:M entity (e.g., "LFMG")
128
+ * @param applicable_attribute_key - Source attribute (e.g., "name")
129
+ * @param organization_id - Organization ID
130
+ * @returns Next available sequence number
131
+ */
132
+ private async generateNextSequence(
133
+ mapped_entity_type: string,
134
+ applicable_entity_type: string,
135
+ applicable_attribute_key: string,
136
+ organization_id: number,
137
+ ): Promise<number> {
138
+ const result = await this.dataSource
139
+ .getRepository(LinkedAttributes)
140
+ .createQueryBuilder('fla')
141
+ .select('MAX(fla.sequence)', 'max_sequence')
142
+ .where('fla.mapped_entity_type = :mapped_entity_type', {
143
+ mapped_entity_type,
144
+ })
145
+ .andWhere('fla.applicable_entity_type = :applicable_entity_type', {
146
+ applicable_entity_type,
147
+ })
148
+ .andWhere('fla.applicable_attribute_key = :applicable_attribute_key', {
149
+ applicable_attribute_key,
150
+ })
151
+ .andWhere('fla.organization_id = :organization_id', { organization_id })
152
+ .getRawOne();
153
+
154
+ const maxSequence = result?.max_sequence;
155
+
156
+ // If no records exist or max is null, return 1; otherwise return max + 1
157
+ return maxSequence ? maxSequence + 1 : 1;
158
+ }
159
+
160
+ /**
161
+ * Generate a flatjson attribute key in format: ENTITY__attribute__N
162
+ * @param applicable_entity_type - Entity code (e.g., "LFMG")
163
+ * @param applicable_attribute_key - Attribute key (e.g., "name")
164
+ * @param sequence - Sequence number (e.g., 1)
165
+ * @returns Generated key (e.g., "LFMG__name__1")
166
+ * @example generateAttributeKey('LFMG', 'name', 1) => 'LFMG__name__1'
167
+ */
168
+ public generateAttributeKey(
169
+ applicable_entity_type: string,
170
+ applicable_attribute_key: string,
171
+ sequence: number,
172
+ ): string {
173
+ // Validate inputs
174
+ if (!applicable_entity_type || applicable_entity_type.trim() === '') {
175
+ throw new Error('applicable_entity_type is required and cannot be empty');
176
+ }
177
+
178
+ if (!applicable_attribute_key || applicable_attribute_key.trim() === '') {
179
+ throw new Error(
180
+ 'applicable_attribute_key is required and cannot be empty',
181
+ );
182
+ }
183
+
184
+ if (!sequence || sequence < 1 || !Number.isInteger(sequence)) {
185
+ throw new Error('sequence must be a positive integer greater than 0');
186
+ }
187
+
188
+ // Generate and return formatted key
189
+ return `${applicable_entity_type}__${applicable_attribute_key}__${sequence}`;
190
+ }
191
+
192
+ /**
193
+ * Create a SavedFilter for a linked attribute
194
+ * @param entity_type - Entity type to filter (e.g., "LFMG")
195
+ * @param conditions - Array of filter conditions
196
+ * @param attribute_key - Linked attribute key (for naming)
197
+ * @param loggedInUser - Current user context
198
+ * @returns Generated filter code
199
+ */
200
+ private async createFilterForLinkedAttribute(
201
+ entity_type: string,
202
+ conditions: Array<{
203
+ filter_attribute: string;
204
+ filter_operator: string;
205
+ filter_value: any;
206
+ }>,
207
+ attribute_key: string,
208
+ loggedInUser: any,
209
+ ): Promise<string> {
210
+ return await this.dataSource.transaction(async (transactionManager) => {
211
+ // Step 1: Generate unique filter code
212
+ const timestamp = Date.now();
213
+ const filterCode = `LA_${entity_type}_${attribute_key}_${timestamp}`;
214
+
215
+ // Step 2: Create SavedFilterMaster
216
+ const filterMasterData = {
217
+ name: `Auto Filter - ${attribute_key}`,
218
+ code: filterCode,
219
+ mapped_entity_type: entity_type,
220
+ filter_scope: 'FILTER' as const,
221
+ organization_id: loggedInUser.organization_id,
222
+ level_type: loggedInUser.level_type,
223
+ level_id: loggedInUser.level_id,
224
+ user_id: loggedInUser.id,
225
+ };
226
+
227
+ const filterMaster = await this.savedFilterService.createEntity(
228
+ filterMasterData,
229
+ loggedInUser,
230
+ );
231
+
232
+ // Step 3: Create SavedFilterDetail records
233
+ const detailPromises = conditions.map((condition) => {
234
+ const detailData = {
235
+ mapped_filter_code: filterMaster.code,
236
+ filter_entity_type: entity_type,
237
+ filter_attribute: condition.filter_attribute,
238
+ filter_operator: condition.filter_operator,
239
+ filter_value: String(condition.filter_value),
240
+ organization_id: loggedInUser.organization_id,
241
+ level_type: loggedInUser.level_type,
242
+ level_id: loggedInUser.level_id,
243
+ };
244
+
245
+ return transactionManager.save('SavedFilterDetail', detailData);
246
+ });
247
+
248
+ await Promise.all(detailPromises);
249
+
250
+ // Step 4: Return the generated filter code
251
+ return filterMaster.code;
252
+ });
253
+ }
254
+
255
+ /**
256
+ * Smart creation of linked attribute with auto-generation
257
+ * @param payload - Linked attribute data
258
+ * @param loggedInUser - Current user context
259
+ * @returns Created LinkedAttribute entity
260
+ */
261
+ async createLinkedAttributeSmart(
262
+ payload: CreateLinkedAttributeSmartDto,
263
+ loggedInUser: any,
264
+ ): Promise<LinkedAttributes> {
265
+ // Step 1: Validate input
266
+ const validation = await this.validateLinkedAttribute(
267
+ {
268
+ field_name: payload.field_name,
269
+ mapped_entity_type: payload.mapped_entity_type,
270
+ applicable_entity_type: payload.applicable_entity_type,
271
+ applicable_attribute_key: payload.applicable_attribute_key,
272
+ organization_id: loggedInUser.organization_id,
273
+ },
274
+ loggedInUser,
275
+ );
276
+
277
+ if (!validation.valid) {
278
+ throw new BadRequestException(validation.errors.join(', '));
279
+ }
280
+
281
+ // Step 2: Generate sequence number
282
+ const sequence = await this.generateNextSequence(
283
+ payload.mapped_entity_type,
284
+ payload.applicable_entity_type,
285
+ payload.applicable_attribute_key,
286
+ loggedInUser.organization_id,
287
+ );
288
+
289
+ // Step 3: Generate attribute_key
290
+ const attribute_key = this.generateAttributeKey(
291
+ payload.applicable_entity_type,
292
+ payload.applicable_attribute_key,
293
+ sequence,
294
+ );
295
+
296
+ // Step 4: Create saved filter if conditions provided
297
+ let saved_filter_code: string | null = payload.saved_filter_code || null;
298
+ // if (payload.filter_conditions && payload.filter_conditions.length > 0) {
299
+ // saved_filter_code = await this.createFilterForLinkedAttribute(
300
+ // payload.applicable_entity_type,
301
+ // payload.filter_conditions,
302
+ // attribute_key,
303
+ // loggedInUser,
304
+ // );
305
+ // }
306
+
307
+ // Step 5: Create LinkedAttribute entity
308
+ let linkedAttrData:any = {
309
+ field_name: payload.field_name,
310
+ attribute_key,
311
+ applicable_entity_type: payload.applicable_entity_type,
312
+ applicable_attribute_key: payload.applicable_attribute_key,
313
+ mapped_entity_type: payload.mapped_entity_type,
314
+ saved_filter_code,
315
+ sequence,
316
+ organization_id: loggedInUser.organization_id,
317
+ level_type: loggedInUser.level_type,
318
+ level_id: loggedInUser.level_id,
319
+ entity_type:'LNATR'
320
+ };
321
+
322
+ const linkedAttribute = (await super.createEntity(
323
+ linkedAttrData,
324
+ loggedInUser,
325
+ )) as LinkedAttributes;
326
+
327
+ // Step 6: Trigger backfill if requested (async, don't await)
328
+ if (payload.backfill) {
329
+ this.backfillLinkedAttribute(linkedAttribute.id, loggedInUser).catch(
330
+ (err) =>
331
+ console.error(
332
+ `Backfill failed for linked attribute ${linkedAttribute.id}:`,
333
+ err,
334
+ ),
335
+ );
336
+ }
337
+
338
+ return linkedAttribute;
339
+ }
340
+
341
+ /**
342
+ * Validate linked attribute payload before creation
343
+ * @param payload - Linked attribute data to validate
344
+ * @param loggedInUser - Current user context
345
+ * @returns Validation result with errors array
346
+ */
347
+ async validateLinkedAttribute(
348
+ payload: {
349
+ field_name: string;
350
+ mapped_entity_type: string;
351
+ applicable_entity_type: string;
352
+ applicable_attribute_key: string;
353
+ attribute_key?: string;
354
+ organization_id: number;
355
+ },
356
+ loggedInUser: any,
357
+ ): Promise<{ valid: boolean; errors: string[] }> {
358
+ const errors: string[] = [];
359
+
360
+ // Run all validations in parallel
361
+ const [
362
+ duplicateError,
363
+ mappedEntityError,
364
+ applicableEntityError,
365
+ attributeError,
366
+ ] = await Promise.all([
367
+ this.checkDuplicateAttributeKey(
368
+ payload.attribute_key,
369
+ payload.organization_id,
370
+ ),
371
+ this.validateEntityTypeExists(
372
+ payload.mapped_entity_type,
373
+ loggedInUser,
374
+ ),
375
+ this.validateEntityTypeExists(
376
+ payload.applicable_entity_type,
377
+ loggedInUser,
378
+ ),
379
+ this.validateAttributeKeyExists(
380
+ payload.applicable_entity_type,
381
+ payload.applicable_attribute_key,
382
+ loggedInUser,
383
+ ),
384
+ ]);
385
+
386
+ // Collect errors
387
+ if (duplicateError) errors.push(duplicateError);
388
+ if (mappedEntityError) errors.push(mappedEntityError);
389
+ if (applicableEntityError) errors.push(applicableEntityError);
390
+ if (attributeError) errors.push(attributeError);
391
+
392
+ // Validate required fields
393
+ this.validateRequiredFields(payload, errors);
394
+
395
+ return { valid: errors.length === 0, errors };
396
+ }
397
+
398
+ /**
399
+ * Validate that all required fields are present and not empty
400
+ * @param payload - Payload to validate
401
+ * @param errors - Array to collect error messages
402
+ */
403
+ private validateRequiredFields(
404
+ payload: {
405
+ field_name: string;
406
+ mapped_entity_type: string;
407
+ applicable_entity_type: string;
408
+ applicable_attribute_key: string;
409
+ },
410
+ errors: string[],
411
+ ): void {
412
+ const requiredFields = [
413
+ { field: 'field_name', value: payload.field_name },
414
+ { field: 'mapped_entity_type', value: payload.mapped_entity_type },
415
+ { field: 'applicable_entity_type', value: payload.applicable_entity_type },
416
+ { field: 'applicable_attribute_key', value: payload.applicable_attribute_key },
417
+ ];
418
+
419
+ for (const { field, value } of requiredFields) {
420
+ if (!value || (typeof value === 'string' && value.trim() === '')) {
421
+ errors.push(`Required field '${field}' is missing or empty`);
422
+ }
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Check if attribute_key already exists for the organization
428
+ * @param attribute_key - Attribute key to check
429
+ * @param organization_id - Organization ID
430
+ * @returns Error message if duplicate exists, null otherwise
431
+ */
432
+ private async checkDuplicateAttributeKey(
433
+ attribute_key: string | undefined,
434
+ organization_id: number,
435
+ ): Promise<string | null> {
436
+ // Skip check if attribute_key is not provided (will be auto-generated)
437
+ if (!attribute_key || attribute_key.trim() === '') {
438
+ return null;
439
+ }
440
+
441
+ const existing = await this.dataSource
442
+ .getRepository(LinkedAttributes)
443
+ .createQueryBuilder('fla')
444
+ .where('fla.attribute_key = :attribute_key', { attribute_key })
445
+ .andWhere('fla.organization_id = :organization_id', { organization_id })
446
+ .getOne();
447
+
448
+ if (existing) {
449
+ return `Attribute key '${attribute_key}' already exists for this organization`;
450
+ }
451
+
452
+ return null;
453
+ }
454
+
455
+ /**
456
+ * Validate that entity type exists in frm_entity_master
457
+ * @param entity_type - Entity type to validate
458
+ * @param loggedInUser - Current user context
459
+ * @returns Error message if entity doesn't exist, null otherwise
460
+ */
461
+ private async validateEntityTypeExists(
462
+ entity_type: string,
463
+ loggedInUser: any,
464
+ ): Promise<string | null> {
465
+ if (!entity_type || entity_type.trim() === '') {
466
+ return null; // Will be caught by required field validation
467
+ }
468
+
469
+ try {
470
+ await this.entityMasterService.getEntityData(entity_type, loggedInUser);
471
+ return null; // Entity exists
472
+ } catch (error) {
473
+ return `Entity type '${entity_type}' does not exist`;
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Validate that attribute exists in frm_attribute_master for the given entity
479
+ * @param entity_type - Entity type
480
+ * @param attribute_key - Attribute key to validate
481
+ * @param loggedInUser - Current user context
482
+ * @returns Error message if attribute doesn't exist, null otherwise
483
+ */
484
+ private async validateAttributeKeyExists(
485
+ entity_type: string,
486
+ attribute_key: string,
487
+ loggedInUser: any,
488
+ ): Promise<string | null> {
489
+ if (!entity_type || !attribute_key) {
490
+ return null; // Will be caught by required field validation
491
+ }
492
+
493
+ try {
494
+ const attributes =
495
+ await this.attributeMasterService.findAttributesByMappedEntityType(
496
+ entity_type,
497
+ loggedInUser,
498
+ );
499
+
500
+ const attributeExists = attributes.some(
501
+ (attr) => attr.attribute_key === attribute_key,
502
+ );
503
+
504
+ if (!attributeExists) {
505
+ return `Attribute '${attribute_key}' does not exist in entity '${entity_type}'`;
506
+ }
507
+
508
+ return null;
509
+ } catch (error) {
510
+ return `Error validating attribute '${attribute_key}' in entity '${entity_type}': ${error.message}`;
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Backfill existing entities with a new linked attribute
516
+ * @param linked_attribute_id - ID of the linked attribute to backfill
517
+ * @param loggedInUser - Current user context
518
+ * @returns Summary of backfill operation
519
+ */
520
+ async backfillLinkedAttribute(
521
+ linked_attribute_id: number,
522
+ loggedInUser: any,
523
+ ): Promise<{
524
+ total: number;
525
+ updated: number;
526
+ failed: number;
527
+ errors: Array<{ entity_id: number; error: string }>;
528
+ }> {
529
+ // Step 1: Load linked attribute
530
+ const linkedAttr = await this.dataSource
531
+ .getRepository(LinkedAttributes)
532
+ .findOne({ where: { id: linked_attribute_id } });
533
+
534
+ if (!linkedAttr) {
535
+ throw new NotFoundException(
536
+ `LinkedAttribute with ID ${linked_attribute_id} not found`,
537
+ );
538
+ }
539
+
540
+ // Step 2: Get all entities of this type
541
+ const entityJsonRecords = await this.dataSource
542
+ .getRepository(EntityJson)
543
+ .createQueryBuilder('ej')
544
+ .select(['ej.entity_id'])
545
+ .where('ej.entity_type = :entityType', {
546
+ entityType: linkedAttr.mapped_entity_type,
547
+ })
548
+ .andWhere('ej.organization_id = :orgId', {
549
+ orgId: loggedInUser.organization_id,
550
+ })
551
+ .getMany();
552
+
553
+ // Step 3: Process in batches
554
+ const batchSize = 100;
555
+ const results = {
556
+ total: entityJsonRecords.length,
557
+ updated: 0,
558
+ failed: 0,
559
+ errors: [] as Array<{ entity_id: number; error: string }>,
560
+ };
561
+
562
+ for (let i = 0; i < entityJsonRecords.length; i += batchSize) {
563
+ const batch = entityJsonRecords.slice(i, i + batchSize);
564
+
565
+ for (const record of batch) {
566
+ try {
567
+ await this.entityJsonService.updateEntityJSON(
568
+ linkedAttr.mapped_entity_type,
569
+ record.entity_id,
570
+ loggedInUser,
571
+ );
572
+ results.updated++;
573
+ } catch (error) {
574
+ results.failed++;
575
+ results.errors.push({
576
+ entity_id: record.entity_id,
577
+ error: error.message,
578
+ });
579
+ console.error(
580
+ `Failed to update entity ${record.entity_id}:`,
581
+ error,
582
+ );
583
+ }
584
+ }
585
+
586
+ // Log progress
587
+ console.log(
588
+ `Backfill progress: ${Math.min(i + batchSize, results.total)}/${results.total}`,
589
+ );
590
+ }
591
+
592
+ return results;
593
+ }
594
+
595
+ /**
596
+ * Backfill all linked attributes for an entity type
597
+ * @param mapped_entity_type - Entity type to backfill
598
+ * @param loggedInUser - Current user context
599
+ * @returns Summary of backfill operation
600
+ */
601
+ async backfillAllForEntity(
602
+ mapped_entity_type: string,
603
+ loggedInUser: any,
604
+ ): Promise<{ updated: number; failed: number }> {
605
+ // Get all entities of this type
606
+ const entityJsonRecords = await this.dataSource
607
+ .getRepository(EntityJson)
608
+ .createQueryBuilder('ej')
609
+ .select(['ej.entity_id'])
610
+ .where('ej.entity_type = :entityType', { entityType: mapped_entity_type })
611
+ .andWhere('ej.organization_id = :orgId', {
612
+ orgId: loggedInUser.organization_id,
613
+ })
614
+ .getMany();
615
+
616
+ const batchSize = 100;
617
+ const results = {
618
+ updated: 0,
619
+ failed: 0,
620
+ };
621
+
622
+ for (let i = 0; i < entityJsonRecords.length; i += batchSize) {
623
+ const batch = entityJsonRecords.slice(i, i + batchSize);
624
+
625
+ for (const record of batch) {
626
+ try {
627
+ await this.entityJsonService.updateEntityJSON(
628
+ mapped_entity_type,
629
+ record.entity_id,
630
+ loggedInUser,
631
+ );
632
+ results.updated++;
633
+ } catch (error) {
634
+ results.failed++;
635
+ console.error(
636
+ `Failed to update entity ${record.entity_id}:`,
637
+ error,
638
+ );
639
+ }
640
+ }
641
+
642
+ // Log progress
643
+ console.log(
644
+ `Backfill all progress: ${Math.min(i + batchSize, entityJsonRecords.length)}/${entityJsonRecords.length}`,
645
+ );
646
+ }
647
+
648
+ return results;
649
+ }
650
+ }