-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathchange-log.js
553 lines (485 loc) · 17.3 KB
/
change-log.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
const cds = require("@sap/cds")
const getTemplate = require("@sap/cds/libx/_runtime/common/utils/template") // REVISIT: bad usage of internal stuff
const templateProcessor = require("./template-processor")
const LOG = cds.log("change-log")
const {
getNameFromPathVal,
getUUIDFromPathVal,
getCurObjFromReqData,
getCurObjFromDbQuery,
getObjectId,
getDBEntity,
getEntityByContextPath,
getObjIdElementNamesInArray,
getValueEntityType,
} = require("./entity-helper")
const { localizeLogFields } = require("./localization")
const isRoot = "change-tracking-isRootEntity"
function formatDecimal(str, scale) {
if (typeof str === "number" && !isNaN(str)) {
str = String(str);
} else return str;
if (scale > 0) {
let parts = str.split(".");
let decimalPart = parts[1] || "";
while (decimalPart.length < scale) {
decimalPart += "0";
}
return `${parts[0]}.${decimalPart}`;
}
return str;
}
const _getRootEntityPathVals = function (txContext, entity, entityKey) {
const serviceEntityPathVals = []
const entityIDs = _getEntityIDs(txContext.params)
let path = txContext.path.split('/')
if (txContext.event === "CREATE") {
const curEntityPathVal = `${entity.name}(${entityKey})`
serviceEntityPathVals.push(curEntityPathVal)
txContext.hasComp && entityIDs.pop();
} else {
// When deleting Composition of one node via REST API in draft-disabled mode,
// the child node ID would be missing in URI
if (txContext.event === "DELETE" && !entityIDs.find((x) => x === entityKey)) {
entityIDs.push(entityKey)
}
const curEntity = getEntityByContextPath(path, txContext.hasComp)
const curEntityID = entityIDs.pop()
const curEntityPathVal = `${curEntity.name}(${curEntityID})`
serviceEntityPathVals.push(curEntityPathVal)
}
while (_isCompositionContextPath(path, txContext.hasComp)) {
const hostEntity = getEntityByContextPath(path = path.slice(0, -1), txContext.hasComp)
const hostEntityID = entityIDs.pop()
const hostEntityPathVal = `${hostEntity.name}(${hostEntityID})`
serviceEntityPathVals.unshift(hostEntityPathVal)
}
return serviceEntityPathVals
}
const _getAllPathVals = function (txContext) {
const pathVals = []
const paths = txContext.path.split('/')
const entityIDs = _getEntityIDs(txContext.params)
for (let idx = 0; idx < paths.length; idx++) {
const entity = getEntityByContextPath(paths.slice(0, idx + 1), txContext.hasComp)
const entityID = entityIDs[idx]
const entityPathVal = `${entity.name}(${entityID})`
pathVals.push(entityPathVal)
}
return pathVals
}
function convertSubjectToParams(subject) {
let params = [];
let subjectRef = [];
subject?.ref?.forEach((item)=>{
if (typeof item === 'string') {
subjectRef.push(item)
return
}
const keys = {}
let id = item.id
if (!id) return
for (let j = 0; j < item?.where?.length; j = j + 4) {
const key = item.where[j].ref[0]
const value = item.where[j + 2].val
if (key !== 'IsActiveEntity') keys[key] = value
}
params.push(keys);
})
return params.length > 0 ? params : subjectRef;
}
const _getEntityIDs = function (txParams) {
const entityIDs = []
for (const param of txParams) {
let id = ""
if (typeof param === "object" && !Array.isArray(param)) {
id = param.ID
}
if (typeof param === "string") {
id = param
}
if (id) {
entityIDs.push(id)
}
}
return entityIDs
}
/**
*
* @param {*} tx
* @param {*} changes
*
* When consuming app implement '@changelog' on an association element,
* change history will use attribute on associated entity which are specified instead of default technical foreign key.
*
* eg:
* entity PurchasedProductFootprints @(cds.autoexpose): cuid, managed {
* ...
* '@changelog': [Plant.identifier]
* '@mandatory' Plant : Association to one Plant;
* ...
* }
*/
const _formatAssociationContext = async function (changes, reqData) {
for (const change of changes) {
const a = cds.model.definitions[change.serviceEntity].elements[change.attribute]
if (a?.type !== "cds.Association") continue
const semkeys = getObjIdElementNamesInArray(a["@changelog"])
if (!semkeys.length) continue
const ID = a.keys[0].ref[0] || 'ID'
const [ from, to ] = await cds.db.run ([
SELECT.one.from(a.target).where({ [ID]: change.valueChangedFrom }),
SELECT.one.from(a.target).where({ [ID]: change.valueChangedTo })
])
const fromObjId = await getObjectId(reqData, a.target, semkeys, { curObjFromDbQuery: from || undefined }) // Note: ... || undefined is important for subsequent object destructuring with defaults
if (fromObjId) change.valueChangedFrom = fromObjId
const toObjId = await getObjectId(reqData, a.target, semkeys, { curObjFromDbQuery: to || undefined }) // Note: ... || undefined is important for subsequent object destructuring with defaults
if (toObjId) change.valueChangedTo = toObjId
const isVLvA = a["@Common.ValueList.viaAssociation"]
if (!isVLvA) change.valueDataType = getValueEntityType(a.target, semkeys)
}
}
const _getChildChangeObjId = async function (
change,
childNodeChange,
curNodePathVal,
reqData
) {
const composition = cds.model.definitions[change.serviceEntity].elements[change.attribute]
const objIdElements = composition ? composition["@changelog"] : null
const objIdElementNames = getObjIdElementNamesInArray(objIdElements)
return _getObjectIdByPath(
reqData,
curNodePathVal,
childNodeChange._path,
objIdElementNames
)
}
const _formatCompositionContext = async function (changes, reqData) {
const childNodeChanges = []
for (const change of changes) {
if (typeof change.valueChangedTo === "object" && change.valueChangedTo instanceof Date !== true) {
if (!Array.isArray(change.valueChangedTo)) {
change.valueChangedTo = [change.valueChangedTo]
}
for (const childNodeChange of change.valueChangedTo) {
const curChange = Object.assign({}, change)
const path = childNodeChange._path.split('/')
const curNodePathVal = path.pop()
curChange.modification = childNodeChange._op
const objId = await _getChildChangeObjId(
change,
childNodeChange,
curNodePathVal,
reqData
)
_formatCompositionValue(curChange, objId, childNodeChange, childNodeChanges)
}
change.valueChangedTo = undefined
}
}
changes.push(...childNodeChanges)
}
const _formatCompositionValue = function (
curChange,
objId,
childNodeChange,
childNodeChanges
) {
if (curChange.modification === undefined) {
return
} else if (curChange.modification === "delete") {
curChange.valueChangedFrom = objId
curChange.valueChangedTo = ""
} else if (curChange.modification === "update") {
curChange.valueChangedFrom = objId
curChange.valueChangedTo = objId
} else {
curChange.valueChangedFrom = ""
curChange.valueChangedTo = objId
}
curChange.valueDataType = _formatCompositionEntityType(curChange)
// Since req.diff() will record the managed data, change history will filter those logs only be changed managed data
const managedAttrs = ["modifiedAt", "modifiedBy"]
if (curChange.modification === "update") {
const rowOldAttrs = Object.keys(childNodeChange._old)
const diffAttrs = rowOldAttrs.filter((attr) => managedAttrs.indexOf(attr) === -1)
if (!diffAttrs.length) {
return
}
}
childNodeChanges.push(curChange)
}
const _formatCompositionEntityType = function (change) {
const composition = cds.model.definitions[change.serviceEntity].elements[change.attribute]
const objIdElements = composition ? composition['@changelog'] : null
if (Array.isArray(objIdElements)) {
// In this case, the attribute is a composition
const objIdElementNames = getObjIdElementNamesInArray(objIdElements)
return getValueEntityType(composition.target, objIdElementNames)
}
return ""
}
const _getObjectIdByPath = async function (
reqData,
nodePathVal,
serviceEntityPath,
/**optional*/ objIdElementNames
) {
const curObjFromReqData = getCurObjFromReqData(reqData, nodePathVal, serviceEntityPath)
const entityName = getNameFromPathVal(nodePathVal)
const entityUUID = getUUIDFromPathVal(nodePathVal)
const obj = await getCurObjFromDbQuery(entityName, entityUUID)
const curObj = { curObjFromReqData, curObjFromDbQuery: obj }
return getObjectId(reqData, entityName, objIdElementNames, curObj)
}
const _formatObjectID = async function (changes, reqData) {
const objectIdCache = new Map()
for (const change of changes) {
const path = change.serviceEntityPath.split('/')
const curNodePathVal = path.pop()
const parentNodePathVal = path.pop()
let curNodeObjId = objectIdCache.get(curNodePathVal)
if (!curNodeObjId) {
curNodeObjId = await _getObjectIdByPath(
reqData,
curNodePathVal,
change.serviceEntityPath
)
objectIdCache.set(curNodePathVal, curNodeObjId)
}
let parentNodeObjId = objectIdCache.get(parentNodePathVal)
if (!parentNodeObjId && parentNodePathVal) {
parentNodeObjId = await _getObjectIdByPath(
reqData,
parentNodePathVal,
change.serviceEntityPath
)
objectIdCache.set(parentNodePathVal, parentNodeObjId)
}
change.entityID = curNodeObjId
change.parentEntityID = parentNodeObjId
change.parentKey = getUUIDFromPathVal(parentNodePathVal)
}
}
const _isCompositionContextPath = function (aPath, hasComp) {
if (!aPath) return
if (typeof aPath === 'string') aPath = aPath.split('/')
if (aPath.length < 2) return false
const target = getEntityByContextPath(aPath, hasComp)
const parent = getEntityByContextPath(aPath.slice(0, -1), hasComp)
if (!parent.compositions) return false
return Object.values(parent.compositions).some(c => c._target === target)
}
const _formatChangeLog = async function (changes, req) {
await _formatObjectID(changes, req.data)
await _formatAssociationContext(changes, req.data)
await _formatCompositionContext(changes, req.data)
}
const _afterReadChangeView = function (data, req) {
if (!data) return
if (!Array.isArray(data)) data = [data]
localizeLogFields(data, req.locale)
}
function _trackedChanges4 (srv, target, diff) {
const template = getTemplate("change-logging", srv, target, { pick: e => e['@changelog'] })
if (!template.elements.size) return
const changes = []
diff._path = `${target.name}(${diff.ID})`
templateProcessor({
template, row: diff, processFn: ({ row, key, element }) => {
const from = row._old?.[key]
const to = row[key]
const eleParentKeys = element.parent.keys
if (from === to) return
/**
*
* HANA driver always filling up the defined decimal places with zeros,
* need to skip the change log if the value is not changed.
* Example:
* entity Books : cuid {
* price : Decimal(11, 4);
* }
* When price is updated from 3000.0000 to 3000,
* the change log should not be created.
*/
if (
row._op === "update" &&
element.type === "cds.Decimal" &&
cds.db.kind === "hana" &&
typeof to === "number"
) {
const scaleNum = element.scale || 0;
if (from === formatDecimal(to, scaleNum))
return;
}
/**
*
* For the Inline entity such as Items,
* further filtering is required on the keys
* within the 'association' and 'foreign key' to ultimately retain the keys of the entity itself.
* entity Order : cuid {
* title : String;
* Items : Composition of many {
* key ID : UUID;
* quantity : Integer;
* }
* }
*/
const keys = Object.keys(eleParentKeys)
.filter(k => k !== "IsActiveEntity")
.filter(k => eleParentKeys[k]?.type !== "cds.Association") // Skip association
.filter(k => !eleParentKeys[k]?.["@odata.foreignKey4"]) // Skip foreign key
.map(k => `${k}=${row[k]}`)
.join(', ')
changes.push({
serviceEntityPath: row._path,
entity: getDBEntity(element.parent).name,
serviceEntity: element.parent.name,
attribute: element["@odata.foreignKey4"] || key,
valueChangedFrom: from?? '',
valueChangedTo: to?? '',
valueDataType: element.type,
modification: row._op,
keys,
})
}
})
return changes.length && changes
}
const _prepareChangeLogForComposition = async function (entity, entityKey, changes, req) {
const rootEntityPathVals = _getRootEntityPathVals(req.context, entity, entityKey)
if (rootEntityPathVals.length < 2) {
LOG.info("Parent entity doesn't exist.")
return
}
const parentEntityPathVal = rootEntityPathVals[rootEntityPathVals.length - 2]
const parentKey = getUUIDFromPathVal(parentEntityPathVal)
const serviceEntityPath = rootEntityPathVals.join('/')
const parentServiceEntityPath = _getAllPathVals(req.context)
.slice(0, rootEntityPathVals.length - 2)
.join('/')
for (const change of changes) {
change.parentEntityID = await _getObjectIdByPath(req.data, parentEntityPathVal, parentServiceEntityPath)
change.parentKey = parentKey
change.serviceEntityPath = serviceEntityPath
}
const rootEntity = getNameFromPathVal(rootEntityPathVals[0])
const rootEntityID = getUUIDFromPathVal(rootEntityPathVals[0])
return [ rootEntity, rootEntityID ]
}
async function generatePathAndParams (req, entityKey) {
const { target, data } = req;
const { ID, foreignKey, parentEntity } = getAssociationDetails(target);
const hasParentAndForeignKey = parentEntity && data[foreignKey];
const targetEntity = hasParentAndForeignKey ? parentEntity : target;
const targetKey = hasParentAndForeignKey ? data[foreignKey] : entityKey;
let compContext = {
path: hasParentAndForeignKey
? `${parentEntity.name}/${target.name}`
: `${target.name}`,
params: hasParentAndForeignKey
? [{ [ID]: data[foreignKey] }, { [ID]: entityKey }]
: [{ [ID]: entityKey }],
hasComp: true
};
if (hasParentAndForeignKey && parentEntity[isRoot]) {
return compContext;
}
let parentAssoc = await processEntity(targetEntity, targetKey, compContext);
while (parentAssoc && !parentAssoc.entity[isRoot]) {
parentAssoc = await processEntity(
parentAssoc.entity,
parentAssoc.ID,
compContext
);
}
return compContext;
}
async function processEntity (entity, entityKey, compContext) {
const { ID, foreignKey, parentEntity } = getAssociationDetails(entity);
if (foreignKey && parentEntity) {
const parentResult =
(await SELECT.one
.from(entity.name)
.where({ [ID]: entityKey })
.columns(foreignKey)) || {};
const hasForeignKey = parentResult[foreignKey];
if (!hasForeignKey) return;
compContext.path = `${parentEntity.name}/${compContext.path}`;
compContext.params.unshift({ [ID]: parentResult[foreignKey] });
return {
entity: parentEntity,
[ID]: hasForeignKey ? parentResult[foreignKey] : undefined
};
}
}
function getAssociationDetails (entity) {
if (!entity) return {};
const assocName = entity['change-tracking-parentEntity']?.associationName;
const assoc = entity.elements[assocName];
const parentEntity = assoc?._target;
const foreignKey = assoc?.keys?.[0]?.$generatedFieldName;
const ID = assoc?.keys?.[0]?.ref[0] || 'ID';
return { ID, foreignKey, parentEntity };
}
function isEmpty(value) {
return value === null || value === undefined || value === "";
}
async function track_changes (req) {
const config = cds.env.requires["change-tracking"];
if (
(req.event === 'UPDATE' && config?.disableUpdateTracking) ||
(req.event === 'CREATE' && config?.disableCreateTracking) ||
(req.event === 'DELETE' && config?.disableDeleteTracking)
) {
return;
}
let diff = await req.diff()
if (!diff) return
let target = req.target
let compContext = null;
let entityKey = diff.ID
const params = convertSubjectToParams(req.subject);
if (req.subject.ref.length === 1 && params.length === 1 && !target[isRoot]) {
compContext = await generatePathAndParams(req, entityKey);
}
let isComposition = _isCompositionContextPath(
compContext?.path || req.path,
compContext?.hasComp
);
if (
req.event === "DELETE" &&
target[isRoot] &&
!cds.env.requires["change-tracking"]?.preserveDeletes
) {
return await DELETE.from(`sap.changelog.ChangeLog`).where({ entityKey });
}
let changes = _trackedChanges4(this, target, diff)
if (!changes) return
await _formatChangeLog(changes, req)
if (isComposition) {
let reqInfo = {
data: req.data,
context: {
path: compContext?.path || req.path,
params: compContext?.params || params,
event: req.event,
hasComp: compContext?.hasComp
}
};
[ target, entityKey ] = await _prepareChangeLogForComposition(target, entityKey, changes, reqInfo)
}
const dbEntity = getDBEntity(target)
await INSERT.into("sap.changelog.ChangeLog").entries({
entity: dbEntity.name,
entityKey: entityKey,
serviceEntity: target.name || target,
changes: changes.filter(c => !isEmpty(c.valueChangedFrom) || !isEmpty(c.valueChangedTo)).map((c) => ({
...c,
valueChangedFrom: `${c.valueChangedFrom ?? ''}`,
valueChangedTo: `${c.valueChangedTo ?? ''}`,
})),
})
}
module.exports = { track_changes, _afterReadChangeView }