rez_core 5.0.145 → 5.0.150

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 (62) hide show
  1. package/dist/config/bull.config.js +4 -4
  2. package/dist/config/bull.config.js.map +1 -1
  3. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.d.ts +6 -0
  4. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js +32 -0
  5. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js.map +1 -0
  6. package/dist/module/entity_json/entity_json.module.js +1 -1
  7. package/dist/module/entity_json/entity_json.module.js.map +1 -1
  8. package/dist/module/entity_json/service/entity_json.service.js +1 -1
  9. package/dist/module/entity_json/service/entity_json.service.js.map +1 -1
  10. package/dist/module/filter/controller/filter.controller.d.ts +12 -0
  11. package/dist/module/filter/controller/filter.controller.js +1 -1
  12. package/dist/module/filter/controller/filter.controller.js.map +1 -1
  13. package/dist/module/filter/filter.module.js +9 -2
  14. package/dist/module/filter/filter.module.js.map +1 -1
  15. package/dist/module/filter/repository/saved-filter.repository.d.ts +5 -1
  16. package/dist/module/filter/repository/saved-filter.repository.js +5 -1
  17. package/dist/module/filter/repository/saved-filter.repository.js.map +1 -1
  18. package/dist/module/filter/service/filter.service.d.ts +37 -1
  19. package/dist/module/filter/service/filter.service.js +30 -2
  20. package/dist/module/filter/service/filter.service.js.map +1 -1
  21. package/dist/module/filter/service/flatjson-filter.service.d.ts +30 -0
  22. package/dist/module/filter/service/flatjson-filter.service.js +615 -0
  23. package/dist/module/filter/service/flatjson-filter.service.js.map +1 -0
  24. package/dist/module/integration/service/wrapper.service.d.ts +1 -3
  25. package/dist/module/integration/service/wrapper.service.js +2 -24
  26. package/dist/module/integration/service/wrapper.service.js.map +1 -1
  27. package/dist/module/linked_attributes/controller/linked_attributes.controller.d.ts +19 -0
  28. package/dist/module/linked_attributes/controller/linked_attributes.controller.js +77 -0
  29. package/dist/module/linked_attributes/controller/linked_attributes.controller.js.map +1 -1
  30. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.d.ts +13 -0
  31. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js +64 -0
  32. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js.map +1 -0
  33. package/dist/module/linked_attributes/linked_attributes.module.js +8 -1
  34. package/dist/module/linked_attributes/linked_attributes.module.js.map +1 -1
  35. package/dist/module/linked_attributes/service/linked_attributes.service.d.ts +41 -1
  36. package/dist/module/linked_attributes/service/linked_attributes.service.js +266 -2
  37. package/dist/module/linked_attributes/service/linked_attributes.service.js.map +1 -1
  38. package/dist/module/meta/dto/entity-table.dto.d.ts +4 -1
  39. package/dist/module/meta/dto/entity-table.dto.js.map +1 -1
  40. package/dist/module/meta/service/media-data.service.js +5 -18
  41. package/dist/module/meta/service/media-data.service.js.map +1 -1
  42. package/dist/tsconfig.build.tsbuildinfo +1 -1
  43. package/package.json +1 -1
  44. package/src/config/bull.config.ts +4 -4
  45. package/src/migrations/1732612800000-AddEntityJsonGinIndex.ts +41 -0
  46. package/src/module/entity_json/docs/FlatJson_Filterin_System.md +2804 -0
  47. package/src/module/entity_json/entity_json.module.ts +1 -1
  48. package/src/module/entity_json/service/entity_json.service.ts +1 -1
  49. package/src/module/filter/controller/filter.controller.ts +1 -3
  50. package/src/module/filter/filter.module.ts +9 -2
  51. package/src/module/filter/repository/saved-filter.repository.ts +5 -8
  52. package/src/module/filter/service/filter.service.ts +49 -0
  53. package/src/module/filter/service/flatjson-filter.service.ts +888 -0
  54. package/src/module/filter/test/flatjson-filter.service.spec.ts +415 -0
  55. package/src/module/integration/service/wrapper.service.ts +0 -37
  56. package/src/module/linked_attributes/controller/linked_attributes.controller.ts +86 -0
  57. package/src/module/linked_attributes/dto/create-linked-attribute-smart.dto.ts +54 -0
  58. package/src/module/linked_attributes/linked_attributes.module.ts +9 -2
  59. package/src/module/linked_attributes/service/linked_attributes.service.ts +548 -3
  60. package/src/module/linked_attributes/test/linked-attributes.service.spec.ts +244 -0
  61. package/src/module/meta/dto/entity-table.dto.ts +1 -2
  62. package/src/module/meta/service/media-data.service.ts +9 -27
