@memberjunction/core 6.2.1 → 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.
- 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.map +1 -1
- package/dist/generic/baseEngineRegistry.js +8 -1
- package/dist/generic/baseEngineRegistry.js.map +1 -1
- package/dist/generic/baseEntity.d.ts +147 -3
- package/dist/generic/baseEntity.d.ts.map +1 -1
- package/dist/generic/baseEntity.js +1063 -25
- package/dist/generic/baseEntity.js.map +1 -1
- package/dist/generic/baseRemotableOperation.d.ts +15 -0
- package/dist/generic/baseRemotableOperation.d.ts.map +1 -1
- package/dist/generic/baseRemotableOperation.js +11 -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/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 +14 -1
- package/dist/generic/dataHooks.d.ts.map +1 -1
- package/dist/generic/dataHooks.js.map +1 -1
- package/dist/generic/databaseProviderBase.d.ts +37 -0
- package/dist/generic/databaseProviderBase.d.ts.map +1 -1
- package/dist/generic/databaseProviderBase.js +220 -24
- 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 +104 -3
- package/dist/generic/entityInfo.d.ts.map +1 -1
- package/dist/generic/entityInfo.js +326 -22
- 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/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 +56 -1
- package/dist/generic/interfaces.d.ts.map +1 -1
- package/dist/generic/interfaces.js +0 -1
- package/dist/generic/interfaces.js.map +1 -1
- package/dist/generic/localCacheManager.d.ts +46 -3
- package/dist/generic/localCacheManager.d.ts.map +1 -1
- package/dist/generic/localCacheManager.js +267 -45
- package/dist/generic/localCacheManager.js.map +1 -1
- package/dist/generic/metadata.d.ts +3 -1
- package/dist/generic/metadata.d.ts.map +1 -1
- package/dist/generic/metadata.js +25 -6
- package/dist/generic/metadata.js.map +1 -1
- package/dist/generic/providerBase.d.ts +212 -33
- package/dist/generic/providerBase.d.ts.map +1 -1
- package/dist/generic/providerBase.js +543 -117
- 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/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/transactionGroup.d.ts +25 -0
- package/dist/generic/transactionGroup.d.ts.map +1 -1
- package/dist/generic/transactionGroup.js +105 -0
- package/dist/generic/transactionGroup.js.map +1 -1
- package/dist/generic/typedQuery.d.ts +151 -0
- package/dist/generic/typedQuery.d.ts.map +1 -0
- package/dist/generic/typedQuery.js +286 -0
- package/dist/generic/typedQuery.js.map +1 -0
- 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/views/runView.d.ts +53 -0
- package/dist/views/runView.d.ts.map +1 -1
- package/dist/views/runView.js +134 -0
- package/dist/views/runView.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Batch-Aware Cross-Entity Policy Engine (`CrossEntityPolicyEngine`).
|
|
3
|
+
*
|
|
4
|
+
* Enforces cross-record invariants across `Save()`, `Delete()`, `MJ.SaveEntityGraph`, and
|
|
5
|
+
* `TransactionGroupBase.Submit()` without incurring `O(N)` per-row parent `RunView` queries:
|
|
6
|
+
*
|
|
7
|
+
* 1. **Transaction-Epoch Scoped Memoization + Promise Coalescing**:
|
|
8
|
+
* - When a provider has an active transaction (`provider.TransactionScopeCacheKey !== null`),
|
|
9
|
+
* all `CrossEntityEvaluationScope.GetOrLoad(namespace, partitionKey, loader)` calls within that
|
|
10
|
+
* transaction share an in-flight `Promise` cache—collapsing 200 sequential or concurrent child
|
|
11
|
+
* saves referencing the same parent into **1 single parent query**.
|
|
12
|
+
* - Outside an active transaction (`TransactionScopeCacheKey === null`), each evaluation creates
|
|
13
|
+
* an ephemeral scope discarded immediately when the call completes so stale snapshots never leak.
|
|
14
|
+
* 2. **Intra-Transaction Mutation Invalidation & Settle Cleanup**:
|
|
15
|
+
* - Saving or deleting a parent record inside an open transaction calls
|
|
16
|
+
* {@link CrossEntityPolicyEngine.NotifyEntityMutated}, immediately evicting cached snapshots for
|
|
17
|
+
* that `(EntityName, PrimaryKey)` pair so subsequent writes in the same transaction observe the
|
|
18
|
+
* updated parent state.
|
|
19
|
+
* - Transaction commit/rollback calls `ClearProviderScope(provider)` via `BumpTransactionEpoch()`.
|
|
20
|
+
* 3. **Built-In Declarative `ParentStateLock` + Programmatic `ICrossEntityPolicy` (`EvaluateBatch`)**:
|
|
21
|
+
* - Entities can declare parent-status write locks in `EntityInfo.Settings` (`'CrossEntityPolicies'`)
|
|
22
|
+
* or `IEntityConfiguration.CrossEntityPolicies`, automatically batching `ID IN (...)` parent
|
|
23
|
+
* queries in `PreEvaluateBatch`.
|
|
24
|
+
*
|
|
25
|
+
* @module @memberjunction/core
|
|
26
|
+
*/
|
|
27
|
+
import { BaseSingleton, NormalizeUUID, SafeJSONParse } from '@memberjunction/global';
|
|
28
|
+
import { ServerOperationScopeManager } from './entityLifecyclePolicy.js';
|
|
29
|
+
import { LogError } from './logging.js';
|
|
30
|
+
class DefaultCrossEntityEvaluationScope {
|
|
31
|
+
constructor(ScopeId, Provider, ContextUser) {
|
|
32
|
+
this.ScopeId = ScopeId;
|
|
33
|
+
this.Provider = Provider;
|
|
34
|
+
this.ContextUser = ContextUser;
|
|
35
|
+
this._entries = new Map();
|
|
36
|
+
this._preEvaluatedEntities = new Map();
|
|
37
|
+
}
|
|
38
|
+
MarkPreEvaluated(entity, operation) {
|
|
39
|
+
this._preEvaluatedEntities.set(entity, operation);
|
|
40
|
+
}
|
|
41
|
+
IsPreEvaluated(entity, operation) {
|
|
42
|
+
return this._preEvaluatedEntities.get(entity) === operation;
|
|
43
|
+
}
|
|
44
|
+
ClearPreEvaluated() {
|
|
45
|
+
this._preEvaluatedEntities.clear();
|
|
46
|
+
}
|
|
47
|
+
GetOrLoad(cacheNamespace, partitionKey, loader) {
|
|
48
|
+
const key = this.composeKey(cacheNamespace, partitionKey);
|
|
49
|
+
const existing = this._entries.get(key);
|
|
50
|
+
if (existing !== undefined) {
|
|
51
|
+
return existing;
|
|
52
|
+
}
|
|
53
|
+
const inFlight = loader().catch((err) => {
|
|
54
|
+
if (this._entries.get(key) === inFlight) {
|
|
55
|
+
this._entries.delete(key);
|
|
56
|
+
}
|
|
57
|
+
throw err;
|
|
58
|
+
});
|
|
59
|
+
this._entries.set(key, inFlight);
|
|
60
|
+
return inFlight;
|
|
61
|
+
}
|
|
62
|
+
Prime(cacheNamespace, partitionKey, value) {
|
|
63
|
+
const key = this.composeKey(cacheNamespace, partitionKey);
|
|
64
|
+
this._entries.set(key, Promise.resolve(value));
|
|
65
|
+
}
|
|
66
|
+
Invalidate(cacheNamespace, partitionKey) {
|
|
67
|
+
this._preEvaluatedEntities.clear();
|
|
68
|
+
const normalizedNs = cacheNamespace.trim().toLowerCase();
|
|
69
|
+
if (partitionKey !== undefined) {
|
|
70
|
+
this._entries.delete(this.composeKey(normalizedNs, partitionKey));
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const prefix = `${normalizedNs}::`;
|
|
74
|
+
for (const key of Array.from(this._entries.keys())) {
|
|
75
|
+
if (key.startsWith(prefix)) {
|
|
76
|
+
this._entries.delete(key);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
InvalidateNamespacePrefix(namespacePrefix, partitionKey) {
|
|
81
|
+
this._preEvaluatedEntities.clear();
|
|
82
|
+
const normalizedPrefix = namespacePrefix.trim().toLowerCase();
|
|
83
|
+
const normalizedSuffix = partitionKey !== undefined ? `::${partitionKey.trim().toLowerCase()}` : null;
|
|
84
|
+
for (const key of Array.from(this._entries.keys())) {
|
|
85
|
+
if (!key.startsWith(normalizedPrefix)) {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (normalizedSuffix === null || key.endsWith(normalizedSuffix)) {
|
|
89
|
+
this._entries.delete(key);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
composeKey(cacheNamespace, partitionKey) {
|
|
94
|
+
return `${cacheNamespace.trim().toLowerCase()}::${partitionKey.trim().toLowerCase()}`;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const SAFE_UUID_OR_ALNUM_KEY_REGEX = /^[A-Za-z0-9_.:-]+$/;
|
|
98
|
+
const BATCH_CHUNK_SIZE = 500;
|
|
99
|
+
/**
|
|
100
|
+
* Process-wide singleton managing declarative and programmatic cross-entity save/delete policies
|
|
101
|
+
* with transaction-scoped memoization and batch pre-warming.
|
|
102
|
+
*/
|
|
103
|
+
export class CrossEntityPolicyEngine extends BaseSingleton {
|
|
104
|
+
static { this.CROSS_ENTITY_POLICIES_SETTING_NAME = 'CrossEntityPolicies'; }
|
|
105
|
+
constructor() {
|
|
106
|
+
super();
|
|
107
|
+
this._programmaticPolicies = new Map();
|
|
108
|
+
this._declarativeCache = new Map();
|
|
109
|
+
this._providerScopes = new WeakMap();
|
|
110
|
+
this._transactionGroupScopes = new WeakMap();
|
|
111
|
+
this._ephemeralScopeCounter = 0;
|
|
112
|
+
this._txGroupScopeCounter = 0;
|
|
113
|
+
}
|
|
114
|
+
static get Instance() {
|
|
115
|
+
return super.getInstance();
|
|
116
|
+
}
|
|
117
|
+
RegisterPolicy(policy) {
|
|
118
|
+
if (!policy.PolicyKey || policy.PolicyKey.trim().length === 0) {
|
|
119
|
+
throw new Error('CrossEntityPolicyEngine.RegisterPolicy: PolicyKey must be non-empty.');
|
|
120
|
+
}
|
|
121
|
+
this._programmaticPolicies.set(policy.PolicyKey.trim().toLowerCase(), policy);
|
|
122
|
+
}
|
|
123
|
+
UnregisterPolicy(policyKey) {
|
|
124
|
+
this._programmaticPolicies.delete(policyKey.trim().toLowerCase());
|
|
125
|
+
}
|
|
126
|
+
ClearProgrammaticPolicies() {
|
|
127
|
+
this._programmaticPolicies.clear();
|
|
128
|
+
this._declarativeCache.clear();
|
|
129
|
+
}
|
|
130
|
+
ClearProviderScope(provider) {
|
|
131
|
+
this._providerScopes.delete(provider);
|
|
132
|
+
}
|
|
133
|
+
ClearTransactionGroupScope(transactionGroup) {
|
|
134
|
+
this._transactionGroupScopes.delete(transactionGroup);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Resolves or creates the evaluation scope for `provider` (and optional `transactionGroup`),
|
|
138
|
+
* partitioned by `contextUser?.ID` so two different users never share RLS-scoped parent snapshots:
|
|
139
|
+
* - When `transactionGroup` is supplied (items enrolling into / submitting a `TransactionGroupBase`),
|
|
140
|
+
* returns the shared memoizing scope bound to that `(TransactionGroupBase, user)` pair.
|
|
141
|
+
* - Inside an active provider transaction (`TransactionScopeCacheKey !== null`), returns the shared
|
|
142
|
+
* memoizing scope bound to that `(transactionEpoch, user)` pair.
|
|
143
|
+
* - Outside both, returns a fresh single-call ephemeral scope so snapshots never outlive the call.
|
|
144
|
+
*/
|
|
145
|
+
ResolveScope(provider, contextUser, transactionGroup) {
|
|
146
|
+
return this.resolveInternalScope(provider, contextUser, transactionGroup);
|
|
147
|
+
}
|
|
148
|
+
resolveInternalScope(provider, contextUser, transactionGroup) {
|
|
149
|
+
const userKey = contextUser?.ID ? NormalizeUUID(contextUser.ID) : '__anon__';
|
|
150
|
+
if (transactionGroup) {
|
|
151
|
+
let tgMap = this._transactionGroupScopes.get(transactionGroup);
|
|
152
|
+
if (!tgMap) {
|
|
153
|
+
tgMap = new Map();
|
|
154
|
+
this._transactionGroupScopes.set(transactionGroup, tgMap);
|
|
155
|
+
}
|
|
156
|
+
let tgScope = tgMap.get(userKey);
|
|
157
|
+
if (!tgScope) {
|
|
158
|
+
tgScope = new DefaultCrossEntityEvaluationScope(`tg:${++this._txGroupScopeCounter}:${userKey}`, provider, contextUser);
|
|
159
|
+
tgMap.set(userKey, tgScope);
|
|
160
|
+
}
|
|
161
|
+
return tgScope;
|
|
162
|
+
}
|
|
163
|
+
const txKey = provider.TransactionScopeCacheKey ?? null;
|
|
164
|
+
if (!txKey) {
|
|
165
|
+
return new DefaultCrossEntityEvaluationScope(`ephemeral:${++this._ephemeralScopeCounter}:${userKey}`, provider, contextUser);
|
|
166
|
+
}
|
|
167
|
+
let mapForProvider = this._providerScopes.get(provider);
|
|
168
|
+
if (!mapForProvider) {
|
|
169
|
+
mapForProvider = new Map();
|
|
170
|
+
this._providerScopes.set(provider, mapForProvider);
|
|
171
|
+
}
|
|
172
|
+
const compositeKey = `${txKey}::${userKey}`;
|
|
173
|
+
let scope = mapForProvider.get(compositeKey);
|
|
174
|
+
if (!scope) {
|
|
175
|
+
// Evict any prior epoch entries on this provider while keeping entries for the current txKey across users.
|
|
176
|
+
const currentEpochPrefix = `${txKey}::`;
|
|
177
|
+
for (const existingKey of Array.from(mapForProvider.keys())) {
|
|
178
|
+
if (!existingKey.startsWith(currentEpochPrefix)) {
|
|
179
|
+
mapForProvider.delete(existingKey);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
scope = new DefaultCrossEntityEvaluationScope(compositeKey, provider, contextUser);
|
|
183
|
+
mapForProvider.set(compositeKey, scope);
|
|
184
|
+
}
|
|
185
|
+
return scope;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Notifies the engine that `entity` was created, updated, or deleted on `provider`, immediately
|
|
189
|
+
* invalidating any cached parent status snapshots for that entity and primary key in the active
|
|
190
|
+
* transaction scope.
|
|
191
|
+
*/
|
|
192
|
+
NotifyEntityMutated(provider, entity, _operation) {
|
|
193
|
+
const mapForProvider = this._providerScopes.get(provider);
|
|
194
|
+
const tgMap = entity.TransactionGroup
|
|
195
|
+
? this._transactionGroupScopes.get(entity.TransactionGroup)
|
|
196
|
+
: undefined;
|
|
197
|
+
if ((!mapForProvider || mapForProvider.size === 0) && (!tgMap || tgMap.size === 0)) {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const entityNameLower = entity.EntityInfo.Name.trim().toLowerCase();
|
|
201
|
+
const pkFields = entity.EntityInfo.PrimaryKeys;
|
|
202
|
+
const singlePkVal = pkFields.length === 1 ? entity.GetFieldByName(pkFields[0].Name)?.Value : null;
|
|
203
|
+
const partitionPrefix = singlePkVal !== null && singlePkVal !== undefined ? String(singlePkVal).trim() : undefined;
|
|
204
|
+
const scopesToInvalidate = [
|
|
205
|
+
...(mapForProvider ? Array.from(mapForProvider.values()) : []),
|
|
206
|
+
...(tgMap ? Array.from(tgMap.values()) : []),
|
|
207
|
+
];
|
|
208
|
+
for (const scope of scopesToInvalidate) {
|
|
209
|
+
scope.InvalidateNamespacePrefix(`parent:${entityNameLower}:`, partitionPrefix);
|
|
210
|
+
// Also invalidate any custom policy caches namespaced by entity name.
|
|
211
|
+
scope.Invalidate(`entity:${entityNameLower}`, partitionPrefix);
|
|
212
|
+
scope.InvalidateNamespacePrefix(`entity:${entityNameLower}:`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Bulk-primes declarative parent-lock snapshots into the active scope for a batch or graph
|
|
217
|
+
* of entity operations without marking individual items as pre-evaluated, so each item's
|
|
218
|
+
* own `EnforceBeforeSave` / `EnforceBeforeDelete` still runs after `Prepare()`, RLS, and
|
|
219
|
+
* before-save hooks while enjoying $O(1)$ cache hits on parent state lookups.
|
|
220
|
+
*/
|
|
221
|
+
async PrimeParentLocksForBatch(items, provider, contextUser, transactionGroup) {
|
|
222
|
+
if (items.length === 0) {
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const scope = this.resolveInternalScope(provider, contextUser, transactionGroup);
|
|
226
|
+
await this.primeDeclarativeParentLocksForBatch(items, scope);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Batch pre-evaluation and cache pre-warming across multiple entity mutations (`MJ.SaveEntityGraph`,
|
|
230
|
+
* `TransactionGroupBase.Submit`, or bulk imports). Returns `null` when all items pass, or the first
|
|
231
|
+
* refusal message encountered.
|
|
232
|
+
*/
|
|
233
|
+
async PreEvaluateBatch(items, provider, contextUser, transactionGroup) {
|
|
234
|
+
const validItems = items.filter((item) => Boolean(item.Entity?.EntityInfo?.Name));
|
|
235
|
+
if (validItems.length === 0) {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
const scope = this.resolveInternalScope(provider, contextUser, transactionGroup);
|
|
239
|
+
// 1. Bulk-prime declarative ParentStateLock lookups (including in-batch parent creates/updates/deletes)
|
|
240
|
+
// with chunked `ID IN (...)` RunView queries per parent entity.
|
|
241
|
+
await this.primeDeclarativeParentLocksForBatch(validItems, scope);
|
|
242
|
+
// 2. Run programmatic policies that implement `EvaluateBatch`.
|
|
243
|
+
const allProgrammatic = this.sortedProgrammaticPolicies();
|
|
244
|
+
for (const policy of allProgrammatic) {
|
|
245
|
+
if (!policy.EvaluateBatch) {
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const targetSet = new Set(policy.TargetEntityNames.map((n) => n.trim().toLowerCase()));
|
|
249
|
+
const matchingItems = validItems.filter((item) => targetSet.has(item.Entity.EntityInfo.Name.trim().toLowerCase()));
|
|
250
|
+
if (matchingItems.length === 0) {
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const verdicts = await policy.EvaluateBatch(matchingItems, scope);
|
|
254
|
+
if (verdicts) {
|
|
255
|
+
for (const item of matchingItems) {
|
|
256
|
+
const verdict = verdicts.get(item.Entity);
|
|
257
|
+
if (verdict && !verdict.Allowed) {
|
|
258
|
+
return (verdict.ErrorMessage ??
|
|
259
|
+
`Cross-entity policy '${policy.PolicyKey}' refused ${item.Operation} on ${item.Entity.EntityInfo.Name}.`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
// 3. Evaluate declarative locks and per-item programmatic policies against the now-primed scope
|
|
265
|
+
// so batch callers fail fast before SQL runs.
|
|
266
|
+
for (const item of validItems) {
|
|
267
|
+
const declPolicies = this.ResolveDeclarativePolicies(item.Entity.EntityInfo);
|
|
268
|
+
for (const decl of declPolicies) {
|
|
269
|
+
const err = await this.evaluateDeclarativeLock(item.Entity, item.Operation, decl, scope);
|
|
270
|
+
if (err) {
|
|
271
|
+
return err;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const progPolicies = this.getProgrammaticPoliciesForEntity(item.Entity.EntityInfo.Name);
|
|
275
|
+
for (const prog of progPolicies) {
|
|
276
|
+
// Skip if already evaluated by EvaluateBatch above without per-item hooks, or run per-item hook against primed scope
|
|
277
|
+
if (item.Operation === 'Delete' && prog.EvaluateBeforeDelete) {
|
|
278
|
+
const verdict = await prog.EvaluateBeforeDelete({
|
|
279
|
+
Entity: item.Entity,
|
|
280
|
+
Operation: 'Delete',
|
|
281
|
+
Scope: scope,
|
|
282
|
+
});
|
|
283
|
+
if (!verdict.Allowed) {
|
|
284
|
+
return (verdict.ErrorMessage ??
|
|
285
|
+
`Cross-entity policy '${prog.PolicyKey}' refused Delete on ${item.Entity.EntityInfo.Name}.`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
else if (item.Operation !== 'Delete' && prog.EvaluateBeforeSave) {
|
|
289
|
+
const verdict = await prog.EvaluateBeforeSave({
|
|
290
|
+
Entity: item.Entity,
|
|
291
|
+
Operation: item.Operation,
|
|
292
|
+
Scope: scope,
|
|
293
|
+
});
|
|
294
|
+
if (!verdict.Allowed) {
|
|
295
|
+
return (verdict.ErrorMessage ??
|
|
296
|
+
`Cross-entity policy '${prog.PolicyKey}' refused ${item.Operation} on ${item.Entity.EntityInfo.Name}.`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
scope.MarkPreEvaluated(item.Entity, item.Operation);
|
|
301
|
+
}
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Enforces all declarative and programmatic cross-entity policies before saving `entity`.
|
|
306
|
+
* Returns `null` when allowed, or a refusal error message when vetoed.
|
|
307
|
+
*/
|
|
308
|
+
async EnforceBeforeSave(entity, contextUser, provider, saveContext) {
|
|
309
|
+
const operation = entity.IsSaved ? 'Update' : 'Create';
|
|
310
|
+
const declPolicies = this.ResolveDeclarativePolicies(entity.EntityInfo);
|
|
311
|
+
const progPolicies = this.getProgrammaticPoliciesForEntity(entity.EntityInfo.Name);
|
|
312
|
+
if (declPolicies.length === 0 && progPolicies.length === 0) {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
const scope = this.resolveInternalScope(provider, contextUser, entity.TransactionGroup);
|
|
316
|
+
if (scope.IsPreEvaluated(entity, operation)) {
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
for (const decl of declPolicies) {
|
|
320
|
+
const err = await this.evaluateDeclarativeLock(entity, operation, decl, scope);
|
|
321
|
+
if (err) {
|
|
322
|
+
return err;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const ctx = {
|
|
326
|
+
Entity: entity,
|
|
327
|
+
Operation: operation,
|
|
328
|
+
Scope: scope,
|
|
329
|
+
SaveContext: saveContext,
|
|
330
|
+
};
|
|
331
|
+
for (const policy of progPolicies) {
|
|
332
|
+
if (!policy.EvaluateBeforeSave) {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
const verdict = await policy.EvaluateBeforeSave(ctx);
|
|
336
|
+
if (!verdict.Allowed) {
|
|
337
|
+
return (verdict.ErrorMessage ??
|
|
338
|
+
`Cross-entity policy '${policy.PolicyKey}' refused ${operation} on ${entity.EntityInfo.Name}.`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Enforces all declarative and programmatic cross-entity policies before deleting `entity`.
|
|
345
|
+
* Returns `null` when allowed, or a refusal error message when vetoed.
|
|
346
|
+
*/
|
|
347
|
+
async EnforceBeforeDelete(entity, contextUser, provider) {
|
|
348
|
+
const declPolicies = this.ResolveDeclarativePolicies(entity.EntityInfo);
|
|
349
|
+
const progPolicies = this.getProgrammaticPoliciesForEntity(entity.EntityInfo.Name);
|
|
350
|
+
if (declPolicies.length === 0 && progPolicies.length === 0) {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
const scope = this.resolveInternalScope(provider, contextUser, entity.TransactionGroup);
|
|
354
|
+
if (scope.IsPreEvaluated(entity, 'Delete')) {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
for (const decl of declPolicies) {
|
|
358
|
+
const err = await this.evaluateDeclarativeLock(entity, 'Delete', decl, scope);
|
|
359
|
+
if (err) {
|
|
360
|
+
return err;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const ctx = {
|
|
364
|
+
Entity: entity,
|
|
365
|
+
Operation: 'Delete',
|
|
366
|
+
Scope: scope,
|
|
367
|
+
};
|
|
368
|
+
for (const policy of progPolicies) {
|
|
369
|
+
if (!policy.EvaluateBeforeDelete) {
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
const verdict = await policy.EvaluateBeforeDelete(ctx);
|
|
373
|
+
if (!verdict.Allowed) {
|
|
374
|
+
return (verdict.ErrorMessage ??
|
|
375
|
+
`Cross-entity policy '${policy.PolicyKey}' refused Delete on ${entity.EntityInfo.Name}.`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
ResolveDeclarativePolicies(entityInfo) {
|
|
381
|
+
if (!entityInfo || !entityInfo.Name) {
|
|
382
|
+
return [];
|
|
383
|
+
}
|
|
384
|
+
const settings = entityInfo.Settings ?? [];
|
|
385
|
+
const setting = settings.find((s) => s.Name?.trim().toLowerCase() ===
|
|
386
|
+
CrossEntityPolicyEngine.CROSS_ENTITY_POLICIES_SETTING_NAME.toLowerCase());
|
|
387
|
+
const configPolicies = entityInfo.ConfigurationObject?.CrossEntityPolicies;
|
|
388
|
+
const signature = `${setting?.Value ?? ''}|${configPolicies ? JSON.stringify(configPolicies) : ''}`;
|
|
389
|
+
if (signature === '|') {
|
|
390
|
+
return [];
|
|
391
|
+
}
|
|
392
|
+
const cacheKey = entityInfo.ID || entityInfo.Name;
|
|
393
|
+
const cached = this._declarativeCache.get(cacheKey);
|
|
394
|
+
if (cached && cached.signature === signature) {
|
|
395
|
+
return cached.policies;
|
|
396
|
+
}
|
|
397
|
+
const list = [];
|
|
398
|
+
if (configPolicies && configPolicies.length > 0) {
|
|
399
|
+
for (const raw of configPolicies) {
|
|
400
|
+
list.push(this.normalizeDeclarativePolicy(raw));
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (setting?.Value && setting.Value.trim().length > 0) {
|
|
404
|
+
const parsed = SafeJSONParse(setting.Value, false);
|
|
405
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
406
|
+
LogError(`CrossEntityPolicyEngine: invalid JSON in EntitySetting '${CrossEntityPolicyEngine.CROSS_ENTITY_POLICIES_SETTING_NAME}' on entity '${entityInfo.Name}'; failing closed.`);
|
|
407
|
+
const invalidSentinel = {
|
|
408
|
+
foreignKeyField: '__INVALID_METADATA_CROSS_ENTITY_POLICY__',
|
|
409
|
+
parentEntityName: '__INVALID__',
|
|
410
|
+
parentStatusField: 'Status',
|
|
411
|
+
};
|
|
412
|
+
this._declarativeCache.set(cacheKey, { signature, policies: [invalidSentinel] });
|
|
413
|
+
return [invalidSentinel];
|
|
414
|
+
}
|
|
415
|
+
const arr = Array.isArray(parsed) ? parsed : [parsed];
|
|
416
|
+
for (const raw of arr) {
|
|
417
|
+
list.push(this.normalizeDeclarativePolicy(raw));
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
this._declarativeCache.set(cacheKey, { signature, policies: list });
|
|
421
|
+
return list;
|
|
422
|
+
}
|
|
423
|
+
normalizeDeclarativePolicy(raw) {
|
|
424
|
+
return {
|
|
425
|
+
kind: 'ParentStateLock',
|
|
426
|
+
policyKey: (raw.policyKey ?? raw.PolicyKey),
|
|
427
|
+
foreignKeyField: String(raw.foreignKeyField ?? raw.ForeignKeyField ?? ''),
|
|
428
|
+
parentEntityName: String(raw.parentEntityName ?? raw.ParentEntityName ?? ''),
|
|
429
|
+
parentKeyField: (raw.parentKeyField ?? raw.ParentKeyField),
|
|
430
|
+
parentStatusField: String(raw.parentStatusField ?? raw.ParentStatusField ?? ''),
|
|
431
|
+
allowedParentStates: (raw.allowedParentStates ?? raw.AllowedParentStates),
|
|
432
|
+
forbiddenParentStates: (raw.forbiddenParentStates ?? raw.ForbiddenParentStates),
|
|
433
|
+
operations: (raw.operations ?? raw.Operations),
|
|
434
|
+
allowOrphanWhenForeignKeyNull: (raw.allowOrphanWhenForeignKeyNull ??
|
|
435
|
+
raw.AllowOrphanWhenForeignKeyNull),
|
|
436
|
+
exemptOperations: (raw.exemptOperations ?? raw.ExemptOperations),
|
|
437
|
+
errorMessage: (raw.errorMessage ?? raw.ErrorMessage),
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
extractForeignKeyIdsForOperation(entity, operation, foreignKeyFieldName) {
|
|
441
|
+
const fkField = entity.GetFieldByName(foreignKeyFieldName);
|
|
442
|
+
if (!fkField) {
|
|
443
|
+
return { fieldExists: false, ids: [] };
|
|
444
|
+
}
|
|
445
|
+
if (operation === 'Delete') {
|
|
446
|
+
const raw = fkField.Dirty ? fkField.OldValue : fkField.Value;
|
|
447
|
+
const id = raw !== null && raw !== undefined ? String(raw).trim() : '';
|
|
448
|
+
return { fieldExists: true, ids: id ? [id] : [] };
|
|
449
|
+
}
|
|
450
|
+
if (operation === 'Update') {
|
|
451
|
+
const ids = [];
|
|
452
|
+
if (fkField.Dirty && fkField.OldValue !== null && fkField.OldValue !== undefined) {
|
|
453
|
+
const oldId = String(fkField.OldValue).trim();
|
|
454
|
+
if (oldId) {
|
|
455
|
+
ids.push(oldId);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
const curRaw = fkField.Value;
|
|
459
|
+
const curId = curRaw !== null && curRaw !== undefined ? String(curRaw).trim() : '';
|
|
460
|
+
if (curId && !ids.some((existing) => existing.toLowerCase() === curId.toLowerCase())) {
|
|
461
|
+
ids.push(curId);
|
|
462
|
+
}
|
|
463
|
+
return { fieldExists: true, ids };
|
|
464
|
+
}
|
|
465
|
+
const raw = fkField.Value;
|
|
466
|
+
const id = raw !== null && raw !== undefined ? String(raw).trim() : '';
|
|
467
|
+
return { fieldExists: true, ids: id ? [id] : [] };
|
|
468
|
+
}
|
|
469
|
+
async primeDeclarativeParentLocksForBatch(items, scope) {
|
|
470
|
+
const grouped = new Map();
|
|
471
|
+
for (const item of items) {
|
|
472
|
+
if (!item.Entity?.EntityInfo?.Name) {
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
const policies = this.ResolveDeclarativePolicies(item.Entity.EntityInfo);
|
|
476
|
+
for (const policy of policies) {
|
|
477
|
+
const ops = policy.operations ?? ['Create', 'Update', 'Delete'];
|
|
478
|
+
if (!ops.includes(item.Operation)) {
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
const { fieldExists, ids } = this.extractForeignKeyIdsForOperation(item.Entity, item.Operation, policy.foreignKeyField);
|
|
482
|
+
if (!fieldExists || ids.length === 0) {
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const parentKeyField = policy.parentKeyField ?? 'ID';
|
|
486
|
+
const groupKey = `${policy.parentEntityName.trim().toLowerCase()}::${parentKeyField.toLowerCase()}::${policy.parentStatusField.toLowerCase()}`;
|
|
487
|
+
let bucket = grouped.get(groupKey);
|
|
488
|
+
if (!bucket) {
|
|
489
|
+
bucket = {
|
|
490
|
+
parentEntityName: policy.parentEntityName,
|
|
491
|
+
parentKeyField,
|
|
492
|
+
parentStatusField: policy.parentStatusField,
|
|
493
|
+
parentIds: new Set(),
|
|
494
|
+
};
|
|
495
|
+
grouped.set(groupKey, bucket);
|
|
496
|
+
}
|
|
497
|
+
for (const fkStr of ids) {
|
|
498
|
+
if (SAFE_UUID_OR_ALNUM_KEY_REGEX.test(fkStr)) {
|
|
499
|
+
bucket.parentIds.add(fkStr);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
for (const bucket of grouped.values()) {
|
|
505
|
+
const ns = this.parentCacheNamespace(bucket.parentEntityName, `${bucket.parentKeyField}:${bucket.parentStatusField}`);
|
|
506
|
+
const parentEntityLower = bucket.parentEntityName.trim().toLowerCase();
|
|
507
|
+
// First prime any in-batch parent mutations (e.g. a new parent Order created in the same graph/group
|
|
508
|
+
// alongside its child OrderLines) so children see the in-batch parent state without failing DB lookup.
|
|
509
|
+
for (const item of items) {
|
|
510
|
+
if (item.Entity.EntityInfo.Name.trim().toLowerCase() !== parentEntityLower) {
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
const pkVal = item.Entity.GetFieldByName(bucket.parentKeyField)?.Value;
|
|
514
|
+
const pkStr = pkVal !== null && pkVal !== undefined ? String(pkVal).trim() : '';
|
|
515
|
+
if (!pkStr) {
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (item.Operation === 'Delete') {
|
|
519
|
+
scope.Prime(ns, pkStr, { exists: false, status: '' });
|
|
520
|
+
}
|
|
521
|
+
else {
|
|
522
|
+
const statusVal = item.Entity.GetFieldByName(bucket.parentStatusField)?.Value;
|
|
523
|
+
const statusStr = statusVal !== null && statusVal !== undefined ? String(statusVal).trim() : '';
|
|
524
|
+
scope.Prime(ns, pkStr, { exists: true, status: statusStr });
|
|
525
|
+
}
|
|
526
|
+
for (const id of Array.from(bucket.parentIds)) {
|
|
527
|
+
if (id.toLowerCase() === pkStr.toLowerCase()) {
|
|
528
|
+
bucket.parentIds.delete(id);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
if (bucket.parentIds.size === 0 || !this.isRunViewCapable(scope.Provider)) {
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
const allIds = Array.from(bucket.parentIds);
|
|
536
|
+
for (let offset = 0; offset < allIds.length; offset += BATCH_CHUNK_SIZE) {
|
|
537
|
+
const chunk = allIds.slice(offset, offset + BATCH_CHUNK_SIZE);
|
|
538
|
+
const quotedList = chunk.map((id) => `'${id.replace(/'/g, "''")}'`).join(', ');
|
|
539
|
+
const rv = await scope.Provider.RunView({
|
|
540
|
+
EntityName: bucket.parentEntityName,
|
|
541
|
+
ExtraFilter: `${bucket.parentKeyField} IN (${quotedList})`,
|
|
542
|
+
Fields: [bucket.parentKeyField, bucket.parentStatusField],
|
|
543
|
+
IgnoreMaxRows: true,
|
|
544
|
+
ResultType: 'simple',
|
|
545
|
+
BypassCache: true,
|
|
546
|
+
}, scope.ContextUser);
|
|
547
|
+
if (!rv.Success) {
|
|
548
|
+
LogError(`CrossEntityPolicyEngine.primeDeclarativeParentLocksForBatch: RunView failed for '${bucket.parentEntityName}': ${rv.ErrorMessage ?? 'unknown error'}`);
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
const foundIds = new Set();
|
|
552
|
+
for (const row of rv.Results ?? []) {
|
|
553
|
+
const rowId = String(row[bucket.parentKeyField] ?? '').trim();
|
|
554
|
+
if (rowId) {
|
|
555
|
+
foundIds.add(rowId.toLowerCase());
|
|
556
|
+
const statusStr = String(row[bucket.parentStatusField] ?? '').trim();
|
|
557
|
+
const snap = { exists: true, status: statusStr };
|
|
558
|
+
scope.Prime(ns, rowId, snap);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
for (const requestedId of chunk) {
|
|
562
|
+
if (!foundIds.has(requestedId.toLowerCase())) {
|
|
563
|
+
const missingSnap = { exists: false, status: '' };
|
|
564
|
+
scope.Prime(ns, requestedId, missingSnap);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
async evaluateDeclarativeLock(entity, operation, policy, scope) {
|
|
571
|
+
const ops = policy.operations ?? ['Create', 'Update', 'Delete'];
|
|
572
|
+
if (!ops.includes(operation)) {
|
|
573
|
+
return null;
|
|
574
|
+
}
|
|
575
|
+
if (policy.exemptOperations &&
|
|
576
|
+
policy.exemptOperations.length > 0 &&
|
|
577
|
+
ServerOperationScopeManager.Instance.IsOperationActive(policy.exemptOperations, entity.EntityInfo.Name, scope.ContextUser)) {
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
const { fieldExists, ids } = this.extractForeignKeyIdsForOperation(entity, operation, policy.foreignKeyField);
|
|
581
|
+
if (!fieldExists) {
|
|
582
|
+
LogError(`CrossEntityPolicyEngine: configured foreignKeyField '${policy.foreignKeyField}' does not exist on entity '${entity.EntityInfo.Name}'.`);
|
|
583
|
+
return `Cross-entity policy error on ${entity.EntityInfo.Name}: configured foreignKeyField '${policy.foreignKeyField}' does not exist.`;
|
|
584
|
+
}
|
|
585
|
+
const curFkVal = operation === 'Delete'
|
|
586
|
+
? entity.GetFieldByName(policy.foreignKeyField)?.Dirty
|
|
587
|
+
? entity.GetFieldByName(policy.foreignKeyField)?.OldValue
|
|
588
|
+
: entity.GetFieldByName(policy.foreignKeyField)?.Value
|
|
589
|
+
: entity.GetFieldByName(policy.foreignKeyField)?.Value;
|
|
590
|
+
const curFkId = curFkVal !== null && curFkVal !== undefined ? String(curFkVal).trim() : '';
|
|
591
|
+
if (!curFkId && ids.length === 0) {
|
|
592
|
+
if (policy.allowOrphanWhenForeignKeyNull === false) {
|
|
593
|
+
return (policy.errorMessage ??
|
|
594
|
+
`Cannot ${operation.toLowerCase()} ${entity.EntityInfo.Name}: required parent reference '${policy.foreignKeyField}' is empty.`);
|
|
595
|
+
}
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
if (!curFkId && policy.allowOrphanWhenForeignKeyNull === false) {
|
|
599
|
+
return (policy.errorMessage ??
|
|
600
|
+
`Cannot ${operation.toLowerCase()} ${entity.EntityInfo.Name}: required parent reference '${policy.foreignKeyField}' is empty.`);
|
|
601
|
+
}
|
|
602
|
+
for (const fkId of ids) {
|
|
603
|
+
if (!SAFE_UUID_OR_ALNUM_KEY_REGEX.test(fkId)) {
|
|
604
|
+
return `Invalid parent key '${fkId}' in ${entity.EntityInfo.Name}.${policy.foreignKeyField}.`;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
if (!this.isRunViewCapable(scope.Provider)) {
|
|
608
|
+
return null;
|
|
609
|
+
}
|
|
610
|
+
const runViewProvider = scope.Provider;
|
|
611
|
+
const parentKeyField = policy.parentKeyField ?? 'ID';
|
|
612
|
+
const ns = this.parentCacheNamespace(policy.parentEntityName, `${parentKeyField}:${policy.parentStatusField}`);
|
|
613
|
+
for (const fkId of ids) {
|
|
614
|
+
const snapshot = await scope.GetOrLoad(ns, fkId, async () => {
|
|
615
|
+
const escaped = fkId.replace(/'/g, "''");
|
|
616
|
+
const rv = await runViewProvider.RunView({
|
|
617
|
+
EntityName: policy.parentEntityName,
|
|
618
|
+
ExtraFilter: `${parentKeyField}='${escaped}'`,
|
|
619
|
+
Fields: [parentKeyField, policy.parentStatusField],
|
|
620
|
+
MaxRows: 1,
|
|
621
|
+
ResultType: 'simple',
|
|
622
|
+
BypassCache: true,
|
|
623
|
+
}, scope.ContextUser);
|
|
624
|
+
if (!rv.Success) {
|
|
625
|
+
throw new Error(`CrossEntityPolicyEngine failed to query parent '${policy.parentEntityName}' (${fkId}): ${rv.ErrorMessage ?? 'RunView failed'}`);
|
|
626
|
+
}
|
|
627
|
+
const row = rv.Results?.[0];
|
|
628
|
+
if (!row) {
|
|
629
|
+
return { exists: false, status: '' };
|
|
630
|
+
}
|
|
631
|
+
return {
|
|
632
|
+
exists: true,
|
|
633
|
+
status: String(row[policy.parentStatusField] ?? '').trim(),
|
|
634
|
+
};
|
|
635
|
+
});
|
|
636
|
+
if (!snapshot.exists) {
|
|
637
|
+
return (policy.errorMessage ??
|
|
638
|
+
`Cannot ${operation.toLowerCase()} ${entity.EntityInfo.Name}: parent ${policy.parentEntityName} '${fkId}' does not exist.`);
|
|
639
|
+
}
|
|
640
|
+
if (policy.forbiddenParentStates && policy.forbiddenParentStates.includes(snapshot.status)) {
|
|
641
|
+
return (policy.errorMessage ??
|
|
642
|
+
`Cannot ${operation.toLowerCase()} ${entity.EntityInfo.Name} while parent ${policy.parentEntityName} ${policy.parentStatusField} is '${snapshot.status}'.`);
|
|
643
|
+
}
|
|
644
|
+
if (policy.allowedParentStates &&
|
|
645
|
+
policy.allowedParentStates.length > 0 &&
|
|
646
|
+
!policy.allowedParentStates.includes(snapshot.status)) {
|
|
647
|
+
return (policy.errorMessage ??
|
|
648
|
+
`Cannot ${operation.toLowerCase()} ${entity.EntityInfo.Name} while parent ${policy.parentEntityName} ${policy.parentStatusField} is '${snapshot.status}' (allowed: [${policy.allowedParentStates.join(', ')}]).`);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
parentCacheNamespace(parentEntityName, fieldDescriptor) {
|
|
654
|
+
return `parent:${parentEntityName.trim().toLowerCase()}:${fieldDescriptor.trim().toLowerCase()}`;
|
|
655
|
+
}
|
|
656
|
+
getProgrammaticPoliciesForEntity(entityName) {
|
|
657
|
+
const wanted = entityName.trim().toLowerCase();
|
|
658
|
+
return this.sortedProgrammaticPolicies().filter((p) => p.TargetEntityNames.some((n) => n.trim().toLowerCase() === wanted));
|
|
659
|
+
}
|
|
660
|
+
sortedProgrammaticPolicies() {
|
|
661
|
+
return Array.from(this._programmaticPolicies.values()).sort((a, b) => (b.Priority ?? 0) - (a.Priority ?? 0));
|
|
662
|
+
}
|
|
663
|
+
isRunViewCapable(provider) {
|
|
664
|
+
return typeof provider.RunView === 'function';
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
//# sourceMappingURL=crossEntityPolicyEngine.js.map
|