charges.js
20 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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/* Round float to two decimals only */
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
function build_chart(div_selector, data_url, entity_name, category_type) {
const main_elt = document.getElementById("main")
var margin = {top: 60, right: 150, bottom: 200, left: 90},
width = main_elt.offsetWidth * 0.95 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
const height_ratio = 1.2; // how murch room to give above chart for lisibility
const tooltip_offset = {dx: 0, dy: 100}
const tooltip_offset_dot = {dx: 20, dy: 60}
const y_ticks_num = 5 // dont show to many y ticks for lisibility
const legend_rect_size = 15; // size of rectangle in legend
const legend_height = 20;
const legend_max_length = 30;
const legend_spacing = 5;
const dot_radius = 6; // size of total line dot
var colorScale = d3.scaleOrdinal([]); // Will be really set later by category type
//
// Configure chart by the category given as arg
//
var chart_title = ""
var category_title = ""
var draw_areas = () => void 0;
var draw_total_line = () => void 0;
var draw_categories_bars = () => void 0;
if (category_type == 'capacity') {
chart_title = "Charges par fonction"
category_title = "Fonction"
//draw_total_line
draw_categories_bars = draw_categories_grouped
colorScale = d3.scaleOrdinal(d3.schemeSet3);
} else if (category_type == 'service') {
chart_title = "Charges par service"
category_title = "Service"
draw_total_line = draw_totalcharge_line
draw_categories_bars = draw_categories_stacked
colorScale = d3.scaleOrdinal(d3.schemeTableau10);
} else if (category_type == 'project') {
chart_title = "Charges par projet"
category_title = "Projet"
draw_categories_bars = draw_categories_stacked
colorScale = d3.scaleOrdinal(d3.schemeTableau10);
} else if (category_type == 'area') {
margin = {top: 60, right: 150, bottom: 350, left: 90};
height = 1200 - margin.top - margin.bottom;
chart_title = "Tous agents confondus"
category_title = "Projet"
draw_areas = draw_projects_areas
colorScale = d3.scaleOrdinal(d3.schemeTableau10);
} else {
alert("ALERT ! Every body shall quit the boat, we are sinking ! ALERT !")
}
const xScale = d3.scaleBand()
.range([0, width])
.padding(0.4);
const yScale = d3.scaleLinear()
.range([height, 0]);
// Configure the tooltip to export svg to png or csv
var update_export_menu = function (e, d) {
const tooltip_test = document.getElementsByClassName('tooltip_hamburger');
if (tooltip_test.length == 0) {
d3.select(".tooltip_hamburger").remove();
const tooltip_hamburger = hamburger.append("div")
.style("opacity", 0)
.attr("class", "tooltip tooltip_hamburger");
d3.select(this).transition()
.duration(1)
tooltip_hamburger
.transition()
.duration(200)
.style("opacity", 1)
tooltip_hamburger
.html("<span>Export </span>" +
"<li id='to_csv'>To CSV</li>" +
"<li id='to_png'>To PNG</li>")
d3.select("#to_png").on("click", download_png);
d3.select("#to_csv").on("click", function () {
download_csv(this, data_url);
})
} else {
d3.select(".tooltip_hamburger").remove();
}
}
// Create a download button inside the div contaning svg chart
const hamburger = d3.select(div_selector).append('i')
.attr('class', 'fas fa-bars fa-lg export')
.on("click", update_export_menu);
const real_width = width + margin.left + margin.right;
const real_height = height + margin.top + margin.bottom;
const svg = d3.select(div_selector).append("svg")
.attr("viewBox", [0, 0, real_width, real_height])
.attr("class", "svg_chart")
.attr("width", real_width)
.attr("height", real_height)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
const tooltip = d3.select('html')
.append("div")
.style("opacity", 0)
.attr("class", "tooltip")
var mousemove = function (e, d) {
tooltip
.style("left", (e.pageX - tooltip_offset.dx) + "px")
.style("top", (e.pageY - tooltip_offset.dy) + "px")
}
var mouseleave = function (d) {
tooltip
.transition()
.duration(900)
.style("opacity", 0)
}
var mouseover = function (e, d) {
var category_name = d3.select(this.parentNode).datum().key
var category_charge = d.data[category_name]
show_tooltip(e, category_name, category_charge)
}
var mouseovergrouped = function (e, d) {
var category_name = d.key
var category_charge = d.value
show_tooltip(e, category_name, category_charge)
}
var show_tooltip = function (e, category_name, category_charge) {
tooltip
.transition()
.duration(200)
.style("opacity", 1);
tooltip
.html("<b>" + category_title + ":</b> " + category_name + "<br>" + "<b>Charge:</b> " + category_charge + " ETP")
.style("left", (e.pageX - tooltip_offset.dx) + "px")
.style("top", (e.pageY - tooltip_offset.dy) + "px")
}
var mouseleavedot = function (e, d) {
d3.select(this).transition()
.duration(1)
.attr("r", dot_radius);
mouseleave(d);
}
var mouseoverdot = function (e, d) {
d3.select(this).transition()
.duration(1)
.attr("r", dot_radius * 1.5);
tooltip
.transition()
.duration(200)
.style("opacity", 1)
tooltip
.html("<b>" + d.period + ": </b>" + d.total + " ETP")
.style("left", (e.pageX - tooltip_offset_dot.dx) + "px")
.style("top", (e.pageY - tooltip_offset_dot.dy) + "px")
}
function mouseoverlegend() {
var legend_category = $(this).attr("class");
var bar_category = document.getElementsByClassName(legend_category);
if (bar_category[0].tagName === "g") {
var rect_to_hover = bar_category[0].children;
(bar_category[1].children[0]).classList.add("brillance");
for (var i=0;i<rect_to_hover.length;i++) {
rect_to_hover[i].classList.add("brillance");
}
} else {
for (var i=0;i<bar_category.length;i++) {
bar_category[i].classList.add("brillance");
}
}
}
function mouseleavelegend() {
var legend_category = $(this).attr("class");
var bar_category = document.getElementsByClassName(legend_category);
if (bar_category[0].tagName === "g") {
var rect_to_hover = bar_category[0].children;
(bar_category[1].children[0]).classList.remove("brillance");
for (var i=0;i<rect_to_hover.length;i++) {
rect_to_hover[i].classList.remove("brillance");
}
} else {
var lenght_i = bar_category.length - 1;
for (var i=lenght_i;i>=0;i--) {
bar_category[i].classList.remove("brillance");
}
}
}
var addlegend = function (color_scale) {
// add horizontal legend
let legend_keys = color_scale.domain();
// Truncate legend keys when too long
legend_keys = legend_keys.map(function (l) {
const n = legend_max_length;
return (l.length > n) ? l.substr(0, n - 1) : l;
});
// Get Max legend key length for later display
const max_key_length = Math.max(...legend_keys.map(el => el.length));
var legendWrap = svg.append('g')
.attr('width', '100%')
.attr('class', 'legendwrap');
var legend = svg.select('.legendwrap').selectAll('.legend')
.data(legend_keys)
.enter()
.append('g')
.attr('class', function (d) { return d})
.on("mouseover", mouseoverlegend)
.on("mouseleave", mouseleavelegend);
legend.append('rect')
.attr('width', legend_rect_size)
.attr('height', legend_rect_size)
.style('fill', color_scale)
.attr('class', 'legend');
legend.append('text')
.attr('class', 'legend')
.attr('x', legend_rect_size + legend_spacing * 1.5)
.attr('y', 13)
.text(d => d);
var ypos = 0,
newxpos = 0,
maxwidth = 0,
xpos;
legend
.attr("transform", function (d, i) {
const key_length = 9*max_key_length;
xpos = newxpos;
if (width < xpos + key_length) {
newxpos = xpos = 0;
ypos += legend_height;
}
newxpos += key_length;
if (newxpos > maxwidth) maxwidth = newxpos;
return 'translate(' + xpos + ',' + ypos + ')';
});
legendWrap
.attr("transform", function (d, i) {
return "translate(0 ," + (height + 100) + ")";
});
}
function draw_categories_grouped(data, categories) {
// TODO: use ymax_from_stacked
// Get the max y to plot
// If no data at all, force to 0
if (categories.length == 0) {
y_max = 0
} else {
var y_max = d3.max(data, function (d) {
return d3.max(categories, function (c) {
return +d[c]
})
});
}
// Force maximum in any cases
if (y_max == 0) {
y_max = 100
}
y_max = y_max * height_ratio
yScale.domain([0, y_max])
// Another scale for subgroup position
var xCategories = d3.scaleBand()
.domain(categories)
.range([0, xScale.bandwidth()])
.padding([0.2])
svg.append("g")
.selectAll("g")
// Enter in data = loop group per group
.data(data)
.enter()
.append("g")
.attr("transform", d => "translate(" + xScale(d.period) + ",0)")
.selectAll("rect")
.data(function (d) {
return categories.map(function (key) {
return {key: key, value: d[key]};
});
})
.enter().append("rect")
.attr("x", d => xCategories(d.key))
.attr("width", xCategories.bandwidth())
/* Transition part */
.attr("y", d => {
return height;
})
.attr("height", 0)
.transition()
.duration(750)
.delay(function (d, i) {
return i * 150;
})
.attr("y", d => yScale(d.value))
.attr("height", d => height - yScale(d.value))
.attr("fill", d => colorScale(d.key))
.attr("class", d => d.key);
svg.selectAll("rect")
.on("mouseover", mouseovergrouped)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave);
}
function ymax_from_stacked(stacked_data){
// Get the max y to plot
// If no data at all, force to 0
if (stacked_data.length == 0) {
y_max = 0
} else {
var y_max = d3.max(stacked_data[stacked_data.length - 1], d => d[1]);
}
// Force maximum in any cases
if (y_max == 0) {
y_max = 100
}
// Enhance it by %ratio to leave room on the top of the graph
y_max = y_max * height_ratio
return y_max
}
function draw_projects_areas(data, projects) {
// Now build the stacked data for stacked bars
//
var stack = d3.stack()
.keys(projects)
// .order(d3.stackOrderNone)
// .offset(d3.stackOffsetNone);
var stacked_data = stack(data)
const y_max = ymax_from_stacked(stacked_data);
yScale.domain([0, y_max ]);
const area = d3.area()
.x(d => xScale(d.data.period))
.y0(d => yScale(d[0]))
.y1(d => yScale(d[1]))
let paths = svg.append("g")
.selectAll("path")
.data(stacked_data)
.join("path")
.attr("fill", ({key}) => colorScale(key))
.attr("stroke", 'black')
.attr("stroke-width", '0.2pt')
.attr("d", area)
.append("title")
.text(({key}) => key);
paths.selectAll("area")
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave);
}
function draw_categories_stacked(data, categories) {
// Now build the stacked data for stacked bars
//
var stack = d3.stack()
.keys(categories)
// .order(d3.stackOrderNone)
// .offset(d3.stackOffsetNone);
var stacked_data = stack(data)
const y_max = ymax_from_stacked(stacked_data);
yScale.domain([0, y_max ]);
// first draw one group for one category containing all bars over periods
let groups = svg.selectAll("g.category")
.data(stacked_data)
.enter()
.append("g")
.attr("class", d => d.key)
.style("fill", (d) => colorScale(d.key));
// then draw each period/category bar
let rect = groups.selectAll("rect")
.data(d => d)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", d => xScale(d.data.period))
.attr("width", xScale.bandwidth())
/* transition part */
.attr("y", d => {
return height;
})
.attr("height", 0)
.transition()
.duration(750)
.delay(function (d, i) {
return i * 150;
})
.attr("y", d => yScale(d[1]))
.attr("height", d => height - yScale(d[1] - d[0]))
groups.selectAll("rect")
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave);
}
function draw_totalcharge_line(data) {
// Build the total charge by period;
// it will be used for the line drawing above bars.
//
var periods_total_charge = []
data.forEach(function (d) {
// get the list of values for all columns except the first one which is the period name
var period_values = Object.values(d).slice(1)
var row = {}
row['period'] = d.period
row['total'] = roundToTwo(d3.sum(period_values))
periods_total_charge.push(row)
});
// the line itselet
//
const line = d3.line()
.x(d => (xScale.bandwidth() / 2) + xScale(d.period)) // décalage pour centrer au milieu des barres
.y(d => yScale(d.total))
.curve(d3.curveMonotoneX); // Fonction de courbe permettant de l'adoucir
svg.append("path")
.datum(periods_total_charge)
.attr("class", "total-line")
.attr("d", line)
.lower();// set it below bars if called after
// data dots at each point
//
svg.selectAll("line-circle")
.data(periods_total_charge)
.enter().append("circle")
.attr("class", "total-circle")
.attr("r", dot_radius)
.attr("cx", function (d) {
return (xScale.bandwidth() / 2) + xScale(d.period)
})
.attr("cy", function (d) {
return yScale(d.total);
})
.on("mouseover", mouseoverdot)
.on("mouseleave", mouseleavedot)
.lower();// set it below bars if called after
}
d3.csv(data_url).then(data => {
// we could get categories that way,
// var categories = data.columns.slice(1)
// but instead we want to filter by non zero, see later
var periods = d3.map(data, d => d.period)
xScale.domain(periods)
// Filter datas to only keep non zero categories
// TODO: should be done on server (python/flask) side
//
// 1- Get the charge sum for each category over periods
// That will leave '0' to categories with no charge at all
// TODO: to be done with Object.keys, Object.values and d3 filtering methods
//
var categories_total_charge = {}
data.forEach(function (d) {
Object.keys(d).forEach(function (k) {
if (k === 'period') {
return;
}
if (categories_total_charge.hasOwnProperty(k)) {
categories_total_charge[k] += +d[k]
} else {
categories_total_charge[k] = +d[k]
}
categories_total_charge[k] = roundToTwo(categories_total_charge[k])
}
)
})
// 2- Now, filter only categories that have a non-zero charge
// TODO: to be done with Object.keys, Object.values and d3 filtering methods
//
var categories = []
for (var key in categories_total_charge) {
if (categories_total_charge[key] > 0) {
categories.push(key)
}
}
//
// Draw the areas, stacked.
//
draw_areas(data, categories)
//
// Draw the bars, stacked or grouped
//
draw_categories_bars(data, categories)
//
// Draw the total charge line ( may be)
//
draw_total_line(data, categories)
//
// This former list we use as color_scale domain.
// And that allows us to build the legend
//
colorScale.domain(categories)
addlegend(colorScale)
// Xaxis
//
const xAxis = d3.axisBottom(xScale)
// Draw Xaxis
svg.append("g")
.attr("class", "x_axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.9em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)");
// Yaxis
//
const yAxis = d3.axisLeft(yScale)
.ticks(y_ticks_num)
// Draw Yaxis
svg.append("g")
.attr("class", "y_axis")
.call(yAxis)
// Draw horizontal lines
svg.selectAll("y axis")
.data(yScale.ticks(y_ticks_num))
.enter()
.append("line")
.attr("class", d => (d == 0 ? "horizontalY0" : "horizontalY"))
.attr("x1", 0)
.attr("x2", width)
.attr("y1", d => yScale(d))
.attr("y2", d => yScale(d))
.lower();// set it below bars if called after
// Write Y axis title
svg.append("text")
.attr("text-anchor", "end")
.attr("transform", "rotate(-90)")
.attr("y", -margin.left + 40)
.attr("x", -margin.top - 70)
.text("Charge en ETP");
//
// Write chart Title
//
// part 1
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2) - 10)
.attr("text-anchor", "middle")
.style("font-size", "16px")
.text(entity_name);
// part 2
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2) + 10)
.attr("text-anchor", "middle")
.style("font-size", "12px")
.text(chart_title);
}); // end of d3.csv().then({})
}