diff --git a/firka/lib/api/client/kreta_client.dart b/firka/lib/api/client/kreta_client.dart index 8ee77e46..5558b69a 100644 --- a/firka/lib/api/client/kreta_client.dart +++ b/firka/lib/api/client/kreta_client.dart @@ -456,10 +456,21 @@ class KretaClient { } } + /// Upserts [caches]. Deletes stale rows in [staleScope]. Future> _save, I extends Identifiable>( - List caches, - ) async { + List caches, [ + QueryBuilder? staleScope, + ]) async { isarInit.writeTxnSync(() { + if (staleScope != null) { + final freshKeys = caches.map((c) => c.cacheKey).toSet(); + final staleIds = staleScope + .findAllSync() + .map((c) => c.cacheKey) + .where((key) => !freshKeys.contains(key)) + .toList(); + isarInit.collection().deleteAllSync(staleIds); + } isarInit.collection().putAllSync(caches); }); initData.homeRefreshCubit.requestRefresh(); @@ -520,7 +531,7 @@ class KretaClient { KretaEndpoints.getGrades(cache.token.iss), GradeCacheModel.new, (json) => Grade.fromJson(json), - ).then(_save); + ).then((caches) => _save(caches, cache.getGrades())); } Future> getHomework({ @@ -534,17 +545,22 @@ class KretaClient { KretaEndpoints.getHomework(cache.token.iss, from, to), HomeworkCacheModel.new, (item) => Homework.fromJson(item), - ).then(_save); + ).then((caches) => _save(caches, cache.getHomeworks())); } /// Automatically aligns requests to start at Monday and end at Sunday Future> getLessons(DateTime from, DateTime to) async { assert(from.difference(to).inDays < 30); return (await _renewCache( - KretaEndpoints.getTimeTable(cache.token.iss, from, to), - LessonCacheModel.new, - (json) => Lesson.fromJson(json), - ).then(resolveDailyNth).then(_save)) + KretaEndpoints.getTimeTable(cache.token.iss, from, to), + LessonCacheModel.new, + (json) => Lesson.fromJson(json), + ) + .then(resolveDailyNth) + .then( + (caches) => + _save(caches, cache.getTimeTable().and().between(from, to)), + )) ..sort((a, b) => a.start.compareTo(b.start)); } @@ -553,15 +569,28 @@ class KretaClient { KretaEndpoints.getTests(cache.token.iss, from, to), TestCacheModel.new, (item) => Test.fromJson(item), - ).then(_save); + ).then( + (caches) => _save( + caches, + isarInit.testCacheModels.filter().classGroup(cache.isCurrentClassGroup), + ), + ); } Future> getOmissions() async { return (await _renewCache( - KretaEndpoints.getOmissions(cache.token.iss), - OmissionCacheModel.new, - (item) => Omission.fromJson(item), - ).then(_save))..sort((a, b) => a.createdAt.compareTo(b.createdAt)); + KretaEndpoints.getOmissions(cache.token.iss), + OmissionCacheModel.new, + (item) => Omission.fromJson(item), + ).then( + (caches) => _save( + caches, + isarInit.omissionCacheModels.filter().classGroup( + cache.isCurrentClassGroup, + ), + ), + )) + ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); } Future> getSubjects() async { diff --git a/firka/test/e2e/collection_cache_reconciliation_test.dart b/firka/test/e2e/collection_cache_reconciliation_test.dart new file mode 100644 index 00000000..6560b5fc --- /dev/null +++ b/firka/test/e2e/collection_cache_reconciliation_test.dart @@ -0,0 +1,348 @@ +// ignore_for_file: depend_on_referenced_packages +import 'dart:convert'; +import 'dart:io'; + +import 'package:firka/app/app_state.dart'; +import 'package:firka/app/initialization.dart'; +import 'package:firka/core/settings/settings_repository.dart'; +import 'package:firka/core/settings/settings_schema.dart'; +import 'package:firka_common/data/database.dart'; +import 'package:firka_common/data/models/grade_cache_model.dart'; +import 'package:firka_common/data/models/homework_cache_model.dart'; +import 'package:firka_common/data/models/omission_cache_model.dart'; +import 'package:firka_common/data/models/test_cache_model.dart'; +import 'package:firka_common/data/models/token_model.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:kreta_api/kreta_api.dart'; +import 'package:logging/logging.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart'; + +const _mockServerUrl = 'http://127.0.0.1:8090'; + +class _RealHttpOverrides extends HttpOverrides {} + +class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform + with MockPlatformInterfaceMixin { + Future initialize( + InitializationSettings initializationSettings, { + void Function(NotificationResponse)? onDidReceiveNotificationResponse, + void Function(NotificationResponse)? + onDidReceiveBackgroundNotificationResponse, + }) async => true; + + @override + Future> getActiveNotifications() async => []; +} + +Future _authenticateMockServer( + HttpClient httpClient, +) async { + final loginReq = await httpClient.getUrl( + Uri.parse('$_mockServerUrl/Account/Login'), + ); + final loginResp = await loginReq.close(); + final loginBody = await loginResp.transform(utf8.decoder).join(); + + final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody); + if (match == null) { + throw Exception( + 'Failed to extract code from mock server login: $loginBody', + ); + } + final code = match.group(1)!; + + final tokenReq = await httpClient.postUrl( + Uri.parse('$_mockServerUrl/connect/token'), + ); + tokenReq.headers.contentType = ContentType( + 'application', + 'x-www-form-urlencoded', + ); + tokenReq.write( + 'grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}', + ); + final tokenResp = await tokenReq.close(); + final tokenBody = await tokenResp.transform(utf8.decoder).join(); + if (tokenResp.statusCode != 200) { + throw Exception( + 'Token request failed (${tokenResp.statusCode}): $tokenBody', + ); + } + return TokenGrantResponse.fromJson( + jsonDecode(tokenBody) as Map, + ); +} + +Future _resetMockServer(HttpClient httpClient) async { + final req = await httpClient.postUrl( + Uri.parse('$_mockServerUrl/admin/api/reset'), + ); + final resp = await req.close(); + await resp.drain(); +} + +Future _putCollection( + HttpClient httpClient, + String endpoint, + List> items, +) async { + final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl$endpoint')); + req.headers.contentType = ContentType.json; + req.write(jsonEncode(items)); + final resp = await req.close(); + if (resp.statusCode != 204 && resp.statusCode != 200) { + final body = await resp.transform(utf8.decoder).join(); + throw Exception('Failed to PUT $endpoint (${resp.statusCode}): $body'); + } +} + +const _subject = { + 'Uid': '1,MATEK', + 'Nev': 'Matematika', + 'Kategoria': {'Uid': '1', 'Nev': 'Kötelező', 'Leiras': 'Kötelező tantárgy'}, + 'SortIndex': 1, +}; + +Map _grade(String uid) => { + 'Uid': uid, + 'RogzitesDatuma': '2026-09-08T00:00:00', + 'KeszitesDatuma': '2026-09-08T00:00:00', + 'Tantargy': _subject, + 'Tema': 'Teszt téma', + 'Tipus': {'Uid': '1', 'Nev': 'Írásbeli', 'Leiras': 'Írásbeli felelet'}, + 'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat', 'Leiras': 'Osztályzat'}, + 'ErtekeloTanarNeve': 'Teszt Tanár', + 'Jelleg': 'Ertekeles', + 'SzamErtek': 5, + 'SzovegesErtek': 'Jeles', + 'SulySzazalekErteke': 100, + 'OsztalyCsoport': {'Uid': '10,11.A'}, + 'SortIndex': 1, +}; + +Map _homework(String uid) => { + 'Uid': uid, + 'Tantargy': _subject, + 'TantargyNeve': 'Matematika', + 'RogzitoTanarNeve': 'Teszt Tanár', + 'Szoveg': 'Teszt házi feladat', + 'FeladasDatuma': '2026-09-09T00:00:00', + 'HataridoDatuma': '2026-09-16T00:00:00', + 'RogzitesIdopontja': '2026-09-09T00:00:00', + 'IsTanarRogzitette': true, + 'IsMegoldva': false, + 'IsBeadhato': false, + 'OsztalyCsoport': {'Uid': '10,11.A'}, + 'IsCsatolasEngedelyezes': false, +}; + +Map _test(String uid) => { + 'Uid': uid, + 'Datum': '2026-09-14T00:00:00', + 'BejelentesDatuma': '2026-09-09T00:00:00', + 'RogzitoTanarNeve': 'Teszt Tanár', + 'OrarendiOraOraszama': 2, + 'Tantargy': _subject, + 'TantargyNeve': 'Matematika', + 'Temaja': 'Teszt dolgozat téma', + 'Modja': {'Uid': '1', 'Nev': 'Írásbeli', 'Leiras': 'Írásbeli dolgozat'}, + 'OsztalyCsoport': {'Uid': '10,11.A'}, +}; + +Map _omission(String uid) => { + 'Uid': uid, + 'Tantargy': _subject, + 'Ora': { + 'KezdoDatum': '2026-09-07T00:00:00', + 'VegDatum': '2026-09-07T00:45:00', + 'Oraszam': 1, + }, + 'Datum': '2026-09-07T00:00:00', + 'RogzitoTanarNeve': 'Teszt Tanár', + 'Tipus': {'Uid': '1', 'Nev': 'Hiányzás', 'Leiras': 'Hiányzás'}, + 'Mod': {'Uid': '', 'Nev': '', 'Leiras': ''}, + 'KeszitesDatuma': '2026-09-07T00:00:00', + 'IgazolasAllapota': 'Igazolt', + 'IgazolasTipusa': {'Uid': '', 'Nev': '', 'Leiras': ''}, + 'OsztalyCsoport': {'Uid': '10,11.A'}, +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + HttpOverrides.global = _RealHttpOverrides(); + FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform(); + logger = Logger('CollectionCacheReconciliationTest'); + + group('Collection cache reconciliation against mock Kreta server', () { + late HttpClient httpClient; + + setUp(() async { + HttpOverrides.global = _RealHttpOverrides(); + httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5); + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (MethodCall methodCall) async => Directory.systemTemp.path, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('dev.fluttercommunity.plus/package_info'), + (MethodCall methodCall) async => { + 'appName': 'firka', + 'packageName': 'app.firka.naplo', + 'version': '1.0.0', + 'buildNumber': '1', + }, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('firka.app/main'), + (MethodCall methodCall) async => 'SM-A705FN;11;30', + ); + }); + + tearDown(() { + httpClient.close(force: true); + }); + + Future initAndSync() async { + final isar = await initDB(); + await isar.writeTxn(() async { + await isar.clear(); + }); + Settings = SettingsRepository(isar); + await Settings.loadAll(); + + await Settings.mockBackendEnabled.set(true); + await Settings.mockBackendUrl.set(_mockServerUrl); + + final tokenResp = await _authenticateMockServer(httpClient); + final tokenModel = TokenModel.fromResp(tokenResp); + + await isar.writeTxn(() async { + await isar.tokenModels.clear(); + await isar.tokenModels.put(tokenModel); + }); + + await initializeApp(); + expect(initDone, isTrue); + + await initData.client!.init(); + await initData.client!.renewCache(reInit: false); + } + + testWidgets('stale grade rows are removed after a server-side correction', ( + tester, + ) async { + HttpOverrides.global = _RealHttpOverrides(); + await tester.runAsync(() async { + await _resetMockServer(httpClient); + await _putCollection(httpClient, '/admin/api/grades', [ + _grade('g-1'), + _grade('g-2'), + ]); + + await initAndSync(); + expect(isarInit.gradeCacheModels.where().findAllSync().length, 2); + + // teacher deletes an erroneously entered grade server-side + await _putCollection(httpClient, '/admin/api/grades', [_grade('g-1')]); + await initData.client!.renewCache(reInit: false); + + expect( + isarInit.gradeCacheModels.where().findAllSync().length, + 1, + reason: 'deleted grade should no longer be cached locally', + ); + }); + }); + + testWidgets( + 'stale homework rows are removed after a server-side deletion', + (tester) async { + HttpOverrides.global = _RealHttpOverrides(); + await tester.runAsync(() async { + await _resetMockServer(httpClient); + await _putCollection(httpClient, '/admin/api/homework', [ + _homework('h-1'), + _homework('h-2'), + ]); + + await initAndSync(); + expect(isarInit.homeworkCacheModels.where().findAllSync().length, 2); + + await _putCollection(httpClient, '/admin/api/homework', [ + _homework('h-1'), + ]); + await initData.client!.renewCache(reInit: false); + + expect( + isarInit.homeworkCacheModels.where().findAllSync().length, + 1, + reason: 'deleted homework should no longer be cached locally', + ); + }); + }, + ); + + testWidgets( + 'stale test rows are removed after a server-side cancellation', + (tester) async { + HttpOverrides.global = _RealHttpOverrides(); + await tester.runAsync(() async { + await _resetMockServer(httpClient); + await _putCollection(httpClient, '/admin/api/tests', [ + _test('t-1'), + _test('t-2'), + ]); + + await initAndSync(); + expect(isarInit.testCacheModels.where().findAllSync().length, 2); + + await _putCollection(httpClient, '/admin/api/tests', [_test('t-1')]); + await initData.client!.renewCache(reInit: false); + + expect( + isarInit.testCacheModels.where().findAllSync().length, + 1, + reason: 'cancelled test should no longer be cached locally', + ); + }); + }, + ); + + testWidgets( + 'stale omission rows are removed after a server-side justification', + (tester) async { + HttpOverrides.global = _RealHttpOverrides(); + await tester.runAsync(() async { + await _resetMockServer(httpClient); + await _putCollection(httpClient, '/admin/api/omissions', [ + _omission('o-1'), + _omission('o-2'), + ]); + + await initAndSync(); + expect(isarInit.omissionCacheModels.where().findAllSync().length, 2); + + // a teacher retroactively removes an incorrectly recorded absence + await _putCollection(httpClient, '/admin/api/omissions', [ + _omission('o-1'), + ]); + await initData.client!.renewCache(reInit: false); + + expect( + isarInit.omissionCacheModels.where().findAllSync().length, + 1, + reason: 'removed absence should no longer be cached locally', + ); + }); + }, + ); + }); +} diff --git a/firka/test/e2e/multi_account_cache_isolation_test.dart b/firka/test/e2e/multi_account_cache_isolation_test.dart new file mode 100644 index 00000000..84f19c12 --- /dev/null +++ b/firka/test/e2e/multi_account_cache_isolation_test.dart @@ -0,0 +1,350 @@ +// ignore_for_file: depend_on_referenced_packages +import 'dart:convert'; +import 'dart:io'; + +import 'package:firka/api/client/kreta_client.dart'; +import 'package:firka/app/app_state.dart'; +import 'package:firka/app/initialization.dart'; +import 'package:firka/core/settings/settings_repository.dart'; +import 'package:firka/core/settings/settings_schema.dart'; +import 'package:firka_common/data/database.dart'; +import 'package:firka_common/data/models/lesson_cache_model.dart'; +import 'package:firka_common/data/models/token_model.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:kreta_api/kreta_api.dart'; +import 'package:logging/logging.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart'; + +const _mockServerUrl = 'http://127.0.0.1:8090'; + +class _RealHttpOverrides extends HttpOverrides {} + +class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform + with MockPlatformInterfaceMixin { + Future initialize( + InitializationSettings initializationSettings, { + void Function(NotificationResponse)? onDidReceiveNotificationResponse, + void Function(NotificationResponse)? + onDidReceiveBackgroundNotificationResponse, + }) async => true; + + @override + Future> getActiveNotifications() async => []; +} + +Future _authenticateMockServer( + HttpClient httpClient, +) async { + final loginReq = await httpClient.getUrl( + Uri.parse('$_mockServerUrl/Account/Login'), + ); + final loginResp = await loginReq.close(); + final loginBody = await loginResp.transform(utf8.decoder).join(); + + final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody); + if (match == null) { + throw Exception( + 'Failed to extract code from mock server login: $loginBody', + ); + } + final code = match.group(1)!; + + final tokenReq = await httpClient.postUrl( + Uri.parse('$_mockServerUrl/connect/token'), + ); + tokenReq.headers.contentType = ContentType( + 'application', + 'x-www-form-urlencoded', + ); + tokenReq.write( + 'grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}', + ); + final tokenResp = await tokenReq.close(); + final tokenBody = await tokenResp.transform(utf8.decoder).join(); + if (tokenResp.statusCode != 200) { + throw Exception( + 'Token request failed (${tokenResp.statusCode}): $tokenBody', + ); + } + return TokenGrantResponse.fromJson( + jsonDecode(tokenBody) as Map, + ); +} + +Future _resetMockServer(HttpClient httpClient) async { + final req = await httpClient.postUrl( + Uri.parse('$_mockServerUrl/admin/api/reset'), + ); + final resp = await req.close(); + await resp.drain(); +} + +Future _putCollection( + HttpClient httpClient, + String endpoint, + List> items, +) async { + final req = await httpClient.putUrl(Uri.parse('$_mockServerUrl$endpoint')); + req.headers.contentType = ContentType.json; + req.write(jsonEncode(items)); + final resp = await req.close(); + if (resp.statusCode != 204 && resp.statusCode != 200) { + final body = await resp.transform(utf8.decoder).join(); + throw Exception('Failed to PUT $endpoint (${resp.statusCode}): $body'); + } +} + +Map _lesson({ + required String uid, + required String start, + required String end, + required String name, +}) { + final today = DateTime.now(); + final datePrefix = + '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}'; + return { + 'Uid': uid, + 'Datum': '${datePrefix}T00:00:00', + 'KezdetIdopont': '${datePrefix}T$start:00', + 'VegIdopont': '${datePrefix}T$end:00', + 'Nev': name, + 'OsztalyCsoport': {'Uid': '10,11.A', 'Nev': '11.A'}, + 'TanarNeve': 'Teszt Tanár', + 'Tantargy': { + 'Uid': '1,MATEK', + 'Nev': name, + 'Kategoria': { + 'Uid': '1', + 'Nev': 'Kötelező', + 'Leiras': 'Kötelező tantárgy', + }, + 'SortIndex': 1, + }, + 'TeremNeve': '101', + 'Tipus': {'Uid': '1', 'Nev': 'Tanóra', 'Leiras': 'Tanóra'}, + 'TanuloJelenlet': {'Uid': '', 'Nev': '', 'Leiras': ''}, + 'Allapot': {'Uid': '1', 'Nev': 'Megtartott', 'Leiras': 'Megtartott óra'}, + 'IsTanuloHaziFeladatEnabled': false, + 'IsHaziFeladatMegoldva': false, + 'Csatolmanyok': [], + 'IsDigitalisOra': false, + 'DigitalisTamogatoEszkozTipusList': [], + 'Letrehozas': '${datePrefix}T00:00:00', + 'UtolsoModositas': DateTime.now().toUtc().toIso8601String(), + }; +} + +Map _grade(String uid) => { + 'Uid': uid, + 'RogzitesDatuma': '2026-09-08T00:00:00', + 'KeszitesDatuma': '2026-09-08T00:00:00', + 'Tantargy': { + 'Uid': '1,MATEK', + 'Nev': 'Matematika', + 'Kategoria': {'Uid': '1', 'Nev': 'Kötelező', 'Leiras': 'Kötelező tantárgy'}, + 'SortIndex': 1, + }, + 'Tema': 'Teszt téma', + 'Tipus': {'Uid': '1', 'Nev': 'Írásbeli', 'Leiras': 'Írásbeli felelet'}, + 'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat', 'Leiras': 'Osztályzat'}, + 'ErtekeloTanarNeve': 'Teszt Tanár', + 'Jelleg': 'Ertekeles', + 'SzamErtek': 5, + 'SzovegesErtek': 'Jeles', + 'SulySzazalekErteke': 100, + 'OsztalyCsoport': {'Uid': '10,11.A'}, + 'SortIndex': 1, +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + HttpOverrides.global = _RealHttpOverrides(); + FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform(); + logger = Logger('MultiAccountCacheIsolationTest'); + + group('Multi-account cache isolation', () { + late HttpClient httpClient; + + setUp(() { + HttpOverrides.global = _RealHttpOverrides(); + httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5); + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (MethodCall methodCall) async => Directory.systemTemp.path, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('dev.fluttercommunity.plus/package_info'), + (MethodCall methodCall) async => { + 'appName': 'firka', + 'packageName': 'app.firka.naplo', + 'version': '1.0.0', + 'buildNumber': '1', + }, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('firka.app/main'), + (MethodCall methodCall) async => 'SM-A705FN;11;30', + ); + }); + + tearDown(() { + httpClient.close(force: true); + }); + + testWidgets( + 'resyncing one account does not delete another account\'s cached rows', + (tester) async { + HttpOverrides.global = _RealHttpOverrides(); + + await tester.runAsync(() async { + await _resetMockServer(httpClient); + await _putCollection(httpClient, '/admin/api/timetable', [ + _lesson( + uid: '9001', + start: '07:30', + end: '08:15', + name: 'Matematika', + ), + _lesson(uid: '9002', start: '08:25', end: '09:10', name: 'Fizika'), + _lesson(uid: '9003', start: '09:20', end: '10:05', name: 'Kémia'), + ]); + await _putCollection(httpClient, '/admin/api/grades', [ + _grade('g-1'), + ]); + + final isar = await initDB(); + await isar.writeTxn(() async { + await isar.clear(); + }); + Settings = SettingsRepository(isar); + await Settings.loadAll(); + await Settings.mockBackendEnabled.set(true); + await Settings.mockBackendUrl.set(_mockServerUrl); + + // mock server is single-tenant. a cloned token with a different iss gets its own cache. + final tokenResp = await _authenticateMockServer(httpClient); + final tokenA = TokenModel.fromResp(tokenResp); + // studentId must match the server's real id. isCurrentStudent matches on it. + final tokenB = TokenModel() + ..key = tokenA.key + 1 + ..studentId = tokenA.studentId + ..username = '${tokenA.username}-b' + ..iss = '${tokenA.iss}-b' + ..idToken = tokenA.idToken + ..accessToken = tokenA.accessToken + ..refreshToken = tokenA.refreshToken + ..expiryDate = tokenA.expiryDate + ..tokenVersion = tokenA.tokenVersion + ..updatedAtMs = tokenA.updatedAtMs; + + await isar.writeTxn(() async { + await isar.tokenModels.clear(); + await isar.tokenModels.put(tokenA); + await isar.tokenModels.put(tokenB); + }); + + await initializeApp(); + expect(initDone, isTrue); + + final clientA = KretaClient(tokenA); + final clientB = KretaClient(tokenB); + + await clientA.init(); + await clientA.renewCache(reInit: false); + await clientB.init(); + await clientB.renewCache(reInit: false); + + List lessonsFor(KretaClient client) { + final today = DateTime.now(); + bool isToday(DateTime d) => + d.year == today.year && + d.month == today.month && + d.day == today.day; + return client.cache + .getTimeTable() + .findAllSync() + .where((l) => isToday(l.start)) + .toList(); + } + + expect(lessonsFor(clientA).length, 3); + expect(lessonsFor(clientB).length, 3); + expect(clientB.cache.getGrades().findAllSync().length, 1); + + // account A's timetable and grade get edited server-side + await _putCollection(httpClient, '/admin/api/timetable', [ + _lesson( + uid: '9001', + start: '07:30', + end: '08:15', + name: 'Matematika', + ), + _lesson( + uid: '9002-v2', + start: '08:20', + end: '09:00', + name: 'Fizika', + ), + _lesson(uid: '9003', start: '09:05', end: '09:50', name: 'Kémia'), + ]); + await _putCollection(httpClient, '/admin/api/grades', []); + await clientA.renewCache(reInit: false); + + final aAfter = lessonsFor(clientA); + expect( + aAfter.length, + 3, + reason: 'account A should still reconcile correctly', + ); + final aFizika = aAfter.firstWhere((l) => l.name == 'Fizika'); + expect( + aFizika.start.minute, + 20, + reason: "account A should see its own edited copy", + ); + expect(clientA.cache.getGrades().findAllSync(), isEmpty); + + final bAfter = lessonsFor(clientB); + expect( + bAfter.length, + 3, + reason: "account B's lessons must survive account A's resync", + ); + expect(bAfter.map((l) => l.name).toSet(), { + 'Matematika', + 'Fizika', + 'Kémia', + }); + // lesson name is identical on both sides. start time reveals the account. + final bFizika = bAfter.firstWhere((l) => l.name == 'Fizika'); + expect(bFizika.start.hour, 8); + expect(bFizika.start.minute, 25); + + final bGrades = clientB.cache.getGrades().findAllSync(); + expect( + bGrades.length, + 1, + reason: + "account B's grade must survive account A's grade being cleared", + ); + expect( + bGrades.single.cacheKey, + clientB.cache.genCacheKey(UidObj(uid: 'g-1')), + reason: + "the surviving row must be account B's own copy of g-1, not " + "some row aliased in from account A", + ); + }); + }, + ); + }); +} diff --git a/firka/test/e2e/timetable_cache_reconciliation_test.dart b/firka/test/e2e/timetable_cache_reconciliation_test.dart new file mode 100644 index 00000000..46783142 --- /dev/null +++ b/firka/test/e2e/timetable_cache_reconciliation_test.dart @@ -0,0 +1,278 @@ +// ignore_for_file: depend_on_referenced_packages +import 'dart:convert'; +import 'dart:io'; + +import 'package:firka/app/app_state.dart'; +import 'package:firka/app/initialization.dart'; +import 'package:firka/core/settings/settings_repository.dart'; +import 'package:firka/core/settings/settings_schema.dart'; +import 'package:firka_common/data/cache_manager.dart'; +import 'package:firka_common/data/database.dart'; +import 'package:firka_common/data/models/lesson_cache_model.dart'; +import 'package:firka_common/data/models/token_model.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:kreta_api/kreta_api.dart'; +import 'package:logging/logging.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_local_notifications_platform_interface/flutter_local_notifications_platform_interface.dart'; + +const _mockServerUrl = 'http://127.0.0.1:8090'; + +class _RealHttpOverrides extends HttpOverrides {} + +class MockNotificationsPlatform extends FlutterLocalNotificationsPlatform + with MockPlatformInterfaceMixin { + Future initialize( + InitializationSettings initializationSettings, { + void Function(NotificationResponse)? onDidReceiveNotificationResponse, + void Function(NotificationResponse)? + onDidReceiveBackgroundNotificationResponse, + }) async => true; + + @override + Future> getActiveNotifications() async => []; +} + +Future _authenticateMockServer( + HttpClient httpClient, +) async { + final loginReq = await httpClient.getUrl( + Uri.parse('$_mockServerUrl/Account/Login'), + ); + final loginResp = await loginReq.close(); + final loginBody = await loginResp.transform(utf8.decoder).join(); + + final match = RegExp(r'name="code" value="([^"]+)"').firstMatch(loginBody); + if (match == null) { + throw Exception( + 'Failed to extract code from mock server login: $loginBody', + ); + } + final code = match.group(1)!; + + final tokenReq = await httpClient.postUrl( + Uri.parse('$_mockServerUrl/connect/token'), + ); + tokenReq.headers.contentType = ContentType( + 'application', + 'x-www-form-urlencoded', + ); + tokenReq.write( + 'grant_type=authorization_code&code=${Uri.encodeQueryComponent(code)}', + ); + final tokenResp = await tokenReq.close(); + final tokenBody = await tokenResp.transform(utf8.decoder).join(); + if (tokenResp.statusCode != 200) { + throw Exception( + 'Token request failed (${tokenResp.statusCode}): $tokenBody', + ); + } + return TokenGrantResponse.fromJson( + jsonDecode(tokenBody) as Map, + ); +} + +Future _resetMockServer(HttpClient httpClient) async { + final req = await httpClient.postUrl( + Uri.parse('$_mockServerUrl/admin/api/reset'), + ); + final resp = await req.close(); + await resp.drain(); +} + +Future _putTimetable( + HttpClient httpClient, + List> lessons, +) async { + final req = await httpClient.putUrl( + Uri.parse('$_mockServerUrl/admin/api/timetable'), + ); + req.headers.contentType = ContentType.json; + req.write(jsonEncode(lessons)); + final resp = await req.close(); + if (resp.statusCode != 204 && resp.statusCode != 200) { + final body = await resp.transform(utf8.decoder).join(); + throw Exception('Failed to PUT timetable (${resp.statusCode}): $body'); + } +} + +Map _lesson({ + required String uid, + required String start, + required String end, + required String name, +}) { + final today = DateTime.now(); + final datePrefix = + '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}'; + return { + 'Uid': uid, + 'Datum': '${datePrefix}T00:00:00', + 'KezdetIdopont': '${datePrefix}T$start:00', + 'VegIdopont': '${datePrefix}T$end:00', + 'Nev': name, + 'OsztalyCsoport': {'Uid': '10,11.A', 'Nev': '11.A'}, + 'TanarNeve': 'Teszt Tanár', + 'Tantargy': { + 'Uid': '1,MATEK', + 'Nev': name, + 'Kategoria': { + 'Uid': '1', + 'Nev': 'Kötelező', + 'Leiras': 'Kötelező tantárgy', + }, + 'SortIndex': 1, + }, + 'TeremNeve': '101', + 'Tipus': {'Uid': '1', 'Nev': 'Tanóra', 'Leiras': 'Tanóra'}, + 'TanuloJelenlet': {'Uid': '', 'Nev': '', 'Leiras': ''}, + 'Allapot': {'Uid': '1', 'Nev': 'Megtartott', 'Leiras': 'Megtartott óra'}, + 'IsTanuloHaziFeladatEnabled': false, + 'IsHaziFeladatMegoldva': false, + 'Csatolmanyok': [], + 'IsDigitalisOra': false, + 'DigitalisTamogatoEszkozTipusList': [], + 'Letrehozas': '${datePrefix}T00:00:00', + 'UtolsoModositas': DateTime.now().toUtc().toIso8601String(), + }; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + HttpOverrides.global = _RealHttpOverrides(); + FlutterLocalNotificationsPlatform.instance = MockNotificationsPlatform(); + logger = Logger('TimetableCacheReconciliationTest'); + + group('Timetable cache reconciliation against mock Kreta server', () { + late HttpClient httpClient; + + setUp(() { + HttpOverrides.global = _RealHttpOverrides(); + httpClient = HttpClient()..connectionTimeout = const Duration(seconds: 5); + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (MethodCall methodCall) async => Directory.systemTemp.path, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('dev.fluttercommunity.plus/package_info'), + (MethodCall methodCall) async => { + 'appName': 'firka', + 'packageName': 'app.firka.naplo', + 'version': '1.0.0', + 'buildNumber': '1', + }, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('firka.app/main'), + (MethodCall methodCall) async => 'SM-A705FN;11;30', + ); + }); + + tearDown(() { + httpClient.close(force: true); + }); + + testWidgets( + 'stale lesson rows are removed when the school edits the timetable', + (tester) async { + HttpOverrides.global = _RealHttpOverrides(); + + await tester.runAsync(() async { + await _resetMockServer(httpClient); + await _putTimetable(httpClient, [ + _lesson( + uid: '9001', + start: '07:30', + end: '08:15', + name: 'Matematika', + ), + _lesson(uid: '9002', start: '08:25', end: '09:10', name: 'Fizika'), + _lesson(uid: '9003', start: '09:20', end: '10:05', name: 'Kémia'), + ]); + + final isar = await initDB(); + await isar.writeTxn(() async { + await isar.clear(); + }); + Settings = SettingsRepository(isar); + await Settings.loadAll(); + + await Settings.mockBackendEnabled.set(true); + await Settings.mockBackendUrl.set(_mockServerUrl); + + final tokenResp = await _authenticateMockServer(httpClient); + final tokenModel = TokenModel.fromResp(tokenResp); + + await isar.writeTxn(() async { + await isar.tokenModels.clear(); + await isar.tokenModels.put(tokenModel); + }); + + await initializeApp(); + expect(initDone, isTrue); + + final client = initData.client!; + await client.init(); + await client.renewCache(reInit: false); + + final today = DateTime.now(); + bool isToday(DateTime d) => + d.year == today.year && + d.month == today.month && + d.day == today.day; + List lessonsFor(CacheManager cache) => cache + .getTimeTable() + .findAllSync() + .where((l) => isToday(l.start)) + .toList(); + + final before = lessonsFor(client.cache); + expect( + before.length, + 3, + reason: 'initial sync should cache exactly the 3 seeded lessons', + ); + + // simulates a school schedule edit + await _putTimetable(httpClient, [ + _lesson( + uid: '9001', + start: '07:30', + end: '08:15', + name: 'Matematika', + ), + _lesson( + uid: '9002-v2', + start: '08:20', + end: '09:00', + name: 'Fizika', + ), + _lesson(uid: '9003', start: '09:05', end: '09:50', name: 'Kémia'), + ]); + + await client.renewCache(reInit: false); + + final after = lessonsFor(client.cache); + expect( + after.length, + 3, + reason: + 'stale lesson row for the old timetable version should have been deleted', + ); + expect( + after.map((l) => l.dailyNth).toSet().length, + after.length, + reason: 'no two lessons should occupy the same period number', + ); + }); + }, + ); + }); +} diff --git a/firka_common/lib/data/models/omission_cache_model.dart b/firka_common/lib/data/models/omission_cache_model.dart index c34b4a0a..db6f475f 100644 --- a/firka_common/lib/data/models/omission_cache_model.dart +++ b/firka_common/lib/data/models/omission_cache_model.dart @@ -1,3 +1,4 @@ +import 'package:firka_common/data/models/class_group_cache_model.dart'; import 'package:firka_common/data/models/generic_cache_model.dart'; import 'package:firka_common/data/models/lesson_cache_model.dart'; import 'package:firka_common/data/util.dart'; @@ -15,6 +16,7 @@ class OmissionCacheModel extends GenericCacheModel { String? proofType; final lesson = IsarLink(); + final classGroup = IsarLink(); @override void apply(CacheContext ctx) { @@ -23,7 +25,8 @@ class OmissionCacheModel extends GenericCacheModel { ..state = ctx.data.state ..teacherName = ctx.data.teacher ..proofType = ctx.data.proofType?.description - ..createdAt = ctx.data.createdAt; + ..createdAt = ctx.data.createdAt + ..classGroup.unsafeInit(ctx.cacheManager, ctx.data.classGroup); lesson.value = ctx.cacheManager .getTimeTable() .startEqualTo(ctx.data.lesson!.start) diff --git a/firka_common/lib/data/models/test_cache_model.dart b/firka_common/lib/data/models/test_cache_model.dart index d5e3b9d1..d7e78c07 100644 --- a/firka_common/lib/data/models/test_cache_model.dart +++ b/firka_common/lib/data/models/test_cache_model.dart @@ -1,3 +1,4 @@ +import 'package:firka_common/data/models/class_group_cache_model.dart'; import 'package:firka_common/data/models/generic_cache_model.dart'; import 'package:firka_common/data/models/lesson_cache_model.dart'; import 'package:firka_common/data/util.dart'; @@ -14,6 +15,7 @@ class TestCacheModel extends GenericCacheModel { @Backlink(to: "test") final lesson = IsarLink(); + final classGroup = IsarLink(); @override void apply(CacheContext ctx) { @@ -21,6 +23,7 @@ class TestCacheModel extends GenericCacheModel { ..topic = ctx.data.theme ..method = ctx.data.method.description ..teacherName = ctx.data.teacherName - ..createdAt = ctx.data.reportDate; + ..createdAt = ctx.data.reportDate + ..classGroup.unsafeInit(ctx.cacheManager, ctx.data.classGroup); } }