@@ -1,15 +1,33 @@
1
- import { Injectable } from '@nestjs/common';
1
+ import { Injectable, Inject, BadRequestException, NotFoundException } from '@nestjs/common';
2
2
  import { EntityServiceImpl } from 'src/module/meta/service/entity-service-impl.service';
3
- import { DataSource } from 'typeorm';
3
+ import { BaseEntity, DataSource } from 'typeorm';
4
4
  import { LinkedAttributes } from '../entity/linked_attribute.entity';
5
+ import { EntityMasterService } from 'src/module/meta/service/entity-master.service';
6
+ import { AttributeMasterService } from 'src/module/meta/service/attribute-master.service';
7
+ import { SavedFilterService } from 'src/module/filter/service/saved-filter.service';
8
+ import { SavedFilterDetailRepository } from 'src/module/filter/repository/saved.filter-detail.repository';
9
+ import { EntityJSONService } from 'src/module/entity_json/service/entity_json.service';
10
+ import { CreateLinkedAttributeSmartDto } from '../dto/create-linked-attribute-smart.dto';
11
+ import { EntityJson } from 'src/module/entity_json/entity/entityJson.entity';
5
12
 
6
13
  @Injectable()
7
14
  export class LinkedAttributesService extends EntityServiceImpl {
8
- constructor(private readonly dataSource: DataSource) {
15
+ constructor(
16
+ private readonly dataSource: DataSource,
17
+ entityMasterService: EntityMasterService,
18
+ private readonly attributeMasterService: AttributeMasterService,
19
+ @Inject('SavedFilterService')
20
+ private readonly savedFilterService: SavedFilterService,
21
+ private readonly entityJsonService: EntityJSONService,
22
+ ) {
9
23
  super();
10
24
  }
11
25
 
12
26
  async createEntity(payload: any, loggedInUser: any): Promise<any> {
27
+ console.warn(
28
+ '[DEPRECATED] Use createLinkedAttributeSmart() instead of createEntity()',
29
+ );
30
+
13
31
  // Auto-generate attribute_key if missing OR empty
14
32
  if (!payload.attribute_key || payload.attribute_key.trim() === '') {
15
33
  payload.attribute_key = payload.field_name
@@ -72,4 +90,531 @@ export class LinkedAttributesService extends EntityServiceImpl {
72
90
 
73
91
  return newlyCreated;
74
92
  }
93
+
94
+ /**
95
+ * Generate the next sequence number for a linked attribute
96
+ * @param mapped_entity_type - Main entity type (e.g., "LEAD")
97
+ * @param applicable_entity_type - Source 1:M entity (e.g., "LFMG")
98
+ * @param applicable_attribute_key - Source attribute (e.g., "name")
99
+ * @param organization_id - Organization ID
100
+ * @returns Next available sequence number
101
+ */
102
+ private async generateNextSequence(
103
+ mapped_entity_type: string,
104
+ applicable_entity_type: string,
105
+ applicable_attribute_key: string,
106
+ organization_id: number,
107
+ ): Promise<number> {
108
+ const result = await this.dataSource
109
+ .getRepository(LinkedAttributes)
110
+ .createQueryBuilder('fla')
111
+ .select('MAX(fla.sequence)', 'max_sequence')
112
+ .where('fla.mapped_entity_type = :mapped_entity_type', {
113
+ mapped_entity_type,
114
+ })
115
+ .andWhere('fla.applicable_entity_type = :applicable_entity_type', {
116
+ applicable_entity_type,
117
+ })
118
+ .andWhere('fla.applicable_attribute_key = :applicable_attribute_key', {
119
+ applicable_attribute_key,
120
+ })
121
+ .andWhere('fla.organization_id = :organization_id', { organization_id })
122
+ .getRawOne();
123
+
124
+ const maxSequence = result?.max_sequence;
125
+
126
+ // If no records exist or max is null, return 1; otherwise return max + 1
127
+ return maxSequence ? maxSequence + 1 : 1;
128
+ }
129
+
130
+ /**
131
+ * Generate a flatjson attribute key in format: ENTITY__attribute__N
132
+ * @param applicable_entity_type - Entity code (e.g., "LFMG")
133
+ * @param applicable_attribute_key - Attribute key (e.g., "name")
134
+ * @param sequence - Sequence number (e.g., 1)
135
+ * @returns Generated key (e.g., "LFMG__name__1")
136
+ * @example generateAttributeKey('LFMG', 'name', 1) => 'LFMG__name__1'
137
+ */
138
+ public generateAttributeKey(
139
+ applicable_entity_type: string,
140
+ applicable_attribute_key: string,
141
+ sequence: number,
142
+ ): string {
143
+ // Validate inputs
144
+ if (!applicable_entity_type || applicable_entity_type.trim() === '') {
145
+ throw new Error('applicable_entity_type is required and cannot be empty');
146
+ }
147
+
148
+ if (!applicable_attribute_key || applicable_attribute_key.trim() === '') {
149
+ throw new Error(
150
+ 'applicable_attribute_key is required and cannot be empty',
151
+ );
152
+ }
153
+
154
+ if (!sequence || sequence < 1 || !Number.isInteger(sequence)) {
155
+ throw new Error('sequence must be a positive integer greater than 0');
156
+ }
157
+
158
+ // Generate and return formatted key
159
+ return `${applicable_entity_type}__${applicable_attribute_key}__${sequence}`;
160
+ }
161
+
162
+ /**
163
+ * Create a SavedFilter for a linked attribute
164
+ * @param entity_type - Entity type to filter (e.g., "LFMG")
165
+ * @param conditions - Array of filter conditions
166
+ * @param attribute_key - Linked attribute key (for naming)
167
+ * @param loggedInUser - Current user context
168
+ * @returns Generated filter code
169
+ */
170
+ private async createFilterForLinkedAttribute(
171
+ entity_type: string,
172
+ conditions: Array<{
173
+ filter_attribute: string;
174
+ filter_operator: string;
175
+ filter_value: any;
176
+ }>,
177
+ attribute_key: string,
178
+ loggedInUser: any,
179
+ ): Promise<string> {
180
+ return await this.dataSource.transaction(async (transactionManager) => {
181
+ // Step 1: Generate unique filter code
182
+ const timestamp = Date.now();
183
+ const filterCode = `LA_${entity_type}_${attribute_key}_${timestamp}`;
184
+
185
+ // Step 2: Create SavedFilterMaster
186
+ const filterMasterData = {
187
+ name: `Auto Filter - ${attribute_key}`,
188
+ code: filterCode,
189
+ mapped_entity_type: entity_type,
190
+ filter_scope: 'FILTER' as const,
191
+ organization_id: loggedInUser.organization_id,
192
+ level_type: loggedInUser.level_type,
193
+ level_id: loggedInUser.level_id,
194
+ user_id: loggedInUser.id,
195
+ };
196
+
197
+ const filterMaster = await this.savedFilterService.createEntity(
198
+ filterMasterData,
199
+ loggedInUser,
200
+ );
201
+
202
+ // Step 3: Create SavedFilterDetail records
203
+ const detailPromises = conditions.map((condition) => {
204
+ const detailData = {
205
+ mapped_filter_code: filterMaster.code,
206
+ filter_entity_type: entity_type,
207
+ filter_attribute: condition.filter_attribute,
208
+ filter_operator: condition.filter_operator,
209
+ filter_value: String(condition.filter_value),
210
+ organization_id: loggedInUser.organization_id,
211
+ level_type: loggedInUser.level_type,
212
+ level_id: loggedInUser.level_id,
213
+ };
214
+
215
+ return transactionManager.save('SavedFilterDetail', detailData);
216
+ });
217
+
218
+ await Promise.all(detailPromises);
219
+
220
+ // Step 4: Return the generated filter code
221
+ return filterMaster.code;
222
+ });
223
+ }
224
+
225
+ /**
226
+ * Smart creation of linked attribute with auto-generation
227
+ * @param payload - Linked attribute data
228
+ * @param loggedInUser - Current user context
229
+ * @returns Created LinkedAttribute entity
230
+ */
231
+ async createLinkedAttributeSmart(
232
+ payload: CreateLinkedAttributeSmartDto,
233
+ loggedInUser: any,
234
+ ): Promise<LinkedAttributes> {
235
+ // Step 1: Validate input
236
+ const validation = await this.validateLinkedAttribute(
237
+ {
238
+ field_name: payload.field_name,
239
+ mapped_entity_type: payload.mapped_entity_type,
240
+ applicable_entity_type: payload.applicable_entity_type,
241
+ applicable_attribute_key: payload.applicable_attribute_key,
242
+ organization_id: loggedInUser.organization_id,
243
+ },
244
+ loggedInUser,
245
+ );
246
+
247
+ if (!validation.valid) {
248
+ throw new BadRequestException(validation.errors.join(', '));
249
+ }
250
+
251
+ // Step 2: Generate sequence number
252
+ const sequence = await this.generateNextSequence(
253
+ payload.mapped_entity_type,
254
+ payload.applicable_entity_type,
255
+ payload.applicable_attribute_key,
256
+ loggedInUser.organization_id,
257
+ );
258
+
259
+ // Step 3: Generate attribute_key
260
+ const attribute_key = this.generateAttributeKey(
261
+ payload.applicable_entity_type,
262
+ payload.applicable_attribute_key,
263
+ sequence,
264
+ );
265
+
266
+ // Step 4: Create saved filter if conditions provided
267
+ let saved_filter_code: string | null = payload.saved_filter_code || null;
268
+ // if (payload.filter_conditions && payload.filter_conditions.length > 0) {
269
+ // saved_filter_code = await this.createFilterForLinkedAttribute(
270
+ // payload.applicable_entity_type,
271
+ // payload.filter_conditions,
272
+ // attribute_key,
273
+ // loggedInUser,
274
+ // );
275
+ // }
276
+
277
+ // Step 5: Create LinkedAttribute entity
278
+ let linkedAttrData:any = {
279
+ field_name: payload.field_name,
280
+ attribute_key,
281
+ applicable_entity_type: payload.applicable_entity_type,
282
+ applicable_attribute_key: payload.applicable_attribute_key,
283
+ mapped_entity_type: payload.mapped_entity_type,
284
+ saved_filter_code,
285
+ sequence,
286
+ organization_id: loggedInUser.organization_id,
287
+ level_type: loggedInUser.level_type,
288
+ level_id: loggedInUser.level_id,
289
+ entity_type:'LNATR'
290
+ };
291
+
292
+ const linkedAttribute = (await super.createEntity(
293
+ linkedAttrData,
294
+ loggedInUser,
295
+ )) as LinkedAttributes;
296
+
297
+ // Step 6: Trigger backfill if requested (async, don't await)
298
+ if (payload.backfill) {
299
+ this.backfillLinkedAttribute(linkedAttribute.id, loggedInUser).catch(
300
+ (err) =>
301
+ console.error(
302
+ `Backfill failed for linked attribute ${linkedAttribute.id}:`,
303
+ err,
304
+ ),
305
+ );
306
+ }
307
+
308
+ return linkedAttribute;
309
+ }
310
+
311
+ /**
312
+ * Validate linked attribute payload before creation
313
+ * @param payload - Linked attribute data to validate
314
+ * @param loggedInUser - Current user context
315
+ * @returns Validation result with errors array
316
+ */
317
+ async validateLinkedAttribute(
318
+ payload: {
319
+ field_name: string;
320
+ mapped_entity_type: string;
321
+ applicable_entity_type: string;
322
+ applicable_attribute_key: string;
323
+ attribute_key?: string;
324
+ organization_id: number;
325
+ },
326
+ loggedInUser: any,
327
+ ): Promise<{ valid: boolean; errors: string[] }> {
328
+ const errors: string[] = [];
329
+
330
+ // Run all validations in parallel
331
+ const [
332
+ duplicateError,
333
+ mappedEntityError,
334
+ applicableEntityError,
335
+ attributeError,
336
+ ] = await Promise.all([
337
+ this.checkDuplicateAttributeKey(
338
+ payload.attribute_key,
339
+ payload.organization_id,
340
+ ),
341
+ this.validateEntityTypeExists(
342
+ payload.mapped_entity_type,
343
+ loggedInUser,
344
+ ),
345
+ this.validateEntityTypeExists(
346
+ payload.applicable_entity_type,
347
+ loggedInUser,
348
+ ),
349
+ this.validateAttributeKeyExists(
350
+ payload.applicable_entity_type,
351
+ payload.applicable_attribute_key,
352
+ loggedInUser,
353
+ ),
354
+ ]);
355
+
356
+ // Collect errors
357
+ if (duplicateError) errors.push(duplicateError);
358
+ if (mappedEntityError) errors.push(mappedEntityError);
359
+ if (applicableEntityError) errors.push(applicableEntityError);
360
+ if (attributeError) errors.push(attributeError);
361
+
362
+ // Validate required fields
363
+ this.validateRequiredFields(payload, errors);
364
+
365
+ return { valid: errors.length === 0, errors };
366
+ }
367
+
368
+ /**
369
+ * Validate that all required fields are present and not empty
370
+ * @param payload - Payload to validate
371
+ * @param errors - Array to collect error messages
372
+ */
373
+ private validateRequiredFields(
374
+ payload: {
375
+ field_name: string;
376
+ mapped_entity_type: string;
377
+ applicable_entity_type: string;
378
+ applicable_attribute_key: string;
379
+ },
380
+ errors: string[],
381
+ ): void {
382
+ const requiredFields = [
383
+ { field: 'field_name', value: payload.field_name },
384
+ { field: 'mapped_entity_type', value: payload.mapped_entity_type },
385
+ { field: 'applicable_entity_type', value: payload.applicable_entity_type },
386
+ { field: 'applicable_attribute_key', value: payload.applicable_attribute_key },
387
+ ];
388
+
389
+ for (const { field, value } of requiredFields) {
390
+ if (!value || (typeof value === 'string' && value.trim() === '')) {
391
+ errors.push(`Required field '${field}' is missing or empty`);
392
+ }
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Check if attribute_key already exists for the organization
398
+ * @param attribute_key - Attribute key to check
399
+ * @param organization_id - Organization ID
400
+ * @returns Error message if duplicate exists, null otherwise
401
+ */
402
+ private async checkDuplicateAttributeKey(
403
+ attribute_key: string | undefined,
404
+ organization_id: number,
405
+ ): Promise<string | null> {
406
+ // Skip check if attribute_key is not provided (will be auto-generated)
407
+ if (!attribute_key || attribute_key.trim() === '') {
408
+ return null;
409
+ }
410
+
411
+ const existing = await this.dataSource
412
+ .getRepository(LinkedAttributes)
413
+ .createQueryBuilder('fla')
414
+ .where('fla.attribute_key = :attribute_key', { attribute_key })
415
+ .andWhere('fla.organization_id = :organization_id', { organization_id })
416
+ .getOne();
417
+
418
+ if (existing) {
419
+ return `Attribute key '${attribute_key}' already exists for this organization`;
420
+ }
421
+
422
+ return null;
423
+ }
424
+
425
+ /**
426
+ * Validate that entity type exists in frm_entity_master
427
+ * @param entity_type - Entity type to validate
428
+ * @param loggedInUser - Current user context
429
+ * @returns Error message if entity doesn't exist, null otherwise
430
+ */
431
+ private async validateEntityTypeExists(
432
+ entity_type: string,
433
+ loggedInUser: any,
434
+ ): Promise<string | null> {
435
+ if (!entity_type || entity_type.trim() === '') {
436
+ return null; // Will be caught by required field validation
437
+ }
438
+
439
+ try {
440
+ await this.entityMasterService.getEntityData(entity_type, loggedInUser);
441
+ return null; // Entity exists
442
+ } catch (error) {
443
+ return `Entity type '${entity_type}' does not exist`;
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Validate that attribute exists in frm_attribute_master for the given entity
449
+ * @param entity_type - Entity type
450
+ * @param attribute_key - Attribute key to validate
451
+ * @param loggedInUser - Current user context
452
+ * @returns Error message if attribute doesn't exist, null otherwise
453
+ */
454
+ private async validateAttributeKeyExists(
455
+ entity_type: string,
456
+ attribute_key: string,
457
+ loggedInUser: any,
458
+ ): Promise<string | null> {
459
+ if (!entity_type || !attribute_key) {
460
+ return null; // Will be caught by required field validation
461
+ }
462
+
463
+ try {
464
+ const attributes =
465
+ await this.attributeMasterService.findAttributesByMappedEntityType(
466
+ entity_type,
467
+ loggedInUser,
468
+ );
469
+
470
+ const attributeExists = attributes.some(
471
+ (attr) => attr.attribute_key === attribute_key,
472
+ );
473
+
474
+ if (!attributeExists) {
475
+ return `Attribute '${attribute_key}' does not exist in entity '${entity_type}'`;
476
+ }
477
+
478
+ return null;
479
+ } catch (error) {
480
+ return `Error validating attribute '${attribute_key}' in entity '${entity_type}': ${error.message}`;
481
+ }
482
+ }
483
+
484
+ /**
485
+ * Backfill existing entities with a new linked attribute
486
+ * @param linked_attribute_id - ID of the linked attribute to backfill
487
+ * @param loggedInUser - Current user context
488
+ * @returns Summary of backfill operation
489
+ */
490
+ async backfillLinkedAttribute(
491
+ linked_attribute_id: number,
492
+ loggedInUser: any,
493
+ ): Promise<{
494
+ total: number;
495
+ updated: number;
496
+ failed: number;
497
+ errors: Array<{ entity_id: number; error: string }>;
498
+ }> {
499
+ // Step 1: Load linked attribute
500
+ const linkedAttr = await this.dataSource
501
+ .getRepository(LinkedAttributes)
502
+ .findOne({ where: { id: linked_attribute_id } });
503
+
504
+ if (!linkedAttr) {
505
+ throw new NotFoundException(
506
+ `LinkedAttribute with ID ${linked_attribute_id} not found`,
507
+ );
508
+ }
509
+
510
+ // Step 2: Get all entities of this type
511
+ const entityJsonRecords = await this.dataSource
512
+ .getRepository(EntityJson)
513
+ .createQueryBuilder('ej')
514
+ .select(['ej.entity_id'])
515
+ .where('ej.entity_type = :entityType', {
516
+ entityType: linkedAttr.mapped_entity_type,
517
+ })
518
+ .andWhere('ej.organization_id = :orgId', {
519
+ orgId: loggedInUser.organization_id,
520
+ })
521
+ .getMany();
522
+
523
+ // Step 3: Process in batches
524
+ const batchSize = 100;
525
+ const results = {
526
+ total: entityJsonRecords.length,
527
+ updated: 0,
528
+ failed: 0,
529
+ errors: [] as Array<{ entity_id: number; error: string }>,
530
+ };
531
+
532
+ for (let i = 0; i < entityJsonRecords.length; i += batchSize) {
533
+ const batch = entityJsonRecords.slice(i, i + batchSize);
534
+
535
+ for (const record of batch) {
536
+ try {
537
+ await this.entityJsonService.updateEntityJSON(
538
+ linkedAttr.mapped_entity_type,
539
+ record.entity_id,
540
+ loggedInUser,
541
+ );
542
+ results.updated++;
543
+ } catch (error) {
544
+ results.failed++;
545
+ results.errors.push({
546
+ entity_id: record.entity_id,
547
+ error: error.message,
548
+ });
549
+ console.error(
550
+ `Failed to update entity ${record.entity_id}:`,
551
+ error,
552
+ );
553
+ }
554
+ }
555
+
556
+ // Log progress
557
+ console.log(
558
+ `Backfill progress: ${Math.min(i + batchSize, results.total)}/${results.total}`,
559
+ );
560
+ }
561
+
562
+ return results;
563
+ }
564
+
565
+ /**
566
+ * Backfill all linked attributes for an entity type
567
+ * @param mapped_entity_type - Entity type to backfill
568
+ * @param loggedInUser - Current user context
569
+ * @returns Summary of backfill operation
570
+ */
571
+ async backfillAllForEntity(
572
+ mapped_entity_type: string,
573
+ loggedInUser: any,
574
+ ): Promise<{ updated: number; failed: number }> {
575
+ // Get all entities of this type
576
+ const entityJsonRecords = await this.dataSource
577
+ .getRepository(EntityJson)
578
+ .createQueryBuilder('ej')
579
+ .select(['ej.entity_id'])
580
+ .where('ej.entity_type = :entityType', { entityType: mapped_entity_type })
581
+ .andWhere('ej.organization_id = :orgId', {
582
+ orgId: loggedInUser.organization_id,
583
+ })
584
+ .getMany();
585
+
586
+ const batchSize = 100;
587
+ const results = {
588
+ updated: 0,
589
+ failed: 0,
590
+ };
591
+
592
+ for (let i = 0; i < entityJsonRecords.length; i += batchSize) {
593
+ const batch = entityJsonRecords.slice(i, i + batchSize);
594
+
595
+ for (const record of batch) {
596
+ try {
597
+ await this.entityJsonService.updateEntityJSON(
598
+ mapped_entity_type,
599
+ record.entity_id,
600
+ loggedInUser,
601
+ );
602
+ results.updated++;
603
+ } catch (error) {
604
+ results.failed++;
605
+ console.error(
606
+ `Failed to update entity ${record.entity_id}:`,
607
+ error,
608
+ );
609
+ }
610
+ }
611
+
612
+ // Log progress
613
+ console.log(
614
+ `Backfill all progress: ${Math.min(i + batchSize, entityJsonRecords.length)}/${entityJsonRecords.length}`,
615
+ );
616
+ }
617
+
618
+ return results;
619
+ }
75
620
  }