@memberjunction/core 6.2.0 → 6.3.0-edge.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.
Files changed (130) hide show
  1. package/dist/generic/BaseEntitySaveQueue.d.ts +11 -0
  2. package/dist/generic/BaseEntitySaveQueue.d.ts.map +1 -1
  3. package/dist/generic/BaseEntitySaveQueue.js +17 -1
  4. package/dist/generic/BaseEntitySaveQueue.js.map +1 -1
  5. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts +94 -0
  6. package/dist/generic/JSONType-interfaces/IEntityConfiguration.d.ts.map +1 -1
  7. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +77 -4
  8. package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
  9. package/dist/generic/appCapabilityRegistry.d.ts +106 -0
  10. package/dist/generic/appCapabilityRegistry.d.ts.map +1 -0
  11. package/dist/generic/appCapabilityRegistry.js +212 -0
  12. package/dist/generic/appCapabilityRegistry.js.map +1 -0
  13. package/dist/generic/baseEngine.d.ts +108 -3
  14. package/dist/generic/baseEngine.d.ts.map +1 -1
  15. package/dist/generic/baseEngine.js +891 -122
  16. package/dist/generic/baseEngine.js.map +1 -1
  17. package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
  18. package/dist/generic/baseEngineRegistry.js +8 -1
  19. package/dist/generic/baseEngineRegistry.js.map +1 -1
  20. package/dist/generic/baseEntity.d.ts +147 -3
  21. package/dist/generic/baseEntity.d.ts.map +1 -1
  22. package/dist/generic/baseEntity.js +1063 -25
  23. package/dist/generic/baseEntity.js.map +1 -1
  24. package/dist/generic/baseRemotableOperation.d.ts +15 -0
  25. package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
  26. package/dist/generic/baseRemotableOperation.js +11 -0
  27. package/dist/generic/baseRemotableOperation.js.map +1 -1
  28. package/dist/generic/compositeKey.d.ts.map +1 -1
  29. package/dist/generic/compositeKey.js +3 -1
  30. package/dist/generic/compositeKey.js.map +1 -1
  31. package/dist/generic/crossEntityPolicyEngine.d.ts +172 -0
  32. package/dist/generic/crossEntityPolicyEngine.d.ts.map +1 -0
  33. package/dist/generic/crossEntityPolicyEngine.js +667 -0
  34. package/dist/generic/crossEntityPolicyEngine.js.map +1 -0
  35. package/dist/generic/dataHooks.d.ts +14 -1
  36. package/dist/generic/dataHooks.d.ts.map +1 -1
  37. package/dist/generic/dataHooks.js.map +1 -1
  38. package/dist/generic/databaseProviderBase.d.ts +37 -0
  39. package/dist/generic/databaseProviderBase.d.ts.map +1 -1
  40. package/dist/generic/databaseProviderBase.js +220 -24
  41. package/dist/generic/databaseProviderBase.js.map +1 -1
  42. package/dist/generic/documentNumberingEngine.d.ts +190 -0
  43. package/dist/generic/documentNumberingEngine.d.ts.map +1 -0
  44. package/dist/generic/documentNumberingEngine.js +739 -0
  45. package/dist/generic/documentNumberingEngine.js.map +1 -0
  46. package/dist/generic/entityInfo.d.ts +104 -3
  47. package/dist/generic/entityInfo.d.ts.map +1 -1
  48. package/dist/generic/entityInfo.js +326 -22
  49. package/dist/generic/entityInfo.js.map +1 -1
  50. package/dist/generic/entityLifecyclePolicy.d.ts +214 -0
  51. package/dist/generic/entityLifecyclePolicy.d.ts.map +1 -0
  52. package/dist/generic/entityLifecyclePolicy.js +708 -0
  53. package/dist/generic/entityLifecyclePolicy.js.map +1 -0
  54. package/dist/generic/entitySubtypeDriver.d.ts +49 -0
  55. package/dist/generic/entitySubtypeDriver.d.ts.map +1 -0
  56. package/dist/generic/entitySubtypeDriver.js +26 -0
  57. package/dist/generic/entitySubtypeDriver.js.map +1 -0
  58. package/dist/generic/fieldSecuritySQLGate.d.ts +17 -0
  59. package/dist/generic/fieldSecuritySQLGate.d.ts.map +1 -1
  60. package/dist/generic/fieldSecuritySQLGate.js +41 -1
  61. package/dist/generic/fieldSecuritySQLGate.js.map +1 -1
  62. package/dist/generic/filters/compositeFilter.d.ts +5 -1
  63. package/dist/generic/filters/compositeFilter.d.ts.map +1 -1
  64. package/dist/generic/filters/compositeFilter.js +127 -12
  65. package/dist/generic/filters/compositeFilter.js.map +1 -1
  66. package/dist/generic/filters/compositeFilterSQL.d.ts +121 -0
  67. package/dist/generic/filters/compositeFilterSQL.d.ts.map +1 -0
  68. package/dist/generic/filters/compositeFilterSQL.js +489 -0
  69. package/dist/generic/filters/compositeFilterSQL.js.map +1 -0
  70. package/dist/generic/filters/filter.types.d.ts +5 -2
  71. package/dist/generic/filters/filter.types.d.ts.map +1 -1
  72. package/dist/generic/filters/filter.types.js +4 -1
  73. package/dist/generic/filters/filter.types.js.map +1 -1
  74. package/dist/generic/filters/filterBuilder.d.ts +75 -0
  75. package/dist/generic/filters/filterBuilder.d.ts.map +1 -0
  76. package/dist/generic/filters/filterBuilder.js +104 -0
  77. package/dist/generic/filters/filterBuilder.js.map +1 -0
  78. package/dist/generic/filters/index.d.ts +2 -0
  79. package/dist/generic/filters/index.d.ts.map +1 -1
  80. package/dist/generic/filters/index.js +2 -0
  81. package/dist/generic/filters/index.js.map +1 -1
  82. package/dist/generic/interfaces.d.ts +74 -1
  83. package/dist/generic/interfaces.d.ts.map +1 -1
  84. package/dist/generic/interfaces.js +0 -1
  85. package/dist/generic/interfaces.js.map +1 -1
  86. package/dist/generic/localCacheManager.d.ts +46 -3
  87. package/dist/generic/localCacheManager.d.ts.map +1 -1
  88. package/dist/generic/localCacheManager.js +267 -45
  89. package/dist/generic/localCacheManager.js.map +1 -1
  90. package/dist/generic/metadata.d.ts +3 -1
  91. package/dist/generic/metadata.d.ts.map +1 -1
  92. package/dist/generic/metadata.js +25 -6
  93. package/dist/generic/metadata.js.map +1 -1
  94. package/dist/generic/providerBase.d.ts +212 -33
  95. package/dist/generic/providerBase.d.ts.map +1 -1
  96. package/dist/generic/providerBase.js +543 -117
  97. package/dist/generic/providerBase.js.map +1 -1
  98. package/dist/generic/queryInfo.d.ts +5 -0
  99. package/dist/generic/queryInfo.d.ts.map +1 -1
  100. package/dist/generic/queryInfo.js +5 -0
  101. package/dist/generic/queryInfo.js.map +1 -1
  102. package/dist/generic/queryInfoInterfaces.d.ts +5 -0
  103. package/dist/generic/queryInfoInterfaces.d.ts.map +1 -1
  104. package/dist/generic/remoteOperationDispatch.d.ts.map +1 -1
  105. package/dist/generic/remoteOperationDispatch.js +13 -1
  106. package/dist/generic/remoteOperationDispatch.js.map +1 -1
  107. package/dist/generic/saveEntityGraphOperation.d.ts +6 -0
  108. package/dist/generic/saveEntityGraphOperation.d.ts.map +1 -1
  109. package/dist/generic/saveEntityGraphOperation.js +8 -0
  110. package/dist/generic/saveEntityGraphOperation.js.map +1 -1
  111. package/dist/generic/transactionGroup.d.ts +25 -0
  112. package/dist/generic/transactionGroup.d.ts.map +1 -1
  113. package/dist/generic/transactionGroup.js +105 -0
  114. package/dist/generic/transactionGroup.js.map +1 -1
  115. package/dist/generic/typedQuery.d.ts +151 -0
  116. package/dist/generic/typedQuery.d.ts.map +1 -0
  117. package/dist/generic/typedQuery.js +286 -0
  118. package/dist/generic/typedQuery.js.map +1 -0
  119. package/dist/generic/util.d.ts.map +1 -1
  120. package/dist/generic/util.js +9 -3
  121. package/dist/generic/util.js.map +1 -1
  122. package/dist/index.d.ts +6 -0
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +6 -0
  125. package/dist/index.js.map +1 -1
  126. package/dist/views/runView.d.ts +53 -0
  127. package/dist/views/runView.d.ts.map +1 -1
  128. package/dist/views/runView.js +134 -0
  129. package/dist/views/runView.js.map +1 -1
  130. package/package.json +3 -3
