@things-factory/survey 0.0.0-stage → 10.1.316

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist-client/index.d.ts +1 -0
  2. package/dist-client/index.js +2 -0
  3. package/dist-client/pages/my-surveys.d.ts +24 -0
  4. package/dist-client/pages/my-surveys.js +256 -0
  5. package/dist-client/pages/survey-editor.d.ts +62 -0
  6. package/dist-client/pages/survey-editor.js +668 -0
  7. package/dist-client/pages/survey-list.d.ts +15 -0
  8. package/dist-client/pages/survey-list.js +150 -0
  9. package/dist-client/pages/survey-trustee.d.ts +21 -0
  10. package/dist-client/pages/survey-trustee.js +170 -0
  11. package/dist-client/route.d.ts +1 -0
  12. package/dist-client/route.js +17 -0
  13. package/dist-client/utils/survey-api.d.ts +16 -0
  14. package/dist-client/utils/survey-api.js +46 -0
  15. package/dist-client/utils/survey-result.d.ts +4 -0
  16. package/dist-client/utils/survey-result.js +79 -0
  17. package/dist-client/utils/survey-secret.d.ts +40 -0
  18. package/dist-client/utils/survey-secret.js +154 -0
  19. package/dist-server/index.d.ts +2 -0
  20. package/dist-server/index.js +27 -0
  21. package/dist-server/role-tasks.d.ts +2 -0
  22. package/dist-server/role-tasks.js +16 -0
  23. package/dist-server/service/index.d.ts +16 -0
  24. package/dist-server/service/index.js +30 -0
  25. package/dist-server/service/refusal.d.ts +57 -0
  26. package/dist-server/service/refusal.js +66 -0
  27. package/dist-server/service/survey/ballot-route.d.ts +1 -0
  28. package/dist-server/service/survey/ballot-route.js +30 -0
  29. package/dist-server/service/survey/ballot-worker.d.ts +1 -0
  30. package/dist-server/service/survey/ballot-worker.js +19 -0
  31. package/dist-server/service/survey/index.d.ts +10 -0
  32. package/dist-server/service/survey/index.js +14 -0
  33. package/dist-server/service/survey/survey-answer.d.ts +23 -0
  34. package/dist-server/service/survey/survey-answer.js +99 -0
  35. package/dist-server/service/survey/survey-attributes.d.ts +16 -0
  36. package/dist-server/service/survey/survey-attributes.js +39 -0
  37. package/dist-server/service/survey/survey-ballot.d.ts +14 -0
  38. package/dist-server/service/survey/survey-ballot.js +61 -0
  39. package/dist-server/service/survey/survey-class-key.d.ts +20 -0
  40. package/dist-server/service/survey/survey-class-key.js +92 -0
  41. package/dist-server/service/survey/survey-question.d.ts +27 -0
  42. package/dist-server/service/survey/survey-question.js +113 -0
  43. package/dist-server/service/survey/survey-resolver.d.ts +37 -0
  44. package/dist-server/service/survey/survey-resolver.js +492 -0
  45. package/dist-server/service/survey/survey-respondent.d.ts +17 -0
  46. package/dist-server/service/survey/survey-respondent.js +81 -0
  47. package/dist-server/service/survey/survey-rules.d.ts +169 -0
  48. package/dist-server/service/survey/survey-rules.js +299 -0
  49. package/dist-server/service/survey/survey-secret.d.ts +133 -0
  50. package/dist-server/service/survey/survey-secret.js +347 -0
  51. package/dist-server/service/survey/survey-service.d.ts +83 -0
  52. package/dist-server/service/survey/survey-service.js +384 -0
  53. package/dist-server/service/survey/survey-trustee.d.ts +25 -0
  54. package/dist-server/service/survey/survey-trustee.js +119 -0
  55. package/dist-server/service/survey/survey-types.d.ts +91 -0
  56. package/dist-server/service/survey/survey-types.js +319 -0
  57. package/dist-server/service/survey/survey.d.ts +47 -0
  58. package/dist-server/service/survey/survey.js +214 -0
  59. package/dist-shared/ballot.d.ts +54 -0
  60. package/dist-shared/ballot.js +146 -0
  61. package/dist-shared/blind-rsa.d.ts +18 -0
  62. package/dist-shared/blind-rsa.js +127 -0
  63. package/dist-shared/elgamal.d.ts +20 -0
  64. package/dist-shared/elgamal.js +54 -0
  65. package/dist-shared/group.d.ts +22 -0
  66. package/dist-shared/group.js +112 -0
  67. package/dist-shared/proofs.d.ts +20 -0
  68. package/dist-shared/proofs.js +94 -0
  69. package/dist-shared/threshold.d.ts +39 -0
  70. package/dist-shared/threshold.js +98 -0
  71. package/dist-shared/verify.d.ts +13 -0
  72. package/dist-shared/verify.js +73 -0
  73. package/package.json +63 -4
  74. package/things-factory.config.js +15 -0
  75. package/translations/en.json +202 -0
  76. package/translations/es.json +202 -0
  77. package/translations/ja.json +202 -0
  78. package/translations/ko.json +202 -0
  79. package/translations/ms.json +202 -0
  80. package/translations/zh.json +202 -0
  81. package/README.md +0 -3
