@memberjunction/codegen-lib 4.0.0 → 4.1.0
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.
- package/README.md +826 -639
- package/dist/Angular/angular-codegen.d.ts +9 -2
- package/dist/Angular/angular-codegen.d.ts.map +1 -1
- package/dist/Angular/angular-codegen.js +84 -62
- package/dist/Angular/angular-codegen.js.map +1 -1
- package/dist/Angular/entity-data-grid-related-entity-component.d.ts.map +1 -1
- package/dist/Angular/entity-data-grid-related-entity-component.js +2 -1
- package/dist/Angular/entity-data-grid-related-entity-component.js.map +1 -1
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +10 -0
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/manage-metadata.d.ts +300 -4
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +1024 -147
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/sql_codegen.d.ts +13 -0
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +74 -17
- package/dist/Database/sql_codegen.js.map +1 -1
- package/dist/Misc/advanced_generation.d.ts +68 -6
- package/dist/Misc/advanced_generation.d.ts.map +1 -1
- package/dist/Misc/advanced_generation.js +94 -49
- package/dist/Misc/advanced_generation.js.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.d.ts +5 -0
- package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.js +24 -6
- package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
- package/dist/Misc/graphql_server_codegen.d.ts.map +1 -1
- package/dist/Misc/graphql_server_codegen.js +3 -1
- package/dist/Misc/graphql_server_codegen.js.map +1 -1
- package/dist/__tests__/metadataConfig.test.d.ts +12 -0
- package/dist/__tests__/metadataConfig.test.d.ts.map +1 -0
- package/dist/__tests__/metadataConfig.test.js +604 -0
- package/dist/__tests__/metadataConfig.test.js.map +1 -0
- package/package.json +21 -17
- package/dist/Angular/user-view-grid-related-entity-component.d.ts +0 -43
- package/dist/Angular/user-view-grid-related-entity-component.d.ts.map +0 -1
- package/dist/Angular/user-view-grid-related-entity-component.js +0 -85
- package/dist/Angular/user-view-grid-related-entity-component.js.map +0 -1
|
@@ -4,6 +4,7 @@ import { CodeNameFromString, EntityInfo, ExtractActualDefaultValue, LogError, Lo
|
|
|
4
4
|
import { logError, logMessage, logStatus } from "../Misc/status_logging.js";
|
|
5
5
|
import { SQLUtilityBase } from "./sql.js";
|
|
6
6
|
import { AdvancedGeneration } from "../Misc/advanced_generation.js";
|
|
7
|
+
import { SQLParser } from "@memberjunction/core-entities-server";
|
|
7
8
|
import { convertCamelCaseToHaveSpaces, generatePluralName, MJGlobal, stripTrailingChars } from "@memberjunction/global";
|
|
8
9
|
import { v4 as uuidv4 } from 'uuid';
|
|
9
10
|
import * as fs from 'fs';
|
|
@@ -92,6 +93,239 @@ export class ManageMetadataBase {
|
|
|
92
93
|
return null;
|
|
93
94
|
}
|
|
94
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* Extracts a flat array of table configs from the config file, handling both formats:
|
|
98
|
+
* 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
|
|
99
|
+
* 2. Flat tables array (legacy format): { "Tables": [{ "SchemaName": "dbo", "TableName": "Orders", ... }] }
|
|
100
|
+
* Returns a normalized array where each entry has SchemaName, TableName, PrimaryKey[], and ForeignKeys[].
|
|
101
|
+
*/
|
|
102
|
+
extractTablesFromConfig(config) {
|
|
103
|
+
const results = [];
|
|
104
|
+
// Check for flat "Tables" array format first
|
|
105
|
+
if (Array.isArray(config.Tables)) {
|
|
106
|
+
for (const table of config.Tables) {
|
|
107
|
+
const t = table;
|
|
108
|
+
results.push({
|
|
109
|
+
SchemaName: t.SchemaName || 'dbo',
|
|
110
|
+
TableName: t.TableName,
|
|
111
|
+
PrimaryKey: t.PrimaryKey || [],
|
|
112
|
+
ForeignKeys: t.ForeignKeys || [],
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return results;
|
|
116
|
+
}
|
|
117
|
+
// Schema-as-key format: iterate over keys, skip metadata and special section keys
|
|
118
|
+
const metadataKeys = new Set(['$schema', 'description', 'version', 'VirtualEntities', 'ISARelationships', 'Tables']);
|
|
119
|
+
for (const key of Object.keys(config)) {
|
|
120
|
+
if (metadataKeys.has(key))
|
|
121
|
+
continue;
|
|
122
|
+
const schemaName = key;
|
|
123
|
+
const tables = config[key];
|
|
124
|
+
if (!Array.isArray(tables))
|
|
125
|
+
continue;
|
|
126
|
+
for (const table of tables) {
|
|
127
|
+
const t = table;
|
|
128
|
+
results.push({
|
|
129
|
+
SchemaName: schemaName,
|
|
130
|
+
TableName: t.TableName,
|
|
131
|
+
PrimaryKey: t.PrimaryKey || [],
|
|
132
|
+
ForeignKeys: t.ForeignKeys || [],
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return results;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Extracts VirtualEntities array from the additionalSchemaInfo config file.
|
|
140
|
+
* The config may contain a top-level "VirtualEntities" key with an array of
|
|
141
|
+
* virtual entity definitions.
|
|
142
|
+
*/
|
|
143
|
+
extractVirtualEntitiesFromConfig(config) {
|
|
144
|
+
const virtualEntities = config.VirtualEntities;
|
|
145
|
+
if (!Array.isArray(virtualEntities))
|
|
146
|
+
return [];
|
|
147
|
+
return virtualEntities.map((ve) => ({
|
|
148
|
+
ViewName: ve.ViewName,
|
|
149
|
+
SchemaName: ve.SchemaName || undefined,
|
|
150
|
+
EntityName: ve.EntityName || undefined,
|
|
151
|
+
Description: ve.Description || undefined,
|
|
152
|
+
PrimaryKey: Array.isArray(ve.PrimaryKey) ? ve.PrimaryKey : undefined,
|
|
153
|
+
ForeignKeys: Array.isArray(ve.ForeignKeys) ? ve.ForeignKeys : undefined,
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Extracts ISARelationships array from the additionalSchemaInfo config file.
|
|
158
|
+
* The config may contain a top-level "ISARelationships" key with an array of
|
|
159
|
+
* parent-child relationship definitions.
|
|
160
|
+
*/
|
|
161
|
+
extractISARelationshipsFromConfig(config) {
|
|
162
|
+
const relationships = config.ISARelationships;
|
|
163
|
+
if (!Array.isArray(relationships))
|
|
164
|
+
return [];
|
|
165
|
+
return relationships.map((rel) => ({
|
|
166
|
+
ChildEntity: rel.ChildEntity,
|
|
167
|
+
ParentEntity: rel.ParentEntity,
|
|
168
|
+
SchemaName: rel.SchemaName || undefined,
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Processes IS-A relationship configurations from the additionalSchemaInfo config.
|
|
173
|
+
* For each configured relationship, looks up both entities by name (or by table name
|
|
174
|
+
* within the given schema) and sets Entity.ParentID on the child entity.
|
|
175
|
+
* Must run AFTER entities are created but BEFORE manageParentEntityFields().
|
|
176
|
+
*/
|
|
177
|
+
async processISARelationshipConfig(pool) {
|
|
178
|
+
const config = ManageMetadataBase.getSoftPKFKConfig();
|
|
179
|
+
if (!config)
|
|
180
|
+
return { success: true, updatedCount: 0 };
|
|
181
|
+
const relationships = this.extractISARelationshipsFromConfig(config);
|
|
182
|
+
if (relationships.length === 0)
|
|
183
|
+
return { success: true, updatedCount: 0 };
|
|
184
|
+
let updatedCount = 0;
|
|
185
|
+
const schema = mj_core_schema();
|
|
186
|
+
for (const rel of relationships) {
|
|
187
|
+
try {
|
|
188
|
+
// Look up the parent entity — try by Name first, then by BaseTable within the given schema
|
|
189
|
+
const parentResult = await pool.request()
|
|
190
|
+
.input('ParentName', rel.ParentEntity)
|
|
191
|
+
.input('SchemaName', rel.SchemaName || null)
|
|
192
|
+
.query(`
|
|
193
|
+
SELECT TOP 1 ID, Name
|
|
194
|
+
FROM [${schema}].vwEntities
|
|
195
|
+
WHERE Name = @ParentName
|
|
196
|
+
OR (BaseTable = @ParentName AND (@SchemaName IS NULL OR SchemaName = @SchemaName))
|
|
197
|
+
ORDER BY CASE WHEN Name = @ParentName THEN 0 ELSE 1 END
|
|
198
|
+
`);
|
|
199
|
+
if (parentResult.recordset.length === 0) {
|
|
200
|
+
logError(` > IS-A config: parent entity "${rel.ParentEntity}" not found — skipping`);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const parentId = parentResult.recordset[0].ID;
|
|
204
|
+
const parentName = parentResult.recordset[0].Name;
|
|
205
|
+
// Look up the child entity — same strategy
|
|
206
|
+
const childResult = await pool.request()
|
|
207
|
+
.input('ChildName', rel.ChildEntity)
|
|
208
|
+
.input('SchemaName', rel.SchemaName || null)
|
|
209
|
+
.query(`
|
|
210
|
+
SELECT TOP 1 ID, Name, ParentID
|
|
211
|
+
FROM [${schema}].vwEntities
|
|
212
|
+
WHERE Name = @ChildName
|
|
213
|
+
OR (BaseTable = @ChildName AND (@SchemaName IS NULL OR SchemaName = @SchemaName))
|
|
214
|
+
ORDER BY CASE WHEN Name = @ChildName THEN 0 ELSE 1 END
|
|
215
|
+
`);
|
|
216
|
+
if (childResult.recordset.length === 0) {
|
|
217
|
+
logError(` > IS-A config: child entity "${rel.ChildEntity}" not found — skipping`);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
const childId = childResult.recordset[0].ID;
|
|
221
|
+
const childName = childResult.recordset[0].Name;
|
|
222
|
+
const existingParentId = childResult.recordset[0].ParentID;
|
|
223
|
+
// Skip if already set correctly
|
|
224
|
+
if (existingParentId === parentId) {
|
|
225
|
+
logStatus(` > IS-A: "${childName}" already has ParentID set to "${parentName}", skipping`);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
// Set ParentID on the child entity
|
|
229
|
+
await pool.request()
|
|
230
|
+
.input('ParentID', parentId)
|
|
231
|
+
.input('ChildID', childId)
|
|
232
|
+
.query(`UPDATE [${schema}].Entity SET ParentID = @ParentID WHERE ID = @ChildID`);
|
|
233
|
+
if (existingParentId) {
|
|
234
|
+
logStatus(` > IS-A: Updated "${childName}" ParentID from previous value to "${parentName}"`);
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
logStatus(` > IS-A: Set "${childName}" ParentID to "${parentName}"`);
|
|
238
|
+
}
|
|
239
|
+
updatedCount++;
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
const errMessage = err instanceof Error ? err.message : String(err);
|
|
243
|
+
logError(` > IS-A config: Failed to set ParentID for "${rel.ChildEntity}": ${errMessage}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { success: true, updatedCount };
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Processes virtual entity configurations from the additionalSchemaInfo config.
|
|
250
|
+
* For each configured virtual entity, checks if it already exists and creates
|
|
251
|
+
* it if not. Uses the spCreateVirtualEntity stored procedure.
|
|
252
|
+
* Must run BEFORE manageVirtualEntities() so newly created entities get field-synced.
|
|
253
|
+
*/
|
|
254
|
+
async processVirtualEntityConfig(pool, currentUser) {
|
|
255
|
+
const config = ManageMetadataBase.getSoftPKFKConfig();
|
|
256
|
+
if (!config)
|
|
257
|
+
return { success: true, createdCount: 0 };
|
|
258
|
+
const virtualEntities = this.extractVirtualEntitiesFromConfig(config);
|
|
259
|
+
if (virtualEntities.length === 0)
|
|
260
|
+
return { success: true, createdCount: 0 };
|
|
261
|
+
let createdCount = 0;
|
|
262
|
+
const schema = mj_core_schema();
|
|
263
|
+
for (const ve of virtualEntities) {
|
|
264
|
+
const viewSchema = ve.SchemaName || schema;
|
|
265
|
+
const viewName = ve.ViewName;
|
|
266
|
+
const entityName = ve.EntityName || this.deriveEntityNameFromView(viewName);
|
|
267
|
+
const pkField = ve.PrimaryKey?.[0] || 'ID';
|
|
268
|
+
// Check if entity already exists for this view
|
|
269
|
+
const existsResult = await pool.request()
|
|
270
|
+
.input('ViewName', viewName)
|
|
271
|
+
.input('SchemaName', viewSchema)
|
|
272
|
+
.query(`SELECT ID FROM [${schema}].vwEntities WHERE BaseView = @ViewName AND SchemaName = @SchemaName`);
|
|
273
|
+
if (existsResult.recordset.length > 0) {
|
|
274
|
+
logStatus(` > Virtual entity "${entityName}" already exists for view [${viewSchema}].[${viewName}], skipping creation`);
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
// Verify the view actually exists in the database
|
|
278
|
+
const viewExistsResult = await pool.request()
|
|
279
|
+
.input('ViewName', viewName)
|
|
280
|
+
.input('SchemaName', viewSchema)
|
|
281
|
+
.query(`SELECT 1 FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = @ViewName AND TABLE_SCHEMA = @SchemaName`);
|
|
282
|
+
if (viewExistsResult.recordset.length === 0) {
|
|
283
|
+
logError(` > View [${viewSchema}].[${viewName}] does not exist — skipping virtual entity creation for "${entityName}"`);
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
// Create the virtual entity via the stored procedure
|
|
287
|
+
try {
|
|
288
|
+
const createResult = await pool.request()
|
|
289
|
+
.input('Name', entityName)
|
|
290
|
+
.input('BaseView', viewName)
|
|
291
|
+
.input('SchemaName', viewSchema)
|
|
292
|
+
.input('PrimaryKeyFieldName', pkField)
|
|
293
|
+
.input('Description', ve.Description || null)
|
|
294
|
+
.execute(`[${schema}].spCreateVirtualEntity`);
|
|
295
|
+
const newEntityId = createResult.recordset?.[0]?.['']
|
|
296
|
+
|| createResult.recordset?.[0]?.ID
|
|
297
|
+
|| createResult.recordset?.[0]?.Column0;
|
|
298
|
+
logStatus(` > Created virtual entity "${entityName}" (ID: ${newEntityId}) for view [${viewSchema}].[${viewName}]`);
|
|
299
|
+
createdCount++;
|
|
300
|
+
// Add virtual entity to the application for its schema and set default permissions
|
|
301
|
+
// (same logic as table-backed entities)
|
|
302
|
+
if (newEntityId) {
|
|
303
|
+
await this.addEntityToApplicationForSchema(pool, newEntityId, entityName, viewSchema, currentUser);
|
|
304
|
+
await this.addDefaultPermissionsForEntity(pool, newEntityId, entityName);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
catch (err) {
|
|
308
|
+
const errMessage = err instanceof Error ? err.message : String(err);
|
|
309
|
+
logError(` > Failed to create virtual entity "${entityName}": ${errMessage}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return { success: true, createdCount };
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Derives an entity name from a view name by removing common prefixes (vw, v_)
|
|
316
|
+
* and converting to a human-friendly format.
|
|
317
|
+
*/
|
|
318
|
+
deriveEntityNameFromView(viewName) {
|
|
319
|
+
let name = viewName;
|
|
320
|
+
// Remove common view prefixes
|
|
321
|
+
if (name.startsWith('vw'))
|
|
322
|
+
name = name.substring(2);
|
|
323
|
+
else if (name.startsWith('v_'))
|
|
324
|
+
name = name.substring(2);
|
|
325
|
+
// Add spaces before capital letters (PascalCase → "Pascal Case")
|
|
326
|
+
name = name.replace(/([a-z])([A-Z])/g, '$1 $2');
|
|
327
|
+
return name.trim();
|
|
328
|
+
}
|
|
95
329
|
/**
|
|
96
330
|
* Primary function to manage metadata within the CodeGen system. This function will call a series of sub-functions to manage the metadata.
|
|
97
331
|
* @param pool - the ConnectionPool object to use for querying and updating the database
|
|
@@ -153,11 +387,29 @@ export class ManageMetadataBase {
|
|
|
153
387
|
if (ManageMetadataBase.newEntityList.length > 0) {
|
|
154
388
|
await this.generateNewEntityDescriptions(pool, md, currentUser); // don't pass excludeSchemas becuase by definition this is the NEW entities we created
|
|
155
389
|
}
|
|
390
|
+
// Config-driven virtual entity creation — run BEFORE manageVirtualEntities
|
|
391
|
+
// so newly created entities get their fields synced in the next step
|
|
392
|
+
const vecResult = await this.processVirtualEntityConfig(pool, currentUser);
|
|
393
|
+
if (vecResult.createdCount > 0) {
|
|
394
|
+
logStatus(` > Created ${vecResult.createdCount} virtual entit${vecResult.createdCount === 1 ? 'y' : 'ies'} from config`);
|
|
395
|
+
// Refresh metadata so manageVirtualEntities can find the newly-created entities
|
|
396
|
+
// in the cache — otherwise EntityByName() returns null and field sync is silently skipped
|
|
397
|
+
const md = new Metadata();
|
|
398
|
+
await md.Refresh();
|
|
399
|
+
}
|
|
156
400
|
const veResult = await this.manageVirtualEntities(pool);
|
|
157
401
|
if (!veResult.success) {
|
|
158
402
|
logError(' Error managing virtual entities');
|
|
159
403
|
bSuccess = false;
|
|
160
404
|
}
|
|
405
|
+
// LLM-assisted virtual entity field decoration — identify PKs, FKs, and descriptions
|
|
406
|
+
await this.decorateVirtualEntitiesWithLLM(pool, currentUser);
|
|
407
|
+
// Config-driven IS-A relationship setup — set ParentID on child entities
|
|
408
|
+
// Must run AFTER entities exist but BEFORE manageEntityFields() which calls manageParentEntityFields()
|
|
409
|
+
const isaConfigResult = await this.processISARelationshipConfig(pool);
|
|
410
|
+
if (isaConfigResult.updatedCount > 0) {
|
|
411
|
+
logStatus(` > Set ParentID on ${isaConfigResult.updatedCount} IS-A child entit${isaConfigResult.updatedCount === 1 ? 'y' : 'ies'} from config`);
|
|
412
|
+
}
|
|
161
413
|
start = new Date();
|
|
162
414
|
logStatus(' Syncing schema info from database...');
|
|
163
415
|
if (!await this.updateSchemaInfoFromDatabase(pool, excludeSchemas)) {
|
|
@@ -307,6 +559,480 @@ export class ManageMetadataBase {
|
|
|
307
559
|
}
|
|
308
560
|
return { success: true, updatedField: didUpdate, newFieldID: newEntityFieldUUID };
|
|
309
561
|
}
|
|
562
|
+
/**
|
|
563
|
+
* Iterates over all virtual entities and applies LLM-assisted field decoration
|
|
564
|
+
* to identify primary keys, foreign keys, and field descriptions.
|
|
565
|
+
* Only runs if the VirtualEntityFieldDecoration advanced generation feature is enabled.
|
|
566
|
+
* Idempotent: skips entities that already have soft PK/FK annotations.
|
|
567
|
+
*/
|
|
568
|
+
async decorateVirtualEntitiesWithLLM(pool, currentUser) {
|
|
569
|
+
const ag = new AdvancedGeneration();
|
|
570
|
+
if (!ag.featureEnabled('VirtualEntityFieldDecoration')) {
|
|
571
|
+
return; // Feature not enabled, nothing to do
|
|
572
|
+
}
|
|
573
|
+
const md = new Metadata();
|
|
574
|
+
const virtualEntities = md.Entities.filter(e => e.VirtualEntity);
|
|
575
|
+
if (virtualEntities.length === 0) {
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
// Pre-build available entities list once (shared across all virtual entity decorations)
|
|
579
|
+
const availableEntities = md.Entities
|
|
580
|
+
.filter(e => !e.VirtualEntity && e.PrimaryKeys.length > 0)
|
|
581
|
+
.map(e => ({
|
|
582
|
+
Name: e.Name,
|
|
583
|
+
SchemaName: e.SchemaName,
|
|
584
|
+
BaseTable: e.BaseTable,
|
|
585
|
+
PrimaryKeyField: e.PrimaryKeys[0]?.Name || 'ID'
|
|
586
|
+
}));
|
|
587
|
+
logStatus(` Decorating virtual entity fields with LLM (${virtualEntities.length} entities)...`);
|
|
588
|
+
let decoratedCount = 0;
|
|
589
|
+
let skippedCount = 0;
|
|
590
|
+
// Process in batches of up to 5 in parallel for better throughput
|
|
591
|
+
const batchSize = 5;
|
|
592
|
+
for (let i = 0; i < virtualEntities.length; i += batchSize) {
|
|
593
|
+
const batch = virtualEntities.slice(i, i + batchSize);
|
|
594
|
+
const results = await Promise.all(batch.map(entity => this.decorateSingleVirtualEntityWithLLM(pool, entity, ag, currentUser, availableEntities)));
|
|
595
|
+
for (const result of results) {
|
|
596
|
+
if (result.decorated) {
|
|
597
|
+
decoratedCount++;
|
|
598
|
+
}
|
|
599
|
+
else if (result.skipped) {
|
|
600
|
+
skippedCount++;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
if (decoratedCount > 0 || skippedCount > 0) {
|
|
605
|
+
logStatus(` > LLM field decoration: ${decoratedCount} decorated, ${skippedCount} skipped (already annotated)`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Applies LLM-assisted field decoration to a single virtual entity.
|
|
610
|
+
* Parses the view SQL to identify source entities, enriches the LLM prompt with their
|
|
611
|
+
* field metadata (descriptions, categories), then applies PKs, FKs, descriptions, and categories.
|
|
612
|
+
* @returns Whether the entity was decorated, skipped, or encountered an error.
|
|
613
|
+
*/
|
|
614
|
+
async decorateSingleVirtualEntityWithLLM(pool, entity, ag, currentUser, availableEntities) {
|
|
615
|
+
try {
|
|
616
|
+
// Idempotency check: if entity already has soft PK or soft FK annotations, skip
|
|
617
|
+
// unless forceRegenerate option is enabled on this feature
|
|
618
|
+
const feature = ag.getFeature('VirtualEntityFieldDecoration');
|
|
619
|
+
const forceRegenerate = feature?.options?.find(o => o.name === 'forceRegenerate')?.value === true;
|
|
620
|
+
const hasSoftAnnotations = entity.Fields.some(f => f.IsSoftPrimaryKey || f.IsSoftForeignKey);
|
|
621
|
+
if (hasSoftAnnotations && !forceRegenerate) {
|
|
622
|
+
return { decorated: false, skipped: true };
|
|
623
|
+
}
|
|
624
|
+
// Get view definition from SQL Server
|
|
625
|
+
const viewDefSQL = `SELECT OBJECT_DEFINITION(OBJECT_ID('[${entity.SchemaName}].[${entity.BaseView}]')) AS ViewDef`;
|
|
626
|
+
const viewDefResult = await pool.request().query(viewDefSQL);
|
|
627
|
+
const viewDefinition = viewDefResult.recordset[0]?.ViewDef;
|
|
628
|
+
if (!viewDefinition) {
|
|
629
|
+
logStatus(` Could not get view definition for ${entity.SchemaName}.${entity.BaseView} — skipping LLM decoration`);
|
|
630
|
+
return { decorated: false, skipped: false };
|
|
631
|
+
}
|
|
632
|
+
// Parse the view SQL to identify referenced tables, then resolve to entities
|
|
633
|
+
const sourceEntities = this.buildSourceEntityContext(viewDefinition);
|
|
634
|
+
// Build field info for the prompt
|
|
635
|
+
const fields = entity.Fields.map(f => ({
|
|
636
|
+
Name: f.Name,
|
|
637
|
+
Type: f.Type,
|
|
638
|
+
Length: f.Length,
|
|
639
|
+
AllowsNull: f.AllowsNull,
|
|
640
|
+
IsPrimaryKey: f.IsPrimaryKey,
|
|
641
|
+
RelatedEntityName: f.RelatedEntity || null
|
|
642
|
+
}));
|
|
643
|
+
// Call the LLM with enriched source entity context
|
|
644
|
+
const result = await ag.decorateVirtualEntityFields(entity.Name, entity.SchemaName, entity.BaseView, viewDefinition, entity.Description || '', fields, availableEntities, sourceEntities, currentUser);
|
|
645
|
+
if (!result) {
|
|
646
|
+
return { decorated: false, skipped: false };
|
|
647
|
+
}
|
|
648
|
+
// Apply results to EntityField records
|
|
649
|
+
const schema = mj_core_schema();
|
|
650
|
+
let anyUpdated = false;
|
|
651
|
+
// Apply primary keys
|
|
652
|
+
anyUpdated = await this.applyLLMPrimaryKeys(pool, entity, result.primaryKeys, schema) || anyUpdated;
|
|
653
|
+
// Apply foreign keys
|
|
654
|
+
anyUpdated = await this.applyLLMForeignKeys(pool, entity, result.foreignKeys, schema) || anyUpdated;
|
|
655
|
+
// Apply field descriptions
|
|
656
|
+
anyUpdated = await this.applyLLMFieldDescriptions(pool, entity, result.fieldDescriptions, schema) || anyUpdated;
|
|
657
|
+
// Apply categories using the shared methods (same stability rules as regular entities)
|
|
658
|
+
anyUpdated = await this.applyVEFieldCategories(pool, entity, result) || anyUpdated;
|
|
659
|
+
if (anyUpdated) {
|
|
660
|
+
const sqlUpdate = `UPDATE [${schema}].Entity SET [${EntityInfo.UpdatedAtFieldName}]=GETUTCDATE() WHERE ID='${entity.ID}'`;
|
|
661
|
+
await this.LogSQLAndExecute(pool, sqlUpdate, `Update entity timestamp for ${entity.Name} after LLM decoration`);
|
|
662
|
+
}
|
|
663
|
+
return { decorated: anyUpdated, skipped: false };
|
|
664
|
+
}
|
|
665
|
+
catch (e) {
|
|
666
|
+
logError(` Error decorating virtual entity ${entity.Name} with LLM: ${e}`);
|
|
667
|
+
return { decorated: false, skipped: false };
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Parses a view definition SQL and resolves referenced tables to MJ entities.
|
|
672
|
+
* Returns enriched source entity context (all fields with descriptions and categories)
|
|
673
|
+
* for the LLM to use when decorating virtual entity fields.
|
|
674
|
+
*/
|
|
675
|
+
buildSourceEntityContext(viewDefinition) {
|
|
676
|
+
const parseResult = SQLParser.Parse(viewDefinition);
|
|
677
|
+
const md = new Metadata();
|
|
678
|
+
const sourceEntities = [];
|
|
679
|
+
const seen = new Set();
|
|
680
|
+
for (const tableRef of parseResult.Tables) {
|
|
681
|
+
// Match against MJ entities by BaseTable/BaseView + SchemaName
|
|
682
|
+
const matchingEntity = md.Entities.find(e => (e.BaseTable.toLowerCase() === tableRef.TableName.toLowerCase() ||
|
|
683
|
+
e.BaseView.toLowerCase() === tableRef.TableName.toLowerCase()) &&
|
|
684
|
+
e.SchemaName.toLowerCase() === tableRef.SchemaName.toLowerCase());
|
|
685
|
+
if (matchingEntity && !seen.has(matchingEntity.ID)) {
|
|
686
|
+
seen.add(matchingEntity.ID);
|
|
687
|
+
sourceEntities.push({
|
|
688
|
+
Name: matchingEntity.Name,
|
|
689
|
+
Description: matchingEntity.Description || '',
|
|
690
|
+
Fields: matchingEntity.Fields.map(f => ({
|
|
691
|
+
Name: f.Name,
|
|
692
|
+
Type: f.Type,
|
|
693
|
+
Description: f.Description || '',
|
|
694
|
+
Category: f.Category || null,
|
|
695
|
+
IsPrimaryKey: f.IsPrimaryKey,
|
|
696
|
+
IsForeignKey: !!(f.RelatedEntityID)
|
|
697
|
+
}))
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return sourceEntities;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Applies category assignments from VE decoration results using the shared category methods.
|
|
705
|
+
* Loads field records from DB (needs ID, Name, Category, AutoUpdateCategory, AutoUpdateDisplayName)
|
|
706
|
+
* then delegates to the shared methods.
|
|
707
|
+
*/
|
|
708
|
+
async applyVEFieldCategories(pool, entity, result) {
|
|
709
|
+
// Check if the LLM returned any category data
|
|
710
|
+
const hasCategories = result.fieldDescriptions?.some(fd => fd.category);
|
|
711
|
+
if (!hasCategories) {
|
|
712
|
+
return false;
|
|
713
|
+
}
|
|
714
|
+
// Load VE EntityField rows from DB (we need the ID and auto-update flags)
|
|
715
|
+
const schema = mj_core_schema();
|
|
716
|
+
const fieldsSQL = `
|
|
717
|
+
SELECT ID, Name, Category, AutoUpdateCategory, AutoUpdateDisplayName
|
|
718
|
+
FROM [${schema}].EntityField
|
|
719
|
+
WHERE EntityID = '${entity.ID}'
|
|
720
|
+
`;
|
|
721
|
+
const fieldsResult = await pool.request().query(fieldsSQL);
|
|
722
|
+
const dbFields = fieldsResult.recordset;
|
|
723
|
+
if (dbFields.length === 0)
|
|
724
|
+
return false;
|
|
725
|
+
// Convert VE decoration field descriptions into the format expected by applyFieldCategories
|
|
726
|
+
const fieldCategories = result.fieldDescriptions
|
|
727
|
+
.filter(fd => fd.category)
|
|
728
|
+
.map(fd => ({
|
|
729
|
+
fieldName: fd.fieldName,
|
|
730
|
+
category: fd.category,
|
|
731
|
+
displayName: fd.displayName || undefined,
|
|
732
|
+
extendedType: fd.extendedType,
|
|
733
|
+
codeType: fd.codeType
|
|
734
|
+
}));
|
|
735
|
+
if (fieldCategories.length === 0)
|
|
736
|
+
return false;
|
|
737
|
+
const existingCategories = this.buildExistingCategorySet(dbFields);
|
|
738
|
+
await this.applyFieldCategories(pool, entity.ID, dbFields, fieldCategories, existingCategories);
|
|
739
|
+
// Apply entity icon if provided
|
|
740
|
+
if (result.entityIcon) {
|
|
741
|
+
await this.applyEntityIcon(pool, entity.ID, result.entityIcon);
|
|
742
|
+
}
|
|
743
|
+
// Apply category info settings if provided
|
|
744
|
+
if (result.categoryInfo && Object.keys(result.categoryInfo).length > 0) {
|
|
745
|
+
await this.applyCategoryInfoSettings(pool, entity.ID, result.categoryInfo);
|
|
746
|
+
}
|
|
747
|
+
logStatus(` Applied categories for VE ${entity.Name} (${fieldCategories.length} fields)`);
|
|
748
|
+
return true;
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Applies LLM-identified primary keys to entity fields.
|
|
752
|
+
* Sets IsPrimaryKey=1 and IsSoftPrimaryKey=1 for identified fields.
|
|
753
|
+
* First clears any default PK that was set by field-sync (field #1 fallback).
|
|
754
|
+
* All SQL updates are batched into a single execution for performance.
|
|
755
|
+
*/
|
|
756
|
+
async applyLLMPrimaryKeys(pool, entity, primaryKeys, schema) {
|
|
757
|
+
if (!primaryKeys || primaryKeys.length === 0) {
|
|
758
|
+
return false;
|
|
759
|
+
}
|
|
760
|
+
// Validate that all identified PK fields exist on the entity
|
|
761
|
+
const validPKs = primaryKeys.filter(pk => entity.Fields.some(f => f.Name.toLowerCase() === pk.toLowerCase()));
|
|
762
|
+
if (validPKs.length === 0) {
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
// Build batched SQL: clear default PK + set all LLM-identified PKs
|
|
766
|
+
const sqlStatements = [];
|
|
767
|
+
// Clear existing default PK (field #1 fallback) before applying LLM-identified PKs
|
|
768
|
+
sqlStatements.push(`UPDATE [${schema}].[EntityField]
|
|
769
|
+
SET IsPrimaryKey=0, IsUnique=0
|
|
770
|
+
WHERE EntityID='${entity.ID}' AND IsPrimaryKey=1 AND IsSoftPrimaryKey=0`);
|
|
771
|
+
// Set LLM-identified PKs
|
|
772
|
+
for (const pk of validPKs) {
|
|
773
|
+
sqlStatements.push(`UPDATE [${schema}].[EntityField]
|
|
774
|
+
SET IsPrimaryKey=1, IsUnique=1, IsSoftPrimaryKey=1
|
|
775
|
+
WHERE EntityID='${entity.ID}' AND Name='${pk}'`);
|
|
776
|
+
logStatus(` ✓ Set PK for ${entity.Name}.${pk} (LLM-identified)`);
|
|
777
|
+
}
|
|
778
|
+
await this.LogSQLAndExecute(pool, sqlStatements.join('\n'), `Set LLM-identified PKs for ${entity.Name}: ${validPKs.join(', ')}`);
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Applies LLM-identified foreign keys to entity fields.
|
|
783
|
+
* Sets RelatedEntityID, RelatedEntityFieldName, and IsSoftForeignKey=1.
|
|
784
|
+
* Only applies high and medium confidence FKs.
|
|
785
|
+
* All SQL updates are batched into a single execution for performance.
|
|
786
|
+
*/
|
|
787
|
+
async applyLLMForeignKeys(pool, entity, foreignKeys, schema) {
|
|
788
|
+
if (!foreignKeys || foreignKeys.length === 0) {
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
const md = new Metadata();
|
|
792
|
+
const sqlStatements = [];
|
|
793
|
+
for (const fk of foreignKeys) {
|
|
794
|
+
// Only apply high/medium confidence
|
|
795
|
+
if (fk.confidence !== 'high' && fk.confidence !== 'medium') {
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
// Validate that the field exists on this entity
|
|
799
|
+
const field = entity.Fields.find(f => f.Name.toLowerCase() === fk.fieldName.toLowerCase());
|
|
800
|
+
if (!field) {
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
// Skip if field already has a FK set (config-defined takes precedence)
|
|
804
|
+
if (field.RelatedEntityID) {
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
// Look up the related entity by name
|
|
808
|
+
const relatedEntity = md.EntityByName(fk.relatedEntityName);
|
|
809
|
+
if (!relatedEntity) {
|
|
810
|
+
logStatus(` ⚠️ LLM FK: related entity '${fk.relatedEntityName}' not found for ${entity.Name}.${fk.fieldName}`);
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
sqlStatements.push(`UPDATE [${schema}].[EntityField]
|
|
814
|
+
SET RelatedEntityID='${relatedEntity.ID}',
|
|
815
|
+
RelatedEntityFieldName='${fk.relatedFieldName}',
|
|
816
|
+
IsSoftForeignKey=1
|
|
817
|
+
WHERE EntityID='${entity.ID}' AND Name='${field.Name}'`);
|
|
818
|
+
logStatus(` ✓ Set FK for ${entity.Name}.${field.Name} → ${fk.relatedEntityName}.${fk.relatedFieldName} (${fk.confidence}, LLM)`);
|
|
819
|
+
}
|
|
820
|
+
if (sqlStatements.length === 0) {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
await this.LogSQLAndExecute(pool, sqlStatements.join('\n'), `Set LLM-identified FKs for ${entity.Name}`);
|
|
824
|
+
return true;
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Applies LLM-generated field descriptions to entity fields that lack descriptions.
|
|
828
|
+
* All SQL updates are batched into a single execution for performance.
|
|
829
|
+
*/
|
|
830
|
+
async applyLLMFieldDescriptions(pool, entity, fieldDescriptions, schema) {
|
|
831
|
+
if (!fieldDescriptions || fieldDescriptions.length === 0) {
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
const sqlStatements = [];
|
|
835
|
+
for (const fd of fieldDescriptions) {
|
|
836
|
+
const field = entity.Fields.find(f => f.Name.toLowerCase() === fd.fieldName.toLowerCase());
|
|
837
|
+
if (!field) {
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
// Only apply if field doesn't already have a description
|
|
841
|
+
if (field.Description && field.Description.trim().length > 0) {
|
|
842
|
+
continue;
|
|
843
|
+
}
|
|
844
|
+
const escapedDescription = fd.description.replace(/'/g, "''");
|
|
845
|
+
let setClauses = `Description='${escapedDescription}'`;
|
|
846
|
+
// Apply extended type if provided and valid
|
|
847
|
+
if (fd.extendedType) {
|
|
848
|
+
const validExtendedType = this.validateExtendedType(fd.extendedType);
|
|
849
|
+
if (validExtendedType) {
|
|
850
|
+
setClauses += `, ExtendedType='${validExtendedType}'`;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
sqlStatements.push(`UPDATE [${schema}].[EntityField]
|
|
854
|
+
SET ${setClauses}
|
|
855
|
+
WHERE EntityID='${entity.ID}' AND Name='${field.Name}'`);
|
|
856
|
+
}
|
|
857
|
+
if (sqlStatements.length === 0) {
|
|
858
|
+
return false;
|
|
859
|
+
}
|
|
860
|
+
await this.LogSQLAndExecute(pool, sqlStatements.join('\n'), `Set LLM-generated descriptions for ${entity.Name} (${sqlStatements.length} fields)`);
|
|
861
|
+
return true;
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Valid values for EntityField.ExtendedType, plus common LLM aliases mapped to valid values.
|
|
865
|
+
*/
|
|
866
|
+
static { this.VALID_EXTENDED_TYPES = new Set([
|
|
867
|
+
'Code', 'Email', 'FaceTime', 'Geo', 'MSTeams', 'Other', 'SIP', 'SMS', 'Skype', 'Tel', 'URL', 'WhatsApp', 'ZoomMtg'
|
|
868
|
+
]); }
|
|
869
|
+
static { this.EXTENDED_TYPE_ALIASES = {
|
|
870
|
+
'phone': 'Tel',
|
|
871
|
+
'telephone': 'Tel',
|
|
872
|
+
'website': 'URL',
|
|
873
|
+
'link': 'URL',
|
|
874
|
+
'hyperlink': 'URL',
|
|
875
|
+
'mail': 'Email',
|
|
876
|
+
'e-mail': 'Email',
|
|
877
|
+
'text': 'SMS',
|
|
878
|
+
'location': 'Geo',
|
|
879
|
+
'address': 'Geo',
|
|
880
|
+
'teams': 'MSTeams',
|
|
881
|
+
'facetime': 'FaceTime',
|
|
882
|
+
'zoom': 'ZoomMtg',
|
|
883
|
+
'whatsapp': 'WhatsApp',
|
|
884
|
+
'skype': 'Skype',
|
|
885
|
+
}; }
|
|
886
|
+
/**
|
|
887
|
+
* Validates an LLM-suggested ExtendedType against the allowed values in EntityField.
|
|
888
|
+
* Returns the valid value (case-corrected) or null if invalid.
|
|
889
|
+
*/
|
|
890
|
+
validateExtendedType(suggested) {
|
|
891
|
+
// Direct match (case-insensitive)
|
|
892
|
+
for (const valid of ManageMetadataBase.VALID_EXTENDED_TYPES) {
|
|
893
|
+
if (valid.toLowerCase() === suggested.toLowerCase()) {
|
|
894
|
+
return valid;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
// Check aliases
|
|
898
|
+
const alias = ManageMetadataBase.EXTENDED_TYPE_ALIASES[suggested.toLowerCase()];
|
|
899
|
+
if (alias) {
|
|
900
|
+
return alias;
|
|
901
|
+
}
|
|
902
|
+
return null;
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Manages virtual EntityField records for IS-A parent entity fields.
|
|
906
|
+
* For each entity with ParentID set (IS-A child), creates/updates virtual field records
|
|
907
|
+
* that mirror the parent entity's base table fields (excluding PKs, timestamps, and virtual fields).
|
|
908
|
+
* Runs collision detection to prevent child table columns from shadowing parent fields.
|
|
909
|
+
*/
|
|
910
|
+
async manageParentEntityFields(pool) {
|
|
911
|
+
let bSuccess = true;
|
|
912
|
+
let anyUpdates = false;
|
|
913
|
+
const md = new Metadata();
|
|
914
|
+
const childEntities = md.Entities.filter(e => e.IsChildType);
|
|
915
|
+
if (childEntities.length === 0) {
|
|
916
|
+
return { success: true, anyUpdates: false };
|
|
917
|
+
}
|
|
918
|
+
logStatus(` Processing IS-A parent fields for ${childEntities.length} child entit${childEntities.length === 1 ? 'y' : 'ies'}...`);
|
|
919
|
+
for (const childEntity of childEntities) {
|
|
920
|
+
try {
|
|
921
|
+
const { success, updated } = await this.manageSingleEntityParentFields(pool, childEntity);
|
|
922
|
+
anyUpdates = anyUpdates || updated;
|
|
923
|
+
if (!success) {
|
|
924
|
+
logError(` Error managing IS-A parent fields for ${childEntity.Name}`);
|
|
925
|
+
bSuccess = false;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
catch (e) {
|
|
929
|
+
logError(` Exception managing IS-A parent fields for ${childEntity.Name}: ${e}`);
|
|
930
|
+
bSuccess = false;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
return { success: bSuccess, anyUpdates };
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Creates/updates virtual EntityField records for a single child entity's parent fields.
|
|
937
|
+
* Detects field name collisions between child's own base table columns and parent fields.
|
|
938
|
+
*/
|
|
939
|
+
async manageSingleEntityParentFields(pool, childEntity) {
|
|
940
|
+
let bUpdated = false;
|
|
941
|
+
// Get all parent fields: non-PK, non-__mj_, non-virtual from each parent in chain
|
|
942
|
+
const parentFields = childEntity.AllParentFields;
|
|
943
|
+
if (parentFields.length === 0) {
|
|
944
|
+
return { success: true, updated: false };
|
|
945
|
+
}
|
|
946
|
+
// Get child's own (non-virtual) field names for collision detection
|
|
947
|
+
const childOwnFieldNames = new Set(childEntity.Fields.filter(f => !f.IsVirtual).map(f => f.Name.toLowerCase()));
|
|
948
|
+
for (const parentField of parentFields) {
|
|
949
|
+
// Collision detection: child's own base table column has same name as parent field.
|
|
950
|
+
// This uses in-memory metadata which filters to non-virtual (base table) fields only.
|
|
951
|
+
if (childOwnFieldNames.has(parentField.Name.toLowerCase())) {
|
|
952
|
+
logError(` FIELD COLLISION: Entity '${childEntity.Name}' has its own column '${parentField.Name}' ` +
|
|
953
|
+
`that conflicts with IS-A parent field '${parentField.Name}' from '${parentField.Entity}'. ` +
|
|
954
|
+
`Rename the child column to resolve this collision. Skipping IS-A field sync for this entity.`);
|
|
955
|
+
return { success: false, updated: false };
|
|
956
|
+
}
|
|
957
|
+
// Check the DATABASE for existing field record — in-memory metadata may be stale
|
|
958
|
+
// (e.g. createNewEntityFieldsFromSchema may have already added this field from the view)
|
|
959
|
+
const existsResult = await pool.request()
|
|
960
|
+
.input('EntityID', childEntity.ID)
|
|
961
|
+
.input('FieldName', parentField.Name)
|
|
962
|
+
.query(`SELECT ID, IsVirtual, Type, Length, Precision, Scale, AllowsNull, AllowUpdateAPI
|
|
963
|
+
FROM [${mj_core_schema()}].EntityField
|
|
964
|
+
WHERE EntityID = @EntityID AND Name = @FieldName`);
|
|
965
|
+
if (existsResult.recordset.length > 0) {
|
|
966
|
+
// Field already exists — update it to ensure it's marked as a virtual IS-A field
|
|
967
|
+
const existingRow = existsResult.recordset[0];
|
|
968
|
+
const needsUpdate = !existingRow.IsVirtual ||
|
|
969
|
+
existingRow.Type?.trim().toLowerCase() !== parentField.Type.trim().toLowerCase() ||
|
|
970
|
+
existingRow.Length !== parentField.Length ||
|
|
971
|
+
existingRow.Precision !== parentField.Precision ||
|
|
972
|
+
existingRow.Scale !== parentField.Scale ||
|
|
973
|
+
existingRow.AllowsNull !== parentField.AllowsNull ||
|
|
974
|
+
!existingRow.AllowUpdateAPI;
|
|
975
|
+
if (needsUpdate) {
|
|
976
|
+
const sqlUpdate = `UPDATE [${mj_core_schema()}].EntityField
|
|
977
|
+
SET IsVirtual=1,
|
|
978
|
+
Type='${parentField.Type}',
|
|
979
|
+
Length=${parentField.Length},
|
|
980
|
+
Precision=${parentField.Precision},
|
|
981
|
+
Scale=${parentField.Scale},
|
|
982
|
+
AllowsNull=${parentField.AllowsNull ? 1 : 0},
|
|
983
|
+
AllowUpdateAPI=1
|
|
984
|
+
WHERE ID='${existingRow.ID}'`;
|
|
985
|
+
await this.LogSQLAndExecute(pool, sqlUpdate, `Update IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
|
|
986
|
+
bUpdated = true;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
else {
|
|
990
|
+
// Create new virtual field record for this parent field
|
|
991
|
+
const newFieldID = this.createNewUUID();
|
|
992
|
+
// Use high sequence — will be reordered by updateExistingEntityFieldsFromSchema
|
|
993
|
+
const sequence = 100000 + parentFields.indexOf(parentField);
|
|
994
|
+
const sqlInsert = `INSERT INTO [${mj_core_schema()}].EntityField (
|
|
995
|
+
ID, EntityID, Name, Type, AllowsNull,
|
|
996
|
+
Length, Precision, Scale,
|
|
997
|
+
Sequence, IsVirtual, AllowUpdateAPI,
|
|
998
|
+
IsPrimaryKey, IsUnique)
|
|
999
|
+
VALUES (
|
|
1000
|
+
'${newFieldID}', '${childEntity.ID}', '${parentField.Name}',
|
|
1001
|
+
'${parentField.Type}', ${parentField.AllowsNull ? 1 : 0},
|
|
1002
|
+
${parentField.Length}, ${parentField.Precision}, ${parentField.Scale},
|
|
1003
|
+
${sequence}, 1, 1, 0, 0)`;
|
|
1004
|
+
await this.LogSQLAndExecute(pool, sqlInsert, `Create IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
|
|
1005
|
+
bUpdated = true;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
// Remove stale IS-A parent virtual fields no longer in the parent chain.
|
|
1009
|
+
// IS-A parent fields are identified by IsVirtual=true AND AllowUpdateAPI=true.
|
|
1010
|
+
const currentParentFieldNames = new Set(parentFields.map(f => f.Name.toLowerCase()));
|
|
1011
|
+
const staleFields = childEntity.Fields.filter(f => f.IsVirtual && f.AllowUpdateAPI &&
|
|
1012
|
+
!f.IsPrimaryKey && !f.Name.startsWith('__mj_') &&
|
|
1013
|
+
!currentParentFieldNames.has(f.Name.toLowerCase()));
|
|
1014
|
+
for (const staleField of staleFields) {
|
|
1015
|
+
const sqlDelete = `DELETE FROM [${mj_core_schema()}].EntityField WHERE ID='${staleField.ID}'`;
|
|
1016
|
+
await this.LogSQLAndExecute(pool, sqlDelete, `Remove stale IS-A parent field ${staleField.Name} from ${childEntity.Name}`);
|
|
1017
|
+
bUpdated = true;
|
|
1018
|
+
}
|
|
1019
|
+
if (bUpdated) {
|
|
1020
|
+
const sqlUpdate = `UPDATE [${mj_core_schema()}].Entity SET [${EntityInfo.UpdatedAtFieldName}]=GETUTCDATE() WHERE ID='${childEntity.ID}'`;
|
|
1021
|
+
await this.LogSQLAndExecute(pool, sqlUpdate, `Update entity timestamp for ${childEntity.Name} after IS-A field sync`);
|
|
1022
|
+
}
|
|
1023
|
+
return { success: true, updated: bUpdated };
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* Checks if an existing virtual parent field record needs to be updated to match the parent field.
|
|
1027
|
+
*/
|
|
1028
|
+
parentFieldNeedsUpdate(existing, parentField) {
|
|
1029
|
+
return existing.Type.trim().toLowerCase() !== parentField.Type.trim().toLowerCase() ||
|
|
1030
|
+
existing.Length !== parentField.Length ||
|
|
1031
|
+
existing.Precision !== parentField.Precision ||
|
|
1032
|
+
existing.Scale !== parentField.Scale ||
|
|
1033
|
+
existing.AllowsNull !== parentField.AllowsNull ||
|
|
1034
|
+
!existing.AllowUpdateAPI;
|
|
1035
|
+
}
|
|
310
1036
|
/**
|
|
311
1037
|
* This method creates and updates relationships in the metadata based on foreign key relationships in the database.
|
|
312
1038
|
* @param pool
|
|
@@ -537,6 +1263,24 @@ export class ManageMetadataBase {
|
|
|
537
1263
|
logError('Error applying soft PK/FK configuration');
|
|
538
1264
|
}
|
|
539
1265
|
logStatus(` Applied soft PK/FK configuration in ${(new Date().getTime() - stepConfigStartTime.getTime()) / 1000} seconds`);
|
|
1266
|
+
// CRITICAL: Refresh metadata to pick up soft PK/FK flags
|
|
1267
|
+
// Without this, downstream SQL and TypeScript generation will fail
|
|
1268
|
+
// because entity.Fields and entity.PrimaryKeys won't reflect the updated flags
|
|
1269
|
+
if (configInfo.additionalSchemaInfo) {
|
|
1270
|
+
logStatus(' Refreshing metadata after applying soft PK/FK configuration...');
|
|
1271
|
+
const md = new Metadata();
|
|
1272
|
+
await md.Refresh();
|
|
1273
|
+
logStatus(' Metadata refresh complete');
|
|
1274
|
+
}
|
|
1275
|
+
// IS-A parent field sync: create/update virtual EntityField records for parent chain fields
|
|
1276
|
+
// Must run AFTER metadata refresh so it sees current soft PK/FK flags
|
|
1277
|
+
const stepISAStartTime = new Date();
|
|
1278
|
+
const isaResult = await this.manageParentEntityFields(pool);
|
|
1279
|
+
if (!isaResult.success) {
|
|
1280
|
+
logError('Error managing IS-A parent entity fields');
|
|
1281
|
+
bSuccess = false;
|
|
1282
|
+
}
|
|
1283
|
+
logStatus(` Managed IS-A parent entity fields in ${(new Date().getTime() - stepISAStartTime.getTime()) / 1000} seconds`);
|
|
540
1284
|
const step4StartTime = new Date();
|
|
541
1285
|
if (!await this.setDefaultColumnWidthWhereNeeded(pool, excludeSchemas)) {
|
|
542
1286
|
logError('Error setting default column width where needed');
|
|
@@ -634,51 +1378,61 @@ export class ManageMetadataBase {
|
|
|
634
1378
|
let totalPKs = 0;
|
|
635
1379
|
let totalFKs = 0;
|
|
636
1380
|
const schema = mj_core_schema();
|
|
637
|
-
|
|
1381
|
+
// Config supports two formats:
|
|
1382
|
+
// 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
|
|
1383
|
+
// 2. Flat tables array (legacy format): { "tables": [{ "SchemaName": "dbo", "TableName": "Orders", ... }] }
|
|
1384
|
+
// Both use PascalCase property names.
|
|
1385
|
+
const tables = this.extractTablesFromConfig(config);
|
|
1386
|
+
for (const table of tables) {
|
|
1387
|
+
const tableSchema = table.SchemaName;
|
|
1388
|
+
const tableName = table.TableName;
|
|
638
1389
|
// Look up entity ID (SELECT query - no need to log to migration file)
|
|
639
|
-
const entityLookupSQL = `SELECT ID FROM [${schema}].[Entity] WHERE SchemaName = '${
|
|
1390
|
+
const entityLookupSQL = `SELECT ID FROM [${schema}].[Entity] WHERE SchemaName = '${tableSchema}' AND BaseTable = '${tableName}'`;
|
|
640
1391
|
const entityResult = await pool.request().query(entityLookupSQL);
|
|
641
1392
|
if (entityResult.recordset.length === 0) {
|
|
642
|
-
logStatus(` ⚠️ Entity not found for ${
|
|
1393
|
+
logStatus(` ⚠️ Entity not found for ${tableSchema}.${tableName} - skipping`);
|
|
643
1394
|
continue;
|
|
644
1395
|
}
|
|
645
1396
|
const entityId = entityResult.recordset[0].ID;
|
|
646
1397
|
// Process primary keys - set BOTH IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1
|
|
647
1398
|
// IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync
|
|
648
|
-
|
|
649
|
-
|
|
1399
|
+
const primaryKeys = table.PrimaryKey || [];
|
|
1400
|
+
if (primaryKeys.length > 0) {
|
|
1401
|
+
for (const pk of primaryKeys) {
|
|
650
1402
|
const sSQL = `UPDATE [${schema}].[EntityField]
|
|
651
1403
|
SET ${EntityInfo.UpdatedAtFieldName}=GETUTCDATE(),
|
|
652
1404
|
[IsPrimaryKey] = 1,
|
|
653
1405
|
[IsSoftPrimaryKey] = 1
|
|
654
|
-
WHERE [EntityID] = '${entityId}' AND [Name] = '${pk.
|
|
655
|
-
const result = await this.LogSQLAndExecute(pool, sSQL, `Set soft PK for ${
|
|
1406
|
+
WHERE [EntityID] = '${entityId}' AND [Name] = '${pk.FieldName}'`;
|
|
1407
|
+
const result = await this.LogSQLAndExecute(pool, sSQL, `Set soft PK for ${tableSchema}.${tableName}.${pk.FieldName}`);
|
|
656
1408
|
if (result !== null) {
|
|
657
|
-
logStatus(` ✓ Set IsPrimaryKey=1, IsSoftPrimaryKey=1 for ${
|
|
1409
|
+
logStatus(` ✓ Set IsPrimaryKey=1, IsSoftPrimaryKey=1 for ${tableName}.${pk.FieldName}`);
|
|
658
1410
|
totalPKs++;
|
|
659
1411
|
}
|
|
660
1412
|
}
|
|
661
1413
|
}
|
|
662
1414
|
// Process foreign keys - set RelatedEntityID, RelatedEntityFieldName, and IsSoftForeignKey = 1
|
|
663
|
-
|
|
664
|
-
|
|
1415
|
+
const foreignKeys = table.ForeignKeys || [];
|
|
1416
|
+
if (foreignKeys.length > 0) {
|
|
1417
|
+
for (const fk of foreignKeys) {
|
|
1418
|
+
const fkSchema = fk.SchemaName || tableSchema;
|
|
665
1419
|
// Look up related entity ID (SELECT query - no need to log to migration file)
|
|
666
|
-
const relatedLookupSQL = `SELECT ID FROM [${schema}].[Entity] WHERE SchemaName = '${
|
|
1420
|
+
const relatedLookupSQL = `SELECT ID FROM [${schema}].[Entity] WHERE SchemaName = '${fkSchema}' AND BaseTable = '${fk.RelatedTable}'`;
|
|
667
1421
|
const relatedEntityResult = await pool.request().query(relatedLookupSQL);
|
|
668
1422
|
if (relatedEntityResult.recordset.length === 0) {
|
|
669
|
-
logStatus(` ⚠️ Related entity not found for ${
|
|
1423
|
+
logStatus(` ⚠️ Related entity not found for ${fkSchema}.${fk.RelatedTable} - skipping FK ${fk.FieldName}`);
|
|
670
1424
|
continue;
|
|
671
1425
|
}
|
|
672
1426
|
const relatedEntityId = relatedEntityResult.recordset[0].ID;
|
|
673
1427
|
const sSQL = `UPDATE [${schema}].[EntityField]
|
|
674
1428
|
SET ${EntityInfo.UpdatedAtFieldName}=GETUTCDATE(),
|
|
675
1429
|
[RelatedEntityID] = '${relatedEntityId}',
|
|
676
|
-
[RelatedEntityFieldName] = '${fk.
|
|
1430
|
+
[RelatedEntityFieldName] = '${fk.RelatedField}',
|
|
677
1431
|
[IsSoftForeignKey] = 1
|
|
678
|
-
WHERE [EntityID] = '${entityId}' AND [Name] = '${fk.
|
|
679
|
-
const result = await this.LogSQLAndExecute(pool, sSQL, `Set soft FK for ${
|
|
1432
|
+
WHERE [EntityID] = '${entityId}' AND [Name] = '${fk.FieldName}'`;
|
|
1433
|
+
const result = await this.LogSQLAndExecute(pool, sSQL, `Set soft FK for ${tableSchema}.${tableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
|
|
680
1434
|
if (result !== null) {
|
|
681
|
-
logStatus(` ✓ Set soft FK for ${
|
|
1435
|
+
logStatus(` ✓ Set soft FK for ${tableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
|
|
682
1436
|
totalFKs++;
|
|
683
1437
|
}
|
|
684
1438
|
}
|
|
@@ -1839,7 +2593,7 @@ NumberedRows AS (
|
|
|
1839
2593
|
}
|
|
1840
2594
|
else {
|
|
1841
2595
|
// this is an error condition, we should have an application for this schema, if we don't, log an error, non fatal, but should be logged
|
|
1842
|
-
LogError(` >>>> ERROR: Unable to add new entity ${newEntityName} to an application because an Application record
|
|
2596
|
+
LogError(` >>>> ERROR: Unable to add new entity ${newEntityName} to an application because no Application has SchemaAutoAddNewEntities='${newEntity.SchemaName}'. To fix this, update an existing Application record or create a new one with SchemaAutoAddNewEntities='${newEntity.SchemaName}'.`);
|
|
1843
2597
|
}
|
|
1844
2598
|
// next up, we need to check if we're configured to add permissions for new entities, and if so, add them
|
|
1845
2599
|
if (configInfo.newEntityDefaults.PermissionDefaults && configInfo.newEntityDefaults.PermissionDefaults.AutoAddPermissionsForNewEntities) {
|
|
@@ -1936,6 +2690,63 @@ NumberedRows AS (
|
|
|
1936
2690
|
return apps.map((a) => a.ID);
|
|
1937
2691
|
}
|
|
1938
2692
|
}
|
|
2693
|
+
/**
|
|
2694
|
+
* Adds a newly created entity to the application(s) that match its schema name.
|
|
2695
|
+
* If no application exists for the schema and config allows it, creates one.
|
|
2696
|
+
* Shared by both table-backed entity creation and virtual entity creation.
|
|
2697
|
+
*/
|
|
2698
|
+
async addEntityToApplicationForSchema(pool, entityId, entityName, schemaName, currentUser) {
|
|
2699
|
+
let apps = await this.getApplicationIDForSchema(pool, schemaName);
|
|
2700
|
+
// If no app exists and config says to create one for new schemas, create it
|
|
2701
|
+
if ((!apps || apps.length === 0) && configInfo.newSchemaDefaults.CreateNewApplicationWithSchemaName) {
|
|
2702
|
+
const appUUID = this.createNewUUID();
|
|
2703
|
+
const newAppID = await this.createNewApplication(pool, appUUID, schemaName, schemaName, currentUser);
|
|
2704
|
+
if (newAppID) {
|
|
2705
|
+
apps = [newAppID];
|
|
2706
|
+
const md = new Metadata();
|
|
2707
|
+
await md.Refresh();
|
|
2708
|
+
}
|
|
2709
|
+
else {
|
|
2710
|
+
LogError(` >>>> ERROR: Unable to create new application for schema ${schemaName}`);
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
if (apps && apps.length > 0) {
|
|
2714
|
+
if (configInfo.newEntityDefaults.AddToApplicationWithSchemaName) {
|
|
2715
|
+
for (const appUUID of apps) {
|
|
2716
|
+
const sSQLInsert = `INSERT INTO ${mj_core_schema()}.ApplicationEntity
|
|
2717
|
+
(ApplicationID, EntityID, Sequence) VALUES
|
|
2718
|
+
('${appUUID}', '${entityId}', (SELECT ISNULL(MAX(Sequence),0)+1 FROM ${mj_core_schema()}.ApplicationEntity WHERE ApplicationID = '${appUUID}'))`;
|
|
2719
|
+
await this.LogSQLAndExecute(pool, sSQLInsert, `SQL generated to add entity ${entityName} to application ID: '${appUUID}'`);
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
else {
|
|
2724
|
+
LogError(` >>>> WARNING: No application found for schema ${schemaName} to add entity ${entityName}`);
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
/**
|
|
2728
|
+
* Adds default permissions for a newly created entity based on config settings.
|
|
2729
|
+
* Shared by both table-backed entity creation and virtual entity creation.
|
|
2730
|
+
*/
|
|
2731
|
+
async addDefaultPermissionsForEntity(pool, entityId, entityName) {
|
|
2732
|
+
if (!configInfo.newEntityDefaults.PermissionDefaults?.AutoAddPermissionsForNewEntities) {
|
|
2733
|
+
return;
|
|
2734
|
+
}
|
|
2735
|
+
const md = new Metadata();
|
|
2736
|
+
const permissions = configInfo.newEntityDefaults.PermissionDefaults.Permissions;
|
|
2737
|
+
for (const p of permissions) {
|
|
2738
|
+
const RoleID = md.Roles.find(r => r.Name.trim().toLowerCase() === p.RoleName.trim().toLowerCase())?.ID;
|
|
2739
|
+
if (RoleID) {
|
|
2740
|
+
const sSQLInsert = `INSERT INTO ${mj_core_schema()}.EntityPermission
|
|
2741
|
+
(EntityID, RoleID, CanRead, CanCreate, CanUpdate, CanDelete) VALUES
|
|
2742
|
+
('${entityId}', '${RoleID}', ${p.CanRead ? 1 : 0}, ${p.CanCreate ? 1 : 0}, ${p.CanUpdate ? 1 : 0}, ${p.CanDelete ? 1 : 0})`;
|
|
2743
|
+
await this.LogSQLAndExecute(pool, sSQLInsert, `SQL generated to add permission for entity ${entityName} for role ${p.RoleName}`);
|
|
2744
|
+
}
|
|
2745
|
+
else {
|
|
2746
|
+
LogError(` >>>> ERROR: Unable to find Role ID for role ${p.RoleName} to add permissions for entity ${entityName}`);
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
1939
2750
|
createNewEntityInsertSQL(newEntityUUID, newEntityName, newEntity, newEntitySuffix, newEntityDisplayName) {
|
|
1940
2751
|
const newEntityDefaults = configInfo.newEntityDefaults;
|
|
1941
2752
|
const newEntityDescriptionEscaped = newEntity.Description ? `'${newEntity.Description.replace(/'/g, "''")}` : null;
|
|
@@ -2029,7 +2840,8 @@ NumberedRows AS (
|
|
|
2029
2840
|
e.Name,
|
|
2030
2841
|
e.Description,
|
|
2031
2842
|
e.SchemaName,
|
|
2032
|
-
e.BaseTable
|
|
2843
|
+
e.BaseTable,
|
|
2844
|
+
e.ParentID
|
|
2033
2845
|
FROM
|
|
2034
2846
|
[${mj_core_schema()}].vwEntities e
|
|
2035
2847
|
WHERE
|
|
@@ -2062,7 +2874,9 @@ NumberedRows AS (
|
|
|
2062
2874
|
ef.AutoUpdateCategory,
|
|
2063
2875
|
ef.AutoUpdateDisplayName,
|
|
2064
2876
|
ef.EntityIDFieldName,
|
|
2065
|
-
ef.RelatedEntity
|
|
2877
|
+
ef.RelatedEntity,
|
|
2878
|
+
ef.IsVirtual,
|
|
2879
|
+
ef.AllowUpdateAPI
|
|
2066
2880
|
FROM
|
|
2067
2881
|
[${mj_core_schema()}].vwEntityFields ef
|
|
2068
2882
|
WHERE
|
|
@@ -2167,12 +2981,15 @@ NumberedRows AS (
|
|
|
2167
2981
|
// Form Layout Generation
|
|
2168
2982
|
// Only run if at least one field allows auto-update
|
|
2169
2983
|
if (fields.some((f) => f.AutoUpdateCategory)) {
|
|
2984
|
+
// Build IS-A parent chain context if this entity has a parent
|
|
2985
|
+
const parentChainContext = this.buildParentChainContext(entity, fields);
|
|
2170
2986
|
const layoutAnalysis = await ag.generateFormLayout({
|
|
2171
2987
|
Name: entity.Name,
|
|
2172
2988
|
Description: entity.Description,
|
|
2173
2989
|
SchemaName: entity.SchemaName,
|
|
2174
2990
|
Settings: entity.Settings,
|
|
2175
|
-
Fields: fields
|
|
2991
|
+
Fields: fields,
|
|
2992
|
+
...parentChainContext
|
|
2176
2993
|
}, currentUser, isNewEntity);
|
|
2177
2994
|
if (layoutAnalysis) {
|
|
2178
2995
|
await this.applyFormLayout(pool, entity.ID, fields, layoutAnalysis, isNewEntity);
|
|
@@ -2180,6 +2997,67 @@ NumberedRows AS (
|
|
|
2180
2997
|
}
|
|
2181
2998
|
}
|
|
2182
2999
|
}
|
|
3000
|
+
/**
|
|
3001
|
+
* Builds IS-A parent chain context for an entity, computing which parent each
|
|
3002
|
+
* inherited field originates from. Used to provide the LLM with inheritance
|
|
3003
|
+
* awareness during form layout generation.
|
|
3004
|
+
*
|
|
3005
|
+
* Returns an empty object for entities without parents, so it can be safely spread
|
|
3006
|
+
* into the entity object passed to generateFormLayout().
|
|
3007
|
+
*/
|
|
3008
|
+
buildParentChainContext(entity, fields) {
|
|
3009
|
+
if (!entity.ParentID) {
|
|
3010
|
+
return {};
|
|
3011
|
+
}
|
|
3012
|
+
// Walk the IS-A chain using in-memory metadata
|
|
3013
|
+
const md = new Metadata();
|
|
3014
|
+
const allEntities = md.Entities;
|
|
3015
|
+
const parentChain = [];
|
|
3016
|
+
const visited = new Set();
|
|
3017
|
+
let currentParentID = entity.ParentID;
|
|
3018
|
+
while (currentParentID) {
|
|
3019
|
+
if (visited.has(currentParentID))
|
|
3020
|
+
break; // circular reference guard
|
|
3021
|
+
visited.add(currentParentID);
|
|
3022
|
+
const parentEntity = allEntities.find(e => e.ID === currentParentID);
|
|
3023
|
+
if (!parentEntity)
|
|
3024
|
+
break;
|
|
3025
|
+
parentChain.push({ entityID: parentEntity.ID, entityName: parentEntity.Name });
|
|
3026
|
+
currentParentID = parentEntity.ParentID ?? null;
|
|
3027
|
+
}
|
|
3028
|
+
if (parentChain.length === 0) {
|
|
3029
|
+
return {};
|
|
3030
|
+
}
|
|
3031
|
+
// Annotate each field with its source parent (if inherited)
|
|
3032
|
+
// An IS-A inherited field is: IsVirtual=true, AllowUpdateAPI=true, not PK, not __mj_
|
|
3033
|
+
for (const field of fields) {
|
|
3034
|
+
if (field.IsVirtual && field.AllowUpdateAPI && !field.IsPrimaryKey && !field.Name.startsWith('__mj_')) {
|
|
3035
|
+
const sourceParent = this.findFieldSourceParent(field.Name, parentChain, allEntities);
|
|
3036
|
+
if (sourceParent) {
|
|
3037
|
+
field.InheritedFromEntityID = sourceParent.entityID;
|
|
3038
|
+
field.InheritedFromEntityName = sourceParent.entityName;
|
|
3039
|
+
}
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
return { ParentChain: parentChain, IsChildEntity: true };
|
|
3043
|
+
}
|
|
3044
|
+
/**
|
|
3045
|
+
* For an inherited field, walks the parent chain to find which specific parent entity
|
|
3046
|
+
* originally defines this field (by matching non-virtual fields on each parent).
|
|
3047
|
+
*/
|
|
3048
|
+
findFieldSourceParent(fieldName, parentChain, allEntities) {
|
|
3049
|
+
for (const parent of parentChain) {
|
|
3050
|
+
const parentEntity = allEntities.find(e => e.ID === parent.entityID);
|
|
3051
|
+
if (!parentEntity)
|
|
3052
|
+
continue;
|
|
3053
|
+
// Check if this parent has a non-virtual field with this name
|
|
3054
|
+
const hasField = parentEntity.Fields.some(f => f.Name === fieldName && !f.IsVirtual);
|
|
3055
|
+
if (hasField) {
|
|
3056
|
+
return parent;
|
|
3057
|
+
}
|
|
3058
|
+
}
|
|
3059
|
+
return null;
|
|
3060
|
+
}
|
|
2183
3061
|
/**
|
|
2184
3062
|
* Apply smart field identification results to entity fields
|
|
2185
3063
|
*/
|
|
@@ -2239,7 +3117,8 @@ NumberedRows AS (
|
|
|
2239
3117
|
}
|
|
2240
3118
|
}
|
|
2241
3119
|
/**
|
|
2242
|
-
* Apply form layout generation results to set category on entity fields
|
|
3120
|
+
* Apply form layout generation results to set category on entity fields.
|
|
3121
|
+
* Delegates to shared methods for category assignment, icon, and category info persistence.
|
|
2243
3122
|
* @param pool Database connection pool
|
|
2244
3123
|
* @param entityId Entity ID to update
|
|
2245
3124
|
* @param fields Entity fields
|
|
@@ -2247,17 +3126,47 @@ NumberedRows AS (
|
|
|
2247
3126
|
* @param isNewEntity If true, apply entityImportance; if false, skip it
|
|
2248
3127
|
*/
|
|
2249
3128
|
async applyFormLayout(pool, entityId, fields, result, isNewEntity = false) {
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
3129
|
+
const existingCategories = this.buildExistingCategorySet(fields);
|
|
3130
|
+
await this.applyFieldCategories(pool, entityId, fields, result.fieldCategories, existingCategories);
|
|
3131
|
+
if (result.entityIcon) {
|
|
3132
|
+
await this.applyEntityIcon(pool, entityId, result.entityIcon);
|
|
3133
|
+
}
|
|
3134
|
+
// Resolve categoryInfo from new or legacy format
|
|
3135
|
+
const categoryInfoToStore = result.categoryInfo ||
|
|
3136
|
+
(result.categoryIcons ?
|
|
3137
|
+
Object.fromEntries(Object.entries(result.categoryIcons).map(([cat, icon]) => [cat, { icon, description: '' }])) : null);
|
|
3138
|
+
if (categoryInfoToStore) {
|
|
3139
|
+
await this.applyCategoryInfoSettings(pool, entityId, categoryInfoToStore);
|
|
3140
|
+
}
|
|
3141
|
+
if (isNewEntity && result.entityImportance) {
|
|
3142
|
+
await this.applyEntityImportance(pool, entityId, result.entityImportance);
|
|
3143
|
+
}
|
|
3144
|
+
}
|
|
3145
|
+
// ─────────────────────────────────────────────────────────────────
|
|
3146
|
+
// Shared category / icon / settings persistence methods
|
|
3147
|
+
// Used by both the regular entity pipeline and VE decoration pipeline
|
|
3148
|
+
// ─────────────────────────────────────────────────────────────────
|
|
3149
|
+
/**
|
|
3150
|
+
* Builds a set of existing category names from entity fields.
|
|
3151
|
+
* Used to enforce category stability (prevent renaming).
|
|
3152
|
+
*/
|
|
3153
|
+
buildExistingCategorySet(fields) {
|
|
2253
3154
|
const existingCategories = new Set();
|
|
2254
3155
|
for (const field of fields) {
|
|
2255
3156
|
if (field.Category && field.Category.trim() !== '') {
|
|
2256
3157
|
existingCategories.add(field.Category);
|
|
2257
3158
|
}
|
|
2258
3159
|
}
|
|
2259
|
-
|
|
2260
|
-
|
|
3160
|
+
return existingCategories;
|
|
3161
|
+
}
|
|
3162
|
+
/**
|
|
3163
|
+
* Applies category, display name, extended type, and code type to entity fields.
|
|
3164
|
+
* Enforces stability rules: fields with existing categories cannot move to NEW categories.
|
|
3165
|
+
* All SQL updates are batched into a single execution for performance.
|
|
3166
|
+
*/
|
|
3167
|
+
async applyFieldCategories(pool, entityId, fields, fieldCategories, existingCategories) {
|
|
3168
|
+
const sqlStatements = [];
|
|
3169
|
+
for (const fieldCategory of fieldCategories) {
|
|
2261
3170
|
const field = fields.find(f => f.Name === fieldCategory.fieldName);
|
|
2262
3171
|
if (field && field.AutoUpdateCategory && field.ID) {
|
|
2263
3172
|
// Override category to "System Metadata" for __mj_ fields (system audit fields)
|
|
@@ -2266,158 +3175,126 @@ NumberedRows AS (
|
|
|
2266
3175
|
category = 'System Metadata';
|
|
2267
3176
|
}
|
|
2268
3177
|
// ENFORCEMENT: Prevent category renaming
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
// 2. Moving to another EXISTING category
|
|
2272
|
-
// New categories are only allowed for fields that don't already have a category
|
|
2273
|
-
const fieldHasExistingCategory = field.Category && field.Category.trim() !== '';
|
|
2274
|
-
const categoryIsExisting = existingCategories.has(category);
|
|
2275
|
-
const categoryIsNew = !categoryIsExisting;
|
|
3178
|
+
const fieldHasExistingCategory = field.Category != null && field.Category.trim() !== '';
|
|
3179
|
+
const categoryIsNew = !existingCategories.has(category);
|
|
2276
3180
|
if (fieldHasExistingCategory && categoryIsNew) {
|
|
2277
|
-
// LLM is trying to move an existing field to a brand new category
|
|
2278
|
-
// This could be an attempt to rename a category - reject it
|
|
2279
3181
|
logStatus(` Rejected category change for field '${field.Name}': cannot move from existing category '${field.Category}' to new category '${category}'. Keeping original category.`);
|
|
2280
|
-
category = field.Category;
|
|
3182
|
+
category = field.Category;
|
|
2281
3183
|
}
|
|
2282
|
-
// Build SET clause with all available metadata
|
|
2283
3184
|
const setClauses = [
|
|
2284
3185
|
`Category = '${category.replace(/'/g, "''")}'`,
|
|
2285
3186
|
`GeneratedFormSection = 'Category'`
|
|
2286
3187
|
];
|
|
2287
|
-
// Add DisplayName if provided and field allows auto-update
|
|
2288
3188
|
if (fieldCategory.displayName && field.AutoUpdateDisplayName) {
|
|
2289
3189
|
setClauses.push(`DisplayName = '${fieldCategory.displayName.replace(/'/g, "''")}'`);
|
|
2290
3190
|
}
|
|
2291
|
-
// Add ExtendedType if provided
|
|
2292
3191
|
if (fieldCategory.extendedType !== undefined) {
|
|
2293
|
-
const extendedType = fieldCategory.extendedType === null ? 'NULL' : `'${fieldCategory.extendedType.replace(/'/g, "''")}'`;
|
|
3192
|
+
const extendedType = fieldCategory.extendedType === null ? 'NULL' : `'${String(fieldCategory.extendedType).replace(/'/g, "''")}'`;
|
|
2294
3193
|
setClauses.push(`ExtendedType = ${extendedType}`);
|
|
2295
3194
|
}
|
|
2296
|
-
// Add CodeType if provided
|
|
2297
3195
|
if (fieldCategory.codeType !== undefined) {
|
|
2298
|
-
const codeType = fieldCategory.codeType === null ? 'NULL' : `'${fieldCategory.codeType.replace(/'/g, "''")}'`;
|
|
3196
|
+
const codeType = fieldCategory.codeType === null ? 'NULL' : `'${String(fieldCategory.codeType).replace(/'/g, "''")}'`;
|
|
2299
3197
|
setClauses.push(`CodeType = ${codeType}`);
|
|
2300
3198
|
}
|
|
2301
|
-
|
|
3199
|
+
sqlStatements.push(`UPDATE [${mj_core_schema()}].EntityField
|
|
2302
3200
|
SET ${setClauses.join(',\n ')}
|
|
2303
3201
|
WHERE ID = '${field.ID}'
|
|
2304
|
-
AND AutoUpdateCategory = 1
|
|
2305
|
-
sqlStatements.push(updateSQL);
|
|
3202
|
+
AND AutoUpdateCategory = 1`);
|
|
2306
3203
|
}
|
|
2307
3204
|
else if (!field) {
|
|
2308
|
-
logError(`Form layout
|
|
3205
|
+
logError(`Form layout returned invalid fieldName: '${fieldCategory.fieldName}' not found in entity`);
|
|
2309
3206
|
}
|
|
2310
3207
|
}
|
|
2311
|
-
// Execute all field updates in one batch
|
|
2312
3208
|
if (sqlStatements.length > 0) {
|
|
2313
|
-
|
|
2314
|
-
await this.LogSQLAndExecute(pool, combinedSQL, `Set categories for ${sqlStatements.length} fields`, false);
|
|
2315
|
-
}
|
|
2316
|
-
// Store entity icon if provided and entity doesn't already have one
|
|
2317
|
-
if (result.entityIcon && result.entityIcon.trim().length > 0) {
|
|
2318
|
-
// Check if entity already has an icon
|
|
2319
|
-
const checkEntitySQL = `
|
|
2320
|
-
SELECT Icon FROM [${mj_core_schema()}].Entity
|
|
2321
|
-
WHERE ID = '${entityId}'
|
|
2322
|
-
`;
|
|
2323
|
-
const entityCheck = await pool.request().query(checkEntitySQL);
|
|
2324
|
-
if (entityCheck.recordset.length > 0) {
|
|
2325
|
-
const currentIcon = entityCheck.recordset[0].Icon;
|
|
2326
|
-
// Only update if entity doesn't have an icon set
|
|
2327
|
-
if (!currentIcon || currentIcon.trim().length === 0) {
|
|
2328
|
-
const escapedIcon = result.entityIcon.replace(/'/g, "''");
|
|
2329
|
-
const updateEntitySQL = `
|
|
2330
|
-
UPDATE [${mj_core_schema()}].Entity
|
|
2331
|
-
SET Icon = '${escapedIcon}',
|
|
2332
|
-
__mj_UpdatedAt = GETUTCDATE()
|
|
2333
|
-
WHERE ID = '${entityId}'
|
|
2334
|
-
`;
|
|
2335
|
-
await this.LogSQLAndExecute(pool, updateEntitySQL, `Set entity icon to ${result.entityIcon}`, false);
|
|
2336
|
-
logStatus(` ✓ Set entity icon: ${result.entityIcon}`);
|
|
2337
|
-
}
|
|
2338
|
-
}
|
|
3209
|
+
await this.LogSQLAndExecute(pool, sqlStatements.join('\n'), `Set categories for ${sqlStatements.length} fields`, false);
|
|
2339
3210
|
}
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
const existingNew = await pool.request().query(checkNewSQL);
|
|
2354
|
-
if (existingNew.recordset.length > 0) {
|
|
2355
|
-
// Update existing setting
|
|
3211
|
+
}
|
|
3212
|
+
/**
|
|
3213
|
+
* Sets the entity icon if the entity doesn't already have one.
|
|
3214
|
+
*/
|
|
3215
|
+
async applyEntityIcon(pool, entityId, entityIcon) {
|
|
3216
|
+
if (!entityIcon || entityIcon.trim().length === 0)
|
|
3217
|
+
return;
|
|
3218
|
+
const checkSQL = `SELECT Icon FROM [${mj_core_schema()}].Entity WHERE ID = '${entityId}'`;
|
|
3219
|
+
const entityCheck = await pool.request().query(checkSQL);
|
|
3220
|
+
if (entityCheck.recordset.length > 0) {
|
|
3221
|
+
const currentIcon = entityCheck.recordset[0].Icon;
|
|
3222
|
+
if (!currentIcon || currentIcon.trim().length === 0) {
|
|
3223
|
+
const escapedIcon = entityIcon.replace(/'/g, "''");
|
|
2356
3224
|
const updateSQL = `
|
|
2357
|
-
UPDATE [${mj_core_schema()}].
|
|
2358
|
-
SET
|
|
2359
|
-
|
|
2360
|
-
WHERE EntityID = '${entityId}' AND Name = 'FieldCategoryInfo'
|
|
3225
|
+
UPDATE [${mj_core_schema()}].Entity
|
|
3226
|
+
SET Icon = '${escapedIcon}', __mj_UpdatedAt = GETUTCDATE()
|
|
3227
|
+
WHERE ID = '${entityId}'
|
|
2361
3228
|
`;
|
|
2362
|
-
await this.LogSQLAndExecute(pool, updateSQL, `
|
|
3229
|
+
await this.LogSQLAndExecute(pool, updateSQL, `Set entity icon to ${entityIcon}`, false);
|
|
3230
|
+
logStatus(` Set entity icon: ${entityIcon}`);
|
|
2363
3231
|
}
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
}
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
3232
|
+
}
|
|
3233
|
+
}
|
|
3234
|
+
/**
|
|
3235
|
+
* Upserts FieldCategoryInfo (new format) and FieldCategoryIcons (legacy format) in EntitySetting.
|
|
3236
|
+
*/
|
|
3237
|
+
async applyCategoryInfoSettings(pool, entityId, categoryInfo) {
|
|
3238
|
+
if (!categoryInfo || Object.keys(categoryInfo).length === 0)
|
|
3239
|
+
return;
|
|
3240
|
+
const infoJSON = JSON.stringify(categoryInfo).replace(/'/g, "''");
|
|
3241
|
+
// Upsert FieldCategoryInfo (new format)
|
|
3242
|
+
const checkNewSQL = `SELECT ID FROM [${mj_core_schema()}].EntitySetting WHERE EntityID = '${entityId}' AND Name = 'FieldCategoryInfo'`;
|
|
3243
|
+
const existingNew = await pool.request().query(checkNewSQL);
|
|
3244
|
+
if (existingNew.recordset.length > 0) {
|
|
3245
|
+
await this.LogSQLAndExecute(pool, `
|
|
3246
|
+
UPDATE [${mj_core_schema()}].EntitySetting
|
|
3247
|
+
SET Value = '${infoJSON}', __mj_UpdatedAt = GETUTCDATE()
|
|
3248
|
+
WHERE EntityID = '${entityId}' AND Name = 'FieldCategoryInfo'
|
|
3249
|
+
`, `Update FieldCategoryInfo setting for entity`, false);
|
|
3250
|
+
}
|
|
3251
|
+
else {
|
|
3252
|
+
const newId = uuidv4();
|
|
3253
|
+
await this.LogSQLAndExecute(pool, `
|
|
3254
|
+
INSERT INTO [${mj_core_schema()}].EntitySetting (ID, EntityID, Name, Value, __mj_CreatedAt, __mj_UpdatedAt)
|
|
3255
|
+
VALUES ('${newId}', '${entityId}', 'FieldCategoryInfo', '${infoJSON}', GETUTCDATE(), GETUTCDATE())
|
|
3256
|
+
`, `Insert FieldCategoryInfo setting for entity`, false);
|
|
3257
|
+
}
|
|
3258
|
+
// Also upsert legacy FieldCategoryIcons for backwards compatibility
|
|
3259
|
+
const iconsOnly = {};
|
|
3260
|
+
for (const [category, info] of Object.entries(categoryInfo)) {
|
|
3261
|
+
if (info && typeof info === 'object' && 'icon' in info) {
|
|
3262
|
+
iconsOnly[category] = info.icon;
|
|
3263
|
+
}
|
|
3264
|
+
}
|
|
3265
|
+
const iconsJSON = JSON.stringify(iconsOnly).replace(/'/g, "''");
|
|
3266
|
+
const checkLegacySQL = `SELECT ID FROM [${mj_core_schema()}].EntitySetting WHERE EntityID = '${entityId}' AND Name = 'FieldCategoryIcons'`;
|
|
3267
|
+
const existingLegacy = await pool.request().query(checkLegacySQL);
|
|
3268
|
+
if (existingLegacy.recordset.length > 0) {
|
|
3269
|
+
await this.LogSQLAndExecute(pool, `
|
|
3270
|
+
UPDATE [${mj_core_schema()}].EntitySetting
|
|
3271
|
+
SET Value = '${iconsJSON}', __mj_UpdatedAt = GETUTCDATE()
|
|
2384
3272
|
WHERE EntityID = '${entityId}' AND Name = 'FieldCategoryIcons'
|
|
2385
|
-
|
|
2386
|
-
const existingLegacy = await pool.request().query(checkLegacySQL);
|
|
2387
|
-
if (existingLegacy.recordset.length > 0) {
|
|
2388
|
-
const updateSQL = `
|
|
2389
|
-
UPDATE [${mj_core_schema()}].EntitySetting
|
|
2390
|
-
SET Value = '${iconsJSON}',
|
|
2391
|
-
__mj_UpdatedAt = GETUTCDATE()
|
|
2392
|
-
WHERE EntityID = '${entityId}' AND Name = 'FieldCategoryIcons'
|
|
2393
|
-
`;
|
|
2394
|
-
await this.LogSQLAndExecute(pool, updateSQL, `Update FieldCategoryIcons setting for entity (legacy format)`, false);
|
|
2395
|
-
}
|
|
2396
|
-
else {
|
|
2397
|
-
const newId = uuidv4();
|
|
2398
|
-
const insertSQL = `
|
|
2399
|
-
INSERT INTO [${mj_core_schema()}].EntitySetting (ID, EntityID, Name, Value, __mj_CreatedAt, __mj_UpdatedAt)
|
|
2400
|
-
VALUES ('${newId}', '${entityId}', 'FieldCategoryIcons', '${iconsJSON}', GETUTCDATE(), GETUTCDATE())
|
|
2401
|
-
`;
|
|
2402
|
-
await this.LogSQLAndExecute(pool, insertSQL, `Insert FieldCategoryIcons setting for entity (legacy format)`, false);
|
|
2403
|
-
}
|
|
3273
|
+
`, `Update FieldCategoryIcons setting (legacy)`, false);
|
|
2404
3274
|
}
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
UPDATE [${mj_core_schema()}].ApplicationEntity
|
|
2412
|
-
SET DefaultForNewUser = ${defaultForNewUser},
|
|
2413
|
-
__mj_UpdatedAt = GETUTCDATE()
|
|
2414
|
-
WHERE EntityID = '${entityId}'
|
|
2415
|
-
`;
|
|
2416
|
-
await this.LogSQLAndExecute(pool, updateAppEntitySQL, `Set DefaultForNewUser=${defaultForNewUser} for NEW entity based on AI analysis (category: ${result.entityImportance.entityCategory}, confidence: ${result.entityImportance.confidence})`, false);
|
|
2417
|
-
logStatus(` ✓ Entity importance (NEW Entity): ${result.entityImportance.entityCategory} (defaultForNewUser: ${result.entityImportance.defaultForNewUser}, confidence: ${result.entityImportance.confidence})`);
|
|
2418
|
-
logStatus(` Reasoning: ${result.entityImportance.reasoning}`);
|
|
3275
|
+
else {
|
|
3276
|
+
const newId = uuidv4();
|
|
3277
|
+
await this.LogSQLAndExecute(pool, `
|
|
3278
|
+
INSERT INTO [${mj_core_schema()}].EntitySetting (ID, EntityID, Name, Value, __mj_CreatedAt, __mj_UpdatedAt)
|
|
3279
|
+
VALUES ('${newId}', '${entityId}', 'FieldCategoryIcons', '${iconsJSON}', GETUTCDATE(), GETUTCDATE())
|
|
3280
|
+
`, `Insert FieldCategoryIcons setting (legacy)`, false);
|
|
2419
3281
|
}
|
|
2420
3282
|
}
|
|
3283
|
+
/**
|
|
3284
|
+
* Applies entity importance analysis to ApplicationEntity records.
|
|
3285
|
+
* Only called for NEW entities to set DefaultForNewUser.
|
|
3286
|
+
*/
|
|
3287
|
+
async applyEntityImportance(pool, entityId, importance) {
|
|
3288
|
+
const defaultForNewUser = importance.defaultForNewUser ? 1 : 0;
|
|
3289
|
+
const updateSQL = `
|
|
3290
|
+
UPDATE [${mj_core_schema()}].ApplicationEntity
|
|
3291
|
+
SET DefaultForNewUser = ${defaultForNewUser}, __mj_UpdatedAt = GETUTCDATE()
|
|
3292
|
+
WHERE EntityID = '${entityId}'
|
|
3293
|
+
`;
|
|
3294
|
+
await this.LogSQLAndExecute(pool, updateSQL, `Set DefaultForNewUser=${defaultForNewUser} for NEW entity (category: ${importance.entityCategory}, confidence: ${importance.confidence})`, false);
|
|
3295
|
+
logStatus(` Entity importance (NEW Entity): ${importance.entityCategory} (defaultForNewUser: ${importance.defaultForNewUser}, confidence: ${importance.confidence})`);
|
|
3296
|
+
logStatus(` Reasoning: ${importance.reasoning}`);
|
|
3297
|
+
}
|
|
2421
3298
|
/**
|
|
2422
3299
|
* Executes the given SQL query using the given ConnectionPool object.
|
|
2423
3300
|
* If the appendToLogFile parameter is true, the query will also be appended to the log file.
|