@@ -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 { EntityFieldInfo, EntityInfo, EntityFieldTSType, EntityPermissionType, FieldSecurityError, RecordChange, ValidationErrorInfo, ValidationResult } from './entityInfo.js';
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
- const loaded = await childEntity.InnerLoad(this.PrimaryKey);
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, the indexes over
1724
- * engine-cached rows, and the record of load-hint messages already logged, so each can be
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,
@@ -3124,6 +3618,11 @@ export class BaseEntity {
3124
3618
  * this save took none (see `_innerSave`), and then only the scope is rolled back.
3125
3619
  */
3126
3620
  async rollbackChainSave(part) {
3621
+ let cur = this.RootEntity;
3622
+ while (cur) {
3623
+ cur._pendingPostSave = null;
3624
+ cur = cur._childEntity;
3625
+ }
3127
3626
  await this.rollbackEntityTransactionScope();
3128
3627
  BaseEntity.settleRollback(part);
3129
3628
  }
@@ -3641,7 +4140,13 @@ export class BaseEntity {
3641
4140
  this.assertFieldActiveStatus(FieldName, 'BaseEntity.Set');
3642
4141
  }
3643
4142
  this.assertFieldReadable(FieldName);
4143
+ const hasDriver = !this._isLoading && this.chainHasSubtypeDriver();
4144
+ const fieldObj = hasDriver ? this.GetFieldByName(FieldName) : null;
4145
+ const oldValue = fieldObj ? fieldObj.Value : undefined;
3644
4146
  this.setLocal(FieldName, Value);
4147
+ if (hasDriver && fieldObj) {
4148
+ this.notifySubtypeDriversFieldChanged(fieldObj.Name, fieldObj.Value, oldValue);
4149
+ }
3645
4150
  }
3646
4151
  }
