Skip to content

Commit 67ece36

Browse files
committed
Use last row read for training sheet
1 parent 8ffb33f commit 67ece36

File tree

3 files changed

+40
-17
lines changed

3 files changed

+40
-17
lines changed

src/init-dependencies/google/cache-sheet-data.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import {Client} from '@libsql/client/.';
22
import {Logger} from 'pino';
3-
import * as O from 'fp-ts/Option';
43
import {dbExecute} from '../../util';
5-
import {LastGoogleSheetRowRead} from '../../dependencies';
4+
import {LastGoogleSheetRowRead} from '../../read-models/shared-state/return-types';
65

76
// This would be more efficient with a simple key-value store.
87
export const cacheSheetData =
@@ -32,12 +31,7 @@ export const cacheSheetData =
3231
last_row_read = excluded.last_row_read,
3332
cached_data = excluded.cached_data;
3433
`,
35-
[
36-
cacheTimestamp,
37-
sheetId,
38-
O.getOrElse<null | number>(() => null)(last_row_read),
39-
cachedData,
40-
]
34+
[cacheTimestamp, sheetId, JSON.stringify(last_row_read), cachedData]
4135
);
4236
} catch (e) {
4337
logger.error(e, 'Failed to insert cache data, failing silently...');

src/read-models/external-event-sources/google/training-sheet.ts

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ import * as RA from 'fp-ts/ReadonlyArray';
3333
import {v4} from 'uuid';
3434
import {lookup} from 'fp-ts/ReadonlyArray';
3535
import {array} from 'fp-ts';
36+
import {LastGoogleSheetRowRead} from '../../shared-state/return-types';
37+
import * as R from 'fp-ts/Record';
3638

3739
const ROW_BATCH_SIZE = 50;
3840
const FORM_RESPONSES_SHEET_REGEX = /^Form Responses [0-9]*/i;
@@ -178,19 +180,22 @@ export const columnBoundsRequired = (
178180
return [Math.min(...colIndexes), Math.max(...colIndexes)];
179181
};
180182

183+
type LastRowRead = number;
184+
181185
const pullNewEquipmentQuizResultsForSheet = async (
182186
logger: Logger,
183187
googleHelpers: GoogleHelpers,
184188
equipmentId: UUID,
185189
trainingSheetId: string,
186190
sheet: GoogleSheetMetadata,
187191
timezone: string,
192+
prevLastRowRead: O.Option<LastRowRead>,
188193
updateState: (event: EventOfType<'EquipmentTrainingQuizResult'>) => void
189-
): Promise<void> => {
194+
): Promise<LastRowRead> => {
190195
logger = logger.child({sheet_name: sheet.name});
191196
logger.info('Processing sheet');
192197
for (const [rowStart, rowEnd] of getChunkIndexes(
193-
2, // 1-indexed and first row is headers.
198+
O.getOrElse(() => 1)(prevLastRowRead) + 1, // 1-indexed and first row is headers.
194199
sheet.rowCount,
195200
ROW_BATCH_SIZE
196201
)) {
@@ -214,7 +219,7 @@ const pullNewEquipmentQuizResultsForSheet = async (
214219
rowStart,
215220
rowEnd
216221
);
217-
return;
222+
return rowStart - 1;
218223
}
219224
logger.info('Pulled data from google, extracting...');
220225
const result = extractGoogleSheetData(
@@ -232,19 +237,21 @@ const pullNewEquipmentQuizResultsForSheet = async (
232237
}
233238
}
234239
logger.info('Finished processing sheet');
240+
return sheet.rowCount - 1;
235241
};
236242

237243
export const pullNewEquipmentQuizResults = async (
238244
logger: Logger,
239245
googleHelpers: GoogleHelpers,
240246
equipmentId: UUID,
241247
trainingSheetId: string,
248+
prevLastRowsRead: Readonly<LastGoogleSheetRowRead>,
242249
updateState: (
243250
event:
244251
| EventOfType<'EquipmentTrainingQuizSync'>
245252
| EventOfType<'EquipmentTrainingQuizResult'>
246253
) => void
247-
): Promise<void> => {
254+
): Promise<Readonly<LastGoogleSheetRowRead>> => {
248255
logger.info('Scanning training sheet. Pulling google sheet data...');
249256

250257
const initialMeta = await googleHelpers.pullGoogleSheetDataMetadata(
@@ -253,7 +260,7 @@ export const pullNewEquipmentQuizResults = async (
253260
)();
254261
if (E.isLeft(initialMeta)) {
255262
logger.warn(initialMeta.left);
256-
return;
263+
return prevLastRowsRead;
257264
}
258265

259266
logger.info('Got meta data for sheet...');
@@ -298,27 +305,43 @@ export const pullNewEquipmentQuizResults = async (
298305
sheets.push(meta.value);
299306
}
300307

308+
const newLastRowRead: LastGoogleSheetRowRead = JSON.parse(
309+
JSON.stringify(prevLastRowsRead)
310+
) as LastGoogleSheetRowRead;
311+
301312
for (const sheet of sheets) {
302-
await pullNewEquipmentQuizResultsForSheet(
313+
const prevLastRowReadForSheet = pipe(
314+
prevLastRowsRead,
315+
R.lookup(trainingSheetId),
316+
O.flatMap(R.lookup(trainingSheetId))
317+
);
318+
const lastRowRead = await pullNewEquipmentQuizResultsForSheet(
303319
logger,
304320
googleHelpers,
305321
equipmentId,
306322
trainingSheetId,
307323
sheet,
308324
initialMeta.right.properties.timeZone,
325+
prevLastRowReadForSheet,
309326
updateState
310327
);
328+
if (!newLastRowRead[trainingSheetId]) {
329+
newLastRowRead[trainingSheetId] = {};
330+
}
331+
newLastRowRead[trainingSheetId][sheet.name] = lastRowRead;
311332
}
312333

313334
logger.info(
314-
'Finished pulling equipment quiz results for all sheets, generating quiz sync event...'
335+
'Finished pulling equipment quiz results for all sheets %o, generating quiz sync event...',
336+
newLastRowRead
315337
);
316338

317339
updateState(
318340
constructEvent('EquipmentTrainingQuizSync')({
319341
equipmentId,
320342
})
321343
);
344+
return newLastRowRead;
322345
};
323346

324347
export async function asyncApplyTrainingSheetEvents(
@@ -371,11 +394,12 @@ export async function asyncApplyTrainingSheetEvents(
371394
updateState(event);
372395
};
373396

374-
await pullNewEquipmentQuizResults(
397+
const lastRowRead = await pullNewEquipmentQuizResults(
375398
equipmentLogger,
376399
googleHelpers,
377400
equipment.id,
378401
equipmentTrainingSheetId,
402+
equipment.lastRowsRead,
379403
collectEvents
380404
);
381405
equipmentLogger.info(
@@ -386,6 +410,7 @@ export async function asyncApplyTrainingSheetEvents(
386410
new Date(),
387411
equipmentTrainingSheetId,
388412
equipmentLogger,
413+
lastRowRead,
389414
events
390415
);
391416
}

src/read-models/shared-state/return-types.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,12 @@ export type TrainerInfo = Pick<
4444
trainerSince: Date;
4545
};
4646

47+
export type GoogleSheetId = string;
4748
export type SheetName = string;
48-
export type LastGoogleSheetRowRead = Record<SheetName, number>;
49+
export type LastGoogleSheetRowRead = Record<
50+
GoogleSheetId,
51+
Record<SheetName, number>
52+
>;
4953

5054
export type MinimalEquipment = {
5155
id: UUID;

0 commit comments

Comments
 (0)