-
Notifications
You must be signed in to change notification settings - Fork 7
/
store.ts
969 lines (858 loc) · 26 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
//
// The durable datastore for CVRs and configuration info.
//
import { Client as DbClient } from '@votingworks/db';
import {
AdjudicationStatus,
BallotPaperSize,
BallotSheetInfo,
BatchInfo,
ElectionDefinition,
Iso8601Timestamp,
mapSheet,
MarkThresholds,
PageInterpretationSchema,
PageInterpretationWithFiles,
PollsState as PollsStateType,
PollsStateSchema,
PrecinctSelection as PrecinctSelectionType,
PrecinctSelectionSchema,
safeParse,
safeParseElectionDefinition,
safeParseJson,
SheetOf,
SystemSettings,
safeParseSystemSettings,
AdjudicationReason,
} from '@votingworks/types';
import { assertDefined, Optional } from '@votingworks/basics';
import * as fs from 'fs-extra';
import { sha256 } from 'js-sha256';
import { DateTime } from 'luxon';
import { join } from 'path';
import { v4 as uuid } from 'uuid';
import { ResultSheet } from '@votingworks/backend';
import {
clearCastVoteRecordHashes,
getCastVoteRecordRootHash,
updateCastVoteRecordHashes,
} from '@votingworks/auth';
import {
BooleanEnvironmentVariableName,
isFeatureFlagEnabled,
} from '@votingworks/utils';
import { sheetRequiresAdjudication } from './sheet_requires_adjudication';
import { rootDebug } from './util/debug';
const debug = rootDebug.extend('store');
const SchemaPath = join(__dirname, '../schema.sql');
function dateTimeFromNoOffsetSqliteDate(noOffsetSqliteDate: string): DateTime {
return DateTime.fromFormat(noOffsetSqliteDate, 'yyyy-MM-dd HH:mm:ss', {
zone: 'GMT',
});
}
const getResultSheetsBaseQuery = `
select
sheets.id as id,
batches.id as batchId,
batches.label as batchLabel,
front_interpretation_json as frontInterpretationJson,
back_interpretation_json as backInterpretationJson,
front_image_path as frontImagePath,
back_image_path as backImagePath
from sheets left join batches on
sheets.batch_id = batches.id
where
(requires_adjudication = 0 or finished_adjudication_at is not null)
and sheets.deleted_at is null
and batches.deleted_at is null
`;
interface ResultSheetRow {
id: string;
batchId: string;
batchLabel: string | null;
frontInterpretationJson: string;
backInterpretationJson: string;
frontImagePath: string;
backImagePath: string;
}
function resultSheetRowToResultSheet(row: ResultSheetRow): ResultSheet {
return {
id: row.id,
batchId: row.batchId,
batchLabel: row.batchLabel ?? undefined,
interpretation: mapSheet(
[row.frontInterpretationJson, row.backInterpretationJson],
(json) => safeParseJson(json, PageInterpretationSchema).unsafeUnwrap()
),
frontImagePath: row.frontImagePath,
backImagePath: row.backImagePath,
};
}
/**
* Manages a data store for imported ballot image batches and cast vote records
* interpreted by reading the sheets.
*/
export class Store {
private constructor(private readonly client: DbClient) {}
getDbPath(): string {
return this.client.getDatabasePath();
}
/**
* Gets the sha256 digest of the current schema file.
*/
static getSchemaDigest(): string {
const schemaSql = fs.readFileSync(SchemaPath, 'utf-8');
return sha256(schemaSql);
}
/**
* 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));
}
// TODO(jonah): Make this the only way to access the store so that we always
// use a transaction.
/**
* Runs the given function in a transaction. If the function throws an error,
* the transaction is rolled back. Otherwise, the transaction is committed.
*
* Returns the result of the function.
*/
withTransaction<T>(fn: () => Promise<T>): Promise<T>;
withTransaction<T>(fn: () => T): T;
withTransaction<T>(fn: () => T): T {
return this.client.transaction(() => fn());
}
/**
* Writes a copy of the database to the given path.
*/
backup(filepath: string): void {
this.client.run('vacuum into ?', filepath);
}
/**
* Resets the database and any cached data in the store.
*/
reset(): void {
this.client.reset();
}
/**
* Gets whether an election is currently configured.
*/
hasElection(): boolean {
return Boolean(this.client.one('select id from election'));
}
/**
* Gets the current election definition.
*/
getElectionDefinition(): ElectionDefinition | undefined {
const electionRow = this.client.one(
'select election_data as electionData from election'
) as { electionData: string } | undefined;
if (!electionRow?.electionData) {
return undefined;
}
return safeParseElectionDefinition(electionRow.electionData).unsafeUnwrap();
}
/**
* Gets the current jurisdiction.
*/
getJurisdiction(): string | undefined {
const electionRow = this.client.one('select jurisdiction from election') as
| { jurisdiction: string }
| undefined;
return electionRow?.jurisdiction;
}
/**
* Sets the current election definition and jurisdiction.
*/
setElectionAndJurisdiction(input?: {
electionData: string;
jurisdiction: string;
}): void {
this.client.run('delete from election');
if (input) {
this.client.run(
'insert into election (election_data, jurisdiction) values (?, ?)',
input.electionData,
input.jurisdiction
);
}
}
/**
* Gets the current test mode setting value.
*/
getTestMode(): boolean {
const electionRow = this.client.one(
'select is_test_mode as isTestMode from election'
) as { isTestMode: number } | undefined;
if (!electionRow) {
// test mode will be the default once an election is defined
return true;
}
return Boolean(electionRow.isTestMode);
}
/**
* Sets the current test mode setting value.
*/
setTestMode(isTestMode: boolean): void {
if (!this.hasElection()) {
throw new Error('Cannot set test mode without an election.');
}
this.client.run('update election set is_test_mode = ?', isTestMode ? 1 : 0);
}
/**
* Gets whether sound is muted.
*/
getIsSoundMuted(): boolean {
const electionRow = this.client.one(
'select is_sound_muted as isSoundMuted from election'
) as { isSoundMuted: number } | undefined;
if (!electionRow) {
// we will not mute sounds by default once an election is defined
return false;
}
return Boolean(electionRow.isSoundMuted);
}
/**
* Gets whether ultrasonic is disabled.
*/
getIsUltrasonicDisabled(): boolean {
const electionRow = this.client.one(
'select is_ultrasonic_disabled as isUltrasonicDisabled from election'
) as { isUltrasonicDisabled: number } | undefined;
if (!electionRow) {
// we will not disable ultrasonic by default once an election is defined
return false;
}
return Boolean(electionRow.isUltrasonicDisabled);
}
/**
* Sets whether or not to mute sounds.
*/
setIsSoundMuted(isSoundMuted: boolean): void {
if (!this.hasElection()) {
throw new Error('Cannot set sounds to muted without an election.');
}
this.client.run(
'update election set is_sound_muted = ?',
isSoundMuted ? 1 : 0
);
}
/**
* Sets whether or not to enable ultrasonic, if supported.
*/
setIsUltrasonicDisabled(isUltrasonicDisabled: boolean): void {
if (!this.hasElection()) {
throw new Error('Cannot toggle ultrasonic without an election.');
}
this.client.run(
'update election set is_ultrasonic_disabled = ?',
isUltrasonicDisabled ? 1 : 0
);
}
/**
* Gets the number of ballots at which the ballot bag was last replaced.
*/
getBallotCountWhenBallotBagLastReplaced(): number {
const electionRow = this.client.one(
'select ballot_count_when_ballot_bag_last_replaced as ballotCountWhenBallotBagLastReplaced from election'
) as { ballotCountWhenBallotBagLastReplaced: number } | undefined;
if (!electionRow) {
// the default will be 0 once the election is defined
return 0;
}
return electionRow.ballotCountWhenBallotBagLastReplaced;
}
/**
* Sets whether to check the election hash.
*/
setBallotCountWhenBallotBagLastReplaced(
ballotCountWhenBallotBagLastReplaced: number
): void {
if (!this.hasElection()) {
throw new Error(
'Cannot set ballot count when ballot bag last replaced without an election.'
);
}
this.client.run(
'update election set ballot_count_when_ballot_bag_last_replaced = ?',
ballotCountWhenBallotBagLastReplaced
);
}
getBallotPaperSizeForElection(): BallotPaperSize {
const electionDefinition = this.getElectionDefinition();
return (
electionDefinition?.election.ballotLayout.paperSize ??
BallotPaperSize.Letter
);
}
getMarkThresholds(): MarkThresholds {
return assertDefined(this.getSystemSettings()).markThresholds;
}
getAdjudicationReasons(): readonly AdjudicationReason[] {
return assertDefined(this.getSystemSettings())
.precinctScanAdjudicationReasons;
}
/**
* Gets the current precinct `scan` is accepting ballots for. If set to
* `undefined`, ballots from all precincts will be accepted (this is the
* default).
*/
getPrecinctSelection(): Optional<PrecinctSelectionType> {
const electionRow = this.client.one(
'select precinct_selection as rawPrecinctSelection from election'
) as { rawPrecinctSelection: string } | undefined;
const rawPrecinctSelection = electionRow?.rawPrecinctSelection;
if (!rawPrecinctSelection) {
// precinct selection is undefined when there is no election
return undefined;
}
const precinctSelectionParseResult = safeParseJson(
rawPrecinctSelection,
PrecinctSelectionSchema
);
if (precinctSelectionParseResult.isErr()) {
throw new Error('Unable to parse stored precinct selection.');
}
return precinctSelectionParseResult.ok();
}
/**
* Sets the current precinct `scan` is accepting ballots for. Set to
* `undefined` to accept from all precincts (this is the default).
*/
setPrecinctSelection(precinctSelection?: PrecinctSelectionType): void {
if (!this.hasElection()) {
throw new Error('Cannot set precinct selection without an election.');
}
this.client.run(
'update election set precinct_selection = ?',
precinctSelection ? JSON.stringify(precinctSelection) : null
);
}
/**
* Gets the current polls state (open, paused, closed initial, or closed final)
*/
getPollsState(): PollsStateType {
const electionRow = this.client.one(
'select polls_state as rawPollsState from election'
) as { rawPollsState: string } | undefined;
if (!electionRow) {
// we will not skip the check by default once an election is defined
return 'polls_closed_initial';
}
const pollsStateParseResult = safeParse(
PollsStateSchema,
electionRow.rawPollsState
);
if (pollsStateParseResult.isErr()) {
throw new Error('Unable to parse stored polls state.');
}
return pollsStateParseResult.ok();
}
/**
* Sets the current polls state
*/
setPollsState(pollsState: PollsStateType): void {
if (!this.hasElection()) {
throw new Error('Cannot set polls state without an election.');
}
this.client.run('update election set polls_state = ?', pollsState);
}
/**
* Adds a batch and returns its id.
*/
addBatch(): string {
const id = uuid();
this.client.run('insert into batches (id) values (?)', id);
this.client.run(
`update batches set label = 'Batch ' || batch_number WHERE id = ?`,
id
);
return id;
}
/**
* Marks the batch with id `batchId` as finished.
*/
finishBatch({ batchId, error }: { batchId: string; error?: string }): void {
this.client.run(
'update batches set ended_at = current_timestamp, error = ? where id = ?',
error ?? null,
batchId
);
}
/**
* Returns the id of the an unfinished batch if there is one
*/
getOngoingBatchId(): Optional<string> {
const ongoingBatchRow = this.client.one(
'select id from batches where ended_at is null'
) as { id: string } | undefined;
return ongoingBatchRow?.id;
}
/**
* Records that batches have been backed up.
*/
setScannerBackedUp(backedUp = true): void {
if (!this.hasElection()) {
throw new Error('Unconfigured scanner cannot be backed up.');
}
if (backedUp) {
this.client.run(
'update election set scanner_backed_up_at = current_timestamp'
);
} else {
this.client.run('update election set scanner_backed_up_at = null');
}
}
/**
* Records that CVRs have been backed up.
*/
setCvrsBackedUp(backedUp = true): void {
if (!this.hasElection()) {
throw new Error('Unconfigured scanner cannot export CVRs.');
}
if (backedUp) {
this.client.run(
'update election set cvrs_backed_up_at = current_timestamp'
);
} else {
this.client.run('update election set cvrs_backed_up_at = null');
}
}
/**
* Gets the timestamp for the last scanner backup
*/
getScannerBackupTimestamp(): DateTime | undefined {
const row = this.client.one(
'select scanner_backed_up_at as scannerBackedUpAt from election'
) as { scannerBackedUpAt: string } | undefined;
if (!row?.scannerBackedUpAt) {
return undefined;
}
return dateTimeFromNoOffsetSqliteDate(row?.scannerBackedUpAt);
}
/**
* Gets the timestamp for the last cvr export
*/
getCvrsBackupTimestamp(): DateTime | undefined {
const row = this.client.one(
'select cvrs_backed_up_at as cvrsBackedUpAt from election'
) as { cvrsBackedUpAt: string } | undefined;
if (!row?.cvrsBackedUpAt) {
return undefined;
}
return dateTimeFromNoOffsetSqliteDate(row?.cvrsBackedUpAt);
}
getBallotsCounted(): number {
const row = this.client.one(`
select
count(sheets.id) as ballotsCounted
from
sheets inner join batches
on
sheets.batch_id = batches.id
and
sheets.deleted_at is null
where
batches.deleted_at is null
`) as { ballotsCounted: number } | undefined;
return row?.ballotsCounted ?? 0;
}
/**
* Returns whether the appropriate backups have been completed and it is safe
* to unconfigure a machine / reset the election session. Always returns
* true in test mode.
*/
getCanUnconfigure(): boolean {
// Always allow in test mode
if (this.getTestMode()) {
return true;
}
// Allow if no ballots have been counted
if (!this.getBallotsCounted()) {
return true;
}
if (
isFeatureFlagEnabled(
BooleanEnvironmentVariableName.ENABLE_CONTINUOUS_EXPORT
)
) {
return true;
}
const scannerBackedUpAt = this.getScannerBackupTimestamp();
// Require that a scanner backup has taken place
if (!scannerBackedUpAt) {
return false;
}
// Adding or deleting sheets would have updated the CVR count
const { maxSheetsCreatedAt, maxSheetsDeletedAt } = this.client.one(`
select
max(created_at) as maxSheetsCreatedAt,
max(deleted_at) as maxSheetsDeletedAt
from sheets
`) as {
maxSheetsCreatedAt: string;
maxSheetsDeletedAt: string;
};
// Deleting non-empty batches would have updated the CVR count
const { maxBatchesDeletedAt } = this.client.one(`
select
max(batches.deleted_at) as maxBatchesDeletedAt
from batches inner join sheets
on sheets.batch_id = batches.id
where sheets.deleted_at is null
`) as {
maxBatchesDeletedAt: string;
};
const cvrsLastUpdatedDates = [
maxBatchesDeletedAt,
maxSheetsCreatedAt,
maxSheetsDeletedAt,
]
.filter(Boolean)
.map((noOffsetSqliteDate) =>
dateTimeFromNoOffsetSqliteDate(noOffsetSqliteDate)
);
return scannerBackedUpAt >= DateTime.max(...cvrsLastUpdatedDates);
}
/**
* Adds a sheet to an existing batch.
*/
addSheet(
sheetId: string,
batchId: string,
[front, back]: SheetOf<PageInterpretationWithFiles>
): string {
try {
const finishedAdjudicationAt =
front.interpretation.type === 'InterpretedHmpbPage' &&
back.interpretation.type === 'InterpretedHmpbPage' &&
!front.interpretation.adjudicationInfo.requiresAdjudication &&
!back.interpretation.adjudicationInfo.requiresAdjudication
? DateTime.now().toISOTime()
: undefined;
this.client.run(
`insert into sheets (
id,
batch_id,
front_image_path,
front_interpretation_json,
back_image_path,
back_interpretation_json,
requires_adjudication,
finished_adjudication_at
) values (
?, ?, ?, ?, ?, ?, ?, ?
)`,
sheetId,
batchId,
front.imagePath,
JSON.stringify(front.interpretation),
back.imagePath,
JSON.stringify(back.interpretation ?? {}),
sheetRequiresAdjudication([front.interpretation, back.interpretation])
? 1
: 0,
finishedAdjudicationAt ?? null
);
} catch (error) {
debug(
'sheet insert failed; maybe a duplicate? filenames=[%s, %s]',
front.imagePath,
back.imagePath
);
const row = this.client.one<[string]>(
'select id from sheets where front_image_path = ?',
front.imagePath
) as { id: string } | undefined;
if (row) {
return row.id;
}
throw error;
}
return sheetId;
}
/**
* Mark a sheet as deleted
*/
deleteSheet(sheetId: string): void {
this.client.run(
'update sheets set deleted_at = current_timestamp where id = ?',
sheetId
);
}
resetElectionSession(): void {
if (this.hasElection()) {
this.client.transaction(() => {
this.setPollsState('polls_closed_initial');
this.setBallotCountWhenBallotBagLastReplaced(0);
this.setCvrsBackedUp(false);
this.setScannerBackedUp(false);
});
}
// delete batches, which will cascade delete sheets
this.client.run('delete from batches');
// reset autoincrementing key on "batches" table
this.client.run("delete from sqlite_sequence where name = 'batches'");
}
getNextAdjudicationSheet(): BallotSheetInfo | undefined {
const row = this.client.one(
`
select
id,
front_interpretation_json as frontInterpretationJson,
back_interpretation_json as backInterpretationJson,
finished_adjudication_at as finishedAdjudicationAt
from sheets
where
requires_adjudication = 1 and
finished_adjudication_at is null and
deleted_at is null
order by created_at asc
limit 1
`
) as
| {
id: string;
frontInterpretationJson: string;
backInterpretationJson: string;
finishedAdjudicationAt: string | null;
}
| undefined;
// TODO: these URLs and others in this file probably don't belong
// in this file, which shouldn't deal with the URL API.
if (row) {
debug('got next review sheet requiring adjudication (id=%s)', row.id);
return {
id: row.id,
front: {
image: {
url: `/central-scanner/scan/hmpb/ballot/${row.id}/front/image`,
},
interpretation: JSON.parse(row.frontInterpretationJson),
adjudicationFinishedAt: row.finishedAdjudicationAt ?? undefined,
},
back: {
image: {
url: `/central-scanner/scan/hmpb/ballot/${row.id}/back/image`,
},
interpretation: JSON.parse(row.backInterpretationJson),
adjudicationFinishedAt: row.finishedAdjudicationAt ?? undefined,
},
};
}
debug('no review sheets requiring adjudication');
}
*getSheets(): Generator<{
id: string;
frontImagePath: string;
backImagePath: string;
exportedAsCvrAt: Iso8601Timestamp;
}> {
for (const { id, frontImagePath, backImagePath, exportedAsCvrAt } of this
.client.each(`
select
id,
front_image_path as frontImagePath,
back_image_path as backImagePath
from sheets
order by created_at asc
`) as Iterable<{
id: string;
frontImagePath: string;
backImagePath: string;
exportedAsCvrAt: Iso8601Timestamp;
}>) {
yield {
id,
frontImagePath,
backImagePath,
exportedAsCvrAt,
};
}
}
adjudicateSheet(sheetId: string): boolean {
debug('finishing adjudication for sheet %s', sheetId);
this.client.run(
`
update
sheets
set
finished_adjudication_at = ?
where id = ?
`,
new Date().toISOString(),
sheetId
);
return true;
}
/**
* Mark a batch as deleted
*/
deleteBatch(batchId: string): boolean {
const { count } = this.client.one(
'select count(*) as count from batches where deleted_at is null and id = ?',
batchId
) as { count: number };
this.client.run(
'update batches set deleted_at = current_timestamp where id = ?',
batchId
);
return count > 0;
}
/**
* Cleanup partial batches
*/
cleanupIncompleteBatches(): void {
// cascades to the sheets
this.client.run('delete from batches where ended_at is null');
}
/**
* Gets all batches, including their sheet count.
*/
getBatches(): BatchInfo[] {
interface SqliteBatchInfo {
id: string;
batchNumber: number;
label: string;
startedAt: string;
endedAt: string | null;
error: string | null;
count: number;
}
const batchInfo = this.client.all(`
select
batches.id as id,
batches.batch_number as batchNumber,
batches.label as label,
strftime('%s', started_at) as startedAt,
(case when ended_at is null then ended_at else strftime('%s', ended_at) end) as endedAt,
error,
sum(case when sheets.id is null then 0 else 1 end) as count
from
batches left join sheets
on
sheets.batch_id = batches.id
and
sheets.deleted_at is null
where
batches.deleted_at is null
group by
batches.id,
batches.started_at,
batches.ended_at,
error
order by
batches.started_at desc
`) as SqliteBatchInfo[];
return batchInfo.map((info) => ({
id: info.id,
batchNumber: info.batchNumber,
label: info.label,
// eslint-disable-next-line vx/gts-safe-number-parse
startedAt: DateTime.fromSeconds(Number(info.startedAt)).toISO(),
endedAt:
// eslint-disable-next-line vx/gts-safe-number-parse
(info.endedAt && DateTime.fromSeconds(Number(info.endedAt)).toISO()) ||
undefined,
error: info.error || undefined,
count: info.count,
}));
}
/**
* Gets adjudication status.
*/
adjudicationStatus(): AdjudicationStatus {
const { remaining } = this.client.one(`
select count(*) as remaining
from sheets
where
requires_adjudication = 1
and deleted_at is null
and finished_adjudication_at is null
`) as { remaining: number };
const { adjudicated } = this.client.one(`
select count(*) as adjudicated
from sheets
where
requires_adjudication = 1
and finished_adjudication_at is not null
`) as { adjudicated: number };
return { adjudicated, remaining };
}
/**
* Yields all sheets in the database that would be included in a CVR export.
*/
*forEachResultSheet(): Generator<ResultSheet> {
const sql = `${getResultSheetsBaseQuery} order by sheets.id`;
for (const row of this.client.each(sql) as Iterable<ResultSheetRow>) {
yield resultSheetRowToResultSheet(row);
}
}
/**
* Gets a single sheet given a sheet ID. Returns undefined if the sheet doesn't exist or wouldn't
* be included in a CVR export.
*/
getResultSheet(sheetId: string): ResultSheet | undefined {
const sql = `${getResultSheetsBaseQuery} and sheets.id = ?`;
const row = this.client.one(sql, sheetId) as ResultSheetRow | undefined;
return row ? resultSheetRowToResultSheet(row) : undefined;
}
/**
* Stores the system settings.
*/
setSystemSettings(systemSettings: SystemSettings): void {
this.client.run('delete from system_settings');
this.client.run(
`
insert into system_settings (data) values (?)
`,
JSON.stringify(systemSettings)
);
}
/**
* Retrieves the system settings.
*/
getSystemSettings(): SystemSettings | undefined {
const result = this.client.one(`select data from system_settings`) as
| { data: string }
| undefined;
if (!result) return undefined;
return safeParseSystemSettings(result.data).unsafeUnwrap();
}
/**
* Gets the name of the directory that we're continuously exporting to, e.g.
* TEST__machine_SCAN-0001__2023-08-16_17-02-24. Returns undefined if not yet set.
*/
getExportDirectoryName(): string | undefined {
const result = this.client.one(
'select export_directory_name as exportDirectoryName from export_directory_name'
) as { exportDirectoryName: string } | undefined;
return result?.exportDirectoryName;
}
/**
* Stores the name of the directory that we'll be continuously exporting to
*/
setExportDirectoryName(exportDirectoryName: string): void {
this.client.run('delete from export_directory_name');
this.client.run(
'insert into export_directory_name (export_directory_name) values (?)',
exportDirectoryName
);
}
getCastVoteRecordRootHash(): string {
return getCastVoteRecordRootHash(this.client);
}
updateCastVoteRecordHashes(cvrId: string, cvrHash: string): void {
updateCastVoteRecordHashes(this.client, cvrId, cvrHash);
}
clearCastVoteRecordHashes(): void {
clearCastVoteRecordHashes(this.client);
}
}