This repository has been archived by the owner on May 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathsentences.js
391 lines (330 loc) · 10.4 KB
/
sentences.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
'use strict';
const debug = require('debug')('sentencecollector:sentences');
const { QueryTypes } = require('sequelize');
const { v4: uuidv4 } = require('uuid');
const { sequelize, Sentence } = require('./models');
const { FALLBACK_LOCALE } = require('./languages');
const { validateSentences } = require('./validation');
const votes = require('./votes');
const DUPLICATE_ERROR = 1062;
module.exports = {
getSentencesForLocale,
getApprovedSentencesForLocale,
getUndecidedSentencesForLocale,
getRejectedSentencesForLocale,
getSentencesForReview,
getRejectedSentences,
getMySentences,
deleteMySentences,
getStats,
getAllStatsForLocale,
getUserAddedSentencesPerLocale,
getUnreviewedByYouCountForLocales,
addSentences,
};
async function getSentencesForLocale({ localeId, source, batch, sentence }) {
debug('GETTING_SENTENCES_FOR_LOCALE', localeId);
const options = {
attributes: { exclude: ['userId'] },
order: [['createdAt', 'DESC']],
where: {
localeId,
}
};
if (sentence) {
options.where.sentence = sentence;
}
if (source) {
options.where.source = source;
}
if (batch) {
options.where.batch = batch;
}
return Sentence.findAll(options);
}
function getApprovedSentencesForLocale(locale) {
const validatedSentencesQuery = getValidatedSentencesQuery();
return sequelize.query(validatedSentencesQuery, { replacements: [locale], type: QueryTypes.SELECT });
}
function getUndecidedSentencesForLocale(locale) {
const undecidedSentencesQuery = getUndecidedSentencesQuery();
return sequelize.query(undecidedSentencesQuery, { replacements: [locale], type: QueryTypes.SELECT });
}
function getRejectedSentencesForLocale(locale) {
const rejectedSentencesQuery = getRejectedSentencesQuery({ locale });
return sequelize.query(rejectedSentencesQuery, { replacements: [locale], type: QueryTypes.SELECT });
}
async function getSentencesForReview({ locale, userId }) {
debug('GETTING_SENTENCES_FOR_LOCALE', locale);
const query = getReviewQuery();
const limittedQuery = `
${query}
LIMIT 1000
`;
const sentences = await sequelize.query(limittedQuery, { replacements: [locale, userId], type: QueryTypes.SELECT });
return sentences;
}
async function getRejectedSentences({ userId }) {
debug('GETTING_REJECTED_SENTENCES');
const query = getRejectedSentencesQuery({ userId });
const sentences = await sequelize.query(query, { replacements: [userId], type: QueryTypes.SELECT });
const sentencesPerLocale = sentences.reduce((perLocale, sentenceInfo) => {
perLocale[sentenceInfo.localeId] = perLocale[sentenceInfo.localeId] || [];
perLocale[sentenceInfo.localeId].push(sentenceInfo);
return perLocale;
}, {});
return sentencesPerLocale;
}
async function getMySentences({ userId }) {
debug('GETTING_MY_SENTENCES');
const options = {
where: {
userId,
},
};
const sentences = await Sentence.findAll(options);
const sentencesPerLocale = sentences.reduce((perLocale, sentenceInfo) => {
perLocale[sentenceInfo.localeId] = perLocale[sentenceInfo.localeId] || {};
const batch = sentenceInfo.batch || 0;
perLocale[sentenceInfo.localeId][batch] = perLocale[sentenceInfo.localeId][batch] || {
source: sentenceInfo.source,
sentences: []
};
perLocale[sentenceInfo.localeId][batch].sentences.push(sentenceInfo);
return perLocale;
}, {});
return sentencesPerLocale;
}
async function deleteMySentences({ userId, sentenceIds }) {
debug('DELETING_MY_SENTENCES');
const options = {
where: {
id: sentenceIds,
// Passing the userId here as well makes sure that sentences that
// do not belong to this user would silently be ignored.
userId,
},
};
await Sentence.destroy(options);
}
async function getStats(locales) {
debug('GETTING_STATS');
const totalStats = {};
for (const locale of locales) {
const options = {
where: {
localeId: locale,
},
};
const [validated, rejected, added] = await Promise.all([
getValidatedSentencesCountForLocale(locale),
getRejectedSentencesCountForLocale(locale),
Sentence.count(options),
]);
totalStats[locale] = {
added,
validated,
rejected,
};
}
return {
all: totalStats,
totals: {
total: await Sentence.count(),
languages: await Sentence.count({ distinct: true, col: 'localeId'}),
}
};
}
async function getAllStatsForLocale(locale) {
debug('GETTING_STATS_FOR_LOCALE');
const [validated, rejected, added, contributors] = await Promise.all([
getValidatedSentencesCountForLocale(locale),
getRejectedSentencesCountForLocale(locale),
Sentence.count({ where: { localeId: locale }}),
Sentence.count({ distinct: true, col: 'userId', where: { localeId: locale }}),
]);
return {
validated,
rejected,
added,
contributors,
};
}
async function getValidatedSentencesCountForLocale(locale) {
const validatedSentencesQuery = getValidatedSentencesQuery();
const query = `
SELECT COUNT(*) FROM
(${validatedSentencesQuery}) as approved_sentences;
`;
const queryResult = await sequelize.query(query, { replacements: [locale], type: QueryTypes.SELECT });
const validatedCount = queryResult[0] && queryResult[0]['COUNT(*)'];
return validatedCount;
}
async function getUnreviewedByYouCountForLocales(locales, userId) {
const stats = {};
for await (const locale of locales) {
const reviewQuery = getReviewQuery();
const query = `
SELECT COUNT(*) FROM
(${reviewQuery}) as approved_sentences;
`;
const queryResult = await sequelize.query(query, { replacements: [locale, userId], type: QueryTypes.SELECT });
stats[locale] = queryResult[0] && queryResult[0]['COUNT(*)'];
}
return stats;
}
async function getRejectedSentencesCountForLocale(locale) {
const rejectedQuery = getRejectedSentencesQuery({ locale });
const query = `
SELECT COUNT(*) FROM
(${rejectedQuery}) as rejected_sentences;
`;
const queryResult = await sequelize.query(query, { replacements: [locale], type: QueryTypes.SELECT });
const rejectedCount = queryResult[0] && queryResult[0]['COUNT(*)'];
return rejectedCount;
}
async function getUserAddedSentencesPerLocale(locales, userId) {
debug('GETTING_USER_ADDED_STATS');
const addedStats = {};
for (const locale of locales) {
const options = {
attributes: ['localeId'],
where: {
userId,
localeId: locale,
},
};
addedStats[locale] = await Sentence.count(options);
}
return addedStats;
}
async function addSentences(data) {
const {
sentences,
userId,
source,
locale = FALLBACK_LOCALE,
} = data;
const batch = uuidv4();
const { valid, validValidated, filtered } = validateSentences(locale, sentences);
debug('Creating database entries');
let duplicateCounter = 0;
const addSentenceToDatabase = (sentence, transaction, isValidated) => {
const params = {
sentence,
userId,
source,
batch,
localeId: locale,
};
return Sentence.create(params, { transaction })
.then((sentence) => {
if (!isValidated) {
return sentence;
}
const voteParams = {
sentenceId: sentence.id,
userId,
approval: true,
};
return votes.addVoteForSentence(voteParams, transaction);
})
.catch((error) => {
if (error.parent && error.parent.errno === DUPLICATE_ERROR) {
debug('Ignoring duplicate sentence', sentence);
duplicateCounter++;
}
});
};
const transaction = await sequelize.transaction();
const validPromises = valid.map((sentence) => addSentenceToDatabase(sentence, transaction, false));
const validatedPromises = validValidated.map((sentence) => addSentenceToDatabase(sentence, transaction, true));
await Promise.all([
...validPromises,
...validatedPromises,
]);
await transaction.commit();
return { errors: filtered, duplicates: duplicateCounter };
}
function getReviewQuery() {
return `
SELECT
Sentences.id,
Sentences.sentence,
Sentences.source,
Sentences.localeId,
SUM(Votes.approval) as number_of_approving_votes,
COUNT(Votes.approval) as number_of_votes
FROM Sentences
LEFT JOIN Votes ON (Votes.sentenceId=Sentences.id)
WHERE Sentences.localeId = ?
AND NOT EXISTS (SELECT *
FROM Votes
WHERE Sentences.id = Votes.sentenceId AND Votes.userId = ?)
GROUP BY Sentences.id
HAVING
number_of_votes < 2 OR # not enough votes yet
number_of_votes = 2 AND number_of_approving_votes = 1 # a tie at one each
ORDER BY number_of_votes DESC`;
}
// This is very similar to the Review Query, but without user. This could be incorporated
// with the query above, but that would make it vastly more complicated.
function getUndecidedSentencesQuery() {
return `
SELECT
Sentences.sentence,
SUM(Votes.approval) as number_of_approving_votes,
COUNT(Votes.approval) as number_of_votes
FROM Sentences
LEFT JOIN Votes ON (Votes.sentenceId=Sentences.id)
WHERE Sentences.localeId = ?
GROUP BY Sentences.id
HAVING
number_of_votes < 2 OR # not enough votes yet
number_of_votes = 2 AND number_of_approving_votes = 1 # a tie at one each
ORDER BY number_of_votes DESC`;
}
function getValidatedSentencesQuery() {
return `
SELECT
Sentences.id,
Sentences.sentence,
SUM(Votes.approval) as number_of_approving_votes
FROM Sentences
LEFT JOIN Votes ON (Votes.sentenceId = Sentences.id)
WHERE Sentences.localeId = ?
GROUP BY Sentences.id
HAVING
number_of_approving_votes >= 2`;
}
function getRejectedSentencesQuery({ userId, locale }) {
let whereClause = '';
if (typeof userId !== 'undefined') {
whereClause = `WHERE Sentences.userId = ?`;
}
if (locale) {
whereClause = whereClause ?
`${whereClause} and Sentences.localeId = ?` :
`WHERE Sentences.localeId = ?`;
}
return `
SELECT
Sentences.id,
Sentences.sentence,
Sentences.localeId,
SUM(Votes.approval) as number_of_approving_votes,
COUNT(Votes.approval) as number_of_votes
FROM Sentences
LEFT JOIN Votes ON (Votes.sentenceId=Sentences.id)
${whereClause}
GROUP BY Sentences.id
HAVING
(
number_of_votes = 3 AND
number_of_approving_votes < 2
) OR (
number_of_votes = 2 AND
number_of_approving_votes = 0
)
ORDER BY Sentences.createdAt DESC`;
}