Repository navigation
Expand file tree
/
Copy pathHistoryController.js
More file actions
382 lines (343 loc) · 15.8 KB
/
Copy pathHistoryController.js
File metadata and controls
382 lines (343 loc) · 15.8 KB
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
/**
* HistoryController
*
* @module :: Controller
* @description :: A set of functions called `actions`.
*
* Actions contain code telling Sails how to respond to a certain type of request.
* (i.e. do stuff, then send some JSON, show an HTML page, or redirect to another URL)
*
* You can configure the blueprint URLs which trigger these actions (`config/controllers.js`)
* and/or override them with custom routes (`config/routes.js`)
*
* NOTE: The code you write here supports both HTTP and Socket.io automatically.
*
* @docs :: http://sailsjs.org/#!documentation/controllers
*/
"use strict";
var JsonDiffPatch = require("jsondiffpatch");
var moment = require("moment-timezone");
var async = require("async");
module.exports = {
/**
* Overrides for the settings in `config/controllers.js`
* (specific to HistoryController)
*/
_config: {
blueprints: {
actions: true,
rest: false,
shortcuts: false
}
},
/**
* Main history action. This will render a GUI which will show specified object
* history data. Actual history data is calculated from database data on each object.
*
* @param {Request} request Request object
* @param {Response} response Response object
*/
index: function(request, response) {
var objectId = request.param("objectId");
var objectName = request.param("objectName");
async.parallel(
{
// Fetch history rows
histories: function(callback) {
History
.find()
.where({
objectName: objectName,
objectId: objectId
})
.sort("createdAt ASC")
.exec(function(error, data) {
callback(error, data)
});
},
// Fetch users
users: function(callback) {
DataService.getUsers({}, callback);
}
},
/**
* Main callback function which is called after all parallel jobs are done.
*
* @param {Error|null} error
* @param {{}} results
*/
function(error, results) {
if (error) {
ResponseService.makeError(error, request, response);
} else {
var historyRows = [];
// Remove duplicate rows
_.each(results.histories, function(row, key) {
if (key === 0
|| row.message
|| row.objectData !== results.histories[key - 1].objectData
|| row.message !== results.histories[key - 1].message
) {
historyRows.push(row);
}
});
// Process history data
processHistoryData(historyRows, results.users);
}
}
);
/**
* Function process history rows for specified object.
*
* @param {sails.model.history[]} historyRows
* @param {sails.model.user[]} users
*/
function processHistoryData(historyRows, users) {
var index = 0;
// Map all history rows to sub-methods
async.map(
historyRows,
/**
* Iterator function to process all history rows for specified object. Note that this
* function will call sub-functions to handle specified data of each history rows and
* those functions will eventually call this callback function.
*
* @param {sails.model.history} historyRow Single history row data as an object
* @param {Function} callback Callback function to call after row is processed
*/
function(historyRow, callback) {
var dateObject = DateService.convertDateObjectToUtc(historyRow.createdAt);
var user;
if (historyRow.userId == -1) {
user = -1;
} else {
user = _.find(users, function(user) { return user.id === historyRow.userId; });
}
// Create main data array which contains all necessary data for this history row
var historyData = {
message: (index === 0) ? "Object created" : historyRow.message,
index: index,
stamp: dateObject.tz(request.user.momentTimezone),
user: user,
data: []
};
// Determine previous and current rows as JSON objects
var currentRow = JSON.parse(historyRow.objectData);
var previousRow = {};
// We have a previous row data defined
if (!_.isUndefined(historyRows[index - 1])) {
previousRow = JSON.parse(historyRows[index - 1].objectData);
}
// Iterate ignore values of history data and delete those from current and previous history rows
_.each(sails.config.history.ignoreValues, function(value) {
delete previousRow[value];
delete currentRow[value];
});
// Calculate object difference to previous one
var difference = JsonDiffPatch.diff(previousRow, currentRow);
index++;
// We have no difference so just call callback function with no parameters
if (historyRow.message) {
callback(null, historyData);
} else if (_.isUndefined(difference)) {
callback(null, null);
} else { // Yeah some difference found...
var differenceArray = [];
// Firstly convert difference object to simple array
_.each(difference, function(value, column) {
differenceArray.push({
column: column,
value: value
});
});
// Process single history row
processHistoryRow(differenceArray, historyData, callback);
}
},
/**
* Main callback function which is called after _all_ specified jobs are done. Basically
* this function just shows pages if no error(s) occurred while processing data.
*
* @param {Error} error
* @param {Array} results
*/
function(error, results) {
if (error) {
ResponseService.makeError(error, request, response);
} else {
// Make view
response.view({
data: _.compact(results).reverse()
});
}
}
);
}
/**
* Function to process single history row data. Basically this function just maps all
* differences and make specified data processing for single column (data attribute).
*
* @param {{}[]} differences Current row differences as an array of objects
* @param {sails.helper.historyRow} historyRow History row data
* @param {Function} next Callback function to call after row is processed
*/
function processHistoryRow(differences, historyRow, next) {
// Map all differences
async.map(
differences,
/**
* Iterator function to process single difference data in one history row. Note that this
* function will call sub-function to handle specified difference handling. That function
* will eventually call this callback function.
*
* @param {sails.helper.historyDifference} difference Difference data
* @param {Function} callback Callback function to call after differences are processed
*/
function(difference, callback) {
var valueOld = false;
var valueIdOld = false;
var valueNew = false;
var valueIdNew = false;
var columnType = false;
var changeType = "";
// On the first row skip all but parentId column
if (historyRow.index === 0 && difference.column !== "parentId") {
callback(null, null);
} else {
if (difference.value.length === 3) {
changeType = "delete";
} else if (difference.value.length == 2) {
changeType = "update";
valueOld = difference.value[0];
valueIdOld = difference.value[0];
valueNew = difference.value[1];
valueIdNew = difference.value[1];
} else {
changeType = "insert";
valueNew = difference.value[0];
valueIdNew = difference.value[0];
}
var differenceData = {
column: difference.column,
columnType: columnType,
changeType: changeType,
valueNew: valueNew,
valueOld: valueOld,
valueIdOld: valueIdOld,
valueIdNew: valueIdNew
};
processHistoryRowColumn(differenceData, callback);
}
},
/**
* Callback function for single history row process which is called after all
* difference data for current history row is processed.
*
* Note that this callback will call main callback.
*
* @param {Error} error Possible error
* @param {sails.helper.historyRowData[]} results History row data as an array
*/
function(error, results) {
// Store history row data
historyRow.data = _.groupBy(_.compact(results), function(result) {
return result.changeType;
});
next(error, historyRow);
}
);
}
/**
* Private function to process single column data on history row.
*
* @param {sails.helper.historyRowData} data Single column data
* @param {Function} next Callback function to call after column is processed
*/
function processHistoryRowColumn(data, next) {
/**
* Magic happens here, we can assume that attributes which ends with 'Id'
* strings are actual relations to another models.
*
* In these cases we want to fetch actual text values for changed old and
* new values.
*
* Note that fetching old and new value must be done at in same process
* otherwise this doesn't work right.
*/
if (data.column.match(/Id$/) !== null) {
var object = data.column.charAt(0).toUpperCase() + data.column.slice(1, -2);
// In project object managerId refers to User object
if (object == "Manager"
|| object == "CurrentUser"
) {
object = "User";
}
data.columnType = "relation";
// Column is parentId, so this is relation to object itself
if (data.column.match(/parentId$/) !== null) {
data.columnType = "parent";
object = objectName;
}
// Only fetch possible relation data if change type is insert or update AND data object is present
if (global[object] && typeof global[object] === "object" && data.changeType != "delete") {
// Fetch relation data for column
async.parallel(
{
// New value object data
dataNew: function(callback) {
if (data.valueIdNew) {
global[object]
.findOne(data.valueIdNew)
.done(function(error, objectData) {
callback(error, objectData);
})
} else {
callback(null, false);
}
},
// New value object data
dataOld: function(callback) {
if (data.changeType == "update" && data.valueIdOld) {
global[object]
.findOne(data.valueIdOld)
.done(function(error, objectData) {
callback(error, objectData);
})
} else {
callback(null, false);
}
}
},
/**
* Callback function which is called after all specified parallel jobs are done.
*
* @param {Error} error Possible error
* @param {{}} results Actual data results
*/
function(error, results) {
data.valueNew = (!results.dataNew) ? "none" : results.dataNew.objectTitle();
data.valueOld = (!results.dataOld) ? "none" : results.dataOld.objectTitle();
next(error, data);
}
);
} else {
next(null, data);
}
} else { // No relation
// Determine column type
if (data.valueOld === true && data.valueNew === false
|| data.valueOld === false && data.valueNew === true
) {
data.columnType = "boolean";
} else {
data.columnType = "normal";
}
if (data.columnType == "normal" && data.valueOld === false && !data.valueNew) {
next(null, null);
} else {
next(null, data);
}
}
}
}
};