@@ -0,0 +1,384 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.questionsOf = void 0;
4
+ exports.surveyOf = surveyOf;
5
+ exports.createSurvey = createSurvey;
6
+ exports.updateSurvey = updateSurvey;
7
+ exports.deleteSurvey = deleteSurvey;
8
+ exports.setSurveyQuestions = setSurveyQuestions;
9
+ exports.askedUserIdsOf = askedUserIdsOf;
10
+ exports.classesOf = classesOf;
11
+ exports.classPreviewOf = classPreviewOf;
12
+ exports.openSurvey = openSurvey;
13
+ exports.answerSurvey = answerSurvey;
14
+ exports.closeSurvey = closeSurvey;
15
+ exports.rateOf = rateOf;
16
+ exports.countSurvey = countSurvey;
17
+ exports.publishSurvey = publishSurvey;
18
+ exports.cancelSurvey = cancelSurvey;
19
+ exports.closeDueSurveys = closeDueSurveys;
20
+ exports.scheduleSurveyClosing = scheduleSurveyClosing;
21
+ exports.previousChoicesOf = previousChoicesOf;
22
+ exports.carryForward = carryForward;
23
+ /*
24
+ * A survey's steps on the database (operato-survey design §3-1) - make a draft and its questions, open it to the people
25
+ * its audience names, take each one's answers once, close it, count and publish. The rules are survey-rules.ts.
26
+ */
27
+ const typeorm_1 = require("typeorm");
28
+ const env_1 = require("@things-factory/env");
29
+ const organization_1 = require("@things-factory/organization");
30
+ const shell_1 = require("@things-factory/shell");
31
+ const refusal_1 = require("../refusal");
32
+ const survey_1 = require("./survey");
33
+ const survey_answer_1 = require("./survey-answer");
34
+ const survey_question_1 = require("./survey-question");
35
+ const survey_respondent_1 = require("./survey-respondent");
36
+ const survey_attributes_1 = require("./survey-attributes");
37
+ const survey_secret_1 = require("./survey-secret");
38
+ const survey_rules_1 = require("./survey-rules");
39
+ const refuse = (problem) => (0, refusal_1.surveyRefusal)(problem.code, problem.params ?? {});
40
+ async function surveyOf(tx, domain, id) {
41
+ const one = id ? await tx.getRepository(survey_1.Survey).findOne({ where: { id, domain: { id: domain.id } } }) : null;
42
+ if (!one)
43
+ throw (0, refusal_1.surveyRefusal)('survey-unknown', { survey: id ?? '' });
44
+ return one;
45
+ }
46
+ function mustStep(survey, step) {
47
+ const problem = (0, survey_rules_1.stepRefusal)(step, survey.status);
48
+ if (problem)
49
+ throw refuse(problem);
50
+ }
51
+ function checkedPatch(patch) {
52
+ const out = {};
53
+ if (patch.name !== undefined) {
54
+ if (!String(patch.name ?? '').trim())
55
+ throw (0, refusal_1.surveyRefusal)('survey-name-required');
56
+ out.name = String(patch.name).trim();
57
+ }
58
+ if (patch.description !== undefined)
59
+ out.description = patch.description ?? undefined;
60
+ if (patch.level !== undefined) {
61
+ if (!survey_rules_1.SURVEY_LEVELS.includes(String(patch.level)))
62
+ throw (0, refusal_1.surveyRefusal)('survey-level-unknown', { level: String(patch.level) });
63
+ out.level = patch.level;
64
+ }
65
+ if (patch.audience !== undefined)
66
+ out.audience = patch.audience ?? [];
67
+ if (patch.excludedUserIds !== undefined)
68
+ out.excludedUserIds = patch.excludedUserIds ?? [];
69
+ if (patch.basisDate !== undefined)
70
+ out.basisDate = patch.basisDate ?? undefined;
71
+ if (patch.closesAt !== undefined)
72
+ out.closesAt = patch.closesAt ?? undefined;
73
+ if (patch.resultReaders !== undefined) {
74
+ if (patch.resultReaders && !survey_rules_1.RESULT_READERS.includes(patch.resultReaders))
75
+ throw (0, refusal_1.surveyRefusal)('survey-readers-required');
76
+ out.resultReaders = patch.resultReaders ?? undefined;
77
+ }
78
+ if (patch.publishedFigure !== undefined) {
79
+ if (patch.publishedFigure && !['WEIGHTED', 'UNWEIGHTED'].includes(patch.publishedFigure))
80
+ throw (0, refusal_1.surveyRefusal)('survey-figure-unknown');
81
+ out.publishedFigure = patch.publishedFigure ?? undefined;
82
+ }
83
+ if (patch.minGroup !== undefined)
84
+ out.minGroup = patch.minGroup && patch.minGroup > 0 ? patch.minGroup : undefined;
85
+ const whole = (value) => (value && Number.isInteger(value) && value > 0 ? value : undefined);
86
+ if (patch.publishTop !== undefined)
87
+ out.publishTop = whole(patch.publishTop) ?? null;
88
+ if (patch.publishTopFigures !== undefined)
89
+ out.publishTopFigures = patch.publishTopFigures ?? null;
90
+ if (patch.followsSurveyId !== undefined)
91
+ out.followsSurveyId = patch.followsSurveyId || null;
92
+ if (patch.carryTop !== undefined)
93
+ out.carryTop = whole(patch.carryTop) ?? null;
94
+ if (patch.successionDepth !== undefined)
95
+ out.successionDepth = whole(patch.successionDepth) ?? null;
96
+ if (patch.withdrawnKeys !== undefined)
97
+ out.withdrawnKeys = patch.withdrawnKeys ?? [];
98
+ if (patch.trusteeUserIds !== undefined)
99
+ out.trusteeUserIds = patch.trusteeUserIds ?? [];
100
+ if (patch.trusteeThreshold !== undefined)
101
+ out.trusteeThreshold = patch.trusteeThreshold ?? undefined;
102
+ if (patch.weighting !== undefined) {
103
+ const problem = (0, survey_rules_1.weightingProblem)(patch.weighting, (0, survey_attributes_1.surveyAttributes)().map(one => one.name));
104
+ if (problem)
105
+ throw refuse(problem);
106
+ out.weighting = patch.weighting ?? null;
107
+ }
108
+ return out;
109
+ }
110
+ /** A secret survey's smallest group is five - not a setting (charter decision 7). */
111
+ const withLevelRules = (survey) => (survey.level === 'SECRET' ? { ...survey, minGroup: survey_rules_1.SECRET_MIN_GROUP } : survey);
112
+ async function createSurvey(tx, domain, user, patch) {
113
+ const values = checkedPatch({ level: 'NAMED', ...patch });
114
+ if (!values.name)
115
+ throw (0, refusal_1.surveyRefusal)('survey-name-required');
116
+ return await tx.getRepository(survey_1.Survey).save(withLevelRules({ ...values, domain, status: 'DRAFT', creator: user, updater: user }));
117
+ }
118
+ async function updateSurvey(tx, domain, user, id, patch) {
119
+ const survey = await surveyOf(tx, domain, id);
120
+ mustStep(survey, 'edit');
121
+ await tx.getRepository(survey_1.Survey).save(withLevelRules({ ...survey, ...checkedPatch(patch), updater: user }));
122
+ return await surveyOf(tx, domain, id);
123
+ }
124
+ async function deleteSurvey(tx, domain, id) {
125
+ const survey = await surveyOf(tx, domain, id);
126
+ mustStep(survey, 'delete');
127
+ await tx.getRepository(survey_question_1.SurveyQuestion).delete({ survey: { id } });
128
+ await tx.getRepository(survey_1.Survey).delete(id);
129
+ return true;
130
+ }
131
+ /** Replaces a draft's questions with `questions`, in their order. */
132
+ async function setSurveyQuestions(tx, domain, user, id, questions) {
133
+ const survey = await surveyOf(tx, domain, id);
134
+ mustStep(survey, 'edit');
135
+ const rows = questions.map((one, index) => ({ ...one, seq: index + 1 }));
136
+ for (const one of rows) {
137
+ const problem = (0, survey_rules_1.questionProblem)(one);
138
+ if (problem)
139
+ throw refuse(problem);
140
+ }
141
+ await tx.getRepository(survey_question_1.SurveyQuestion).delete({ survey: { id } });
142
+ const repository = tx.getRepository(survey_question_1.SurveyQuestion);
143
+ for (const one of rows) {
144
+ await repository.save({
145
+ domain,
146
+ survey,
147
+ seq: one.seq,
148
+ kind: one.kind,
149
+ prompt: String(one.prompt).trim(),
150
+ options: one.kind === 'SCALE' ? null : (one.options ?? []).map(option => ({ key: String(option.key).trim(), label: String(option.label).trim() })),
151
+ maxPicks: one.kind === 'MULTI' ? one.maxPicks : null,
152
+ scaleMin: one.kind === 'SCALE' ? one.scaleMin : null,
153
+ scaleMax: one.kind === 'SCALE' ? one.scaleMax : null,
154
+ allocateTotal: one.kind === 'ALLOCATE' ? one.allocateTotal : null,
155
+ creator: user,
156
+ updater: user
157
+ });
158
+ }
159
+ return await (0, exports.questionsOf)(tx, id);
160
+ }
161
+ const questionsOf = (tx, surveyId) => tx.getRepository(survey_question_1.SurveyQuestion).find({ where: { survey: { id: surveyId } }, order: { seq: 'ASC' } });
162
+ exports.questionsOf = questionsOf;
163
+ /** The people a survey asks now: those its audience names who work here today, less those left out. */
164
+ async function askedUserIdsOf(tx, domain, survey, now = new Date()) {
165
+ const named = await (0, organization_1.audienceUserIds)(domain, survey.audience ?? [], tx);
166
+ const working = new Set(await (0, organization_1.workingEmployeeUserIds)(domain, tx, now));
167
+ const left = new Set(survey.excludedUserIds ?? []);
168
+ return named.filter(id => working.has(id) && !left.has(id));
169
+ }
170
+ /**
171
+ * Each person's weight class on the basis day (design §5) - refused when the weighting does not stand, someone fits no
172
+ * class, or a class with anyone in it holds fewer than the smallest group. An unweighted survey has no classes.
173
+ */
174
+ async function classesOf(tx, domain, survey, userIds, check = true) {
175
+ const weighting = survey.weighting;
176
+ if (!weighting?.classes?.length)
177
+ return { byUser: new Map(), sizes: {} };
178
+ const known = (0, survey_attributes_1.surveyAttributes)().map(one => one.name);
179
+ const problem = (0, survey_rules_1.weightingProblem)(weighting, known);
180
+ if (problem)
181
+ throw refuse(problem);
182
+ if (!survey.basisDate)
183
+ throw (0, refusal_1.surveyRefusal)('survey-basis-date-required');
184
+ if (check && !['WEIGHTED', 'UNWEIGHTED'].includes(String(survey.publishedFigure)))
185
+ throw (0, refusal_1.surveyRefusal)('survey-figure-required');
186
+ const names = [...new Set(weighting.classes.flatMap(one => (one.when ?? []).map(condition => condition.attribute)))];
187
+ const values = new Map(userIds.map(id => [id, {}]));
188
+ for (const name of names) {
189
+ const read = await (0, survey_attributes_1.surveyAttributeOf)(name).valuesOn(tx, domain, userIds, survey.basisDate);
190
+ for (const [id, value] of read)
191
+ if (values.has(id))
192
+ values.get(id)[name] = value;
193
+ }
194
+ const byUser = new Map();
195
+ const sizes = Object.fromEntries(weighting.classes.map(one => [one.key, 0]));
196
+ let unmatched = 0;
197
+ for (const id of userIds) {
198
+ const key = (0, survey_rules_1.classOf)(weighting, values.get(id));
199
+ if (!key)
200
+ unmatched++;
201
+ else {
202
+ byUser.set(id, key);
203
+ sizes[key]++;
204
+ }
205
+ }
206
+ if (check && unmatched)
207
+ throw (0, refusal_1.surveyRefusal)('survey-weight-unmatched', { count: unmatched });
208
+ const small = check ? (0, survey_rules_1.classSizeProblem)(sizes, survey.minGroup) : undefined;
209
+ if (small)
210
+ throw refuse(small);
211
+ return { byUser, sizes };
212
+ }
213
+ /** How many people each class would hold if the draft opened now - for the operator, before opening; sizes only. */
214
+ async function classPreviewOf(tx, domain, id, now = new Date()) {
215
+ const survey = await surveyOf(tx, domain, id);
216
+ const asked = await askedUserIdsOf(tx, domain, survey, now);
217
+ return (await classesOf(tx, domain, survey, asked, false)).sizes;
218
+ }
219
+ /** Opens a draft: the list of people asked is made once, now, and kept (design §3-1 step 2). */
220
+ async function openSurvey(tx, domain, user, id, now = new Date()) {
221
+ const survey = await surveyOf(tx, domain, id);
222
+ mustStep(survey, 'open');
223
+ if (survey.level === 'SECRET') {
224
+ /* A secret survey opens once its key holders have made its key (design §3-2). */
225
+ if (survey.status !== 'KEYING')
226
+ throw (0, refusal_1.surveyRefusal)('survey-keying-incomplete');
227
+ await (0, survey_secret_1.openSecret)(tx, domain, user, survey, now);
228
+ return await surveyOf(tx, domain, id);
229
+ }
230
+ if (survey.status !== 'DRAFT')
231
+ throw (0, refusal_1.surveyRefusal)('survey-step-not-now', { step: 'open', status: survey.status });
232
+ const questions = await (0, exports.questionsOf)(tx, id);
233
+ const asked = await askedUserIdsOf(tx, domain, survey, now);
234
+ const problem = (0, survey_rules_1.openingProblem)({ level: survey.level, questions, audienceCount: asked.length, closesAt: survey.closesAt, resultReaders: survey.resultReaders }, now);
235
+ if (problem)
236
+ throw refuse(problem);
237
+ if (survey.publishTop && (survey.publishTopFigures === null || survey.publishTopFigures === undefined))
238
+ throw (0, refusal_1.surveyRefusal)('survey-top-figures-required');
239
+ const classes = await classesOf(tx, domain, survey, asked);
240
+ const respondents = tx.getRepository(survey_respondent_1.SurveyRespondent);
241
+ for (const userId of asked)
242
+ await respondents.save({ domain, survey, user: { id: userId }, weightClass: classes.byUser.get(userId) ?? null, taken: false, creator: user });
243
+ await tx.getRepository(survey_1.Survey).update(id, { status: 'OPEN', openedAt: now, askedCount: asked.length, updater: user });
244
+ return await surveyOf(tx, domain, id);
245
+ }
246
+ /** One person's answers to a named survey - every question, once (design §3-1 step 3). */
247
+ async function answerSurvey(tx, domain, user, id, answers, now = new Date()) {
248
+ const survey = await surveyOf(tx, domain, id);
249
+ if (survey.level !== 'NAMED')
250
+ throw (0, refusal_1.surveyRefusal)('survey-not-named');
251
+ if (survey.status !== 'OPEN' || (0, survey_rules_1.closeDue)(survey, now))
252
+ throw (0, refusal_1.surveyRefusal)('survey-step-not-now', { step: 'answer', status: survey.status });
253
+ const respondent = await tx.getRepository(survey_respondent_1.SurveyRespondent).findOne({ where: { survey: { id }, user: { id: user.id } } });
254
+ if (!respondent)
255
+ throw (0, refusal_1.surveyRefusal)('survey-not-asked');
256
+ if (respondent.taken)
257
+ throw (0, refusal_1.surveyRefusal)('survey-answered');
258
+ const given = new Map(answers.map(one => [one.questionId, one.value]));
259
+ const questions = await (0, exports.questionsOf)(tx, id);
260
+ for (const one of questions) {
261
+ const problem = (0, survey_rules_1.answerProblem)(one, given.get(one.id));
262
+ if (problem)
263
+ throw refuse(problem);
264
+ }
265
+ /* One update that only a turn not yet taken passes - two answers sent at once do not both count. */
266
+ const taken = await tx.getRepository(survey_respondent_1.SurveyRespondent).update({ id: respondent.id, taken: false }, { taken: true });
267
+ if (!taken.affected)
268
+ throw (0, refusal_1.surveyRefusal)('survey-answered');
269
+ const rows = tx.getRepository(survey_answer_1.SurveyAnswer);
270
+ for (const one of questions)
271
+ await rows.save({ domain, survey, respondent, question: one, value: given.get(one.id), creator: user, updater: user });
272
+ return true;
273
+ }
274
+ async function closeSurvey(tx, domain, user, id, now = new Date()) {
275
+ const survey = await surveyOf(tx, domain, id);
276
+ mustStep(survey, 'close');
277
+ await tx.getRepository(survey_1.Survey).update(id, { status: 'CLOSED', closedAt: now, updater: user });
278
+ return await surveyOf(tx, domain, id);
279
+ }
280
+ /** The rate of a weight class - 1 when the survey is not weighted. */
281
+ function rateOf(weighting, weightClass) {
282
+ const found = (weighting?.classes ?? []).find((one) => one.key === weightClass);
283
+ return found ? Number(found.rate) : 1;
284
+ }
285
+ /** Counts a closed named survey; the count is the operators' until published (design §3-1 step 5). */
286
+ async function countSurvey(tx, domain, user, id) {
287
+ const survey = await surveyOf(tx, domain, id);
288
+ mustStep(survey, 'count');
289
+ if (survey.level === 'SECRET') {
290
+ /* The ballots multiply into sums; the key holders open the sums (design §3-2 steps 6 · 7). */
291
+ if (survey.status !== 'CLOSED')
292
+ throw (0, refusal_1.surveyRefusal)('survey-step-not-now', { step: 'count', status: survey.status });
293
+ await (0, survey_secret_1.beginSecretCount)(tx, domain, user, survey);
294
+ return await surveyOf(tx, domain, id);
295
+ }
296
+ const questions = await (0, exports.questionsOf)(tx, id);
297
+ const respondents = await tx.getRepository(survey_respondent_1.SurveyRespondent).find({ where: { survey: { id }, taken: true } });
298
+ const answers = respondents.length ? await tx.getRepository(survey_answer_1.SurveyAnswer).find({ where: { survey: { id }, respondent: { id: (0, typeorm_1.In)(respondents.map(one => one.id)) } } }) : [];
299
+ const byRespondent = new Map();
300
+ for (const one of answers)
301
+ byRespondent.set(one.respondentId, { ...(byRespondent.get(one.respondentId) ?? {}), [one.questionId]: one.value });
302
+ const result = (0, survey_rules_1.countOf)(questions, respondents.map(one => ({ rate: rateOf(survey.weighting, one.weightClass), answers: byRespondent.get(one.id) ?? {} })));
303
+ await tx.getRepository(survey_1.Survey).update(id, { status: 'COUNTED', result, updater: user });
304
+ return await surveyOf(tx, domain, id);
305
+ }
306
+ /** Publishes what may be published (design §4) - the readers chosen when it was made read it. */
307
+ async function publishSurvey(tx, domain, user, id, now = new Date()) {
308
+ const survey = await surveyOf(tx, domain, id);
309
+ mustStep(survey, 'publish');
310
+ const published = (0, survey_rules_1.publishable)(survey.result, { minGroup: survey.minGroup, figure: survey.publishedFigure, top: survey.publishTop, topFigures: survey.publishTopFigures });
311
+ if (published.problem)
312
+ throw refuse(published.problem);
313
+ await tx.getRepository(survey_1.Survey).update(id, { status: 'PUBLISHED', published, publishedAt: now, updater: user });
314
+ return await surveyOf(tx, domain, id);
315
+ }
316
+ async function cancelSurvey(tx, domain, user, id, reason) {
317
+ const survey = await surveyOf(tx, domain, id);
318
+ mustStep(survey, 'cancel');
319
+ await tx.getRepository(survey_1.Survey).update(id, { status: 'CANCELLED', cancelReason: reason ?? null, updater: user });
320
+ return await surveyOf(tx, domain, id);
321
+ }
322
+ /** Closes the open surveys whose time has come - each by one update while it is still open, so two servers close it once. */
323
+ async function closeDueSurveys(now = new Date()) {
324
+ const due = await (0, shell_1.getRepository)(survey_1.Survey).find({ where: { status: 'OPEN', closesAt: (0, typeorm_1.LessThanOrEqual)(now) }, take: 50 });
325
+ let closed = 0;
326
+ for (const one of due) {
327
+ try {
328
+ const taken = await (0, shell_1.getRepository)(survey_1.Survey).update({ id: one.id, status: 'OPEN' }, { status: 'CLOSED', closedAt: now });
329
+ if (taken.affected)
330
+ closed++;
331
+ }
332
+ catch (error) {
333
+ env_1.logger.error(`survey ${one.id}: closing failed`, error);
334
+ }
335
+ }
336
+ return closed;
337
+ }
338
+ let timer;
339
+ /** Checked every minute, as a proposal's vote is (ADR-0197 decision 5). */
340
+ function scheduleSurveyClosing() {
341
+ if (timer)
342
+ return;
343
+ timer = setInterval(() => {
344
+ void closeDueSurveys(new Date()).catch(error => env_1.logger.error('surveys', error));
345
+ }, 60 * 1000);
346
+ timer.unref?.();
347
+ }
348
+ /** The choices of the round before - their labels only, for marking who withdrew; never their ranks (design §7). */
349
+ async function previousChoicesOf(tx, domain, id) {
350
+ const survey = await surveyOf(tx, domain, id);
351
+ if (!survey.followsSurveyId)
352
+ return [];
353
+ const before = await surveyOf(tx, domain, survey.followsSurveyId);
354
+ const [first] = await (0, exports.questionsOf)(tx, before.id);
355
+ return (first?.options ?? []).map(one => ({ key: one.key, label: one.label }));
356
+ }
357
+ /**
358
+ * Takes this draft's choices from the round before (design §7): its first question's top `carryTop` among those not
359
+ * withdrawn, no further down than `successionDepth`. The round before must be counted. The draft's first question takes
360
+ * the round before's prompt unless it has one of its own; it is a pick-one.
361
+ */
362
+ async function carryForward(tx, domain, user, id) {
363
+ const survey = await surveyOf(tx, domain, id);
364
+ mustStep(survey, 'edit');
365
+ if (!survey.followsSurveyId || !survey.carryTop)
366
+ throw (0, refusal_1.surveyRefusal)('survey-carry-unset');
367
+ const before = await surveyOf(tx, domain, survey.followsSurveyId);
368
+ if (!['COUNTED', 'PUBLISHED'].includes(before.status) || !before.result)
369
+ throw (0, refusal_1.surveyRefusal)('survey-follows-not-counted');
370
+ const { keys, problem } = (0, survey_rules_1.carriedOf)(before.result, before.publishedFigure, survey.carryTop, survey.withdrawnKeys ?? [], survey.successionDepth);
371
+ if (problem)
372
+ throw refuse(problem);
373
+ const [previous] = await (0, exports.questionsOf)(tx, before.id);
374
+ const labels = new Map((previous?.options ?? []).map(one => [one.key, one.label]));
375
+ const mine = await (0, exports.questionsOf)(tx, id);
376
+ const first = {
377
+ kind: 'SINGLE',
378
+ prompt: mine[0]?.prompt ?? previous?.prompt ?? '',
379
+ options: keys.map(key => ({ key, label: labels.get(key) ?? key }))
380
+ };
381
+ const rest = mine.slice(1).map(one => ({ kind: one.kind, prompt: one.prompt, options: one.options, maxPicks: one.maxPicks, scaleMin: one.scaleMin, scaleMax: one.scaleMax, allocateTotal: one.allocateTotal }));
382
+ return await setSurveyQuestions(tx, domain, user, id, [first, ...rest]);
383
+ }
384
+ //# sourceMappingURL=survey-service.js.map
@@ -0,0 +1,25 @@
1
+ import { User } from '@things-factory/auth-base';
2
+ import { Domain } from '@things-factory/shell';
3
+ import { Survey } from './survey';
4
+ export declare class SurveyTrustee {
5
+ readonly id: string;
6
+ domain?: Domain;
7
+ domainId?: string;
8
+ survey?: Survey;
9
+ surveyId?: string;
10
+ user?: User;
11
+ userId?: string;
12
+ seq: number;
13
+ status: string;
14
+ transportKey?: string;
15
+ transportProof?: any;
16
+ dealing?: any;
17
+ sealedShares?: any;
18
+ partials?: any;
19
+ createdAt?: Date;
20
+ updatedAt?: Date;
21
+ creator?: User;
22
+ creatorId?: string;
23
+ updater?: User;
24
+ updaterId?: string;
25
+ }
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SurveyTrustee = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const typeorm_1 = require("typeorm");
6
+ const type_graphql_1 = require("type-graphql");
7
+ const auth_base_1 = require("@things-factory/auth-base");
8
+ const shell_1 = require("@things-factory/shell");
9
+ const survey_1 = require("./survey");
10
+ /*
11
+ * A key holder of a secret survey (operato-survey design §2-7 · §6-3). What is kept here is public: the transport key
12
+ * shares reach them by, their dealing's commitments, the shares they sealed for the others, and their partial
13
+ * decryptions with proofs. Their secrets stay in their own key file.
14
+ */
15
+ let SurveyTrustee = class SurveyTrustee {
16
+ };
17
+ exports.SurveyTrustee = SurveyTrustee;
18
+ tslib_1.__decorate([
19
+ (0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
20
+ (0, type_graphql_1.Field)(type => type_graphql_1.ID, { description: 'Unique identifier' }),
21
+ tslib_1.__metadata("design:type", String)
22
+ ], SurveyTrustee.prototype, "id", void 0);
23
+ tslib_1.__decorate([
24
+ (0, typeorm_1.ManyToOne)(type => shell_1.Domain),
25
+ (0, type_graphql_1.Field)(type => shell_1.Domain, { nullable: true, description: 'The domain' }),
26
+ tslib_1.__metadata("design:type", shell_1.Domain)
27
+ ], SurveyTrustee.prototype, "domain", void 0);
28
+ tslib_1.__decorate([
29
+ (0, typeorm_1.RelationId)((row) => row.domain),
30
+ tslib_1.__metadata("design:type", String)
31
+ ], SurveyTrustee.prototype, "domainId", void 0);
32
+ tslib_1.__decorate([
33
+ (0, typeorm_1.ManyToOne)(type => survey_1.Survey, { onDelete: 'CASCADE' }),
34
+ tslib_1.__metadata("design:type", survey_1.Survey)
35
+ ], SurveyTrustee.prototype, "survey", void 0);
36
+ tslib_1.__decorate([
37
+ (0, typeorm_1.RelationId)((row) => row.survey),
38
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The survey' }),
39
+ tslib_1.__metadata("design:type", String)
40
+ ], SurveyTrustee.prototype, "surveyId", void 0);
41
+ tslib_1.__decorate([
42
+ (0, typeorm_1.ManyToOne)(type => auth_base_1.User),
43
+ tslib_1.__metadata("design:type", auth_base_1.User)
44
+ ], SurveyTrustee.prototype, "user", void 0);
45
+ tslib_1.__decorate([
46
+ (0, typeorm_1.RelationId)((row) => row.user),
47
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The key holder' }),
48
+ tslib_1.__metadata("design:type", String)
49
+ ], SurveyTrustee.prototype, "userId", void 0);
50
+ tslib_1.__decorate([
51
+ (0, typeorm_1.Column)(),
52
+ (0, type_graphql_1.Field)(type => type_graphql_1.Int, { description: 'Their number among the key holders, from 1' }),
53
+ tslib_1.__metadata("design:type", Number)
54
+ ], SurveyTrustee.prototype, "seq", void 0);
55
+ tslib_1.__decorate([
56
+ (0, typeorm_1.Column)({ default: 'INVITED' }),
57
+ (0, type_graphql_1.Field)({ description: 'INVITED, KEYED, DEALT, CONFIRMED or DECRYPTED' }),
58
+ tslib_1.__metadata("design:type", String)
59
+ ], SurveyTrustee.prototype, "status", void 0);
60
+ tslib_1.__decorate([
61
+ (0, typeorm_1.Column)({ type: 'text', nullable: true }),
62
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The public key shares are sealed to - hex' }),
63
+ tslib_1.__metadata("design:type", String)
64
+ ], SurveyTrustee.prototype, "transportKey", void 0);
65
+ tslib_1.__decorate([
66
+ (0, typeorm_1.Column)('simple-json', { nullable: true }),
67
+ (0, type_graphql_1.Field)(type => shell_1.ScalarObject, { nullable: true, description: 'That they know the transport key’s secret' }),
68
+ tslib_1.__metadata("design:type", Object)
69
+ ], SurveyTrustee.prototype, "transportProof", void 0);
70
+ tslib_1.__decorate([
71
+ (0, typeorm_1.Column)('simple-json', { nullable: true }),
72
+ (0, type_graphql_1.Field)(type => shell_1.ScalarObject, { nullable: true, description: 'Their dealing - { commitments, proof }' }),
73
+ tslib_1.__metadata("design:type", Object)
74
+ ], SurveyTrustee.prototype, "dealing", void 0);
75
+ tslib_1.__decorate([
76
+ (0, typeorm_1.Column)('simple-json', { nullable: true }),
77
+ (0, type_graphql_1.Field)(type => shell_1.ScalarObject, { nullable: true, description: 'The shares they sealed, by the receiving key holder’s number' }),
78
+ tslib_1.__metadata("design:type", Object)
79
+ ], SurveyTrustee.prototype, "sealedShares", void 0);
80
+ tslib_1.__decorate([
81
+ (0, typeorm_1.Column)('simple-json', { nullable: true }),
82
+ (0, type_graphql_1.Field)(type => shell_1.ScalarObject, { nullable: true, description: 'Their partial decryptions of the sums, with proofs' }),
83
+ tslib_1.__metadata("design:type", Object)
84
+ ], SurveyTrustee.prototype, "partials", void 0);
85
+ tslib_1.__decorate([
86
+ (0, typeorm_1.CreateDateColumn)(),
87
+ (0, type_graphql_1.Field)({ nullable: true, description: 'When they were named' }),
88
+ tslib_1.__metadata("design:type", Date)
89
+ ], SurveyTrustee.prototype, "createdAt", void 0);
90
+ tslib_1.__decorate([
91
+ (0, typeorm_1.UpdateDateColumn)(),
92
+ (0, type_graphql_1.Field)({ nullable: true, description: 'When their part last changed' }),
93
+ tslib_1.__metadata("design:type", Date)
94
+ ], SurveyTrustee.prototype, "updatedAt", void 0);
95
+ tslib_1.__decorate([
96
+ (0, typeorm_1.ManyToOne)(type => auth_base_1.User, { nullable: true }),
97
+ (0, type_graphql_1.Field)(type => auth_base_1.User, { nullable: true, description: 'Who named them' }),
98
+ tslib_1.__metadata("design:type", auth_base_1.User)
99
+ ], SurveyTrustee.prototype, "creator", void 0);
100
+ tslib_1.__decorate([
101
+ (0, typeorm_1.RelationId)((row) => row.creator),
102
+ tslib_1.__metadata("design:type", String)
103
+ ], SurveyTrustee.prototype, "creatorId", void 0);
104
+ tslib_1.__decorate([
105
+ (0, typeorm_1.ManyToOne)(type => auth_base_1.User, { nullable: true }),
106
+ (0, type_graphql_1.Field)(type => auth_base_1.User, { nullable: true, description: 'Who changed it last' }),
107
+ tslib_1.__metadata("design:type", auth_base_1.User)
108
+ ], SurveyTrustee.prototype, "updater", void 0);
109
+ tslib_1.__decorate([
110
+ (0, typeorm_1.RelationId)((row) => row.updater),
111
+ tslib_1.__metadata("design:type", String)
112
+ ], SurveyTrustee.prototype, "updaterId", void 0);
113
+ exports.SurveyTrustee = SurveyTrustee = tslib_1.__decorate([
114
+ (0, typeorm_1.Entity)({ name: 'survey_trustees' }),
115
+ (0, typeorm_1.Index)('ix_survey_trustee_0', (row) => [row.survey, row.seq], { unique: true }),
116
+ (0, typeorm_1.Index)('ix_survey_trustee_1', (row) => [row.survey, row.user], { unique: true }),
117
+ (0, type_graphql_1.ObjectType)({ description: 'A key holder of a secret survey' })
118
+ ], SurveyTrustee);
119
+ //# sourceMappingURL=survey-trustee.js.map
@@ -0,0 +1,91 @@
1
+ import { Survey } from './survey';
2
+ import { SurveyQuestion } from './survey-question';
3
+ export declare class SurveyPatch {
4
+ name?: string;
5
+ description?: string;
6
+ level?: string;
7
+ audience?: {
8
+ scope: string;
9
+ targetId: string;
10
+ }[];
11
+ excludedUserIds?: string[];
12
+ basisDate?: string;
13
+ closesAt?: Date;
14
+ resultReaders?: string;
15
+ publishedFigure?: string;
16
+ minGroup?: number;
17
+ weighting?: any;
18
+ trusteeUserIds?: string[];
19
+ trusteeThreshold?: number;
20
+ publishTop?: number;
21
+ publishTopFigures?: boolean;
22
+ followsSurveyId?: string;
23
+ carryTop?: number;
24
+ successionDepth?: number;
25
+ withdrawnKeys?: string[];
26
+ }
27
+ export declare class SurveyQuestionInput {
28
+ kind: string;
29
+ prompt: string;
30
+ options?: {
31
+ key: string;
32
+ label: string;
33
+ }[];
34
+ maxPicks?: number;
35
+ scaleMin?: number;
36
+ scaleMax?: number;
37
+ allocateTotal?: number;
38
+ }
39
+ export declare class SurveyAnswerInput {
40
+ questionId: string;
41
+ value: any;
42
+ }
43
+ export declare class SurveyDetail {
44
+ survey: Survey;
45
+ questions: SurveyQuestion[];
46
+ askedCount: number;
47
+ takenCount: number;
48
+ result?: any;
49
+ published?: any;
50
+ }
51
+ export declare class SurveyAnswerSheet {
52
+ userId: string;
53
+ name?: string;
54
+ answers: any;
55
+ }
56
+ export declare class MySurvey {
57
+ survey: Survey;
58
+ taken: boolean;
59
+ questions: SurveyQuestion[];
60
+ published?: any;
61
+ }
62
+ export declare class SurveyChoice {
63
+ id: string;
64
+ name: string;
65
+ }
66
+ export declare class SurveyAudienceChoices {
67
+ domainId: string;
68
+ departments: SurveyChoice[];
69
+ roles: SurveyChoice[];
70
+ people: SurveyChoice[];
71
+ }
72
+ export declare class SurveyAttributeInfo {
73
+ name: string;
74
+ label: string;
75
+ type: string;
76
+ }
77
+ export declare class SurveyBallotKit {
78
+ surveyId: string;
79
+ publicKey: string;
80
+ weightClass: string;
81
+ modulus: string;
82
+ exponent: string;
83
+ taken: boolean;
84
+ }
85
+ export declare class MyTrusteeSurvey {
86
+ surveyId: string;
87
+ name: string;
88
+ status: string;
89
+ myStatus: string;
90
+ seq: number;
91
+ }