rez_core 7.1.3 → 7.1.4

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/.idea/250218_ether_core.iml +12 -0
  2. package/.idea/codeStyles/Project.xml +58 -58
  3. package/.idea/codeStyles/codeStyleConfig.xml +4 -4
  4. package/.idea/modules.xml +7 -7
  5. package/.idea/vcs.xml +5 -5
  6. package/.prettierrc +3 -3
  7. package/README.md +99 -99
  8. package/dist/module/filter/repository/saved-filter.repository.js +2 -0
  9. package/dist/module/filter/repository/saved-filter.repository.js.map +1 -1
  10. package/dist/module/filter/service/filter.service.js +33 -28
  11. package/dist/module/filter/service/filter.service.js.map +1 -1
  12. package/dist/module/integration/examples/usage.example.js +9 -9
  13. package/dist/module/integration/service/integration.service.d.ts +6 -1
  14. package/dist/module/integration/service/integration.service.js +14 -2
  15. package/dist/module/integration/service/integration.service.js.map +1 -1
  16. package/dist/module/integration/service/oauth.service.js +2 -0
  17. package/dist/module/integration/service/oauth.service.js.map +1 -1
  18. package/dist/module/integration/service/wrapper.service.js +1 -0
  19. package/dist/module/integration/service/wrapper.service.js.map +1 -1
  20. package/dist/module/integration/strategies/email/gmail-api.strategy.js +23 -7
  21. package/dist/module/integration/strategies/email/gmail-api.strategy.js.map +1 -1
  22. package/dist/module/integration/strategies/email/sendgrid-api.strategy.js +8 -5
  23. package/dist/module/integration/strategies/email/sendgrid-api.strategy.js.map +1 -1
  24. package/dist/module/listmaster/controller/list-master.controller.d.ts +6 -21
  25. package/dist/module/listmaster/controller/list-master.controller.js +6 -17
  26. package/dist/module/listmaster/controller/list-master.controller.js.map +1 -1
  27. package/dist/module/listmaster/service/list-master.service.d.ts +4 -9
  28. package/dist/module/listmaster/service/list-master.service.js +45 -54
  29. package/dist/module/listmaster/service/list-master.service.js.map +1 -1
  30. package/dist/module/meta/controller/media.controller.d.ts +3 -0
  31. package/dist/module/meta/controller/media.controller.js +27 -0
  32. package/dist/module/meta/controller/media.controller.js.map +1 -1
  33. package/dist/module/meta/entity/media-data.entity.d.ts +1 -0
  34. package/dist/module/meta/entity/media-data.entity.js +4 -0
  35. package/dist/module/meta/entity/media-data.entity.js.map +1 -1
  36. package/dist/module/meta/repository/attribute-master.repository.js +14 -14
  37. package/dist/module/meta/service/entity-dynamic.service.js +16 -16
  38. package/dist/module/meta/service/entity-dynamic.service.js.map +1 -1
  39. package/dist/module/meta/service/entity-master.service.js +20 -20
  40. package/dist/module/meta/service/media-data.service.d.ts +2 -0
  41. package/dist/module/meta/service/media-data.service.js +8 -0
  42. package/dist/module/meta/service/media-data.service.js.map +1 -1
  43. package/dist/module/meta/service/resolver.service.js +23 -13
  44. package/dist/module/meta/service/resolver.service.js.map +1 -1
  45. package/dist/module/notification/notification.module.js +2 -0
  46. package/dist/module/notification/notification.module.js.map +1 -1
  47. package/dist/module/notification/repository/notification.repository.d.ts +7 -0
  48. package/dist/module/notification/repository/notification.repository.js +43 -0
  49. package/dist/module/notification/repository/notification.repository.js.map +1 -0
  50. package/dist/module/notification/service/notification.service.d.ts +3 -1
  51. package/dist/module/notification/service/notification.service.js +27 -40
  52. package/dist/module/notification/service/notification.service.js.map +1 -1
  53. package/dist/module/workflow/controller/workflow.controller.js +1 -1
  54. package/dist/module/workflow/controller/workflow.controller.js.map +1 -1
  55. package/dist/module/workflow/repository/action-data.repository.js +10 -3
  56. package/dist/module/workflow/repository/action-data.repository.js.map +1 -1
  57. package/dist/module/workflow/repository/action.repository.js +2 -2
  58. package/dist/module/workflow/repository/activity-log.repository.js +4 -4
  59. package/dist/module/workflow/repository/activity-log.repository.js.map +1 -1
  60. package/dist/module/workflow/repository/comm-template.repository.js +4 -4
  61. package/dist/module/workflow/repository/comm-template.repository.js.map +1 -1
  62. package/dist/module/workflow/repository/stage.repository.js +8 -8
  63. package/dist/module/workflow/repository/task.repository.js +4 -4
  64. package/dist/module/workflow/repository/task.repository.js.map +1 -1
  65. package/dist/module/workflow/service/action-template-mapping.service.js +2 -2
  66. package/dist/module/workflow/service/action.service.js +5 -5
  67. package/dist/module/workflow/service/comm-template.service.js +1 -1
  68. package/dist/module/workflow/service/comm-template.service.js.map +1 -1
  69. package/dist/module/workflow/service/entity-modification.service.d.ts +4 -1
  70. package/dist/module/workflow/service/entity-modification.service.js +9 -5
  71. package/dist/module/workflow/service/entity-modification.service.js.map +1 -1
  72. package/dist/module/workflow/service/populate-workflow.service.d.ts +1 -1
  73. package/dist/module/workflow/service/populate-workflow.service.js +24 -24
  74. package/dist/module/workflow/service/populate-workflow.service.js.map +1 -1
  75. package/dist/module/workflow/service/task.service.js +10 -11
  76. package/dist/module/workflow/service/task.service.js.map +1 -1
  77. package/dist/module/workflow/service/workflow-list-master.service.js +2 -2
  78. package/dist/module/workflow/service/workflow-list-master.service.js.map +1 -1
  79. package/dist/module/workflow-automation/service/schedule-handler.service.js +9 -9
  80. package/dist/module/workflow-automation/service/workflow-automation.service.js +8 -6
  81. package/dist/module/workflow-automation/service/workflow-automation.service.js.map +1 -1
  82. package/dist/tsconfig.build.tsbuildinfo +1 -1
  83. package/dist/utils/service/reflection-helper.service.js +2 -2
  84. package/docs/modules/event-driven-integration-design.md +91 -91
  85. package/docs/modules/integration.md +250 -250
  86. package/eslint.config.mjs +34 -34
  87. package/nest-cli.json +14 -14
  88. package/package.json +128 -128
  89. package/src/app.controller.ts +12 -12
  90. package/src/app.module.ts +62 -62
  91. package/src/app.service.ts +8 -8
  92. package/src/config/bull.config.ts +72 -72
  93. package/src/config/config.module.ts +17 -17
  94. package/src/config/database.config.ts +48 -48
  95. package/src/config/redis.config.ts +55 -55
  96. package/src/constant/attribute.constant.ts +8 -8
  97. package/src/constant/db-data-type.constant.ts +160 -160
  98. package/src/constant/entity.constant.ts +3 -3
  99. package/src/constant/global.constant.ts +67 -67
  100. package/src/constant/status.constant.ts +3 -3
  101. package/src/core.module.ts +96 -96
  102. package/src/decorators/roles.decorator.ts +7 -7
  103. package/src/dtos/response.dto.ts +6 -6
  104. package/src/dtos/response.ts +5 -5
  105. package/src/index.ts +1 -1
  106. package/src/module/auth/auth.module.ts +65 -65
  107. package/src/module/auth/controller/auth.controller.ts +28 -28
  108. package/src/module/auth/dto/user.dto.ts +56 -56
  109. package/src/module/auth/guards/google-auth.guard.ts +9 -9
  110. package/src/module/auth/guards/jwt.guard.ts +22 -22
  111. package/src/module/auth/services/auth.service.ts +56 -56
  112. package/src/module/auth/services/jwt.service.ts +11 -11
  113. package/src/module/auth/strategies/google.strategy.ts +54 -54
  114. package/src/module/auth/strategies/jwt.strategy.ts +65 -65
  115. package/src/module/auth/strategies/local.strategy.ts +13 -13
  116. package/src/module/dashboard/controller/dashboard.controller.ts +38 -38
  117. package/src/module/dashboard/dashboard.module.ts +19 -19
  118. package/src/module/dashboard/entity/dashboard_page_data.entity.ts +23 -23
  119. package/src/module/dashboard/entity/widget_master.entity.ts +15 -15
  120. package/src/module/dashboard/repository/dashboard.repository.ts +49 -49
  121. package/src/module/dashboard/service/dashboard.service.ts +69 -69
  122. package/src/module/eav/EAV_USAGE_GUIDE.md +351 -351
  123. package/src/module/eav/controller/eav.controller.ts +119 -119
  124. package/src/module/eav/dto/eav-operation.dto.ts +62 -62
  125. package/src/module/eav/eav.module.ts +79 -79
  126. package/src/module/eav/entity/eav-boolean.entity.ts +25 -25
  127. package/src/module/eav/entity/eav-date.entity.ts +24 -24
  128. package/src/module/eav/entity/eav-decimal.entity.ts +24 -24
  129. package/src/module/eav/entity/eav-int.entity.ts +24 -24
  130. package/src/module/eav/entity/eav-json.entity.ts +24 -24
  131. package/src/module/eav/entity/eav-text.entity.ts +24 -24
  132. package/src/module/eav/entity/eav-time.entity.ts +24 -24
  133. package/src/module/eav/entity/eav-timestamp.entity.ts +24 -24
  134. package/src/module/eav/entity/eav-varchar.entity.ts +24 -24
  135. package/src/module/eav/interface/eav-strategy.interface.ts +32 -32
  136. package/src/module/eav/repository/eav-boolean.repository.ts +67 -67
  137. package/src/module/eav/repository/eav-date.repository.ts +67 -67
  138. package/src/module/eav/repository/eav-decimal.repository.ts +67 -67
  139. package/src/module/eav/repository/eav-int.repository.ts +67 -67
  140. package/src/module/eav/repository/eav-json.repository.ts +67 -67
  141. package/src/module/eav/repository/eav-text.repository.ts +67 -67
  142. package/src/module/eav/repository/eav-time.repository.ts +67 -67
  143. package/src/module/eav/repository/eav-timestamp.repository.ts +67 -67
  144. package/src/module/eav/repository/eav-varchar.repository.ts +67 -67
  145. package/src/module/eav/service/eav-boolean.service.ts +64 -64
  146. package/src/module/eav/service/eav-date.service.ts +64 -64
  147. package/src/module/eav/service/eav-decimal.service.ts +64 -64
  148. package/src/module/eav/service/eav-factory.service.ts +93 -93
  149. package/src/module/eav/service/eav-int.service.ts +64 -64
  150. package/src/module/eav/service/eav-json.service.ts +64 -64
  151. package/src/module/eav/service/eav-text.service.ts +64 -64
  152. package/src/module/eav/service/eav-time.service.ts +64 -64
  153. package/src/module/eav/service/eav-timestamp.service.ts +64 -64
  154. package/src/module/eav/service/eav-varchar.service.ts +65 -65
  155. package/src/module/eav/service/eav.service.ts +116 -116
  156. package/src/module/entity_json/controller/entity_json.controller.ts +75 -75
  157. package/src/module/entity_json/docs/FlatJson_Filterin_System.md +2803 -2803
  158. package/src/module/entity_json/entity/entityJson.entity.ts +42 -42
  159. package/src/module/entity_json/entity_json.module.ts +22 -22
  160. package/src/module/entity_json/service/entityJson.repository.ts +37 -37
  161. package/src/module/entity_json/service/entity_json.service.ts +492 -492
  162. package/src/module/export/controller/export.controller.ts +83 -83
  163. package/src/module/export/export.module.ts +14 -14
  164. package/src/module/export/service/export.service.ts +107 -107
  165. package/src/module/filter/controller/filter.controller.ts +214 -214
  166. package/src/module/filter/dto/filter-request.dto.ts +41 -41
  167. package/src/module/filter/entity/saved-filter-detail.entity.ts +37 -37
  168. package/src/module/filter/entity/saved-filter-master.entity.ts +30 -30
  169. package/src/module/filter/filter.module.ts +33 -33
  170. package/src/module/filter/repository/saved-filter.repository.ts +249 -247
  171. package/src/module/filter/repository/saved.filter-detail.repository.ts +19 -19
  172. package/src/module/filter/service/filter-evaluator.service.ts +82 -82
  173. package/src/module/filter/service/filter.service.ts +1752 -1722
  174. package/src/module/filter/service/saved-filter.service.ts +164 -164
  175. package/src/module/ics/controller/ics.controller.ts +21 -21
  176. package/src/module/ics/dto/ics.dto.ts +55 -55
  177. package/src/module/ics/ics.module.ts +13 -13
  178. package/src/module/ics/service/ics.service.ts +57 -57
  179. package/src/module/integration/controller/calender-event.controller.ts +31 -31
  180. package/src/module/integration/controller/integration.controller.ts +662 -662
  181. package/src/module/integration/controller/wrapper.controller.ts +37 -37
  182. package/src/module/integration/dto/create-config.dto.ts +526 -526
  183. package/src/module/integration/entity/integration-config.entity.ts +112 -112
  184. package/src/module/integration/entity/integration-entity-mapper.entity.ts +14 -14
  185. package/src/module/integration/entity/integration-source.entity.ts +17 -17
  186. package/src/module/integration/entity/user-integration.entity.ts +71 -71
  187. package/src/module/integration/examples/usage.example.ts +338 -338
  188. package/src/module/integration/factories/base.factory.ts +7 -7
  189. package/src/module/integration/factories/email.factory.ts +49 -49
  190. package/src/module/integration/factories/integration.factory.ts +121 -121
  191. package/src/module/integration/factories/sms.factory.ts +51 -51
  192. package/src/module/integration/factories/telephone.factory.ts +41 -41
  193. package/src/module/integration/factories/whatsapp.factory.ts +56 -56
  194. package/src/module/integration/integration.module.ts +110 -110
  195. package/src/module/integration/service/calendar-event.service.ts +118 -118
  196. package/src/module/integration/service/integration-entity-mapper.service.ts +17 -17
  197. package/src/module/integration/service/integration-queue.service.ts +229 -229
  198. package/src/module/integration/service/integration.service.ts +2651 -2632
  199. package/src/module/integration/service/oauth.service.ts +226 -224
  200. package/src/module/integration/service/wrapper.service.ts +754 -753
  201. package/src/module/integration/strategies/email/gmail-api.strategy.ts +307 -281
  202. package/src/module/integration/strategies/email/outlook-api.strategy.ts +44 -44
  203. package/src/module/integration/strategies/email/outlook.strategy.ts +64 -64
  204. package/src/module/integration/strategies/email/sendgrid-api.strategy.ts +263 -260
  205. package/src/module/integration/strategies/integration.strategy.ts +97 -97
  206. package/src/module/integration/strategies/sms/gupshup-sms.strategy.ts +146 -146
  207. package/src/module/integration/strategies/sms/msg91-sms.strategy.ts +164 -164
  208. package/src/module/integration/strategies/sms/tubelight-sms.strategy.ts +163 -163
  209. package/src/module/integration/strategies/telephone/ozonetel-voice.strategy.ts +238 -238
  210. package/src/module/integration/strategies/telephone/tubelight-voice.strategy.ts +210 -210
  211. package/src/module/integration/strategies/whatsapp/gupshup-whatsapp.strategy.ts +359 -359
  212. package/src/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.ts +372 -372
  213. package/src/module/integration/strategies/whatsapp/whatsapp-cloud.strategy.ts +403 -403
  214. package/src/module/integration/strategies/whatsapp/whatsapp.strategy.ts +57 -57
  215. package/src/module/layout/controller/layout.controller.ts +38 -38
  216. package/src/module/layout/entity/header-items.entity.ts +28 -28
  217. package/src/module/layout/entity/header-section.entity.ts +13 -13
  218. package/src/module/layout/layout.module.ts +20 -20
  219. package/src/module/layout/repository/header-items.repository.ts +18 -18
  220. package/src/module/layout/repository/header-section.repository.ts +16 -16
  221. package/src/module/layout/service/header-section.service.ts +25 -25
  222. package/src/module/layout_preference/controller/layout_preference.controller.ts +76 -76
  223. package/src/module/layout_preference/entity/layout_preference.entity.ts +28 -28
  224. package/src/module/layout_preference/layout_preference.module.ts +22 -22
  225. package/src/module/layout_preference/repository/layout_preference.repository.ts +65 -65
  226. package/src/module/layout_preference/service/layout_preference.service.ts +191 -191
  227. package/src/module/linked_attributes/controller/linked_attributes.controller.ts +137 -137
  228. package/src/module/linked_attributes/dto/create-linked-attribute-smart.dto.ts +54 -54
  229. package/src/module/linked_attributes/entity/linked_attribute.entity.ts +51 -51
  230. package/src/module/linked_attributes/linked_attributes.module.ts +23 -23
  231. package/src/module/linked_attributes/repository/linked_attribute.repository.ts +12 -12
  232. package/src/module/linked_attributes/service/linked_attributes.service.ts +650 -650
  233. package/src/module/linked_attributes/test/linked-attributes.service.spec.ts +244 -244
  234. package/src/module/listmaster/controller/list-master.controller.ts +215 -226
  235. package/src/module/listmaster/entity/list-master-items.entity.ts +30 -30
  236. package/src/module/listmaster/entity/list-master.entity.ts +25 -25
  237. package/src/module/listmaster/listmaster.module.ts +46 -46
  238. package/src/module/listmaster/repository/list-master-items.repository.ts +262 -262
  239. package/src/module/listmaster/repository/list-master.repository.ts +60 -60
  240. package/src/module/listmaster/service/list-master-engine.ts +19 -19
  241. package/src/module/listmaster/service/list-master-extension.interface.ts +4 -4
  242. package/src/module/listmaster/service/list-master-item.service.ts +382 -382
  243. package/src/module/listmaster/service/list-master-registry.ts +15 -15
  244. package/src/module/listmaster/service/list-master.service.ts +774 -760
  245. package/src/module/mapper/controller/field-mapper.controller.ts +76 -76
  246. package/src/module/mapper/controller/mapper.controller.ts +20 -20
  247. package/src/module/mapper/dto/field-mapper.dto.ts +14 -14
  248. package/src/module/mapper/entity/field-lovs.entity.ts +15 -15
  249. package/src/module/mapper/entity/field-mapper.entity.ts +49 -49
  250. package/src/module/mapper/entity/mapper.entity.ts +9 -9
  251. package/src/module/mapper/mapper.module.ts +35 -35
  252. package/src/module/mapper/repository/field-lovs.repository.ts +35 -35
  253. package/src/module/mapper/repository/field-mapper.repository.ts +42 -42
  254. package/src/module/mapper/repository/mapper.repository.ts +32 -32
  255. package/src/module/mapper/service/field-mapper.service.ts +268 -268
  256. package/src/module/mapper/service/mapper.service.ts +80 -80
  257. package/src/module/master/controller/master.controller.ts +71 -71
  258. package/src/module/master/service/master.service.ts +460 -460
  259. package/src/module/master/service/poupulate-meta.service.ts +210 -210
  260. package/src/module/meta/controller/attribute-master.controller.ts +83 -83
  261. package/src/module/meta/controller/entity-dynamic.controller.ts +123 -123
  262. package/src/module/meta/controller/entity-master.controller.ts +41 -41
  263. package/src/module/meta/controller/entity-relation.controller.ts +36 -36
  264. package/src/module/meta/controller/entity.controller.ts +301 -301
  265. package/src/module/meta/controller/entity.public.controller.ts +76 -76
  266. package/src/module/meta/controller/media.controller.ts +162 -135
  267. package/src/module/meta/controller/meta.controller.ts +80 -80
  268. package/src/module/meta/controller/view-master.controller.ts +79 -79
  269. package/src/module/meta/dto/entity-list-data.dto.ts +6 -6
  270. package/src/module/meta/dto/entity-tab.dto.ts +4 -4
  271. package/src/module/meta/dto/entity-table.dto.ts +12 -12
  272. package/src/module/meta/entity/attribute-master.entity.ts +62 -62
  273. package/src/module/meta/entity/base-entity.entity.ts +52 -52
  274. package/src/module/meta/entity/dynamic.entity.ts +5 -5
  275. package/src/module/meta/entity/entity-master.entity.ts +53 -53
  276. package/src/module/meta/entity/entity-relation-data.entity.ts +24 -24
  277. package/src/module/meta/entity/entity-relation.entity.ts +18 -18
  278. package/src/module/meta/entity/entity-table-column.entity.ts +56 -56
  279. package/src/module/meta/entity/entity-table.entity.ts +45 -45
  280. package/src/module/meta/entity/media-data.entity.ts +35 -32
  281. package/src/module/meta/entity/preference.entity.ts +57 -57
  282. package/src/module/meta/entity/view-master.entity.ts +36 -36
  283. package/src/module/meta/entity.module.ts +153 -153
  284. package/src/module/meta/repository/attribute-master.repository.ts +206 -206
  285. package/src/module/meta/repository/entity-attribute-update.repository.ts +48 -48
  286. package/src/module/meta/repository/entity-master.repository.ts +120 -120
  287. package/src/module/meta/repository/entity-relation.repository.ts +36 -36
  288. package/src/module/meta/repository/entity-table-column.repository.ts +39 -39
  289. package/src/module/meta/repository/entity-table.repository.ts +53 -53
  290. package/src/module/meta/repository/media-data.repository.ts +50 -50
  291. package/src/module/meta/repository/preference.repository.ts +20 -20
  292. package/src/module/meta/repository/user-app-mapping.repository.ts +28 -28
  293. package/src/module/meta/repository/view-master.repository.ts +42 -42
  294. package/src/module/meta/service/attribute-master.service.ts +329 -329
  295. package/src/module/meta/service/common.service.ts +9 -9
  296. package/src/module/meta/service/entity-attribute-update.service.ts +26 -26
  297. package/src/module/meta/service/entity-dynamic.service.ts +1038 -1037
  298. package/src/module/meta/service/entity-master.service.ts +288 -288
  299. package/src/module/meta/service/entity-realation-data.service.ts +9 -9
  300. package/src/module/meta/service/entity-relation.service.ts +85 -85
  301. package/src/module/meta/service/entity-service-impl.service.ts +390 -390
  302. package/src/module/meta/service/entity-table-column.service.ts +26 -26
  303. package/src/module/meta/service/entity-table.service.ts +144 -144
  304. package/src/module/meta/service/entity-validation.service.ts +187 -187
  305. package/src/module/meta/service/entity.service.ts +48 -48
  306. package/src/module/meta/service/field-group.service.ts +103 -103
  307. package/src/module/meta/service/media-data.service.ts +397 -385
  308. package/src/module/meta/service/preference.service.ts +16 -16
  309. package/src/module/meta/service/resolver.service.ts +293 -260
  310. package/src/module/meta/service/section-master.service.ts +104 -104
  311. package/src/module/meta/service/update-form-json.service.ts +22 -22
  312. package/src/module/meta/service/user-app-mapping.service.ts +17 -17
  313. package/src/module/meta/service/view-master.service.ts +127 -127
  314. package/src/module/microservice-client/microservice-clients.module.ts +13 -13
  315. package/src/module/microservice-client/service/microservice-client-factory.ts +37 -37
  316. package/src/module/microservice-client/service/microservice-clients.ts +4 -4
  317. package/src/module/notification/controller/notification.controller.ts +58 -58
  318. package/src/module/notification/entity/notification.entity.ts +76 -76
  319. package/src/module/notification/entity/otp.entity.ts +28 -28
  320. package/src/module/notification/firebase-admin.config.ts +22 -22
  321. package/src/module/notification/notification.module.ts +65 -63
  322. package/src/module/notification/repository/notification.repository.ts +33 -0
  323. package/src/module/notification/repository/otp.repository.ts +27 -27
  324. package/src/module/notification/service/email.service.ts +142 -142
  325. package/src/module/notification/service/notification.service.ts +145 -163
  326. package/src/module/preference_master/entity/preference.entity.ts +25 -25
  327. package/src/module/preference_master/preference.service.ts +27 -27
  328. package/src/module/preference_master/repo/preference.repository.ts +36 -36
  329. package/src/module/third-party-module/entity/third-party-api-registry.entity.ts +52 -52
  330. package/src/module/third-party-module/repository/third-party-api-registry.repository.ts +20 -20
  331. package/src/module/third-party-module/service/api-registry.service.ts +13 -13
  332. package/src/module/third-party-module/third-party.module.ts +12 -12
  333. package/src/module/workflow/controller/action-category.controller.ts +54 -54
  334. package/src/module/workflow/controller/action-resource-mapping.controller.ts +23 -23
  335. package/src/module/workflow/controller/action-template-mapping.controller.ts +35 -35
  336. package/src/module/workflow/controller/action.controller.ts +111 -111
  337. package/src/module/workflow/controller/activity-log.controller.ts +55 -55
  338. package/src/module/workflow/controller/comm-template.controller.ts +43 -43
  339. package/src/module/workflow/controller/entity-modification.controller.ts +35 -35
  340. package/src/module/workflow/controller/form-master.controller.ts +43 -43
  341. package/src/module/workflow/controller/stage-group.controller.ts +49 -49
  342. package/src/module/workflow/controller/stage.controller.ts +51 -51
  343. package/src/module/workflow/controller/task.controller.ts +77 -77
  344. package/src/module/workflow/controller/workflow-list-master.controller.ts +44 -44
  345. package/src/module/workflow/controller/workflow-meta.controller.ts +80 -80
  346. package/src/module/workflow/controller/workflow.controller.ts +66 -66
  347. package/src/module/workflow/entity/action-category.entity.ts +33 -33
  348. package/src/module/workflow/entity/action-data.entity.ts +51 -51
  349. package/src/module/workflow/entity/action-resources-mapping.entity.ts +21 -21
  350. package/src/module/workflow/entity/action-template-mapping.entity.ts +12 -12
  351. package/src/module/workflow/entity/action.entity.ts +48 -48
  352. package/src/module/workflow/entity/activity-log.entity.ts +39 -39
  353. package/src/module/workflow/entity/comm-template.entity.ts +38 -38
  354. package/src/module/workflow/entity/entity-modification.entity.ts +33 -33
  355. package/src/module/workflow/entity/form.entity.ts +21 -21
  356. package/src/module/workflow/entity/stage-action-mapping.entity.ts +12 -12
  357. package/src/module/workflow/entity/stage-group.entity.ts +18 -18
  358. package/src/module/workflow/entity/stage-movement-data.entity.ts +33 -33
  359. package/src/module/workflow/entity/stage.entity.ts +15 -15
  360. package/src/module/workflow/entity/task-data.entity.ts +84 -84
  361. package/src/module/workflow/entity/template-attach-mapper.entity.ts +30 -30
  362. package/src/module/workflow/entity/workflow-data.entity.ts +6 -6
  363. package/src/module/workflow/entity/workflow-level-mapping.entity.ts +18 -18
  364. package/src/module/workflow/entity/workflow.entity.ts +15 -15
  365. package/src/module/workflow/repository/action-category.repository.ts +78 -78
  366. package/src/module/workflow/repository/action-data.repository.ts +353 -345
  367. package/src/module/workflow/repository/action.repository.ts +339 -339
  368. package/src/module/workflow/repository/activity-log.repository.ts +148 -148
  369. package/src/module/workflow/repository/comm-template.repository.ts +157 -157
  370. package/src/module/workflow/repository/form-master.repository.ts +50 -50
  371. package/src/module/workflow/repository/stage-group.repository.ts +186 -186
  372. package/src/module/workflow/repository/stage-movement.repository.ts +217 -217
  373. package/src/module/workflow/repository/stage.repository.ts +160 -160
  374. package/src/module/workflow/repository/task.repository.ts +156 -154
  375. package/src/module/workflow/repository/workflow.repository.ts +42 -42
  376. package/src/module/workflow/service/action-category.service.ts +32 -32
  377. package/src/module/workflow/service/action-data.service.ts +62 -62
  378. package/src/module/workflow/service/action-resources-mapping.service.ts +10 -10
  379. package/src/module/workflow/service/action-template-mapping.service.ts +137 -137
  380. package/src/module/workflow/service/action.service.ts +300 -300
  381. package/src/module/workflow/service/activity-log.service.ts +106 -106
  382. package/src/module/workflow/service/comm-template.service.ts +179 -179
  383. package/src/module/workflow/service/entity-modification.service.ts +63 -55
  384. package/src/module/workflow/service/form-master.service.ts +35 -35
  385. package/src/module/workflow/service/populate-workflow.service.ts +313 -313
  386. package/src/module/workflow/service/stage-action-mapping.service.ts +5 -5
  387. package/src/module/workflow/service/stage-group.service.ts +325 -325
  388. package/src/module/workflow/service/stage.service.ts +196 -196
  389. package/src/module/workflow/service/task.service.ts +546 -547
  390. package/src/module/workflow/service/workflow-list-master.service.ts +68 -68
  391. package/src/module/workflow/service/workflow-meta.service.ts +638 -638
  392. package/src/module/workflow/service/workflow.service.ts +212 -212
  393. package/src/module/workflow/workflow.module.ts +180 -180
  394. package/src/module/workflow-automation/SCHEDULING_GUIDE.md +145 -145
  395. package/src/module/workflow-automation/controller/workflow-automation.controller.ts +43 -43
  396. package/src/module/workflow-automation/entity/workflow-automation-action.entity.ts +26 -26
  397. package/src/module/workflow-automation/entity/workflow-automation.entity.ts +35 -35
  398. package/src/module/workflow-automation/interface/action.decorator.ts +7 -7
  399. package/src/module/workflow-automation/interface/action.interface.ts +5 -5
  400. package/src/module/workflow-automation/service/action-registery.service.ts +35 -35
  401. package/src/module/workflow-automation/service/schedule-handler.service.ts +167 -167
  402. package/src/module/workflow-automation/service/workflow-automation-engine.service.ts +219 -219
  403. package/src/module/workflow-automation/service/workflow-automation.service.ts +486 -486
  404. package/src/module/workflow-automation/workflow-automation.module.ts +55 -55
  405. package/src/module/workflow-schedule/INSTALLATION.md +244 -244
  406. package/src/module/workflow-schedule/MULTI_PROJECT_GUIDE.md +196 -196
  407. package/src/module/workflow-schedule/README.md +422 -422
  408. package/src/module/workflow-schedule/constants/schedule.constants.ts +48 -48
  409. package/src/module/workflow-schedule/controller/workflow-schedule.controller.ts +253 -253
  410. package/src/module/workflow-schedule/docs/CLAUDE_CODE_GUIDE.md +510 -510
  411. package/src/module/workflow-schedule/docs/CLAUDE_CODE_PROMPT.md +362 -362
  412. package/src/module/workflow-schedule/docs/RUN_CLAUDE_CODE.sh +68 -68
  413. package/src/module/workflow-schedule/dto/create-schedule.dto.ts +147 -147
  414. package/src/module/workflow-schedule/dto/get-execution-logs.dto.ts +119 -119
  415. package/src/module/workflow-schedule/dto/update-schedule.dto.ts +96 -96
  416. package/src/module/workflow-schedule/entities/scheduled-workflow.entity.ts +148 -148
  417. package/src/module/workflow-schedule/entities/workflow-execution-log.entity.ts +154 -154
  418. package/src/module/workflow-schedule/interfaces/schedule-job-data.interface.ts +51 -51
  419. package/src/module/workflow-schedule/interfaces/workflow-schedule-options.interface.ts +12 -12
  420. package/src/module/workflow-schedule/processors/schedule.processor.ts +616 -616
  421. package/src/module/workflow-schedule/service/workflow-schedule.service.ts +588 -588
  422. package/src/module/workflow-schedule/workflow-schedule.module.ts +67 -67
  423. package/src/resources/dev.properties.yaml +33 -33
  424. package/src/resources/local.properties.yaml +27 -27
  425. package/src/resources/properties.module.ts +12 -12
  426. package/src/resources/properties.yaml.ts +11 -11
  427. package/src/resources/uat.properties.yaml +31 -31
  428. package/src/table.config.ts +123 -123
  429. package/src/utils/dto/excel-data.dto.ts +14 -14
  430. package/src/utils/dto/excelsheet-data.dto.ts +5 -5
  431. package/src/utils/service/base64util.service.ts +18 -18
  432. package/src/utils/service/clockIDGenUtil.service.ts +21 -21
  433. package/src/utils/service/codeGenerator.service.ts +22 -22
  434. package/src/utils/service/dateUtil.service.ts +17 -17
  435. package/src/utils/service/encryptUtil.service.ts +97 -97
  436. package/src/utils/service/excel-helper.service.ts +72 -72
  437. package/src/utils/service/excelUtil.service.ts +15 -15
  438. package/src/utils/service/file-util.service.ts +11 -11
  439. package/src/utils/service/json-util.service.ts +23 -23
  440. package/src/utils/service/loggingUtil.service.ts +88 -88
  441. package/src/utils/service/reflection-helper.service.ts +62 -62
  442. package/src/utils/service/wbsCodeGen.service.ts +8 -8
  443. package/src/utils/utils.module.ts +27 -27
  444. package/tsconfig.build.json +4 -4
  445. package/tsconfig.json +24 -24
  446. package/.claude/settings.local.json +0 -26
  447. package/.idea/250218_nodejs_core.iml +0 -9
  448. package/.idea/copilot.data.migration.agent.xml +0 -6
  449. package/.idea/copilot.data.migration.ask.xml +0 -6
  450. package/.idea/copilot.data.migration.ask2agent.xml +0 -6
  451. package/.idea/copilot.data.migration.edit.xml +0 -6
  452. package/.idea/inspectionProfiles/Project_Default.xml +0 -6
  453. package/.idea/misc.xml +0 -6
  454. package/.idea/prettier.xml +0 -6
  455. package/server.log +0 -850
@@ -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
+ }