@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,739 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview First-Class Scoped Document Auto-Numbering (`DocumentNumberingEngine`).
|
|
3
|
+
*
|
|
4
|
+
* Replaces ad-hoc `SELECT MAX(...) + 1`, `Date.now()` suffixes, and per-app stored procedures across
|
|
5
|
+
* business applications with a concurrency-safe, dialect-aware (`sqlserver` + `postgresql`), gap-free
|
|
6
|
+
* transactional numbering engine:
|
|
7
|
+
*
|
|
8
|
+
* - **Rich Pattern Grammar**: `{PREFIX}`, `{YYYY}`, `{YY}`, `{MM}`, `{DD}`, `{FY}`, `{FY2}`, `{TenantID}`,
|
|
9
|
+
* `{Field:FieldName[:TRANSFORM[:FALLBACK]]}`, `{Scope:KeyName}`, and `{SEQ:N}` / `{SEQ}`.
|
|
10
|
+
* - **Multi-Dimensional Partitioning**: independent counters partitioned by `scopeByTenant`, `scopeFields`
|
|
11
|
+
* (e.g. `['CompanyID']`, `['AppScope']`, `['BrandID']`), custom `DocumentScopeResolver` values, and
|
|
12
|
+
* `resetPeriod` (`'Never' | 'CalendarYear' | 'CalendarMonth' | 'FiscalYear'`).
|
|
13
|
+
* - **`NOT NULL` Validation & Reserved Namespace Protection**: `BaseEntity.Validate()` automatically
|
|
14
|
+
* exempts blank auto-numbered fields on unsaved records (`!entity.IsSaved`) while still rejecting null
|
|
15
|
+
* on saved records and preventing hand-typed values from colliding with the system sequence format
|
|
16
|
+
* (`manualValueMode: 'AllowNonColliding'`).
|
|
17
|
+
* - **Trigger-Safe Atomic SQL Allocation**:
|
|
18
|
+
* - SQL Server: `DECLARE @allocated TABLE ... UPDATE ... WITH (UPDLOCK, HOLDLOCK) ... OUTPUT ... INTO @allocated`
|
|
19
|
+
* (safe on tables with triggers, range-locked against concurrent first-row inserts).
|
|
20
|
+
* - PostgreSQL: `INSERT ... ON CONFLICT ("SequenceKey", "ScopeKey") DO UPDATE ... RETURNING`.
|
|
21
|
+
* - Rides the caller's ambient entity transaction (`DatabaseProviderBase.Save()`) for gap-free rollback.
|
|
22
|
+
*
|
|
23
|
+
* @module @memberjunction/core
|
|
24
|
+
*/
|
|
25
|
+
import { BaseSingleton, NormalizeUUID, SafeJSONParse, ValidationErrorInfo, ValidationErrorType, } from '@memberjunction/global';
|
|
26
|
+
import { LogError } from './logging.js';
|
|
27
|
+
const SAFE_SQL_IDENTIFIER_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
28
|
+
/**
|
|
29
|
+
* Production SQL sequence store backed by `${MJCoreSchemaName}.DocumentSequenceCounter`.
|
|
30
|
+
* Emits trigger-safe `UPDLOCK, HOLDLOCK` + `OUTPUT ... INTO` on SQL Server and atomic
|
|
31
|
+
* `INSERT ... ON CONFLICT DO UPDATE RETURNING` on PostgreSQL, riding `provider.ExecuteSQL`
|
|
32
|
+
* inside the caller's active transaction.
|
|
33
|
+
*/
|
|
34
|
+
export class SqlTableDocumentSequenceStore {
|
|
35
|
+
BuildAllocateStatement(platform, schemaName, sequenceKey, scopeKey, startAt, incrementBy) {
|
|
36
|
+
if (!SAFE_SQL_IDENTIFIER_REGEX.test(schemaName)) {
|
|
37
|
+
throw new Error(`SqlTableDocumentSequenceStore: invalid schema identifier '${schemaName}'.`);
|
|
38
|
+
}
|
|
39
|
+
if (platform === 'postgresql') {
|
|
40
|
+
const sql = [
|
|
41
|
+
`INSERT INTO "${schemaName}"."DocumentSequenceCounter"`,
|
|
42
|
+
` ("ID", "SequenceKey", "ScopeKey", "CurrentValue")`,
|
|
43
|
+
`VALUES`,
|
|
44
|
+
` (gen_random_uuid(), $1, $2, $3)`,
|
|
45
|
+
`ON CONFLICT ("SequenceKey", "ScopeKey")`,
|
|
46
|
+
`DO UPDATE SET`,
|
|
47
|
+
` "CurrentValue" = "${schemaName}"."DocumentSequenceCounter"."CurrentValue" + $4,`,
|
|
48
|
+
` "__mj_UpdatedAt" = NOW()`,
|
|
49
|
+
`RETURNING "CurrentValue" AS "AllocatedValue";`,
|
|
50
|
+
].join('\n');
|
|
51
|
+
return {
|
|
52
|
+
sql,
|
|
53
|
+
parameters: [sequenceKey, scopeKey, startAt, incrementBy],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const sql = [
|
|
57
|
+
`DECLARE @inc BIGINT = ?;`,
|
|
58
|
+
`DECLARE @seqKey NVARCHAR(255) = ?;`,
|
|
59
|
+
`DECLARE @scpKey NVARCHAR(255) = ?;`,
|
|
60
|
+
`DECLARE @startVal BIGINT = ?;`,
|
|
61
|
+
`DECLARE @allocated TABLE (AllocatedValue BIGINT NOT NULL);`,
|
|
62
|
+
`DECLARE @startedLocalTran BIT = 0;`,
|
|
63
|
+
`IF @@TRANCOUNT = 0`,
|
|
64
|
+
`BEGIN`,
|
|
65
|
+
` BEGIN TRANSACTION;`,
|
|
66
|
+
` SET @startedLocalTran = 1;`,
|
|
67
|
+
`END;`,
|
|
68
|
+
`BEGIN TRY`,
|
|
69
|
+
` UPDATE [${schemaName}].[DocumentSequenceCounter] WITH (UPDLOCK, HOLDLOCK)`,
|
|
70
|
+
` SET [CurrentValue] = [CurrentValue] + @inc`,
|
|
71
|
+
` OUTPUT inserted.[CurrentValue] INTO @allocated(AllocatedValue)`,
|
|
72
|
+
` WHERE [SequenceKey] = @seqKey AND [ScopeKey] = @scpKey;`,
|
|
73
|
+
` IF NOT EXISTS (SELECT 1 FROM @allocated)`,
|
|
74
|
+
` BEGIN`,
|
|
75
|
+
` INSERT INTO [${schemaName}].[DocumentSequenceCounter]`,
|
|
76
|
+
` ([ID], [SequenceKey], [ScopeKey], [CurrentValue])`,
|
|
77
|
+
` OUTPUT inserted.[CurrentValue] INTO @allocated(AllocatedValue)`,
|
|
78
|
+
` VALUES (NEWSEQUENTIALID(), @seqKey, @scpKey, @startVal);`,
|
|
79
|
+
` END;`,
|
|
80
|
+
` IF @startedLocalTran = 1 AND @@TRANCOUNT > 0`,
|
|
81
|
+
` BEGIN`,
|
|
82
|
+
` COMMIT TRANSACTION;`,
|
|
83
|
+
` END;`,
|
|
84
|
+
`END TRY`,
|
|
85
|
+
`BEGIN CATCH`,
|
|
86
|
+
` IF @startedLocalTran = 1 AND @@TRANCOUNT > 0`,
|
|
87
|
+
` BEGIN`,
|
|
88
|
+
` ROLLBACK TRANSACTION;`,
|
|
89
|
+
` END;`,
|
|
90
|
+
` THROW;`,
|
|
91
|
+
`END CATCH;`,
|
|
92
|
+
`SELECT AllocatedValue FROM @allocated;`,
|
|
93
|
+
].join('\n');
|
|
94
|
+
return {
|
|
95
|
+
sql,
|
|
96
|
+
parameters: [incrementBy, sequenceKey, scopeKey, startAt],
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async AllocateNext(request) {
|
|
100
|
+
const stmt = this.BuildAllocateStatement(request.provider.PlatformKey, request.provider.MJCoreSchemaName, request.sequenceKey, request.scopeKey, request.startAt, request.incrementBy);
|
|
101
|
+
const rows = await request.provider.ExecuteSQL(stmt.sql, [...stmt.parameters], {
|
|
102
|
+
isMutation: true,
|
|
103
|
+
description: `DocumentNumberingEngine:${request.sequenceKey}`,
|
|
104
|
+
}, request.contextUser);
|
|
105
|
+
const raw = rows?.[0]?.AllocatedValue ?? rows?.[0]?.allocatedvalue;
|
|
106
|
+
const parsed = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN;
|
|
107
|
+
if (!Number.isFinite(parsed)) {
|
|
108
|
+
throw new Error(`DocumentNumberingEngine failed to allocate sequence value for '${request.sequenceKey}' (scope '${request.scopeKey}').`);
|
|
109
|
+
}
|
|
110
|
+
return parsed;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Deterministic concurrency-safe in-memory sequence store for unit tests and mock providers.
|
|
115
|
+
*/
|
|
116
|
+
export class InMemoryDocumentSequenceStore {
|
|
117
|
+
constructor() {
|
|
118
|
+
this._counters = new Map();
|
|
119
|
+
this._locks = new Map();
|
|
120
|
+
}
|
|
121
|
+
Reset() {
|
|
122
|
+
this._counters.clear();
|
|
123
|
+
this._locks.clear();
|
|
124
|
+
}
|
|
125
|
+
PeekCurrentValue(sequenceKey, scopeKey) {
|
|
126
|
+
return this._counters.get(`${sequenceKey}::${scopeKey}`);
|
|
127
|
+
}
|
|
128
|
+
async AllocateNext(request) {
|
|
129
|
+
const compositeKey = `${request.sequenceKey}::${request.scopeKey}`;
|
|
130
|
+
const prior = this._locks.get(compositeKey) ?? Promise.resolve();
|
|
131
|
+
let releaseGate = () => { };
|
|
132
|
+
const gate = new Promise((resolve) => {
|
|
133
|
+
releaseGate = resolve;
|
|
134
|
+
});
|
|
135
|
+
const tail = prior.then(() => gate);
|
|
136
|
+
this._locks.set(compositeKey, tail);
|
|
137
|
+
await prior;
|
|
138
|
+
try {
|
|
139
|
+
const existing = this._counters.get(compositeKey);
|
|
140
|
+
const nextValue = existing === undefined ? request.startAt : existing + request.incrementBy;
|
|
141
|
+
this._counters.set(compositeKey, nextValue);
|
|
142
|
+
return nextValue;
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
releaseGate();
|
|
146
|
+
if (this._locks.get(compositeKey) === tail) {
|
|
147
|
+
this._locks.delete(compositeKey);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Singleton engine coordinating declarative and programmatic document auto-numbering policies.
|
|
154
|
+
*/
|
|
155
|
+
export class DocumentNumberingEngine extends BaseSingleton {
|
|
156
|
+
static { this.AUTO_NUMBER_SETTING_NAME = 'AutoNumberPolicy'; }
|
|
157
|
+
constructor() {
|
|
158
|
+
super();
|
|
159
|
+
this._programmaticPolicies = new Map();
|
|
160
|
+
this._metadataCache = new Map();
|
|
161
|
+
this._scopeResolvers = new Map();
|
|
162
|
+
this._reservedPatternRegexCache = new Map();
|
|
163
|
+
this._systemAssignedFields = new WeakMap();
|
|
164
|
+
this._assignedPriorValues = new WeakMap();
|
|
165
|
+
this._sequenceStore = new SqlTableDocumentSequenceStore();
|
|
166
|
+
}
|
|
167
|
+
static get Instance() {
|
|
168
|
+
return super.getInstance();
|
|
169
|
+
}
|
|
170
|
+
SetSequenceStore(store) {
|
|
171
|
+
this._sequenceStore = store;
|
|
172
|
+
}
|
|
173
|
+
GetSequenceStore() {
|
|
174
|
+
return this._sequenceStore;
|
|
175
|
+
}
|
|
176
|
+
RegisterPolicy(entityName, policy) {
|
|
177
|
+
const key = entityName.trim().toLowerCase();
|
|
178
|
+
if (!key) {
|
|
179
|
+
throw new Error('DocumentNumberingEngine.RegisterPolicy: entityName must be non-empty.');
|
|
180
|
+
}
|
|
181
|
+
const list = Array.isArray(policy) ? [...policy] : [policy];
|
|
182
|
+
this._programmaticPolicies.set(key, list);
|
|
183
|
+
}
|
|
184
|
+
UnregisterPolicy(entityName) {
|
|
185
|
+
this._programmaticPolicies.delete(entityName.trim().toLowerCase());
|
|
186
|
+
}
|
|
187
|
+
RegisterScopeResolver(sequenceKeyOrEntityName, resolver) {
|
|
188
|
+
this._scopeResolvers.set(sequenceKeyOrEntityName.trim().toLowerCase(), resolver);
|
|
189
|
+
}
|
|
190
|
+
ClearProgrammaticPolicies() {
|
|
191
|
+
this._programmaticPolicies.clear();
|
|
192
|
+
this._metadataCache.clear();
|
|
193
|
+
this._scopeResolvers.clear();
|
|
194
|
+
this._reservedPatternRegexCache.clear();
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Clears system-assigned markers and prior-value snapshots for `entity` (invoked on `NewRecord()`).
|
|
198
|
+
*/
|
|
199
|
+
ClearSystemAssignedMarkers(entity) {
|
|
200
|
+
this._systemAssignedFields.delete(entity);
|
|
201
|
+
this._assignedPriorValues.delete(entity);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Reverts system-assigned field values on `entity` back to their pre-allocation state (typically `null`)
|
|
205
|
+
* when a save or transaction group fails and rolls back.
|
|
206
|
+
*/
|
|
207
|
+
RevertAssignedNumbers(entity, fieldNames) {
|
|
208
|
+
const priorMap = this._assignedPriorValues.get(entity);
|
|
209
|
+
const sysSet = this._systemAssignedFields.get(entity);
|
|
210
|
+
if (!priorMap && !sysSet) {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const targets = fieldNames && fieldNames.length > 0
|
|
214
|
+
? fieldNames
|
|
215
|
+
: priorMap
|
|
216
|
+
? Array.from(priorMap.keys())
|
|
217
|
+
: sysSet
|
|
218
|
+
? Array.from(sysSet.values())
|
|
219
|
+
: [];
|
|
220
|
+
for (const rawName of targets) {
|
|
221
|
+
const keyLower = rawName.trim().toLowerCase();
|
|
222
|
+
const field = entity.GetFieldByName(rawName);
|
|
223
|
+
if (field && priorMap && priorMap.has(keyLower)) {
|
|
224
|
+
field.Value = priorMap.get(keyLower) ?? null;
|
|
225
|
+
}
|
|
226
|
+
else if (field && sysSet?.has(keyLower)) {
|
|
227
|
+
field.Value = null;
|
|
228
|
+
}
|
|
229
|
+
priorMap?.delete(keyLower);
|
|
230
|
+
sysSet?.delete(keyLower);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
ResolvePolicies(entityInfo) {
|
|
234
|
+
if (!entityInfo || !entityInfo.Name) {
|
|
235
|
+
return [];
|
|
236
|
+
}
|
|
237
|
+
const programmatic = this._programmaticPolicies.get(entityInfo.Name.trim().toLowerCase());
|
|
238
|
+
const fromMetadata = this.resolveMetadataPolicies(entityInfo);
|
|
239
|
+
if (!programmatic || programmatic.length === 0) {
|
|
240
|
+
return fromMetadata;
|
|
241
|
+
}
|
|
242
|
+
if (fromMetadata.length === 0) {
|
|
243
|
+
return programmatic;
|
|
244
|
+
}
|
|
245
|
+
// Programmatic policies override metadata policies targeting the same field; remaining metadata policies stay active.
|
|
246
|
+
const overriddenFields = new Set(programmatic.map((p) => p.targetField.trim().toLowerCase()));
|
|
247
|
+
return [
|
|
248
|
+
...fromMetadata.filter((m) => !overriddenFields.has(m.targetField.trim().toLowerCase())),
|
|
249
|
+
...programmatic,
|
|
250
|
+
];
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Whether `ResolverBase.UpdateRecord` MUST load the authoritative stored row from the database
|
|
254
|
+
* to prevent clients from spoofing `OldValues___` on `immutableAfterCreate` auto-numbered fields.
|
|
255
|
+
*/
|
|
256
|
+
RequiresStoredTruthOnUpdate(entityInfo) {
|
|
257
|
+
return this.ResolvePolicies(entityInfo).some((p) => p.immutableAfterCreate !== false);
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Returns true when `fieldName` on `entityInfo` is governed by an active auto-number policy,
|
|
261
|
+
* allowing `BaseEntity.Validate()` to suppress the pre-save `cannot be null` error on new records.
|
|
262
|
+
*/
|
|
263
|
+
WillAutoPopulateOnCreate(entityInfo, fieldName) {
|
|
264
|
+
const wanted = fieldName.trim().toLowerCase();
|
|
265
|
+
return this.ResolvePolicies(entityInfo).some((p) => p.targetField.trim().toLowerCase() === wanted);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Returns true when an unsaved `entity` has at least one auto-numbered target field that is blank
|
|
269
|
+
* and will require counter allocation during `Save()`.
|
|
270
|
+
*/
|
|
271
|
+
NeedsAllocation(entity) {
|
|
272
|
+
if (entity.IsSaved) {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
const policies = this.ResolvePolicies(entity.EntityInfo);
|
|
276
|
+
if (policies.length === 0) {
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
return policies.some((p) => {
|
|
280
|
+
const field = entity.GetFieldByName(p.targetField);
|
|
281
|
+
return field !== null && this.isBlankValue(field.Value);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Returns true when any active auto-number policy on `entityInfo` requests gap-free transactional
|
|
286
|
+
* wrapping (default `true`).
|
|
287
|
+
*/
|
|
288
|
+
RequiresTransactionalSave(entityInfo) {
|
|
289
|
+
return this.ResolvePolicies(entityInfo).some((p) => p.gapFreeTransactional !== false);
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Validates manual overrides on new records (`Forbid` vs `AllowNonColliding` reserved-namespace check)
|
|
293
|
+
* and enforces post-create immutability on saved records.
|
|
294
|
+
*/
|
|
295
|
+
ValidateAutoNumberFields(entity, result) {
|
|
296
|
+
const policies = this.ResolvePolicies(entity.EntityInfo);
|
|
297
|
+
if (policies.length === 0) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const systemAssigned = this._systemAssignedFields.get(entity);
|
|
301
|
+
for (const policy of policies) {
|
|
302
|
+
const field = entity.GetFieldByName(policy.targetField);
|
|
303
|
+
if (!field) {
|
|
304
|
+
LogError(`DocumentNumberingEngine: configured targetField '${policy.targetField}' does not exist on entity '${entity.EntityInfo.Name}'.`);
|
|
305
|
+
result.Success = false;
|
|
306
|
+
result.Errors.push(new ValidationErrorInfo(policy.targetField || entity.EntityInfo.Name, `Auto-number policy error on ${entity.EntityInfo.Name}: targetField '${policy.targetField}' does not exist.`, null, ValidationErrorType.Failure));
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (!policy.pattern || !policy.pattern.includes('{SEQ')) {
|
|
310
|
+
LogError(`DocumentNumberingEngine: pattern '${policy.pattern}' on '${entity.EntityInfo.Name}.${policy.targetField}' must include a {SEQ} token.`);
|
|
311
|
+
result.Success = false;
|
|
312
|
+
result.Errors.push(new ValidationErrorInfo(field.Name, `Auto-number policy error on ${entity.EntityInfo.Name}.${field.Name}: pattern '${policy.pattern}' must include a {SEQ} token.`, null, ValidationErrorType.Failure));
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (policy.incrementBy !== undefined && policy.incrementBy <= 0) {
|
|
316
|
+
LogError(`DocumentNumberingEngine: incrementBy (${policy.incrementBy}) on '${entity.EntityInfo.Name}.${policy.targetField}' must be > 0.`);
|
|
317
|
+
result.Success = false;
|
|
318
|
+
result.Errors.push(new ValidationErrorInfo(field.Name, `Auto-number policy error on ${entity.EntityInfo.Name}.${field.Name}: incrementBy must be > 0.`, policy.incrementBy, ValidationErrorType.Failure));
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
if (!entity.IsSaved) {
|
|
322
|
+
if (this.isBlankValue(field.Value)) {
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (systemAssigned?.has(field.Name.trim().toLowerCase())) {
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
const mode = policy.manualValueMode ?? 'AllowNonColliding';
|
|
329
|
+
const strVal = String(field.Value).trim();
|
|
330
|
+
if (mode === 'Forbid') {
|
|
331
|
+
result.Success = false;
|
|
332
|
+
result.Errors.push(new ValidationErrorInfo(field.Name, `Field '${field.Name}' on ${entity.EntityInfo.Name} is system-numbered and cannot be assigned manually.`, strVal, ValidationErrorType.Failure));
|
|
333
|
+
}
|
|
334
|
+
else if (mode === 'AllowNonColliding') {
|
|
335
|
+
const reservedRegex = this.compileReservedNamespaceRegex(policy);
|
|
336
|
+
if (reservedRegex && reservedRegex.test(strVal)) {
|
|
337
|
+
result.Success = false;
|
|
338
|
+
result.Errors.push(new ValidationErrorInfo(field.Name, `Manual value '${strVal}' for '${field.Name}' uses the reserved system sequence format '${policy.pattern}'. Leave it blank for automatic assignment or use a distinct external prefix.`, strVal, ValidationErrorType.Failure));
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
else if (policy.immutableAfterCreate !== false) {
|
|
343
|
+
if (field.Dirty && String(field.OldValue ?? '') !== String(field.Value ?? '')) {
|
|
344
|
+
result.Success = false;
|
|
345
|
+
result.Errors.push(new ValidationErrorInfo(field.Name, `Auto-numbered field '${field.Name}' on ${entity.EntityInfo.Name} cannot be modified after creation.`, field.Value === null || field.Value === undefined ? null : String(field.Value), ValidationErrorType.Failure));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Allocates and stamps sequence numbers for all blank auto-numbered fields on an unsaved `entity`.
|
|
352
|
+
* Returns the list of field names populated during this call.
|
|
353
|
+
*/
|
|
354
|
+
async AllocateAndAssignForEntity(entity, provider, contextUser, now = new Date()) {
|
|
355
|
+
if (entity.IsSaved) {
|
|
356
|
+
return [];
|
|
357
|
+
}
|
|
358
|
+
const policies = this.ResolvePolicies(entity.EntityInfo);
|
|
359
|
+
if (policies.length === 0) {
|
|
360
|
+
return [];
|
|
361
|
+
}
|
|
362
|
+
const assignedFields = [];
|
|
363
|
+
for (const policy of policies) {
|
|
364
|
+
const field = entity.GetFieldByName(policy.targetField);
|
|
365
|
+
if (!field) {
|
|
366
|
+
throw new Error(`DocumentNumberingEngine: configured targetField '${policy.targetField}' does not exist on ${entity.EntityInfo.Name}.`);
|
|
367
|
+
}
|
|
368
|
+
if (!this.isBlankValue(field.Value)) {
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (!policy.pattern || !policy.pattern.includes('{SEQ')) {
|
|
372
|
+
throw new Error(`DocumentNumberingEngine: pattern '${policy.pattern}' on ${entity.EntityInfo.Name}.${policy.targetField} must include a {SEQ} token.`);
|
|
373
|
+
}
|
|
374
|
+
const incrementBy = policy.incrementBy ?? 1;
|
|
375
|
+
if (incrementBy <= 0) {
|
|
376
|
+
throw new Error(`DocumentNumberingEngine: incrementBy (${incrementBy}) on ${entity.EntityInfo.Name}.${policy.targetField} must be > 0.`);
|
|
377
|
+
}
|
|
378
|
+
const sequenceKey = (policy.sequenceKey?.trim() || `${entity.EntityInfo.Name}.${policy.targetField}`).trim();
|
|
379
|
+
const customScope = await this.resolveCustomScopeMap(entity, policy, sequenceKey, provider, contextUser, now);
|
|
380
|
+
const effectiveDate = this.resolveReferenceDate(entity, policy.dateSourceField, now);
|
|
381
|
+
const fiscalYear = this.computeFiscalYear(effectiveDate, policy.fiscalYearStartMonth ?? 1, customScope);
|
|
382
|
+
const scopeKey = this.BuildScopeKey(entity, policy, contextUser, effectiveDate, fiscalYear, customScope);
|
|
383
|
+
if (scopeKey.length > 255) {
|
|
384
|
+
throw new Error(`DocumentNumberingEngine: derived ScopeKey length (${scopeKey.length}) exceeds 255 characters for '${sequenceKey}'.`);
|
|
385
|
+
}
|
|
386
|
+
const seqValue = await this._sequenceStore.AllocateNext({
|
|
387
|
+
sequenceKey,
|
|
388
|
+
scopeKey,
|
|
389
|
+
startAt: policy.startAt ?? 1,
|
|
390
|
+
incrementBy,
|
|
391
|
+
provider,
|
|
392
|
+
contextUser,
|
|
393
|
+
});
|
|
394
|
+
const formatted = this.FormatPattern(policy, seqValue, entity, contextUser, effectiveDate, fiscalYear, customScope);
|
|
395
|
+
const maxLen = field.EntityFieldInfo.MaxLength;
|
|
396
|
+
if (maxLen > 0 && formatted.length > maxLen) {
|
|
397
|
+
throw new Error(`DocumentNumberingEngine: generated value '${formatted}' (${formatted.length} chars) exceeds MaxLength (${maxLen}) on ${entity.EntityInfo.Name}.${field.Name}.`);
|
|
398
|
+
}
|
|
399
|
+
const priorVal = field.Value;
|
|
400
|
+
field.Value = formatted;
|
|
401
|
+
this.markSystemAssigned(entity, field.Name, priorVal);
|
|
402
|
+
assignedFields.push(field.Name);
|
|
403
|
+
}
|
|
404
|
+
return assignedFields;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Deterministically derives the partition `ScopeKey` for a policy and entity instance.
|
|
408
|
+
*/
|
|
409
|
+
BuildScopeKey(entity, policy, contextUser, referenceDate, fiscalYear, customScope = {}) {
|
|
410
|
+
const segments = [];
|
|
411
|
+
if (policy.scopeByTenant) {
|
|
412
|
+
const tenantId = contextUser?.TenantContext?.TenantID?.trim();
|
|
413
|
+
if (!tenantId) {
|
|
414
|
+
throw new Error(`DocumentNumberingEngine: policy for '${entity.EntityInfo.Name}.${policy.targetField}' requires TenantContext.TenantID (scopeByTenant = true).`);
|
|
415
|
+
}
|
|
416
|
+
segments.push(`Tenant=${tenantId}`);
|
|
417
|
+
}
|
|
418
|
+
const fieldTokenSpecs = this.extractPatternFieldTokenSpecs(policy.pattern);
|
|
419
|
+
if (policy.scopeFields && policy.scopeFields.length > 0) {
|
|
420
|
+
for (const scopeFieldName of policy.scopeFields) {
|
|
421
|
+
const fieldObj = entity.GetFieldByName(scopeFieldName);
|
|
422
|
+
const rawVal = fieldObj?.Value;
|
|
423
|
+
const tokenSpec = fieldTokenSpecs.get(scopeFieldName.trim().toLowerCase());
|
|
424
|
+
const fallback = policy.scopeFieldFallbacks?.[scopeFieldName] ?? tokenSpec?.fallback;
|
|
425
|
+
let resolved = !this.isBlankValue(rawVal)
|
|
426
|
+
? String(rawVal).trim()
|
|
427
|
+
: fallback !== undefined
|
|
428
|
+
? fallback.trim()
|
|
429
|
+
: '';
|
|
430
|
+
if (!resolved) {
|
|
431
|
+
throw new Error(`DocumentNumberingEngine: required scope field '${scopeFieldName}' is empty on ${entity.EntityInfo.Name} while allocating '${policy.targetField}'.`);
|
|
432
|
+
}
|
|
433
|
+
const sqlType = fieldObj?.EntityFieldInfo?.Type?.trim().toLowerCase() ?? '';
|
|
434
|
+
if (sqlType === 'uniqueidentifier' || sqlType === 'uuid') {
|
|
435
|
+
resolved = NormalizeUUID(resolved);
|
|
436
|
+
}
|
|
437
|
+
if (tokenSpec?.transform) {
|
|
438
|
+
resolved = this.applyFieldTransform(resolved, tokenSpec.transform);
|
|
439
|
+
}
|
|
440
|
+
segments.push(`Field:${scopeFieldName}=${resolved}`);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
const customKeys = Object.keys(customScope).sort();
|
|
444
|
+
for (const key of customKeys) {
|
|
445
|
+
segments.push(`Scope:${key}=${customScope[key]}`);
|
|
446
|
+
}
|
|
447
|
+
const resetPeriod = policy.resetPeriod ?? 'Never';
|
|
448
|
+
if (resetPeriod === 'CalendarYear') {
|
|
449
|
+
segments.push(`YYYY=${referenceDate.getUTCFullYear()}`);
|
|
450
|
+
}
|
|
451
|
+
else if (resetPeriod === 'CalendarMonth') {
|
|
452
|
+
const mm = String(referenceDate.getUTCMonth() + 1).padStart(2, '0');
|
|
453
|
+
segments.push(`YYYYMM=${referenceDate.getUTCFullYear()}-${mm}`);
|
|
454
|
+
}
|
|
455
|
+
else if (resetPeriod === 'FiscalYear') {
|
|
456
|
+
segments.push(`FY=${fiscalYear}`);
|
|
457
|
+
}
|
|
458
|
+
return segments.length > 0 ? segments.join('|') : '__GLOBAL__';
|
|
459
|
+
}
|
|
460
|
+
extractPatternFieldTokenSpecs(pattern) {
|
|
461
|
+
const specs = new Map();
|
|
462
|
+
if (!pattern) {
|
|
463
|
+
return specs;
|
|
464
|
+
}
|
|
465
|
+
const tokenRe = /\{([^{}]+)\}/g;
|
|
466
|
+
let match = tokenRe.exec(pattern);
|
|
467
|
+
while (match !== null) {
|
|
468
|
+
const trimmed = match[1].trim();
|
|
469
|
+
if (trimmed.startsWith('Field:')) {
|
|
470
|
+
const parts = trimmed.split(':');
|
|
471
|
+
const fieldName = (parts[1] ?? '').trim().toLowerCase();
|
|
472
|
+
if (fieldName) {
|
|
473
|
+
const transform = (parts[2] ?? '').trim().toUpperCase();
|
|
474
|
+
const fallback = parts[3];
|
|
475
|
+
specs.set(fieldName, { transform, fallback });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
match = tokenRe.exec(pattern);
|
|
479
|
+
}
|
|
480
|
+
return specs;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Renders `policy.pattern` with the allocated integer `sequenceNumber`.
|
|
484
|
+
*/
|
|
485
|
+
FormatPattern(policy, sequenceNumber, entity, contextUser, referenceDate, fiscalYear, customScope = {}) {
|
|
486
|
+
const yyyy = String(referenceDate.getUTCFullYear());
|
|
487
|
+
const yy = yyyy.slice(-2);
|
|
488
|
+
const mm = String(referenceDate.getUTCMonth() + 1).padStart(2, '0');
|
|
489
|
+
const dd = String(referenceDate.getUTCDate()).padStart(2, '0');
|
|
490
|
+
const fy = String(fiscalYear);
|
|
491
|
+
const fy2 = fy.slice(-2);
|
|
492
|
+
return policy.pattern.replace(/\{([^{}]+)\}/g, (_full, tokenBody) => {
|
|
493
|
+
const trimmed = tokenBody.trim();
|
|
494
|
+
if (trimmed === 'PREFIX') {
|
|
495
|
+
return policy.prefix ?? '';
|
|
496
|
+
}
|
|
497
|
+
if (trimmed === 'YYYY') {
|
|
498
|
+
return yyyy;
|
|
499
|
+
}
|
|
500
|
+
if (trimmed === 'YY') {
|
|
501
|
+
return yy;
|
|
502
|
+
}
|
|
503
|
+
if (trimmed === 'MM') {
|
|
504
|
+
return mm;
|
|
505
|
+
}
|
|
506
|
+
if (trimmed === 'DD') {
|
|
507
|
+
return dd;
|
|
508
|
+
}
|
|
509
|
+
if (trimmed === 'FY') {
|
|
510
|
+
return fy;
|
|
511
|
+
}
|
|
512
|
+
if (trimmed === 'FY2') {
|
|
513
|
+
return fy2;
|
|
514
|
+
}
|
|
515
|
+
if (trimmed === 'TenantID') {
|
|
516
|
+
const tid = contextUser?.TenantContext?.TenantID?.trim();
|
|
517
|
+
if (!tid) {
|
|
518
|
+
throw new Error(`DocumentNumberingEngine: pattern '${policy.pattern}' references {TenantID} without an active TenantContext.`);
|
|
519
|
+
}
|
|
520
|
+
return tid;
|
|
521
|
+
}
|
|
522
|
+
if (trimmed === 'SEQ' || trimmed.startsWith('SEQ:')) {
|
|
523
|
+
const widthStr = trimmed.includes(':') ? trimmed.split(':')[1] : '1';
|
|
524
|
+
const width = Math.max(1, Number.parseInt(widthStr, 10) || 1);
|
|
525
|
+
return String(sequenceNumber).padStart(width, '0');
|
|
526
|
+
}
|
|
527
|
+
if (trimmed.startsWith('Field:')) {
|
|
528
|
+
const parts = trimmed.split(':');
|
|
529
|
+
const fieldName = parts[1] ?? '';
|
|
530
|
+
const transform = (parts[2] ?? '').toUpperCase();
|
|
531
|
+
const fallback = parts[3] ?? policy.scopeFieldFallbacks?.[fieldName] ?? '';
|
|
532
|
+
const rawFieldVal = entity.GetFieldByName(fieldName)?.Value;
|
|
533
|
+
let str = !this.isBlankValue(rawFieldVal) ? String(rawFieldVal) : fallback;
|
|
534
|
+
str = this.applyFieldTransform(str, transform);
|
|
535
|
+
if (!str) {
|
|
536
|
+
throw new Error(`DocumentNumberingEngine: pattern '${policy.pattern}' token '{${trimmed}}' resolved to an empty string on ${entity.EntityInfo.Name}.`);
|
|
537
|
+
}
|
|
538
|
+
return str;
|
|
539
|
+
}
|
|
540
|
+
if (trimmed.startsWith('Scope:')) {
|
|
541
|
+
const scopeName = trimmed.slice('Scope:'.length).trim();
|
|
542
|
+
const val = customScope[scopeName];
|
|
543
|
+
if (val === undefined || val === '') {
|
|
544
|
+
throw new Error(`DocumentNumberingEngine: pattern '${policy.pattern}' token '{${trimmed}}' was not provided by ScopeResolver.`);
|
|
545
|
+
}
|
|
546
|
+
return val;
|
|
547
|
+
}
|
|
548
|
+
throw new Error(`DocumentNumberingEngine: unsupported pattern token '{${trimmed}}' in '${policy.pattern}'.`);
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
applyFieldTransform(value, transform) {
|
|
552
|
+
if (transform === 'UPPER') {
|
|
553
|
+
return value.trim().toUpperCase();
|
|
554
|
+
}
|
|
555
|
+
if (transform === 'LOWER') {
|
|
556
|
+
return value.trim().toLowerCase();
|
|
557
|
+
}
|
|
558
|
+
if (transform === 'TRIM') {
|
|
559
|
+
return value.trim();
|
|
560
|
+
}
|
|
561
|
+
if (transform === 'ALNUM') {
|
|
562
|
+
return value.replace(/[^A-Za-z0-9]/g, '').toUpperCase();
|
|
563
|
+
}
|
|
564
|
+
return value.trim();
|
|
565
|
+
}
|
|
566
|
+
compileReservedNamespaceRegex(policy) {
|
|
567
|
+
const cacheKey = `${policy.pattern}::${policy.prefix ?? ''}`;
|
|
568
|
+
const existing = this._reservedPatternRegexCache.get(cacheKey);
|
|
569
|
+
if (existing) {
|
|
570
|
+
return existing;
|
|
571
|
+
}
|
|
572
|
+
if (!policy.pattern.includes('{SEQ')) {
|
|
573
|
+
return null;
|
|
574
|
+
}
|
|
575
|
+
// Convert pattern tokens into a conservative regular expression matching generated system numbers.
|
|
576
|
+
// Compile when the pattern has a static prefix/literal, starts with a literal before `{`, starts with
|
|
577
|
+
// a date/fiscal token, or uses a `{Field:...}` token with a configured fallback prefix.
|
|
578
|
+
const hasStaticPrefix = (policy.pattern.includes('{PREFIX}') && Boolean(policy.prefix && policy.prefix.length > 0)) ||
|
|
579
|
+
/^[A-Za-z0-9]+(\{[A-Za-z]|[-_/:])/.test(policy.pattern) ||
|
|
580
|
+
/^\{(YYYY|YY|MM|DD|FY|FY2)\}[-_/:]/.test(policy.pattern);
|
|
581
|
+
if (!hasStaticPrefix) {
|
|
582
|
+
return null;
|
|
583
|
+
}
|
|
584
|
+
let regexSource = '^';
|
|
585
|
+
let cursor = 0;
|
|
586
|
+
const tokenRe = /\{([^{}]+)\}/g;
|
|
587
|
+
let match = tokenRe.exec(policy.pattern);
|
|
588
|
+
while (match !== null) {
|
|
589
|
+
if (match.index > cursor) {
|
|
590
|
+
regexSource += this.escapeRegexLiteral(policy.pattern.slice(cursor, match.index));
|
|
591
|
+
}
|
|
592
|
+
const token = match[1].trim();
|
|
593
|
+
if (token === 'PREFIX') {
|
|
594
|
+
regexSource += this.escapeRegexLiteral(policy.prefix ?? '');
|
|
595
|
+
}
|
|
596
|
+
else if (token === 'YYYY' || token === 'FY') {
|
|
597
|
+
regexSource += '\\d{4}';
|
|
598
|
+
}
|
|
599
|
+
else if (token === 'YY' || token === 'MM' || token === 'DD' || token === 'FY2') {
|
|
600
|
+
regexSource += '\\d{2}';
|
|
601
|
+
}
|
|
602
|
+
else if (token === 'SEQ' || token.startsWith('SEQ:')) {
|
|
603
|
+
regexSource += '\\d+';
|
|
604
|
+
}
|
|
605
|
+
else {
|
|
606
|
+
regexSource += '[A-Za-z0-9_-]+';
|
|
607
|
+
}
|
|
608
|
+
cursor = match.index + match[0].length;
|
|
609
|
+
match = tokenRe.exec(policy.pattern);
|
|
610
|
+
}
|
|
611
|
+
if (cursor < policy.pattern.length) {
|
|
612
|
+
regexSource += this.escapeRegexLiteral(policy.pattern.slice(cursor));
|
|
613
|
+
}
|
|
614
|
+
regexSource += '$';
|
|
615
|
+
const compiled = new RegExp(regexSource, 'i');
|
|
616
|
+
this._reservedPatternRegexCache.set(cacheKey, compiled);
|
|
617
|
+
return compiled;
|
|
618
|
+
}
|
|
619
|
+
escapeRegexLiteral(literal) {
|
|
620
|
+
return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
621
|
+
}
|
|
622
|
+
async resolveCustomScopeMap(entity, policy, sequenceKey, provider, contextUser, now) {
|
|
623
|
+
const resolver = this._scopeResolvers.get(sequenceKey.toLowerCase()) ??
|
|
624
|
+
this._scopeResolvers.get(entity.EntityInfo.Name.trim().toLowerCase());
|
|
625
|
+
if (!resolver) {
|
|
626
|
+
return {};
|
|
627
|
+
}
|
|
628
|
+
return await resolver({ entity, policy, provider, contextUser, now });
|
|
629
|
+
}
|
|
630
|
+
resolveReferenceDate(entity, dateSourceField, fallback) {
|
|
631
|
+
if (!dateSourceField) {
|
|
632
|
+
return fallback;
|
|
633
|
+
}
|
|
634
|
+
const raw = entity.GetFieldByName(dateSourceField)?.Value;
|
|
635
|
+
if (raw instanceof Date && !isNaN(raw.getTime())) {
|
|
636
|
+
return raw;
|
|
637
|
+
}
|
|
638
|
+
if (typeof raw === 'string' && raw.trim().length > 0) {
|
|
639
|
+
const parsed = new Date(raw);
|
|
640
|
+
if (!isNaN(parsed.getTime())) {
|
|
641
|
+
return parsed;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return fallback;
|
|
645
|
+
}
|
|
646
|
+
computeFiscalYear(referenceDate, fiscalYearStartMonth, customScope) {
|
|
647
|
+
if (customScope.FY && /^\d{4}$/.test(customScope.FY)) {
|
|
648
|
+
return Number.parseInt(customScope.FY, 10);
|
|
649
|
+
}
|
|
650
|
+
const startMonth = Math.min(12, Math.max(1, fiscalYearStartMonth));
|
|
651
|
+
const year = referenceDate.getUTCFullYear();
|
|
652
|
+
const month1Based = referenceDate.getUTCMonth() + 1;
|
|
653
|
+
if (startMonth === 1) {
|
|
654
|
+
return year;
|
|
655
|
+
}
|
|
656
|
+
return month1Based >= startMonth ? year + 1 : year;
|
|
657
|
+
}
|
|
658
|
+
resolveMetadataPolicies(entityInfo) {
|
|
659
|
+
const settings = entityInfo.Settings ?? [];
|
|
660
|
+
const setting = settings.find((s) => s.Name?.trim().toLowerCase() === DocumentNumberingEngine.AUTO_NUMBER_SETTING_NAME.toLowerCase());
|
|
661
|
+
const configAutoNumber = entityInfo.ConfigurationObject?.AutoNumber;
|
|
662
|
+
const signature = `${setting?.Value ?? ''}|${configAutoNumber ? JSON.stringify(configAutoNumber) : ''}`;
|
|
663
|
+
if (signature === '|') {
|
|
664
|
+
return [];
|
|
665
|
+
}
|
|
666
|
+
const cacheKey = entityInfo.ID || entityInfo.Name;
|
|
667
|
+
const cached = this._metadataCache.get(cacheKey);
|
|
668
|
+
if (cached && cached.signature === signature) {
|
|
669
|
+
return cached.policies;
|
|
670
|
+
}
|
|
671
|
+
const policies = [];
|
|
672
|
+
if (configAutoNumber) {
|
|
673
|
+
const rawList = Array.isArray(configAutoNumber) ? configAutoNumber : [configAutoNumber];
|
|
674
|
+
for (const item of rawList) {
|
|
675
|
+
policies.push(this.normalizeNumberPolicy(item));
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
if (setting?.Value && setting.Value.trim().length > 0) {
|
|
679
|
+
const parsed = SafeJSONParse(setting.Value, false);
|
|
680
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
681
|
+
LogError(`DocumentNumberingEngine: invalid JSON in EntitySetting '${DocumentNumberingEngine.AUTO_NUMBER_SETTING_NAME}' on entity '${entityInfo.Name}'; failing closed.`);
|
|
682
|
+
const invalidSentinel = {
|
|
683
|
+
targetField: '__INVALID_METADATA_AUTO_NUMBER_POLICY__',
|
|
684
|
+
pattern: '__INVALID__',
|
|
685
|
+
};
|
|
686
|
+
this._metadataCache.set(cacheKey, { signature, policies: [invalidSentinel] });
|
|
687
|
+
return [invalidSentinel];
|
|
688
|
+
}
|
|
689
|
+
const rawArr = Array.isArray(parsed) ? parsed : [parsed];
|
|
690
|
+
const fromSetting = rawArr.map((raw) => this.normalizeNumberPolicy(raw));
|
|
691
|
+
const overrideTargets = new Set(fromSetting.map((p) => p.targetField.trim().toLowerCase()));
|
|
692
|
+
const retained = policies.filter((p) => !overrideTargets.has(p.targetField.trim().toLowerCase()));
|
|
693
|
+
policies.length = 0;
|
|
694
|
+
policies.push(...retained, ...fromSetting);
|
|
695
|
+
}
|
|
696
|
+
this._metadataCache.set(cacheKey, { signature, policies });
|
|
697
|
+
return policies;
|
|
698
|
+
}
|
|
699
|
+
normalizeNumberPolicy(raw) {
|
|
700
|
+
return {
|
|
701
|
+
targetField: String(raw.targetField ?? raw.TargetField ?? ''),
|
|
702
|
+
sequenceKey: (raw.sequenceKey ?? raw.SequenceKey),
|
|
703
|
+
pattern: String(raw.pattern ?? raw.Pattern ?? ''),
|
|
704
|
+
prefix: (raw.prefix ?? raw.Prefix),
|
|
705
|
+
scopeFields: (raw.scopeFields ?? raw.ScopeFields),
|
|
706
|
+
scopeFieldFallbacks: (raw.scopeFieldFallbacks ?? raw.ScopeFieldFallbacks),
|
|
707
|
+
scopeByTenant: (raw.scopeByTenant ?? raw.ScopeByTenant),
|
|
708
|
+
resetPeriod: (raw.resetPeriod ?? raw.ResetPeriod),
|
|
709
|
+
dateSourceField: (raw.dateSourceField ?? raw.DateSourceField),
|
|
710
|
+
fiscalYearStartMonth: (raw.fiscalYearStartMonth ?? raw.FiscalYearStartMonth),
|
|
711
|
+
startAt: (raw.startAt ?? raw.StartAt),
|
|
712
|
+
incrementBy: (raw.incrementBy ?? raw.IncrementBy),
|
|
713
|
+
manualValueMode: (raw.manualValueMode ?? raw.ManualValueMode),
|
|
714
|
+
immutableAfterCreate: (raw.immutableAfterCreate ?? raw.ImmutableAfterCreate),
|
|
715
|
+
gapFreeTransactional: (raw.gapFreeTransactional ?? raw.GapFreeTransactional),
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
markSystemAssigned(entity, fieldName, priorValue) {
|
|
719
|
+
const keyLower = fieldName.trim().toLowerCase();
|
|
720
|
+
let set = this._systemAssignedFields.get(entity);
|
|
721
|
+
if (!set) {
|
|
722
|
+
set = new Set();
|
|
723
|
+
this._systemAssignedFields.set(entity, set);
|
|
724
|
+
}
|
|
725
|
+
set.add(keyLower);
|
|
726
|
+
let priorMap = this._assignedPriorValues.get(entity);
|
|
727
|
+
if (!priorMap) {
|
|
728
|
+
priorMap = new Map();
|
|
729
|
+
this._assignedPriorValues.set(entity, priorMap);
|
|
730
|
+
}
|
|
731
|
+
if (!priorMap.has(keyLower)) {
|
|
732
|
+
priorMap.set(keyLower, priorValue);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
isBlankValue(value) {
|
|
736
|
+
return value === null || value === undefined || (typeof value === 'string' && value.trim().length === 0);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
//# sourceMappingURL=documentNumberingEngine.js.map
|