-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmodelService.ts
More file actions
897 lines (826 loc) · 32.1 KB
/
Copy pathmodelService.ts
File metadata and controls
897 lines (826 loc) · 32.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
import api from "./api";
import { faker } from '@faker-js/faker';
import {
ApiResponse,
DataModel,
CountResponse,
DataModelWithDetailsDTO,
EntityWithAttributesDTO,
EntityTreeNode,
DataModelWithDetailsWithTree,
StateType,
} from "../types";
import { downloadJsonFile } from "../utils/downloadJsonFile";
const apiBaseUrl = import.meta.env.VITE_API_URL;
const BaseLIF = 'BaseLIF';
const OrgLIF = 'OrgLIF';
const SourceSchema = 'SourceSchema';
const PartnerLIF = 'PartnerLIF';
/**
* List data models, optionally filtering by DataModel.Type on the client side.
* Example types could include "SourceSchema", "Base", "Extension", etc.
*/
export const listModels = async (
filters?: { type?: string | string[] }
): Promise<DataModel[]> => {
try {
const result = await api.get<ApiResponse>(
`${apiBaseUrl}/datamodels/?pagination=false`);
let models = result.data.data;
// Optional client-side type filter
if (filters?.type) {
const toArray = Array.isArray(filters.type)
? filters.type
: [filters.type];
const wanted = new Set(
toArray
.filter((t) => t != null)
.map((t) => String(t).trim().toLowerCase())
);
models = models.filter(
(m) => m.Type && wanted.has(String(m.Type).trim().toLowerCase())
);
}
return models;
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
};
export const getModel_BaseLIF = async () => { // returns the first BaseLIF model
try {
const models = await listModels({ type: BaseLIF });
if (models?.length) return models[0];
else throw new Error("No Base LIF model found");
} catch (error) {
console.error("Error fetching Base LIF model:", error);
}
};
export const getModel_OrgLIF = async () => { // returns the first OrgLIF model
try {
const models = await listModels({ type: OrgLIF });
if (models?.length) return models[0];
else throw new Error("No Org LIF model found");
} catch (error) {
console.error("Error fetching Org LIF model:", error);
}
};
export const getModel = async (id: number) => {
try {
const result = await api.get<ApiResponse>(`${apiBaseUrl}/datamodels/${id}`);
return result.data;
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
};
export const getModelDetails = async (id: number, params?: string): Promise<DataModelWithDetailsDTO> => {
try {
const basePath = `${apiBaseUrl}/datamodels/with_details/${id}`;
const queryPath = basePath + (params ? `?${params}` : "");
// console.log("getModelDetails queryPath:", queryPath);
const result = await api.get<DataModelWithDetailsDTO>(queryPath);
return result.data;
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
};
/**
* Fetches model details and augments them with an EntityTree derived from
* ParentEntities/ChildEntities relationships.
*
* Rules applied:
* - If a child relationship is not null and does not start with "has" or "relevant",
* the child's display name is prefixed with the relationship (e.g., "owns Asset").
* - If ChildEntityDTO.Placement === "Reference" (case-insensitive), treat it as a reference:
* only the required attributes of that child entity are included, and no child entities are shown.
*
* Note: Nodes generally reference the existing entity objects from the response,
* but for Reference placements and/or relationship-prefixed labels a shallow clone
* is used to adjust display Name and/or filter Attributes for that node only.
*/
export const getModelDetailsWithTree = async (
id: number,
params?: string
): Promise<DataModelWithDetailsWithTree> => {
const details = await getModelDetails(id, params);
// Build quick lookups for entity by id and its children ids
const entityById = new Map<number, EntityWithAttributesDTO>();
details.Entities.forEach((ewa) => entityById.set(ewa.Entity.Id, ewa));
// Track placements for each entity when it appears as a child so we can identify
// entities that are ONLY ever referenced (Placement === 'Reference'). Those will
// also be promoted to root-level entities per new rule.
const childPlacements = new Map<number, Set<string>>();
details.Entities.forEach((ewa) => {
(ewa.ChildEntities || []).forEach((c: any) => {
const set = childPlacements.get(c.Id) || new Set<string>();
if (c.Placement != null) set.add(String(c.Placement).trim().toLowerCase());
else set.add("__null"); // mark null/undefined distinctly so it disqualifies reference-only status
childPlacements.set(c.Id, set);
});
});
const hasParent = new Set<number>();
details.Entities.forEach((ewa) => {
ewa.ParentEntities.forEach((p) => hasParent.add(ewa.Entity.Id));
});
const referenceOnlyEntityIds = new Set<number>();
childPlacements.forEach((placements, childId) => {
if (placements.size === 0) return;
// Entity is reference-only if every placement collected is exactly 'reference'.
// Any null/blank/embedded/other value disqualifies.
const allReference = Array.from(placements).every((pl) => pl === 'reference');
if (allReference) referenceOnlyEntityIds.add(childId);
});
// Roots are entities with no parents
// New rule: also treat entities that only ever appear as Reference children as additional roots
const roots = details.Entities.filter((ewa) => !hasParent.has(ewa.Entity.Id) || referenceOnlyEntityIds.has(ewa.Entity.Id));
const normalize = (s: string | null | undefined) => (s ?? '').trim();
const isReferencePlacement = (p?: string | null) => normalize(p).toLowerCase() === 'reference';
const shouldPrefixRelationship = (rel?: string | null) => {
const r = normalize(rel);
if (!r) return false;
const lower = r.toLowerCase();
return !(lower.startsWith('has') || lower.startsWith('relevant'));
};
const prefixRelationshipName = (name: string, rel?: string | null) =>
shouldPrefixRelationship(rel) ? `${normalize(rel)}Ref${name}` : name;
const isRequiredAttribute = (required: string | null | undefined) => {
const r = normalize(required).toLowerCase();
if (!r) return false;
return r === 'yes' || r === 'y' || r === 'true' || r === 'required' || r === 'mandatory';
};
const filterRequiredAttributes = (attrs: EntityWithAttributesDTO['Attributes']) =>
(attrs || []).filter((a) => isRequiredAttribute(a.Required));
const makeNode = (
ewa: EntityWithAttributesDTO,
pathEntityIds: string,
siblingIndex: number,
visitedIds: Set<number>
): EntityTreeNode => {
// PathId uses comma-separated entity IDs (e.g., "4,238,6") to align with backend EntityIdPath format
const eid = String(ewa.Entity.Id);
const pathId = pathEntityIds ? `${pathEntityIds},${eid}` : eid;
// Avoid infinite loops in case of accidental cycles
const nextVisited = new Set(visitedIds);
nextVisited.add(ewa.Entity.Id);
const children: EntityTreeNode[] = [];
ewa.ChildEntities.forEach((childEntityDTO, idx) => {
const child = entityById.get(childEntityDTO.Id);
if (!child) return;
if (nextVisited.has(child.Entity.Id)) return; // guard against cycles
const isRef = isReferencePlacement(childEntityDTO.Placement);
const displayName = prefixRelationshipName(child.Entity.Name, childEntityDTO.Relationship);
// Shallow clone the child EWA to adjust display name and/or attributes for this node only
const adjustedChild: EntityWithAttributesDTO = {
...child,
Entity: child.Entity.Name === displayName ? child.Entity : { ...child.Entity, Name: displayName },
Attributes: isRef ? filterRequiredAttributes(child.Attributes) : child.Attributes,
// For references, display no child entities
ChildEntities: isRef ? [] : child.ChildEntities,
};
if (isRef) {
const childPathId = `${pathId},${child.Entity.Id}`;
children.push({
PathId: childPathId,
EntityId: child.Entity.Id,
Entity: adjustedChild,
Children: [],
});
return;
}
children.push(makeNode(adjustedChild, pathId, idx + 1, nextVisited));
});
return {
PathId: pathId,
EntityId: ewa.Entity.Id,
Entity: ewa, // keep reference to the same object
Children: children,
};
};
const tree: EntityTreeNode[] = roots.map((ewa, idx) =>
makeNode(ewa, "", idx + 1, new Set())
);
// console.log("Entity tree:", tree, "Reference-only promoted roots:", Array.from(referenceOnlyEntityIds));
return Object.assign({}, details, { EntityTree: tree });
};
/**
* Generate a single hierarchical sample JSON object from a model's EntityTree.
* Top-level keys are root entity names. Each entity can either be:
* - An object of its attributes (and nested entities)
* - An array of such objects if Entity.Array === 'Yes' (case-insensitive) OR null (null defaults to Yes).
*
* Parameter 'count' controls ONLY the number of objects created for root-level array entities.
* Nested array entities ALWAYS get exactly 1 object element (still wrapped in an array to reflect schema).
*
* Attribute value generation rules (unchanged from prior implementation):
* - Use Attribute.Example if present (non-empty).
* - Otherwise infer based on DataType (string/number/boolean/date/enum); unknown -> string.
* - Enum picks a random ValueName/Value from its ValueSet (if available).
*
* Repeated root entity names are disambiguated by suffix _N.
*/
export function generateSampleRecords(
model: DataModelWithDetailsWithTree | DataModelWithDetailsDTO,
tree: EntityTreeNode[],
count: number
): any {
const rootArrayCount = Math.max(0, Math.min(count, 100));
// Value set lookup for enum support
const valueSetMap = new Map<number, { names: string[] }>();
const valueSets = (model as any).ValueSets || [];
valueSets.forEach((vs: any) => {
const names = Array.isArray(vs.Values)
? vs.Values.map((v: any) => v?.ValueName || v?.Value).filter((v: any) => v != null)
: [];
valueSetMap.set(vs.ValueSet?.Id || vs.ValueSetId || vs.Id, { names });
});
const lc = (s: any) => String(s || "").toLowerCase();
const genValue = (attr: any) => {
const example = attr?.Example;
if (example !== null && example !== undefined && example !== "") return example;
const isArray = attr?.Array && attr.Array !== "No";
const dt = lc(attr?.DataType || "string");
let myGenVal: any = "";
switch (dt) {
case "number":
case "int":
case "integer":
myGenVal = faker.number.int({ min: 0, max: 1000 });
break;
case "float":
case "double":
myGenVal = faker.number.float({ min: 0, max: 1000, fractionDigits: 2 });
break;
case "boolean":
case "bool":
myGenVal = faker.datatype.boolean();
break;
case "date":
case "datetime":
case "timestamp":
myGenVal = faker.date.recent({ days: 30 }).toISOString();
break;
case "enum": {
const vsId = attr?.ValueSetId;
if (vsId && valueSetMap.has(vsId)) {
const { names } = valueSetMap.get(vsId)!;
if (names.length) {
myGenVal = names[Math.floor(Math.random() * names.length)];
break;
}
}
myGenVal = faker.helpers.arrayElement([
faker.word.sample(),
faker.word.noun(),
faker.word.adjective(),
]);
break;
}
case "string":
default: {
const nameLc = lc(attr?.Name);
if (nameLc.includes("id")) myGenVal = faker.string.uuid();
if (nameLc.includes("email")) myGenVal = faker.internet.email();
if (nameLc.includes("name")) myGenVal = faker.person.fullName();
if (nameLc.includes("date")) myGenVal = faker.date.recent().toISOString();
if (nameLc.includes("url")) myGenVal = faker.internet.url();
myGenVal = myGenVal || faker.lorem.word();
}
}
return isArray ? [myGenVal] : myGenVal;
};
const isArrayEntity = (wrapper: any) => {
const meta = wrapper?.Entity?.Id ? wrapper.Entity : wrapper;
const arr = meta?.Array; // 'Yes' | 'No' | null
if (arr == null) return true; // default to Yes
return String(arr).trim().toLowerCase() === 'yes';
};
const buildEntityContent = (node: EntityTreeNode): any => {
const entityWrapper: any = node.Entity as any;
const attrs = (entityWrapper.Attributes || []) as any[];
const obj: any = {};
attrs.forEach((attr) => {
const key = attr.Name || attr.UniqueName || `attr_${attr.Id}`;
obj[key] = genValue(attr);
});
if (node.Children && node.Children.length) {
node.Children.forEach((child) => {
const childWrapper: any = child.Entity as any;
const childMeta = childWrapper.Entity?.Id ? childWrapper.Entity : childWrapper;
const childName = childMeta.Name || childMeta.UniqueName || `Entity_${child.EntityId}`;
const childIsArray = isArrayEntity(childWrapper);
const childValue = buildEntityObject(child, false); // returns object or array
obj[childName] = childValue;
if (childIsArray && Array.isArray(childValue) && childValue.length === 0) {
// ensure at least one element for nested arrays
childValue.push(buildEntityContent(child));
}
});
}
return obj;
};
const buildEntityObject = (node: EntityTreeNode, isRoot: boolean): any => {
const wrapper: any = node.Entity as any;
const arrayFlag = isArrayEntity(wrapper);
if (!arrayFlag) {
return buildEntityContent(node);
}
// Array case
const desired = isRoot ? rootArrayCount : 1; // nested arrays -> single element
const arr: any[] = [];
for (let i = 0; i < desired; i++) {
arr.push(buildEntityContent(node));
}
return arr;
};
const rootNamesCounter = new Map<string, number>();
const rootObject: any = {};
tree.forEach((rootNode) => {
const rootWrapper: any = rootNode.Entity as any;
const meta = rootWrapper.Entity?.Id ? rootWrapper.Entity : rootWrapper;
let rootName = meta.Name || meta.UniqueName || `Entity_${rootNode.EntityId}`;
if (rootObject[rootName] !== undefined) {
const idx = (rootNamesCounter.get(rootName) || 0) + 1;
rootNamesCounter.set(rootName, idx);
rootName = `${rootName}_${idx}`;
} else {
rootNamesCounter.set(rootName, 0);
}
rootObject[rootName] = buildEntityObject(rootNode, true);
});
return rootObject;
}
/**
* Generate a JSON Schema (draft 2020-12) from the provided EntityTree.
*
* Rules / Mapping:
* - Each root entity becomes a top-level property on the returned schema's root object.
* - If an entity's Array flag (Entity.Array) is 'Yes' (or null -> default Yes) it is represented as
* { type: 'array', items: <entityObjectSchema> }. Otherwise just the object schema.
* - Attributes map to JSON Schema primitive types based on DataType (string/number/integer/boolean/date/datetime/timestamp/enum).
* - Enum attributes include an 'enum' keyword populated from associated ValueSet values (when available).
* - Required attributes are gathered using the same heuristics as elsewhere (Required in ['yes','y','true','required','mandatory']).
* - Child entities become nested properties (recursively applying the same array logic).
* - Duplicate root entity names get suffixed ( _N ) just like sample record generation to avoid collisions.
* - additionalProperties is set to false for generated object schemas to keep them strict (can be relaxed if needed).
*/
export function generateJsonSchema(
model: DataModelWithDetailsWithTree | DataModelWithDetailsDTO,
tree: EntityTreeNode[]
): any {
const lc = (s: any) => String(s || '').toLowerCase();
// Build value set map for enum expansion
const valueSetMap = new Map<number, { names: string[] }>();
const valueSets = (model as any).ValueSets || [];
valueSets.forEach((vs: any) => {
const names = Array.isArray(vs.Values)
? vs.Values.map((v: any) => v?.ValueName || v?.Value).filter((v: any) => v != null)
: [];
valueSetMap.set(vs.ValueSet?.Id || vs.ValueSetId || vs.Id, { names });
});
const isArrayEntity = (wrapper: any) => {
const meta = wrapper?.Entity?.Id ? wrapper.Entity : wrapper;
const arr = meta?.Array; // 'Yes' | 'No' | null
if (arr == null) return true; // default to Yes
return String(arr).trim().toLowerCase() === 'yes';
};
const isRequiredAttribute = (required: string | null | undefined) => {
const r = lc(required).trim();
if (!r) return false;
return (
r === 'yes' ||
r === 'y' ||
r === 'true' ||
r === 'required' ||
r === 'mandatory'
);
};
const mapAttribute = (attr: any) => {
const dt = lc(attr?.DataType || 'string');
switch (dt) {
case 'number':
case 'int':
case 'integer':
return { type: 'integer' };
case 'float':
case 'double':
return { type: 'number' };
case 'boolean':
case 'bool':
return { type: 'boolean' };
case 'date':
case 'datetime':
case 'timestamp':
return { type: 'string', format: 'date-time' };
case 'enum': {
const vsId = attr?.ValueSetId;
if (vsId && valueSetMap.has(vsId)) {
const { names } = valueSetMap.get(vsId)!;
if (names.length) {
return { type: 'string', enum: names };
}
}
return { type: 'string' };
}
case 'string':
default:
return { type: 'string' };
}
};
const buildEntitySchema = (node: EntityTreeNode): any => {
const wrapper: any = node.Entity as any;
const attrs = (wrapper.Attributes || []) as any[];
const properties: Record<string, any> = {};
const required: string[] = [];
attrs.forEach(attr => {
const key = attr.Name || attr.UniqueName || `attr_${attr.Id}`;
properties[key] = mapAttribute(attr);
if (isRequiredAttribute(attr.Required)) required.push(key);
});
if (node.Children && node.Children.length) {
node.Children.forEach(child => {
const childWrapper: any = child.Entity as any;
const meta = childWrapper.Entity?.Id ? childWrapper.Entity : childWrapper;
const childName = meta.Name || meta.UniqueName || `Entity_${child.EntityId}`;
const childSchema = buildNode(child);
properties[childName] = childSchema;
});
}
const objSchema: any = {
type: 'object',
properties,
additionalProperties: false,
};
if (required.length) objSchema.required = required;
return objSchema;
};
const buildNode = (node: EntityTreeNode): any => {
const wrapper: any = node.Entity as any;
if (isArrayEntity(wrapper)) {
return {
type: 'array',
items: buildEntitySchema(node),
minItems: 0,
};
}
return buildEntitySchema(node);
};
const rootNamesCounter = new Map<string, number>();
const rootProperties: Record<string, any> = {};
tree.forEach(rootNode => {
const rootWrapper: any = rootNode.Entity as any;
const meta = rootWrapper.Entity?.Id ? rootWrapper.Entity : rootWrapper;
let rootName = meta.Name || meta.UniqueName || `Entity_${rootNode.EntityId}`;
if (rootProperties[rootName] !== undefined) {
const idx = (rootNamesCounter.get(rootName) || 0) + 1;
rootNamesCounter.set(rootName, idx);
rootName = `${rootName}_${idx}`;
} else {
rootNamesCounter.set(rootName, 0);
}
rootProperties[rootName] = buildNode(rootNode);
});
return {
$schema: 'https://json-schema.org/draft/2020-12/schema',
type: 'object',
properties: rootProperties,
additionalProperties: false,
};
}
/**
* Generate sample data from a JSON Schema object (draft 2020-12 style or similar).
*
* This is a schema-driven counterpart to generateSampleRecords().
* It intentionally keeps generation predictable and shallow while still producing
* representative shape samples:
* - object: populate each property (recursing) and include required props.
* - array: produce `options.arrayCount` root elements (default 1) and exactly 1 element for nested arrays.
* - string/integer/number/boolean/date-time: lightweight faker-backed examples.
* - enum: pick a random allowed value.
* - oneOf/anyOf/allOf: pick the first resolvable branch (simple heuristic).
* - $ref (internal): if schema.definitions or components.schemas is present, it resolves basic local refs (#/definitions/Name or #/components/schemas/Name).
*/
export function generateSampleDataFromSchema(
schema: any,
options?: { arrayCount?: number; depthLimit?: number }
): any {
const arrayRootCount = Math.max(1, Math.min(options?.arrayCount ?? 1, 25));
const depthLimit = Math.max(1, Math.min(options?.depthLimit ?? 12, 50));
// Basic ref resolver (internal only)
const resolveRef = (ref: string): any => {
if (!ref.startsWith('#/')) return {}; // unsupported external refs
const path = ref.replace(/^#\//, '').split('/');
let cur: any = schema;
for (const seg of path) {
if (cur && typeof cur === 'object') cur = cur[seg]; else return {};
}
return cur;
};
const rand = (min: number, max: number) => min + Math.floor(Math.random() * (max - min + 1));
const genPrimitive = (sch: any, keyName?: string): any => {
if (sch && Array.isArray(sch.enum) && sch.enum.length) {
return sch.enum[rand(0, sch.enum.length - 1)];
}
const fmt = sch?.format;
switch (sch?.type) {
case 'integer':
return faker.number.int({ min: 0, max: 1000 });
case 'number':
return faker.number.float({ min: 0, max: 1000, fractionDigits: 2 });
case 'boolean':
return faker.datatype.boolean();
case 'string': {
if (fmt === 'date-time') return faker.date.recent({ days: 30 }).toISOString();
const k = (keyName || '').toLowerCase();
if (k.includes('id')) return faker.string.uuid();
if (k.includes('email')) return faker.internet.email();
if (k.includes('name')) return faker.person.fullName();
if (k.includes('url')) return faker.internet.url();
if (k.includes('date')) return faker.date.recent().toISOString();
return faker.lorem.word();
}
default:
return null;
}
};
const chooseComposite = (sch: any): any => {
if (Array.isArray(sch.oneOf) && sch.oneOf.length) return sch.oneOf[0];
if (Array.isArray(sch.anyOf) && sch.anyOf.length) return sch.anyOf[0];
if (Array.isArray(sch.allOf) && sch.allOf.length) {
// Merge shallowly (later objects override earlier)
return sch.allOf.reduce((acc: any, part: any) => ({ ...acc, ...part }), {});
}
return sch;
};
// isTopLevelArray indicates either the schema itself is an array OR an array that is a direct child of the root object.
const build = (sch: any, depth: number, keyName?: string, isTopLevelArray = false): any => {
if (!sch || depth > depthLimit) return null;
if (sch.$ref) return build(resolveRef(sch.$ref), depth + 1, keyName, isTopLevelArray);
sch = chooseComposite(sch);
if (Array.isArray(sch.type)) {
// prefer first non-null type
const primary = sch.type.find((t: string) => t !== 'null') || sch.type[0];
sch = { ...sch, type: primary };
}
switch (sch.type) {
case 'object': {
const obj: any = {};
const props = sch.properties || {};
Object.keys(props).forEach(propKey => {
// Arrays that are direct children of the root object (depth === 0 for root, so child depth === 1)
const childSchema = props[propKey];
const childIsTopLevelArray = depth === 0 && childSchema && (childSchema.type === 'array' || (Array.isArray(childSchema.type) && childSchema.type.includes('array')));
obj[propKey] = build(childSchema, depth + 1, propKey, childIsTopLevelArray);
});
return obj;
}
case 'array': {
const items = sch.items || {};
const count = isTopLevelArray ? arrayRootCount : 1;
const arr: any[] = [];
for (let i = 0; i < count; i++) arr.push(build(items, depth + 1, keyName, false));
return arr;
}
case 'string':
case 'integer':
case 'number':
case 'boolean':
return genPrimitive(sch, keyName);
case 'null':
return null;
default: {
// fallback: attempt properties/items
if (sch.properties) return build({ ...sch, type: 'object' }, depth + 1, keyName, isTopLevelArray);
if (sch.items) return build({ ...sch, type: 'array' }, depth + 1, keyName, isTopLevelArray);
return genPrimitive({ type: 'string' }, keyName);
}
}
};
return build(schema, 0, undefined, schema?.type === 'array');
}
// export const getModelEntityAssociations = async (modelId: number) => {
// try {
// const response = await api.get<EntityAssociation>(
// `${apiBaseUrl}/entity_associations/by_data_model_id/${modelId}?page=1&pagination=false&check_base=true`
// );
// return response.data;
// } catch (error) {
// console.error("Error fetching entity associations:", error);
// throw error;
// }
// };
export const getModelValueSets = async (modelId: number) => {
try {
const response = await api.get<CountResponse>(
`${apiBaseUrl}/value_sets/by_data_model_id/${modelId}?page=1&pagination=false&check_base=true`
);
return response.data.data;
// return {
// valuesets: response.data.data,
// count: response.data.total,
// };
} catch (error) {
console.error("Error fetching value sets:", error);
throw error;
}
};
export const getModelConstraints = async (modelId: number) => {
try {
const response = await api.get(
`${apiBaseUrl}/datamodel_constraints/by_data_model_id/${modelId}?page=1&size=10&pagination=false`
);
return response.data;
} catch (error) {
console.error("!!!Error fetching model constraints:", error);
throw error;
}
};
/**
* Fetch OrgLIF extension data models.
* Optional filters:
* - contributor_organization: string
* - state: string (matches backend StateType values)
* Returns a plain list of DataModel (no ApiResponse wrapper).
*/
export const listOrgLifModels = async (
filters?: { contributor_organization?: string; state?: StateType }
): Promise<DataModel[]> => {
try {
const response = await api.get<DataModel[]>(`${apiBaseUrl}/datamodels/orglif/`, {
params: {
contributor_organization: filters?.contributor_organization,
state: filters?.state,
},
// Avoid sending undefined params
paramsSerializer: {
serialize: (params) => {
const entries = Object.entries(params).filter(([, v]) => v !== undefined && v !== null && String(v).length > 0);
const usp = new URLSearchParams(entries as [string, string][]);
return usp.toString();
},
},
});
return response.data ?? [];
} catch (error) {
console.error("Error fetching OrgLIF data models:", error);
throw error;
}
};
export interface CreateDataModelParams {
Name: string;
Description?: string;
UseConsiderations?: string;
Type: "SourceSchema" | "PartnerLIF";
BaseDataModelId?: number;
DataModelVersion: string;
Notes?: string;
Contributor?: string;
ContributorOrganization?: string;
LevelOfAccess?: "Public" | "Private";
State?: "Draft" | "Published";
Tags?: string;
CreationDate?: string;
ActivationDate?: string;
DeprecationDate?: string;
File?: File | null; // for uploads
}
export const createDataModel = async (params: CreateDataModelParams) => {
try {
const response = await api.post(`${apiBaseUrl}/datamodels/`, params);
return response.data;
} catch (error) {
console.error("Error creating data model:", error);
throw error;
}
};
export const createDataModelFromUpload = async (params: CreateDataModelParams) => {
try {
const { File, ...rest } = params;
if (!File) {
throw new Error("File is required when uploading a data model schema.");
}
const formData = new FormData();
formData.append("file", File);
const restRecord = rest as Record<string, unknown>;
const appendIfPresent = (formKey: string, value: unknown) => {
if (value !== undefined && value !== null && value !== "") {
formData.append(formKey, String(value));
}
};
appendIfPresent("data_model_type", restRecord.Type);
appendIfPresent(
"use_considerations",
restRecord.UseConsiderations ?? restRecord["Use Considerations"]
);
appendIfPresent("notes", restRecord.Notes);
appendIfPresent("activation_date", restRecord.ActivationDate);
appendIfPresent("deprecation_date", restRecord.DeprecationDate);
appendIfPresent("contributor", restRecord.Contributor);
appendIfPresent(
"contributor_organization",
restRecord.ContributorOrganization
);
appendIfPresent("data_model_name", restRecord.Name);
appendIfPresent("data_model_version", restRecord.DataModelVersion);
appendIfPresent("data_model_description", restRecord.Description);
appendIfPresent("base_data_model_id", restRecord.BaseDataModelId);
appendIfPresent("state", restRecord.State);
appendIfPresent("tags", restRecord.Tags);
const response = await api.post(
`${apiBaseUrl}/datamodels/open_api_schema/upload`,
formData,
{
headers: { "Content-Type": "multipart/form-data" },
}
);
return response.data;
} catch (error) {
console.error("Error creating data model from upload:", error);
throw error;
}
};
export const updateDataModel = async (id: number, params: Partial<CreateDataModelParams>) => {
try {
const response = await api.put(`${apiBaseUrl}/datamodels/${id}`, params);
return response.data;
} catch (error) {
console.error("Error updating data model:", error);
throw error;
}
};
export const deleteDataModel = async (id: number) => {
try {
const response = await api.delete(`${apiBaseUrl}/datamodels/${id}`);
return response.data;
} catch (error) {
console.error("Error deleting data model:", error);
throw error;
}
};
export interface ConstraintDTO {
Id: number;
Name: string;
Description: string | null;
ForDataModelId: number;
ElementType: "Entity" | "Attribute" | "ValueSet";
ElementId: number;
ElementName: string;
ConstraintType: string | null;
Notes: string | null;
CreationDate: string | null;
ActivationDate: string | null;
DeprecationDate: string | null;
Contributor: string | null;
ContributorOrganization: string | null;
Deleted: boolean;
}
export interface CreateConstraintParams {
Name: string;
Description?: string | null;
ForDataModelId: number;
ElementType: "Entity" | "Attribute" | "ValueSet";
ElementId: number;
Notes?: string | null;
Contributor?: string | null;
ContributorOrganization?: string | null;
}
export const getOpenApiSchema = async (id: number, pub?: boolean, mdEnt?: boolean, mdAttr?: boolean, mdFull?: boolean, blob?: boolean) => {
const params = [
blob ? `download=true` : '',
pub ? `public_only=true` : '',
mdEnt ? `include_entity_md=${mdEnt}` : '',
mdAttr ? `include_attr_md=${mdAttr}` : '',
mdFull ? `full_export=${mdFull}` : '',
].filter(Boolean);
const query = params.length ? `?${params.join('&')}` : '';
let result: any = {};
try {
result = await api.get<ApiResponse>(`${apiBaseUrl}/datamodels/open_api_schema/${id}${query}`, { responseType: blob ? 'blob' : 'json' });
// console.log("getOpenApiSchema result:", result);
return result.data;
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
};
export const downloadOpenApiSchema = async (id: number, type?: string, pub?: boolean) => {
type = type?.length && ['full', 'legacy', 'bare'].includes(type) ? type : 'full';
let mdEnt = false;
let mdAttr = false;
let mdFull = false;
switch (type) {
case 'full': mdEnt = true; mdAttr = true; mdFull = true; break;
case 'legacy': mdAttr = true; break;
default: break;
}
const fileName = `data_model_${id}_${type}_openapi_schema.json`;
const result = await getOpenApiSchema(id, pub, mdEnt, mdAttr, mdFull);
if (result) {
// console.log("Initiating download of OpenAPI schema:", { fileName, result });
downloadJsonFile(result, fileName);
} else {
// console.error("No data received for file download.");
throw new Error("No data received for file download.");
}
};