-
Notifications
You must be signed in to change notification settings - Fork 5
/
store.ts
1374 lines (1258 loc) · 34.1 KB
/
store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// The durable datastore for election data, CVRs, and adjudication info.
//
import { Admin } from '@votingworks/api';
import { assert, Result, err, ok, typedAs } from '@votingworks/basics';
import { Bindable, Client as DbClient } from '@votingworks/db';
import {
BallotId,
BallotStyleId,
CastVoteRecord,
ContestId,
ContestOptionId,
Id,
Iso8601Timestamp,
Optional,
PrecinctId,
safeParse,
safeParseElectionDefinition,
safeParseJson,
SystemSettings,
SystemSettingsDbRow,
} from '@votingworks/types';
import { ParseCastVoteRecordResult, parseCvrs } from '@votingworks/utils';
import * as fs from 'fs';
import { join } from 'path';
import * as readline from 'readline';
import { v4 as uuid } from 'uuid';
import { getWriteInsFromCastVoteRecord } from './util/cvrs';
import { sha256File } from './util/sha256_file';
/**
* Path to the store's schema file, i.e. the file that defines the database.
*/
const SchemaPath = join(__dirname, '../schema.sql');
function convertSqliteTimestampToIso8601(
sqliteTimestamp: string
): Iso8601Timestamp {
return new Date(sqliteTimestamp).toISOString();
}
/**
* Errors that can occur when adding a CVR file.
*/
export type AddCastVoteRecordError = {
userFriendlyMessage?: string;
} & (
| {
readonly kind: 'BallotIdRequired';
}
| {
readonly kind: 'BallotIdAlreadyExistsWithDifferentData';
readonly newData: string;
readonly existingData: string;
}
| {
readonly kind: 'InvalidCvr';
readonly lineNumber: number;
readonly errors: string[];
}
| {
readonly kind: 'InvalidCvrFileMode';
}
| {
readonly kind: 'InvalidElectionId';
}
| {
readonly kind: 'InvalidVote';
readonly lineNumber: number;
}
| {
readonly kind: 'MismatchedElectionDetails';
readonly lineNumber: number;
}
| {
readonly kind: 'MixedLiveAndTestBallots';
}
);
type AddCvrFileResult = Result<Admin.CvrFileImportInfo, AddCastVoteRecordError>;
/**
* Manages a data store for imported election data, cast vote records, and
* transcribed and adjudicated write-ins.
*/
export class Store {
private constructor(private readonly client: DbClient) {}
getDbPath(): string {
return this.client.getDatabasePath();
}
/**
* Builds and returns a new store whose data is kept in memory.
*/
static memoryStore(): Store {
return new Store(DbClient.memoryClient(SchemaPath));
}
/**
* Builds and returns a new store at `dbPath`.
*/
static fileStore(dbPath: string): Store {
return new Store(DbClient.fileClient(dbPath, SchemaPath));
}
/**
* Creates an election record and returns its ID.
*/
addElection(electionData: string): Id {
const id = uuid();
this.client.run(
'insert into elections (id, data) values (?, ?)',
id,
electionData
);
return id;
}
/**
* Gets all election records.
*/
getElections(): Admin.ElectionRecord[] {
return (
this.client.all(`
select
id,
data as electionData,
datetime(created_at, 'localtime') as createdAt,
is_official_results as isOfficialResults
from elections
where deleted_at is null
`) as Array<{
id: Id;
electionData: string;
createdAt: string;
isOfficialResults: 0 | 1;
}>
).map((r) => ({
id: r.id,
electionDefinition: safeParseElectionDefinition(
r.electionData
).unsafeUnwrap(),
createdAt: convertSqliteTimestampToIso8601(r.createdAt),
isOfficialResults: r.isOfficialResults === 1,
}));
}
/**
* Gets a specific election record.
*/
getElection(electionId: string): Admin.ElectionRecord | undefined {
const result = this.client.one(
`
select
id,
data as electionData,
datetime(created_at, 'localtime') as createdAt,
is_official_results as isOfficialResults
from elections
where deleted_at is null AND id = ?
`,
electionId
) as
| {
id: Id;
electionData: string;
createdAt: string;
isOfficialResults: 0 | 1;
}
| undefined;
if (!result) {
return undefined;
}
return {
id: result.id,
electionDefinition: safeParseElectionDefinition(
result.electionData
).unsafeUnwrap(),
createdAt: convertSqliteTimestampToIso8601(result.createdAt),
isOfficialResults: result.isOfficialResults === 1,
};
}
/**
* Deletes an election record.
*/
deleteElection(id: Id): void {
this.client.run(
'update elections set deleted_at = current_timestamp where id = ?',
id
);
}
/**
* Asserts that an election with the given ID exists and is not deleted.
*/
assertElectionExists(electionId: Id): void {
const election = this.client.one(
`
select id from elections
where id = ? and deleted_at is null
`,
electionId
) as { id: Id } | undefined;
if (!election) {
throw new Error(`Election not found: ${electionId}`);
}
}
/**
* Sets the id for the current election
*/
setCurrentElectionId(currentElectionId?: Id): void {
if (currentElectionId) {
this.client.run(
'update settings set current_election_id = ?',
currentElectionId
);
} else {
this.client.run('update settings set current_election_id = NULL');
}
}
/**
* Gets the id for the current election
*/
getCurrentElectionId(): Optional<Id> {
const settings = this.client.one(
`
select current_election_id as currentElectionId from settings
`
) as { currentElectionId: Id } | null;
return settings?.currentElectionId ?? undefined;
}
/**
* Creates a system settings record and returns its ID.
* Note `system_settings` are logical settings that span other machines eg. VxScan.
* `settings` are local to VxAdmin
*/
saveSystemSettings(systemSettings: SystemSettings): void {
this.client.run(
'insert into system_settings (are_poll_worker_card_pins_enabled) values (?)',
systemSettings.arePollWorkerCardPinsEnabled ? 1 : 0 // No booleans in sqlite3
);
}
/**
* Gets a specific system settings record.
*/
getSystemSettings(): SystemSettings | undefined {
const result = this.client.one(
`
select
are_poll_worker_card_pins_enabled as arePollWorkerCardPinsEnabled
from system_settings
`
) as SystemSettingsDbRow | undefined;
if (!result) {
return undefined;
}
return {
arePollWorkerCardPinsEnabled: result.arePollWorkerCardPinsEnabled === 1,
};
}
private convertCvrParseErrorsToApiError(
cvrParseResult: ParseCastVoteRecordResult
): AddCastVoteRecordError {
// Find errors for which we want surface specific messaging to
// the user:
// [TODO: there's room for simplification here - currently leveraging
// older validation code in `parseCvrs` as a first step.]
for (const errorMessage of cvrParseResult.errors) {
if (errorMessage.includes('not in the election definition')) {
return {
kind: 'MismatchedElectionDetails',
lineNumber: cvrParseResult.lineNumber,
userFriendlyMessage: errorMessage,
};
}
if (
errorMessage.includes('not a valid contest choice') ||
errorMessage.includes('not a valid candidate choice')
) {
return {
kind: 'InvalidVote',
lineNumber: cvrParseResult.lineNumber,
userFriendlyMessage: errorMessage,
};
}
}
// Generic fallback error for unhandled validation errors:
return {
kind: 'InvalidCvr',
lineNumber: cvrParseResult.lineNumber,
errors: cvrParseResult.errors,
userFriendlyMessage:
`the CVR at line ${cvrParseResult.lineNumber} is invalid for ` +
`this election`,
};
}
/**
* Adds a CVR file record and returns its ID. If a CVR file with the same
* contents has already been added, returns the ID of that record instead.
*
* Call with `analyzeOnly` set to `true` to only analyze the file and not add
* it to the database.
*/
async addCastVoteRecordFile({
electionId,
filePath,
originalFilename,
analyzeOnly,
exportedTimestamp,
}: {
electionId: Id;
filePath: string;
originalFilename: string;
analyzeOnly?: boolean;
exportedTimestamp: Iso8601Timestamp;
}): Promise<AddCvrFileResult> {
const election = this.getElection(electionId)?.electionDefinition.election;
if (!election) {
return err({ kind: 'InvalidElectionId' });
}
const sha256Hash = await sha256File(filePath);
const transactionFn = async (): Promise<AddCvrFileResult> => {
let id = uuid();
let newlyAdded = 0;
let alreadyPresent = 0;
const currentCvrFileMode =
this.getCurrentCvrFileModeForElection(electionId);
let newCvrFileMode: Admin.CvrFileMode;
const precinctIds = new Set<string>();
const scannerIds = new Set<string>();
const existing = this.client.one(
`
select id
from cvr_files
where election_id = ?
and sha256_hash = ?
`,
electionId,
sha256Hash
) as { id: Id } | undefined;
if (existing) {
alreadyPresent = (
this.client.one(
`
select count(cvr_id) as alreadyPresent
from cvr_file_entries
where cvr_file_id = ?
`,
existing.id
) as { alreadyPresent: number }
).alreadyPresent;
id = existing.id;
newCvrFileMode = currentCvrFileMode;
} else {
this.client.run(
`
insert into cvr_files (
id,
election_id,
filename,
export_timestamp,
precinct_ids,
scanner_ids,
sha256_hash
) values (
?, ?, ?, ?, ?, ?, ?
)
`,
id,
electionId,
originalFilename,
exportedTimestamp,
JSON.stringify([]),
JSON.stringify([]),
sha256Hash
);
const lines = readline.createInterface(fs.createReadStream(filePath));
let containsTestBallots = false;
let containsLiveBallots = false;
for await (const line of lines) {
if (line.trim() === '') {
continue;
}
const [cvrParseResult] = [...parseCvrs(line, election)];
assert(cvrParseResult);
if (cvrParseResult.errors.length > 0) {
return err(this.convertCvrParseErrorsToApiError(cvrParseResult));
}
const { cvr } = cvrParseResult;
if (!cvr._ballotId) {
return err({ kind: 'BallotIdRequired' });
}
containsTestBallots ||= cvr._testBallot;
containsLiveBallots ||= !cvr._testBallot;
if (containsTestBallots && containsLiveBallots) {
return err({
kind: 'MixedLiveAndTestBallots',
userFriendlyMessage:
'these CVRs cannot be tabulated together because ' +
'they mix live and test ballots',
});
}
const result = this.addCastVoteRecordFileEntry(
electionId,
id,
cvr._ballotId,
line
);
if (result.isErr()) {
return result;
}
precinctIds.add(cvr._precinctId);
scannerIds.add(cvr._scannerId);
this.addWriteInsFromCvr(result.ok().id, cvr);
if (result.ok().isNew) {
newlyAdded += 1;
} else {
alreadyPresent += 1;
}
}
this.client.run(
`
update cvr_files
set
precinct_ids = ?,
scanner_ids = ?
where id = ?
`,
JSON.stringify([...precinctIds]),
JSON.stringify([...scannerIds]),
id
);
newCvrFileMode = containsLiveBallots
? Admin.CvrFileMode.Official
: Admin.CvrFileMode.Test;
// Ensure CVR mode matches previous file imports, if any:
if (
currentCvrFileMode !== Admin.CvrFileMode.Unlocked &&
newCvrFileMode !== currentCvrFileMode
) {
return err({
kind: 'InvalidCvrFileMode',
userFriendlyMessage:
`this file contains ${newCvrFileMode} ballots, ` +
`but you are currently in ${currentCvrFileMode} mode`,
});
}
}
return ok({
id,
alreadyPresent,
exportedTimestamp,
fileMode: newCvrFileMode,
fileName: originalFilename,
newlyAdded,
scannerIds: [...scannerIds],
wasExistingFile: !!existing,
});
};
function shouldCommit(result: AddCvrFileResult): boolean {
if (analyzeOnly) {
return false;
}
return result.isOk();
}
return await this.client.transaction(transactionFn, shouldCommit);
}
getCastVoteRecordForWriteIn(
writeInId: Id
): Admin.CastVoteRecordData | undefined {
const result = this.client.one(
`
select
write_ins.id as writeInId,
write_ins.contest_id as contestId,
write_ins.option_id as optionId,
cvrs.election_id as electionId,
cvrs.data as cvrData
from write_ins
inner join
cvrs on cvrs.id = write_ins.cvr_id
where write_ins.id = ?
`,
writeInId
) as
| {
writeInId: Id;
contestId: ContestId;
optionId: ContestOptionId;
electionId: Id;
cvrData: string;
}
| undefined;
if (!result) {
return undefined;
}
return {
cvr: safeParseJson(result.cvrData).unsafeUnwrap() as CastVoteRecord,
writeInId: result.writeInId,
contestId: result.contestId,
optionId: result.optionId,
electionId: result.electionId,
};
}
/**
* Adds a CVR file entry record and returns its ID. If a CVR file entry with
* the same contents has already been added, returns the ID of that record and
* associates `cvrFileId` with it.
*/
private addCastVoteRecordFileEntry(
electionId: Id,
cvrFileId: Id,
ballotId: BallotId,
data: string
): Result<{ id: Id; isNew: boolean }, AddCastVoteRecordError> {
const existing = this.client.one(
`
select
id,
data
from cvrs
where
election_id = ? and
ballot_id = ?
`,
electionId,
ballotId
) as { id: Id; data: string } | undefined;
const id = existing?.id ?? uuid();
if (existing) {
if (existing.data !== data) {
return err({
kind: 'BallotIdAlreadyExistsWithDifferentData',
newData: data,
existingData: existing.data,
});
}
} else {
this.client.run(
`
insert into cvrs (
id,
election_id,
ballot_id,
data
) values (
?, ?, ?, ?
)
`,
id,
electionId,
ballotId,
data
);
}
this.client.run(
`
insert or ignore into cvr_file_entries (
cvr_file_id,
cvr_id
) values (
?, ?
)
`,
cvrFileId,
id
);
return ok({ id, isNew: !existing });
}
private addWriteInsFromCvr(cvrId: string, cvr: CastVoteRecord): void {
for (const [contestId, writeInIds] of getWriteInsFromCastVoteRecord(cvr)) {
for (const optionId of writeInIds) {
this.addWriteIn({
castVoteRecordId: cvrId,
contestId,
optionId,
});
}
}
}
/**
* Returns the current CVR file mode for the current election.
*/
getCurrentCvrFileModeForElection(electionId: Id): Admin.CvrFileMode {
const sampleCvr = this.client.one(
`
select
data
from cvrs
where
election_id = ?
`,
electionId
) as { data: string } | undefined;
if (!sampleCvr) {
return Admin.CvrFileMode.Unlocked;
}
const parsedCvr = safeParseJson(
sampleCvr.data
).unsafeUnwrap() as CastVoteRecord;
return parsedCvr._testBallot
? Admin.CvrFileMode.Test
: Admin.CvrFileMode.Official;
}
/**
* Adds a write-in and returns its ID.
*/
addWriteIn({
castVoteRecordId,
contestId,
optionId,
}: {
castVoteRecordId: Id;
contestId: Id;
optionId: Id;
}): Id {
const id = uuid();
this.client.run(
`
insert or ignore into write_ins (
id,
cvr_id,
contest_id,
option_id
) values (
?, ?, ?, ?
)
`,
id,
castVoteRecordId,
contestId,
optionId
);
return id;
}
getCvrFiles(electionId: Id): Admin.CastVoteRecordFileRecord[] {
const results = this.client.all(
`
select
cvr_files.id as id,
filename,
export_timestamp as exportTimestamp,
count(cvr_id) as numCvrsImported,
precinct_ids as precinctIds,
scanner_ids as scannerIds,
sha256_hash as sha256Hash,
datetime(cvr_files.created_at, 'localtime') as createdAt
from cvr_files
join (
select
cvr_file_entries.cvr_id,
min(cvr_files.created_at) as min_import_date,
cvr_file_entries.cvr_file_id
from cvr_file_entries, cvr_files
group by cvr_file_entries.cvr_id
) cvrs_by_min_import_date on
cvrs_by_min_import_date.cvr_file_id = cvr_files.id
where cvr_files.election_id = ?
group by cvr_files.id
order by export_timestamp desc
`,
electionId
) as Array<{
id: Id;
filename: string;
exportTimestamp: string;
numCvrsImported: number;
precinctIds: string;
scannerIds: string;
sha256Hash: string;
createdAt: string;
}>;
return results
.map((result) =>
safeParse(Admin.CastVoteRecordFileRecordSchema, {
id: result.id,
electionId,
sha256Hash: result.sha256Hash,
filename: result.filename,
exportTimestamp: convertSqliteTimestampToIso8601(
result.exportTimestamp
),
numCvrsImported: result.numCvrsImported,
precinctIds: safeParseJson(result.precinctIds).unsafeUnwrap(),
scannerIds: safeParseJson(result.scannerIds).unsafeUnwrap(),
createdAt: convertSqliteTimestampToIso8601(result.createdAt),
}).unsafeUnwrap()
)
.map<Admin.CastVoteRecordFileRecord>((parsedResult) => ({
...parsedResult,
precinctIds: [...parsedResult.precinctIds].sort(),
scannerIds: [...parsedResult.scannerIds].sort(),
}));
}
/**
* Gets all CVR entries for an election.
*/
getCastVoteRecordEntries(
electionId: Id
): Admin.CastVoteRecordFileEntryRecord[] {
const entries = this.client.all(
`
select
id,
ballot_id as ballotId,
data,
datetime(created_at, 'localtime') as createdAt
from cvrs
where election_id = ?
order by created_at asc
`,
electionId
) as Array<{
id: Id;
ballotId: string;
data: string;
createdAt: Iso8601Timestamp;
}>;
return entries.map((entry) => ({
id: entry.id,
ballotId: entry.ballotId,
electionId,
data: entry.data,
createdAt: convertSqliteTimestampToIso8601(entry.createdAt),
}));
}
/**
* Deletes all CVR files for an election.
*/
deleteCastVoteRecordFiles(electionId: Id): void {
this.client.transaction(() => {
this.client.run(
`
delete from cvr_file_entries
where cvr_file_id in (
select id from cvr_files where election_id = ?
)
`,
electionId
);
this.client.run(
`
delete from cvr_files
where election_id = ?
`,
electionId
);
this.client.run(
`
delete from cvrs
where not exists (
select 1 from cvr_file_entries where cvr_id = cvrs.id
)
`
);
this.client.run(
`
delete from write_in_adjudications
where election_id = ?
`,
electionId
);
});
}
/**
* Gets a summary of the write-in adjudication status.
*/
getWriteInAdjudicationSummary({
electionId,
contestId,
status,
}: {
electionId: Id;
contestId?: ContestId;
status?: Admin.WriteInAdjudicationStatus;
}): Admin.WriteInSummaryEntry[] {
const whereParts: string[] = ['cvrs.election_id = ?'];
const params: Bindable[] = [electionId];
if (contestId) {
whereParts.push('contest_id = ?');
params.push(contestId);
}
if (status === 'adjudicated') {
whereParts.push('writeInAdjudicationId is not null');
}
if (status === 'transcribed') {
whereParts.push('write_ins.transcribed_value is not null');
}
if (status === 'pending') {
whereParts.push(
'writeInAdjudicationId is null and write_ins.transcribed_value is null'
);
}
const rows = this.client.all(
`
select
write_ins.contest_id as contestId,
write_ins.transcribed_value as transcribedValue,
count(write_ins.id) as writeInCount,
(
select write_in_adjudications.id from write_in_adjudications
where write_in_adjudications.election_id = cvrs.election_id
and write_in_adjudications.contest_id = write_ins.contest_id
and write_in_adjudications.transcribed_value = write_ins.transcribed_value
limit 1
) as writeInAdjudicationId
from write_ins
inner join
cvrs on cvrs.id = write_ins.cvr_id
where ${whereParts.join(' and ')}
group by contest_id, transcribed_value
`,
...params
) as Array<{
contestId: ContestId;
transcribedValue: string | null;
writeInCount: number;
writeInAdjudicationId: Id | null;
}>;
const writeInAdjudications = this.getWriteInAdjudicationRecords({
electionId,
contestId,
});
return rows.map((row): Admin.WriteInSummaryEntry => {
const adjudication = writeInAdjudications.find(
(a) => a.id === row.writeInAdjudicationId
);
if (adjudication && row.transcribedValue) {
return {
status: 'adjudicated',
contestId: row.contestId,
writeInCount: row.writeInCount,
transcribedValue: row.transcribedValue,
writeInAdjudication: adjudication,
};
}
if (row.transcribedValue) {
return {
status: 'transcribed',
contestId: row.contestId,
writeInCount: row.writeInCount,
transcribedValue: row.transcribedValue,
};
}
return {
status: 'pending',
contestId: row.contestId,
writeInCount: row.writeInCount,
};
});
}
/**
* Gets all write-in records, filtered by the given options.
*/
getWriteInRecords({
electionId,
contestId,
status,
limit,
}: {
electionId: Id;
contestId?: ContestId;
status?: Admin.WriteInAdjudicationStatus;
limit?: number;
}): Admin.WriteInRecord[] {
this.assertElectionExists(electionId);
const whereParts: string[] = ['cvr_files.election_id = ?'];
const params: Bindable[] = [electionId];
if (contestId) {
whereParts.push('contest_id = ?');
params.push(contestId);
}
if (status === 'adjudicated' || status === 'transcribed') {
whereParts.push('write_ins.transcribed_value is not null');
} else if (status === 'pending') {
whereParts.push('write_ins.transcribed_value is null');
}
if (typeof limit === 'number') {
params.push(limit);
}
const writeInRows = this.client.all(
`
select distinct
write_ins.id as id,
write_ins.cvr_id as castVoteRecordId,
write_ins.contest_id as contestId,
write_ins.option_id as optionId,
write_ins.transcribed_value as transcribedValue,
datetime(write_ins.transcribed_at, 'localtime') as transcribedAt
from write_ins
inner join
cvr_file_entries on write_ins.cvr_id = cvr_file_entries.cvr_id
inner join
cvr_files on cvr_file_entries.cvr_file_id = cvr_files.id
where
${whereParts.join(' and ')}
${typeof limit === 'number' ? 'limit ?' : ''}
`,
...params
) as Array<{
id: Id;
castVoteRecordId: Id;
contestId: ContestId;
optionId: ContestOptionId;
transcribedValue: string | null;
transcribedAt: Iso8601Timestamp | null;
}>;
const adjudicationRows = this.getWriteInAdjudicationRecords({ electionId });
return writeInRows
.map((row) => {
if (!row.transcribedValue) {
return typedAs<Admin.WriteInRecordPendingTranscription>({
id: row.id,
status: 'pending',
castVoteRecordId: row.castVoteRecordId,
contestId: row.contestId,
optionId: row.optionId,
});
}
const adjudication = adjudicationRows.find(