@solidstarters/solid-core 1.2.135 → 1.2.137

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 (215) hide show
  1. package/dist/controllers/ai-interaction.controller.d.ts +3 -1
  2. package/dist/controllers/ai-interaction.controller.d.ts.map +1 -1
  3. package/dist/controllers/ai-interaction.controller.js +27 -3
  4. package/dist/controllers/ai-interaction.controller.js.map +1 -1
  5. package/dist/controllers/dashboard-question-sql-dataset-config.controller.d.ts +43 -0
  6. package/dist/controllers/dashboard-question-sql-dataset-config.controller.d.ts.map +1 -0
  7. package/dist/controllers/{question-sql-dataset-config.controller.js → dashboard-question-sql-dataset-config.controller.js} +30 -30
  8. package/dist/controllers/dashboard-question-sql-dataset-config.controller.js.map +1 -0
  9. package/dist/controllers/dashboard-question.controller.d.ts +45 -0
  10. package/dist/controllers/dashboard-question.controller.d.ts.map +1 -0
  11. package/dist/controllers/{question.controller.js → dashboard-question.controller.js} +31 -31
  12. package/dist/controllers/dashboard-question.controller.js.map +1 -0
  13. package/dist/dtos/{create-question-sql-dataset-config.dto.d.ts → create-dashboard-question-sql-dataset-config.dto.d.ts} +2 -2
  14. package/dist/dtos/create-dashboard-question-sql-dataset-config.dto.d.ts.map +1 -0
  15. package/dist/dtos/{create-question-sql-dataset-config.dto.js → create-dashboard-question-sql-dataset-config.dto.js} +13 -13
  16. package/dist/dtos/create-dashboard-question-sql-dataset-config.dto.js.map +1 -0
  17. package/dist/dtos/create-dashboard-question.dto.d.ts +17 -0
  18. package/dist/dtos/create-dashboard-question.dto.d.ts.map +1 -0
  19. package/dist/dtos/{create-question.dto.js → create-dashboard-question.dto.js} +25 -19
  20. package/dist/dtos/create-dashboard-question.dto.js.map +1 -0
  21. package/dist/dtos/create-dashboard.dto.d.ts +2 -2
  22. package/dist/dtos/create-dashboard.dto.d.ts.map +1 -1
  23. package/dist/dtos/create-dashboard.dto.js +3 -3
  24. package/dist/dtos/create-dashboard.dto.js.map +1 -1
  25. package/dist/dtos/{update-question-sql-dataset-config.dto.d.ts → update-dashboard-question-sql-dataset-config.dto.d.ts} +2 -2
  26. package/dist/dtos/update-dashboard-question-sql-dataset-config.dto.d.ts.map +1 -0
  27. package/dist/dtos/{update-question-sql-dataset-config.dto.js → update-dashboard-question-sql-dataset-config.dto.js} +14 -14
  28. package/dist/dtos/update-dashboard-question-sql-dataset-config.dto.js.map +1 -0
  29. package/dist/dtos/update-dashboard-question.dto.d.ts +18 -0
  30. package/dist/dtos/update-dashboard-question.dto.d.ts.map +1 -0
  31. package/dist/dtos/{update-question.dto.js → update-dashboard-question.dto.js} +26 -20
  32. package/dist/dtos/update-dashboard-question.dto.js.map +1 -0
  33. package/dist/dtos/update-dashboard.dto.d.ts +2 -2
  34. package/dist/dtos/update-dashboard.dto.d.ts.map +1 -1
  35. package/dist/dtos/update-dashboard.dto.js +3 -3
  36. package/dist/dtos/update-dashboard.dto.js.map +1 -1
  37. package/dist/entities/dashboard-question-sql-dataset-config.entity.d.ts +13 -0
  38. package/dist/entities/dashboard-question-sql-dataset-config.entity.d.ts.map +1 -0
  39. package/dist/entities/{question-sql-dataset-config.entity.js → dashboard-question-sql-dataset-config.entity.js} +19 -19
  40. package/dist/entities/dashboard-question-sql-dataset-config.entity.js.map +1 -0
  41. package/dist/entities/dashboard-question.entity.d.ts +16 -0
  42. package/dist/entities/dashboard-question.entity.d.ts.map +1 -0
  43. package/dist/entities/{question.entity.js → dashboard-question.entity.js} +23 -19
  44. package/dist/entities/dashboard-question.entity.js.map +1 -0
  45. package/dist/entities/dashboard.entity.d.ts +2 -2
  46. package/dist/entities/dashboard.entity.d.ts.map +1 -1
  47. package/dist/entities/dashboard.entity.js +3 -3
  48. package/dist/entities/dashboard.entity.js.map +1 -1
  49. package/dist/index.d.ts +7 -2
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +7 -2
  52. package/dist/index.js.map +1 -1
  53. package/dist/interfaces.d.ts +21 -2
  54. package/dist/interfaces.d.ts.map +1 -1
  55. package/dist/interfaces.js.map +1 -1
  56. package/dist/jobs/database/trigger-mcp-client-publisher-database.service.d.ts +11 -0
  57. package/dist/jobs/database/trigger-mcp-client-publisher-database.service.d.ts.map +1 -0
  58. package/dist/jobs/database/trigger-mcp-client-publisher-database.service.js +39 -0
  59. package/dist/jobs/database/trigger-mcp-client-publisher-database.service.js.map +1 -0
  60. package/dist/jobs/database/trigger-mcp-client-queue-options.d.ts +8 -0
  61. package/dist/jobs/database/trigger-mcp-client-queue-options.d.ts.map +1 -0
  62. package/dist/jobs/database/trigger-mcp-client-queue-options.js +10 -0
  63. package/dist/jobs/database/trigger-mcp-client-queue-options.js.map +1 -0
  64. package/dist/jobs/database/trigger-mcp-client-subscriber-database.service.d.ts +16 -0
  65. package/dist/jobs/database/trigger-mcp-client-subscriber-database.service.d.ts.map +1 -0
  66. package/dist/jobs/database/trigger-mcp-client-subscriber-database.service.js +91 -0
  67. package/dist/jobs/database/trigger-mcp-client-subscriber-database.service.js.map +1 -0
  68. package/dist/repository/dashboard.repository.d.ts +1 -3
  69. package/dist/repository/dashboard.repository.d.ts.map +1 -1
  70. package/dist/repository/dashboard.repository.js +42 -37
  71. package/dist/repository/dashboard.repository.js.map +1 -1
  72. package/dist/seeders/seed-data/solid-core-metadata.json +88 -131
  73. package/dist/services/ai-interaction.service.d.ts +13 -2
  74. package/dist/services/ai-interaction.service.d.ts.map +1 -1
  75. package/dist/services/ai-interaction.service.js +84 -19
  76. package/dist/services/ai-interaction.service.js.map +1 -1
  77. package/dist/services/chatter-message.service.d.ts.map +1 -1
  78. package/dist/services/chatter-message.service.js +8 -6
  79. package/dist/services/chatter-message.service.js.map +1 -1
  80. package/dist/services/{question-sql-dataset-config.service.d.ts → dashboard-question-sql-dataset-config.service.d.ts} +5 -5
  81. package/dist/services/dashboard-question-sql-dataset-config.service.d.ts.map +1 -0
  82. package/dist/services/{question-sql-dataset-config.service.js → dashboard-question-sql-dataset-config.service.js} +9 -9
  83. package/dist/services/dashboard-question-sql-dataset-config.service.js.map +1 -0
  84. package/dist/services/{question.service.d.ts → dashboard-question.service.d.ts} +5 -5
  85. package/dist/services/dashboard-question.service.d.ts.map +1 -0
  86. package/dist/services/{question.service.js → dashboard-question.service.js} +10 -10
  87. package/dist/services/dashboard-question.service.js.map +1 -0
  88. package/dist/services/field-metadata.service.d.ts.map +1 -1
  89. package/dist/services/field-metadata.service.js +1 -0
  90. package/dist/services/field-metadata.service.js.map +1 -1
  91. package/dist/services/import-transaction.service.d.ts +3 -1
  92. package/dist/services/import-transaction.service.d.ts.map +1 -1
  93. package/dist/services/import-transaction.service.js +22 -0
  94. package/dist/services/import-transaction.service.js.map +1 -1
  95. package/dist/services/list-of-values.service.d.ts +1 -0
  96. package/dist/services/list-of-values.service.d.ts.map +1 -1
  97. package/dist/services/list-of-values.service.js +3 -0
  98. package/dist/services/list-of-values.service.js.map +1 -1
  99. package/dist/services/mcp-tool-response-handlers/mcp-tool-response-handler-factory.service.d.ts +9 -0
  100. package/dist/services/mcp-tool-response-handlers/mcp-tool-response-handler-factory.service.d.ts.map +1 -0
  101. package/dist/services/mcp-tool-response-handlers/mcp-tool-response-handler-factory.service.js +40 -0
  102. package/dist/services/mcp-tool-response-handlers/mcp-tool-response-handler-factory.service.js.map +1 -0
  103. package/dist/services/mcp-tool-response-handlers/solid-create-module-mcp-tool-response-handler.service.d.ts +11 -0
  104. package/dist/services/mcp-tool-response-handlers/solid-create-module-mcp-tool-response-handler.service.d.ts.map +1 -0
  105. package/dist/services/mcp-tool-response-handlers/solid-create-module-mcp-tool-response-handler.service.js +46 -0
  106. package/dist/services/mcp-tool-response-handlers/solid-create-module-mcp-tool-response-handler.service.js.map +1 -0
  107. package/dist/services/module-metadata.service.d.ts.map +1 -1
  108. package/dist/services/module-metadata.service.js.map +1 -1
  109. package/dist/services/question-data-providers/chartjs-sql-data-provider.service.d.ts +2 -2
  110. package/dist/services/question-data-providers/chartjs-sql-data-provider.service.d.ts.map +1 -1
  111. package/dist/services/question-data-providers/chartjs-sql-data-provider.service.js +11 -7
  112. package/dist/services/question-data-providers/chartjs-sql-data-provider.service.js.map +1 -1
  113. package/dist/services/question-data-providers/helpers.d.ts +5 -2
  114. package/dist/services/question-data-providers/helpers.d.ts.map +1 -1
  115. package/dist/services/question-data-providers/helpers.js +18 -3
  116. package/dist/services/question-data-providers/helpers.js.map +1 -1
  117. package/dist/services/question-data-providers/prime-react-datatable-sql-data-provider.service.d.ts +2 -2
  118. package/dist/services/question-data-providers/prime-react-datatable-sql-data-provider.service.d.ts.map +1 -1
  119. package/dist/services/question-data-providers/prime-react-datatable-sql-data-provider.service.js +10 -4
  120. package/dist/services/question-data-providers/prime-react-datatable-sql-data-provider.service.js.map +1 -1
  121. package/dist/services/question-data-providers/prime-react-meter-group-sql-data-provider.service.d.ts +2 -2
  122. package/dist/services/question-data-providers/prime-react-meter-group-sql-data-provider.service.d.ts.map +1 -1
  123. package/dist/services/question-data-providers/prime-react-meter-group-sql-data-provider.service.js +11 -3
  124. package/dist/services/question-data-providers/prime-react-meter-group-sql-data-provider.service.js.map +1 -1
  125. package/dist/services/queues/publisher-factory.service.js +1 -1
  126. package/dist/services/queues/publisher-factory.service.js.map +1 -1
  127. package/dist/services/scheduled-jobs/scheduled-job.interface.d.ts +1 -1
  128. package/dist/services/scheduled-jobs/scheduled-job.interface.d.ts.map +1 -1
  129. package/dist/services/scheduled-jobs/scheduled-job.interface.js.map +1 -1
  130. package/dist/services/scheduled-jobs/scheduler.service.js +1 -6
  131. package/dist/services/scheduled-jobs/scheduler.service.js.map +1 -1
  132. package/dist/solid-core.module.d.ts.map +1 -1
  133. package/dist/solid-core.module.js +56 -39
  134. package/dist/solid-core.module.js.map +1 -1
  135. package/dist/subscribers/{question-sql-dataset-config.subscriber.d.ts → dashboard-question-sql-dataset-config.subscriber.d.ts} +6 -6
  136. package/dist/subscribers/dashboard-question-sql-dataset-config.subscriber.d.ts.map +1 -0
  137. package/dist/subscribers/{question-sql-dataset-config.subscriber.js → dashboard-question-sql-dataset-config.subscriber.js} +10 -10
  138. package/dist/subscribers/dashboard-question-sql-dataset-config.subscriber.js.map +1 -0
  139. package/dist/subscribers/{question.subscriber.d.ts → dashboard-question.subscriber.d.ts} +7 -7
  140. package/dist/subscribers/dashboard-question.subscriber.d.ts.map +1 -0
  141. package/dist/subscribers/{question.subscriber.js → dashboard-question.subscriber.js} +8 -8
  142. package/dist/subscribers/dashboard-question.subscriber.js.map +1 -0
  143. package/dist/tsconfig.tsbuildinfo +1 -1
  144. package/package.json +1 -1
  145. package/src/controllers/ai-interaction.controller.ts +14 -2
  146. package/src/controllers/{question-sql-dataset-config.controller.ts → dashboard-question-sql-dataset-config.controller.ts} +10 -10
  147. package/src/controllers/{question.controller.ts → dashboard-question.controller.ts} +10 -10
  148. package/src/dtos/{create-question-sql-dataset-config.dto.ts → create-dashboard-question-sql-dataset-config.dto.ts} +1 -1
  149. package/src/dtos/{create-question.dto.ts → create-dashboard-question.dto.ts} +9 -4
  150. package/src/dtos/create-dashboard.dto.ts +3 -3
  151. package/src/dtos/{update-question-sql-dataset-config.dto.ts → update-dashboard-question-sql-dataset-config.dto.ts} +1 -1
  152. package/src/dtos/{update-question.dto.ts → update-dashboard-question.dto.ts} +9 -4
  153. package/src/dtos/update-dashboard.dto.ts +3 -3
  154. package/src/entities/{question-sql-dataset-config.entity.ts → dashboard-question-sql-dataset-config.entity.ts} +5 -5
  155. package/src/entities/{question.entity.ts → dashboard-question.entity.ts} +8 -5
  156. package/src/entities/dashboard.entity.ts +3 -3
  157. package/src/index.ts +7 -4
  158. package/src/interfaces.ts +24 -2
  159. package/src/jobs/database/trigger-mcp-client-publisher-database.service.ts +22 -0
  160. package/src/jobs/database/trigger-mcp-client-queue-options.ts +9 -0
  161. package/src/jobs/database/trigger-mcp-client-subscriber-database.service.ts +89 -0
  162. package/src/repository/dashboard.repository.ts +54 -53
  163. package/src/seeders/seed-data/solid-core-metadata.json +88 -131
  164. package/src/services/ai-interaction.service.ts +117 -33
  165. package/src/services/chatter-message.service.ts +12 -6
  166. package/src/services/{question-sql-dataset-config.service.ts → dashboard-question-sql-dataset-config.service.ts} +5 -5
  167. package/src/services/{question.service.ts → dashboard-question.service.ts} +6 -6
  168. package/src/services/field-metadata.service.ts +1 -0
  169. package/src/services/import-transaction.service.ts +29 -1
  170. package/src/services/list-of-values.service.ts +5 -0
  171. package/src/services/mcp-tool-response-handlers/mcp-tool-response-handler-factory.service.ts +36 -0
  172. package/src/services/mcp-tool-response-handlers/solid-create-module-mcp-tool-response-handler.service.ts +52 -0
  173. package/src/services/module-metadata.service.ts +0 -5
  174. package/src/services/question-data-providers/chartjs-sql-data-provider.service.ts +14 -10
  175. package/src/services/question-data-providers/helpers.ts +23 -4
  176. package/src/services/question-data-providers/prime-react-datatable-sql-data-provider.service.ts +12 -6
  177. package/src/services/question-data-providers/prime-react-meter-group-sql-data-provider.service.ts +14 -5
  178. package/src/services/question-data-providers/test.sql +1 -0
  179. package/src/services/queues/publisher-factory.service.ts +1 -1
  180. package/src/services/scheduled-jobs/scheduled-job.interface.ts +1 -1
  181. package/src/services/scheduled-jobs/scheduler.service.ts +6 -6
  182. package/src/solid-core.module.ts +59 -39
  183. package/src/subscribers/{question-sql-dataset-config.subscriber.ts → dashboard-question-sql-dataset-config.subscriber.ts} +8 -10
  184. package/src/subscribers/{question.subscriber.ts → dashboard-question.subscriber.ts} +7 -10
  185. package/dist/controllers/question-sql-dataset-config.controller.d.ts +0 -43
  186. package/dist/controllers/question-sql-dataset-config.controller.d.ts.map +0 -1
  187. package/dist/controllers/question-sql-dataset-config.controller.js.map +0 -1
  188. package/dist/controllers/question.controller.d.ts +0 -45
  189. package/dist/controllers/question.controller.d.ts.map +0 -1
  190. package/dist/controllers/question.controller.js.map +0 -1
  191. package/dist/dtos/create-question-sql-dataset-config.dto.d.ts.map +0 -1
  192. package/dist/dtos/create-question-sql-dataset-config.dto.js.map +0 -1
  193. package/dist/dtos/create-question.dto.d.ts +0 -16
  194. package/dist/dtos/create-question.dto.d.ts.map +0 -1
  195. package/dist/dtos/create-question.dto.js.map +0 -1
  196. package/dist/dtos/update-question-sql-dataset-config.dto.d.ts.map +0 -1
  197. package/dist/dtos/update-question-sql-dataset-config.dto.js.map +0 -1
  198. package/dist/dtos/update-question.dto.d.ts +0 -17
  199. package/dist/dtos/update-question.dto.d.ts.map +0 -1
  200. package/dist/dtos/update-question.dto.js.map +0 -1
  201. package/dist/entities/question-sql-dataset-config.entity.d.ts +0 -13
  202. package/dist/entities/question-sql-dataset-config.entity.d.ts.map +0 -1
  203. package/dist/entities/question-sql-dataset-config.entity.js.map +0 -1
  204. package/dist/entities/question.entity.d.ts +0 -15
  205. package/dist/entities/question.entity.d.ts.map +0 -1
  206. package/dist/entities/question.entity.js.map +0 -1
  207. package/dist/services/question-sql-dataset-config.service.d.ts.map +0 -1
  208. package/dist/services/question-sql-dataset-config.service.js.map +0 -1
  209. package/dist/services/question.service.d.ts.map +0 -1
  210. package/dist/services/question.service.js.map +0 -1
  211. package/dist/subscribers/question-sql-dataset-config.subscriber.d.ts.map +0 -1
  212. package/dist/subscribers/question-sql-dataset-config.subscriber.js.map +0 -1
  213. package/dist/subscribers/question.subscriber.d.ts.map +0 -1
  214. package/dist/subscribers/question.subscriber.js.map +0 -1
  215. package/src/services/1. Create a context menu option i.py +0 -12
