6 Commits
staging ... dev

Author SHA1 Message Date
checkedear
5e757d9afd fix: wrong order on homepage
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2026-09-10 17:31:12 +02:00
checkedear
fff41d95d7 fix: apply title formatting for subject names 2026-09-10 09:46:56 +02:00
checkedear
93b1d78fd2 fix: display omission bar even if no lesson available 2026-09-10 09:46:56 +02:00
checkedear
717b4b27aa fix: lesson bottom sheet subject navigation 2026-09-10 09:46:56 +02:00
a097c80516 Bump version string to 1.2.0
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2026-09-09 17:07:20 +02:00
ec2b22c825 fix(cache): reconcile stale rows on resync instead of only upserting
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2026-09-09 15:33:35 +02:00
13 changed files with 1043 additions and 24 deletions

View File

@@ -456,10 +456,21 @@ class KretaClient {
}
}
/// Upserts [caches]. Deletes stale rows in [staleScope].
Future<List<C>> _save<C extends GenericCacheModel<I>, I extends Identifiable>(
List<C> caches,
) async {
List<C> caches, [
QueryBuilder<C, C, QAfterFilterCondition>? 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<C>().deleteAllSync(staleIds);
}
isarInit.collection<C>().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<List<HomeworkCacheModel>> 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<List<LessonCacheModel>> 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<List<OmissionCacheModel>> 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<List<SubjectCacheModel>> getSubjects() async {

View File

@@ -290,12 +290,6 @@ extension StringExtension on String {
return regex.hasMatch(trim());
}
String firstUpper() {
if (isEmpty) return this;
if (length == 1) this[0].toUpperCase();
return this[0].toUpperCase() + substring(1, length);
}
String shortenName([int start = 0]) {
if (length <= 16 || start >= length) {
return this;

View File

@@ -244,7 +244,7 @@ Future<void> showLessonBottomSheet(
color: appStyle.colors.buttonSecondaryFill,
),
onTap: () {
context.go('/timetable/subject', extra: lesson.subject);
context.go('/timetable/subject', extra: lesson.subject.loadAndGet()!);
},
),
]);

View File

@@ -146,6 +146,7 @@ class _HomeMainScreen extends FirkaState<HomeMainScreen> {
final todayLesson = widget.data.client!.cache
.getClassLessons()
.on(now)
.sortByStart()
.findAllSync();
for (final item in infoItems) {

View File

@@ -62,6 +62,10 @@ class OmissionBar extends StatelessWidget {
.toList();
}
if (segmentColors.isEmpty) {
segmentColors.add(stateColor(null));
}
final bar = ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Row(

View File

@@ -2,7 +2,7 @@ name: firka
description: "Firka, Alternatív e-Kréta kliens."
publish_to: 'none'
version: 1.1.2+2001
version: 1.2.0+2001
environment:
sdk: ^3.11.0

View File

@@ -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<bool?> initialize(
InitializationSettings initializationSettings, {
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
void Function(NotificationResponse)?
onDidReceiveBackgroundNotificationResponse,
}) async => true;
@override
Future<List<ActiveNotification>> getActiveNotifications() async => [];
}
Future<TokenGrantResponse> _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<String, dynamic>,
);
}
Future<void> _resetMockServer(HttpClient httpClient) async {
final req = await httpClient.postUrl(
Uri.parse('$_mockServerUrl/admin/api/reset'),
);
final resp = await req.close();
await resp.drain();
}
Future<void> _putCollection(
HttpClient httpClient,
String endpoint,
List<Map<String, dynamic>> 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<String, dynamic> _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<String, dynamic> _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<String, dynamic> _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<String, dynamic> _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<void> 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',
);
});
},
);
});
}

View File

@@ -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<bool?> initialize(
InitializationSettings initializationSettings, {
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
void Function(NotificationResponse)?
onDidReceiveBackgroundNotificationResponse,
}) async => true;
@override
Future<List<ActiveNotification>> getActiveNotifications() async => [];
}
Future<TokenGrantResponse> _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<String, dynamic>,
);
}
Future<void> _resetMockServer(HttpClient httpClient) async {
final req = await httpClient.postUrl(
Uri.parse('$_mockServerUrl/admin/api/reset'),
);
final resp = await req.close();
await resp.drain();
}
Future<void> _putCollection(
HttpClient httpClient,
String endpoint,
List<Map<String, dynamic>> 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<String, dynamic> _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<String, dynamic> _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<LessonCacheModel> 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",
);
});
},
);
});
}

View File

@@ -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<bool?> initialize(
InitializationSettings initializationSettings, {
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
void Function(NotificationResponse)?
onDidReceiveBackgroundNotificationResponse,
}) async => true;
@override
Future<List<ActiveNotification>> getActiveNotifications() async => [];
}
Future<TokenGrantResponse> _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<String, dynamic>,
);
}
Future<void> _resetMockServer(HttpClient httpClient) async {
final req = await httpClient.postUrl(
Uri.parse('$_mockServerUrl/admin/api/reset'),
);
final resp = await req.close();
await resp.drain();
}
Future<void> _putTimetable(
HttpClient httpClient,
List<Map<String, dynamic>> 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<String, dynamic> _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<LessonCacheModel> 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',
);
});
},
);
});
}

View File

@@ -18,6 +18,14 @@ extension IterableExtension<T> on Iterable<T> {
}
}
extension FirstUpperExtension on String {
String firstUpper() {
if (isEmpty) return this;
if (length == 1) this[0].toUpperCase();
return this[0].toUpperCase() + substring(1, length);
}
}
extension MidnightExtension on DateTime {
DateTime getMidnight() {
return subtract(

View File

@@ -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<Omission> {
String? proofType;
final lesson = IsarLink<LessonCacheModel>();
final classGroup = IsarLink<ClassGroupCacheModel>();
@override
void apply(CacheContext<Omission> ctx) {
@@ -23,7 +25,8 @@ class OmissionCacheModel extends GenericCacheModel<Omission> {
..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)

View File

@@ -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<Test> {
@Backlink(to: "test")
final lesson = IsarLink<LessonCacheModel>();
final classGroup = IsarLink<ClassGroupCacheModel>();
@override
void apply(CacheContext<Test> ctx) {
@@ -21,6 +23,7 @@ class TestCacheModel extends GenericCacheModel<Test> {
..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);
}
}

View File

@@ -1,3 +1,4 @@
import 'package:firka_common/core/extensions.dart';
import 'package:firka_common/data/models/subject_cache_model.dart';
import 'package:flutter/material.dart';
@@ -34,7 +35,7 @@ class GradeSmallCard extends StatelessWidget {
),
Expanded(
child: Text(
subject.name,
subject.name.firstUpper(),
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),