-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresourceAnalysis.js
More file actions
459 lines (397 loc) · 20.3 KB
/
resourceAnalysis.js
File metadata and controls
459 lines (397 loc) · 20.3 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
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
import resourceAnalysisValidator from './resourceAnalysisValidator.js';
import { RequestConstructor } from './requestConstructor.js';
import { PivotSelector } from './flexiPivotSelector.js';
import { FlexiTable } from './flexiTable.js';
import { FlexiRowSelector } from './flexiRowSelector.js';
import { EffortTransformer } from './effortTransformer.js';
import { mergeDeep } from './utils.js';
// TODO - 🔴 - Translations
// TODO - 🟡 - Date formats. Consider using usr config instead of browser's
// TODO - 🟡 - retrieve pivotConfig from the viewTemplate
// TODO - 🟡 - Add a spinner when loading first time. Following loads use the button
// TODO - 🟡 - Review browser's issues
// TODO - 🟢 - request Constructor separator thickness changes upon pivot selection. Only with console open. Test with many rows
const VALID_ANALYSIS_MODES = { intervals: 'intervals', totals: 'totals' };
const VALID_TOTALS_DATE_RANGE_MODES = { liveBetween: 'liveBetween', strictlyBetween: 'strictlyBetween' };
const VALID_PIVOT_CONFIGS = { entityWorkItem: 'entity-workItem', entityUser: 'entity-user', user: 'user' };
export class ResourceAnalysis {
/**
* Creates an instance of ResourceAnalysis.
* @param {String[]} parentDivIds - The IDs of the parent div elements.
* @param {Object} [options={}] - Configuration options for the instance.
* @param {Object} [options.preFilter] - preFilter to add to the filterConstructor result. For example, limit to a single project
* @param {Object} [options.shouldFilterBeVisible]
* @param {String} [options.viewTemplateId] - The viewTemplate ID if initializing with a view ID.
* @param {String[]} [options.tablesAllowed] - The tables allowed for the requestConstructor.
*/
constructor(parentDivIds, options = {}) {
this.requestConstructorDivId = parentDivIds.requestConstructorContainer;
this.rowSelectorDivId = parentDivIds.rowSelectorContainer;
this.tableContainerDivId = parentDivIds.tableContainer;
this.viewTemplateId = options.viewTemplateId || null;
this.preFilter = options.preFilter || null;
this.tablesAllowed = options.tablesAllowed || null;
this.requestConstructor = null;
this.pivotSelector = null;
this.flexiRowSelector = null;
this.flexiTable = null;
this.APIToken = null;
this.state = {
request: {
analysisMode: null,
filter: {},
intervals: null,
totals: null
},
pivotConfig: VALID_PIVOT_CONFIGS.entityWorkItem, // Default view configuration
responseData: null, // Data received from the server
transformedData: null // Data transformed for the table
};
this._initPromise = this.#initDependencies().then(() => {
this.#initComponents();
this.#addEventListeners();
});
}
async #initDependencies() {
await itmGlobal.ensureDiContainerReady();
this.APIToken = window.userLoginToken;
}
async #initComponents() {
const dataServiceModel = await this.#fetchDataServiceModel();
const viewTemplate = await this.#getViewTemplate(this.viewTemplateId);
const requestObject = this.#extractRequestObjectFromViewTemplate(viewTemplate);
this.#setState({ request: requestObject });
const rcOptions = {
tablesAllowed: this.tablesAllowed,
shouldFilterBeVisible: true
};
this.requestConstructor = new RequestConstructor(
this.state.request,
dataServiceModel,
this.requestConstructorDivId,
rcOptions
);
//TODO - 🟢 - Remove this line making the requestConstructor global
window.requestConstructor = this.requestConstructor; // For testing purposes
// TODO - 🟡 - Add selected: true to the default pivotConfig, and apply the data transformation
this.pivotSelector = new PivotSelector([
{ name: VALID_PIVOT_CONFIGS.entityWorkItem, tooltip: 'Entity - Work Item', svg: this.getSVG(VALID_PIVOT_CONFIGS.entityWorkItem) },
{ name: VALID_PIVOT_CONFIGS.entityUser, tooltip: 'Entity - User', svg: this.getSVG(VALID_PIVOT_CONFIGS.entityUser) },
{ name: VALID_PIVOT_CONFIGS.user, tooltip: 'User - Entity', svg: this.getSVG(VALID_PIVOT_CONFIGS.user) }
]);
this.#fetchEffortData().then(() => {
this.#renderFlexiTable();
});
}
async #fetchDataServiceModel() {
if (!this.APIToken) {
throw new Error('No token provided to fetch data service model.');
}
let url = `/v2/${window.companyId}/dataServiceModel`;
const testingResourceAnalysisWithProxy = localStorage.getItem('testingResourceAnalysisWithProxy') === 'true';
if (testingResourceAnalysisWithProxy) {
url = `/proxy${url}`;
}
try {
const response = await fetch(url, {
headers: {
'Token': this.APIToken
}
});
const data = await response.json();
return data;
} catch (error) {
throw new Error('Error fetching data service model: ' + error.message);
}
}
async #getViewTemplate(viewTemplateId) {
const viewTemplate = await this.#fetchViewTemplate(viewTemplateId);
if (!viewTemplate) {
return this.#getDefaultViewTemplate();
}
return viewTemplate;
}
#fetchViewTemplate(viewTemplateId) {
// For now, return a promise that resolves to null.
// The final version should call GET /retrieve view with payload. (GET / constext/...) If the viewTemplateId is null,
// it will return the active view for the user. If there is no active view,
// it can either return null and we manage it in the frontend (as we do here now),
// or it can return a default view.
return Promise.resolve(null);
}
#saveViewTemplate() {
// TODO - 🟡 - Save the viewTemplate with the current state
// Careful with different views. Must analyze.
}
#getDefaultViewTemplate() {
// TODO - 🟡 - Allow the caller to inject the view and bypass the template.
// For example, to add it to one single project, we can directly call resourceAnalysis
// with the filter injected.
// We only need the `view` property from the viewTemplate, but we mock up the whole object
// as definition for the templateManager we will build.
// Active view by user
return {
viewTemplateId: 'cbafa593-5ad9-4803-9d6e-e6490d9117d4',
companyId: 15,
contextView: 'resourceAnalysis',
name: 'Totals Q1 2024',
description: 'Projects live in Q1 2024',
isPrivateToCreator: false,
isDefaultViewInContext: true,
createdDate: '2023-09-01T00:00:00.000Z',
createdBy: { userId: 3890, displayName: 'Ben Li' },
owner: { userId: 3890, displayName: 'Ben Li' },
lastUpdatedDate: '2023-12-01T00:00:00.000Z',
lastUpdatedBy: { userId: 3890, displayName: 'Ben Li' },
view: {
analysisMode: 'intervals',
intervals: {
startDate: '2024-02-01',
intervalType: 'day',
noOfIntervals: 5
},
totals: {
dateRangeMode: 'liveBetween',
startDate: '2024-01-01',
endDate: '2024-03-31'
},
filter: {
projects: {Duration: { $gt: 10 }},
},
pivotConfig: 'user'
}
};
}
#extractRequestObjectFromViewTemplate(viewTemplate) {
// return an object with viewTemplate.view analysisMode, intervals, and filter properties
return {
analysisMode: viewTemplate.view.analysisMode,
intervals: viewTemplate.view.intervals,
totals: viewTemplate.view.totals,
filter: viewTemplate.view.filter,
};
}
_convertTotalDatesToFilters(totals) {
const { dateRangeMode, startDate, endDate } = totals;
// TODO - 🟡 - VAlidate the dates somewhere
const totalFilters = {};
// TODO - 🟡 - What if the preFilter is only for one project or service?
['projects', 'services'].forEach((key) => {
totalFilters[key] = {};
if (dateRangeMode === VALID_TOTALS_DATE_RANGE_MODES.liveBetween) {
totalFilters[key].StartDate = { $lte: endDate };
totalFilters[key].EndDate = { $gte: startDate };
} else {
totalFilters[key].StartDate = { $bt: [startDate, endDate] };
totalFilters[key].EndDate = { $bt: [startDate, endDate] };
}
});
return totalFilters;
}
_mixFiltersForRequest(preFilter, totalsFilters, filter) {
const mergeObjects = (base, override) => {
for (let key in override) {
if (override.hasOwnProperty(key)) {
if (typeof base[key] === 'object' && typeof override[key] === 'object') {
base[key] = mergeObjects(base[key], override[key]);
} else {
base[key] = override[key];
}
}
}
return base;
};
const result = {};
// Merge in reverse order of precedence
if (filter && typeof filter === 'object') {
mergeObjects(result, JSON.parse(JSON.stringify(filter)));
}
if (totalsFilters && typeof totalsFilters === 'object') {
mergeObjects(result, JSON.parse(JSON.stringify(totalsFilters)));
}
if (preFilter && typeof preFilter === 'object') {
mergeObjects(result, JSON.parse(JSON.stringify(preFilter)));
}
return result;
}
async #fetchEffortData() {
const getResponseDataFromServer = async () => {
try {
let url = `/v2/${window.companyId}/resourceAnalysis`;
const testingResourceAnalysisWithProxy = localStorage.getItem('testingResourceAnalysisWithProxy') === 'true';
if (testingResourceAnalysisWithProxy) {
url = `/proxy${url}`;
}
if (!this.APIToken) { throw new Error('No token provided to fetch data.'); }
url = 'http://localhost/ITM.API/v2/itmrozas/resourceAnalysis/';
const payload = {
analysisMode,
filter: mixedFiltersForRequest,
...(analysisMode === VALID_ANALYSIS_MODES.intervals && { intervals }),
};
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Token': this.APIToken
},
body: JSON.stringify(payload)
});
return await response.json();
} catch (err) {
console.error('Error fetching data from server:', err);
throw err;
}
};
//console.log(`State before fetching data:, ${JSON.stringify(this.state.request, null, 2)}`);
const testingResourceAnalysisWithLocalFiles = localStorage.getItem('testingResourceAnalysisWithLocalFiles') === 'true';
const { request } = this.state;
const { analysisMode, filter, intervals, totals } = request;
let totalsFilters;
if (analysisMode === VALID_ANALYSIS_MODES.totals) {
totalsFilters = this._convertTotalDatesToFilters(totals);
}
const mixedFiltersForRequest = this._mixFiltersForRequest(this.preFilter, totalsFilters, filter);
//TODO - 🟢 - Remove this line:
const payloadMock = {
analysisMode,
filter: mixedFiltersForRequest,
...(analysisMode === VALID_ANALYSIS_MODES.intervals && { intervals }),
};
//console.log(`Payload: ${JSON.stringify(payloadMock, null, 2)}`);
let responseData;
if (testingResourceAnalysisWithLocalFiles) {
console.warn('TESTING: Fetching data from local files');
responseData = await getResponseDataFromLocalTestingFiles();
} else {
responseData = await getResponseDataFromServer();
}
try {
resourceAnalysisValidator.validateResponse(responseData);
this.#setState({ responseData });
this.transformedData = this.#transformData(responseData, analysisMode, this.state.pivotConfig);
} catch (err) {
console.error('Error processing data:', err);
throw err;
}
async function getResponseDataFromLocalTestingFiles() {
let fileURL;
if (analysisMode === VALID_ANALYSIS_MODES.intervals) {
fileURL = './tests/dataSamples/responseResourceAnalysisIntervals.js';
} else if (analysisMode === VALID_ANALYSIS_MODES.totals) {
fileURL = './tests/dataSamples/responseResourceAnalysisTotals.js';
}
try {
const module = await import(fileURL);
return module.default;
} catch (err) {
console.error('Error fetching data from testing files:', err);
throw err;
}
}
}
#renderFlexiTable() {
document.getElementById(this.tableContainerDivId).innerHTML = '';
this.flexiRowSelector = new FlexiRowSelector(this.rowSelectorDivId, {
// TODO - 🟢 - // inject row selection from viewTemplate
user: true, project: true, workItem: true
}, this.transformedData.rows);
this.flexiTable = new FlexiTable(this.tableContainerDivId, this.transformedData, this.flexiRowSelector.getRows(), this.pivotSelector);
}
#addEventListeners() {
/* TODO - 🟢 - scope events to requestConstructor.
The technique is to add:
addEventListener(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}
dispatchEvent(event, data) {
if (this.events[event]) {
this.events[event].forEach(callback => callback(data));
}
}
and then ` this.requestConstructor.addEventListener('resourceAnalysisRequestUpdated'
Problem is the component is not yet created.
*/
document.addEventListener('resourceAnalysisRequestUpdated', event => {
this.#setState({ request: event.detail });
this.#fetchEffortData().then(() => {
this.#renderFlexiTable();
document.dispatchEvent(new CustomEvent('resourceAnalysisRequestFulfilled', { detail: { success: true } }));
// TODO - 🟡 - error fetching is fatal an needs communication to user. Saving template just report to development.
this.#saveViewTemplate();
}).catch(
error => {
console.error('Error updating data:', error);
document.dispatchEvent(new CustomEvent('resourceAnalysisRequestFulfilled', { detail: { success: false } }));
});
});
document.addEventListener('flexiTablePivotOptionSelected', event => {
this.#setState({ pivotConfig: event.detail });
this.#saveViewTemplate();
this.#loadEffortTable();
});
//document.getElementById('loadAnalysisBtn').addEventListener('click', () => this.#fetchEffortData());
}
#loadEffortTable() {
if (this.state.responseData) {
const transformedData = this.#transformData(this.state.responseData, this.state.request.analysisMode, this.state.pivotConfig);
const event = new CustomEvent('resourceAnalysisDataUpdated', { detail: transformedData, bubbles: true });
document.dispatchEvent(event);
}
}
#transformData(responseData, analysisMode, pivotConfig) {
// Create an instance of EffortTransformer with the responseData
const effortTransformer = new EffortTransformer(responseData);
let data;
// Check the analysisMode and pivotConfig to decide which transformation method to use
switch (analysisMode) {
case VALID_ANALYSIS_MODES.intervals:
switch (pivotConfig) {
case VALID_PIVOT_CONFIGS.entityWorkItem:
data = effortTransformer.transformToIntervals('entity', 'workItem');
break;
case VALID_PIVOT_CONFIGS.entityUser:
data = effortTransformer.transformToIntervals('entity', 'user');
break;
case VALID_PIVOT_CONFIGS.user:
data = effortTransformer.transformToIntervals('user');
break;
default:
throw new Error('Invalid pivotConfig');
}
break;
case VALID_ANALYSIS_MODES.totals:
switch (pivotConfig) {
case VALID_PIVOT_CONFIGS.entityWorkItem:
data = effortTransformer.transformToTotals('entity', 'workItem');
break;
case VALID_PIVOT_CONFIGS.entityUser:
data = effortTransformer.transformToTotals('entity', 'user');
break;
case VALID_PIVOT_CONFIGS.user:
data = effortTransformer.transformToTotals('user');
break;
default:
throw new Error('Invalid pivotConfig');
}
break;
default:
throw new Error('Invalid analysisMode');
}
return data;
}
#setState(newState) {
mergeDeep(this.state, newState);
}
getSVG(name) {
const svgMap = {
'entity-workItem': '<svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg"><path d="M0 3.375C0 2.13398 1.00898 1.125 2.25 1.125H15.75C16.991 1.125 18 2.13398 18 3.375V5.625C18 6.86602 16.991 7.875 15.75 7.875H5.34375V11.25C5.34375 12.027 5.97305 12.6562 6.75 12.6562H7.875V12.375C7.875 11.134 8.88398 10.125 10.125 10.125H15.75C16.991 10.125 18 11.134 18 12.375V14.625C18 15.866 16.991 16.875 15.75 16.875H10.125C8.88398 16.875 7.875 15.866 7.875 14.625V14.3438H6.75C5.04141 14.3438 3.65625 12.9586 3.65625 11.25V7.875H2.25C1.00898 7.875 0 6.86602 0 5.625V3.375ZM15.75 11.8125H10.125C9.81562 11.8125 9.5625 12.0656 9.5625 12.375V14.625C9.5625 14.9344 9.81562 15.1875 10.125 15.1875H15.75C16.0594 15.1875 16.3125 14.9344 16.3125 14.625V12.375C16.3125 12.0656 16.0594 11.8125 15.75 11.8125Z" /></svg>',
'entity-user': '<svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg"><path d="M0 3.75C0 2.50898 1.00898 1.5 2.25 1.5H15.75C16.991 1.5 18 2.50898 18 3.75V6C18 7.24102 16.991 8.25 15.75 8.25H5.34375V13.0312C5.34375 13.8082 5.97305 13.875 6.75 13.875H7.9588L7.875 14.5C7.875 13.259 8.75898 12.5 10 12.5H13C14.241 12.5 15 13.259 15 14.5V15.375C15 16.616 15.241 17.25 14 17.25H9C7.75898 17.25 7.875 17.378 7.875 16.1369V15.375H6.75C5.04141 15.375 3.65625 14.7398 3.65625 13.0312V8.25H2.25C1.00898 8.25 0 7.24102 0 6V3.75Z" /><circle cx="11.5" cy="10.5" r="1.5" /></svg>',
'user': '<svg width="18" height="17" viewBox="0 0 18 17" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_345_11)"><path d="M0.125 6.5C0.125 5.25898 1.13398 4.5 2.375 4.5H8C9.24102 4.5 10 5.25898 10 6.5V9.34376C10 10.5848 9.61602 10.3438 8.375 10.3438H5.93674V12.2188C5.93674 12.9957 5.72305 13.5 6.5 13.5L7 13.5C7 12.259 7.25898 12.2188 8.5 12.2188H16C17.241 12.2188 17.75 12.259 17.75 13.5V15C17.75 16.241 17.241 16 16 16H8.5C7.25898 16 7 16.241 7 15V14.7188H5.875C4.16641 14.7188 4 13.9274 4 12.2188V10.3438H2.375C1.13398 10.3438 0.125 10.5848 0.125 9.34376V6.5Z"/><circle cx="5" cy="2" r="2"/></g><defs><clipPath id="clip0_345_11"><rect width="18" height="17" /></clipPath></defs></svg>'
};
return svgMap[name] || '';
}
}