@@ -1 +1 @@
1
- {"version":3,"file":"import-transaction.service.js","sourceRoot":"","sources":["../../src/services/import-transaction.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyE;AACzE,uCAA2D;AAC3D,6CAAwE;AACxE,qCAAoD;AAEpD,2CAA+C;AAC/C,+DAAqE;AACrE,iDAAwD;AACxD,iDAAwD;AACxD,qEAA2E;AAC3E,uEAA6E;AAG7E,oEAAkE;AAClE,yCAA4C;AAC5C,iFAAyG;AAGzG,yGAA6F;AAI7F,+BAAoC;AACpC,qFAA0E;AAC1E,+CAA2C;AAC3C,mDAA+C;AAC/C,yEAAoE;AAQ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Y,4DAAwB;mCAAxB,wBAAwB;IADpC,IAAA,mBAAU,GAAE;IASR,WAAA,IAAA,6BAAmB,GAAE,CAAA;IAErB,WAAA,IAAA,0BAAgB,EAAC,6CAAiB,EAAE,SAAS,CAAC,CAAA;qCARhB,6CAAoB;QACnB,+CAAqB;QAC7B,sBAAa;QACf,0BAAW;QACN,uBAAgB;QACf,uCAAiB;QAErB,uBAAa;QAEtB,oBAAU;QACL,gBAAS;QACN,4BAAY;QACd,wBAAU;QACT,mBAAW;QACL,iDAAsB;GAhBzC,wBAAwB,CA2jBpC","sourcesContent":["import { BadRequestException, Injectable, Logger } from '@nestjs/common';\nimport { DiscoveryService, ModuleRef } from \"@nestjs/core\";\nimport { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';\nimport { EntityManager, Repository } from 'typeorm';\n\nimport { ConfigService } from '@nestjs/config';\nimport { CrudHelperService } from 'src/services/crud-helper.service';\nimport { CRUDService } from 'src/services/crud.service';\nimport { FileService } from 'src/services/file.service';\nimport { ModelMetadataService } from 'src/services/model-metadata.service';\nimport { ModuleMetadataService } from 'src/services/module-metadata.service';\n\n\nimport { classify } from '@angular-devkit/core/src/utils/strings';\nimport { HttpService } from '@nestjs/axios';\nimport { RelationFieldsCommand, RelationType, SolidFieldType } from 'src/dtos/create-field-metadata.dto';\nimport { ImportInstructionsResponseDto, StandardImportInstructionsResponseDto } from 'src/dtos/import-instructions.dto';\nimport { FieldMetadata } from 'src/entities/field-metadata.entity';\nimport { ImportTransactionErrorLog } from 'src/entities/import-transaction-error-log.entity';\nimport { ModelMetadata } from 'src/entities/model-metadata.entity';\nimport { MediaWithFullUrl } from 'src/interfaces';\nimport { Readable } from 'stream';\nimport { v4 as uuidv4 } from 'uuid';\nimport { ImportTransaction } from '../entities/import-transaction.entity';\nimport { CsvService } from './csv.service';\nimport { ExcelService } from './excel.service';\nimport { SolidIntrospectService } from './solid-introspect.service';\n\ninterface ImportTemplateFileInfo {\n stream: NodeJS.ReadableStream;\n fileName: string;\n mimeType: string;\n}\n\nexport enum ImportFormat {\n CSV = 'csv',\n EXCEL = 'excel',\n}\n\nexport enum ImportMimeTypes {\n CSV = 'text/csv',\n EXCEL = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n}\nexport interface ImportMappingInfo {\n sampleImportedRecordInfo: SampleImportedRecordInfo[];\n importableFields: ImportableFieldInfo[];\n}\nexport interface SampleImportedRecordInfo {\n cellHeader: string; // The header of the cell in the import file\n cellValue: string; // The value of the cell in the import file\n defaultMappedFieldName: string; // The default mapped field name in the model metadata\n}\nexport interface ImportableFieldInfo {\n name: string;\n displayName: string;\n}\n\nexport interface ImportPaginatedReadResult {\n headers: string[]; // Headers of the CSV file\n data: Record<string, any>[]; // Data records in the current page\n}\n\ninterface ImportMapping {\n header: string; // The name of the field in the import file\n fieldName: string; // The name of the field in the model metadata to which the imported field is mapped\n}\n\nexport enum ImportTransactionStatus {\n draft = 'draft',\n mapping_created = 'mapping_created',\n import_started = 'import_started',\n import_succeeded = 'import_succeeded',\n import_failed = 'import_failed',\n}\n\nexport interface ImportSyncResult {\n status: string; // The status of the import transaction\n importedIds: Array<number>; // The IDs of the records created during the import\n importedCount: number; // The number of records created during the import\n failedCount: number; // The number of records that failed to import\n}\ninterface ImportRecordsResult {\n ids: Array<number>; // The IDs of the records created during the import\n errorLogIds: Array<number>; // The IDs of the error log entries created during the import\n}\n\n@Injectable()\nexport class ImportTransactionService extends CRUDService<ImportTransaction> {\n constructor(\n readonly modelMetadataService: ModelMetadataService,\n readonly moduleMetadataService: ModuleMetadataService,\n readonly configService: ConfigService,\n readonly fileService: FileService,\n readonly discoveryService: DiscoveryService,\n readonly crudHelperService: CrudHelperService,\n @InjectEntityManager()\n readonly entityManager: EntityManager,\n @InjectRepository(ImportTransaction, 'default')\n readonly repo: Repository<ImportTransaction>,\n readonly moduleRef: ModuleRef,\n readonly excelService: ExcelService,\n readonly csvService: CsvService,\n readonly httpService: HttpService,\n readonly introspectService: SolidIntrospectService,\n // readonly fieldMetadataService: FieldMetadataService,\n ) {\n super(modelMetadataService, moduleMetadataService, configService, fileService, discoveryService, crudHelperService, entityManager, repo, 'importTransaction', 'solid-core', moduleRef);\n }\n\n private readonly logger = new Logger(ImportTransactionService.name);\n\n /**\n * This method is used to return a csv / excel template for the import transaction\n * It will contain the display names of the fields in the header row\n * @param modelMetadataId \n */\n async getImportTemplate(modelMetadataId: number, format: ImportFormat = ImportFormat.CSV): Promise<ImportTemplateFileInfo> {\n // Load the model metadata for the given ID\n const modelMetadata = await this.modelMetadataService.findOne(modelMetadataId, {\n populate: ['fields'],\n });\n if (!modelMetadata) {\n throw new Error(`Model metadata with ID ${modelMetadataId} not found.`);\n }\n // Create a header row with the display names of the fields, excluding the media fields,computed fields\n const headers = this.fieldsAllowedForImport(modelMetadata.fields)\n .map(field => field.displayName);\n\n // Depending on the format, generate the template\n if (format === ImportFormat.CSV) {\n const stream = await this.csvService.createCsvStream(null, 0, headers); // Create a CSV stream with the header row\n const fileName = `${modelMetadata.singularName}-import-template.csv`;\n const mimeType = 'text/csv';\n return {\n stream,\n fileName,\n mimeType,\n };\n } else if (format === ImportFormat.EXCEL) {\n const stream = await this.excelService.createExcelStream(null, 0, headers); // Create an Excel stream with the header row\n const fileName = `${modelMetadata.singularName}-import-template.xlsx`;\n // Set the MIME type for Excel files\n const mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';\n return {\n stream,\n fileName,\n mimeType,\n };\n } else {\n throw new Error(`Unsupported import format: ${format}`);\n }\n\n }\n\n async getImportInstructions(modelMetadataId: number): Promise<ImportInstructionsResponseDto> {\n // Load the model metadata for the given ID\n const modelMetadata = await this.modelMetadataService.findOne(modelMetadataId, {\n populate: ['fields'],\n });\n if (!modelMetadata) {\n throw new Error(`Model metadata with ID ${modelMetadataId} not found.`);\n }\n\n // Create the standard import instructions\n const standardInstructions: StandardImportInstructionsResponseDto = {\n requiredFields: [],\n dateFields: [],\n dateTimeFields: [],\n numberFields: [],\n emailFields: [],\n regexFields: [],\n jsonFields: [],\n booleanFields: [],\n };\n\n // Iterate through the fields and populate the standard instructions\n for (const field of modelMetadata.fields) {\n if (field.isSystem) continue; // Skip system fields\n if (field.required) {\n standardInstructions.requiredFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.date) {\n standardInstructions.dateFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.datetime) {\n standardInstructions.dateTimeFields.push(field.displayName);\n }\n if ([SolidFieldType.bigint, SolidFieldType.int, SolidFieldType.decimal].includes(field.type as SolidFieldType)) {\n standardInstructions.numberFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.email) {\n standardInstructions.emailFields.push(field.displayName);\n }\n if (field.regexPattern) {\n standardInstructions.regexFields.push({\n fieldName: field.displayName,\n regexPattern: field.regexPattern,\n });\n }\n if (field.type === SolidFieldType.json) {\n standardInstructions.jsonFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.boolean) {\n standardInstructions.booleanFields.push(field.displayName);\n }\n }\n\n // Create the custom instructions\n const customInstructions: string[] = [];\n\n return {\n standard: standardInstructions,\n custom: customInstructions,\n };\n }\n\n async getImportMappingInfo(importTransactionId: number): Promise<ImportMappingInfo> {\n // Load the import transaction for the given ID\n const importTransaction = await this.loadImportTransaction(importTransactionId);\n\n // Get all the importable fields from the model metadata\n const importableFields: ImportableFieldInfo[] = this.fieldsAllowedForImport(importTransaction.modelMetadata.fields).map(field => ({\n name: field.name,\n displayName: field.displayName,\n required: field.required,\n }));\n\n // Get the import file media object from the import transaction\n const importFileMediaObject = this.getImportFileObject(importTransaction);\n\n // Get the import file stream for the import transaction\n const importFileStream = await this.getImportFileStream(importFileMediaObject);\n\n // Get a sample of records from the import file\n const sampleRecord = await this.getFileRecordsSample(importFileStream, importFileMediaObject.mimeType);\n\n // Convert sampleRecord to the format required for SampleImportedRecordInfo\n const wrappedRecords: SampleImportedRecordInfo[] = sampleRecord.data.map((record: Record<string, any>) => {\n return Object.entries(record).map(([key, value]) => ({\n cellHeader: key,\n cellValue: value,\n defaultMappedFieldName: importableFields.find(field => field.displayName === key)?.name || '',\n }));\n }).flat();\n\n // for await (const page of this.csvService.readCsvInPagesFromStream(importFileStream)) {\n // // await dbService.bulkInsert(page);\n // }\n\n return {\n sampleImportedRecordInfo: wrappedRecords, // This will hold the sample data from the file\n importableFields: importableFields, // This will hold the fields that can be imported\n };\n }\n\n async startImportSync(importTransactionId: number): Promise<ImportSyncResult> {\n // Load the import transaction for the given ID\n const importTransaction = await this.loadImportTransaction(importTransactionId);\n\n // Get the import file media object from the import transaction\n const importFileMediaObject = this.getImportFileObject(importTransaction);\n\n // Get the import file stream for the import transaction\n const importFileStream = await this.getImportFileStream(importFileMediaObject);\n\n const { ids, errorLogIds } = await this.importFromFileToDB(\n importTransaction,\n importFileStream,\n importFileMediaObject.mimeType,\n );\n\n // Update the import transaction status to 'completed'\n (errorLogIds.length > 0) ? importTransaction.status = ImportTransactionStatus.import_failed : importTransaction.status = ImportTransactionStatus.import_succeeded; //FIXME: We can probably have import_partially_failed status to differentiate\n // Save the import transaction\n await this.repo.save(importTransaction);\n return {\n status: importTransaction.status,\n importedIds: ids, // The IDs of the records created during the import\n importedCount: ids.length, // The number of records created during the import\n failedCount: errorLogIds.length, // The number of records that failed to import\n };\n }\n\n startImportAsync(importTransactionId: number): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async exportFailedImportedImports(importTransactionId: number) {\n // Get the 1st error log entry to determine the headers for the export file\n const firstErrorLogEntry = await this.entityManager.getRepository(ImportTransactionErrorLog).findOne({\n where: {\n importTransaction: { id: importTransactionId },\n },\n });\n\n if (!firstErrorLogEntry) {\n throw new BadRequestException(`No error log entries found for import transaction ID ${importTransactionId}.`);\n }\n\n // Create the headers for the export file\n const headers = [\n ...Object.keys(firstErrorLogEntry.rowData ? JSON.parse(firstErrorLogEntry.rowData) : {}), // Include all keys from the rowData JSON\n 'Error', // Error message for the failed record\n ];\n\n\n // Depending upon the format of the import tranaction file, create a readable stream of the error log entries\n const importTransaction = await this.loadImportTransaction(importTransactionId);\n const importFileMediaObject = this.getImportFileObject(importTransaction);\n const mimeType = importFileMediaObject.mimeType;\n const templateFormat = mimeType === ImportMimeTypes.CSV ? \"csv\" : \"excel\";\n const dataRecordsFunc = async (chunkIndex: number, chunkSize: number): Promise<any[]> => {\n // Get the error log entries for the import transaction\n const errorLogEntries = await this.entityManager.getRepository(ImportTransactionErrorLog).find({\n where: {\n importTransaction: { id: importTransactionId },\n },\n skip: chunkIndex * chunkSize,\n take: chunkSize,\n });\n\n if (!errorLogEntries || errorLogEntries.length === 0) {\n return []; // Return an empty array if no error log entries found\n }\n\n // Read the row data json from the error log entry, parse it and write it as a record to the stream\n return errorLogEntries.map(entry => {\n const rowData = entry.rowData ? JSON.parse(entry.rowData) : {};\n return {\n ...rowData, // Spread the row data into the record\n Error: entry.errorMessage,\n };\n });\n };\n\n // Get the export stream for the failed records\n const exportStream = await this.getFailedRecordsStream(templateFormat, headers, dataRecordsFunc);\n if (!exportStream) {\n throw new BadRequestException(`Failed to create export stream for import transaction ID ${importTransactionId}.`);\n }\n // Return the export stream\n const extension = templateFormat === \"excel\" ? 'xlsx' : 'csv';\n return {\n stream: exportStream,\n fileName: `${importTransaction.modelMetadata.singularName}-failed-imports.${extension}`,\n mimeType: templateFormat === \"excel\" ? ImportMimeTypes.EXCEL : ImportMimeTypes.CSV,\n };\n\n }\n\n private async getFailedRecordsStream(templateFormat: string, headers: string[], dataRecordsFunc: (chunkIndex: number, chunkSize: number) => Promise<any[]>) {\n let exportStream = null;\n switch (templateFormat) {\n case \"excel\":\n exportStream = await this.excelService.createExcelStream(dataRecordsFunc, 100, headers);\n break;\n case \"csv\":\n exportStream = await this.csvService.createCsvStream(dataRecordsFunc, 100, headers);\n break;\n default:\n throw new Error('Invalid export format');\n }\n return exportStream;\n }\n\n\n private async loadImportTransaction(importTransactionId: number) {\n const importTransaction = await this.findOne(importTransactionId, {\n populate: ['modelMetadata', 'modelMetadata.fields'],\n populateMedia: ['fileLocation'],\n });\n if (!importTransaction) {\n throw new Error(`Import transaction with ID ${importTransactionId} not found.`);\n }\n return importTransaction;\n }\n\n private fieldsAllowedForImport(fields: FieldMetadata[]): FieldMetadata[] {\n // Filter out fields that are not allowed for import\n return fields.filter(field =>\n field.type !== SolidFieldType.mediaMultiple && // Exclude media multiple fields\n field.type !== SolidFieldType.mediaSingle &&\n field.type !== SolidFieldType.computed && // Exclude computed fields\n field.type !== SolidFieldType.password &&\n field.type !== SolidFieldType.richText &&\n field.type !== SolidFieldType.uuid &&\n field.isSystem !== true // Exclude system fields\n );\n }\n\n private async getFileRecordsSample(importFileStream: Readable, mimeType: string): Promise<ImportPaginatedReadResult> {\n // Depending upon the mime type of the file, read the file in pages\n // For CSV files, use the csvService to read the file in pages\n // For Excel files, use the excelService to read the file in pages\n if (mimeType === 'text/csv') {\n const generator = this.csvService.readCsvInPagesFromStream(importFileStream, { pageSize: 1 });\n const firstRecord = await generator.next(); // Get the first record to extract headers and sample data\n return firstRecord.value;\n } else if (mimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {\n const generator = this.excelService.readExcelInPagesFromStream(importFileStream, { pageSize: 1 });\n const firstRecord = await generator.next(); // Get the first record to extract headers and sample data\n return firstRecord.value;\n }\n else { // If the file is neither CSV nor Excel, throw an error\n throw new Error(`Unsupported file type: ${mimeType}`);\n }\n }\n\n private getImportFileObject(importTransaction: ImportTransaction): MediaWithFullUrl {\n const importFileMediaObject = importTransaction['_media']['fileLocation'][0] as MediaWithFullUrl; // Since there can be only one fileLocation, we can safely access the first element\n if (!importFileMediaObject) {\n throw new Error(`Import file for transaction ID ${importTransaction.id} not found.`);\n }\n return importFileMediaObject;\n }\n\n private async getImportFileStream(importFileMediaObject: MediaWithFullUrl): Promise<Readable> {\n const fileUrl = importFileMediaObject['_full_url'];\n const mimeType = importFileMediaObject['mimeType'];\n if (!fileUrl) {\n throw new Error(`File URL ${fileUrl} not found.`);\n }\n // From the file URL, convert the file URL to a readable stream using nestjs http service and axios\n const fileUrlResponse = await this.httpService.axiosRef.get(fileUrl, {\n responseType: 'stream',\n });\n\n if (!fileUrlResponse || !fileUrlResponse.data) {\n throw new Error(`Failed to read file from URL: ${fileUrl}`);\n }\n // fileUrlResponse.data is a Node.js Readable stream\n return fileUrlResponse.data;\n }\n\n private async importFromFileToDB(\n importTransaction: ImportTransaction,\n importFileStream: Readable,\n mimeType: string,\n ): Promise<ImportRecordsResult> {\n if (!importTransaction.modelMetadata) {\n throw new Error(`Model metadata for import transaction ID ${importTransaction.id} not found.`);\n }\n\n const createdRecordIds = [];\n const createdErrorLogIds = [];\n\n // Get the model service for the model metadata name\n const modelService = this.getModelService(importTransaction.modelMetadata.singularName);\n\n // Depending upon the mime type of the file, read the file in pages and insert the records into the database\n if (mimeType === ImportMimeTypes.CSV) {\n for await (const page of this.csvService.readCsvInPagesFromStream(importFileStream)) {\n const { ids, errorLogIds } = await this.importRecords(page, importTransaction, modelService);\n createdRecordIds.push(...ids);\n createdErrorLogIds.push(...errorLogIds);\n }\n }\n else if (mimeType === ImportMimeTypes.EXCEL) {\n for await (const page of this.excelService.readExcelInPagesFromStream(importFileStream)) {\n const { ids, errorLogIds } = await this.importRecords(page, importTransaction, modelService);\n createdRecordIds.push(...ids);\n createdErrorLogIds.push(...errorLogIds);\n }\n } else { // If the file is neither CSV nor Excel, throw an error\n throw new Error(`Unsupported file type: ${mimeType}`);\n }\n\n return {\n ids: createdRecordIds, // Return the IDs of the created records\n errorLogIds: createdErrorLogIds, // Return the IDs of the error log entries created during the import\n }\n }\n\n private async importRecords(page: ImportPaginatedReadResult, importTransaction: ImportTransaction, modelService: CRUDService<any>): Promise<ImportRecordsResult> {\n if (!importTransaction.modelMetadata || !importTransaction.modelMetadata.fields) {\n throw new Error(`Model metadata with fields for import transaction ID ${importTransaction.id} not found.`);\n }\n\n const ids: Array<number> = [];\n const errorLogIds: Array<number> = [];\n for (const record of page.data) {\n try {\n const createdRecord = await this.insertRecord(record, JSON.parse(importTransaction.mapping) as ImportMapping[], importTransaction.modelMetadata, modelService);\n ids.push(createdRecord.id); // Add the ID of the created record to the ids array\n }\n catch (error) {\n this.logger.debug(`Error inserting record: ${JSON.stringify(record)}. Error: ${error.message}`);\n // Get the Import transaction error log repo\n const errorLog = await this.createErrorLogEntry(importTransaction, record, error);\n errorLogIds.push(errorLog.id); // Add the ID of the error log entry to the errorLogIds array\n }\n }\n return {\n ids: ids, // Return the IDs of the created records\n errorLogIds: errorLogIds, // Return the IDs of the error log entries created during the import\n };\n }\n\n private async createErrorLogEntry(importTransaction: ImportTransaction, record: Record<string, any>, error: any) {\n const importTransactionRepo = this.entityManager.getRepository(ImportTransactionErrorLog);\n // Create a new ImportTransactionErrorLog entry\n const rowNumber = uuidv4(); // Generate a unique row number or use page.rowNumber if available \n\n const errorLogEntry = {\n importTransactionErrorLogId: `${importTransaction.id}-${rowNumber}`, // FIXME pending to retrieve the row number from the page\n rowNumber: 1, // FIXME pending to retrieve the row number from the page\n rowData: JSON.stringify(record), // Store the row data\n importTransaction: importTransaction, // Link to the import transaction\n errorMessage: error.message, // Store the error message\n errorTrace: error.stack || '', // Store the error stack trace if available\n } as ImportTransactionErrorLog;\n\n // Save the error log entry to the database\n const savedEntry = await importTransactionRepo.save(errorLogEntry);\n return savedEntry; // Return the ID of the saved error log entry\n }\n\n //FIXME Currently below method fails if any field in the record is not valid or if the record is not valid. It does not collect the errors for all fields in a record\n private async insertRecord(record: Record<string, any>, mapping: ImportMapping[], modelMetadataWithFields: ModelMetadata, modelService: CRUDService<any>): Promise<any> {\n // Convert the imported record to a DTO\n const dto = await this.convertImportedRecordToDto(record, mapping, modelMetadataWithFields);\n // Use the model service to create the record in the database\n const createdRecord = await modelService.create(dto, [], {}); //FIXME: Need to handle this part alongwith the refactoring of the CRUDService for permissions\n return createdRecord; // Return the created record\n }\n\n private getModelService(modelSingularName: string): CRUDService<any> {\n // Get the model service for the model metadata name\n const modelServiceWrapper = this.introspectService.getProvider(`${classify(modelSingularName)}Service`);\n const modelService = modelServiceWrapper.instance as CRUDService<any>;\n if (!modelService) {\n throw new Error(`Model service for ${modelSingularName} not found.`);\n }\n return modelService;\n }\n\n private async convertImportedRecordToDto(record: Record<string, any>, mapping: ImportMapping[], modelMetadataWithFields: ModelMetadata) {\n // Create a new record object\n const dtoRecord: Record<string, any> = {};\n\n // Iterate through every cell in the record\n // Using the saved mapping, populate the dtoRecord w.r.t the record and fields\n for (const key in record) {\n const mappedField = mapping.find(m => m.header === key);\n if (mappedField) {\n // If the field is found in the mapping, get the field metadata from the model metadata\n const fieldMetadata = modelMetadataWithFields.fields.find(f => f.name === mappedField.fieldName);\n // const userKeyField = modelMetadataWithFields.fields.find(f => f.isUserKey === true); // Assuming userKey is a field in the model metadata\n if (fieldMetadata) {\n // If the field is found in the model metadata, set the value in the dtoRecord\n await this.populateDtoForACell(dtoRecord, fieldMetadata, record, key);\n } else {\n this.logger.warn(`Field ${mappedField.fieldName} not found in model metadata ${modelMetadataWithFields.singularName}`);\n }\n }\n }\n return dtoRecord;\n }\n\n private async populateDtoForACell(dtoRecord: Record<string, any>, fieldMetadata: FieldMetadata, record: Record<string, any>, key: string): Promise<Record<string, any>> {\n const fieldType = fieldMetadata.type;\n // const userKeyFieldName = userKeyField?.name || 'id'; // Default to 'id' if not found\n\n // TODO Move this logic to field crud managers i.e add a parse method to the field crud manager interface\n switch (fieldType) {\n case SolidFieldType.relation: {\n return await this.populateDtoForRelations(fieldMetadata, record, key, dtoRecord);\n }\n case SolidFieldType.date:\n case SolidFieldType.datetime: return this.populateDtoForDate(record, key, fieldMetadata, dtoRecord);\n case SolidFieldType.int:\n case SolidFieldType.bigint:\n case SolidFieldType.decimal:\n return this.populateDtoForNumber(dtoRecord, fieldMetadata, record, key);\n case SolidFieldType.boolean:\n return this.populateDtoForBoolean(dtoRecord, fieldMetadata, record, key);\n default:\n dtoRecord[fieldMetadata.name] = record[key];\n return dtoRecord;\n }\n }\n\n private populateDtoForBoolean(dtoRecord: Record<string, any>, fieldMetadata: FieldMetadata, record: Record<string, any>, key: string) {\n const booleanValue = Boolean(record[key]);\n if (typeof booleanValue !== 'boolean') {\n throw new Error(`Invalid boolean value for cell ${key} with value ${record[key]}`);\n }\n dtoRecord[fieldMetadata.name] = booleanValue;\n return dtoRecord;\n }\n\n private populateDtoForNumber(dtoRecord: Record<string, any>, fieldMetadata: FieldMetadata, record: Record<string, any>, key: string) {\n const numberValue = Number(record[key]);\n if (isNaN(numberValue)) {\n throw new Error(`Invalid number value for cell ${key} with value ${record[key]}`);\n }\n dtoRecord[fieldMetadata.name] = numberValue;\n return dtoRecord;\n }\n\n private populateDtoForDate(record: Record<string, any>, key: string, fieldMetadata: FieldMetadata, dtoRecord: Record<string, any>) {\n {\n const dateValue = new Date(record[key]);\n if (isNaN(dateValue.getTime())) {\n throw new Error(`Invalid date value for cell ${key} with value ${record[key]}`);\n }\n dtoRecord[fieldMetadata.name] = dateValue;\n return dtoRecord;\n }\n }\n\n private async populateDtoForRelations(fieldMetadata: FieldMetadata, record: Record<string, any>, key: string, dtoRecord: Record<string, any>) {\n if (!fieldMetadata.relationCoModelSingularName) {\n throw new Error(`Relation coModelSingularName is not defined for relation field ${fieldMetadata.name}`);\n }\n\n const relatedRecordsIds = await this.getRelatedEntityIdsFromUserKeys(fieldMetadata, record, key);\n if (relatedRecordsIds.length === 0) {\n return dtoRecord; // If no related records found, return the dtoRecord as is\n }\n\n if (fieldMetadata.relationType === RelationType.manyTomany || fieldMetadata.relationType === RelationType.oneToMany) {\n dtoRecord[`${fieldMetadata.name}Ids`] = relatedRecordsIds;\n dtoRecord[`${fieldMetadata.name}Command`] = RelationFieldsCommand.set; // Reset the relation field association with the related records IDs\n }\n else if (fieldMetadata.relationType === RelationType.manyToOne) {\n dtoRecord[`${fieldMetadata.name}Id`] = relatedRecordsIds.pop(); // For many-to-one relations, we need only one ID\n }\n return dtoRecord;\n }\n\n private async getRelatedEntityIdsFromUserKeys(fieldMetadata: FieldMetadata, record: Record<string, any>, key: string): Promise<Array<number>> {\n // For many-to-many or one-to-many relations, we expect the record cell to contains a comma-separated list of userKeys\n const relationUserKeys = record[key] ? String(record[key]).split(',').map((userKey: string) => userKey.trim()) : [];\n if (relationUserKeys.length === 0) return [];\n\n const coModelService = this.getModelService(fieldMetadata.relationCoModelSingularName);\n const coModelWithUserKeyField = await this.modelMetadataService.findOneBySingularName(fieldMetadata.relationCoModelSingularName, ['userKeyField']);\n const coModelUserKeyFieldName = coModelWithUserKeyField?.userKeyField?.name || 'id'; // Default to 'id' if not found\n\n\n // Set the relation basic filter dto filters with the userkeys and call the find method of the model service to get the related records\n const relationFilterDto = {\n filters: {\n [coModelUserKeyFieldName]: {\n $in: relationUserKeys, // Use the userKeyFieldName to filter by userKeys\n },\n },\n };\n\n // From the userKeys, we will get the IDs of the related records using the userKeyFieldName and throw an error if any of the userKeys is not found\n const relatedRecordsResult = await coModelService.find(relationFilterDto);\n if (!relatedRecordsResult || !relatedRecordsResult.records || relatedRecordsResult.records.length === 0 || relatedRecordsResult.records.length !== relationUserKeys.length) {\n throw new Error(`Invalid related records userKey values found for cell ${key} with value ${record[key]}`);\n }\n const relatedRecordsIds = relatedRecordsResult.records.map(record => record.id);\n return relatedRecordsIds;\n }\n}"]}
1
+ {"version":3,"file":"import-transaction.service.js","sourceRoot":"","sources":["../../src/services/import-transaction.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyE;AACzE,uCAA2D;AAC3D,6CAAwE;AACxE,qCAAoD;AAEpD,2CAA+C;AAC/C,+DAAqE;AACrE,iDAAwD;AACxD,iDAAwD;AACxD,qEAA2E;AAC3E,uEAA6E;AAG7E,oEAAkE;AAClE,yCAA4C;AAC5C,iFAAyG;AAGzG,yGAA6F;AAI7F,+BAAoC;AACpC,qFAA0E;AAC1E,+CAA2C;AAC3C,mDAA+C;AAC/C,yEAAoE;AAQpE,IAAY,YAGX;AAHD,WAAY,YAAY;IACtB,2BAAW,CAAA;IACX,+BAAe,CAAA;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CAulBpC","sourcesContent":["import { BadRequestException, Injectable, Logger } from '@nestjs/common';\nimport { DiscoveryService, ModuleRef } from \"@nestjs/core\";\nimport { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';\nimport { EntityManager, Repository } from 'typeorm';\n\nimport { ConfigService } from '@nestjs/config';\nimport { CrudHelperService } from 'src/services/crud-helper.service';\nimport { CRUDService } from 'src/services/crud.service';\nimport { FileService } from 'src/services/file.service';\nimport { ModelMetadataService } from 'src/services/model-metadata.service';\nimport { ModuleMetadataService } from 'src/services/module-metadata.service';\n\n\nimport { classify } from '@angular-devkit/core/src/utils/strings';\nimport { HttpService } from '@nestjs/axios';\nimport { RelationFieldsCommand, RelationType, SolidFieldType } from 'src/dtos/create-field-metadata.dto';\nimport { ImportInstructionsResponseDto, StandardImportInstructionsResponseDto } from 'src/dtos/import-instructions.dto';\nimport { FieldMetadata } from 'src/entities/field-metadata.entity';\nimport { ImportTransactionErrorLog } from 'src/entities/import-transaction-error-log.entity';\nimport { ModelMetadata } from 'src/entities/model-metadata.entity';\nimport { MediaWithFullUrl } from 'src/interfaces';\nimport { Readable } from 'stream';\nimport { v4 as uuidv4 } from 'uuid';\nimport { ImportTransaction } from '../entities/import-transaction.entity';\nimport { CsvService } from './csv.service';\nimport { ExcelService } from './excel.service';\nimport { SolidIntrospectService } from './solid-introspect.service';\n\ninterface ImportTemplateFileInfo {\n stream: NodeJS.ReadableStream;\n fileName: string;\n mimeType: string;\n}\n\nexport enum ImportFormat {\n CSV = 'csv',\n EXCEL = 'excel',\n}\n\nexport enum ImportMimeTypes {\n CSV = 'text/csv',\n EXCEL = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n}\nexport interface ImportMappingInfo {\n sampleImportedRecordInfo: SampleImportedRecordInfo[];\n importableFields: ImportableFieldInfo[];\n}\nexport interface SampleImportedRecordInfo {\n cellHeader: string; // The header of the cell in the import file\n cellValue: string; // The value of the cell in the import file\n defaultMappedFieldName: string; // The default mapped field name in the model metadata\n}\nexport interface ImportableFieldInfo {\n name: string;\n displayName: string;\n}\n\nexport interface ImportPaginatedReadResult {\n headers: string[]; // Headers of the CSV file\n data: Record<string, any>[]; // Data records in the current page\n}\n\ninterface ImportMapping {\n header: string; // The name of the field in the import file\n fieldName: string; // The name of the field in the model metadata to which the imported field is mapped\n}\n\nexport enum ImportTransactionStatus {\n draft = 'draft',\n mapping_created = 'mapping_created',\n import_started = 'import_started',\n import_succeeded = 'import_succeeded',\n import_failed = 'import_failed',\n}\n\nexport interface ImportSyncResult {\n status: string; // The status of the import transaction\n importedIds: Array<number>; // The IDs of the records created during the import\n importedCount: number; // The number of records created during the import\n failedCount: number; // The number of records that failed to import\n}\ninterface ImportRecordsResult {\n ids: Array<number>; // The IDs of the records created during the import\n errorLogIds: Array<number>; // The IDs of the error log entries created during the import\n}\n\n@Injectable()\nexport class ImportTransactionService extends CRUDService<ImportTransaction> {\n constructor(\n readonly modelMetadataService: ModelMetadataService,\n readonly moduleMetadataService: ModuleMetadataService,\n readonly configService: ConfigService,\n readonly fileService: FileService,\n readonly discoveryService: DiscoveryService,\n readonly crudHelperService: CrudHelperService,\n @InjectEntityManager()\n readonly entityManager: EntityManager,\n @InjectRepository(ImportTransaction, 'default')\n readonly repo: Repository<ImportTransaction>,\n readonly moduleRef: ModuleRef,\n readonly excelService: ExcelService,\n readonly csvService: CsvService,\n readonly httpService: HttpService,\n readonly introspectService: SolidIntrospectService,\n // readonly fieldMetadataService: FieldMetadataService,\n ) {\n super(modelMetadataService, moduleMetadataService, configService, fileService, discoveryService, crudHelperService, entityManager, repo, 'importTransaction', 'solid-core', moduleRef);\n }\n\n private readonly logger = new Logger(ImportTransactionService.name);\n\n /**\n * This method is used to return a csv / excel template for the import transaction\n * It will contain the display names of the fields in the header row\n * @param modelMetadataId \n */\n async getImportTemplate(modelMetadataId: number, format: ImportFormat = ImportFormat.CSV): Promise<ImportTemplateFileInfo> {\n // Load the model metadata for the given ID\n const modelMetadata = await this.modelMetadataService.findOne(modelMetadataId, {\n populate: ['fields'],\n });\n if (!modelMetadata) {\n throw new Error(`Model metadata with ID ${modelMetadataId} not found.`);\n }\n // Create a header row with the display names of the fields, excluding the media fields,computed fields\n const headers = this.fieldsAllowedForImport(modelMetadata.fields)\n .map(field => field.displayName);\n\n // Depending on the format, generate the template\n if (format === ImportFormat.CSV) {\n const stream = await this.csvService.createCsvStream(null, 0, headers); // Create a CSV stream with the header row\n const fileName = `${modelMetadata.singularName}-import-template.csv`;\n const mimeType = 'text/csv';\n return {\n stream,\n fileName,\n mimeType,\n };\n } else if (format === ImportFormat.EXCEL) {\n const stream = await this.excelService.createExcelStream(null, 0, headers); // Create an Excel stream with the header row\n const fileName = `${modelMetadata.singularName}-import-template.xlsx`;\n // Set the MIME type for Excel files\n const mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';\n return {\n stream,\n fileName,\n mimeType,\n };\n } else {\n throw new Error(`Unsupported import format: ${format}`);\n }\n\n }\n\n async getImportInstructions(modelMetadataId: number): Promise<ImportInstructionsResponseDto> {\n // Load the model metadata for the given ID\n const modelMetadata = await this.modelMetadataService.findOne(modelMetadataId, {\n populate: ['fields'],\n });\n if (!modelMetadata) {\n throw new Error(`Model metadata with ID ${modelMetadataId} not found.`);\n }\n\n // Create the standard import instructions\n const standardInstructions: StandardImportInstructionsResponseDto = {\n requiredFields: [],\n dateFields: [],\n dateTimeFields: [],\n numberFields: [],\n emailFields: [],\n regexFields: [],\n jsonFields: [],\n booleanFields: [],\n };\n\n // Iterate through the fields and populate the standard instructions\n for (const field of modelMetadata.fields) {\n if (field.isSystem) continue; // Skip system fields\n if (field.required) {\n standardInstructions.requiredFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.date) {\n standardInstructions.dateFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.datetime) {\n standardInstructions.dateTimeFields.push(field.displayName);\n }\n if ([SolidFieldType.bigint, SolidFieldType.int, SolidFieldType.decimal].includes(field.type as SolidFieldType)) {\n standardInstructions.numberFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.email) {\n standardInstructions.emailFields.push(field.displayName);\n }\n if (field.regexPattern) {\n standardInstructions.regexFields.push({\n fieldName: field.displayName,\n regexPattern: field.regexPattern,\n });\n }\n if (field.type === SolidFieldType.json) {\n standardInstructions.jsonFields.push(field.displayName);\n }\n if (field.type === SolidFieldType.boolean) {\n standardInstructions.booleanFields.push(field.displayName);\n }\n }\n\n // Create the custom instructions\n const customInstructions: string[] = [];\n\n return {\n standard: standardInstructions,\n custom: customInstructions,\n };\n }\n\n async getImportMappingInfo(importTransactionId: number): Promise<ImportMappingInfo> {\n // Load the import transaction for the given ID\n const importTransaction = await this.loadImportTransaction(importTransactionId);\n\n // Get all the importable fields from the model metadata\n const importableFields: ImportableFieldInfo[] = this.fieldsAllowedForImport(importTransaction.modelMetadata.fields).map(field => ({\n name: field.name,\n displayName: field.displayName,\n required: field.required,\n }));\n\n // Get the import file media object from the import transaction\n const importFileMediaObject = this.getImportFileObject(importTransaction);\n\n // Get the import file stream for the import transaction\n const importFileStream = await this.getImportFileStream(importFileMediaObject);\n\n // Get a sample of records from the import file\n const sampleRecord = await this.getFileRecordsSample(importFileStream, importFileMediaObject.mimeType);\n\n // Convert sampleRecord to the format required for SampleImportedRecordInfo\n const wrappedRecords: SampleImportedRecordInfo[] = sampleRecord.data.map((record: Record<string, any>) => {\n return Object.entries(record).map(([key, value]) => ({\n cellHeader: key,\n cellValue: value,\n defaultMappedFieldName: importableFields.find(field => field.displayName === key)?.name || '',\n }));\n }).flat();\n\n // for await (const page of this.csvService.readCsvInPagesFromStream(importFileStream)) {\n // // await dbService.bulkInsert(page);\n // }\n\n return {\n sampleImportedRecordInfo: wrappedRecords, // This will hold the sample data from the file\n importableFields: importableFields, // This will hold the fields that can be imported\n };\n }\n\n async startImportSync(importTransactionId: number): Promise<ImportSyncResult> {\n // Load the import transaction for the given ID\n const importTransaction = await this.loadImportTransaction(importTransactionId);\n\n // Get the import file media object from the import transaction\n const importFileMediaObject = this.getImportFileObject(importTransaction);\n\n // Get the import file stream for the import transaction\n const importFileStream = await this.getImportFileStream(importFileMediaObject);\n\n const { ids, errorLogIds } = await this.importFromFileToDB(\n importTransaction,\n importFileStream,\n importFileMediaObject.mimeType,\n );\n\n // Update the import transaction status to 'completed'\n (errorLogIds.length > 0) ? importTransaction.status = ImportTransactionStatus.import_failed : importTransaction.status = ImportTransactionStatus.import_succeeded; //FIXME: We can probably have import_partially_failed status to differentiate\n // Save the import transaction\n await this.repo.save(importTransaction);\n return {\n status: importTransaction.status,\n importedIds: ids, // The IDs of the records created during the import\n importedCount: ids.length, // The number of records created during the import\n failedCount: errorLogIds.length, // The number of records that failed to import\n };\n }\n\n startImportAsync(importTransactionId: number): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async exportFailedImportedImports(importTransactionId: number) {\n // Get the 1st error log entry to determine the headers for the export file\n const firstErrorLogEntry = await this.entityManager.getRepository(ImportTransactionErrorLog).findOne({\n where: {\n importTransaction: { id: importTransactionId },\n },\n });\n\n if (!firstErrorLogEntry) {\n throw new BadRequestException(`No error log entries found for import transaction ID ${importTransactionId}.`);\n }\n\n // Create the headers for the export file\n const headers = [\n ...Object.keys(firstErrorLogEntry.rowData ? JSON.parse(firstErrorLogEntry.rowData) : {}), // Include all keys from the rowData JSON\n 'Error', // Error message for the failed record\n ];\n\n\n // Depending upon the format of the import tranaction file, create a readable stream of the error log entries\n const importTransaction = await this.loadImportTransaction(importTransactionId);\n const importFileMediaObject = this.getImportFileObject(importTransaction);\n const mimeType = importFileMediaObject.mimeType;\n const templateFormat = mimeType === ImportMimeTypes.CSV ? \"csv\" : \"excel\";\n const dataRecordsFunc = async (chunkIndex: number, chunkSize: number): Promise<any[]> => {\n // Get the error log entries for the import transaction\n const errorLogEntries = await this.entityManager.getRepository(ImportTransactionErrorLog).find({\n where: {\n importTransaction: { id: importTransactionId },\n },\n skip: chunkIndex * chunkSize,\n take: chunkSize,\n });\n\n if (!errorLogEntries || errorLogEntries.length === 0) {\n return []; // Return an empty array if no error log entries found\n }\n\n // Read the row data json from the error log entry, parse it and write it as a record to the stream\n return errorLogEntries.map(entry => {\n const rowData = entry.rowData ? JSON.parse(entry.rowData) : {};\n return {\n ...rowData, // Spread the row data into the record\n Error: entry.errorMessage,\n };\n });\n };\n\n // Get the export stream for the failed records\n const exportStream = await this.getFailedRecordsStream(templateFormat, headers, dataRecordsFunc);\n if (!exportStream) {\n throw new BadRequestException(`Failed to create export stream for import transaction ID ${importTransactionId}.`);\n }\n // Return the export stream\n const extension = templateFormat === \"excel\" ? 'xlsx' : 'csv';\n return {\n stream: exportStream,\n fileName: `${importTransaction.modelMetadata.singularName}-failed-imports.${extension}`,\n mimeType: templateFormat === \"excel\" ? ImportMimeTypes.EXCEL : ImportMimeTypes.CSV,\n };\n\n }\n\n private async getFailedRecordsStream(templateFormat: string, headers: string[], dataRecordsFunc: (chunkIndex: number, chunkSize: number) => Promise<any[]>) {\n let exportStream = null;\n switch (templateFormat) {\n case \"excel\":\n exportStream = await this.excelService.createExcelStream(dataRecordsFunc, 100, headers);\n break;\n case \"csv\":\n exportStream = await this.csvService.createCsvStream(dataRecordsFunc, 100, headers);\n break;\n default:\n throw new Error('Invalid export format');\n }\n return exportStream;\n }\n\n\n private async loadImportTransaction(importTransactionId: number) {\n const importTransaction = await this.findOne(importTransactionId, {\n populate: ['modelMetadata', 'modelMetadata.fields'],\n populateMedia: ['fileLocation'],\n });\n if (!importTransaction) {\n throw new Error(`Import transaction with ID ${importTransactionId} not found.`);\n }\n return importTransaction;\n }\n\n private fieldsAllowedForImport(fields: FieldMetadata[]): FieldMetadata[] {\n // Filter out fields that are not allowed for import\n return fields.filter(field =>\n field.type !== SolidFieldType.mediaMultiple && // Exclude media multiple fields\n field.type !== SolidFieldType.mediaSingle &&\n field.type !== SolidFieldType.computed && // Exclude computed fields\n field.type !== SolidFieldType.password &&\n field.type !== SolidFieldType.richText &&\n field.type !== SolidFieldType.uuid &&\n field.isSystem !== true // Exclude system fields\n );\n }\n\n private async getFileRecordsSample(importFileStream: Readable, mimeType: string): Promise<ImportPaginatedReadResult> {\n // Depending upon the mime type of the file, read the file in pages\n // For CSV files, use the csvService to read the file in pages\n // For Excel files, use the excelService to read the file in pages\n if (mimeType === 'text/csv') {\n const generator = this.csvService.readCsvInPagesFromStream(importFileStream, { pageSize: 1 });\n const firstRecord = await generator.next(); // Get the first record to extract headers and sample data\n return firstRecord.value;\n } else if (mimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {\n const generator = this.excelService.readExcelInPagesFromStream(importFileStream, { pageSize: 1 });\n const firstRecord = await generator.next(); // Get the first record to extract headers and sample data\n return firstRecord.value;\n }\n else { // If the file is neither CSV nor Excel, throw an error\n throw new Error(`Unsupported file type: ${mimeType}`);\n }\n }\n\n private getImportFileObject(importTransaction: ImportTransaction): MediaWithFullUrl {\n const importFileMediaObject = importTransaction['_media']['fileLocation'][0] as MediaWithFullUrl; // Since there can be only one fileLocation, we can safely access the first element\n if (!importFileMediaObject) {\n throw new Error(`Import file for transaction ID ${importTransaction.id} not found.`);\n }\n return importFileMediaObject;\n }\n\n private async getImportFileStream(importFileMediaObject: MediaWithFullUrl): Promise<Readable> {\n const fileUrl = importFileMediaObject['_full_url'];\n const mimeType = importFileMediaObject['mimeType'];\n if (!fileUrl) {\n throw new Error(`File URL ${fileUrl} not found.`);\n }\n // From the file URL, convert the file URL to a readable stream using nestjs http service and axios\n const fileUrlResponse = await this.httpService.axiosRef.get(fileUrl, {\n responseType: 'stream',\n });\n\n if (!fileUrlResponse || !fileUrlResponse.data) {\n throw new Error(`Failed to read file from URL: ${fileUrl}`);\n }\n // fileUrlResponse.data is a Node.js Readable stream\n return fileUrlResponse.data;\n }\n\n private async importFromFileToDB(\n importTransaction: ImportTransaction,\n importFileStream: Readable,\n mimeType: string,\n ): Promise<ImportRecordsResult> {\n if (!importTransaction.modelMetadata) {\n throw new Error(`Model metadata for import transaction ID ${importTransaction.id} not found.`);\n }\n\n const createdRecordIds = [];\n const createdErrorLogIds = [];\n\n // Get the model service for the model metadata name\n const modelService = this.getModelService(importTransaction.modelMetadata.singularName);\n\n // Depending upon the mime type of the file, read the file in pages and insert the records into the database\n if (mimeType === ImportMimeTypes.CSV) {\n for await (const page of this.csvService.readCsvInPagesFromStream(importFileStream)) {\n const { ids, errorLogIds } = await this.importRecords(page, importTransaction, modelService);\n createdRecordIds.push(...ids);\n createdErrorLogIds.push(...errorLogIds);\n }\n }\n else if (mimeType === ImportMimeTypes.EXCEL) {\n for await (const page of this.excelService.readExcelInPagesFromStream(importFileStream)) {\n const { ids, errorLogIds } = await this.importRecords(page, importTransaction, modelService);\n createdRecordIds.push(...ids);\n createdErrorLogIds.push(...errorLogIds);\n }\n } else { // If the file is neither CSV nor Excel, throw an error\n throw new Error(`Unsupported file type: ${mimeType}`);\n }\n\n return {\n ids: createdRecordIds, // Return the IDs of the created records\n errorLogIds: createdErrorLogIds, // Return the IDs of the error log entries created during the import\n }\n }\n\n private async importRecords(page: ImportPaginatedReadResult, importTransaction: ImportTransaction, modelService: CRUDService<any>): Promise<ImportRecordsResult> {\n if (!importTransaction.modelMetadata || !importTransaction.modelMetadata.fields) {\n throw new Error(`Model metadata with fields for import transaction ID ${importTransaction.id} not found.`);\n }\n\n const ids: Array<number> = [];\n const errorLogIds: Array<number> = [];\n for (const record of page.data) {\n try {\n const createdRecord = await this.insertRecord(record, JSON.parse(importTransaction.mapping) as ImportMapping[], importTransaction.modelMetadata, modelService);\n ids.push(createdRecord.id); // Add the ID of the created record to the ids array\n }\n catch (error) {\n this.logger.debug(`Error inserting record: ${JSON.stringify(record)}. Error: ${error.message}`);\n // Get the Import transaction error log repo\n const errorLog = await this.createErrorLogEntry(importTransaction, record, error);\n errorLogIds.push(errorLog.id); // Add the ID of the error log entry to the errorLogIds array\n }\n }\n return {\n ids: ids, // Return the IDs of the created records\n errorLogIds: errorLogIds, // Return the IDs of the error log entries created during the import\n };\n }\n\n async createErrorLogEntry(importTransaction: ImportTransaction, record: Record<string, any>, error: any) {\n const importTransactionRepo = this.entityManager.getRepository(ImportTransactionErrorLog);\n // Create a new ImportTransactionErrorLog entry\n const rowNumber = uuidv4(); // Generate a unique row number or use page.rowNumber if available \n\n const errorLogEntry = {\n importTransactionErrorLogId: `${importTransaction.id}-${rowNumber}`, // FIXME pending to retrieve the row number from the page\n rowNumber: 1, // FIXME pending to retrieve the row number from the page\n rowData: JSON.stringify(record), // Store the row data\n importTransaction: importTransaction, // Link to the import transaction\n errorMessage: error.message, // Store the error message\n errorTrace: error.stack || '', // Store the error stack trace if available\n } as ImportTransactionErrorLog;\n\n // Save the error log entry to the database\n const savedEntry = await importTransactionRepo.save(errorLogEntry);\n return savedEntry; // Return the ID of the saved error log entry\n }\n\n //FIXME Currently below method fails if any field in the record is not valid or if the record is not valid. It does not collect the errors for all fields in a record\n private async insertRecord(record: Record<string, any>, mapping: ImportMapping[], modelMetadataWithFields: ModelMetadata, modelService: CRUDService<any>): Promise<any> {\n // Convert the imported record to a DTO\n const dto = await this.convertImportedRecordToDto(record, mapping, modelMetadataWithFields);\n // Use the model service to create the record in the database\n const createdRecord = await modelService.create(dto, [], {}); //FIXME: Need to handle this part alongwith the refactoring of the CRUDService for permissions\n return createdRecord; // Return the created record\n }\n\n private getModelService(modelSingularName: string): CRUDService<any> {\n // Get the model service for the model metadata name\n const modelServiceWrapper = this.introspectService.getProvider(`${classify(modelSingularName)}Service`);\n const modelService = modelServiceWrapper.instance as CRUDService<any>;\n if (!modelService) {\n throw new Error(`Model service for ${modelSingularName} not found.`);\n }\n return modelService;\n }\n\n private async convertImportedRecordToDto(record: Record<string, any>, mapping: ImportMapping[], modelMetadataWithFields: ModelMetadata) {\n // Create a new record object\n const dtoRecord: Record<string, any> = {};\n\n // Iterate through every cell in the record\n // Using the saved mapping, populate the dtoRecord w.r.t the record and fields\n for (const key in record) {\n const mappedField = mapping.find(m => m.header === key);\n if (mappedField) {\n // If the field is found in the mapping, get the field metadata from the model metadata\n const fieldMetadata = modelMetadataWithFields.fields.find(f => f.name === mappedField.fieldName);\n // const userKeyField = modelMetadataWithFields.fields.find(f => f.isUserKey === true); // Assuming userKey is a field in the model metadata\n if (fieldMetadata) {\n // If the field is found in the model metadata, set the value in the dtoRecord\n await this.populateDtoForACell(dtoRecord, fieldMetadata, record, key);\n } else {\n this.logger.warn(`Field ${mappedField.fieldName} not found in model metadata ${modelMetadataWithFields.singularName}`);\n }\n }\n }\n return dtoRecord;\n }\n\n private async populateDtoForACell(dtoRecord: Record<string, any>, fieldMetadata: FieldMetadata, record: Record<string, any>, key: string): Promise<Record<string, any>> {\n const fieldType = fieldMetadata.type;\n // const userKeyFieldName = userKeyField?.name || 'id'; // Default to 'id' if not found\n\n // TODO Move this logic to field crud managers i.e add a parse method to the field crud manager interface\n switch (fieldType) {\n case SolidFieldType.relation: {\n return await this.populateDtoForRelations(fieldMetadata, record, key, dtoRecord);\n }\n case SolidFieldType.date:\n case SolidFieldType.datetime: return this.populateDtoForDate(record, key, fieldMetadata, dtoRecord);\n case SolidFieldType.int:\n case SolidFieldType.bigint:\n case SolidFieldType.decimal:\n return this.populateDtoForNumber(dtoRecord, fieldMetadata, record, key);\n case SolidFieldType.boolean:\n return this.populateDtoForBoolean(dtoRecord, fieldMetadata, record, key);\n case SolidFieldType.selectionStatic:\n case SolidFieldType.selectionDynamic:\n return this.populateDtoForSelectionValues(dtoRecord, fieldMetadata, record, key);\n default:\n dtoRecord[fieldMetadata.name] = record[key];\n return dtoRecord;\n }\n }\n \n private populateDtoForSelectionValues(dtoRecord: Record<string, any>, fieldMetadata: FieldMetadata, record: Record<string, any>, key: string) {\n const rawValue = record[key];\n\n if (rawValue == null) {\n dtoRecord[fieldMetadata.name] = null;\n return dtoRecord;\n }\n\n const isMultipleSelection = fieldMetadata.isMultiSelect;\n\n if (isMultipleSelection) {\n const selectionValues = String(rawValue)\n .split(',')\n .map(value => value.trim())\n .filter(value => value !== '');\n\n dtoRecord[fieldMetadata.name] = JSON.stringify(selectionValues);\n } else {\n dtoRecord[fieldMetadata.name] = rawValue; // Single select: assign directly\n }\n\n return dtoRecord;\n }\n\n\n private populateDtoForBoolean(dtoRecord: Record<string, any>, fieldMetadata: FieldMetadata, record: Record<string, any>, key: string) {\n const booleanValue = Boolean(record[key]);\n if (typeof booleanValue !== 'boolean') {\n throw new Error(`Invalid boolean value for cell ${key} with value ${record[key]}`);\n }\n dtoRecord[fieldMetadata.name] = booleanValue;\n return dtoRecord;\n }\n\n private populateDtoForNumber(dtoRecord: Record<string, any>, fieldMetadata: FieldMetadata, record: Record<string, any>, key: string) {\n const numberValue = Number(record[key]);\n if (isNaN(numberValue)) {\n throw new Error(`Invalid number value for cell ${key} with value ${record[key]}`);\n }\n dtoRecord[fieldMetadata.name] = numberValue;\n return dtoRecord;\n }\n\n private populateDtoForDate(record: Record<string, any>, key: string, fieldMetadata: FieldMetadata, dtoRecord: Record<string, any>) {\n {\n const dateValue = new Date(record[key]);\n if (isNaN(dateValue.getTime())) {\n throw new Error(`Invalid date value for cell ${key} with value ${record[key]}`);\n }\n dtoRecord[fieldMetadata.name] = dateValue;\n return dtoRecord;\n }\n }\n\n private async populateDtoForRelations(fieldMetadata: FieldMetadata, record: Record<string, any>, key: string, dtoRecord: Record<string, any>) {\n if (!fieldMetadata.relationCoModelSingularName) {\n throw new Error(`Relation coModelSingularName is not defined for relation field ${fieldMetadata.name}`);\n }\n\n const relatedRecordsIds = await this.getRelatedEntityIdsFromUserKeys(fieldMetadata, record, key);\n if (relatedRecordsIds.length === 0) {\n return dtoRecord; // If no related records found, return the dtoRecord as is\n }\n\n if (fieldMetadata.relationType === RelationType.manyTomany || fieldMetadata.relationType === RelationType.oneToMany) {\n dtoRecord[`${fieldMetadata.name}Ids`] = relatedRecordsIds;\n dtoRecord[`${fieldMetadata.name}Command`] = RelationFieldsCommand.set; // Reset the relation field association with the related records IDs\n }\n else if (fieldMetadata.relationType === RelationType.manyToOne) {\n dtoRecord[`${fieldMetadata.name}Id`] = relatedRecordsIds.pop(); // For many-to-one relations, we need only one ID\n }\n return dtoRecord;\n }\n\n private async getRelatedEntityIdsFromUserKeys(fieldMetadata: FieldMetadata, record: Record<string, any>, key: string): Promise<Array<number>> {\n // For many-to-many or one-to-many relations, we expect the record cell to contains a comma-separated list of userKeys\n const relationUserKeys = record[key] ? String(record[key]).split(',').map((userKey: string) => userKey.trim()) : [];\n if (relationUserKeys.length === 0) return [];\n\n const coModelService = this.getModelService(fieldMetadata.relationCoModelSingularName);\n const coModelWithUserKeyField = await this.modelMetadataService.findOneBySingularName(fieldMetadata.relationCoModelSingularName, ['userKeyField']);\n const coModelUserKeyFieldName = coModelWithUserKeyField?.userKeyField?.name || 'id'; // Default to 'id' if not found\n\n\n // Set the relation basic filter dto filters with the userkeys and call the find method of the model service to get the related records\n const relationFilterDto = {\n filters: {\n [coModelUserKeyFieldName]: {\n $in: relationUserKeys, // Use the userKeyFieldName to filter by userKeys\n },\n },\n };\n\n // From the userKeys, we will get the IDs of the related records using the userKeyFieldName and throw an error if any of the userKeys is not found\n const relatedRecordsResult = await coModelService.find(relationFilterDto);\n if (!relatedRecordsResult || !relatedRecordsResult.records || relatedRecordsResult.records.length === 0 || relatedRecordsResult.records.length !== relationUserKeys.length) {\n throw new Error(`Invalid related records userKey values found for cell ${key} with value ${record[key]}`);\n }\n const relatedRecordsIds = relatedRecordsResult.records.map(record => record.id);\n return relatedRecordsIds;\n }\n}"]}
@@ -19,6 +19,7 @@ export declare class ListOfValuesService extends CRUDService<ListOfValues> {
19
19
  readonly moduleRef: ModuleRef;
20
20
  constructor(modelMetadataService: ModelMetadataService, moduleMetadataService: ModuleMetadataService, configService: ConfigService, fileService: FileService, discoveryService: DiscoveryService, crudHelperService: CrudHelperService, entityManager: EntityManager, repo: Repository<ListOfValues>, moduleRef: ModuleRef);
21
21
  findOneByValueAndType(lovValue: string, lovType: string): Promise<ListOfValues>;
22
+ findAll(): Promise<ListOfValues[]>;
22
23
  upsert(updateListOfValuesDto: any): Promise<any>;
23
24
  }
24
25
  //# sourceMappingURL=list-of-values.service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"list-of-values.service.d.ts","sourceRoot":"","sources":["../../src/services/list-of-values.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAEpD,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAGrE,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAEjE,qBACa,mBAAoB,SAAQ,WAAW,CAAC,YAAY,CAAC;IAE9D,QAAQ,CAAC,oBAAoB,EAAE,oBAAoB;IACnD,QAAQ,CAAC,qBAAqB,EAAE,qBAAqB;IACrD,QAAQ,CAAC,aAAa,EAAE,aAAa;IACrC,QAAQ,CAAC,WAAW,EAAE,WAAW;IACjC,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB;IAC3C,QAAQ,CAAC,iBAAiB,EAAE,iBAAiB;IAE7C,QAAQ,CAAC,aAAa,EAAE,aAAa;IAErC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,YAAY,CAAC;IACvC,QAAQ,CAAC,SAAS,EAAE,SAAS;gBAVpB,oBAAoB,EAAE,oBAAoB,EAC1C,qBAAqB,EAAE,qBAAqB,EAC5C,aAAa,EAAE,aAAa,EAC5B,WAAW,EAAE,WAAW,EACxB,gBAAgB,EAAE,gBAAgB,EAClC,iBAAiB,E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B,oBAAoB,EAAE,oBAAoB,EAC1C,qBAAqB,EAAE,qBAAqB,EAC5C,aAAa,EAAE,aAAa,EAC5B,WAAW,EAAE,WAAW,EACxB,gBAAgB,EAAE,gBAAgB,EAClC,iBAAiB,EAAE,iBAAiB,EAEpC,aAAa,EAAE,aAAa,EAE5B,IAAI,EAAE,UAAU,CAAC,YAAY,CAAC,EAC9B,SAAS,EAAE,SAAS;IAKzB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IASvD,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAIlC,MAAM,CAAC,qBAAqB,EAAE,GAAG;CAoBxC"}
@@ -45,6 +45,9 @@ let ListOfValuesService = class ListOfValuesService extends crud_service_1.CRUDS
45
45
  },
46
46
  });
