@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,668 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import '@operato/input/ox-select.js';
3
+ import '@operato/popup/ox-popup-list.js';
4
+ import gql from 'graphql-tag';
5
+ import { css, html, nothing } from 'lit';
6
+ import { customElement, state } from 'lit/decorators.js';
7
+ import { client } from '@operato/graphql';
8
+ import { i18next, localize } from '@operato/i18n';
9
+ import { navigate, PageView } from '@operato/shell';
10
+ import { ButtonStyles, FormFieldStyles, ScrollbarStyles, WorkSurfacePageStyles } from '@operato/styles';
11
+ import { levelLabel, mutate, statusLabel } from '../utils/survey-api.js';
12
+ import { SurveyResultStyles, surveyResultView } from '../utils/survey-result.js';
13
+ import { checkBulletin } from '../utils/survey-secret.js';
14
+ /*
15
+ * **설문 편집** - a draft's title, level, whom it asks, when it closes, who reads its result, and its questions
16
+ * (operato-survey design §2 · §9). Past the draft the survey is read here: how many were asked and answered, its count,
17
+ * and - a named survey only - who answered what.
18
+ */
19
+ const KINDS = ['SINGLE', 'MULTI', 'SCALE', 'ALLOCATE'];
20
+ const LEVELS = ['NAMED', 'SECRET'];
21
+ const READERS = ['RESPONDENTS', 'OPERATORS'];
22
+ const FIGURES = ['WEIGHTED', 'UNWEIGHTED'];
23
+ const blankQuestion = () => ({ kind: 'SINGLE', prompt: '', options: [], maxPicks: 2, scaleMin: 1, scaleMax: 5, allocateTotal: 100 });
24
+ /** A datetime-local value in the reader's time. */
25
+ const localValue = (at) => {
26
+ if (!at)
27
+ return '';
28
+ const day = new Date(at);
29
+ return new Date(day.getTime() - day.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
30
+ };
31
+ /** Options from one label per line - each keeps the key it had at its place, a new one gets the next free key. */
32
+ function optionsFrom(text, before) {
33
+ const labels = text.split('\n').map(line => line.trim()).filter(Boolean);
34
+ const used = new Set();
35
+ const out = labels.map((label, index) => {
36
+ const key = before[index]?.key && !used.has(before[index].key) ? before[index].key : '';
37
+ if (key)
38
+ used.add(key);
39
+ return { key, label };
40
+ });
41
+ let next = 1;
42
+ for (const one of out) {
43
+ if (one.key)
44
+ continue;
45
+ while (used.has(`o${next}`))
46
+ next++;
47
+ one.key = `o${next}`;
48
+ used.add(one.key);
49
+ }
50
+ return out;
51
+ }
52
+ let SurveyEditorPage = class SurveyEditorPage extends localize(i18next)(PageView) {
53
+ constructor() {
54
+ super(...arguments);
55
+ this.survey = {};
56
+ this.questions = [];
57
+ this.sheets = [];
58
+ this.weightAttributes = [];
59
+ this.rounds = [];
60
+ this.previous = [];
61
+ }
62
+ static { this.styles = [
63
+ WorkSurfacePageStyles,
64
+ ScrollbarStyles,
65
+ ButtonStyles,
66
+ FormFieldStyles,
67
+ SurveyResultStyles,
68
+ css `
69
+ main {
70
+ overflow-y: auto;
71
+ padding: 16px;
72
+ display: flex;
73
+ flex-direction: column;
74
+ gap: 16px;
75
+ max-width: 880px;
76
+ }
77
+ .field {
78
+ display: flex;
79
+ flex-direction: column;
80
+ gap: 4px;
81
+ }
82
+ .row {
83
+ display: flex;
84
+ flex-wrap: wrap;
85
+ gap: 12px;
86
+ align-items: flex-end;
87
+ }
88
+ .chosen {
89
+ display: flex;
90
+ flex-wrap: wrap;
91
+ gap: 6px;
92
+ }
93
+ .picked {
94
+ display: inline-flex;
95
+ align-items: center;
96
+ gap: 4px;
97
+ padding: 2px 8px;
98
+ border-radius: 12px;
99
+ background: var(--md-sys-color-surface-container-high);
100
+ font-size: 13px;
101
+ }
102
+ .question {
103
+ border: 1px solid var(--md-sys-color-outline-variant);
104
+ border-radius: 8px;
105
+ padding: 12px;
106
+ display: flex;
107
+ flex-direction: column;
108
+ gap: 8px;
109
+ }
110
+ .note {
111
+ color: var(--md-sys-color-on-surface-variant);
112
+ font-size: 13px;
113
+ margin: 0;
114
+ }
115
+ table {
116
+ border-collapse: collapse;
117
+ font-size: 13px;
118
+ }
119
+ th,
120
+ td {
121
+ padding: 4px 8px;
122
+ border-bottom: 1px solid var(--md-sys-color-outline-variant);
123
+ text-align: left;
124
+ }
125
+ `
126
+ ]; }
127
+ get context() {
128
+ return { title: i18next.t('title.survey-editor') };
129
+ }
130
+ get editable() {
131
+ return !this.surveyId || this.survey.status === 'DRAFT';
132
+ }
133
+ render() {
134
+ return html `<main>${this.editable ? this.renderDraft() : this.renderPast()}</main>`;
135
+ }
136
+ renderDraft() {
137
+ const survey = this.survey;
138
+ return html `
139
+ <div class="field">
140
+ <label>${i18next.t('label.survey-name')}</label>
141
+ <input .value=${survey.name ?? ''} @input=${(e) => (this.survey = { ...this.survey, name: e.target.value })} />
142
+ </div>
143
+ <div class="field">
144
+ <label>${i18next.t('label.survey-description')}</label>
145
+ <textarea rows="3" .value=${survey.description ?? ''} @input=${(e) => (this.survey = { ...this.survey, description: e.target.value })}></textarea>
146
+ </div>
147
+ <div class="row">
148
+ <div class="field">
149
+ <label>${i18next.t('label.survey-level')}</label>
150
+ ${this.choice(LEVELS.map(one => ({ value: one, display: levelLabel(one) })), survey.level ?? 'NAMED', value => (this.survey = { ...this.survey, level: value }))}
151
+ </div>
152
+ <div class="field">
153
+ <label>${i18next.t('label.survey-closes-at')}</label>
154
+ <input type="datetime-local" .value=${localValue(survey.closesAt)} @change=${(e) => (this.survey = { ...this.survey, closesAt: e.target.value ? new Date(e.target.value).toISOString() : null })} />
155
+ </div>
156
+ <div class="field">
157
+ <label>${i18next.t('label.survey-result-readers')}</label>
158
+ ${this.choice(READERS.map(one => ({ value: one, display: i18next.t(`label.survey-readers-${one.toLowerCase()}`) })), survey.resultReaders ?? '', value => (this.survey = { ...this.survey, resultReaders: value }))}
159
+ </div>
160
+ ${(survey.level ?? 'NAMED') === 'NAMED'
161
+ ? html `<div class="field">
162
+ <label>${i18next.t('label.survey-min-group')}</label>
163
+ <input type="number" min="1" .value=${survey.minGroup ?? ''} @change=${(e) => (this.survey = { ...this.survey, minGroup: e.target.value ? Number(e.target.value) : null })} />
164
+ </div>`
165
+ : html `<p class="note">${i18next.t('text.survey-secret-min-group')}</p>`}
166
+ </div>
167
+
168
+ <section class="field">
169
+ <label>${i18next.t('label.survey-audience')}</label>
170
+ <div class="chosen">${(survey.audience ?? []).map((target, index) => this.chip(this.targetName(target), () => this.dropTarget(index)))}</div>
171
+ ${this.choice(this.targetChoices(), '', value => this.addTarget(value), i18next.t('text.survey-add-audience'))}
172
+ </section>
173
+ <section class="field">
174
+ <label>${i18next.t('label.survey-excluded')}</label>
175
+ <div class="chosen">${(survey.excludedUserIds ?? []).map((id) => this.chip(this.personName(id), () => this.dropExcluded(id)))}</div>
176
+ ${this.choice((this.choices?.people ?? []).map((one) => ({ value: one.id, display: one.name })), '', value => (this.survey = { ...this.survey, excludedUserIds: [...new Set([...(this.survey.excludedUserIds ?? []), value])] }), i18next.t('text.survey-add-excluded'))}
177
+ </section>
178
+
179
+ ${this.renderWeighting()} ${(survey.level ?? 'NAMED') === 'SECRET' ? this.renderTrustees() : nothing} ${this.renderRounds()}
180
+
181
+ <section class="field">
182
+ <label>${i18next.t('label.survey-questions')}</label>
183
+ ${this.questions.map((question, index) => this.renderQuestion(question, index))}
184
+ <div><button @click=${() => (this.questions = [...this.questions, blankQuestion()])}>${i18next.t('button.survey-add-question')}</button></div>
185
+ </section>
186
+
187
+ <div class="row">
188
+ <button raised @click=${() => this.save()}>${i18next.t('button.save')}</button>
189
+ <button @click=${() => navigate('survey-list')}>${i18next.t('button.survey-back')}</button>
190
+ </div>
191
+ `;
192
+ }
193
+ get classes() {
194
+ return this.survey.weighting?.classes ?? [];
195
+ }
196
+ setClasses(classes) {
197
+ this.survey = { ...this.survey, weighting: classes ? { classes } : null };
198
+ this.preview = undefined;
199
+ }
200
+ renderWeighting() {
201
+ const survey = this.survey;
202
+ const on = !!survey.weighting;
203
+ const attributeOptions = this.weightAttributes.map(one => ({ value: one.name, display: i18next.t(one.label) }));
204
+ return html `<section class="field">
205
+ <label>${i18next.t('label.survey-weighting')}</label>
206
+ ${this.choice([
207
+ { value: 'OFF', display: i18next.t('label.survey-weighting-off') },
208
+ { value: 'ON', display: i18next.t('label.survey-weighting-on') }
209
+ ], on ? 'ON' : 'OFF', value => this.setClasses(value === 'ON' ? [{ label: '', rate: 2, when: [] }, { label: '', rate: 1, when: [] }] : null))}
210
+ ${on
211
+ ? html `<p class="note">${i18next.t('text.survey-weighting-note')}</p>
212
+ <div class="row">
213
+ <label>${i18next.t('label.survey-basis-date')} <input type="date" .value=${survey.basisDate ?? ''} @change=${(e) => (this.survey = { ...this.survey, basisDate: e.target.value || null })} /></label>
214
+ <label
215
+ >${i18next.t('label.survey-published-figure')}
216
+ ${this.choice(FIGURES.map(one => ({ value: one, display: i18next.t(`label.survey-figure-${one.toLowerCase()}`) })), survey.publishedFigure ?? '', value => (this.survey = { ...this.survey, publishedFigure: value }))}</label
217
+ >
218
+ </div>
219
+ ${this.classes.map((one, index) => this.renderClass(one, index, attributeOptions))}
220
+ <div class="row">
221
+ <button @click=${() => this.setClasses([...this.classes.slice(0, -1), { label: '', rate: 1, when: [] }, this.classes[this.classes.length - 1]])}>${i18next.t('button.survey-add-class')}</button>
222
+ ${this.surveyId ? html `<button @click=${() => this.loadPreview()}>${i18next.t('button.survey-class-preview')}</button>` : nothing}
223
+ ${this.preview
224
+ ? html `<span class="note">${this.classes.map((one, index) => `${one.label || index + 1}: ${this.preview[one.key ?? `k${index + 1}`] ?? 0}`).join(' · ')}</span>`
225
+ : nothing}
226
+ </div>`
227
+ : nothing}
228
+ </section>`;
229
+ }
230
+ renderClass(one, index, attributeOptions) {
231
+ const last = index === this.classes.length - 1;
232
+ const set = (patch) => this.setClasses(this.classes.map((row, at) => (at === index ? { ...row, ...patch } : row)));
233
+ const setCondition = (at, patch) => set({ when: one.when.map((row, n) => (n === at ? { attribute: row.attribute, ...patch } : row)) });
234
+ return html `<div class="question">
235
+ <div class="row">
236
+ <input .value=${one.label} .placeholder=${i18next.t('label.survey-class-label')} @input=${(e) => set({ label: e.target.value })} />
237
+ <label>${i18next.t('label.survey-class-rate')} <input type="number" min="1" step="1" .value=${String(one.rate)} @change=${(e) => set({ rate: Number(e.target.value) })} /></label>
238
+ ${!last && this.classes.length > 2 ? html `<button small danger @click=${() => this.setClasses(this.classes.filter((_, at) => at !== index))}>${i18next.t('button.delete')}</button>` : nothing}
239
+ </div>
240
+ ${last
241
+ ? html `<p class="note">${i18next.t('text.survey-class-rest')}</p>`
242
+ : html `${one.when.map((condition, at) => {
243
+ const type = this.weightAttributes.find(row => row.name === condition.attribute)?.type;
244
+ const op = condition.equals !== undefined ? String(condition.equals) : condition.below !== undefined ? 'below' : 'atLeast';
245
+ const ops = type === 'boolean'
246
+ ? [
247
+ { value: 'true', display: i18next.t('label.survey-cond-true') },
248
+ { value: 'false', display: i18next.t('label.survey-cond-false') }
249
+ ]
250
+ : [
251
+ { value: 'atLeast', display: i18next.t('label.survey-cond-at-least') },
252
+ { value: 'below', display: i18next.t('label.survey-cond-below') }
253
+ ];
254
+ const amount = condition.atLeast ?? condition.below ?? 0;
255
+ return html `<div class="row">
256
+ ${this.choice(attributeOptions, condition.attribute, value => {
257
+ const kind = this.weightAttributes.find(row => row.name === value)?.type;
258
+ setCondition(at, kind === 'boolean' ? { attribute: value, equals: true } : { attribute: value, atLeast: 1 });
259
+ })}
260
+ ${this.choice(ops, op, value => setCondition(at, value === 'true' || value === 'false' ? { equals: value === 'true' } : value === 'below' ? { below: amount } : { atLeast: amount }))}
261
+ ${type === 'boolean'
262
+ ? nothing
263
+ : html `<input type="number" .value=${String(amount)} @change=${(e) => setCondition(at, op === 'below' ? { below: Number(e.target.value) } : { atLeast: Number(e.target.value) })} />`}
264
+ <button small @click=${() => set({ when: one.when.filter((_, n) => n !== at) })}>×</button>
265
+ </div>`;
266
+ })}
267
+ <div>
268
+ <button small @click=${() => set({ when: [...one.when, { attribute: this.weightAttributes[0]?.name ?? '', atLeast: 1 }] })}>${i18next.t('button.survey-add-condition')}</button>
269
+ </div>`}
270
+ </div>`;
271
+ }
272
+ renderRounds() {
273
+ const survey = this.survey;
274
+ const withdrawn = survey.withdrawnKeys ?? [];
275
+ return html `<section class="field">
276
+ <label>${i18next.t('label.survey-rounds')}</label>
277
+ <div class="row">
278
+ <label
279
+ >${i18next.t('label.survey-publish-top')}
280
+ <input type="number" min="1" .value=${String(survey.publishTop ?? '')} @change=${(e) => (this.survey = { ...this.survey, publishTop: e.target.value ? Number(e.target.value) : null })}
281
+ /></label>
282
+ ${survey.publishTop
283
+ ? this.choice([
284
+ { value: 'NAMES', display: i18next.t('label.survey-top-names') },
285
+ { value: 'FIGURES', display: i18next.t('label.survey-top-figures') }
286
+ ], survey.publishTopFigures === true ? 'FIGURES' : survey.publishTopFigures === false ? 'NAMES' : '', value => (this.survey = { ...this.survey, publishTopFigures: value === 'FIGURES' }), i18next.t('text.survey-top-choose'))
287
+ : nothing}
288
+ </div>
289
+ <div class="row">
290
+ <label
291
+ >${i18next.t('label.survey-follows')}
292
+ ${this.choice([{ value: '-', display: i18next.t('label.survey-follows-none') }, ...this.rounds.filter(one => one.id !== this.surveyId).map(one => ({ value: one.id, display: one.name }))], survey.followsSurveyId ?? '-', value => {
293
+ this.survey = { ...this.survey, followsSurveyId: value === '-' ? null : value, withdrawnKeys: [] };
294
+ this.previous = [];
295
+ })}</label
296
+ >
297
+ ${survey.followsSurveyId
298
+ ? html `<label
299
+ >${i18next.t('label.survey-carry-top')}
300
+ <input type="number" min="1" .value=${String(survey.carryTop ?? '')} @change=${(e) => (this.survey = { ...this.survey, carryTop: e.target.value ? Number(e.target.value) : null })}
301
+ /></label>
302
+ <label
303
+ >${i18next.t('label.survey-succession-depth')}
304
+ <input type="number" min="1" .value=${String(survey.successionDepth ?? '')} @change=${(e) => (this.survey = { ...this.survey, successionDepth: e.target.value ? Number(e.target.value) : null })}
305
+ /></label>`
306
+ : nothing}
307
+ </div>
308
+ ${survey.followsSurveyId && this.surveyId
309
+ ? html `<p class="note">${i18next.t('text.survey-withdrawn-note')}</p>
310
+ <div class="row">
311
+ ${this.previous.map(one => html `<label
312
+ ><input
313
+ type="checkbox"
314
+ .checked=${withdrawn.includes(one.id)}
315
+ @change=${(e) => (this.survey = { ...this.survey, withdrawnKeys: e.target.checked ? [...withdrawn, one.id] : withdrawn.filter(key => key !== one.id) })}
316
+ />
317
+ ${one.name}</label
318
+ >`)}
319
+ </div>
320
+ <div><button @click=${() => this.carry()}>${i18next.t('button.survey-carry-forward')}</button></div>`
321
+ : nothing}
322
+ </section>`;
323
+ }
324
+ renderTrustees() {
325
+ const survey = this.survey;
326
+ const ids = survey.trusteeUserIds ?? [];
327
+ return html `<section class="field">
328
+ <label>${i18next.t('label.survey-trustees')}</label>
329
+ <p class="note">${i18next.t('text.survey-trustees-note')}</p>
330
+ <div class="chosen">${ids.map(id => this.chip(this.personName(id), () => (this.survey = { ...this.survey, trusteeUserIds: ids.filter(one => one !== id) })))}</div>
331
+ ${this.choice((this.choices?.people ?? []).map((one) => ({ value: one.id, display: one.name })), '', value => (this.survey = { ...this.survey, trusteeUserIds: [...new Set([...ids, value])] }), i18next.t('text.survey-add-trustee'))}
332
+ <label
333
+ >${i18next.t('label.survey-trustee-threshold')}
334
+ <input type="number" min="1" .max=${String(Math.max(1, ids.length))} .value=${String(survey.trusteeThreshold ?? '')} @change=${(e) => (this.survey = { ...this.survey, trusteeThreshold: e.target.value ? Number(e.target.value) : null })}
335
+ /></label>
336
+ </section>`;
337
+ }
338
+ renderQuestion(question, index) {
339
+ const set = (patch) => (this.questions = this.questions.map((one, at) => (at === index ? { ...one, ...patch } : one)));
340
+ const move = (by) => {
341
+ const next = [...this.questions];
342
+ const [one] = next.splice(index, 1);
343
+ next.splice(Math.max(0, Math.min(next.length, index + by)), 0, one);
344
+ this.questions = next;
345
+ };
346
+ return html `<div class="question">
347
+ <div class="row">
348
+ <strong>${index + 1}.</strong>
349
+ ${this.choice(KINDS.map(one => ({ value: one, display: i18next.t(`label.survey-kind-${one.toLowerCase()}`) })), question.kind, value => set({ kind: value }))}
350
+ <button small @click=${() => move(-1)}>↑</button>
351
+ <button small @click=${() => move(1)}>↓</button>
352
+ <button small danger @click=${() => (this.questions = this.questions.filter((_, at) => at !== index))}>${i18next.t('button.delete')}</button>
353
+ </div>
354
+ <input .value=${question.prompt} .placeholder=${i18next.t('label.survey-prompt')} @input=${(e) => set({ prompt: e.target.value })} />
355
+ ${question.kind === 'SCALE'
356
+ ? html `<div class="row">
357
+ <label>${i18next.t('label.survey-scale-min')} <input type="number" .value=${String(question.scaleMin ?? 1)} @change=${(e) => set({ scaleMin: Number(e.target.value) })} /></label>
358
+ <label>${i18next.t('label.survey-scale-max')} <input type="number" .value=${String(question.scaleMax ?? 5)} @change=${(e) => set({ scaleMax: Number(e.target.value) })} /></label>
359
+ </div>`
360
+ : html `<textarea
361
+ rows="4"
362
+ .placeholder=${i18next.t('text.survey-options-one-per-line')}
363
+ .value=${question.options.map(one => one.label).join('\n')}
364
+ @change=${(e) => set({ options: optionsFrom(e.target.value, question.options) })}
365
+ ></textarea>
366
+ ${question.kind === 'MULTI'
367
+ ? html `<label>${i18next.t('label.survey-max-picks')} <input type="number" min="1" .value=${String(question.maxPicks ?? 2)} @change=${(e) => set({ maxPicks: Number(e.target.value) })} /></label>`
368
+ : nothing}
369
+ ${question.kind === 'ALLOCATE'
370
+ ? html `<label>${i18next.t('label.survey-allocate-total')} <input type="number" min="1" .value=${String(question.allocateTotal ?? 100)} @change=${(e) => set({ allocateTotal: Number(e.target.value) })} /></label>`
371
+ : nothing}`}
372
+ </div>`;
373
+ }
374
+ renderPast() {
375
+ const survey = this.survey;
376
+ const detail = this.detail;
377
+ return html `
378
+ <h2>${survey.name}</h2>
379
+ ${survey.description ? html `<p>${survey.description}</p>` : nothing}
380
+ <p class="note">
381
+ ${levelLabel(survey.level)} · ${statusLabel(survey.status)} · ${i18next.t('text.survey-taken-of-asked', { taken: detail?.takenCount ?? 0, asked: detail?.askedCount ?? 0 })}
382
+ ${survey.closesAt ? html ` · ${i18next.t('label.survey-closes-at')} ${new Date(survey.closesAt).toLocaleString()}` : nothing}
383
+ </p>
384
+ ${detail?.published
385
+ ? html `<h3>${i18next.t('label.survey-published')}</h3>
386
+ ${surveyResultView(detail.questions, detail.published)}`
387
+ : detail?.result
388
+ ? html `<h3>${i18next.t('label.survey-count')}</h3>
389
+ <p class="note">${i18next.t('text.survey-count-not-published')}</p>
390
+ ${surveyResultView(detail.questions, detail.result)}`
391
+ : nothing}
392
+ ${survey.level === 'SECRET' && this.bulletin
393
+ ? html `<h3>${i18next.t('label.survey-trustees')}</h3>
394
+ <p class="note">
395
+ ${this.bulletin.trustees.map((one) => `${one.seq}: ${i18next.t(`label.survey-trustee-${String(one.status).toLowerCase()}`)}`).join(' · ')} ·
396
+ ${i18next.t('text.survey-threshold-of', { threshold: this.bulletin.threshold, count: this.bulletin.trustees.length })}
397
+ </p>
398
+ ${this.bulletin.bulletinHash ? html `<p class="note">${i18next.t('text.survey-bulletin-hash', { hash: this.bulletin.bulletinHash.slice(0, 16) })}</p>` : nothing}
399
+ ${this.bulletin.result
400
+ ? html `<div>
401
+ <button @click=${() => this.checkCount()}>${i18next.t('button.survey-check-count')}</button>
402
+ ${this.check
403
+ ? html `<span class="note"
404
+ >${this.check.running
405
+ ? i18next.t('text.survey-checking', { done: this.check.done, of: this.check.of })
406
+ : this.check.ok
407
+ ? i18next.t('text.survey-check-ok', { count: this.check.checked })
408
+ : i18next.t('text.survey-check-failed', { problems: this.check.problems.join(', ') })}</span
409
+ >`
410
+ : nothing}
411
+ </div>`
412
+ : nothing}`
413
+ : nothing}
414
+ ${survey.level === 'NAMED' && this.sheets.length
415
+ ? html `<h3>${i18next.t('label.survey-answer-sheets')}</h3>
416
+ <table>
417
+ <thead>
418
+ <tr>
419
+ <th>${i18next.t('label.survey-respondent')}</th>
420
+ ${(detail?.questions ?? []).map((one) => html `<th>${one.seq}</th>`)}
421
+ </tr>
422
+ </thead>
423
+ <tbody>
424
+ ${this.sheets.map(sheet => html `<tr>
425
+ <td>${sheet.name ?? sheet.userId}</td>
426
+ ${(detail?.questions ?? []).map((one) => html `<td>${this.answerText(one, sheet.answers?.[one.id])}</td>`)}
427
+ </tr>`)}
428
+ </tbody>
429
+ </table>`
430
+ : nothing}
431
+ <div><button @click=${() => navigate('survey-list')}>${i18next.t('button.survey-back')}</button></div>
432
+ `;
433
+ }
434
+ answerText(question, value) {
435
+ if (!value)
436
+ return '';
437
+ const label = (key) => (question.options ?? []).find((one) => one.key === key)?.label ?? key;
438
+ if (value.pick)
439
+ return label(value.pick);
440
+ if (value.picks)
441
+ return value.picks.map(label).join(', ');
442
+ if (value.shares)
443
+ return Object.entries(value.shares).map(([key, share]) => `${label(key)} ${share}`).join(', ');
444
+ return String(value.value ?? '');
445
+ }
446
+ choice(options, value, change, placeholder = '') {
447
+ const shown = options.find(one => one.value === value)?.display ?? placeholder;
448
+ return html `<ox-select
449
+ .value=${value}
450
+ @change=${(e) => {
451
+ e.stopPropagation();
452
+ const next = String(e.detail ?? '');
453
+ if (next && next !== value)
454
+ change(next);
455
+ }}
456
+ >
457
+ <span slot="label">${shown}</span>
458
+ <ox-popup-list align-left nowrap with-search>${options.map(one => html `<div option value=${one.value}>${one.display}</div>`)}</ox-popup-list>
459
+ </ox-select>`;
460
+ }
461
+ chip(label, drop) {
462
+ return html `<span class="picked">${label}<button small @click=${drop} aria-label=${i18next.t('button.delete')}>×</button></span>`;
463
+ }
464
+ targetChoices() {
465
+ const choices = this.choices;
466
+ if (!choices)
467
+ return [];
468
+ return [
469
+ { value: `DOMAIN:${choices.domainId}`, display: i18next.t('label.survey-everyone') },
470
+ ...choices.departments.map((one) => ({ value: `DEPARTMENT:${one.id}`, display: `${i18next.t('label.survey-department')} · ${one.name}` })),
471
+ ...choices.roles.map((one) => ({ value: `ROLE:${one.id}`, display: `${i18next.t('label.survey-role')} · ${one.name}` })),
472
+ ...choices.people.map((one) => ({ value: `USER:${one.id}`, display: `${i18next.t('label.survey-person')} · ${one.name}` }))
473
+ ];
474
+ }
475
+ targetName(target) {
476
+ return this.targetChoices().find(one => one.value === `${target.scope}:${target.targetId}`)?.display ?? `${target.scope}:${target.targetId}`;
477
+ }
478
+ personName(id) {
479
+ return (this.choices?.people ?? []).find((one) => one.id === id)?.name ?? id;
480
+ }
481
+ addTarget(value) {
482
+ const [scope, targetId] = value.split(':');
483
+ const audience = (this.survey.audience ?? []).filter((one) => !(one.scope === scope && one.targetId === targetId));
484
+ this.survey = { ...this.survey, audience: [...audience, { scope, targetId }] };
485
+ }
486
+ dropTarget(index) {
487
+ this.survey = { ...this.survey, audience: (this.survey.audience ?? []).filter((_, at) => at !== index) };
488
+ }
489
+ dropExcluded(id) {
490
+ this.survey = { ...this.survey, excludedUserIds: (this.survey.excludedUserIds ?? []).filter((one) => one !== id) };
491
+ }
492
+ async pageUpdated(changes, lifecycle) {
493
+ if (!this.active || !(changes.active || changes.params))
494
+ return;
495
+ this.surveyId = lifecycle?.params?.id || undefined;
496
+ this.survey = { level: 'NAMED', audience: [], excludedUserIds: [] };
497
+ this.questions = [];
498
+ this.detail = undefined;
499
+ this.sheets = [];
500
+ await this.load();
501
+ }
502
+ async load() {
503
+ const choices = await client.query({
504
+ query: gql `query { surveyAudienceChoices { domainId departments { id name } roles { id name } people { id name } } surveyAttributes { name label type } }`,
505
+ fetchPolicy: 'network-only'
506
+ });
507
+ this.choices = choices.data?.surveyAudienceChoices;
508
+ const rounds = await client.query({ query: gql `query { surveys { id name status } }`, fetchPolicy: 'network-only' });
509
+ this.rounds = (rounds.data?.surveys ?? []).filter((one) => ['COUNTED', 'PUBLISHED'].includes(one.status));
510
+ this.weightAttributes = choices.data?.surveyAttributes ?? [];
511
+ if (!this.surveyId)
512
+ return;
513
+ const response = await client.query({
514
+ query: gql `
515
+ query ($id: String!) {
516
+ surveyDetail(id: $id) {
517
+ survey { id name description level status audience excludedUserIds closesAt resultReaders minGroup weighting basisDate publishedFigure trusteeUserIds trusteeThreshold publishTop publishTopFigures followsSurveyId carryTop successionDepth withdrawnKeys }
518
+ questions { id seq kind prompt options maxPicks scaleMin scaleMax allocateTotal }
519
+ askedCount takenCount result published
520
+ }
521
+ }
522
+ `,
523
+ variables: { id: this.surveyId },
524
+ fetchPolicy: 'network-only'
525
+ });
526
+ const detail = response.data?.surveyDetail;
527
+ if (!detail)
528
+ return;
529
+ this.detail = detail;
530
+ this.survey = { ...detail.survey };
531
+ this.questions = detail.questions.map((one) => ({ ...one, options: one.options ?? [] }));
532
+ this.bulletin = undefined;
533
+ this.check = undefined;
534
+ this.previous = [];
535
+ if (detail.survey.followsSurveyId && detail.survey.status === 'DRAFT') {
536
+ const previous = await client.query({ query: gql `query ($id: String!) { surveyPreviousChoices(id: $id) { id name } }`, variables: { id: this.surveyId }, fetchPolicy: 'network-only' });
537
+ this.previous = previous.data?.surveyPreviousChoices ?? [];
538
+ }
539
+ if (detail.survey.level === 'SECRET' && detail.survey.status !== 'DRAFT') {
540
+ const bulletin = await client.query({ query: gql `query ($id: String!) { surveyBulletin(id: $id) }`, variables: { id: this.surveyId }, fetchPolicy: 'network-only' });
541
+ this.bulletin = bulletin.data?.surveyBulletin;
542
+ }
543
+ if (detail.survey.level === 'NAMED' && detail.survey.status !== 'DRAFT') {
544
+ const sheets = await client.query({ query: gql `query ($id: String!) { surveyAnswerSheets(id: $id) { userId name answers } }`, variables: { id: this.surveyId }, fetchPolicy: 'network-only' });
545
+ this.sheets = sheets.data?.surveyAnswerSheets ?? [];
546
+ }
547
+ }
548
+ async save() {
549
+ const { name, description, level, audience, excludedUserIds, closesAt, resultReaders, minGroup, basisDate, publishedFigure, trusteeUserIds, trusteeThreshold } = this.survey;
550
+ const weighting = this.survey.weighting ? { classes: this.classes.map((one, index) => ({ ...one, key: one.key ?? `k${index + 1}`, when: index === this.classes.length - 1 ? [] : one.when })) } : null;
551
+ const patch = {
552
+ name,
553
+ description,
554
+ level,
555
+ audience,
556
+ excludedUserIds,
557
+ closesAt,
558
+ resultReaders,
559
+ minGroup: minGroup ?? null,
560
+ weighting,
561
+ basisDate: basisDate ?? null,
562
+ publishedFigure: publishedFigure ?? null,
563
+ trusteeUserIds: trusteeUserIds ?? [],
564
+ trusteeThreshold: trusteeThreshold ?? null,
565
+ publishTop: this.survey.publishTop ?? null,
566
+ publishTopFigures: this.survey.publishTop ? (this.survey.publishTopFigures ?? null) : null,
567
+ followsSurveyId: this.survey.followsSurveyId ?? null,
568
+ carryTop: this.survey.carryTop ?? null,
569
+ successionDepth: this.survey.successionDepth ?? null,
570
+ withdrawnKeys: this.survey.withdrawnKeys ?? []
571
+ };
572
+ let id = this.surveyId;
573
+ if (!id) {
574
+ const made = await mutate(gql `mutation ($patch: SurveyPatch!) { createSurvey(patch: $patch) { id } }`, { patch });
575
+ if (!made)
576
+ return;
577
+ id = made.createSurvey.id;
578
+ }
579
+ else if (!(await mutate(gql `mutation ($id: String!, $patch: SurveyPatch!) { updateSurvey(id: $id, patch: $patch) { id } }`, { id, patch })))
580
+ return;
581
+ const questions = this.questions.map(one => ({
582
+ kind: one.kind,
583
+ prompt: one.prompt,
584
+ options: one.kind === 'SCALE' ? null : one.options,
585
+ maxPicks: one.kind === 'MULTI' ? one.maxPicks : null,
586
+ scaleMin: one.kind === 'SCALE' ? one.scaleMin : null,
587
+ scaleMax: one.kind === 'SCALE' ? one.scaleMax : null,
588
+ allocateTotal: one.kind === 'ALLOCATE' ? one.allocateTotal : null
589
+ }));
590
+ await mutate(gql `mutation ($id: String!, $questions: [SurveyQuestionInput!]!) { setSurveyQuestions(id: $id, questions: $questions) { id } }`, { id, questions });
591
+ if (id !== this.surveyId)
592
+ navigate(`survey-editor?id=${id}`);
593
+ else
594
+ await this.load();
595
+ }
596
+ async loadPreview() {
597
+ const response = await client.query({ query: gql `query ($id: String!) { surveyClassPreview(id: $id) }`, variables: { id: this.surveyId }, fetchPolicy: 'network-only' });
598
+ if (response.errors?.length)
599
+ return;
600
+ this.preview = response.data?.surveyClassPreview ?? {};
601
+ }
602
+ async checkCount() {
603
+ if (!this.bulletin)
604
+ return;
605
+ this.check = { running: true, done: 0, of: this.bulletin.ballots.length };
606
+ const result = await checkBulletin(this.bulletin, (done, of) => (this.check = { running: true, done, of }));
607
+ this.check = result;
608
+ }
609
+ /* Saves first, so the withdrawals marked are the ones the carry reads. */
610
+ async carry() {
611
+ await this.save();
612
+ if (await mutate(gql `mutation ($id: String!) { carrySurveyForward(id: $id) { id } }`, { id: this.surveyId }))
613
+ await this.load();
614
+ }
615
+ };
616
+ __decorate([
617
+ state(),
618
+ __metadata("design:type", String)
619
+ ], SurveyEditorPage.prototype, "surveyId", void 0);
620
+ __decorate([
621
+ state(),
622
+ __metadata("design:type", Object)
623
+ ], SurveyEditorPage.prototype, "survey", void 0);
624
+ __decorate([
625
+ state(),
626
+ __metadata("design:type", Array)
627
+ ], SurveyEditorPage.prototype, "questions", void 0);
628
+ __decorate([
629
+ state(),
630
+ __metadata("design:type", Object)
631
+ ], SurveyEditorPage.prototype, "detail", void 0);
632
+ __decorate([
633
+ state(),
634
+ __metadata("design:type", Array)
635
+ ], SurveyEditorPage.prototype, "sheets", void 0);
636
+ __decorate([
637
+ state(),
638
+ __metadata("design:type", Object)
639
+ ], SurveyEditorPage.prototype, "choices", void 0);
640
+ __decorate([
641
+ state(),
642
+ __metadata("design:type", Array)
643
+ ], SurveyEditorPage.prototype, "weightAttributes", void 0);
644
+ __decorate([
645
+ state(),
646
+ __metadata("design:type", Object)
647
+ ], SurveyEditorPage.prototype, "preview", void 0);
648
+ __decorate([
649
+ state(),
650
+ __metadata("design:type", Object)
651
+ ], SurveyEditorPage.prototype, "bulletin", void 0);
652
+ __decorate([
653
+ state(),
654
+ __metadata("design:type", Object)
655
+ ], SurveyEditorPage.prototype, "check", void 0);
656
+ __decorate([
657
+ state(),
658
+ __metadata("design:type", Array)
659
+ ], SurveyEditorPage.prototype, "rounds", void 0);
660
+ __decorate([
661
+ state(),
662
+ __metadata("design:type", Array)
663
+ ], SurveyEditorPage.prototype, "previous", void 0);
664
+ SurveyEditorPage = __decorate([
665
+ customElement('survey-editor')
666
+ ], SurveyEditorPage);
667
+ export { SurveyEditorPage };
668
+ //# sourceMappingURL=survey-editor.js.map