3647
4152
  /**
@@ -4388,6 +4893,7 @@ export class BaseEntity {
4388
4893
  this.init();
4389
4894
  this.discardJSONFieldObjects();
4390
4895
  this._everSaved = false; // Reset save state for new record
4896
+ DocumentNumberingEngine.Instance.ClearSystemAssignedMarkers(this);
4391
4897
  // Clear child entity state — new records don't have children yet
4392
4898
  this._childEntity = null;
4393
4899
  this._childEntities = null;
@@ -4715,19 +5221,45 @@ export class BaseEntity {
4715
5221
  // in one, taken only when this entity starts an IS-A chain save whose writes a failure undoes.
4716
5222
  const enclosing = this._unitOfWork;
4717
5223
  let part = null;
5224
+ let activeSaveOptions = null;
5225
+ let reconciledChainRoot = null;
4718
5226
  try {
4719
5227
  this.FlushJSONFieldObjects(); // idempotent; covers graph-node saves that bypass Save()
4720
5228
  const initialDirtyState = this.Dirty; // save this because parent entity save cycle, if any, will clear their dirty flags
4721
5229
  const _options = options ? options : new EntitySaveOptions();
5230
+ activeSaveOptions = _options;
5231
+ // Generic SubtypeSelector orchestration (AutoEnsureOnSave & OnSubtypeChange: 'Refuse' | 'Replace').
5232
+ // Runs once on the initiating Save() across the IS-A chain from root downward before leaf
5233
+ // delegation, so newly-ensured children participate in the leaf's single atomic transaction.
5234
+ if (!_options.IsParentEntitySave &&
5235
+ !_options.ReplayOnly &&
5236
+ !BaseEntity.hasReconciledSaveChain(_options, this.RootEntity)) {
5237
+ reconciledChainRoot = this.RootEntity;
5238
+ BaseEntity.markReconciledSaveChain(_options, reconciledChainRoot);
5239
+ const reconcileOutcome = await this.reconcileISAChainBeforeSave(_options);
5240
+ if (reconcileOutcome.kind === 'handled') {
5241
+ return reconcileOutcome.result;
5242
+ }
5243
+ }
4722
5244
  // IS-A leaf delegation: if this entity has a child entity and we are NOT
4723
5245
  // already being called as part of a parent chain save, delegate to the leaf.
4724
5246
  // The leaf's Save() will then save the full chain (root → branch → leaf)
4725
5247
  // using the existing IS-A parent chain orchestration.
4726
5248
  if (this._childEntity && !_options.IsParentEntitySave) {
4727
- return this.LeafEntity.Save(_options);
5249
+ const leaf = this.LeafEntity;
5250
+ const leafSaved = await leaf.Save(_options);
5251
+ if (!leafSaved && currentResultCount === this.ResultHistory.length && leaf.LatestResult) {
5252
+ this.copyFailureResultFrom(leaf.LatestResult);
5253
+ }
5254
+ return leafSaved;
4728
5255
  }
4729
5256
  // IS-A orchestration: determine if this is the initiating save in a parent chain
4730
- const isISAInitiator = (!!this._parentEntity) && !_options.IsParentEntitySave;
5257
+ // (or a standalone entity whose active SubtypeSelector.Driver resolves to a registered driver)
5258
+ const hasActiveDriver = !this._parentEntity &&
5259
+ !_options.IsParentEntitySave &&
5260
+ Boolean(this.EntityInfo?.SubtypeSelectorConfig?.Driver) &&
5261
+ (await this.ResolveSubtypeDriver()) !== null;
5262
+ const isISAInitiator = (Boolean(this._parentEntity) || hasActiveDriver) && !_options.IsParentEntitySave;
4731
5263
  // Open (or join) a transaction scope for the parent chain. The provider arbitrates:
4732
5264
  // if a transaction is already in flight — an application cascade, an enclosing graph
4733
5265
  // save — this joins it as a savepoint rather than starting a second physical
@@ -4756,11 +5288,36 @@ export class BaseEntity {
4756
5288
  parentSaveOptions.SkipEntityActions = _options.SkipEntityActions;
4757
5289
  parentSaveOptions.ReplayOnly = _options.ReplayOnly;
4758
5290
  parentSaveOptions.SkipOldValuesCheck = _options.SkipOldValuesCheck;
5291
+ if (_options.ConcurrencyBaseline) {
5292
+ const parentChainFieldNames = new Set();
5293
+ for (let anc = this._parentEntity; anc; anc = anc._parentEntity) {
5294
+ for (const f of anc.EntityInfo.Fields) {
5295
+ parentChainFieldNames.add(f.Name);
5296
+ parentChainFieldNames.add(f.CodeName);
5297
+ }
5298
+ }
5299
+ const filteredParentBaseline = {};
5300
+ let hasParentBaseline = false;
5301
+ for (const [k, v] of Object.entries(_options.ConcurrencyBaseline)) {
5302
+ if (parentChainFieldNames.has(k)) {
5303
+ filteredParentBaseline[k] = v;
5304
+ hasParentBaseline = true;
5305
+ }
5306
+ }
5307
+ if (hasParentBaseline) {
5308
+ parentSaveOptions.ConcurrencyBaseline = filteredParentBaseline;
5309
+ }
5310
+ }
5311
+ parentSaveOptions.ConcurrencyCheck = _options.ConcurrencyCheck;
4759
5312
  parentSaveOptions.SkipAsyncValidation = _options.SkipAsyncValidation;
4760
5313
  parentSaveOptions.IsParentEntitySave = true;
4761
5314
  parentSaveOptions.ISAActiveChildEntityName = this.EntityInfo.Name;
4762
5315
  const parentResult = await this._parentEntity.Save(parentSaveOptions); // we know parent entity exists hre
4763
5316
  if (!parentResult) {
5317
+ // Capture parent failure BEFORE rollbackChainSave restores pre-save ResultHistory
5318
+ // on any ancestor that reached finalizeSave() before failing in AfterSave/commit.
5319
+ const parentLatest = this._parentEntity.LatestResult;
5320
+ const parentErrors = parentLatest?.Errors ?? [];
4764
5321
  // Parent save failed — roll back if we started the transaction, and put back
4765
5322
  // the levels above it that had already saved
4766
5323
  await this.rollbackChainSave(part);
@@ -4772,8 +5329,6 @@ export class BaseEntity {
4772
5329
  // the child never set fails with literally no message anywhere the caller can
4773
5330
  // reach. Mirrors the transaction-group-failure and catch-block paths below.
4774
5331
  if (currentResultCount === this.ResultHistory.length) {
4775
- const parentLatest = this._parentEntity.LatestResult;
4776
- const parentErrors = parentLatest?.Errors ?? [];
4777
5332
  // A failed parent commonly reports its detail ONLY in Errors (validation
4778
5333
  // failures leave Message empty), so fall back to the error text rather than
4779
5334
  // handing the caller a message that says nothing.
@@ -4786,6 +5341,9 @@ export class BaseEntity {
4786
5341
  `Failed to save parent entity '${this._parentEntity.EntityInfo?.Name}': ${detail}`;
4787
5342
  // Surface the parent's field-level errors so the caller can act on them.
4788
5343
  newResult.Errors = parentErrors;
5344
+ if (parentLatest?.ConcurrencyConflict) {
5345
+ newResult.ConcurrencyConflict = parentLatest.ConcurrencyConflict;
5346
+ }
4789
5347
  // When `detail` was built from `parentErrors` (no parent Message), `Message` already renders
4790
5348
  // them — say so, or CompleteMessage repeats every one.
4791
5349
  newResult.MessageIncludesErrors = !parentLatest?.Message && parentErrors.length > 0;
@@ -4813,6 +5371,12 @@ export class BaseEntity {
4813
5371
  }
4814
5372
  }
4815
5373
  if (_options.IgnoreDirtyState || initialDirtyState || _options.ReplayOnly) {
5374
+ if (!_options.ReplayOnly) {
5375
+ const gateError = EntityLifecyclePolicyEngine.Instance.CheckWritePermissionGate(this, this.IsSaved ? 'Update' : 'Create', this.ActiveUser, this.isDatabaseProvider());
5376
+ if (gateError) {
5377
+ throw new Error(gateError);
5378
+ }
5379
+ }
4816
5380
  // Raise save_started event only when we're actually going to save
4817
5381
  this.RaiseEvent('save_started', null, saveSubType);
4818
5382
  if (!this.ProviderToUse) {
@@ -4824,8 +5388,16 @@ export class BaseEntity {
4824
5388
  valResult.Success = true; // bypassing validation since we are in replay only....
4825
5389
  }
4826
5390
  else {
4827
- // First run synchronous validation
4828
- valResult = this.Validate();
5391
+ // First run synchronous validation (suppressing sync subtype-driver validation
5392
+ // on self and already-saved IS-A ancestors so each level's validateSubtypeDriverAsync
5393
+ // runs its driver's Validate exactly once)
5394
+ this.setChainInSaveValidation(true);
5395
+ try {
5396
+ valResult = this.Validate();
5397
+ }
5398
+ finally {
5399
+ this.setChainInSaveValidation(false);
5400
+ }
4829
5401
  // Determine if we should run async validation, in order of authority:
4830
5402
  // 1. An explicit SkipAsyncValidation in the options.
4831
5403
  // 2. An explicit DefaultSkipAsyncValidation override on the subclass.
@@ -4871,10 +5443,14 @@ export class BaseEntity {
4871
5443
  // save in production: the class never overrode DefaultSkipAsyncValidation
4872
5444
  // (which defaults to true) and no caller ever passed SkipAsyncValidation:false.
4873
5445
  await this.validateCompanionsAsync(valResult);
5446
+ await this.validateSubtypeDriverAsync(valResult);
4874
5447
  }
4875
5448
  if (valResult.Success) {
4876
- // Run registered PreSave hooks (e.g., tenant validation)
5449
+ // Run registered PreSave hooks (e.g., tenant validation) and subtype driver BeforeSave
4877
5450
  await this.runPreSaveHooks();
5451
+ if (!_options.ReplayOnly) {
5452
+ await this.runSubtypeDriverBeforeSave();
5453
+ }
4878
5454
  // Optimistic-UI hook: every pre-flight check (Validate, ValidateAsync,
4879
5455
  // PreSave hooks) has passed and the DB write is imminent. Fire the optional
4880
5456
  // OnValidated callback so a UI can render the now-known-valid change before
@@ -4907,6 +5483,7 @@ export class BaseEntity {
4907
5483
  });
4908
5484
  throw saveErr;
4909
5485
  }
5486
+ const wasNewBeforeFinalize = !this.IsSaved;
4910
5487
  if (!this.TransactionGroup) {
4911
5488
  // no transaction group, so we have our results here
4912
5489
  const result = this.finalizeSave(data, saveSubType, _options);
@@ -4917,8 +5494,14 @@ export class BaseEntity {
4917
5494
  // chain around a leaf that reported failure: precisely the torn write
4918
5495
  // this scope exists to prevent.
4919
5496
  if (result) {
5497
+ if (!_options.ReplayOnly) {
5498
+ await this.runSubtypeDriverAfterSave(wasNewBeforeFinalize);
5499
+ }
4920
5500
  await this.commitEntityTransactionScope();
4921
5501
  BaseEntity.settleCommit(part);
5502
+ if (!_options.IsParentEntitySave && !_options.ReplayOnly) {
5503
+ await this.runChainPostSaveHooks();
5504
+ }
4922
5505
  }
4923
5506
  else {
4924
5507
  await this.rollbackChainSave(part);
@@ -4926,13 +5509,39 @@ export class BaseEntity {
4926
5509
  return result;
4927
5510
  }
4928
5511
  else {
5512
+ // Enlist SubtypeSelector.Driver AfterSave inside the open group transaction
5513
+ // so it runs atomically (and rolls back the group if it throws), matching direct Save().
5514
+ // Finalize the entity before running AfterSave so the hook observes IsSaved === true
5515
+ // and any server-returned values, restoring the pre-save snapshot if the group rolls back.
5516
+ let finalizedInAfterSaveHook = false;
5517
+ const preFinalizeSnapshots = BaseEntity.captureChains([this]);
5518
+ if (!_options.ReplayOnly && this.EntityInfo?.SubtypeSelectorConfig?.Driver) {
5519
+ this.TransactionGroup.RegisterInTransactionAfterSave(this, async (resultRecord) => {
5520
+ const finalized = this.finalizeSave(resultRecord, saveSubType, _options);
5521
+ if (!finalized) {
5522
+ return;
5523
+ }
5524
+ finalizedInAfterSaveHook = true;
5525
+ await this.runSubtypeDriverAfterSave(wasNewBeforeFinalize);
5526
+ });
5527
+ }
4929
5528
  // 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
5529
  this.TransactionGroup.TransactionNotifications$.subscribe(({ success, results, error }) => {
4931
5530
  const transItem = success && results ? results.find(r => r.Transaction.BaseEntity === this) : undefined;
4932
5531
  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
5532
+ 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
5533
+ if (finalized && !_options.ReplayOnly && !_options.IsParentEntitySave) {
5534
+ void this.runChainPostSaveHooks().catch(hookErr => {
5535
+ LogError(`PostSave hook failed after TransactionGroup commit on '${this.EntityInfo?.Name}': ${BaseEntity.errorText(hookErr)}`);
5536
+ });
5537
+ }
4934
5538
  }
4935
5539
  else {
5540
+ if (finalizedInAfterSaveHook) {
5541
+ this._pendingPostSave = null;
5542
+ BaseEntity.restoreChains(preFinalizeSnapshots);
5543
+ finalizedInAfterSaveHook = false;
5544
+ }
4936
5545
  // The transaction group failed / rolled back, OR (should never happen) reported success
4937
5546
  // without a result for this entity. Either way, RECORD the failure on ResultHistory rather
4938
5547
  // than throwing. This handler runs ASYNCHRONOUSLY — after Save() has already returned true and
@@ -4970,6 +5579,9 @@ export class BaseEntity {
4970
5579
  // empty scope writes nothing; it only releases the transaction.
4971
5580
  await this.commitEntityTransactionScope();
4972
5581
  BaseEntity.settleCommit(part);
5582
+ if (!_options.IsParentEntitySave && !_options.ReplayOnly) {
5583
+ await this.runChainPostSaveHooks();
5584
+ }
4973
5585
  return true; // nothing to save since we're not dirty
4974
5586
  }
4975
5587
  }
@@ -4991,6 +5603,239 @@ export class BaseEntity {
4991
5603
  }
4992
5604
  return false;
4993
5605
  }
5606
+ finally {
5607
+ if (activeSaveOptions && reconciledChainRoot) {
5608
+ BaseEntity.unmarkReconciledSaveChain(activeSaveOptions, reconciledChainRoot);
5609
+ }
5610
+ }
5611
+ }
5612
+ /**
5613
+ * Walks the IS-A chain from `RootEntity` downward before an initiating `Save()`, applying:
5614
+ * 1. `AutoEnsureOnSave` — creates missing child entities in the same transaction.
5615
+ * 2. Unsaved subtype switching — swaps an unsaved prospective child when the record's type changed before first save.
5616
+ * 3. `OnSubtypeChange` (`'Refuse'` | `'Replace'`) — enforces subtype-change policy when a saved record's
5617
+ * selector resolves to a different child entity (or to no child entity after its selector FK changed).
5618
+ * Moving from a type with no extension entity to one with an extension entity is always allowed.
5619
+ */
5620
+ async reconcileISAChainBeforeSave(options) {
5621
+ let level = this.RootEntity;
5622
+ while (level) {
5623
+ if (!level.EntityInfo?.IsParentType || level.EntityInfo.AllowMultipleSubtypes) {
5624
+ level = level._childEntity;
5625
+ continue;
5626
+ }
5627
+ const selector = level.EntityInfo.SubtypeSelectorConfig;
5628
+ if (!selector) {
5629
+ level = level._childEntity;
5630
+ continue;
5631
+ }
5632
+ if (level.IsSaved) {
5633
+ // Ensure any existing persisted child row is discovered before deciding subtype-change policy
5634
+ if (!level._childEntity && !level._childEntityDiscoveryDone) {
5635
+ level._childEntityDiscoveryDone = true;
5636
+ const childCheck = await level.CheckForChildRecords();
5637
+ if (childCheck.HasChildren && childCheck.ChildEntityName) {
5638
+ await level.createAndLinkChildEntity(childCheck.ChildEntityName);
5639
+ }
5640
+ }
5641
+ const resolvedSubtype = await level.ResolveSubtypeEntityName();
5642
+ const currentChild = level._childEntity;
5643
+ if (currentChild && currentChild.IsSaved) {
5644
+ const changedToDifferentExtension = resolvedSubtype !== null && !sameEntityName(currentChild.EntityInfo.Name, resolvedSubtype);
5645
+ const changedToNoExtension = resolvedSubtype === null && level.isSubtypeSelectorFirstHopDirty(selector.Path);
5646
+ if (changedToDifferentExtension || changedToNoExtension) {
5647
+ const policy = selector.OnSubtypeChange ?? 'Refuse';
5648
+ if (policy === 'Refuse') {
5649
+ const targetDesc = resolvedSubtype ? `'${resolvedSubtype}'` : 'no extension entity';
5650
+ const msg = `Cannot change subtype of saved '${level.EntityInfo.Name}' record from ` +
5651
+ `'${currentChild.EntityInfo.Name}' to ${targetDesc} (OnSubtypeChange is 'Refuse').`;
5652
+ level.recordSaveFailure(msg);
5653
+ if (this !== level) {
5654
+ this.recordSaveFailure(msg);
5655
+ }
5656
+ return { kind: 'handled', result: false };
5657
+ }
5658
+ const replaced = await this.executeSubtypeReplacementSave(level, currentChild, resolvedSubtype, options);
5659
+ return { kind: 'handled', result: replaced };
5660
+ }
5661
+ }
5662
+ else if (currentChild && !currentChild.IsSaved) {
5663
+ // Unsaved prospective child attached for promotion on a saved parent
5664
+ if (!resolvedSubtype || !sameEntityName(currentChild.EntityInfo.Name, resolvedSubtype)) {
5665
+ const firstHopVal = level.getSubtypeSelectorFirstHopValue(selector.Path);
5666
+ const shouldDetach = resolvedSubtype !== null || (firstHopVal !== null && firstHopVal !== undefined && firstHopVal !== '');
5667
+ if (shouldDetach) {
5668
+ level.detachUnsavedChildSubtree();
5669
+ }
5670
+ }
5671
+ if (!level._childEntity && resolvedSubtype && selector.AutoEnsureOnSave) {
5672
+ await level.EnsureISAChild(resolvedSubtype);
5673
+ }
5674
+ }
5675
+ else if (!currentChild && resolvedSubtype && selector.AutoEnsureOnSave) {
5676
+ // Saved parent had no extension row; promoting from null -> ExtensionEntity is always allowed
5677
+ await level.EnsureISAChild(resolvedSubtype);
5678
+ }
5679
+ }
5680
+ else {
5681
+ // Unsaved parent record
5682
+ const resolvedSubtype = await level.ResolveSubtypeEntityName();
5683
+ if (level._childEntity && !level._childEntity.IsSaved) {
5684
+ if (!resolvedSubtype || !sameEntityName(level._childEntity.EntityInfo.Name, resolvedSubtype)) {
5685
+ const firstHopVal = level.getSubtypeSelectorFirstHopValue(selector.Path);
5686
+ const shouldDetach = resolvedSubtype !== null || (firstHopVal !== null && firstHopVal !== undefined && firstHopVal !== '');
5687
+ if (shouldDetach) {
5688
+ level.detachUnsavedChildSubtree();
5689
+ }
5690
+ }
5691
+ }
5692
+ if (!level._childEntity && resolvedSubtype && selector.AutoEnsureOnSave) {
5693
+ await level.EnsureISAChild(resolvedSubtype);
5694
+ }
5695
+ }
5696
+ level = level._childEntity;
5697
+ }
5698
+ return { kind: 'proceed' };
5699
+ }
5700
+ /**
5701
+ * Executes an atomic `OnSubtypeChange: 'Replace'` transition: deletes `oldChild` (and any deeper
5702
+ * child subtree, without cascading up to `levelWithReplacement`), attaches `resolvedSubtype` if
5703
+ * non-null, and saves the updated chain — all inside one `EntityTransactionScope` and `UnitOfWork`.
5704
+ */
5705
+ async executeSubtypeReplacementSave(levelWithReplacement, oldChild, resolvedSubtype, options) {
5706
+ const root = this.RootEntity;
5707
+ const provider = root.ProviderToUse;
5708
+ const enclosing = this._unitOfWork;
5709
+ let scope = null;
5710
+ let part = null;
5711
+ let attachedNewChild = null;
5712
+ try {
5713
+ if (!root.TransactionGroup && provider?.SupportsEntityTransactions === true && provider.BeginEntityTransaction) {
5714
+ scope = await provider.BeginEntityTransaction();
5715
+ }
5716
+ if (!root.TransactionGroup && (scope || provider?.SupportsEntityTransactions !== true)) {
5717
+ part = BaseEntity.beginUnitOfWork(enclosing, BaseEntity.captureChains([root, oldChild]));
5718
+ }
5719
+ const unit = part?.unit ?? enclosing;
5720
+ // Detach oldChild from levelWithReplacement so deleting oldChild deletes only the old
5721
+ // child subtree (logging Record Changes for the deleted child row(s)) and never cascades
5722
+ // upward to levelWithReplacement.
5723
+ levelWithReplacement._childEntity = null;
5724
+ oldChild._parentEntity = null;
5725
+ const deleteOptions = new EntityDeleteOptions();
5726
+ deleteOptions.SkipEntityAIActions = options.SkipEntityAIActions;
5727
+ deleteOptions.SkipEntityActions = options.SkipEntityActions;
5728
+ deleteOptions.ReplayOnly = options.ReplayOnly;
5729
+ const deleted = await BaseEntity.inUnitOfWork(oldChild, unit, c => c.Delete(deleteOptions));
5730
+ if (!deleted) {
5731
+ oldChild._parentEntity = levelWithReplacement;
5732
+ levelWithReplacement._childEntity = oldChild;
5733
+ await scope?.Rollback();
5734
+ BaseEntity.settleRollback(part);
5735
+ const errMsg = oldChild.LatestResult?.Message ||
5736
+ `Failed to delete replaced subtype '${oldChild.EntityInfo.Name}' on '${levelWithReplacement.EntityInfo.Name}'.`;
5737
+ levelWithReplacement.recordSaveFailure(errMsg, oldChild.LatestResult?.Errors);
5738
+ if (this !== levelWithReplacement) {
5739
+ this.recordSaveFailure(errMsg, oldChild.LatestResult?.Errors);
5740
+ }
5741
+ return false;
5742
+ }
5743
+ if (resolvedSubtype) {
5744
+ attachedNewChild = await levelWithReplacement.EnsureISAChild(resolvedSubtype);
5745
+ // Recursively reconcile deeper levels if the newly attached child is also a parent type
5746
+ let sub = attachedNewChild;
5747
+ while (sub) {
5748
+ const subSelector = sub.EntityInfo?.SubtypeSelectorConfig;
5749
+ if (sub.EntityInfo?.IsParentType && !sub.EntityInfo.AllowMultipleSubtypes && !sub._childEntity && subSelector?.AutoEnsureOnSave) {
5750
+ const grandChildName = await sub.ResolveSubtypeEntityName();
5751
+ if (grandChildName) {
5752
+ await sub.EnsureISAChild(grandChildName);
5753
+ }
5754
+ }
5755
+ sub = sub._childEntity;
5756
+ }
5757
+ }
5758
+ const leafToSave = root.LeafEntity;
5759
+ const saveOpts = Object.assign(new EntitySaveOptions(), options);
5760
+ BaseEntity.markReconciledSaveChain(saveOpts, root);
5761
+ let saved;
5762
+ try {
5763
+ saved = await BaseEntity.inUnitOfWork(leafToSave, unit, target => target._innerSave(saveOpts));
5764
+ }
5765
+ finally {
5766
+ BaseEntity.unmarkReconciledSaveChain(saveOpts, root);
5767
+ }
5768
+ if (!saved) {
5769
+ if (attachedNewChild) {
5770
+ attachedNewChild._parentEntity = null;
5771
+ levelWithReplacement._childEntity = null;
5772
+ }
5773
+ oldChild._parentEntity = levelWithReplacement;
5774
+ levelWithReplacement._childEntity = oldChild;
5775
+ await scope?.Rollback();
5776
+ BaseEntity.settleRollback(part);
5777
+ if (leafToSave.LatestResult) {
5778
+ if (levelWithReplacement !== leafToSave) {
5779
+ levelWithReplacement.copyFailureResultFrom(leafToSave.LatestResult);
5780
+ }
5781
+ if (this !== leafToSave && this !== levelWithReplacement) {
5782
+ this.copyFailureResultFrom(leafToSave.LatestResult);
5783
+ }
5784
+ }
5785
+ return false;
5786
+ }
5787
+ await scope?.Commit();
5788
+ BaseEntity.settleCommit(part);
5789
+ return true;
5790
+ }
5791
+ catch (err) {
5792
+ if (attachedNewChild) {
5793
+ attachedNewChild._parentEntity = null;
5794
+ levelWithReplacement._childEntity = null;
5795
+ }
5796
+ oldChild._parentEntity = levelWithReplacement;
5797
+ levelWithReplacement._childEntity = oldChild;
5798
+ try {
5799
+ await scope?.Rollback();
5800
+ }
5801
+ catch (rbErr) {
5802
+ LogError(`Error rolling back subtype replacement scope on '${root.EntityInfo?.Name}': ${BaseEntity.errorText(rbErr)}`);
5803
+ }
5804
+ BaseEntity.settleRollback(part);
5805
+ const msg = BaseEntity.errorText(err);
5806
+ const errors = err?.Errors;
5807
+ levelWithReplacement.recordSaveFailure(msg, errors);
5808
+ if (this !== levelWithReplacement) {
5809
+ this.recordSaveFailure(msg, errors);
5810
+ }
5811
+ return false;
5812
+ }
5813
+ }
5814
+ recordSaveFailure(message, errors) {
5815
+ const entry = new BaseEntityResult();
5816
+ entry.StartedAt = new Date();
5817
+ entry.EndedAt = new Date();
5818
+ entry.Success = false;
5819
+ entry.Type = this.IsSaved ? 'update' : 'create';
5820
+ entry.Message = message;
5821
+ entry.Errors = errors ? [...errors] : [];
5822
+ entry.OriginalValues = this.Fields.map(f => ({ FieldName: f.CodeName, Value: f.OldValue }));
5823
+ this.RegisterResultHistoryEntry(entry);
5824
+ }
5825
+ copyFailureResultFrom(source) {
5826
+ const detail = source.Message ||
5827
+ (source.Errors ?? []).map(e => e?.Message ?? String(e)).filter(Boolean).join('; ') ||
5828
+ 'Child entity save failed';
5829
+ const entry = new BaseEntityResult();
5830
+ entry.StartedAt = source.StartedAt ?? new Date();
5831
+ entry.EndedAt = source.EndedAt ?? new Date();
5832
+ entry.Success = false;
5833
+ entry.Type = this.IsSaved ? 'update' : 'create';
5834
+ entry.Message = detail;
5835
+ entry.Errors = source.Errors ? [...source.Errors] : [];
5836
+ entry.MessageIncludesErrors = !source.Message && entry.Errors.length > 0;
5837
+ entry.OriginalValues = this.Fields.map(f => ({ FieldName: f.CodeName, Value: f.OldValue }));
5838
+ this.RegisterResultHistoryEntry(entry);
4994
5839
  }
