aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/sync/scheduler.test.ts
blob: adee34ebee2f1a058b051126e0a7f0394fe29d36 (plain)
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
/**
 * @vitest-environment jsdom
 */
import "fake-indexeddb/auto";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { CardState, db, Rating } from "../db/index";
import {
	localCardRepository,
	localDeckRepository,
	localReviewLogRepository,
} from "../db/repositories";
import { syncQueue } from "./queue";
import {
	cacheStudyCards,
	type ServerStudyCard,
	submitReviewLocal,
	undoReviewLocal,
} from "./scheduler";

async function clearDb() {
	await db.decks.clear();
	await db.cards.clear();
	await db.reviewLogs.clear();
	await db.noteTypes.clear();
	await db.noteFieldTypes.clear();
	await db.notes.clear();
	await db.noteFieldValues.clear();
}

async function seedDeck() {
	const deck = await localDeckRepository.create({
		userId: "user-1",
		name: "Test Deck",
		description: null,
		defaultNoteTypeId: null,
	});
	await localDeckRepository.markSynced(deck.id, 1);
	return deck;
}

async function seedSyncedCard(deckId: string) {
	const card = await localCardRepository.create({
		deckId,
		noteId: "note-1",
		isReversed: false,
		front: "front",
		back: "back",
	});
	await localCardRepository.markSynced(card.id, 1);
	return card;
}

describe("submitReviewLocal", () => {
	beforeEach(async () => {
		await clearDb();
		localStorage.clear();
	});

	afterEach(async () => {
		await clearDb();
		localStorage.clear();
	});

	it("updates card scheduling and creates a review log in IndexedDB", async () => {
		const deck = await seedDeck();
		const card = await seedSyncedCard(deck.id);

		const result = await submitReviewLocal({
			cardId: card.id,
			rating: Rating.Good,
			durationMs: 5000,
		});

		expect(result.card.reps).toBe(1);
		expect(result.card.lastReview).toBeInstanceOf(Date);
		expect(result.card._synced).toBe(false);
		expect(result.reviewLogId).toBeDefined();

		const logs = await localReviewLogRepository.findByCardId(card.id);
		expect(logs).toHaveLength(1);
		expect(logs[0]?.rating).toBe(Rating.Good);
		expect(logs[0]?.userId).toBe(deck.userId);
		expect(logs[0]?.durationMs).toBe(5000);
		expect(logs[0]?._synced).toBe(false);
	});

	it("returns the previous card snapshot for undo", async () => {
		const deck = await seedDeck();
		const card = await seedSyncedCard(deck.id);

		const result = await submitReviewLocal({
			cardId: card.id,
			rating: Rating.Again,
			durationMs: 3000,
		});

		expect(result.prevCard.reps).toBe(0);
		expect(result.prevCard.state).toBe(CardState.New);
	});

	it("queues 5 offline reviews and exposes them as pending changes", async () => {
		const deck = await seedDeck();
		const cards = await Promise.all(
			Array.from({ length: 5 }, () => seedSyncedCard(deck.id)),
		);

		for (const card of cards) {
			await submitReviewLocal({
				cardId: card.id,
				rating: Rating.Good,
				durationMs: 1000,
			});
		}

		const pending = await syncQueue.getPendingChanges();
		expect(pending.cards.filter((c) => !c._synced)).toHaveLength(5);
		expect(pending.reviewLogs).toHaveLength(5);
	});

	it("notifies sync queue listeners after each review", async () => {
		const deck = await seedDeck();
		const card = await seedSyncedCard(deck.id);

		const counts: number[] = [];
		const unsub = syncQueue.subscribe((state) => {
			counts.push(state.pendingCount);
		});

		await submitReviewLocal({
			cardId: card.id,
			rating: Rating.Good,
			durationMs: 1000,
		});

		unsub();
		// Card was synced=true before; now both card and reviewLog are unsynced.
		expect(counts.at(-1)).toBe(2);
	});

	it("throws when the card is missing from local DB", async () => {
		await expect(
			submitReviewLocal({
				cardId: "missing-card",
				rating: Rating.Good,
				durationMs: 1000,
			}),
		).rejects.toThrow(/Card not found/);
	});
});

describe("undoReviewLocal", () => {
	beforeEach(async () => {
		await clearDb();
		localStorage.clear();
	});

	afterEach(async () => {
		await clearDb();
		localStorage.clear();
	});

	it("restores the card and removes the review log", async () => {
		const deck = await seedDeck();
		const card = await seedSyncedCard(deck.id);

		const result = await submitReviewLocal({
			cardId: card.id,
			rating: Rating.Good,
			durationMs: 1000,
		});

		await undoReviewLocal({
			prevCard: result.prevCard,
			reviewLogId: result.reviewLogId,
		});

		const restored = await localCardRepository.findById(card.id);
		expect(restored?.reps).toBe(0);
		expect(restored?.state).toBe(CardState.New);

		const logs = await localReviewLogRepository.findByCardId(card.id);
		expect(logs).toHaveLength(0);
	});
});

describe("cacheStudyCards", () => {
	beforeEach(async () => {
		await clearDb();
		localStorage.clear();
	});

	afterEach(async () => {
		await clearDb();
		localStorage.clear();
	});

	function makeServerCard(id: string): ServerStudyCard {
		return {
			id,
			deckId: "deck-1",
			noteId: `note-${id}`,
			isReversed: false,
			front: "front",
			back: "back",
			state: 0,
			due: "2026-05-02T00:00:00.000Z",
			stability: 0,
			difficulty: 0,
			elapsedDays: 0,
			scheduledDays: 0,
			reps: 0,
			lapses: 0,
			lastReview: null,
			createdAt: "2026-05-01T00:00:00.000Z",
			updatedAt: "2026-05-01T00:00:00.000Z",
			deletedAt: null,
			syncVersion: 1,
		};
	}

	it("upserts new cards into IndexedDB as synced", async () => {
		await cacheStudyCards([makeServerCard("card-1"), makeServerCard("card-2")]);

		const card1 = await localCardRepository.findById("card-1");
		expect(card1?._synced).toBe(true);
		expect(card1?.due).toBeInstanceOf(Date);
		expect(card1?.syncVersion).toBe(1);

		const card2 = await localCardRepository.findById("card-2");
		expect(card2).toBeDefined();
	});

	it("does not clobber unsynced local edits", async () => {
		const deck = await seedDeck();
		const card = await seedSyncedCard(deck.id);
		await submitReviewLocal({
			cardId: card.id,
			rating: Rating.Good,
			durationMs: 1000,
		});

		const before = await localCardRepository.findById(card.id);
		expect(before?._synced).toBe(false);

		// Simulate the server returning a stale view of this card.
		await cacheStudyCards([{ ...makeServerCard(card.id), reps: 0, state: 0 }]);

		const after = await localCardRepository.findById(card.id);
		expect(after?._synced).toBe(false);
		expect(after?.reps).toBe(1);
	});
});