@memberjunction/core 6.2.2 → 6.3.0-edge.1
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/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
- package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
- package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
- package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
- package/dist/generic/appCapabilityRegistry.d.ts +106 -0
- package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
- package/dist/generic/appCapabilityRegistry.js +212 -0
- package/dist/generic/appCapabilityRegistry.js.map +1 -0
- package/dist/generic/baseEngine.d.ts +108 -3
- package/dist/generic/baseEngine.d.ts.map +1 -1
- package/dist/generic/baseEngine.js +891 -122
- package/dist/generic/baseEngine.js.map +1 -1
- package/dist/generic/baseEngineRegistry.d.ts +8 -0
- package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
- package/dist/generic/baseEngineRegistry.js +36 -11
- package/dist/generic/baseEngineRegistry.js.map +1 -1
- package/dist/generic/baseEntity.d.ts +155 -3
- package/dist/generic/baseEntity.d.ts.map +1 -1
- package/dist/generic/baseEntity.js +1146 -74
- package/dist/generic/baseEntity.js.map +1 -1
- package/dist/generic/baseRemotableOperation.d.ts +32 -0
- package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
- package/dist/generic/baseRemotableOperation.js +29 -0
- package/dist/generic/baseRemotableOperation.js.map +1 -1
- package/dist/generic/compositeKey.d.ts.map +1 -1
- package/dist/generic/compositeKey.js +3 -1
- package/dist/generic/compositeKey.js.map +1 -1
- package/dist/generic/constraintErrorRedaction.d.ts +26 -0
- package/dist/generic/constraintErrorRedaction.d.ts.map +1 -0
- package/dist/generic/constraintErrorRedaction.js +166 -0
- package/dist/generic/constraintErrorRedaction.js.map +1 -0
- package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
- package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
- package/dist/generic/crossEntityPolicyEngine.js +667 -0
- package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
- package/dist/generic/dataHooks.d.ts +41 -4
- package/dist/generic/dataHooks.d.ts.map +1 -1
- package/dist/generic/dataHooks.js +82 -0
- package/dist/generic/dataHooks.js.map +1 -1
- package/dist/generic/databaseProviderBase.d.ts +96 -1
- package/dist/generic/databaseProviderBase.d.ts.map +1 -1
- package/dist/generic/databaseProviderBase.js +414 -44
- package/dist/generic/databaseProviderBase.js.map +1 -1
- package/dist/generic/documentNumberingEngine.d.ts +190 -0
- package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
- package/dist/generic/documentNumberingEngine.js +739 -0
- package/dist/generic/documentNumberingEngine.js.map +1 -0
- package/dist/generic/entityInfo.d.ts +152 -8
- package/dist/generic/entityInfo.d.ts.map +1 -1
- package/dist/generic/entityInfo.js +507 -71
- package/dist/generic/entityInfo.js.map +1 -1
- package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
- package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
- package/dist/generic/entityLifecyclePolicy.js +708 -0
- package/dist/generic/entityLifecyclePolicy.js.map +1 -0
- package/dist/generic/entitySavePlan.d.ts +6 -0
- package/dist/generic/entitySavePlan.d.ts.map +1 -1
- package/dist/generic/entitySavePlan.js +145 -1
- package/dist/generic/entitySavePlan.js.map +1 -1
- package/dist/generic/entitySubtypeDriver.d.ts +49 -0
- package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
- package/dist/generic/entitySubtypeDriver.js +26 -0
- package/dist/generic/entitySubtypeDriver.js.map +1 -0
- package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
- package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
- package/dist/generic/fieldSecuritySQLGate.js +41 -1
- package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
- package/dist/generic/filters/compositeFilter.d.ts +5 -1
- package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
- package/dist/generic/filters/compositeFilter.js +127 -12
- package/dist/generic/filters/compositeFilter.js.map +1 -1
- package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
- package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
- package/dist/generic/filters/compositeFilterSQL.js +489 -0
- package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
- package/dist/generic/filters/filter.types.d.ts +5 -2
- package/dist/generic/filters/filter.types.d.ts.map +1 -1
- package/dist/generic/filters/filter.types.js +4 -1
- package/dist/generic/filters/filter.types.js.map +1 -1
- package/dist/generic/filters/filterBuilder.d.ts +75 -0
- package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
- package/dist/generic/filters/filterBuilder.js +104 -0
- package/dist/generic/filters/filterBuilder.js.map +1 -0
- package/dist/generic/filters/index.d.ts +2 -0
- package/dist/generic/filters/index.d.ts.map +1 -1
- package/dist/generic/filters/index.js +2 -0
- package/dist/generic/filters/index.js.map +1 -1
- package/dist/generic/interfaces.d.ts +125 -19
- package/dist/generic/interfaces.d.ts.map +1 -1
- package/dist/generic/interfaces.js +9 -10
- package/dist/generic/interfaces.js.map +1 -1
- package/dist/generic/localCacheManager.d.ts +54 -14
- package/dist/generic/localCacheManager.d.ts.map +1 -1
- package/dist/generic/localCacheManager.js +450 -106
- package/dist/generic/localCacheManager.js.map +1 -1
- package/dist/generic/metadata.d.ts +7 -5
- package/dist/generic/metadata.d.ts.map +1 -1
- package/dist/generic/metadata.js +29 -10
- package/dist/generic/metadata.js.map +1 -1
- package/dist/generic/providerBase.d.ts +405 -45
- package/dist/generic/providerBase.d.ts.map +1 -1
- package/dist/generic/providerBase.js +1107 -200
- package/dist/generic/providerBase.js.map +1 -1
- package/dist/generic/queryInfo.d.ts +5 -0
- package/dist/generic/queryInfo.d.ts.map +1 -1
- package/dist/generic/queryInfo.js +5 -0
- package/dist/generic/queryInfo.js.map +1 -1
- package/dist/generic/queryInfoInterfaces.d.ts +5 -0
- package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
- package/dist/generic/queryResultEnricher.d.ts +4 -1
- package/dist/generic/queryResultEnricher.d.ts.map +1 -1
- package/dist/generic/queryResultEnricher.js.map +1 -1
- package/dist/generic/queryTemplateContext.d.ts.map +1 -1
- package/dist/generic/queryTemplateContext.js +38 -3
- package/dist/generic/queryTemplateContext.js.map +1 -1
- package/dist/generic/relatedRecordCollection.d.ts +20 -0
- package/dist/generic/relatedRecordCollection.d.ts.map +1 -1
- package/dist/generic/relatedRecordCollection.js +257 -22
- package/dist/generic/relatedRecordCollection.js.map +1 -1
- package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
- package/dist/generic/remoteOperationDispatch.js +13 -1
- package/dist/generic/remoteOperationDispatch.js.map +1 -1
- package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
- package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
- package/dist/generic/saveEntityGraphOperation.js +8 -0
- package/dist/generic/saveEntityGraphOperation.js.map +1 -1
- package/dist/generic/securityInfo.d.ts +49 -2
- package/dist/generic/securityInfo.d.ts.map +1 -1
- package/dist/generic/securityInfo.js +139 -12
- package/dist/generic/securityInfo.js.map +1 -1
- package/dist/generic/telemetryManager.d.ts +40 -4
- package/dist/generic/telemetryManager.d.ts.map +1 -1
- package/dist/generic/telemetryManager.js +68 -15
- package/dist/generic/telemetryManager.js.map +1 -1
- package/dist/generic/transactionGroup.d.ts +66 -23
- package/dist/generic/transactionGroup.d.ts.map +1 -1
- package/dist/generic/transactionGroup.js +225 -57
- package/dist/generic/transactionGroup.js.map +1 -1
- package/dist/generic/util.d.ts.map +1 -1
- package/dist/generic/util.js +9 -3
- package/dist/generic/util.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/views/runView.d.ts +61 -0
- package/dist/views/runView.d.ts.map +1 -1
- package/dist/views/runView.js +154 -3
- package/dist/views/runView.js.map +1 -1
- package/package.json +3 -3
- package/readme.md +6 -5
|
@@ -10,8 +10,12 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
10
10
|
var EntityField_1;
|
|
11
11
|
import { Base64DecodedByteLength, DeserializeValidationErrors, Float32VectorToBase64, IsValidBase64, IsMemberOverridden, MJEventType, MJGlobal, NormalizeUUID, OptionalKeyedSpecialization, uuidv4, UUIDsEqual, UserCacheKeySegment, WarningManager, ComputeContentHashAsync, EscapeSQLString } from '@memberjunction/global';
|
|
12
12
|
import { GetDataHooks } from './dataHooks.js';
|
|
13
|
-
import {
|
|
13
|
+
import { EntityLifecyclePolicyEngine } from './entityLifecyclePolicy.js';
|
|
14
|
+
import { DocumentNumberingEngine } from './documentNumberingEngine.js';
|
|
15
|
+
import { CrossEntityPolicyEngine } from './crossEntityPolicyEngine.js';
|
|
16
|
+
import { EntityFieldInfo, EntityInfo, EntityFieldTSType, EntityPermissionType, FieldSecurityError, RecordChange, ValidationErrorInfo, ValidationErrorType, ValidationResult } from './entityInfo.js';
|
|
14
17
|
import { EntitySubtypeResolver } from './entitySubtypeResolver.js';
|
|
18
|
+
import { EntitySubtypeDriverBase } from './entitySubtypeDriver.js';
|
|
15
19
|
import { CanonicalPrimaryKeyValue } from './util.js';
|
|
16
20
|
import { BaseEngineRegistry } from './baseEngineRegistry.js';
|
|
17
21
|
import { IsPermittedImageFieldValue, IsValidCssColor, TryParseJsonText } from './extendedTypeValue.js';
|
|
@@ -1052,6 +1056,15 @@ export class BaseEntity {
|
|
|
1052
1056
|
* a hint would name it and miss.
|
|
1053
1057
|
*/
|
|
1054
1058
|
this._skipSubtypeLoadHint = false;
|
|
1059
|
+
/**
|
|
1060
|
+
* Set while an already-loaded parent links and loads an IS-A child downward
|
|
1061
|
+
* ({@link linkAndLoadChildEntity}, {@link loadChildRowQuietly}). Child views join the parent's
|
|
1062
|
+
* physical base table rather than the parent's view, so they omit the parent's virtual joined
|
|
1063
|
+
* columns (e.g. `Conversation.Type`, `Comment.CommentType`). Skipping `this._parentEntity.Hydrate`
|
|
1064
|
+
* during downward child hydration preserves the parent's authoritative virtual columns while
|
|
1065
|
+
* `SetMany` still synchronizes shared physical columns.
|
|
1066
|
+
*/
|
|
1067
|
+
this._skipParentChainHydration = false;
|
|
1055
1068
|
/**
|
|
1056
1069
|
* For **overlapping** subtype parents (AllowMultipleSubtypes = true), stores
|
|
1057
1070
|
* the list of child entity type names that have records for this PK.
|
|
@@ -1091,7 +1104,10 @@ export class BaseEntity {
|
|
|
1091
1104
|
* pay nothing for the feature, not even an empty Map per instance.
|
|
1092
1105
|
*/
|
|
1093
1106
|
this._companions = null;
|
|
1107
|
+
/** Per-instance async queue serializing `EnsureISAChild` and `ReconcileISAChild` calls. */
|
|
1108
|
+
this._isaChildOpQueue = Promise.resolve();
|
|
1094
1109
|
this._finalizeGeneration = 0;
|
|
1110
|
+
this._pendingPostSave = null;
|
|
1095
1111
|
/**
|
|
1096
1112
|
* Returns true if the object is Dirty, meaning something has changed since it was last saved to the database, and false otherwise. For new records, this will always return true.
|
|
1097
1113
|
*
|
|
@@ -1127,6 +1143,7 @@ export class BaseEntity {
|
|
|
1127
1143
|
* @returns ValidationResult The validation result
|
|
1128
1144
|
*/
|
|
1129
1145
|
this._isValidating = false;
|
|
1146
|
+
this._inSaveValidation = false;
|
|
1130
1147
|
/**
|
|
1131
1148
|
* private storage for vectors that might be used for this entity, typically in association with individual fields
|
|
1132
1149
|
* however it is possible for the string in the map to be any unique key relative to the object so you could have vectors
|
|
@@ -1462,8 +1479,16 @@ export class BaseEntity {
|
|
|
1462
1479
|
this._childEntity = childEntity;
|
|
1463
1480
|
// Capture any pending modifications on this entity or its ancestors before child InnerLoad
|
|
1464
1481
|
const dirtySnapshots = this.captureChainDirtyState();
|
|
1465
|
-
// Load the child's record using our shared PK
|
|
1466
|
-
|
|
1482
|
+
// Load the child's record using our shared PK without wiping virtual columns on the
|
|
1483
|
+
// already-loaded parent chain (child views join parent base tables, not parent views).
|
|
1484
|
+
childEntity._skipParentChainHydration = true;
|
|
1485
|
+
let loaded;
|
|
1486
|
+
try {
|
|
1487
|
+
loaded = await childEntity.InnerLoad(this.PrimaryKey);
|
|
1488
|
+
}
|
|
1489
|
+
finally {
|
|
1490
|
+
childEntity._skipParentChainHydration = false;
|
|
1491
|
+
}
|
|
1467
1492
|
if (!loaded) {
|
|
1468
1493
|
// Load failed — clean up the link
|
|
1469
1494
|
this._childEntity = null;
|
|
@@ -1716,17 +1741,49 @@ export class BaseEntity {
|
|
|
1716
1741
|
}
|
|
1717
1742
|
/** Per entity (lowercased name): the resolver asked for load hints, decided once per registration. */
|
|
1718
1743
|
static { this._subtypeLoadHintResolvers = new Map(); }
|
|
1744
|
+
/** Cached driver instances keyed by `${baseClassName.toLowerCase()}|${driverKey.toLowerCase()}`. */
|
|
1745
|
+
static { this._subtypeDrivers = new Map(); }
|
|
1746
|
+
/** Memoized type-table field rules derived from entities declaring multi-segment `SubtypeSelector.Path`s. */
|
|
1747
|
+
static { this._subtypeTypeFieldRulesCache = null; }
|
|
1748
|
+
/**
|
|
1749
|
+
* Active `(EntitySaveOptions -> WeakSet<RootEntity>)` pairs whose IS-A chain is currently inside
|
|
1750
|
+
* an initiating `Save()` call, preventing leaf delegation from double-reconciling the same chain
|
|
1751
|
+
* while allowing callers to reuse a single `EntitySaveOptions` instance across sequential or
|
|
1752
|
+
* concurrent saves of other records.
|
|
1753
|
+
*/
|
|
1754
|
+
static { this._reconciledSaveChains = new WeakMap(); }
|
|
1755
|
+
static hasReconciledSaveChain(options, root) {
|
|
1756
|
+
return BaseEntity._reconciledSaveChains.get(options)?.has(root) ?? false;
|
|
1757
|
+
}
|
|
1758
|
+
static markReconciledSaveChain(options, root) {
|
|
1759
|
+
let roots = BaseEntity._reconciledSaveChains.get(options);
|
|
1760
|
+
if (!roots) {
|
|
1761
|
+
roots = new WeakSet();
|
|
1762
|
+
BaseEntity._reconciledSaveChains.set(options, roots);
|
|
1763
|
+
}
|
|
1764
|
+
roots.add(root);
|
|
1765
|
+
}
|
|
1766
|
+
static unmarkReconciledSaveChain(options, root) {
|
|
1767
|
+
BaseEntity._reconciledSaveChains.get(options)?.delete(root);
|
|
1768
|
+
}
|
|
1769
|
+
runExclusiveISAChildOp(fn) {
|
|
1770
|
+
const next = this._isaChildOpQueue.then(fn, fn);
|
|
1771
|
+
this._isaChildOpQueue = next.then(() => undefined, () => undefined);
|
|
1772
|
+
return next;
|
|
1773
|
+
}
|
|
1719
1774
|
/** Indexes over engine-cached arrays, keyed by the live array itself; see {@link findEngineCachedRow}. */
|
|
1720
1775
|
static { this._engineCachedRowIndexes = new WeakMap(); }
|
|
1721
1776
|
/**
|
|
1722
1777
|
* Clears the static caches IsA subtype resolution keeps: the create path's SubtypeSelector
|
|
1723
|
-
* lookup memo, the per-entity decision about which resolver gives load hints,
|
|
1724
|
-
*
|
|
1725
|
-
* reported again.
|
|
1778
|
+
* lookup memo, the per-entity decision about which resolver gives load hints, cached subtype
|
|
1779
|
+
* drivers, derived type-table validation rules, the indexes over engine-cached rows, and the
|
|
1780
|
+
* record of load-hint messages already logged, so each can be reported again.
|
|
1726
1781
|
*/
|
|
1727
1782
|
static ClearSubtypeLookupCache() {
|
|
1728
1783
|
BaseEntity._subtypeLookupCache = new WeakMap();
|
|
1729
1784
|
BaseEntity._subtypeLoadHintResolvers.clear();
|
|
1785
|
+
BaseEntity._subtypeDrivers.clear();
|
|
1786
|
+
BaseEntity._subtypeTypeFieldRulesCache = null;
|
|
1730
1787
|
BaseEntity._engineCachedRowIndexes = new WeakMap();
|
|
1731
1788
|
BaseEntity._loggedSubtypeLoadHintMessages.clear();
|
|
1732
1789
|
}
|
|
@@ -1806,6 +1863,9 @@ export class BaseEntity {
|
|
|
1806
1863
|
* @returns The linked child BaseEntity, or null if no subtype applies.
|
|
1807
1864
|
*/
|
|
1808
1865
|
async EnsureISAChild(entityName) {
|
|
1866
|
+
return this.runExclusiveISAChildOp(() => this.ensureISAChildInternal(entityName));
|
|
1867
|
+
}
|
|
1868
|
+
async ensureISAChildInternal(entityName) {
|
|
1809
1869
|
if (!entityName) {
|
|
1810
1870
|
entityName = await this.ResolveSubtypeEntityName();
|
|
1811
1871
|
}
|
|
@@ -1878,11 +1938,13 @@ export class BaseEntity {
|
|
|
1878
1938
|
async loadChildRowQuietly(childEntity) {
|
|
1879
1939
|
const probe = { RowReadFailed: false };
|
|
1880
1940
|
childEntity._subtypeHintProbe = probe;
|
|
1941
|
+
childEntity._skipParentChainHydration = true;
|
|
1881
1942
|
try {
|
|
1882
1943
|
return await childEntity.InnerLoad(this.PrimaryKey);
|
|
1883
1944
|
}
|
|
1884
1945
|
finally {
|
|
1885
1946
|
childEntity._subtypeHintProbe = null;
|
|
1947
|
+
childEntity._skipParentChainHydration = false;
|
|
1886
1948
|
}
|
|
1887
1949
|
}
|
|
1888
1950
|
mirrorSharedKeysToChild(childEntity) {
|
|
@@ -1965,6 +2027,413 @@ export class BaseEntity {
|
|
|
1965
2027
|
}
|
|
1966
2028
|
return record === this || !actingUser || record.EntityInfo.IsFieldReadableByUser(fieldName, actingUser);
|
|
1967
2029
|
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Synchronous counterpart of {@link evaluateSubtypeSelectorPath} for hooks that cannot await
|
|
2032
|
+
* (`OnFieldChanged`, synchronous `Validate()`, and cache-hot UI driver checks). Walks hops
|
|
2033
|
+
* strictly through `findTargetSync` and returns `null` when any hop misses memory.
|
|
2034
|
+
*/
|
|
2035
|
+
evaluateSubtypeSelectorPathSync(path, findTargetSync) {
|
|
2036
|
+
const segments = path.split('.').map(s => s.trim()).filter(Boolean);
|
|
2037
|
+
if (segments.length === 0)
|
|
2038
|
+
return null;
|
|
2039
|
+
let currentEntity = this;
|
|
2040
|
+
let currentEntityInfo = this.EntityInfo;
|
|
2041
|
+
const actingUser = this.resolveActiveUserOrNull();
|
|
2042
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
2043
|
+
const fieldName = segments[i];
|
|
2044
|
+
const fieldInfo = currentEntityInfo.Fields.find(f => f.Name.trim().toLowerCase() === fieldName.toLowerCase());
|
|
2045
|
+
if (!fieldInfo) {
|
|
2046
|
+
return null;
|
|
2047
|
+
}
|
|
2048
|
+
if (!this.subtypeSelectorMayRead(currentEntity, fieldInfo.Name, actingUser)) {
|
|
2049
|
+
return null;
|
|
2050
|
+
}
|
|
2051
|
+
const fkValue = currentEntity.Get(fieldInfo.Name);
|
|
2052
|
+
if (fkValue == null || fkValue === '') {
|
|
2053
|
+
return null;
|
|
2054
|
+
}
|
|
2055
|
+
const relatedEntityName = fieldInfo.RelatedEntity;
|
|
2056
|
+
if (!relatedEntityName) {
|
|
2057
|
+
return null;
|
|
2058
|
+
}
|
|
2059
|
+
const targetEntity = findTargetSync(relatedEntityName, fkValue);
|
|
2060
|
+
if (!targetEntity) {
|
|
2061
|
+
return null;
|
|
2062
|
+
}
|
|
2063
|
+
currentEntity = targetEntity;
|
|
2064
|
+
currentEntityInfo = targetEntity.EntityInfo;
|
|
2065
|
+
}
|
|
2066
|
+
const terminalSegment = segments[segments.length - 1];
|
|
2067
|
+
const terminalField = currentEntityInfo.Fields.find(f => f.Name.trim().toLowerCase() === terminalSegment.toLowerCase());
|
|
2068
|
+
if (!terminalField) {
|
|
2069
|
+
return null;
|
|
2070
|
+
}
|
|
2071
|
+
if (!this.subtypeSelectorMayRead(currentEntity, terminalField.Name, actingUser)) {
|
|
2072
|
+
return null;
|
|
2073
|
+
}
|
|
2074
|
+
const terminalValue = currentEntity.Get(terminalField.Name);
|
|
2075
|
+
if (terminalValue == null || typeof terminalValue !== 'string' || terminalValue.trim() === '') {
|
|
2076
|
+
return null;
|
|
2077
|
+
}
|
|
2078
|
+
return terminalValue.trim();
|
|
2079
|
+
}
|
|
2080
|
+
findSubtypePathTargetSync(entityName, pkValue) {
|
|
2081
|
+
const engineHit = BaseEntity.findSubtypePathTargetInEngineCache(entityName, pkValue);
|
|
2082
|
+
if (engineHit) {
|
|
2083
|
+
return engineHit;
|
|
2084
|
+
}
|
|
2085
|
+
const cacheKey = `${entityName.trim().toLowerCase()}|${String(pkValue).trim().toLowerCase()}`;
|
|
2086
|
+
const provider = this.ProviderToUse;
|
|
2087
|
+
const lookupCache = BaseEntity.subtypeLookupCacheFor(provider, this.resolveActiveUserOrNull());
|
|
2088
|
+
if (lookupCache?.has(cacheKey)) {
|
|
2089
|
+
return lookupCache.get(cacheKey) ?? null;
|
|
2090
|
+
}
|
|
2091
|
+
return null;
|
|
2092
|
+
}
|
|
2093
|
+
/**
|
|
2094
|
+
* Reconciles this disjoint parent's attached IS-A child against {@link ResolveSubtypeEntityName}.
|
|
2095
|
+
*
|
|
2096
|
+
* Unlike {@link EnsureISAChild}, which throws if a different child is already attached,
|
|
2097
|
+
* `ReconcileISAChild` cleanly replaces an **unsaved** prospective child when the user changes
|
|
2098
|
+
* the record's type before its first save (for example, inside an Angular form with
|
|
2099
|
+
* `FoldIntoForm: true`). If a **saved** child is already attached, `ReconcileISAChild` leaves
|
|
2100
|
+
* it intact so `Save()` can enforce `OnSubtypeChange` (`'Refuse'` or `'Replace'`).
|
|
2101
|
+
*/
|
|
2102
|
+
async ReconcileISAChild() {
|
|
2103
|
+
return this.runExclusiveISAChildOp(() => this.reconcileISAChildInternal());
|
|
2104
|
+
}
|
|
2105
|
+
async reconcileISAChildInternal() {
|
|
2106
|
+
if (!this.EntityInfo.IsParentType || this.EntityInfo.AllowMultipleSubtypes) {
|
|
2107
|
+
return null;
|
|
2108
|
+
}
|
|
2109
|
+
const resolvedName = await this.ResolveSubtypeEntityName();
|
|
2110
|
+
if (this._childEntity) {
|
|
2111
|
+
if (resolvedName && sameEntityName(this._childEntity.EntityInfo.Name, resolvedName)) {
|
|
2112
|
+
if (this._childEntity.EntityInfo.IsParentType) {
|
|
2113
|
+
await this._childEntity.ReconcileISAChild();
|
|
2114
|
+
}
|
|
2115
|
+
return this._childEntity;
|
|
2116
|
+
}
|
|
2117
|
+
if (this._childEntity.IsSaved) {
|
|
2118
|
+
return this._childEntity;
|
|
2119
|
+
}
|
|
2120
|
+
// Detach unsaved prospective child when type changed to another subtype or to no subtype
|
|
2121
|
+
const selectorPath = this.EntityInfo.SubtypeSelectorConfig?.Path;
|
|
2122
|
+
const firstHopVal = selectorPath ? this.getSubtypeSelectorFirstHopValue(selectorPath) : undefined;
|
|
2123
|
+
const shouldDetach = resolvedName !== null || (firstHopVal !== null && firstHopVal !== undefined && firstHopVal !== '');
|
|
2124
|
+
if (shouldDetach) {
|
|
2125
|
+
this.detachUnsavedChildSubtree();
|
|
2126
|
+
}
|
|
2127
|
+
else {
|
|
2128
|
+
return this._childEntity;
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
if (!resolvedName) {
|
|
2132
|
+
return null;
|
|
2133
|
+
}
|
|
2134
|
+
const ensured = await this.ensureISAChildInternal(resolvedName);
|
|
2135
|
+
if (ensured && ensured.EntityInfo.IsParentType) {
|
|
2136
|
+
await ensured.ReconcileISAChild();
|
|
2137
|
+
}
|
|
2138
|
+
return ensured;
|
|
2139
|
+
}
|
|
2140
|
+
detachUnsavedChildSubtree() {
|
|
2141
|
+
const child = this._childEntity;
|
|
2142
|
+
if (!child || child.IsSaved) {
|
|
2143
|
+
return;
|
|
2144
|
+
}
|
|
2145
|
+
child._parentEntity = null;
|
|
2146
|
+
this._childEntity = null;
|
|
2147
|
+
}
|
|
2148
|
+
getSubtypeSelectorFirstHopField(path) {
|
|
2149
|
+
const firstSegment = path.split('.').map(s => s.trim()).filter(Boolean)[0];
|
|
2150
|
+
if (!firstSegment) {
|
|
2151
|
+
return null;
|
|
2152
|
+
}
|
|
2153
|
+
return this.GetFieldByName(firstSegment);
|
|
2154
|
+
}
|
|
2155
|
+
getSubtypeSelectorFirstHopValue(path) {
|
|
2156
|
+
const firstSegment = path.split('.').map(s => s.trim()).filter(Boolean)[0];
|
|
2157
|
+
if (!firstSegment) {
|
|
2158
|
+
return undefined;
|
|
2159
|
+
}
|
|
2160
|
+
const field = this.GetFieldByName(firstSegment);
|
|
2161
|
+
return field ? field.Value : undefined;
|
|
2162
|
+
}
|
|
2163
|
+
isSubtypeSelectorFirstHopDirty(path) {
|
|
2164
|
+
const field = this.getSubtypeSelectorFirstHopField(path);
|
|
2165
|
+
return Boolean(field?.Dirty);
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* Resolves and caches the behavior driver configured on `EntityInfo.SubtypeSelectorConfig.Driver`
|
|
2169
|
+
* for this record's current type row, loading the type row if needed.
|
|
2170
|
+
*/
|
|
2171
|
+
async ResolveSubtypeDriver() {
|
|
2172
|
+
const driverConfig = this.EntityInfo?.SubtypeSelectorConfig?.Driver;
|
|
2173
|
+
if (!driverConfig?.Path) {
|
|
2174
|
+
return null;
|
|
2175
|
+
}
|
|
2176
|
+
const driverClassKey = await this.evaluateSubtypeSelectorPath(driverConfig.Path, (entityName, pkValue) => this.getSubtypePathTargetEntity(entityName, pkValue));
|
|
2177
|
+
if (!driverClassKey) {
|
|
2178
|
+
return null;
|
|
2179
|
+
}
|
|
2180
|
+
return BaseEntity.resolveSubtypeDriverByKey(driverConfig, driverClassKey);
|
|
2181
|
+
}
|
|
2182
|
+
/**
|
|
2183
|
+
* Synchronous cache-only counterpart of {@link ResolveSubtypeDriver}. Returns `null` when a hop
|
|
2184
|
+
* is not yet in memory or no driver class is registered for the type.
|
|
2185
|
+
*/
|
|
2186
|
+
ResolveSubtypeDriverSync() {
|
|
2187
|
+
const driverConfig = this.EntityInfo?.SubtypeSelectorConfig?.Driver;
|
|
2188
|
+
if (!driverConfig?.Path) {
|
|
2189
|
+
return null;
|
|
2190
|
+
}
|
|
2191
|
+
const driverClassKey = this.evaluateSubtypeSelectorPathSync(driverConfig.Path, (entityName, pkValue) => this.findSubtypePathTargetSync(entityName, pkValue));
|
|
2192
|
+
if (!driverClassKey) {
|
|
2193
|
+
return null;
|
|
2194
|
+
}
|
|
2195
|
+
return BaseEntity.resolveSubtypeDriverByKey(driverConfig, driverClassKey);
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Resolves the `UIDriver` class registration key configured on `EntityInfo.SubtypeSelectorConfig.UIDriver`
|
|
2199
|
+
* for this record's current type row, loading the type row if needed.
|
|
2200
|
+
*/
|
|
2201
|
+
async ResolveSubtypeUIDriverName() {
|
|
2202
|
+
const uiDriverConfig = this.EntityInfo?.SubtypeSelectorConfig?.UIDriver;
|
|
2203
|
+
if (!uiDriverConfig?.Path) {
|
|
2204
|
+
return null;
|
|
2205
|
+
}
|
|
2206
|
+
return this.evaluateSubtypeSelectorPath(uiDriverConfig.Path, (entityName, pkValue) => this.getSubtypePathTargetEntity(entityName, pkValue));
|
|
2207
|
+
}
|
|
2208
|
+
/**
|
|
2209
|
+
* Synchronous cache-only counterpart of {@link ResolveSubtypeUIDriverName}.
|
|
2210
|
+
*/
|
|
2211
|
+
ResolveSubtypeUIDriverNameSync() {
|
|
2212
|
+
const uiDriverConfig = this.EntityInfo?.SubtypeSelectorConfig?.UIDriver;
|
|
2213
|
+
if (!uiDriverConfig?.Path) {
|
|
2214
|
+
return null;
|
|
2215
|
+
}
|
|
2216
|
+
return this.evaluateSubtypeSelectorPathSync(uiDriverConfig.Path, (entityName, pkValue) => this.findSubtypePathTargetSync(entityName, pkValue));
|
|
2217
|
+
}
|
|
2218
|
+
static resolveSubtypeDriverByKey(driverConfig, driverClassKey) {
|
|
2219
|
+
const baseName = driverConfig.BaseClass?.trim() || EntitySubtypeDriverBase.name;
|
|
2220
|
+
const cacheKey = `${baseName.toLowerCase()}|${driverClassKey.trim().toLowerCase()}`;
|
|
2221
|
+
const cf = MJGlobal.Instance.ClassFactory;
|
|
2222
|
+
const namedBaseToken = { name: baseName };
|
|
2223
|
+
const reg = cf.GetRegistration(namedBaseToken, driverClassKey) ??
|
|
2224
|
+
(baseName !== EntitySubtypeDriverBase.name
|
|
2225
|
+
? cf.GetRegistration(EntitySubtypeDriverBase, driverClassKey)
|
|
2226
|
+
: null);
|
|
2227
|
+
if (!reg) {
|
|
2228
|
+
return null;
|
|
2229
|
+
}
|
|
2230
|
+
const cached = BaseEntity._subtypeDrivers.get(cacheKey);
|
|
2231
|
+
if (cached && cached.Registration === reg) {
|
|
2232
|
+
return cached.Driver;
|
|
2233
|
+
}
|
|
2234
|
+
try {
|
|
2235
|
+
const Ctor = reg.SubClass;
|
|
2236
|
+
const instance = new Ctor();
|
|
2237
|
+
BaseEntity._subtypeDrivers.set(cacheKey, { Registration: reg, Driver: instance });
|
|
2238
|
+
return instance;
|
|
2239
|
+
}
|
|
2240
|
+
catch (err) {
|
|
2241
|
+
LogError(`SubtypeSelector.Driver: failed to construct driver '${driverClassKey}' (base '${baseName}'): ${BaseEntity.errorText(err)}`);
|
|
2242
|
+
BaseEntity._subtypeDrivers.set(cacheKey, { Registration: reg, Driver: null });
|
|
2243
|
+
return null;
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
chainHasSubtypeDriver() {
|
|
2247
|
+
for (let node = this.RootEntity; node; node = node._childEntity) {
|
|
2248
|
+
if (node.EntityInfo?.SubtypeSelectorConfig?.Driver) {
|
|
2249
|
+
return true;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
return false;
|
|
2253
|
+
}
|
|
2254
|
+
notifySubtypeDriversFieldChanged(fieldName, newValue, oldValue) {
|
|
2255
|
+
if (this._isLoading || newValue === oldValue) {
|
|
2256
|
+
return;
|
|
2257
|
+
}
|
|
2258
|
+
for (let node = this.RootEntity; node; node = node._childEntity) {
|
|
2259
|
+
if (!node.EntityInfo?.SubtypeSelectorConfig?.Driver) {
|
|
2260
|
+
continue;
|
|
2261
|
+
}
|
|
2262
|
+
const driver = node.ResolveSubtypeDriverSync();
|
|
2263
|
+
if (driver?.OnFieldChanged) {
|
|
2264
|
+
driver.OnFieldChanged(node, fieldName, newValue, oldValue);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
validateSubtypeDriverSync(result) {
|
|
2269
|
+
if (!this.EntityInfo?.SubtypeSelectorConfig?.Driver) {
|
|
2270
|
+
return;
|
|
2271
|
+
}
|
|
2272
|
+
const driver = this.ResolveSubtypeDriverSync();
|
|
2273
|
+
if (!driver?.Validate) {
|
|
2274
|
+
return;
|
|
2275
|
+
}
|
|
2276
|
+
const maybePromise = driver.Validate(this, result, this.resolveActiveUserOrNull());
|
|
2277
|
+
if (maybePromise instanceof Promise) {
|
|
2278
|
+
maybePromise.catch((err) => {
|
|
2279
|
+
LogError(`SubtypeSelector.Driver Validate rejected asynchronously during synchronous Validate() on '${this.EntityInfo.Name}': ${BaseEntity.errorText(err)}`);
|
|
2280
|
+
});
|
|
2281
|
+
const msg = `Subtype driver for '${this.EntityInfo.Name}' requires asynchronous validation; use ValidateAsync() or Save() instead of synchronous Validate().`;
|
|
2282
|
+
LogError(msg);
|
|
2283
|
+
result.Success = false;
|
|
2284
|
+
result.Errors.push(new ValidationErrorInfo(this.EntityInfo.FirstPrimaryKey?.Name ?? 'ID', // first-pk-ok: fallback source field name for entity-level validation error
|
|
2285
|
+
msg, null, ValidationErrorType.Failure));
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
async validateSubtypeDriverAsync(result) {
|
|
2289
|
+
if (!this.EntityInfo?.SubtypeSelectorConfig?.Driver) {
|
|
2290
|
+
return;
|
|
2291
|
+
}
|
|
2292
|
+
const driver = await this.ResolveSubtypeDriver();
|
|
2293
|
+
if (!driver?.Validate) {
|
|
2294
|
+
return;
|
|
2295
|
+
}
|
|
2296
|
+
await driver.Validate(this, result, this.resolveActiveUserOrNull());
|
|
2297
|
+
}
|
|
2298
|
+
async runSubtypeDriverBeforeSave() {
|
|
2299
|
+
if (!this.EntityInfo?.SubtypeSelectorConfig?.Driver) {
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
const driver = await this.ResolveSubtypeDriver();
|
|
2303
|
+
if (!driver?.BeforeSave) {
|
|
2304
|
+
return;
|
|
2305
|
+
}
|
|
2306
|
+
const outcome = await driver.BeforeSave(this, !this.IsSaved, this.resolveActiveUserOrNull());
|
|
2307
|
+
if (outcome === false) {
|
|
2308
|
+
throw new Error(`Save rejected by subtype driver for '${this.EntityInfo.Name}'`);
|
|
2309
|
+
}
|
|
2310
|
+
if (typeof outcome === 'string' && outcome.trim().length > 0) {
|
|
2311
|
+
throw new Error(outcome);
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
async runSubtypeDriverAfterSave(wasNew) {
|
|
2315
|
+
if (!this.EntityInfo?.SubtypeSelectorConfig?.Driver) {
|
|
2316
|
+
return;
|
|
2317
|
+
}
|
|
2318
|
+
const driver = await this.ResolveSubtypeDriver();
|
|
2319
|
+
if (!driver?.AfterSave) {
|
|
2320
|
+
return;
|
|
2321
|
+
}
|
|
2322
|
+
await driver.AfterSave(this, wasNew, this.resolveActiveUserOrNull());
|
|
2323
|
+
}
|
|
2324
|
+
/**
|
|
2325
|
+
* Validates that when this entity is a type table referenced by one or more parent entities'
|
|
2326
|
+
* `SubtypeSelector.Path` declarations, every non-empty extension-entity name stored on this row
|
|
2327
|
+
* is a declared IS-A child of the corresponding parent entity.
|
|
2328
|
+
*/
|
|
2329
|
+
validateSubtypeTypeRowFields(result) {
|
|
2330
|
+
const provider = this.ProviderToUse ?? Metadata.Provider;
|
|
2331
|
+
const entities = provider?.Entities;
|
|
2332
|
+
if (!entities || entities.length === 0 || !this.EntityInfo?.Name) {
|
|
2333
|
+
return;
|
|
2334
|
+
}
|
|
2335
|
+
const rules = BaseEntity.subtypeTypeFieldRulesForEntity(entities, this.EntityInfo.Name);
|
|
2336
|
+
if (!rules || rules.length === 0) {
|
|
2337
|
+
return;
|
|
2338
|
+
}
|
|
2339
|
+
for (const rule of rules) {
|
|
2340
|
+
const field = this.GetFieldByName(rule.TerminalFieldName);
|
|
2341
|
+
if (!field) {
|
|
2342
|
+
continue;
|
|
2343
|
+
}
|
|
2344
|
+
const rawVal = field.Value;
|
|
2345
|
+
if (rawVal === null || rawVal === undefined) {
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
if (typeof rawVal !== 'string') {
|
|
2349
|
+
continue;
|
|
2350
|
+
}
|
|
2351
|
+
const candidate = rawVal.trim();
|
|
2352
|
+
if (candidate.length === 0) {
|
|
2353
|
+
continue;
|
|
2354
|
+
}
|
|
2355
|
+
const isDeclaredChild = rule.DeclaredChildNamesLower.has(candidate.toLowerCase());
|
|
2356
|
+
if (!isDeclaredChild) {
|
|
2357
|
+
result.Errors.push(new ValidationErrorInfo(field.Name, `'${candidate}' is not a declared IS-A child entity of '${rule.ParentEntity.Name}' (referenced via SubtypeSelector '${rule.SelectorPath}').`, rawVal, ValidationErrorType.Failure));
|
|
2358
|
+
result.Success = false;
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
static subtypeTypeFieldRulesForEntity(entities, entityName) {
|
|
2363
|
+
let sigParts = null;
|
|
2364
|
+
for (let i = 0; i < entities.length; i++) {
|
|
2365
|
+
const ent = entities[i];
|
|
2366
|
+
if (ent.SubtypeSelector) {
|
|
2367
|
+
(sigParts ??= []).push(`${ent.ID}:${ent.SubtypeSelector}:${ent.ChildEntities?.length ?? 0}`);
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
if (!sigParts) {
|
|
2371
|
+
return undefined;
|
|
2372
|
+
}
|
|
2373
|
+
const signature = `${entities.length}|${sigParts.join('||')}`;
|
|
2374
|
+
if (!BaseEntity._subtypeTypeFieldRulesCache || BaseEntity._subtypeTypeFieldRulesCache.Signature !== signature) {
|
|
2375
|
+
const byTypeEntity = new Map();
|
|
2376
|
+
const childNamesByParentId = new Map();
|
|
2377
|
+
for (const ent of entities) {
|
|
2378
|
+
if (!ent.ParentID || !ent.Name) {
|
|
2379
|
+
continue;
|
|
2380
|
+
}
|
|
2381
|
+
const parentKey = NormalizeUUID(ent.ParentID);
|
|
2382
|
+
let set = childNamesByParentId.get(parentKey);
|
|
2383
|
+
if (!set) {
|
|
2384
|
+
set = new Set();
|
|
2385
|
+
childNamesByParentId.set(parentKey, set);
|
|
2386
|
+
}
|
|
2387
|
+
set.add(ent.Name.trim().toLowerCase());
|
|
2388
|
+
}
|
|
2389
|
+
for (const parentEntity of entities) {
|
|
2390
|
+
const selector = parentEntity.SubtypeSelectorConfig;
|
|
2391
|
+
if (!selector?.Path) {
|
|
2392
|
+
continue;
|
|
2393
|
+
}
|
|
2394
|
+
const segments = selector.Path.split('.').map(s => s.trim()).filter(Boolean);
|
|
2395
|
+
if (segments.length < 2) {
|
|
2396
|
+
continue;
|
|
2397
|
+
}
|
|
2398
|
+
let currentInfo = parentEntity;
|
|
2399
|
+
for (let sIdx = 0; sIdx < segments.length - 1 && currentInfo; sIdx++) {
|
|
2400
|
+
const hopField = currentInfo.Fields.find(f => f.Name.trim().toLowerCase() === segments[sIdx].toLowerCase());
|
|
2401
|
+
if (!hopField?.RelatedEntity) {
|
|
2402
|
+
currentInfo = undefined;
|
|
2403
|
+
break;
|
|
2404
|
+
}
|
|
2405
|
+
currentInfo = entities.find(e => sameEntityName(e.Name, hopField.RelatedEntity));
|
|
2406
|
+
}
|
|
2407
|
+
const terminalSegment = segments[segments.length - 1];
|
|
2408
|
+
const terminalField = currentInfo?.Fields.find(f => f.Name.trim().toLowerCase() === terminalSegment.toLowerCase());
|
|
2409
|
+
if (currentInfo && terminalField) {
|
|
2410
|
+
const declaredChildNamesLower = new Set(childNamesByParentId.get(NormalizeUUID(parentEntity.ID)) ?? []);
|
|
2411
|
+
for (const child of parentEntity.ChildEntities ?? []) {
|
|
2412
|
+
if (child.Name) {
|
|
2413
|
+
declaredChildNamesLower.add(child.Name.trim().toLowerCase());
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
const key = currentInfo.Name.trim().toLowerCase();
|
|
2417
|
+
let list = byTypeEntity.get(key);
|
|
2418
|
+
if (!list) {
|
|
2419
|
+
list = [];
|
|
2420
|
+
byTypeEntity.set(key, list);
|
|
2421
|
+
}
|
|
2422
|
+
list.push({
|
|
2423
|
+
TerminalFieldName: terminalField.Name,
|
|
2424
|
+
ParentEntity: parentEntity,
|
|
2425
|
+
SelectorPath: selector.Path,
|
|
2426
|
+
DeclaredChildNamesLower: declaredChildNamesLower,
|
|
2427
|
+
});
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
BaseEntity._subtypeTypeFieldRulesCache = {
|
|
2431
|
+
Signature: signature,
|
|
2432
|
+
ByTypeEntityName: byTypeEntity,
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
return BaseEntity._subtypeTypeFieldRulesCache.ByTypeEntityName.get(entityName.trim().toLowerCase());
|
|
2436
|
+
}
|
|
1968
2437
|
async getSubtypePathTargetEntity(entityName, pkValue) {
|
|
1969
2438
|
const cacheKey = `${entityName.trim().toLowerCase()}|${String(pkValue).trim().toLowerCase()}`;
|
|
1970
2439
|
const provider = this.ProviderToUse;
|
|
@@ -2605,6 +3074,7 @@ export class BaseEntity {
|
|
|
2605
3074
|
// report (and notify subscribers) as an update.
|
|
2606
3075
|
const saveSubType = this.IsSaved ? 'update' : 'create';
|
|
2607
3076
|
const changedFieldNames = this.dirtyFieldNames();
|
|
3077
|
+
const postSaveChangedFields = this.computePostSaveChangedFieldNames(saveSubType, changedFieldNames);
|
|
2608
3078
|
// Root: rebase field values and dirty state onto what the database now holds.
|
|
2609
3079
|
this.init();
|
|
2610
3080
|
const fields = this.narrowHydrationSource(output.Fields);
|
|
@@ -2626,6 +3096,24 @@ export class BaseEntity {
|
|
|
2626
3096
|
result.EndedAt = new Date();
|
|
2627
3097
|
this.RegisterResultHistoryEntry(result);
|
|
2628
3098
|
this.RaiseEvent('save', null, saveSubType, changedFieldNames);
|
|
3099
|
+
await this.runPostSaveHooks(postSaveChangedFields, saveSubType ?? 'update');
|
|
3100
|
+
}
|
|
3101
|
+
/**
|
|
3102
|
+
* Computes the changed field list for PostSave hooks. On 'update', this equals `dirtyFieldNames()`.
|
|
3103
|
+
* On 'create', `EntityField.Value` records the initial non-null write into `_oldValue` so `Dirty`
|
|
3104
|
+
* is false; include populated writable fields so PostSave observers see newly created field values.
|
|
3105
|
+
*/
|
|
3106
|
+
computePostSaveChangedFieldNames(saveSubType, dirtyNames) {
|
|
3107
|
+
if (saveSubType !== 'create' && this.IsSaved) {
|
|
3108
|
+
return dirtyNames;
|
|
3109
|
+
}
|
|
3110
|
+
const combined = new Set(dirtyNames);
|
|
3111
|
+
for (const f of this.Fields) {
|
|
3112
|
+
if (!f.ReadOnly && !f.EntityFieldInfo.IsVirtual && (!f.NeverSet || (f.Value !== null && f.Value !== undefined))) {
|
|
3113
|
+
combined.add(f.Name);
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
return Array.from(combined);
|
|
2629
3117
|
}
|
|
2630
3118
|
/**
|
|
2631
3119
|
* The names of the fields that are dirty right now. Cheaper than walking {@link Fields}: an
|
|
@@ -2932,6 +3420,12 @@ export class BaseEntity {
|
|
|
2932
3420
|
for (const record of records) {
|
|
2933
3421
|
record._unitOfWork = part.unit;
|
|
2934
3422
|
}
|
|
3423
|
+
if (!saveOptions?.ReplayOnly && !deleteOptions?.ReplayOnly && provider) {
|
|
3424
|
+
await CrossEntityPolicyEngine.Instance.PrimeParentLocksForBatch(plan.Nodes.map((n) => ({
|
|
3425
|
+
Entity: n.Entity,
|
|
3426
|
+
Operation: n.Operation === 'Delete' ? 'Delete' : (n.Entity.IsSaved ? 'Update' : 'Create'),
|
|
3427
|
+
})), provider, this.ActiveUser);
|
|
3428
|
+
}
|
|
2935
3429
|
}
|
|
2936
3430
|
const result = await ExecuteEntitySavePlan(plan, {
|
|
2937
3431
|
SaveOptions: childSaveOptions,
|
|
@@ -2939,6 +3433,9 @@ export class BaseEntity {
|
|
|
2939
3433
|
Visited: visited,
|
|
2940
3434
|
SaveSelfOnly: (entity, opts) => entity.saveAsGraphNode(opts),
|
|
2941
3435
|
DeleteSelfOnly: (entity, opts) => entity.deleteAsGraphNode(opts),
|
|
3436
|
+
CanBatchLeaf: (entity, op) => op === 'Save'
|
|
3437
|
+
? entity.Save === BaseEntity.prototype.Save
|
|
3438
|
+
: entity.Delete === BaseEntity.prototype.Delete,
|
|
2942
3439
|
});
|
|
2943
3440
|
if (!result.Success) {
|
|
2944
3441
|
await scope?.Rollback();
|
|
@@ -3124,6 +3621,11 @@ export class BaseEntity {
|
|
|
3124
3621
|
* this save took none (see `_innerSave`), and then only the scope is rolled back.
|
|
3125
3622
|
*/
|
|
3126
3623
|
async rollbackChainSave(part) {
|
|
3624
|
+
let cur = this.RootEntity;
|
|
3625
|
+
while (cur) {
|
|
3626
|
+
cur._pendingPostSave = null;
|
|
3627
|
+
cur = cur._childEntity;
|
|
3628
|
+
}
|
|
3127
3629
|
await this.rollbackEntityTransactionScope();
|
|
3128
3630
|
BaseEntity.settleRollback(part);
|
|
3129
3631
|
}
|
|
@@ -3641,7 +4143,13 @@ export class BaseEntity {
|
|
|
3641
4143
|
this.assertFieldActiveStatus(FieldName, 'BaseEntity.Set');
|
|
3642
4144
|
}
|
|
3643
4145
|
this.assertFieldReadable(FieldName);
|
|
4146
|
+
const hasDriver = !this._isLoading && this.chainHasSubtypeDriver();
|
|
4147
|
+
const fieldObj = hasDriver ? this.GetFieldByName(FieldName) : null;
|
|
4148
|
+
const oldValue = fieldObj ? fieldObj.Value : undefined;
|
|
3644
4149
|
this.setLocal(FieldName, Value);
|
|
4150
|
+
if (hasDriver && fieldObj) {
|
|
4151
|
+
this.notifySubtypeDriversFieldChanged(fieldObj.Name, fieldObj.Value, oldValue);
|
|
4152
|
+
}
|
|
3645
4153
|
}
|
|
3646
4154
|
}
|
|
3647
4155
|
/**
|
|
@@ -4388,6 +4896,7 @@ export class BaseEntity {
|
|
|
4388
4896
|
this.init();
|
|
4389
4897
|
this.discardJSONFieldObjects();
|
|
4390
4898
|
this._everSaved = false; // Reset save state for new record
|
|
4899
|
+
DocumentNumberingEngine.Instance.ClearSystemAssignedMarkers(this);
|
|
4391
4900
|
// Clear child entity state — new records don't have children yet
|
|
4392
4901
|
this._childEntity = null;
|
|
4393
4902
|
this._childEntities = null;
|
|
@@ -4715,19 +5224,45 @@ export class BaseEntity {
|
|
|
4715
5224
|
// in one, taken only when this entity starts an IS-A chain save whose writes a failure undoes.
|
|
4716
5225
|
const enclosing = this._unitOfWork;
|
|
4717
5226
|
let part = null;
|
|
5227
|
+
let activeSaveOptions = null;
|
|
5228
|
+
let reconciledChainRoot = null;
|
|
4718
5229
|
try {
|
|
4719
5230
|
this.FlushJSONFieldObjects(); // idempotent; covers graph-node saves that bypass Save()
|
|
4720
5231
|
const initialDirtyState = this.Dirty; // save this because parent entity save cycle, if any, will clear their dirty flags
|
|
4721
5232
|
const _options = options ? options : new EntitySaveOptions();
|
|
5233
|
+
activeSaveOptions = _options;
|
|
5234
|
+
// Generic SubtypeSelector orchestration (AutoEnsureOnSave & OnSubtypeChange: 'Refuse' | 'Replace').
|
|
5235
|
+
// Runs once on the initiating Save() across the IS-A chain from root downward before leaf
|
|
5236
|
+
// delegation, so newly-ensured children participate in the leaf's single atomic transaction.
|
|
5237
|
+
if (!_options.IsParentEntitySave &&
|
|
5238
|
+
!_options.ReplayOnly &&
|
|
5239
|
+
!BaseEntity.hasReconciledSaveChain(_options, this.RootEntity)) {
|
|
5240
|
+
reconciledChainRoot = this.RootEntity;
|
|
5241
|
+
BaseEntity.markReconciledSaveChain(_options, reconciledChainRoot);
|
|
5242
|
+
const reconcileOutcome = await this.reconcileISAChainBeforeSave(_options);
|
|
5243
|
+
if (reconcileOutcome.kind === 'handled') {
|
|
5244
|
+
return reconcileOutcome.result;
|
|
5245
|
+
}
|
|
5246
|
+
}
|
|
4722
5247
|
// IS-A leaf delegation: if this entity has a child entity and we are NOT
|
|
4723
5248
|
// already being called as part of a parent chain save, delegate to the leaf.
|
|
4724
5249
|
// The leaf's Save() will then save the full chain (root → branch → leaf)
|
|
4725
5250
|
// using the existing IS-A parent chain orchestration.
|
|
4726
5251
|
if (this._childEntity && !_options.IsParentEntitySave) {
|
|
4727
|
-
|
|
5252
|
+
const leaf = this.LeafEntity;
|
|
5253
|
+
const leafSaved = await leaf.Save(_options);
|
|
5254
|
+
if (!leafSaved && currentResultCount === this.ResultHistory.length && leaf.LatestResult) {
|
|
5255
|
+
this.copyFailureResultFrom(leaf.LatestResult);
|
|
5256
|
+
}
|
|
5257
|
+
return leafSaved;
|
|
4728
5258
|
}
|
|
4729
5259
|
// IS-A orchestration: determine if this is the initiating save in a parent chain
|
|
4730
|
-
|
|
5260
|
+
// (or a standalone entity whose active SubtypeSelector.Driver resolves to a registered driver)
|
|
5261
|
+
const hasActiveDriver = !this._parentEntity &&
|
|
5262
|
+
!_options.IsParentEntitySave &&
|
|
5263
|
+
Boolean(this.EntityInfo?.SubtypeSelectorConfig?.Driver) &&
|
|
5264
|
+
(await this.ResolveSubtypeDriver()) !== null;
|
|
5265
|
+
const isISAInitiator = (Boolean(this._parentEntity) || hasActiveDriver) && !_options.IsParentEntitySave;
|
|
4731
5266
|
// Open (or join) a transaction scope for the parent chain. The provider arbitrates:
|
|
4732
5267
|
// if a transaction is already in flight — an application cascade, an enclosing graph
|
|
4733
5268
|
// save — this joins it as a savepoint rather than starting a second physical
|
|
@@ -4756,11 +5291,36 @@ export class BaseEntity {
|
|
|
4756
5291
|
parentSaveOptions.SkipEntityActions = _options.SkipEntityActions;
|
|
4757
5292
|
parentSaveOptions.ReplayOnly = _options.ReplayOnly;
|
|
4758
5293
|
parentSaveOptions.SkipOldValuesCheck = _options.SkipOldValuesCheck;
|
|
5294
|
+
if (_options.ConcurrencyBaseline) {
|
|
5295
|
+
const parentChainFieldNames = new Set();
|
|
5296
|
+
for (let anc = this._parentEntity; anc; anc = anc._parentEntity) {
|
|
5297
|
+
for (const f of anc.EntityInfo.Fields) {
|
|
5298
|
+
parentChainFieldNames.add(f.Name);
|
|
5299
|
+
parentChainFieldNames.add(f.CodeName);
|
|
5300
|
+
}
|
|
5301
|
+
}
|
|
5302
|
+
const filteredParentBaseline = {};
|
|
5303
|
+
let hasParentBaseline = false;
|
|
5304
|
+
for (const [k, v] of Object.entries(_options.ConcurrencyBaseline)) {
|
|
5305
|
+
if (parentChainFieldNames.has(k)) {
|
|
5306
|
+
filteredParentBaseline[k] = v;
|
|
5307
|
+
hasParentBaseline = true;
|
|
5308
|
+
}
|
|
5309
|
+
}
|
|
5310
|
+
if (hasParentBaseline) {
|
|
5311
|
+
parentSaveOptions.ConcurrencyBaseline = filteredParentBaseline;
|
|
5312
|
+
}
|
|
5313
|
+
}
|
|
5314
|
+
parentSaveOptions.ConcurrencyCheck = _options.ConcurrencyCheck;
|
|
4759
5315
|
parentSaveOptions.SkipAsyncValidation = _options.SkipAsyncValidation;
|
|
4760
5316
|
parentSaveOptions.IsParentEntitySave = true;
|
|
4761
5317
|
parentSaveOptions.ISAActiveChildEntityName = this.EntityInfo.Name;
|
|
4762
5318
|
const parentResult = await this._parentEntity.Save(parentSaveOptions); // we know parent entity exists hre
|
|
4763
5319
|
if (!parentResult) {
|
|
5320
|
+
// Capture parent failure BEFORE rollbackChainSave restores pre-save ResultHistory
|
|
5321
|
+
// on any ancestor that reached finalizeSave() before failing in AfterSave/commit.
|
|
5322
|
+
const parentLatest = this._parentEntity.LatestResult;
|
|
5323
|
+
const parentErrors = parentLatest?.Errors ?? [];
|
|
4764
5324
|
// Parent save failed — roll back if we started the transaction, and put back
|
|
4765
5325
|
// the levels above it that had already saved
|
|
4766
5326
|
await this.rollbackChainSave(part);
|
|
@@ -4772,8 +5332,6 @@ export class BaseEntity {
|
|
|
4772
5332
|
// the child never set fails with literally no message anywhere the caller can
|
|
4773
5333
|
// reach. Mirrors the transaction-group-failure and catch-block paths below.
|
|
4774
5334
|
if (currentResultCount === this.ResultHistory.length) {
|
|
4775
|
-
const parentLatest = this._parentEntity.LatestResult;
|
|
4776
|
-
const parentErrors = parentLatest?.Errors ?? [];
|
|
4777
5335
|
// A failed parent commonly reports its detail ONLY in Errors (validation
|
|
4778
5336
|
// failures leave Message empty), so fall back to the error text rather than
|
|
4779
5337
|
// handing the caller a message that says nothing.
|
|
@@ -4786,6 +5344,9 @@ export class BaseEntity {
|
|
|
4786
5344
|
`Failed to save parent entity '${this._parentEntity.EntityInfo?.Name}': ${detail}`;
|
|
4787
5345
|
// Surface the parent's field-level errors so the caller can act on them.
|
|
4788
5346
|
newResult.Errors = parentErrors;
|
|
5347
|
+
if (parentLatest?.ConcurrencyConflict) {
|
|
5348
|
+
newResult.ConcurrencyConflict = parentLatest.ConcurrencyConflict;
|
|
5349
|
+
}
|
|
4789
5350
|
// When `detail` was built from `parentErrors` (no parent Message), `Message` already renders
|
|
4790
5351
|
// them — say so, or CompleteMessage repeats every one.
|
|
4791
5352
|
newResult.MessageIncludesErrors = !parentLatest?.Message && parentErrors.length > 0;
|
|
@@ -4813,6 +5374,12 @@ export class BaseEntity {
|
|
|
4813
5374
|
}
|
|
4814
5375
|
}
|
|
4815
5376
|
if (_options.IgnoreDirtyState || initialDirtyState || _options.ReplayOnly) {
|
|
5377
|
+
if (!_options.ReplayOnly) {
|
|
5378
|
+
const gateError = EntityLifecyclePolicyEngine.Instance.CheckWritePermissionGate(this, this.IsSaved ? 'Update' : 'Create', this.ActiveUser, this.isDatabaseProvider());
|
|
5379
|
+
if (gateError) {
|
|
5380
|
+
throw new Error(gateError);
|
|
5381
|
+
}
|
|
5382
|
+
}
|
|
4816
5383
|
// Raise save_started event only when we're actually going to save
|
|
4817
5384
|
this.RaiseEvent('save_started', null, saveSubType);
|
|
4818
5385
|
if (!this.ProviderToUse) {
|
|
@@ -4824,8 +5391,16 @@ export class BaseEntity {
|
|
|
4824
5391
|
valResult.Success = true; // bypassing validation since we are in replay only....
|
|
4825
5392
|
}
|
|
4826
5393
|
else {
|
|
4827
|
-
// First run synchronous validation
|
|
4828
|
-
|
|
5394
|
+
// First run synchronous validation (suppressing sync subtype-driver validation
|
|
5395
|
+
// on self and already-saved IS-A ancestors so each level's validateSubtypeDriverAsync
|
|
5396
|
+
// runs its driver's Validate exactly once)
|
|
5397
|
+
this.setChainInSaveValidation(true);
|
|
5398
|
+
try {
|
|
5399
|
+
valResult = this.Validate();
|
|
5400
|
+
}
|
|
5401
|
+
finally {
|
|
5402
|
+
this.setChainInSaveValidation(false);
|
|
5403
|
+
}
|
|
4829
5404
|
// Determine if we should run async validation, in order of authority:
|
|
4830
5405
|
// 1. An explicit SkipAsyncValidation in the options.
|
|
4831
5406
|
// 2. An explicit DefaultSkipAsyncValidation override on the subclass.
|
|
@@ -4871,10 +5446,14 @@ export class BaseEntity {
|
|
|
4871
5446
|
// save in production: the class never overrode DefaultSkipAsyncValidation
|
|
4872
5447
|
// (which defaults to true) and no caller ever passed SkipAsyncValidation:false.
|
|
4873
5448
|
await this.validateCompanionsAsync(valResult);
|
|
5449
|
+
await this.validateSubtypeDriverAsync(valResult);
|
|
4874
5450
|
}
|
|
4875
5451
|
if (valResult.Success) {
|
|
4876
|
-
// Run registered PreSave hooks (e.g., tenant validation)
|
|
5452
|
+
// Run registered PreSave hooks (e.g., tenant validation) and subtype driver BeforeSave
|
|
4877
5453
|
await this.runPreSaveHooks();
|
|
5454
|
+
if (!_options.ReplayOnly) {
|
|
5455
|
+
await this.runSubtypeDriverBeforeSave();
|
|
5456
|
+
}
|
|
4878
5457
|
// Optimistic-UI hook: every pre-flight check (Validate, ValidateAsync,
|
|
4879
5458
|
// PreSave hooks) has passed and the DB write is imminent. Fire the optional
|
|
4880
5459
|
// OnValidated callback so a UI can render the now-known-valid change before
|
|
@@ -4907,6 +5486,7 @@ export class BaseEntity {
|
|
|
4907
5486
|
});
|
|
4908
5487
|
throw saveErr;
|
|
4909
5488
|
}
|
|
5489
|
+
const wasNewBeforeFinalize = !this.IsSaved;
|
|
4910
5490
|
if (!this.TransactionGroup) {
|
|
4911
5491
|
// no transaction group, so we have our results here
|
|
4912
5492
|
const result = this.finalizeSave(data, saveSubType, _options);
|
|
@@ -4917,8 +5497,14 @@ export class BaseEntity {
|
|
|
4917
5497
|
// chain around a leaf that reported failure: precisely the torn write
|
|
4918
5498
|
// this scope exists to prevent.
|
|
4919
5499
|
if (result) {
|
|
5500
|
+
if (!_options.ReplayOnly) {
|
|
5501
|
+
await this.runSubtypeDriverAfterSave(wasNewBeforeFinalize);
|
|
5502
|
+
}
|
|
4920
5503
|
await this.commitEntityTransactionScope();
|
|
4921
5504
|
BaseEntity.settleCommit(part);
|
|
5505
|
+
if (!_options.IsParentEntitySave && !_options.ReplayOnly) {
|
|
5506
|
+
await this.runChainPostSaveHooks();
|
|
5507
|
+
}
|
|
4922
5508
|
}
|
|
4923
5509
|
else {
|
|
4924
5510
|
await this.rollbackChainSave(part);
|
|
@@ -4926,13 +5512,39 @@ export class BaseEntity {
|
|
|
4926
5512
|
return result;
|
|
4927
5513
|
}
|
|
4928
5514
|
else {
|
|
5515
|
+
// Enlist SubtypeSelector.Driver AfterSave inside the open group transaction
|
|
5516
|
+
// so it runs atomically (and rolls back the group if it throws), matching direct Save().
|
|
5517
|
+
// Finalize the entity before running AfterSave so the hook observes IsSaved === true
|
|
5518
|
+
// and any server-returned values, restoring the pre-save snapshot if the group rolls back.
|
|
5519
|
+
let finalizedInAfterSaveHook = false;
|
|
5520
|
+
const preFinalizeSnapshots = BaseEntity.captureChains([this]);
|
|
5521
|
+
if (!_options.ReplayOnly && this.EntityInfo?.SubtypeSelectorConfig?.Driver) {
|
|
5522
|
+
this.TransactionGroup.RegisterInTransactionAfterSave(this, async (resultRecord) => {
|
|
5523
|
+
const finalized = this.finalizeSave(resultRecord, saveSubType, _options);
|
|
5524
|
+
if (!finalized) {
|
|
5525
|
+
return;
|
|
5526
|
+
}
|
|
5527
|
+
finalizedInAfterSaveHook = true;
|
|
5528
|
+
await this.runSubtypeDriverAfterSave(wasNewBeforeFinalize);
|
|
5529
|
+
});
|
|
5530
|
+
}
|
|
4929
5531
|
// we are part of a transaction group, so we return true and subscribe to the transaction groups' events and do the finalization work then
|
|
4930
5532
|
this.TransactionGroup.TransactionNotifications$.subscribe(({ success, results, error }) => {
|
|
4931
5533
|
const transItem = success && results ? results.find(r => r.Transaction.BaseEntity === this) : undefined;
|
|
4932
5534
|
if (transItem) {
|
|
4933
|
-
this.finalizeSave(transItem.Result, saveSubType, _options); // we get the resulting data from the transaction result, not data above as that will be blank when in a TG
|
|
5535
|
+
const finalized = finalizedInAfterSaveHook || this.finalizeSave(transItem.Result, saveSubType, _options); // we get the resulting data from the transaction result, not data above as that will be blank when in a TG
|
|
5536
|
+
if (finalized && !_options.ReplayOnly && !_options.IsParentEntitySave) {
|
|
5537
|
+
void this.runChainPostSaveHooks().catch(hookErr => {
|
|
5538
|
+
LogError(`PostSave hook failed after TransactionGroup commit on '${this.EntityInfo?.Name}': ${BaseEntity.errorText(hookErr)}`);
|
|
5539
|
+
});
|
|
5540
|
+
}
|
|
4934
5541
|
}
|
|
4935
5542
|
else {
|
|
5543
|
+
if (finalizedInAfterSaveHook) {
|
|
5544
|
+
this._pendingPostSave = null;
|
|
5545
|
+
BaseEntity.restoreChains(preFinalizeSnapshots);
|
|
5546
|
+
finalizedInAfterSaveHook = false;
|
|
5547
|
+
}
|
|
4936
5548
|
// The transaction group failed / rolled back, OR (should never happen) reported success
|
|
4937
5549
|
// without a result for this entity. Either way, RECORD the failure on ResultHistory rather
|
|
4938
5550
|
// than throwing. This handler runs ASYNCHRONOUSLY — after Save() has already returned true and
|
|
@@ -4970,6 +5582,9 @@ export class BaseEntity {
|
|
|
4970
5582
|
// empty scope writes nothing; it only releases the transaction.
|
|
4971
5583
|
await this.commitEntityTransactionScope();
|
|
4972
5584
|
BaseEntity.settleCommit(part);
|
|
5585
|
+
if (!_options.IsParentEntitySave && !_options.ReplayOnly) {
|
|
5586
|
+
await this.runChainPostSaveHooks();
|
|
5587
|
+
}
|
|
4973
5588
|
return true; // nothing to save since we're not dirty
|
|
4974
5589
|
}
|
|
4975
5590
|
}
|
|
@@ -4991,6 +5606,239 @@ export class BaseEntity {
|
|
|
4991
5606
|
}
|
|
4992
5607
|
return false;
|
|
4993
5608
|
}
|
|
5609
|
+
finally {
|
|
5610
|
+
if (activeSaveOptions && reconciledChainRoot) {
|
|
5611
|
+
BaseEntity.unmarkReconciledSaveChain(activeSaveOptions, reconciledChainRoot);
|
|
5612
|
+
}
|
|
5613
|
+
}
|
|
5614
|
+
}
|
|
5615
|
+
/**
|
|
5616
|
+
* Walks the IS-A chain from `RootEntity` downward before an initiating `Save()`, applying:
|
|
5617
|
+
* 1. `AutoEnsureOnSave` — creates missing child entities in the same transaction.
|
|
5618
|
+
* 2. Unsaved subtype switching — swaps an unsaved prospective child when the record's type changed before first save.
|
|
5619
|
+
* 3. `OnSubtypeChange` (`'Refuse'` | `'Replace'`) — enforces subtype-change policy when a saved record's
|
|
5620
|
+
* selector resolves to a different child entity (or to no child entity after its selector FK changed).
|
|
5621
|
+
* Moving from a type with no extension entity to one with an extension entity is always allowed.
|
|
5622
|
+
*/
|
|
5623
|
+
async reconcileISAChainBeforeSave(options) {
|
|
5624
|
+
let level = this.RootEntity;
|
|
5625
|
+
while (level) {
|
|
5626
|
+
if (!level.EntityInfo?.IsParentType || level.EntityInfo.AllowMultipleSubtypes) {
|
|
5627
|
+
level = level._childEntity;
|
|
5628
|
+
continue;
|
|
5629
|
+
}
|
|
5630
|
+
const selector = level.EntityInfo.SubtypeSelectorConfig;
|
|
5631
|
+
if (!selector) {
|
|
5632
|
+
level = level._childEntity;
|
|
5633
|
+
continue;
|
|
5634
|
+
}
|
|
5635
|
+
if (level.IsSaved) {
|
|
5636
|
+
// Ensure any existing persisted child row is discovered before deciding subtype-change policy
|
|
5637
|
+
if (!level._childEntity && !level._childEntityDiscoveryDone) {
|
|
5638
|
+
level._childEntityDiscoveryDone = true;
|
|
5639
|
+
const childCheck = await level.CheckForChildRecords();
|
|
5640
|
+
if (childCheck.HasChildren && childCheck.ChildEntityName) {
|
|
5641
|
+
await level.createAndLinkChildEntity(childCheck.ChildEntityName);
|
|
5642
|
+
}
|
|
5643
|
+
}
|
|
5644
|
+
const resolvedSubtype = await level.ResolveSubtypeEntityName();
|
|
5645
|
+
const currentChild = level._childEntity;
|
|
5646
|
+
if (currentChild && currentChild.IsSaved) {
|
|
5647
|
+
const changedToDifferentExtension = resolvedSubtype !== null && !sameEntityName(currentChild.EntityInfo.Name, resolvedSubtype);
|
|
5648
|
+
const changedToNoExtension = resolvedSubtype === null && level.isSubtypeSelectorFirstHopDirty(selector.Path);
|
|
5649
|
+
if (changedToDifferentExtension || changedToNoExtension) {
|
|
5650
|
+
const policy = selector.OnSubtypeChange ?? 'Refuse';
|
|
5651
|
+
if (policy === 'Refuse') {
|
|
5652
|
+
const targetDesc = resolvedSubtype ? `'${resolvedSubtype}'` : 'no extension entity';
|
|
5653
|
+
const msg = `Cannot change subtype of saved '${level.EntityInfo.Name}' record from ` +
|
|
5654
|
+
`'${currentChild.EntityInfo.Name}' to ${targetDesc} (OnSubtypeChange is 'Refuse').`;
|
|
5655
|
+
level.recordSaveFailure(msg);
|
|
5656
|
+
if (this !== level) {
|
|
5657
|
+
this.recordSaveFailure(msg);
|
|
5658
|
+
}
|
|
5659
|
+
return { kind: 'handled', result: false };
|
|
5660
|
+
}
|
|
5661
|
+
const replaced = await this.executeSubtypeReplacementSave(level, currentChild, resolvedSubtype, options);
|
|
5662
|
+
return { kind: 'handled', result: replaced };
|
|
5663
|
+
}
|
|
5664
|
+
}
|
|
5665
|
+
else if (currentChild && !currentChild.IsSaved) {
|
|
5666
|
+
// Unsaved prospective child attached for promotion on a saved parent
|
|
5667
|
+
if (!resolvedSubtype || !sameEntityName(currentChild.EntityInfo.Name, resolvedSubtype)) {
|
|
5668
|
+
const firstHopVal = level.getSubtypeSelectorFirstHopValue(selector.Path);
|
|
5669
|
+
const shouldDetach = resolvedSubtype !== null || (firstHopVal !== null && firstHopVal !== undefined && firstHopVal !== '');
|
|
5670
|
+
if (shouldDetach) {
|
|
5671
|
+
level.detachUnsavedChildSubtree();
|
|
5672
|
+
}
|
|
5673
|
+
}
|
|
5674
|
+
if (!level._childEntity && resolvedSubtype && selector.AutoEnsureOnSave) {
|
|
5675
|
+
await level.EnsureISAChild(resolvedSubtype);
|
|
5676
|
+
}
|
|
5677
|
+
}
|
|
5678
|
+
else if (!currentChild && resolvedSubtype && selector.AutoEnsureOnSave) {
|
|
5679
|
+
// Saved parent had no extension row; promoting from null -> ExtensionEntity is always allowed
|
|
5680
|
+
await level.EnsureISAChild(resolvedSubtype);
|
|
5681
|
+
}
|
|
5682
|
+
}
|
|
5683
|
+
else {
|
|
5684
|
+
// Unsaved parent record
|
|
5685
|
+
const resolvedSubtype = await level.ResolveSubtypeEntityName();
|
|
5686
|
+
if (level._childEntity && !level._childEntity.IsSaved) {
|
|
5687
|
+
if (!resolvedSubtype || !sameEntityName(level._childEntity.EntityInfo.Name, resolvedSubtype)) {
|
|
5688
|
+
const firstHopVal = level.getSubtypeSelectorFirstHopValue(selector.Path);
|
|
5689
|
+
const shouldDetach = resolvedSubtype !== null || (firstHopVal !== null && firstHopVal !== undefined && firstHopVal !== '');
|
|
5690
|
+
if (shouldDetach) {
|
|
5691
|
+
level.detachUnsavedChildSubtree();
|
|
5692
|
+
}
|
|
5693
|
+
}
|
|
5694
|
+
}
|
|
5695
|
+
if (!level._childEntity && resolvedSubtype && selector.AutoEnsureOnSave) {
|
|
5696
|
+
await level.EnsureISAChild(resolvedSubtype);
|
|
5697
|
+
}
|
|
5698
|
+
}
|
|
5699
|
+
level = level._childEntity;
|
|
5700
|
+
}
|
|
5701
|
+
return { kind: 'proceed' };
|
|
5702
|
+
}
|
|
5703
|
+
/**
|
|
5704
|
+
* Executes an atomic `OnSubtypeChange: 'Replace'` transition: deletes `oldChild` (and any deeper
|
|
5705
|
+
* child subtree, without cascading up to `levelWithReplacement`), attaches `resolvedSubtype` if
|
|
5706
|
+
* non-null, and saves the updated chain — all inside one `EntityTransactionScope` and `UnitOfWork`.
|
|
5707
|
+
*/
|
|
5708
|
+
async executeSubtypeReplacementSave(levelWithReplacement, oldChild, resolvedSubtype, options) {
|
|
5709
|
+
const root = this.RootEntity;
|
|
5710
|
+
const provider = root.ProviderToUse;
|
|
5711
|
+
const enclosing = this._unitOfWork;
|
|
5712
|
+
let scope = null;
|
|
5713
|
+
let part = null;
|
|
5714
|
+
let attachedNewChild = null;
|
|
5715
|
+
try {
|
|
5716
|
+
if (!root.TransactionGroup && provider?.SupportsEntityTransactions === true && provider.BeginEntityTransaction) {
|
|
5717
|
+
scope = await provider.BeginEntityTransaction();
|
|
5718
|
+
}
|
|
5719
|
+
if (!root.TransactionGroup && (scope || provider?.SupportsEntityTransactions !== true)) {
|
|
5720
|
+
part = BaseEntity.beginUnitOfWork(enclosing, BaseEntity.captureChains([root, oldChild]));
|
|
5721
|
+
}
|
|
5722
|
+
const unit = part?.unit ?? enclosing;
|
|
5723
|
+
// Detach oldChild from levelWithReplacement so deleting oldChild deletes only the old
|
|
5724
|
+
// child subtree (logging Record Changes for the deleted child row(s)) and never cascades
|
|
5725
|
+
// upward to levelWithReplacement.
|
|
5726
|
+
levelWithReplacement._childEntity = null;
|
|
5727
|
+
oldChild._parentEntity = null;
|
|
5728
|
+
const deleteOptions = new EntityDeleteOptions();
|
|
5729
|
+
deleteOptions.SkipEntityAIActions = options.SkipEntityAIActions;
|
|
5730
|
+
deleteOptions.SkipEntityActions = options.SkipEntityActions;
|
|
5731
|
+
deleteOptions.ReplayOnly = options.ReplayOnly;
|
|
5732
|
+
const deleted = await BaseEntity.inUnitOfWork(oldChild, unit, c => c.Delete(deleteOptions));
|
|
5733
|
+
if (!deleted) {
|
|
5734
|
+
oldChild._parentEntity = levelWithReplacement;
|
|
5735
|
+
levelWithReplacement._childEntity = oldChild;
|
|
5736
|
+
await scope?.Rollback();
|
|
5737
|
+
BaseEntity.settleRollback(part);
|
|
5738
|
+
const errMsg = oldChild.LatestResult?.Message ||
|
|
5739
|
+
`Failed to delete replaced subtype '${oldChild.EntityInfo.Name}' on '${levelWithReplacement.EntityInfo.Name}'.`;
|
|
5740
|
+
levelWithReplacement.recordSaveFailure(errMsg, oldChild.LatestResult?.Errors);
|
|
5741
|
+
if (this !== levelWithReplacement) {
|
|
5742
|
+
this.recordSaveFailure(errMsg, oldChild.LatestResult?.Errors);
|
|
5743
|
+
}
|
|
5744
|
+
return false;
|
|
5745
|
+
}
|
|
5746
|
+
if (resolvedSubtype) {
|
|
5747
|
+
attachedNewChild = await levelWithReplacement.EnsureISAChild(resolvedSubtype);
|
|
5748
|
+
// Recursively reconcile deeper levels if the newly attached child is also a parent type
|
|
5749
|
+
let sub = attachedNewChild;
|
|
5750
|
+
while (sub) {
|
|
5751
|
+
const subSelector = sub.EntityInfo?.SubtypeSelectorConfig;
|
|
5752
|
+
if (sub.EntityInfo?.IsParentType && !sub.EntityInfo.AllowMultipleSubtypes && !sub._childEntity && subSelector?.AutoEnsureOnSave) {
|
|
5753
|
+
const grandChildName = await sub.ResolveSubtypeEntityName();
|
|
5754
|
+
if (grandChildName) {
|
|
5755
|
+
await sub.EnsureISAChild(grandChildName);
|
|
5756
|
+
}
|
|
5757
|
+
}
|
|
5758
|
+
sub = sub._childEntity;
|
|
5759
|
+
}
|
|
5760
|
+
}
|
|
5761
|
+
const leafToSave = root.LeafEntity;
|
|
5762
|
+
const saveOpts = Object.assign(new EntitySaveOptions(), options);
|
|
5763
|
+
BaseEntity.markReconciledSaveChain(saveOpts, root);
|
|
5764
|
+
let saved;
|
|
5765
|
+
try {
|
|
5766
|
+
saved = await BaseEntity.inUnitOfWork(leafToSave, unit, target => target._innerSave(saveOpts));
|
|
5767
|
+
}
|
|
5768
|
+
finally {
|
|
5769
|
+
BaseEntity.unmarkReconciledSaveChain(saveOpts, root);
|
|
5770
|
+
}
|
|
5771
|
+
if (!saved) {
|
|
5772
|
+
if (attachedNewChild) {
|
|
5773
|
+
attachedNewChild._parentEntity = null;
|
|
5774
|
+
levelWithReplacement._childEntity = null;
|
|
5775
|
+
}
|
|
5776
|
+
oldChild._parentEntity = levelWithReplacement;
|
|
5777
|
+
levelWithReplacement._childEntity = oldChild;
|
|
5778
|
+
await scope?.Rollback();
|
|
5779
|
+
BaseEntity.settleRollback(part);
|
|
5780
|
+
if (leafToSave.LatestResult) {
|
|
5781
|
+
if (levelWithReplacement !== leafToSave) {
|
|
5782
|
+
levelWithReplacement.copyFailureResultFrom(leafToSave.LatestResult);
|
|
5783
|
+
}
|
|
5784
|
+
if (this !== leafToSave && this !== levelWithReplacement) {
|
|
5785
|
+
this.copyFailureResultFrom(leafToSave.LatestResult);
|
|
5786
|
+
}
|
|
5787
|
+
}
|
|
5788
|
+
return false;
|
|
5789
|
+
}
|
|
5790
|
+
await scope?.Commit();
|
|
5791
|
+
BaseEntity.settleCommit(part);
|
|
5792
|
+
return true;
|
|
5793
|
+
}
|
|
5794
|
+
catch (err) {
|
|
5795
|
+
if (attachedNewChild) {
|
|
5796
|
+
attachedNewChild._parentEntity = null;
|
|
5797
|
+
levelWithReplacement._childEntity = null;
|
|
5798
|
+
}
|
|
5799
|
+
oldChild._parentEntity = levelWithReplacement;
|
|
5800
|
+
levelWithReplacement._childEntity = oldChild;
|
|
5801
|
+
try {
|
|
5802
|
+
await scope?.Rollback();
|
|
5803
|
+
}
|
|
5804
|
+
catch (rbErr) {
|
|
5805
|
+
LogError(`Error rolling back subtype replacement scope on '${root.EntityInfo?.Name}': ${BaseEntity.errorText(rbErr)}`);
|
|
5806
|
+
}
|
|
5807
|
+
BaseEntity.settleRollback(part);
|
|
5808
|
+
const msg = BaseEntity.errorText(err);
|
|
5809
|
+
const errors = err?.Errors;
|
|
5810
|
+
levelWithReplacement.recordSaveFailure(msg, errors);
|
|
5811
|
+
if (this !== levelWithReplacement) {
|
|
5812
|
+
this.recordSaveFailure(msg, errors);
|
|
5813
|
+
}
|
|
5814
|
+
return false;
|
|
5815
|
+
}
|
|
5816
|
+
}
|
|
5817
|
+
recordSaveFailure(message, errors) {
|
|
5818
|
+
const entry = new BaseEntityResult();
|
|
5819
|
+
entry.StartedAt = new Date();
|
|
5820
|
+
entry.EndedAt = new Date();
|
|
5821
|
+
entry.Success = false;
|
|
5822
|
+
entry.Type = this.IsSaved ? 'update' : 'create';
|
|
5823
|
+
entry.Message = message;
|
|
5824
|
+
entry.Errors = errors ? [...errors] : [];
|
|
5825
|
+
entry.OriginalValues = this.Fields.map(f => ({ FieldName: f.CodeName, Value: f.OldValue }));
|
|
5826
|
+
this.RegisterResultHistoryEntry(entry);
|
|
5827
|
+
}
|
|
5828
|
+
copyFailureResultFrom(source) {
|
|
5829
|
+
const detail = source.Message ||
|
|
5830
|
+
(source.Errors ?? []).map(e => e?.Message ?? String(e)).filter(Boolean).join('; ') ||
|
|
5831
|
+
'Child entity save failed';
|
|
5832
|
+
const entry = new BaseEntityResult();
|
|
5833
|
+
entry.StartedAt = source.StartedAt ?? new Date();
|
|
5834
|
+
entry.EndedAt = source.EndedAt ?? new Date();
|
|
5835
|
+
entry.Success = false;
|
|
5836
|
+
entry.Type = this.IsSaved ? 'update' : 'create';
|
|
5837
|
+
entry.Message = detail;
|
|
5838
|
+
entry.Errors = source.Errors ? [...source.Errors] : [];
|
|
5839
|
+
entry.MessageIncludesErrors = !source.Message && entry.Errors.length > 0;
|
|
5840
|
+
entry.OriginalValues = this.Fields.map(f => ({ FieldName: f.CodeName, Value: f.OldValue }));
|
|
5841
|
+
this.RegisterResultHistoryEntry(entry);
|
|
4994
5842
|
}
|
|
4995
5843
|
/**
|
|
4996
5844
|
* Runs all registered PreSave hooks. If any hook returns false or a string
|
|
@@ -5008,6 +5856,104 @@ export class BaseEntity {
|
|
|
5008
5856
|
}
|
|
5009
5857
|
}
|
|
5010
5858
|
}
|
|
5859
|
+
/**
|
|
5860
|
+
* Runs all registered PostSave hooks for this single entity after a committed save.
|
|
5861
|
+
* Errors thrown by PostSave hooks are logged and never abort the already-committed save.
|
|
5862
|
+
*/
|
|
5863
|
+
async runPostSaveHooks(changedFieldNames, saveSubType) {
|
|
5864
|
+
const postSaveHooks = GetDataHooks('PostSave');
|
|
5865
|
+
if (postSaveHooks.length === 0) {
|
|
5866
|
+
return;
|
|
5867
|
+
}
|
|
5868
|
+
for (const hook of postSaveHooks) {
|
|
5869
|
+
try {
|
|
5870
|
+
await hook(this, this.ActiveUser, changedFieldNames, saveSubType);
|
|
5871
|
+
}
|
|
5872
|
+
catch (hookErr) {
|
|
5873
|
+
LogError(`PostSave hook failed on '${this.EntityInfo?.Name}': ${BaseEntity.errorText(hookErr)}`);
|
|
5874
|
+
}
|
|
5875
|
+
}
|
|
5876
|
+
}
|
|
5877
|
+
/**
|
|
5878
|
+
* Runs registered PostSave hooks across every finalized node in this entity's IS-A chain
|
|
5879
|
+
* once the outermost save scope has committed. Propagates inherited dirty field names from
|
|
5880
|
+
* ancestors to live child nodes so observers on either level see modified fields.
|
|
5881
|
+
*/
|
|
5882
|
+
async runChainPostSaveHooks() {
|
|
5883
|
+
const postSaveHooks = GetDataHooks('PostSave');
|
|
5884
|
+
const chain = [];
|
|
5885
|
+
let cur = this.RootEntity;
|
|
5886
|
+
while (cur) {
|
|
5887
|
+
chain.push(cur);
|
|
5888
|
+
cur = cur._childEntity;
|
|
5889
|
+
}
|
|
5890
|
+
const unionChanged = new Set();
|
|
5891
|
+
let chainSaveSubType = null;
|
|
5892
|
+
for (const node of chain) {
|
|
5893
|
+
if (node._pendingPostSave) {
|
|
5894
|
+
for (const name of node._pendingPostSave.changedFieldNames) {
|
|
5895
|
+
unionChanged.add(name);
|
|
5896
|
+
}
|
|
5897
|
+
if (chainSaveSubType === null) {
|
|
5898
|
+
chainSaveSubType = node._pendingPostSave.saveSubType;
|
|
5899
|
+
}
|
|
5900
|
+
}
|
|
5901
|
+
}
|
|
5902
|
+
const pendingByNode = new Map();
|
|
5903
|
+
for (const node of chain) {
|
|
5904
|
+
if (node._pendingPostSave) {
|
|
5905
|
+
pendingByNode.set(node, node._pendingPostSave);
|
|
5906
|
+
node._pendingPostSave = null;
|
|
5907
|
+
}
|
|
5908
|
+
}
|
|
5909
|
+
if (postSaveHooks.length === 0 || (pendingByNode.size === 0 && unionChanged.size === 0)) {
|
|
5910
|
+
return;
|
|
5911
|
+
}
|
|
5912
|
+
const allChangedArray = Array.from(unionChanged);
|
|
5913
|
+
for (const node of chain) {
|
|
5914
|
+
const ownPending = pendingByNode.get(node);
|
|
5915
|
+
const nodeFieldNames = new Set(node.EntityInfo.Fields.map(f => f.Name));
|
|
5916
|
+
const effectiveChanged = allChangedArray.filter(name => nodeFieldNames.has(name));
|
|
5917
|
+
if (!ownPending && effectiveChanged.length === 0) {
|
|
5918
|
+
continue;
|
|
5919
|
+
}
|
|
5920
|
+
const subType = ownPending?.saveSubType ?? chainSaveSubType ?? 'update';
|
|
5921
|
+
await node.runPostSaveHooks(effectiveChanged, subType);
|
|
5922
|
+
}
|
|
5923
|
+
}
|
|
5924
|
+
/**
|
|
5925
|
+
* Runs all registered PreDelete hooks. If any hook returns false or a string
|
|
5926
|
+
* (error message), the delete is rejected by throwing an Error.
|
|
5927
|
+
*/
|
|
5928
|
+
async runPreDeleteHooks() {
|
|
5929
|
+
const preDeleteHooks = GetDataHooks('PreDelete');
|
|
5930
|
+
for (const hook of preDeleteHooks) {
|
|
5931
|
+
const hookResult = await hook(this, this.ActiveUser);
|
|
5932
|
+
if (hookResult === false) {
|
|
5933
|
+
throw new Error('Delete rejected by pre-delete hook');
|
|
5934
|
+
}
|
|
5935
|
+
if (typeof hookResult === 'string') {
|
|
5936
|
+
throw new Error(hookResult);
|
|
5937
|
+
}
|
|
5938
|
+
}
|
|
5939
|
+
}
|
|
5940
|
+
/**
|
|
5941
|
+
* Returns true when `ProviderToUse` is a server-side database provider (`ProviderType.Database`)
|
|
5942
|
+
* rather than a client network transport (`ProviderType.Network`).
|
|
5943
|
+
*/
|
|
5944
|
+
isDatabaseProvider() {
|
|
5945
|
+
const provider = this.ProviderToUse;
|
|
5946
|
+
if (!provider) {
|
|
5947
|
+
return false;
|
|
5948
|
+
}
|
|
5949
|
+
if (provider.ProviderType === ProviderType.Database) {
|
|
5950
|
+
return true;
|
|
5951
|
+
}
|
|
5952
|
+
if (provider.ProviderType === ProviderType.Network) {
|
|
5953
|
+
return false;
|
|
5954
|
+
}
|
|
5955
|
+
return 'ExecuteSQL' in provider && typeof provider.ExecuteSQL === 'function';
|
|
5956
|
+
}
|
|
5011
5957
|
/**
|
|
5012
5958
|
* Determines whether the parent entity should be deleted after this child entity
|
|
5013
5959
|
* has been deleted. For overlapping subtype parents (AllowMultipleSubtypes = true),
|
|
@@ -5036,6 +5982,7 @@ export class BaseEntity {
|
|
|
5036
5982
|
if (data) {
|
|
5037
5983
|
// The 'save' event names the fields this save wrote; init() below clears every dirty flag.
|
|
5038
5984
|
const changedFieldNames = this.dirtyFieldNames();
|
|
5985
|
+
const postSaveChangedFields = this.computePostSaveChangedFieldNames(saveSubType, changedFieldNames);
|
|
5039
5986
|
const effectiveReturnMode = options?.SaveReturnMode ?? this.EntityInfo.SaveReturnMode;
|
|
5040
5987
|
const hasGetAll = (val) => val instanceof BaseEntity || typeof val.GetAll === 'function';
|
|
5041
5988
|
const rawFieldData = hasGetAll(data) ? data.GetAll() : data;
|
|
@@ -5079,6 +6026,10 @@ export class BaseEntity {
|
|
|
5079
6026
|
result.NewValues = this.Fields.map(f => { return { FieldName: f.CodeName, Value: f.Value }; }); // set the latest values here
|
|
5080
6027
|
// Cache the record name for faster lookups (updates cache with potentially new name)
|
|
5081
6028
|
this.cacheRecordName();
|
|
6029
|
+
this._pendingPostSave = {
|
|
6030
|
+
changedFieldNames: postSaveChangedFields,
|
|
6031
|
+
saveSubType: saveSubType === 'create' ? 'create' : 'update',
|
|
6032
|
+
};
|
|
5082
6033
|
this.RaiseEvent('save', null, saveSubType, changedFieldNames);
|
|
5083
6034
|
return true;
|
|
5084
6035
|
}
|
|
@@ -5092,7 +6043,7 @@ export class BaseEntity {
|
|
|
5092
6043
|
get ActiveUser() {
|
|
5093
6044
|
// Use the entity's bound provider (per-instance) before falling back to the global
|
|
5094
6045
|
// default — multi-provider correctness for server requests with per-request users.
|
|
5095
|
-
return this.ContextCurrentUser || this.ProviderToUse?.CurrentUser || Metadata.Provider
|
|
6046
|
+
return this.ContextCurrentUser || this.ProviderToUse?.CurrentUser || Metadata.Provider?.CurrentUser; // global-provider-ok: final fallback when no provider is bound
|
|
5096
6047
|
}
|
|
5097
6048
|
/**
|
|
5098
6049
|
* Offers the record's name to the provider for later synchronous lookups. Only a provider that
|
|
@@ -5437,7 +6388,7 @@ export class BaseEntity {
|
|
|
5437
6388
|
if (!this.IsSaved) {
|
|
5438
6389
|
this.init(); // wipe out current data if we're loading on top of existing record
|
|
5439
6390
|
}
|
|
5440
|
-
|
|
6391
|
+
const data = await this.readRowForLoad(CompositeKey, EntityRelationshipsToLoad);
|
|
5441
6392
|
this.discardJSONFieldObjects(); // a reload replaces the record's data
|
|
5442
6393
|
if (!data) {
|
|
5443
6394
|
// A subtype-hint probe asks whether this row exists, so "no" is an answer, not an error
|
|
@@ -5446,65 +6397,95 @@ export class BaseEntity {
|
|
|
5446
6397
|
}
|
|
5447
6398
|
return false; // no data loaded, return false
|
|
5448
6399
|
}
|
|
5449
|
-
|
|
5450
|
-
// did not narrow its SELECT (see narrowHydrationSource).
|
|
5451
|
-
data = this.narrowHydrationSource(data);
|
|
5452
|
-
// IS-A: hydrate parent chain from loaded data before populating self.
|
|
5453
|
-
// Hydrate resets each parent via init() (giving fresh _NeverSet=true on PK fields)
|
|
5454
|
-
// then populates from data. This must happen before self's SetMany so parents
|
|
5455
|
-
// are in clean state when they receive routed field values.
|
|
5456
|
-
if (this._parentEntity) {
|
|
5457
|
-
this._parentEntity.Hydrate(data);
|
|
5458
|
-
}
|
|
5459
|
-
// Reset _NeverSet on all fields before SetMany so that ReadOnly/virtual fields
|
|
5460
|
-
// (e.g. view-computed columns like PrimaryAddressLine1, PrimaryEmail) can be
|
|
5461
|
-
// updated on reload. Without this, the EntityField Value setter silently drops
|
|
5462
|
-
// writes to ReadOnly fields after the initial load, meaning InnerLoad called a
|
|
5463
|
-
// second time (e.g. to refresh denormalized data after a related entity changed)
|
|
5464
|
-
// would fail to update those fields even though the provider returned fresh data.
|
|
5465
|
-
for (const f of this.Fields) {
|
|
5466
|
-
f.ResetNeverSetFlag();
|
|
5467
|
-
}
|
|
5468
|
-
this.SetMany(data, false, true, true); // don't ignore non-existent fields, but DO replace old values
|
|
5469
|
-
// InnerLoad is a hydration entry point: any field the provider's row omitted (e.g.
|
|
5470
|
-
// a client-side load whose server response stripped read-denied fields) is
|
|
5471
|
-
// not-loaded, so its constructor state never masquerades as data on the next save.
|
|
5472
|
-
this.markFieldsOmittedBySourceAsNotLoaded(data);
|
|
5473
|
-
if (EntityRelationshipsToLoad) {
|
|
5474
|
-
for (let relationship of EntityRelationshipsToLoad) {
|
|
5475
|
-
if (data[relationship]) {
|
|
5476
|
-
// we have some data, put into an array for ease of access
|
|
5477
|
-
this[relationship] = data[relationship];
|
|
5478
|
-
}
|
|
5479
|
-
}
|
|
5480
|
-
}
|
|
5481
|
-
this._recordLoaded = true;
|
|
5482
|
-
this._everSaved = true; // Mark as saved since we loaded from database
|
|
5483
|
-
this._compositeKey = CompositeKey; // set the composite key to the one we just loaded
|
|
5484
|
-
// Cache the record name for faster lookups
|
|
5485
|
-
this.cacheRecordName();
|
|
5486
|
-
// IS-A: discover child entity records after load completes.
|
|
5487
|
-
// This populates _childEntity so Save/Delete can delegate to the leaf.
|
|
5488
|
-
// Only runs for parent-type entities; idempotent via _childEntityDiscoveryDone.
|
|
5489
|
-
await this.InitializeChildEntity();
|
|
5490
|
-
// Companions declared Load:'immediate' populate here — and ONLY here.
|
|
5491
|
-
//
|
|
5492
|
-
// Deliberately not in LoadFromData(): that is the per-row materialization path for
|
|
5493
|
-
// RunView(ResultType:'entity_object'), so an eager child query there becomes one query
|
|
5494
|
-
// per row of every view. That is a live N+1 in production accounting code today
|
|
5495
|
-
// (JournalEntryEntityServer.LoadFromData → LoadLines), and excluding it here is the
|
|
5496
|
-
// structural fix. Set-oriented eager loading is served by RunView's batched child
|
|
5497
|
-
// loading, which issues one WHERE fk IN (...) for the whole result set.
|
|
5498
|
-
await this.loadEagerCompanions();
|
|
5499
|
-
// Raise load completion event
|
|
5500
|
-
this.RaiseEvent('load_complete', { CompositeKey });
|
|
5501
|
-
return true;
|
|
6400
|
+
return await this.applyLoadedRowData(data, CompositeKey, EntityRelationshipsToLoad);
|
|
5502
6401
|
}
|
|
5503
6402
|
finally {
|
|
5504
6403
|
// Always clear loading state when done, regardless of success or failure
|
|
5505
6404
|
this._isLoading = false;
|
|
5506
6405
|
}
|
|
5507
6406
|
}
|
|
6407
|
+
/**
|
|
6408
|
+
* Hydrates this entity from an already-fetched database row using the exact same permission,
|
|
6409
|
+
* FLS-narrowing, IS-A parent/child, and eager-companion contract as {@link InnerLoad}.
|
|
6410
|
+
* Used by batched loaders (e.g. `RelatedRecordCollection.Deserialize`) to avoid N individual queries.
|
|
6411
|
+
*/
|
|
6412
|
+
async HydrateFromRow(data, compositeKey, entityRelationshipsToLoad = null) {
|
|
6413
|
+
if (!this.ProviderToUse) {
|
|
6414
|
+
throw new Error('No provider set');
|
|
6415
|
+
}
|
|
6416
|
+
const valResult = compositeKey.Validate();
|
|
6417
|
+
if (!valResult || !valResult.IsValid) {
|
|
6418
|
+
throw new Error(`Invalid CompositeKey passed to BaseEntity.HydrateFromRow(${this.EntityInfo.Name}): ${valResult.ErrorMessage}`);
|
|
6419
|
+
}
|
|
6420
|
+
this.CheckPermissions(EntityPermissionType.Read, true);
|
|
6421
|
+
this._isLoading = true;
|
|
6422
|
+
this.RaiseEvent('load_started', { CompositeKey: compositeKey });
|
|
6423
|
+
try {
|
|
6424
|
+
if (!this.IsSaved) {
|
|
6425
|
+
this.init();
|
|
6426
|
+
}
|
|
6427
|
+
this.discardJSONFieldObjects();
|
|
6428
|
+
return await this.applyLoadedRowData(data, compositeKey, entityRelationshipsToLoad);
|
|
6429
|
+
}
|
|
6430
|
+
finally {
|
|
6431
|
+
this._isLoading = false;
|
|
6432
|
+
}
|
|
6433
|
+
}
|
|
6434
|
+
/** Shared post-read hydration used by both {@link InnerLoad} and {@link HydrateFromRow}. */
|
|
6435
|
+
async applyLoadedRowData(rawData, compositeKey, entityRelationshipsToLoad = null) {
|
|
6436
|
+
// Field security: denied values never enter this object, even from a provider that
|
|
6437
|
+
// did not narrow its SELECT (see narrowHydrationSource).
|
|
6438
|
+
const data = this.narrowHydrationSource(rawData);
|
|
6439
|
+
// IS-A: hydrate parent chain from loaded data before populating self when loading
|
|
6440
|
+
// upward from a child/leaf instance. Skipped when an already-loaded parent links a
|
|
6441
|
+
// child downward so the parent's virtual view columns are not cleared.
|
|
6442
|
+
if (this._parentEntity && !this._skipParentChainHydration) {
|
|
6443
|
+
this._parentEntity.Hydrate(data);
|
|
6444
|
+
}
|
|
6445
|
+
// Reset _NeverSet on all fields before SetMany so that ReadOnly/virtual fields
|
|
6446
|
+
// (e.g. view-computed columns like PrimaryAddressLine1, PrimaryEmail) can be
|
|
6447
|
+
// updated on reload. Without this, the EntityField Value setter silently drops
|
|
6448
|
+
// writes to ReadOnly fields after the initial load, meaning InnerLoad called a
|
|
6449
|
+
// second time (e.g. to refresh denormalized data after a related entity changed)
|
|
6450
|
+
// would fail to update those fields even though the provider returned fresh data.
|
|
6451
|
+
for (const f of this.Fields) {
|
|
6452
|
+
f.ResetNeverSetFlag();
|
|
6453
|
+
}
|
|
6454
|
+
this.SetMany(data, false, true, true); // don't ignore non-existent fields, but DO replace old values
|
|
6455
|
+
// InnerLoad is a hydration entry point: any field the provider's row omitted (e.g.
|
|
6456
|
+
// a client-side load whose server response stripped read-denied fields) is
|
|
6457
|
+
// not-loaded, so its constructor state never masquerades as data on the next save.
|
|
6458
|
+
this.markFieldsOmittedBySourceAsNotLoaded(data);
|
|
6459
|
+
if (entityRelationshipsToLoad) {
|
|
6460
|
+
for (const relationship of entityRelationshipsToLoad) {
|
|
6461
|
+
if (data[relationship]) {
|
|
6462
|
+
// we have some data, put into an array for ease of access
|
|
6463
|
+
this[relationship] = data[relationship];
|
|
6464
|
+
}
|
|
6465
|
+
}
|
|
6466
|
+
}
|
|
6467
|
+
this._recordLoaded = true;
|
|
6468
|
+
this._everSaved = true; // Mark as saved since we loaded from database
|
|
6469
|
+
this._compositeKey = compositeKey; // set the composite key to the one we just loaded
|
|
6470
|
+
// Cache the record name for faster lookups
|
|
6471
|
+
this.cacheRecordName();
|
|
6472
|
+
// IS-A: discover child entity records after load completes.
|
|
6473
|
+
// This populates _childEntity so Save/Delete can delegate to the leaf.
|
|
6474
|
+
// Only runs for parent-type entities; idempotent via _childEntityDiscoveryDone.
|
|
6475
|
+
await this.InitializeChildEntity();
|
|
6476
|
+
// Companions declared Load:'immediate' populate here — and ONLY here.
|
|
6477
|
+
//
|
|
6478
|
+
// Deliberately not in LoadFromData(): that is the per-row materialization path for
|
|
6479
|
+
// RunView(ResultType:'entity_object'), so an eager child query there becomes one query
|
|
6480
|
+
// per row of every view. That is a live N+1 in production accounting code today
|
|
6481
|
+
// (JournalEntryEntityServer.LoadFromData → LoadLines), and excluding it here is the
|
|
6482
|
+
// structural fix. Set-oriented eager loading is served by RunView's batched child
|
|
6483
|
+
// loading, which issues one WHERE fk IN (...) for the whole result set.
|
|
6484
|
+
await this.loadEagerCompanions();
|
|
6485
|
+
// Raise load completion event
|
|
6486
|
+
this.RaiseEvent('load_complete', { CompositeKey: compositeKey });
|
|
6487
|
+
return true;
|
|
6488
|
+
}
|
|
5508
6489
|
/**
|
|
5509
6490
|
* The provider's read of the row {@link InnerLoad} loads. While this record is a subtype-hint
|
|
5510
6491
|
* probe, a throw from the read is recorded on the probe before it propagates, so the parent
|
|
@@ -6587,11 +7568,62 @@ export class BaseEntity {
|
|
|
6587
7568
|
await this.DeserializeCompanions(payloads);
|
|
6588
7569
|
}
|
|
6589
7570
|
}
|
|
7571
|
+
/**
|
|
7572
|
+
* Walks this instance's prototype chain up to (but excluding) `BaseEntity.prototype` and
|
|
7573
|
+
* `Object.prototype` to resolve the most-derived property `get` and `set` accessors for
|
|
7574
|
+
* `codeName`. Resolving `get` and `set` independently supports multi-level subclasses where an
|
|
7575
|
+
* intermediate class defines both and a leaf subclass overrides only `set` (or only `get`).
|
|
7576
|
+
*/
|
|
7577
|
+
resolveSubclassFieldAccessors(codeName) {
|
|
7578
|
+
let getter;
|
|
7579
|
+
let setter;
|
|
7580
|
+
let proto = Object.getPrototypeOf(this);
|
|
7581
|
+
while (proto && proto !== BaseEntity.prototype && proto !== Object.prototype && (!getter || !setter)) {
|
|
7582
|
+
const desc = Object.getOwnPropertyDescriptor(proto, codeName);
|
|
7583
|
+
if (desc) {
|
|
7584
|
+
if (!getter && typeof desc.get === 'function') {
|
|
7585
|
+
getter = desc.get;
|
|
7586
|
+
}
|
|
7587
|
+
if (!setter && typeof desc.set === 'function') {
|
|
7588
|
+
setter = desc.set;
|
|
7589
|
+
}
|
|
7590
|
+
}
|
|
7591
|
+
proto = Object.getPrototypeOf(proto);
|
|
7592
|
+
}
|
|
7593
|
+
return { get: getter, set: setter };
|
|
7594
|
+
}
|
|
6590
7595
|
getJSONFieldBinding(fieldName) {
|
|
6591
7596
|
this._jsonFieldBindings ??= new Map();
|
|
6592
7597
|
let binding = this._jsonFieldBindings.get(fieldName);
|
|
6593
7598
|
if (!binding) {
|
|
6594
|
-
|
|
7599
|
+
const codeName = this.EntityInfo?.FieldByName(fieldName)?.CodeName ?? fieldName;
|
|
7600
|
+
const accessors = this.resolveSubclassFieldAccessors(codeName);
|
|
7601
|
+
let inAccessorRead = false;
|
|
7602
|
+
let inAccessorWrite = false;
|
|
7603
|
+
binding = new JSONFieldBinding(fieldName, () => {
|
|
7604
|
+
if (!inAccessorRead && accessors.get) {
|
|
7605
|
+
inAccessorRead = true;
|
|
7606
|
+
try {
|
|
7607
|
+
return accessors.get.call(this);
|
|
7608
|
+
}
|
|
7609
|
+
finally {
|
|
7610
|
+
inAccessorRead = false;
|
|
7611
|
+
}
|
|
7612
|
+
}
|
|
7613
|
+
return this.Get(fieldName);
|
|
7614
|
+
}, (raw) => {
|
|
7615
|
+
if (!inAccessorWrite && accessors.set) {
|
|
7616
|
+
inAccessorWrite = true;
|
|
7617
|
+
try {
|
|
7618
|
+
accessors.set.call(this, raw);
|
|
7619
|
+
return;
|
|
7620
|
+
}
|
|
7621
|
+
finally {
|
|
7622
|
+
inAccessorWrite = false;
|
|
7623
|
+
}
|
|
7624
|
+
}
|
|
7625
|
+
this.Set(fieldName, raw);
|
|
7626
|
+
});
|
|
6595
7627
|
this._jsonFieldBindings.set(fieldName, binding);
|
|
6596
7628
|
}
|
|
6597
7629
|
return binding;
|
|
@@ -6671,6 +7703,11 @@ export class BaseEntity {
|
|
|
6671
7703
|
}
|
|
6672
7704
|
ValidateJSONFieldValue(fieldName, this.Get(fieldName), schema, rules, severity, this, result);
|
|
6673
7705
|
}
|
|
7706
|
+
setChainInSaveValidation(flag) {
|
|
7707
|
+
for (let node = this; node; node = node._parentEntity) {
|
|
7708
|
+
node._inSaveValidation = flag;
|
|
7709
|
+
}
|
|
7710
|
+
}
|
|
6674
7711
|
Validate() {
|
|
6675
7712
|
if (this._isValidating) {
|
|
6676
7713
|
const emptyResult = new ValidationResult();
|
|
@@ -6698,10 +7735,38 @@ export class BaseEntity {
|
|
|
6698
7735
|
if (this._parentEntityFieldNames?.has(field.Name))
|
|
6699
7736
|
continue; // skip parent field mirrors — authoritative validation is on _parentEntity
|
|
6700
7737
|
const err = field.Validate();
|
|
6701
|
-
|
|
6702
|
-
|
|
6703
|
-
|
|
6704
|
-
|
|
7738
|
+
const suppressPreSaveNullForAutoNumber = !this.IsSaved &&
|
|
7739
|
+
(field.Value === null ||
|
|
7740
|
+
field.Value === undefined ||
|
|
7741
|
+
(typeof field.Value === 'string' && field.Value.trim().length === 0)) &&
|
|
7742
|
+
DocumentNumberingEngine.Instance.WillAutoPopulateOnCreate(this.EntityInfo, field.Name);
|
|
7743
|
+
if (suppressPreSaveNullForAutoNumber) {
|
|
7744
|
+
const nullErrorMessage = `${field.EntityFieldInfo.DisplayNameOrName} cannot be null`;
|
|
7745
|
+
const retainedErrors = err.Errors.filter((e) => e.Message !== nullErrorMessage);
|
|
7746
|
+
retainedErrors.forEach((element) => {
|
|
7747
|
+
result.Errors.push(element);
|
|
7748
|
+
});
|
|
7749
|
+
if (retainedErrors.length > 0) {
|
|
7750
|
+
result.Success = false;
|
|
7751
|
+
}
|
|
7752
|
+
}
|
|
7753
|
+
else {
|
|
7754
|
+
err.Errors.forEach(element => {
|
|
7755
|
+
result.Errors.push(element);
|
|
7756
|
+
});
|
|
7757
|
+
result.Success = result.Success && err.Success; // if any field fails, we fail, but keep going to get all of the validation messages
|
|
7758
|
+
}
|
|
7759
|
+
}
|
|
7760
|
+
// Declarative & programmatic lifecycle state machine, field-freeze, and auto-number reserved-namespace rules
|
|
7761
|
+
EntityLifecyclePolicyEngine.Instance.ValidateLifecycleOnEntity(this, this.resolveActiveUserOrNull() ?? this.ActiveUser, result);
|
|
7762
|
+
DocumentNumberingEngine.Instance.ValidateAutoNumberFields(this, result);
|
|
7763
|
+
// Type-table validation: ensure any ExtensionEntity column referenced by a parent entity's
|
|
7764
|
+
// SubtypeSelector.Path names a declared IS-A child of that parent entity
|
|
7765
|
+
this.validateSubtypeTypeRowFields(result);
|
|
7766
|
+
// Synchronous cached subtype-driver validation when Validate() is invoked directly
|
|
7767
|
+
// (during Save(), _innerSave runs validateSubtypeDriverAsync instead so cold caches load)
|
|
7768
|
+
if (!this._inSaveValidation) {
|
|
7769
|
+
this.validateSubtypeDriverSync(result);
|
|
6705
7770
|
}
|
|
6706
7771
|
// Companions validate LAST but still BEFORE any write, over their complete state including
|
|
6707
7772
|
// pending removals. That ordering is what lets a cross-child invariant — "debits must equal
|
|
@@ -6910,6 +7975,13 @@ export class BaseEntity {
|
|
|
6910
7975
|
}
|
|
6911
7976
|
const unit = part?.unit ?? enclosing;
|
|
6912
7977
|
this.CheckPermissions(EntityPermissionType.Delete, true); // this will throw an error and exit out if we don't have permission
|
|
7978
|
+
if (!_options.ReplayOnly) {
|
|
7979
|
+
const gateError = EntityLifecyclePolicyEngine.Instance.CheckWritePermissionGate(this, 'Delete', this.ActiveUser, this.isDatabaseProvider());
|
|
7980
|
+
if (gateError) {
|
|
7981
|
+
throw new Error(gateError);
|
|
7982
|
+
}
|
|
7983
|
+
await this.runPreDeleteHooks();
|
|
7984
|
+
}
|
|
6913
7985
|
// Raise delete_started event before the actual delete operation begins
|
|
6914
7986
|
this.RaiseEvent('delete_started', null);
|
|
6915
7987
|
// stash the old values for the event
|