4995
5840
  /**
4996
5841
  * Runs all registered PreSave hooks. If any hook returns false or a string
@@ -5008,6 +5853,104 @@ export class BaseEntity {
5008
5853
  }
5009
5854
  }
5010
5855
  }
5856
+ /**
5857
+ * Runs all registered PostSave hooks for this single entity after a committed save.
5858
+ * Errors thrown by PostSave hooks are logged and never abort the already-committed save.
5859
+ */
5860
+ async runPostSaveHooks(changedFieldNames, saveSubType) {
5861
+ const postSaveHooks = GetDataHooks('PostSave');
5862
+ if (postSaveHooks.length === 0) {
5863
+ return;
5864
+ }
5865
+ for (const hook of postSaveHooks) {
5866
+ try {
5867
+ await hook(this, this.ActiveUser, changedFieldNames, saveSubType);
5868
+ }
5869
+ catch (hookErr) {
5870
+ LogError(`PostSave hook failed on '${this.EntityInfo?.Name}': ${BaseEntity.errorText(hookErr)}`);
5871
+ }
5872
+ }
5873
+ }
5874
+ /**
5875
+ * Runs registered PostSave hooks across every finalized node in this entity's IS-A chain
5876
+ * once the outermost save scope has committed. Propagates inherited dirty field names from
5877
+ * ancestors to live child nodes so observers on either level see modified fields.
5878
+ */
5879
+ async runChainPostSaveHooks() {
5880
+ const postSaveHooks = GetDataHooks('PostSave');
5881
+ const chain = [];
5882
+ let cur = this.RootEntity;
5883
+ while (cur) {
5884
+ chain.push(cur);
5885
+ cur = cur._childEntity;
5886
+ }
5887
+ const unionChanged = new Set();
5888
+ let chainSaveSubType = null;
5889
+ for (const node of chain) {
5890
+ if (node._pendingPostSave) {
5891
+ for (const name of node._pendingPostSave.changedFieldNames) {
5892
+ unionChanged.add(name);
5893
+ }
5894
+ if (chainSaveSubType === null) {
5895
+ chainSaveSubType = node._pendingPostSave.saveSubType;
5896
+ }
5897
+ }
5898
+ }
5899
+ const pendingByNode = new Map();
5900
+ for (const node of chain) {
5901
+ if (node._pendingPostSave) {
5902
+ pendingByNode.set(node, node._pendingPostSave);
5903
+ node._pendingPostSave = null;
5904
+ }
5905
+ }
5906
+ if (postSaveHooks.length === 0 || (pendingByNode.size === 0 && unionChanged.size === 0)) {
5907
+ return;
5908
+ }
5909
+ const allChangedArray = Array.from(unionChanged);
5910
+ for (const node of chain) {
5911
+ const ownPending = pendingByNode.get(node);
5912
+ const nodeFieldNames = new Set(node.EntityInfo.Fields.map(f => f.Name));
5913
+ const effectiveChanged = allChangedArray.filter(name => nodeFieldNames.has(name));
5914
+ if (!ownPending && effectiveChanged.length === 0) {
5915
+ continue;
5916
+ }
5917
+ const subType = ownPending?.saveSubType ?? chainSaveSubType ?? 'update';
5918
+ await node.runPostSaveHooks(effectiveChanged, subType);
5919
+ }
5920
+ }
5921
+ /**
5922
+ * Runs all registered PreDelete hooks. If any hook returns false or a string
5923
+ * (error message), the delete is rejected by throwing an Error.
5924
+ */
5925
+ async runPreDeleteHooks() {
5926
+ const preDeleteHooks = GetDataHooks('PreDelete');
5927
+ for (const hook of preDeleteHooks) {
5928
+ const hookResult = await hook(this, this.ActiveUser);
5929
+ if (hookResult === false) {
5930
+ throw new Error('Delete rejected by pre-delete hook');
5931
+ }
5932
+ if (typeof hookResult === 'string') {
5933
+ throw new Error(hookResult);
5934
+ }
5935
+ }
5936
+ }
5937
+ /**
5938
+ * Returns true when `ProviderToUse` is a server-side database provider (`ProviderType.Database`)
5939
+ * rather than a client network transport (`ProviderType.Network`).
5940
+ */
5941
+ isDatabaseProvider() {
5942
+ const provider = this.ProviderToUse;
5943
+ if (!provider) {
5944
+ return false;
5945
+ }
5946
+ if (provider.ProviderType === ProviderType.Database) {
5947
+ return true;
5948
+ }
5949
+ if (provider.ProviderType === ProviderType.Network) {
5950
+ return false;
5951
+ }
5952
+ return 'ExecuteSQL' in provider && typeof provider.ExecuteSQL === 'function';
5953
+ }
5011
5954
  /**
5012
5955
  * Determines whether the parent entity should be deleted after this child entity
5013
5956
  * has been deleted. For overlapping subtype parents (AllowMultipleSubtypes = true),
@@ -5036,6 +5979,7 @@ export class BaseEntity {
5036
5979
  if (data) {
5037
5980
  // The 'save' event names the fields this save wrote; init() below clears every dirty flag.
5038
5981
  const changedFieldNames = this.dirtyFieldNames();
5982
+ const postSaveChangedFields = this.computePostSaveChangedFieldNames(saveSubType, changedFieldNames);
5039
5983
  const effectiveReturnMode = options?.SaveReturnMode ?? this.EntityInfo.SaveReturnMode;
5040
5984
  const hasGetAll = (val) => val instanceof BaseEntity || typeof val.GetAll === 'function';
5041
5985
  const rawFieldData = hasGetAll(data) ? data.GetAll() : data;
@@ -5079,6 +6023,10 @@ export class BaseEntity {
5079
6023
  result.NewValues = this.Fields.map(f => { return { FieldName: f.CodeName, Value: f.Value }; }); // set the latest values here
5080
6024
  // Cache the record name for faster lookups (updates cache with potentially new name)
5081
6025
  this.cacheRecordName();
6026
+ this._pendingPostSave = {
6027
+ changedFieldNames: postSaveChangedFields,
6028
+ saveSubType: saveSubType === 'create' ? 'create' : 'update',
6029
+ };
5082
6030
  this.RaiseEvent('save', null, saveSubType, changedFieldNames);
5083
6031
  return true;
5084
6032
  }
@@ -5092,7 +6040,7 @@ export class BaseEntity {
5092
6040
  get ActiveUser() {
5093
6041
  // Use the entity's bound provider (per-instance) before falling back to the global
5094
6042
  // default — multi-provider correctness for server requests with per-request users.
5095
- return this.ContextCurrentUser || this.ProviderToUse?.CurrentUser || Metadata.Provider.CurrentUser; // global-provider-ok: final fallback when no provider is bound
6043
+ return this.ContextCurrentUser || this.ProviderToUse?.CurrentUser || Metadata.Provider?.CurrentUser; // global-provider-ok: final fallback when no provider is bound
5096
6044
  }
5097
6045
  /**
5098
6046
  * Offers the record's name to the provider for later synchronous lookups. Only a provider that
@@ -5449,11 +6397,10 @@ export class BaseEntity {
5449
6397
  // Field security: denied values never enter this object, even from a provider that
5450
6398
  // did not narrow its SELECT (see narrowHydrationSource).
5451
6399
  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) {
6400
+ // IS-A: hydrate parent chain from loaded data before populating self when loading
6401
+ // upward from a child/leaf instance. Skipped when an already-loaded parent links a
6402
+ // child downward so the parent's virtual view columns are not cleared.
6403
+ if (this._parentEntity && !this._skipParentChainHydration) {
5457
6404
  this._parentEntity.Hydrate(data);
5458
6405
  }
5459
6406
  // Reset _NeverSet on all fields before SetMany so that ReadOnly/virtual fields
@@ -6587,11 +7534,62 @@ export class BaseEntity {
6587
7534
  await this.DeserializeCompanions(payloads);
6588
7535
  }
6589
7536
  }
7537
+ /**
7538
+ * Walks this instance's prototype chain up to (but excluding) `BaseEntity.prototype` and
7539
+ * `Object.prototype` to resolve the most-derived property `get` and `set` accessors for
7540
+ * `codeName`. Resolving `get` and `set` independently supports multi-level subclasses where an
7541
+ * intermediate class defines both and a leaf subclass overrides only `set` (or only `get`).
7542
+ */
7543
+ resolveSubclassFieldAccessors(codeName) {
7544
+ let getter;
7545
+ let setter;
7546
+ let proto = Object.getPrototypeOf(this);
7547
+ while (proto && proto !== BaseEntity.prototype && proto !== Object.prototype && (!getter || !setter)) {
7548
+ const desc = Object.getOwnPropertyDescriptor(proto, codeName);
7549
+ if (desc) {
7550
+ if (!getter && typeof desc.get === 'function') {
7551
+ getter = desc.get;
7552
+ }
7553
+ if (!setter && typeof desc.set === 'function') {
7554
+ setter = desc.set;
7555
+ }
7556
+ }
7557
+ proto = Object.getPrototypeOf(proto);
7558
+ }
7559
+ return { get: getter, set: setter };
7560
+ }
6590
7561
  getJSONFieldBinding(fieldName) {
6591
7562
  this._jsonFieldBindings ??= new Map();
6592
7563
  let binding = this._jsonFieldBindings.get(fieldName);
6593
7564
  if (!binding) {
6594
- binding = new JSONFieldBinding(fieldName, () => this.Get(fieldName), (raw) => this.Set(fieldName, raw));
7565
+ const codeName = this.EntityInfo?.FieldByName(fieldName)?.CodeName ?? fieldName;
7566
+ const accessors = this.resolveSubclassFieldAccessors(codeName);
7567
+ let inAccessorRead = false;
7568
+ let inAccessorWrite = false;
7569
+ binding = new JSONFieldBinding(fieldName, () => {
7570
+ if (!inAccessorRead && accessors.get) {
7571
+ inAccessorRead = true;
7572
+ try {
7573
+ return accessors.get.call(this);
7574
+ }
7575
+ finally {
7576
+ inAccessorRead = false;
7577
+ }
7578
+ }
7579
+ return this.Get(fieldName);
7580
+ }, (raw) => {
7581
+ if (!inAccessorWrite && accessors.set) {
7582
+ inAccessorWrite = true;
7583
+ try {
7584
+ accessors.set.call(this, raw);
7585
+ return;
7586
+ }
7587
+ finally {
7588
+ inAccessorWrite = false;
7589
+ }
7590
+ }
7591
+ this.Set(fieldName, raw);
7592
+ });
6595
7593
  this._jsonFieldBindings.set(fieldName, binding);
6596
7594
  }
6597
7595
  return binding;
@@ -6671,6 +7669,11 @@ export class BaseEntity {
6671
7669
  }
6672
7670
  ValidateJSONFieldValue(fieldName, this.Get(fieldName), schema, rules, severity, this, result);
6673
7671
  }
