This repository was archived by the owner on Mar 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathVoteStats.js
452 lines (417 loc) · 11.2 KB
/
VoteStats.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
const {postalCodeData, postalCodeParsers} = require('../../lib/geo/postalCode')
const countryNameNormalizer = require('../../lib/geo/country').nameNormalizer
const nest = require('d3-collection').nest
const {descending} = require('d3-array')
// see commented code below for chSlt2012
// const getBFSNr = require('../../lib/geo/chPostalCode').getBFSNr
// const getSlt = require('../../lib/geo/chSlt').getSlt
// const util = require('util')
const reduceOptions = (entries) =>
nest()
.key(o => o.name)
.rollup(values => ({
name: values[0].name,
id: values[0].id,
count: values.reduce(
(sum, v) => sum + v.count,
0
)
}))
.entries(entries)
.map(o => ({
name: o.value.name,
id: o.value.id,
count: o.value.count
}))
const countStatsCounts = (statsCounts, sort = true) => {
const keyOrder = (key) => {
switch (key) {
case 'others':
return -1
case 'null':
return -2
default:
return 0
}
}
const countedStatsCounts = statsCounts
.map(c => {
const optionCountMax = c.options.map(o => o.count).reduce(
(prev, current) => prev > current ? prev : current,
0
)
return Object.assign({}, c, {
count: c.options.reduce(
(sum, v) => sum + v.count,
0
),
options: c.options
.map(o => Object.assign({}, o, {
winner: o.count === optionCountMax
}))
.sort((a, b) => descending(a.count, b.count))
})
})
if (sort) {
return countedStatsCounts
.sort((a, b) => (
descending(keyOrder(a.key), keyOrder(b.key)) ||
descending(a.count, b.count)
))
} else {
return countedStatsCounts
}
}
module.exports = {
ages: async (stats, args, {pgdb}) => {
if (stats && stats.ages) { // cached by countVoting
return stats.ages
}
const {voting} = stats
// others (no birthday)
const nullOptions = await pgdb.query(`
SELECT
vo.id AS id,
vo.name AS name,
COUNT(b."votingOptionId") AS count
FROM
"votingOptions" vo
LEFT JOIN
ballots b
ON vo.id=b."votingOptionId"
LEFT JOIN
users u
ON b."userId"=u.id
WHERE
u.birthday is null AND
vo."votingId" = :votingId
GROUP BY
1, 2
ORDER BY
3 DESC
`, {
votingId: voting.id
})
const nullStatsCount = {
key: 'null',
options: nullOptions
}
const flatAgeOptions = await pgdb.query(`
SELECT
min,
max,
id,
name,
count
FROM (
SELECT
*
FROM
json_to_recordset('[
{"min": 0, "max": 19},
{"min": 20, "max": 29},
{"min": 30, "max": 39},
{"min": 40, "max": 49},
{"min": 50, "max": 59},
{"min": 60, "max": 69},
{"min": 70, "max": 79},
{"min": 80, "max": null}
]') as x("min" int, "max" int)
) e1 JOIN LATERAL (
SELECT
vo.id AS id,
vo.name AS name,
COUNT(b."votingOptionId") AS count
FROM
"votingOptions" vo
JOIN
ballots b
ON vo.id=b."votingOptionId"
JOIN
users u
ON
b."userId"=u.id AND
u.birthday is not null AND
extract(year from age(u.birthday)) >= e1.min AND
((e1.max IS NULL) OR extract(year from age(u.birthday)) <= e1.max)
WHERE
vo."votingId" = :votingId
GROUP BY
1, 2
ORDER BY
3 DESC
) e2 ON true;
`, {
votingId: voting.id
})
const allOptions = await pgdb.query(`
SELECT
vo.id AS id,
vo.name AS name,
0 AS count
FROM
"votingOptions" vo
WHERE
vo."votingId" = :votingId
`, {
votingId: voting.id
})
const ageStatsCount = nest()
.key(d => d.max ? `${d.min}-${d.max}` : `${d.min}+`)
.entries(flatAgeOptions)
.map(d => ({
key: d.key,
options: d.values.map(o => ({
id: o.id,
name: o.name,
count: o.count
}))
}))
.map(d => {
if (d.options.length < 3) {
let missingOptions = []
allOptions.forEach(option => {
if (!d.options.find(o => o.id === option.id)) {
missingOptions.push(option)
}
})
return Object.assign({}, d, {
options: d.options.concat(missingOptions)
})
}
return d
})
return countStatsCounts(ageStatsCount.concat([nullStatsCount]), false)
},
countries: async (stats, args, {pgdb}) => {
if (stats && stats.countries) { // cached by countVoting
return stats.countries
}
const {voting} = stats
const allCountriesVotingOptions = await pgdb.query(`
SELECT
"countryName",
id,
name,
count
FROM (
SELECT
lower(trim(a.country)) AS "countryName",
array_agg(b.id) AS ballot_ids
FROM
users u
JOIN
ballots b
ON b."userId"=u.id
LEFT JOIN
addresses a
ON u."addressId" = a.id
WHERE
b."votingId" = :votingId
GROUP BY
1
ORDER BY
1
) e1 JOIN LATERAL (
SELECT
vo.id AS id,
vo.name AS name,
COUNT(b."votingOptionId") AS count
FROM
"votingOptions" vo
LEFT JOIN
ballots b
ON
vo.id=b."votingOptionId" AND
ARRAY[b.id] && e1.ballot_ids
GROUP BY
1, 2
ORDER BY
3 DESC
) e2 ON true;
`, {
votingId: voting.id
})
const nullCountryOptions = {
key: 'null',
options: allCountriesVotingOptions.filter(o => o.countryName === null)
}
const countryOptions = nest()
.key(d => countryNameNormalizer(d.countryName))
.entries(allCountriesVotingOptions.filter(d => d.countryName !== null))
.map(d => ({
key: d.key,
options: reduceOptions(d.values)
}))
let designatedCountryOptions = []
let otherCountryOptions = []
countryOptions.forEach(c => {
const total = c.options.reduce(
(sum, v) => sum + v.count,
0
)
if (total >= 7) {
designatedCountryOptions.push(c)
} else {
otherCountryOptions.push(c)
}
})
const combinedOtherCountryOptions = {
key: 'others',
options: reduceOptions([].concat.apply([], otherCountryOptions.map(d => d.options)))
}
return countStatsCounts([].concat(designatedCountryOptions, combinedOtherCountryOptions, nullCountryOptions))
},
chCantons: async (stats, args, {pgdb}) => {
if (stats && stats.chCantons) { // cached by countVoting
return stats.chCantons
}
const {voting} = stats
const allCountriesWithPostalCodesVotingOptions = await pgdb.query(`
SELECT
"countryName",
"postalCode",
id,
name,
count
FROM (
SELECT
lower(trim(a.country)) AS "countryName",
trim(a."postalCode") as "postalCode",
array_agg(b.id) AS ballot_ids
FROM
users u
JOIN
ballots b
ON b."userId"=u.id
LEFT JOIN
addresses a
ON u."addressId" = a.id
WHERE
b."votingId" = :votingId
GROUP BY
1, 2
ORDER BY
2
) e1 JOIN LATERAL (
SELECT
vo.id AS id,
vo.name AS name,
COUNT(b."votingOptionId") AS count
FROM
"votingOptions" vo
LEFT JOIN
ballots b
ON
vo.id=b."votingOptionId" AND
ARRAY[b.id] && e1.ballot_ids
GROUP BY
1, 2
ORDER BY
3 DESC
) e2 ON true;
`, {
votingId: voting.id
})
const pcParser = postalCodeParsers['CH']
const switzerlandOptions = nest()
.key(d => countryNameNormalizer(d.countryName))
.entries(allCountriesWithPostalCodesVotingOptions.filter(d => d.countryName !== null))
.find(d => d.key === 'Schweiz')
const postalCodeOptions = nest()
.key(d => pcParser(d.postalCode))
.entries(switzerlandOptions.values)
.map(d => {
const baseData = postalCodeData('CH', d.key)
return {
key: baseData && baseData.stateAbbr.length > 0
? baseData.stateAbbr
: 'others',
options: reduceOptions(d.values)
}
})
const stateStatsCount = nest()
.key(c => c.key)
.entries(postalCodeOptions)
.map(c => ({
key: c.key,
options: reduceOptions([].concat.apply([], c.values.map(d => d.options)))
}))
return countStatsCounts(stateStatsCount)
}
/* addresses -> bfsNr matching needs refinement. check lib/geo/chPostalCode.js
chSlt2012: async (_, args, {pgdb}) => {
const {voting} = stats
const allCountriesWithPostalCodesAndCityVotingOptions = await pgdb.query(`
SELECT
"countryName",
"postalCode",
city,
id,
name,
count
FROM (
SELECT
lower(trim(a.country)) AS "countryName",
trim(a."postalCode") as "postalCode",
trim(a.city) as city,
array_agg(b.id) AS ballot_ids
FROM
users u
JOIN
ballots b
ON b."userId"=u.id
LEFT JOIN
addresses a
ON u."addressId" = a.id
WHERE
b."votingId" = :votingId
GROUP BY
1, 2, 3
ORDER BY
2, 3
) e1 JOIN LATERAL (
SELECT
vo.id AS id,
vo.name AS name,
COUNT(b."votingOptionId") AS count
FROM
"votingOptions" vo
LEFT JOIN
ballots b
ON
vo.id=b."votingOptionId" AND
ARRAY[b.id] && e1.ballot_ids
GROUP BY
1, 2
ORDER BY
3 DESC
) e2 ON true;
`, {
votingId: voting.id
})
const pcParser = postalCodeParsers['CH']
const switzerlandOptions = nest()
.key( d => countryNameNormalizer(d.countryName))
.entries(allCountriesWithPostalCodesAndCityVotingOptions.filter( d => d.countryName !== null))
.find( d => d.key === 'Schweiz')
const bfsOptions = nest()
.key( d => getBFSNr(d.postalCode, d.city.trim()))
.entries(switzerlandOptions.values)
//console.log(util.inspect(bfsOptions, {depth: null}))
const reducedBfsOptions = bfsOptions
.map( d => ({
bfsNr: d.key,
options: reduceOptions(d.values)
}))
const chSlt2012 = nest()
.key( d => getSlt(d.bfsNr))
.entries(reducedBfsOptions)
.map( d => ({
key: d.key === 'undefined' ? 'others' : d.key,
options: reduceOptions( [].concat.apply([], d.values.map( c => c.options) ) )
}))
return countStatsCounts(chSlt2012)
},
*/
}