47
47
  }
48
+ async findAll() {
49
+ return await this.repo.find();
50
+ }
48
51
  async upsert(updateListOfValuesDto) {
49
52
  const existingListOfValue = await this.repo.findOne({
50
53
  where: {
@@ -1 +1 @@
1
- {"version":3,"file":"list-of-values.service.js","sourceRoot":"","sources":["../../src/services/list-of-values.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAA4C;AAC5C,6CAAwE;AACxE,uCAA2D;AAC3D,qCAAoD;AAEpD,iDAAwD;AACxD,qEAA2E;AAC3E,uEAA6E;AAC7E,2CAA+C;AAC/C,iDAAwD;AACxD,+DAAqE;AAGrE,6EAAiE;AAG1D,IAAM,mBAAmB,GAAzB,MAAM,mBAAoB,SAAQ,0BAAyB;IAChE,YACW,oBAA0C,EAC1C,qBAA4C,EAC5C,aAA4B,EAC5B,WAAwB,EACxB,gBAAkC,EAClC,iBAAoC,EAEpC,aAA4B,EAE5B,IAA8B,EAC9B,SAAoB;QAG7B,KAAK,CAAC,oBAAoB,EAAE,qBAAqB,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,aAAa,EAAE,IAAI,EAAE,cAAc,EAAE,YAAY,EAAE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IAAA,0BAAgB,EAAC,oCAAY,EAAE,SAAS,CAAC,CAAA;qCARX,6CAAoB;QACnB,+CAAqB;QAC7B,sBAAa;QACf,0BAAW;QACN,uBAAgB;QACf,uCAAiB;QAErB,uBAAa;QAEtB,oBAAU;QACL,gBAAS;GAZpB,mBAAmB,CA6C/B","sourcesContent":["import { Injectable } from '@nestjs/common';\nimport { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';\nimport { DiscoveryService, ModuleRef } from \"@nestjs/core\";\nimport { EntityManager, Repository } from 'typeorm';\n\nimport { CRUDService } from 'src/services/crud.service';\nimport { ModelMetadataService } from 'src/services/model-metadata.service';\nimport { ModuleMetadataService } from 'src/services/module-metadata.service';\nimport { ConfigService } from '@nestjs/config';\nimport { FileService } from 'src/services/file.service';\nimport { CrudHelperService } from 'src/services/crud-helper.service';\n\n\nimport { ListOfValues } from '../entities/list-of-values.entity';\n\n@Injectable()\nexport class ListOfValuesService extends CRUDService<ListOfValues> {\n constructor(\n readonly modelMetadataService: ModelMetadataService,\n readonly moduleMetadataService: ModuleMetadataService,\n readonly configService: ConfigService,\n readonly fileService: FileService,\n readonly discoveryService: DiscoveryService,\n readonly crudHelperService: CrudHelperService,\n @InjectEntityManager()\n readonly entityManager: EntityManager,\n @InjectRepository(ListOfValues, 'default')\n readonly repo: Repository<ListOfValues>,\n readonly moduleRef: ModuleRef\n\n ) {\n super(modelMetadataService, moduleMetadataService, configService, fileService, discoveryService, crudHelperService, entityManager, repo, 'listOfValues', 'solid-core', moduleRef);\n }\n async findOneByValueAndType(lovValue: string, lovType: string) {\n return await this.repo.findOne({\n where: {\n value: lovValue,\n type: lovType,\n },\n });\n }\n async upsert(updateListOfValuesDto: any) {\n // First check if module already exists using name\n const existingListOfValue = await this.repo.findOne({\n where: {\n value: updateListOfValuesDto.value\n }\n })\n\n // if found\n if (existingListOfValue) {\n const updatedListOfValuesDto = { ...existingListOfValue, ...updateListOfValuesDto };\n return this.repo.save(updatedListOfValuesDto);\n }\n // if not found - create new \n else {\n const listOfValue = this.repo.create(updateListOfValuesDto);\n return this.repo.save(listOfValue);\n }\n }\n\n}\n"]}
1
+ {"version":3,"file":"list-of-values.service.js","sourceRoot":"","sources":["../../src/services/list-of-values.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAA4C;AAC5C,6CAAwE;AACxE,uCAA2D;AAC3D,qCAAoD;AAEpD,iDAAwD;AACxD,qEAA2E;AAC3E,uEAA6E;AAC7E,2CAA+C;AAC/C,iDAAwD;AACxD,+DAAqE;AAGrE,6EAAiE;AAG1D,IAAM,mBAAmB,GAAzB,MAAM,mBAAoB,SAAQ,0BAAyB;IAChE,YACW,oBAA0C,EAC1C,qBAA4C,EAC5C,aAA4B,EAC5B,WAAwB,EACxB,gBAAkC,EAClC,iBAAoC,EAEpC,aAA4B,EAE5B,IAA8B,EAC9B,SAAoB;QAG7B,KAAK,CAAC,oBAAoB,EAAE,qBAAqB,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,aAAa,EAAE,IAAI,EAAE,cAAc,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;QAbzK,yBAAoB,GAApB,oBAAoB,CAAsB;QAC1C,0BAAqB,GAArB,qBAAqB,CAAuB;QAC5C,kBAAa,GAAb,aAAa,CAAe;QAC5B,gBAAW,GAAX,WAAW,CAAa;QACxB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,sBAAiB,GAAjB,iBAAiB,CAAmB;QAEpC,kBAAa,GAAb,aAAa,CAAe;QAE5B,SAAI,GAAJ,IAAI,CAA0B;QAC9B,cAAS,GAAT,SAAS,CAAW;IAI/B,CAAC;IACD,KAAK,CAAC,qBAAqB,CAAC,QAAgB,EAAE,OAAe;QAC3D,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;YAC7B,KAAK,EAAE;gBACL,KAAK,EAAE,QAAQ;gBACf,IAAI,EAAE,OAAO;aACd;SACF,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,OAAO;QACX,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAChC,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,qBAA0B;QAErC,MAAM,mBAAmB,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;YAClD,KAAK,EAAE;gBACL,KAAK,EAAE,qBAAqB,CAAC,KAAK;aACnC;SACF,CAAC,CAAA;QAGF,IAAI,mBAAmB,EAAE,CAAC;YACxB,MAAM,sBAAsB,GAAG,EAAE,GAAG,mBAAmB,EAAE,GAAG,qBAAqB,EAAE,CAAC;YACpF,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;QAChD,CAAC;aAEI,CAAC;YACJ,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,qBAAqB,CAAC,CAAC;YAC5D,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;CAEF,CAAA;AAlDY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,mBAAU,GAAE;IASR,WAAA,IAAA,6BAAmB,GAAE,CAAA;IAErB,WAAA,IAAA,0BAAgB,EAAC,oCAAY,EAAE,SAAS,CAAC,CAAA;qCARX,6CAAoB;QACnB,+CAAqB;QAC7B,sBAAa;QACf,0BAAW;QACN,uBAAgB;QACf,uCAAiB;QAErB,uBAAa;QAEtB,oBAAU;QACL,gBAAS;GAZpB,mBAAmB,CAkD/B","sourcesContent":["import { Injectable } from '@nestjs/common';\nimport { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';\nimport { DiscoveryService, ModuleRef } from \"@nestjs/core\";\nimport { EntityManager, Repository } from 'typeorm';\n\nimport { CRUDService } from 'src/services/crud.service';\nimport { ModelMetadataService } from 'src/services/model-metadata.service';\nimport { ModuleMetadataService } from 'src/services/module-metadata.service';\nimport { ConfigService } from '@nestjs/config';\nimport { FileService } from 'src/services/file.service';\nimport { CrudHelperService } from 'src/services/crud-helper.service';\n\n\nimport { ListOfValues } from '../entities/list-of-values.entity';\n\n@Injectable()\nexport class ListOfValuesService extends CRUDService<ListOfValues> {\n constructor(\n readonly modelMetadataService: ModelMetadataService,\n readonly moduleMetadataService: ModuleMetadataService,\n readonly configService: ConfigService,\n readonly fileService: FileService,\n readonly discoveryService: DiscoveryService,\n readonly crudHelperService: CrudHelperService,\n @InjectEntityManager()\n readonly entityManager: EntityManager,\n @InjectRepository(ListOfValues, 'default')\n readonly repo: Repository<ListOfValues>,\n readonly moduleRef: ModuleRef\n\n ) {\n super(modelMetadataService, moduleMetadataService, configService, fileService, discoveryService, crudHelperService, entityManager, repo, 'listOfValues', 'solid-core', moduleRef);\n }\n async findOneByValueAndType(lovValue: string, lovType: string) {\n return await this.repo.findOne({\n where: {\n value: lovValue,\n type: lovType,\n },\n });\n }\n\n async findAll(): Promise<ListOfValues[]> {\n return await this.repo.find();\n }\n \n async upsert(updateListOfValuesDto: any) {\n // First check if module already exists using name\n const existingListOfValue = await this.repo.findOne({\n where: {\n value: updateListOfValuesDto.value\n }\n })\n\n // if found\n if (existingListOfValue) {\n const updatedListOfValuesDto = { ...existingListOfValue, ...updateListOfValuesDto };\n return this.repo.save(updatedListOfValuesDto);\n }\n // if not found - create new \n else {\n const listOfValue = this.repo.create(updateListOfValuesDto);\n return this.repo.save(listOfValue);\n }\n }\n\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import { SolidIntrospectService } from '../solid-introspect.service';
2
+ import { IMcpToolResponseHandler } from 'src/interfaces';
3
+ export declare class McpToolResponseHandlerFactory {
4
+ private readonly solidIntrospectionService;
5
+ private readonly logger;
6
+ constructor(solidIntrospectionService: SolidIntrospectService);
7
+ getInstance(toolInvoked: string): IMcpToolResponseHandler;
8
+ }
9
+ //# sourceMappingURL=mcp-tool-response-handler-factory.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-tool-response-handler-factory.service.d.ts","sourceRoot":"","sources":["../../../src/services/mcp-tool-response-handlers/mcp-tool-response-handler-factory.service.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAGzD,qBACa,6BAA6B;IAIlC,OAAO,CAAC,QAAQ,CAAC,yBAAyB;IAH9C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkD;gBAGpD,yBAAyB,EAAE,sBAAsB;IAItE,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,uBAAuB;CAiB5D"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var McpToolResponseHandlerFactory_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.McpToolResponseHandlerFactory = void 0;
14
+ const common_1 = require("@nestjs/common");
15
+ const common_2 = require("@nestjs/common");
16
+ const strings_1 = require("@angular-devkit/core/src/utils/strings");
17
+ const solid_introspect_service_1 = require("../solid-introspect.service");
18
+ let McpToolResponseHandlerFactory = McpToolResponseHandlerFactory_1 = class McpToolResponseHandlerFactory {
19
+ constructor(solidIntrospectionService) {
20
+ this.solidIntrospectionService = solidIntrospectionService;
21
+ this.logger = new common_1.Logger(McpToolResponseHandlerFactory_1.name);
22
+ }
23
+ getInstance(toolInvoked) {
24
+ toolInvoked = (0, strings_1.classify)(toolInvoked);
25
+ let resolvedHandlerName = `${toolInvoked}McpToolResponseHandler`;
26
+ let actualHandler = this.solidIntrospectionService.getProvider(resolvedHandlerName);
27
+ if (!actualHandler) {
28
+ throw new Error(`Unable to locate mcp tool handler with name ${resolvedHandlerName}`);
29
+ }
30
+ const actualHandlerInstance = actualHandler.instance;
31
+ this.logger.error(`Resolved mcp tool response handler with name ${actualHandler.name}`);
32
+ return actualHandlerInstance;
33
+ }
34
+ };
35
+ exports.McpToolResponseHandlerFactory = McpToolResponseHandlerFactory;
36
+ exports.McpToolResponseHandlerFactory = McpToolResponseHandlerFactory = McpToolResponseHandlerFactory_1 = __decorate([
37
+ (0, common_2.Injectable)(),
38
+ __metadata("design:paramtypes", [solid_introspect_service_1.SolidIntrospectService])
39
+ ], McpToolResponseHandlerFactory);
40
+ //# sourceMappingURL=mcp-tool-response-handler-factory.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-tool-response-handler-factory.service.js","sourceRoot":"","sources":["../../../src/services/mcp-tool-response-handlers/mcp-tool-response-handler-factory.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,2CAAwC;AACxC,2CAA4C;AAG5C,oEAAkE;AAClE,0EAAqE;AAK9D,IAAM,6BAA6B,qCAAnC,MAAM,6BAA6B;IAGtC,YACqB,yBAAiD;QAAjD,8BAAyB,GAAzB,yBAAyB,CAAwB;QAHrD,WAAM,GAAG,IAAI,eAAM,CAAC,+BAA6B,CAAC,IAAI,CAAC,CAAC;IAKzE,CAAC;IAED,WAAW,CAAC,WAAmB;QAC3B,WAAW,GAAG,IAAA,kBAAQ,EAAC,WAAW,CAAC,CAAC;QAEpC,IAAI,mBAAmB,GAAG,GAAG,WAAW,wBAAwB,CAAC;QAGjE,IAAI,aAAa,GAAG,IAAI,CAAC,yBAAyB,CAAC,WAAW,CAAC,mBAAmB,CAAC,CAAC;QACpF,IAAI,CAAC,aAAa,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,+CAA+C,mBAAmB,EAAE,CAAC,CAAC;QAC1F,CAAC;QAGD,MAAM,qBAAqB,GAA4B,aAAa,CAAC,QAAQ,CAAC;QAC9E,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gDAAgD,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC;QAExF,OAAO,qBAAqB,CAAC;IACjC,CAAC;CACJ,CAAA;AAzBY,sEAA6B;wCAA7B,6BAA6B;IADzC,IAAA,mBAAU,GAAE;qCAKuC,iDAAsB;GAJ7D,6BAA6B,CAyBzC","sourcesContent":["import { Logger } from '@nestjs/common';\nimport { Injectable } from '@nestjs/common';\n\nimport { QueueMessage, QueuePublisher } from 'src/interfaces/mq';\nimport { classify } from '@angular-devkit/core/src/utils/strings';\nimport { SolidIntrospectService } from '../solid-introspect.service';\nimport { IMcpToolResponseHandler } from 'src/interfaces';\n\n\n@Injectable()\nexport class McpToolResponseHandlerFactory {\n private readonly logger = new Logger(McpToolResponseHandlerFactory.name);\n\n constructor(\n private readonly solidIntrospectionService: SolidIntrospectService\n ) {\n }\n\n getInstance(toolInvoked: string): IMcpToolResponseHandler {\n toolInvoked = classify(toolInvoked);\n\n let resolvedHandlerName = `${toolInvoked}McpToolResponseHandler`;\n\n // Register all ISolidDatabaseModules implementations\n let actualHandler = this.solidIntrospectionService.getProvider(resolvedHandlerName);\n if (!actualHandler) {\n throw new Error(`Unable to locate mcp tool handler with name ${resolvedHandlerName}`);\n }\n\n // type safe\n const actualHandlerInstance: IMcpToolResponseHandler = actualHandler.instance;\n this.logger.error(`Resolved mcp tool response handler with name ${actualHandler.name}`);\n\n return actualHandlerInstance;\n }\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import { IMcpToolResponseHandler } from "../../interfaces";
2
+ import { AiInteraction } from "src/entities/ai-interaction.entity";
3
+ import { ModuleMetadataService } from "../module-metadata.service";
4
+ import { SolidRegistry } from "src/helpers/solid-registry";
5
+ export declare class SolidCreateModuleMcpToolResponseHandler implements IMcpToolResponseHandler {
6
+ private readonly moduleMetadataService;
7
+ private readonly solidRegistry;
8
+ constructor(moduleMetadataService: ModuleMetadataService, solidRegistry: SolidRegistry);
9
+ apply(aiInteraction: AiInteraction): Promise<{}>;
10
+ }
11
+ //# sourceMappingURL=solid-create-module-mcp-tool-response-handler.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solid-create-module-mcp-tool-response-handler.service.d.ts","sourceRoot":"","sources":["../../../src/services/mcp-tool-response-handlers/solid-create-module-mcp-tool-response-handler.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE3D,qBACa,uCAAwC,YAAW,uBAAuB;IAG/E,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IACtC,OAAO,CAAC,QAAQ,CAAC,aAAa;gBADb,qBAAqB,EAAE,qBAAqB,EAC5C,aAAa,EAAE,aAAa;IAK3C,KAAK,CAAC,aAAa,EAAE,aAAa;CAkC3C"}
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.SolidCreateModuleMcpToolResponseHandler = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const module_metadata_service_1 = require("../module-metadata.service");
15
+ const solid_registry_1 = require("../../helpers/solid-registry");
16
+ let SolidCreateModuleMcpToolResponseHandler = class SolidCreateModuleMcpToolResponseHandler {
17
+ constructor(moduleMetadataService, solidRegistry) {
18
+ this.moduleMetadataService = moduleMetadataService;
19
+ this.solidRegistry = solidRegistry;
20
+ }
21
+ async apply(aiInteraction) {
22
+ const aiResponse = JSON.parse(aiInteraction.message);
23
+ const moduleMetadata = aiResponse['moduleMetadata'];
24
+ const createDto = {
25
+ defaultDataSource: 'default',
26
+ description: moduleMetadata['description'],
27
+ displayName: moduleMetadata['displayName'],
28
+ isSystem: false,
29
+ menuIconUrl: '',
30
+ models: [],
31
+ name: moduleMetadata['name'],
32
+ menuSequenceNumber: 1
33
+ };
34
+ const moduleObj = await this.moduleMetadataService.create(createDto);
35
+ const seeder = this.solidRegistry.getSeeders().filter((seeder) => seeder.name === 'ModuleMetadataSeederService').map((seeder) => seeder.instance).pop();
36
+ await this.moduleMetadataService.generateCode({ moduleId: moduleObj.id });
37
+ return {};
38
+ }
39
+ };
40
+ exports.SolidCreateModuleMcpToolResponseHandler = SolidCreateModuleMcpToolResponseHandler;
41
+ exports.SolidCreateModuleMcpToolResponseHandler = SolidCreateModuleMcpToolResponseHandler = __decorate([
42
+ (0, common_1.Injectable)(),
43
+ __metadata("design:paramtypes", [module_metadata_service_1.ModuleMetadataService,
44
+ solid_registry_1.SolidRegistry])
45
+ ], SolidCreateModuleMcpToolResponseHandler);
46
+ //# sourceMappingURL=solid-create-module-mcp-tool-response-handler.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solid-create-module-mcp-tool-response-handler.service.js","sourceRoot":"","sources":["../../../src/services/m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A3CY,0FAAuC;kDAAvC,uCAAuC;IADnD,IAAA,mBAAU,GAAE;qCAImC,+CAAqB;QAC7B,8BAAa;GAJxC,uCAAuC,CA2CnD","sourcesContent":["import { Injectable } from \"@nestjs/common\";\nimport { IMcpToolResponseHandler } from \"../../interfaces\";\nimport { AiInteraction } from \"src/entities/ai-interaction.entity\";\nimport { ModuleMetadataService } from \"../module-metadata.service\";\nimport { CreateModuleMetadataDto } from \"src/dtos/create-module-metadata.dto\";\nimport { SolidRegistry } from \"src/helpers/solid-registry\";\n\n@Injectable()\nexport class SolidCreateModuleMcpToolResponseHandler implements IMcpToolResponseHandler {\n\n constructor(\n private readonly moduleMetadataService: ModuleMetadataService,\n private readonly solidRegistry: SolidRegistry,\n\n ) {\n }\n\n async apply(aiInteraction: AiInteraction) {\n const aiResponse = JSON.parse(aiInteraction.message);\n\n const moduleMetadata = aiResponse['moduleMetadata'];\n\n // TODO: Validate if another module with same name exists, if it does then raise an error...\n\n const createDto: CreateModuleMetadataDto = {\n defaultDataSource: 'default',\n description: moduleMetadata['description'],\n displayName: moduleMetadata['displayName'],\n isSystem: false,\n menuIconUrl: '',\n models: [],\n name: moduleMetadata['name'],\n menuSequenceNumber: 1\n }\n\n // This creates the module-metadata.json file....\n const moduleObj = await this.moduleMetadataService.create(createDto);\n\n const seeder = this.solidRegistry.getSeeders().filter((seeder) => seeder.name === 'ModuleMetadataSeederService').map((seeder) => seeder.instance).pop();\n\n // Now we need to run solid seed & then solid refresh-model --name <module-name>\n await this.moduleMetadataService.generateCode({ moduleId: moduleObj.id });\n\n // solid seed ... this has to be run after reboot from the UI...\n // await new Promise(resolve => setTimeout(resolve, 1000));\n // await seeder.seed();\n\n // TODO: decide on some shape to return hre...\n return {}\n }\n\n}"]}
@@ -1 +1 @@
1
- {"version":3,"file":"module-metadata.service.d.ts","sourceRoot":"","sources":["../../src/services/module-metadata.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,UAAU,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,YAAY,CAAC,IAAI,EAAE,MAAM;IAOzB,MAAM,CAAC,EAAE,EAAE,MAAM;IAKjB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC;IAsBvC,iBAAiB;IAMjB,YAAY,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC;YAuBrD,qBAAqB;YAgBrB,yBAAyB;IAkBvC,OAAO,CAAC,0BAA0B;IAMlC,OAAO,CAAC,WAAW;CAIpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"module-metadata.service.js","sourceRoot":"","sources":["../../src/services/module-metadata.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAgH;AAChH,6CAAqE;AACrE,qCAAoF;AAEpF,+EAAoE;AAEpE,oEAAkE;AAClE,2CAA+C;AAC/C,gDAAkC;AAClC,2CAA6B;AAC7B,sGAAiG;AACjG,iDAAwD;AAGxD,oEAGsC;AACtC,8DAA0D;AAE1D,+DAA0D;AAC1D,qEAAgE;AAChE,8FAAyF;AACzF,qGAAuF;AAGhF,IAAM,qBAAqB,6BAA3B,MAAM,qBAAqB;IAGhC,YAEE,UAAuC,EAEvC,kBAA+D,EAC9C,iBAAoC,EACpC,gBAAkC,EAClC,aAA4B,EAC5B,WAAwB,EACxB,wBAAyD,EAE1E,oBAA2D,EAC1C,aAA4B,EAC5B,2BAAwD;QAXxD,eAAU,GAAV,UAAU,CAAY;QAEtB,uBAAkB,GAAlB,kBAAkB,CAA4B;QAC9C,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,kBAAa,GAAb,aAAa,CAAe;QAC5B,gBAAW,GAAX,WAAW,CAAa;QACxB,6BAAwB,GAAxB,wBAAwB,CAAiC;QAEzD,yBAAoB,GAApB,oBAAoB,CAAsB;QAC1C,kBAAa,GAAb,aAAa,CAAe;Q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AAM,GAAG,MAAM,IAAI,CAAC,oBAAoB,CAAC,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;YACzF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,sBAAsB,MAAM,EAAE,CAAC,CAAC;YAClD,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QAC1B,CAAC;QACD,OAAO,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAEO,0BAA0B,CAAC,QAAgB;QACjD,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,4BAA4B,CAAC,IAAI,QAAQ,EAAE,CAAC;IAC/E,CAAC;IAIO,WAAW,CAAC,IAAyB;QAC3C,OAAO,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;IACjD,CAAC;CAEF,CAAA;AA1YY,sDAAqB;AAuU1B;IADL,IAAA,uDAAoB,GAAE;;;;yDAsBtB;gCA5VU,qBAAqB;IADjC,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,0BAAgB,GAAE,CAAA;IAElB,WAAA,IAAA,0BAAgB,EAAC,uCAAc,CAAC,CAAA;IAOhC,WAAA,IAAA,eAAM,EAAC,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,6CAAoB,CAAC,CAAC,CAAA;qCARlB,oBAAU;QAEF,oBAAU;QACX,uCAAiB;QAClB,oCAAgB;QACnB,sBAAa;QACf,0BAAW;QACE,oEAA+B;QAEnC,6CAAoB;QAC3B,8BAAa;QACC,4DAA2B;GAhBhE,qBAAqB,CA0YjC","sourcesContent":["import { BadRequestException, forwardRef, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';\nimport { InjectDataSource, InjectRepository } from '@nestjs/typeorm';\nimport { DataSource, EntityManager, Repository, SelectQueryBuilder } from 'typeorm';\nimport { CreateModuleMetadataDto } from '../dtos/create-module-metadata.dto';\nimport { ModuleMetadata } from '../entities/module-metadata.entity';\n\nimport { classify } from '@angular-devkit/core/src/utils/strings';\nimport { ConfigService } from '@nestjs/config';\nimport * as fs from 'fs/promises'; // Use the Promise-based version of fs for async/await\nimport * as path from 'path'; // To handle file paths\nimport { PermissionMetadataSeederService } from 'src/seeders/permission-metadata-seeder.service';\nimport { FileService } from 'src/services/file.service';\nimport { BasicFilterDto } from '../dtos/basic-filters.dto';\nimport { UpdateModuleMetadataDto } from '../dtos/update-module-metadata.dto';\nimport {\n ADD_MODULE_COMMAND,\n SchematicService,\n} from '../helpers/schematic.service';\nimport { SolidRegistry } from '../helpers/solid-registry';\nimport { CodeGenerationOptions, ModuleMetadataConfiguration } from '../interfaces';\nimport { CrudHelperService } from './crud-helper.service';\nimport { ModelMetadataService } from './model-metadata.service';\nimport { ModuleMetadataHelperService } from 'src/helpers/module-metadata-helper.service';\nimport { DisallowInProduction } from 'src/decorators/disallow-in-production.decorator';\n\n@Injectable()\nexport class ModuleMetadataService {\n private readonly logger = new Logger(ModuleMetadataService.name);\n\n constructor(\n @InjectDataSource()\n private readonly dataSource: DataSource,\n @InjectRepository(ModuleMetadata)\n private readonly moduleMetadataRepo: Repository<ModuleMetadata>,\n private readonly crudHelperService: CrudHelperService,\n private readonly schematicService: SchematicService,\n private readonly configService: ConfigService,\n private readonly fileService: FileService,\n private readonly permissionsSeederService: PermissionMetadataSeederService,\n @Inject(forwardRef(() => ModelMetadataService))\n private readonly modelMetadataService: ModelMetadataService,\n private readonly solidRegistry: SolidRegistry,\n private readonly moduleMetadataHelperService: ModuleMetadataHelperService,\n ) { }\n\n async findMany(basicFilterDto: BasicFilterDto) {\n const alias = 'moduleMetadata';\n // Extract the required keys from the input query\n let { limit, offset } = basicFilterDto;\n\n // Create above query on pincode table using query builder\n var qb: SelectQueryBuilder<ModuleMetadata> = this.moduleMetadataRepo.createQueryBuilder(alias)\n qb = await this.crudHelperService.buildFilterQuery(qb, basicFilterDto, alias);\n\n // Get the records and the count\n const [entities, count] = await qb.getManyAndCount();\n\n const currentPage = Math.floor(offset / limit) + 1;\n const totalPages = Math.ceil(count / limit);\n\n const nextPage = currentPage < totalPages ? currentPage + 1 : null;\n const prevPage = currentPage > 1 ? currentPage - 1 : null;\n\n const r = {\n meta: {\n totalRecords: count,\n currentPage: currentPage,\n nextPage: nextPage,\n prevPage: prevPage,\n totalPages: totalPages,\n perPage: +limit,\n },\n records: entities\n };\n return r\n }\n\n async findOneByUserKey(name: string, relations = {}) {\n if (!name) {\n throw new BadRequestException('name is required for finding entity');\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n name: name,\n },\n relations: relations,\n });\n return entity;\n }\n\n async findOne(id: number, relations = {}) {\n if (!id) {\n throw new BadRequestException('ID is required for finding entity');\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n id: id,\n },\n relations: relations,\n });\n if (!entity) {\n throw new NotFoundException(`entity #${id} not found`);\n }\n return entity;\n }\n\n async create(createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.createInDB(manager, createDto, files);\n await this.createInFile(module);\n return module\n });\n } catch (error) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n async createInDB(manager: EntityManager, createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n if (files.length > 0) {\n const fileStoragePath = this.getFileSysytemFullFilePath(this.getFileName(files[0]));\n this.fileService.copyFile(files[0].path, fileStoragePath);\n this.fileService.deleteFile(files[0].path);\n createDto.menuIconUrl = fileStoragePath;\n }\n const moduleMetadata = this.moduleMetadataRepo.create(createDto);\n return manager.save(moduleMetadata); // Use the provided manager to perform DB operations\n }\n\n async createInFile(module: ModuleMetadata) {\n try {\n // Prepare the metadata JSON structure\n\n const moduleMetaDataJson: ModuleMetadataConfiguration = {\n moduleMetadata: {\n name: module?.name,\n displayName: module?.displayName,\n description: module?.description,\n defaultDataSource: module?.defaultDataSource,\n menuIconUrl: module?.menuIconUrl,\n menuSequenceNumber: module?.menuSequenceNumber,\n isSystem: module?.isSystem,\n models: [],\n },\n roles: [],\n users: [],\n actions: [\n {\n displayName: `${module?.name} Home`,\n name: `${module?.name}-home-action`,\n type: \"custom\",\n domain: \"\",\n context: \"\",\n customComponent: `/admin/core/${module?.name}/home`,\n customIsModal: true,\n serverEndpoint: \"\",\n viewUserKey: \"\",\n moduleUserKey: module?.name,\n modelUserKey: \"\"\n }\n ],\n menus: [\n {\n displayName: \"Home\",\n name: `${module?.name}-home-menu`,\n sequenceNumber: 1,\n actionUserKey: `${module?.name}-home-action`,\n moduleUserKey: module?.name,\n parentMenuItemUserKey: \"\"\n }\n ],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n securityRules: [],\n };\n\n // Convert the object to JSON string\n const metadataJson = JSON.stringify(moduleMetaDataJson, null, 2);\n\n // Create the folder path inside 'module-metadata'\n const folderPath = path.resolve(process.cwd(), 'module-metadata', module.name);\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Ensure the folder exists\n await fs.mkdir(folderPath, { recursive: true });\n\n // Write the JSON to the file\n await fs.writeFile(filePath, metadataJson);\n\n } catch (error) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error('File creation failed, rolling back transaction'); // Trigger rollback\n }\n }\n\n async update(id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.updateInDB(manager, id, updateModuleMetadataDto, files);\n await this.updateInFile(module);\n return module\n });\n } catch (error) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n\n\n async updateInDB(manager: EntityManager, id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n\n const module = await this.moduleMetadataRepo.preload({\n id,\n ...updateModuleMetadataDto,\n });\n\n if (!module) {\n throw new NotFoundException(`Module ${id} not found`);\n }\n if (files.length > 0) {\n\n const fileStoragePath = this.getFileSysytemFullFilePath(this.getFileName(files[0]));\n this.fileService.copyFile(files[0].path, fileStoragePath);\n this.fileService.deleteFile(files[0].path);\n module.menuIconUrl = fileStoragePath;\n }\n return manager.save(ModuleMetadata, module);\n }\n\n async updateInFile(module: ModuleMetadata) {\n try {\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Read the existing JSON file\n let metaData;\n try {\n metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);\n\n } catch (error) {\n metaData = {\n moduleMetadata: {\n name: null,\n displayName: null,\n description: null,\n defaultDataSource: null,\n menuIconUrl: null,\n menuSequenceNumber: null,\n isSystem: null,\n models: [],\n },\n roles: [],\n users: [],\n actions: [],\n menus: [],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n };\n }\n\n\n metaData.moduleMetadata.name = module?.name;\n metaData.moduleMetadata.displayName = module?.displayName;\n metaData.moduleMetadata.description = module?.description;\n metaData.moduleMetadata.defaultDataSource = module?.defaultDataSource;\n metaData.moduleMetadata.menuIconUrl = module?.menuIconUrl;\n metaData.moduleMetadata.menuSequenceNumber = module?.menuSequenceNumber;\n metaData.moduleMetadata.isSystem = module?.isSystem;\n\n // Write the JSON to the file\n const updatedContent = JSON.stringify(metaData, null, 2);\n await fs.writeFile(filePath, updatedContent);\n\n } catch (error) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error('File creation failed, rolling back transaction'); // Trigger rollback\n }\n }\n\n\n async upsert(updateModuleMetadataDto: UpdateModuleMetadataDto) {\n this.logger.log(`Module Upsert called for : ${updateModuleMetadataDto.name}`);\n // First check if module already exists using name\n const existingModuleMetadata = await this.moduleMetadataRepo.findOne({\n where: {\n name: updateModuleMetadataDto.name\n }\n })\n const { models, ...restUpdateModuleMetadataDto } = updateModuleMetadataDto;\n // if found\n if (existingModuleMetadata) {\n const updatedModuleMetadata = { ...existingModuleMetadata, ...restUpdateModuleMetadataDto };\n return this.moduleMetadataRepo.save(updatedModuleMetadata);\n }\n // if not found - create new \n else {\n const moduleMetadata = this.moduleMetadataRepo.create(restUpdateModuleMetadataDto);\n return this.moduleMetadataRepo.save(moduleMetadata);\n }\n }\n\n\n\n\n async removeByName(name: string) {\n const entity = await this.findOneByUserKey(name);\n if (entity) {\n await this.moduleMetadataRepo.remove(entity);\n }\n }\n\n async remove(id: number) {\n const entity = await this.findOne(id);\n return this.moduleMetadataRepo.remove(entity);\n }\n\n async deleteMany(ids: number[]): Promise<any> {\n if (!ids || ids.length === 0) {\n throw new Error('At least one ID is required for deletion');\n }\n const removedEntities = [];\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n //@ts-ignore\n id: id,\n }\n });\n // if (!entity) {\n // throw new Error(`Entity with id ${id} not found`);\n // }\n removedEntities.push(await this.moduleMetadataRepo.remove(entity));\n }\n\n return removedEntities\n }\n\n async refreshPermission() {\n await this.permissionsSeederService.seed();\n return true\n }\n\n @DisallowInProduction()\n async generateCode(options: CodeGenerationOptions): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException('Module ID or Module Name is required for generating code');\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n // Check if the module exists\n if (!module) {\n throw new NotFoundException(`Module ${options.moduleId} not found`);\n }\n\n // Check if the module name already exists and is loaded\n const moduleInstance = this.solidRegistry.getModule(`${classify(module.name)}Module`);\n\n if (!moduleInstance) {\n const addModuleOutput = await this.generateAddModuleCode(options);\n const refreshModuleOutput = await this.generateRefreshModuleCode(options);\n return `${addModuleOutput}\\n${refreshModuleOutput}`;\n } else {\n return await this.generateRefreshModuleCode(options);\n }\n }\n\n private async generateAddModuleCode(options: CodeGenerationOptions = { dryRun: false }): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException('Module ID or Module Name is required for generating code');\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n //Generate the module\n const output = await this.schematicService.executeSchematicCommand(\n ADD_MODULE_COMMAND,\n { module: module.name },\n options.dryRun ?? false\n );\n this.logger.debug(`Schematic output : ${output}`);\n return output;\n }\n\n private async generateRefreshModuleCode(options: CodeGenerationOptions): Promise<string> {\n const query = {\n relations: { models: { fields: true } },\n };\n const module = options.moduleId ? await this.findOne(options.moduleId, query.relations) : await this.findOneByUserKey(options.moduleUserKey, query.relations);\n const outputLines = []\n for (const model of module.models) {\n const codeGenerationOptions = {\n modelId: model.id,\n dryRun: options.dryRun,\n };\n const output = await this.modelMetadataService.handleGenerateCode(codeGenerationOptions);\n this.logger.debug(`Schematic output : ${output}`);\n outputLines.push(output)\n }\n return outputLines.join('\\n');\n }\n\n private getFileSysytemFullFilePath(fileName: string): string {\n return `${this.configService.get('app-builder.fileStorageDir')}/${fileName}`;\n }\n\n\n\n private getFileName(file: Express.Multer.File): string {\n return `${file.filename}-${file.originalname}`;\n }\n\n}\n"]}
1
+ {"version":3,"file":"module-metadata.service.js","sourceRoot":"","sources":["../../src/services/module-metadata.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAgH;AAChH,6CAAqE;AACrE,qCAAoF;AAEpF,+EAAoE;AAEpE,oEAAkE;AAClE,2CAA+C;AAC/C,gDAAkC;AAClC,2CAA6B;AAC7B,sGAAiG;AACjG,iDAAwD;AAGxD,oEAGsC;AACtC,8DAA0D;AAE1D,+DAA0D;AAC1D,qEAAgE;AAChE,8FAAyF;AACzF,qGAAuF;AAGhF,IAAM,qBAAqB,6BAA3B,MAAM,qBAAqB;IAGhC,YAEE,UAAuC,EAEvC,kBAA+D,EAC9C,iBAAoC,EACpC,gBAAkC,EAClC,aAA4B,EAC5B,WAAwB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X,uCAAiB;QAClB,oCAAgB;QACnB,sBAAa;QACf,0BAAW;QACE,oEAA+B;QAEnC,6CAAoB;QAC3B,8BAAa;QACC,4DAA2B;GAhBhE,qBAAqB,CAqYjC","sourcesContent":["import { BadRequestException, forwardRef, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';\nimport { InjectDataSource, InjectRepository } from '@nestjs/typeorm';\nimport { DataSource, EntityManager, Repository, SelectQueryBuilder } from 'typeorm';\nimport { CreateModuleMetadataDto } from '../dtos/create-module-metadata.dto';\nimport { ModuleMetadata } from '../entities/module-metadata.entity';\n\nimport { classify } from '@angular-devkit/core/src/utils/strings';\nimport { ConfigService } from '@nestjs/config';\nimport * as fs from 'fs/promises'; // Use the Promise-based version of fs for async/await\nimport * as path from 'path'; // To handle file paths\nimport { PermissionMetadataSeederService } from 'src/seeders/permission-metadata-seeder.service';\nimport { FileService } from 'src/services/file.service';\nimport { BasicFilterDto } from '../dtos/basic-filters.dto';\nimport { UpdateModuleMetadataDto } from '../dtos/update-module-metadata.dto';\nimport {\n ADD_MODULE_COMMAND,\n SchematicService,\n} from '../helpers/schematic.service';\nimport { SolidRegistry } from '../helpers/solid-registry';\nimport { CodeGenerationOptions, ModuleMetadataConfiguration } from '../interfaces';\nimport { CrudHelperService } from './crud-helper.service';\nimport { ModelMetadataService } from './model-metadata.service';\nimport { ModuleMetadataHelperService } from 'src/helpers/module-metadata-helper.service';\nimport { DisallowInProduction } from 'src/decorators/disallow-in-production.decorator';\n\n@Injectable()\nexport class ModuleMetadataService {\n private readonly logger = new Logger(ModuleMetadataService.name);\n\n constructor(\n @InjectDataSource()\n private readonly dataSource: DataSource,\n @InjectRepository(ModuleMetadata)\n private readonly moduleMetadataRepo: Repository<ModuleMetadata>,\n private readonly crudHelperService: CrudHelperService,\n private readonly schematicService: SchematicService,\n private readonly configService: ConfigService,\n private readonly fileService: FileService,\n private readonly permissionsSeederService: PermissionMetadataSeederService,\n @Inject(forwardRef(() => ModelMetadataService))\n private readonly modelMetadataService: ModelMetadataService,\n private readonly solidRegistry: SolidRegistry,\n private readonly moduleMetadataHelperService: ModuleMetadataHelperService,\n ) { }\n\n async findMany(basicFilterDto: BasicFilterDto) {\n const alias = 'moduleMetadata';\n // Extract the required keys from the input query\n let { limit, offset } = basicFilterDto;\n\n // Create above query on pincode table using query builder\n var qb: SelectQueryBuilder<ModuleMetadata> = this.moduleMetadataRepo.createQueryBuilder(alias)\n qb = await this.crudHelperService.buildFilterQuery(qb, basicFilterDto, alias);\n\n // Get the records and the count\n const [entities, count] = await qb.getManyAndCount();\n\n const currentPage = Math.floor(offset / limit) + 1;\n const totalPages = Math.ceil(count / limit);\n\n const nextPage = currentPage < totalPages ? currentPage + 1 : null;\n const prevPage = currentPage > 1 ? currentPage - 1 : null;\n\n const r = {\n meta: {\n totalRecords: count,\n currentPage: currentPage,\n nextPage: nextPage,\n prevPage: prevPage,\n totalPages: totalPages,\n perPage: +limit,\n },\n records: entities\n };\n return r\n }\n\n async findOneByUserKey(name: string, relations = {}) {\n if (!name) {\n throw new BadRequestException('name is required for finding entity');\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n name: name,\n },\n relations: relations,\n });\n return entity;\n }\n\n async findOne(id: number, relations = {}) {\n if (!id) {\n throw new BadRequestException('ID is required for finding entity');\n }\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n id: id,\n },\n relations: relations,\n });\n if (!entity) {\n throw new NotFoundException(`entity #${id} not found`);\n }\n return entity;\n }\n\n async create(createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.createInDB(manager, createDto, files);\n await this.createInFile(module);\n return module\n });\n } catch (error) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n async createInDB(manager: EntityManager, createDto: CreateModuleMetadataDto, files: Express.Multer.File[] = []) {\n if (files.length > 0) {\n const fileStoragePath = this.getFileSysytemFullFilePath(this.getFileName(files[0]));\n this.fileService.copyFile(files[0].path, fileStoragePath);\n this.fileService.deleteFile(files[0].path);\n createDto.menuIconUrl = fileStoragePath;\n }\n const moduleMetadata = this.moduleMetadataRepo.create(createDto);\n return manager.save(moduleMetadata); // Use the provided manager to perform DB operations\n }\n\n async createInFile(module: ModuleMetadata) {\n try {\n // Prepare the metadata JSON structure\n\n const moduleMetaDataJson: ModuleMetadataConfiguration = {\n moduleMetadata: {\n name: module?.name,\n displayName: module?.displayName,\n description: module?.description,\n defaultDataSource: module?.defaultDataSource,\n menuIconUrl: module?.menuIconUrl,\n menuSequenceNumber: module?.menuSequenceNumber,\n isSystem: module?.isSystem,\n models: [],\n },\n roles: [],\n users: [],\n actions: [\n {\n displayName: `${module?.name} Home`,\n name: `${module?.name}-home-action`,\n type: \"custom\",\n domain: \"\",\n context: \"\",\n customComponent: `/admin/core/${module?.name}/home`,\n customIsModal: true,\n serverEndpoint: \"\",\n viewUserKey: \"\",\n moduleUserKey: module?.name,\n modelUserKey: \"\"\n }\n ],\n menus: [\n {\n displayName: \"Home\",\n name: `${module?.name}-home-menu`,\n sequenceNumber: 1,\n actionUserKey: `${module?.name}-home-action`,\n moduleUserKey: module?.name,\n parentMenuItemUserKey: \"\"\n }\n ],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n securityRules: [],\n };\n\n // Convert the object to JSON string\n const metadataJson = JSON.stringify(moduleMetaDataJson, null, 2);\n\n // Create the folder path inside 'module-metadata'\n const folderPath = path.resolve(process.cwd(), 'module-metadata', module.name);\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Ensure the folder exists\n await fs.mkdir(folderPath, { recursive: true });\n\n // Write the JSON to the file\n await fs.writeFile(filePath, metadataJson);\n\n } catch (error) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error('File creation failed, rolling back transaction'); // Trigger rollback\n }\n }\n\n async update(id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n try {\n return await this.dataSource.transaction(async (manager: EntityManager) => {\n // Step 1: Write initial data to the database\n const module = await this.updateInDB(manager, id, updateModuleMetadataDto, files);\n await this.updateInFile(module);\n return module\n });\n } catch (error) {\n // console.error('Transaction failed:', error);\n this.logger.error('Transaction failed:', error);\n throw error;\n }\n }\n\n async updateInDB(manager: EntityManager, id: number, updateModuleMetadataDto: UpdateModuleMetadataDto, files: Express.Multer.File[] = []) {\n\n const module = await this.moduleMetadataRepo.preload({\n id,\n ...updateModuleMetadataDto,\n });\n\n if (!module) {\n throw new NotFoundException(`Module ${id} not found`);\n }\n if (files.length > 0) {\n\n const fileStoragePath = this.getFileSysytemFullFilePath(this.getFileName(files[0]));\n this.fileService.copyFile(files[0].path, fileStoragePath);\n this.fileService.deleteFile(files[0].path);\n module.menuIconUrl = fileStoragePath;\n }\n return manager.save(ModuleMetadata, module);\n }\n\n async updateInFile(module: ModuleMetadata) {\n try {\n const filePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(module.name);\n\n // Read the existing JSON file\n let metaData;\n try {\n metaData = await this.moduleMetadataHelperService.getModuleMetadataConfiguration(filePath);\n\n } catch (error) {\n metaData = {\n moduleMetadata: {\n name: null,\n displayName: null,\n description: null,\n defaultDataSource: null,\n menuIconUrl: null,\n menuSequenceNumber: null,\n isSystem: null,\n models: [],\n },\n roles: [],\n users: [],\n actions: [],\n menus: [],\n views: [],\n emailTemplates: [],\n smsTemplates: [],\n mediaStorageProviders: [],\n };\n }\n\n\n metaData.moduleMetadata.name = module?.name;\n metaData.moduleMetadata.displayName = module?.displayName;\n metaData.moduleMetadata.description = module?.description;\n metaData.moduleMetadata.defaultDataSource = module?.defaultDataSource;\n metaData.moduleMetadata.menuIconUrl = module?.menuIconUrl;\n metaData.moduleMetadata.menuSequenceNumber = module?.menuSequenceNumber;\n metaData.moduleMetadata.isSystem = module?.isSystem;\n\n // Write the JSON to the file\n const updatedContent = JSON.stringify(metaData, null, 2);\n await fs.writeFile(filePath, updatedContent);\n\n } catch (error) {\n // console.error('File creation failed:', error);\n this.logger.error('File creation failed:', error);\n throw new Error('File creation failed, rolling back transaction'); // Trigger rollback\n }\n }\n\n async upsert(updateModuleMetadataDto: UpdateModuleMetadataDto) {\n this.logger.log(`Module Upsert called for : ${updateModuleMetadataDto.name}`);\n // First check if module already exists using name\n const existingModuleMetadata = await this.moduleMetadataRepo.findOne({\n where: {\n name: updateModuleMetadataDto.name\n }\n })\n const { models, ...restUpdateModuleMetadataDto } = updateModuleMetadataDto;\n // if found\n if (existingModuleMetadata) {\n const updatedModuleMetadata = { ...existingModuleMetadata, ...restUpdateModuleMetadataDto };\n return this.moduleMetadataRepo.save(updatedModuleMetadata);\n }\n // if not found - create new \n else {\n const moduleMetadata = this.moduleMetadataRepo.create(restUpdateModuleMetadataDto);\n return this.moduleMetadataRepo.save(moduleMetadata);\n }\n }\n\n async removeByName(name: string) {\n const entity = await this.findOneByUserKey(name);\n if (entity) {\n await this.moduleMetadataRepo.remove(entity);\n }\n }\n\n async remove(id: number) {\n const entity = await this.findOne(id);\n return this.moduleMetadataRepo.remove(entity);\n }\n\n async deleteMany(ids: number[]): Promise<any> {\n if (!ids || ids.length === 0) {\n throw new Error('At least one ID is required for deletion');\n }\n const removedEntities = [];\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]\n const entity = await this.moduleMetadataRepo.findOne({\n where: {\n //@ts-ignore\n id: id,\n }\n });\n // if (!entity) {\n // throw new Error(`Entity with id ${id} not found`);\n // }\n removedEntities.push(await this.moduleMetadataRepo.remove(entity));\n }\n\n return removedEntities\n }\n\n async refreshPermission() {\n await this.permissionsSeederService.seed();\n return true\n }\n\n @DisallowInProduction()\n async generateCode(options: CodeGenerationOptions): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException('Module ID or Module Name is required for generating code');\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n // Check if the module exists\n if (!module) {\n throw new NotFoundException(`Module ${options.moduleId} not found`);\n }\n\n // Check if the module name already exists and is loaded\n const moduleInstance = this.solidRegistry.getModule(`${classify(module.name)}Module`);\n\n if (!moduleInstance) {\n const addModuleOutput = await this.generateAddModuleCode(options);\n const refreshModuleOutput = await this.generateRefreshModuleCode(options);\n return `${addModuleOutput}\\n${refreshModuleOutput}`;\n } else {\n return await this.generateRefreshModuleCode(options);\n }\n }\n\n private async generateAddModuleCode(options: CodeGenerationOptions = { dryRun: false }): Promise<string> {\n if (!options.moduleId && !options.moduleUserKey) {\n throw new BadRequestException('Module ID or Module Name is required for generating code');\n }\n const module = options.moduleId ? await this.findOne(options.moduleId) : await this.findOneByUserKey(options.moduleUserKey);\n\n //Generate the module\n const output = await this.schematicService.executeSchematicCommand(\n ADD_MODULE_COMMAND,\n { module: module.name },\n options.dryRun ?? false\n );\n this.logger.debug(`Schematic output : ${output}`);\n return output;\n }\n\n private async generateRefreshModuleCode(options: CodeGenerationOptions): Promise<string> {\n const query = {\n relations: { models: { fields: true } },\n };\n const module = options.moduleId ? await this.findOne(options.moduleId, query.relations) : await this.findOneByUserKey(options.moduleUserKey, query.relations);\n const outputLines = []\n for (const model of module.models) {\n const codeGenerationOptions = {\n modelId: model.id,\n dryRun: options.dryRun,\n };\n const output = await this.modelMetadataService.handleGenerateCode(codeGenerationOptions);\n this.logger.debug(`Schematic output : ${output}`);\n outputLines.push(output)\n }\n return outputLines.join('\\n');\n }\n\n private getFileSysytemFullFilePath(fileName: string): string {\n return `${this.configService.get('app-builder.fileStorageDir')}/${fileName}`;\n }\n\n\n\n private getFileName(file: Express.Multer.File): string {\n return `${file.filename}-${file.originalname}`;\n }\n\n}\n"]}