7672
+ setChainInSaveValidation(flag) {
7673
+ for (let node = this; node; node = node._parentEntity) {
7674
+ node._inSaveValidation = flag;
7675
+ }
7676
+ }
6674
7677
  Validate() {
6675
7678
  if (this._isValidating) {
6676
7679
  const emptyResult = new ValidationResult();
@@ -6698,10 +7701,38 @@ export class BaseEntity {
6698
7701
  if (this._parentEntityFieldNames?.has(field.Name))
6699
7702
  continue; // skip parent field mirrors — authoritative validation is on _parentEntity
6700
7703
  const err = field.Validate();
6701
- err.Errors.forEach(element => {
6702
- result.Errors.push(element);
6703
- });
6704
- result.Success = result.Success && err.Success; // if any field fails, we fail, but keep going to get all of the validation messages
7704
+ const suppressPreSaveNullForAutoNumber = !this.IsSaved &&
7705
+ (field.Value === null ||
7706
+ field.Value === undefined ||
7707
+ (typeof field.Value === 'string' && field.Value.trim().length === 0)) &&
7708
+ DocumentNumberingEngine.Instance.WillAutoPopulateOnCreate(this.EntityInfo, field.Name);
7709
+ if (suppressPreSaveNullForAutoNumber) {
7710
+ const nullErrorMessage = `${field.EntityFieldInfo.DisplayNameOrName} cannot be null`;
7711
+ const retainedErrors = err.Errors.filter((e) => e.Message !== nullErrorMessage);
7712
+ retainedErrors.forEach((element) => {
7713
+ result.Errors.push(element);
7714
+ });
7715
+ if (retainedErrors.length > 0) {
7716
+ result.Success = false;
7717
+ }
7718
+ }
7719
+ else {
7720
+ err.Errors.forEach(element => {
7721
+ result.Errors.push(element);
7722
+ });
7723
+ result.Success = result.Success && err.Success; // if any field fails, we fail, but keep going to get all of the validation messages
7724
+ }
7725
+ }
7726
+ // Declarative & programmatic lifecycle state machine, field-freeze, and auto-number reserved-namespace rules
7727
+ EntityLifecyclePolicyEngine.Instance.ValidateLifecycleOnEntity(this, this.resolveActiveUserOrNull() ?? this.ActiveUser, result);
7728
+ DocumentNumberingEngine.Instance.ValidateAutoNumberFields(this, result);
7729
+ // Type-table validation: ensure any ExtensionEntity column referenced by a parent entity's
7730
+ // SubtypeSelector.Path names a declared IS-A child of that parent entity
7731
+ this.validateSubtypeTypeRowFields(result);
7732
+ // Synchronous cached subtype-driver validation when Validate() is invoked directly
7733
+ // (during Save(), _innerSave runs validateSubtypeDriverAsync instead so cold caches load)
7734
+ if (!this._inSaveValidation) {
7735
+ this.validateSubtypeDriverSync(result);
6705
7736
  }
6706
7737
  // Companions validate LAST but still BEFORE any write, over their complete state including
6707
7738
  // pending removals. That ordering is what lets a cross-child invariant — "debits must equal
@@ -6910,6 +7941,13 @@ export class BaseEntity {
6910
7941
  }
6911
7942
  const unit = part?.unit ?? enclosing;
6912
7943
  this.CheckPermissions(EntityPermissionType.Delete, true); // this will throw an error and exit out if we don't have permission
7944
+ if (!_options.ReplayOnly) {
7945
+ const gateError = EntityLifecyclePolicyEngine.Instance.CheckWritePermissionGate(this, 'Delete', this.ActiveUser, this.isDatabaseProvider());
7946
+ if (gateError) {
7947
+ throw new Error(gateError);
7948
+ }
7949
+ await this.runPreDeleteHooks();
7950
+ }
6913
7951
  // Raise delete_started event before the actual delete operation begins
6914
7952
  this.RaiseEvent('delete_started', null);
6915
7953
  // stash the old values for the event