LifeMate — Personal, Family & Learning Companion
feat: add in-app school library quizzes and explicit server setup
Quinn White committed
Oct 11, 2026 at 04:58 UTC
5be8a972517599ae455b1e4d9e3ff05a95caa3ed
29 files changed
+4105
-29
.github/workflows/ci.yml
+3
@@ -47,6 +47,9 @@ jobs:
47
- name: Apply migrations and verify repeat run
48
working-directory: backend
49
run: npm run migrate && npm run migrate
50
+ - name: Import checked educational metadata and verify repeat run
51
+ working-directory: backend
52
+ run: node scripts/import-learning-catalog.js && node scripts/import-learning-catalog.js
53
- name: SQL authorization matrix
54
run: |
55
for test in backend/tests/*schema_test.sql; do psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f "$test"; done
apps/lifemate/deploy/security-headers.inc
+1
-1
@@ -2,4 +2,4 @@ add_header X-Content-Type-Options nosniff always;
2
add_header Referrer-Policy no-referrer always;
3
add_header X-Frame-Options DENY always;
4
add_header Permissions-Policy 'camera=(), microphone=(), geolocation=()' always;
5
-add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'" always;
5
+add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; frame-src https://www.aparat.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'" always;
apps/lifemate/lib/aparat_player.dart
new
+138
@@ -0,0 +1,138 @@
1
+import 'package:flutter/material.dart';
2
+
3
+import 'aparat_player_native.dart'
4
+ if (dart.library.js_interop) 'aparat_player_web.dart' as platform;
5
+import 'aparat_player_policy.dart';
6
+import 'aparat_player_port.dart';
7
+
8
+export 'aparat_player_policy.dart';
9
+export 'aparat_player_port.dart';
10
+export 'aparat_player_fullscreen.dart';
11
+
12
+/// Click-to-load official Aparat frame. Frame readiness never records study
13
+/// progress, completion or evidence that a video was watched.
14
+class AparatPlayer extends StatefulWidget {
15
+ const AparatPlayer({super.key, required this.videoHash, required this.title});
16
+
17
+ final String videoHash;
18
+ final String title;
19
+
20
+ @override
21
+ State<AparatPlayer> createState() => _AparatPlayerState();
22
+}
23
+
24
+class _AparatPlayerState extends State<AparatPlayer>
25
+ with WidgetsBindingObserver {
26
+ bool _loaded = false;
27
+ String? _error;
28
+ int _attempt = 0;
29
+
30
+ @override
31
+ void initState() {
32
+ super.initState();
33
+ WidgetsBinding.instance.addObserver(this);
34
+ }
35
+
36
+ @override
37
+ void didUpdateWidget(AparatPlayer oldWidget) {
38
+ super.didUpdateWidget(oldWidget);
39
+ if (oldWidget.videoHash != widget.videoHash) {
40
+ _reset();
41
+ }
42
+ }
43
+
44
+ void _reset() {
45
+ _attempt++;
46
+ _loaded = false;
47
+ _error = null;
48
+ }
49
+
50
+ @override
51
+ void didChangeAppLifecycleState(AppLifecycleState state) {
52
+ if (_loaded &&
53
+ (state == AppLifecycleState.paused ||
54
+ state == AppLifecycleState.hidden ||
55
+ state == AppLifecycleState.detached)) {
56
+ setState(_reset);
57
+ }
58
+ }
59
+
60
+ @override
61
+ void dispose() {
62
+ WidgetsBinding.instance.removeObserver(this);
63
+ super.dispose();
64
+ }
65
+
66
+ @override
67
+ Widget build(BuildContext context) {
68
+ final uri = aparatEmbedUri(widget.videoHash);
69
+ final port = AparatPlayerPortScope.maybeOf(context) ??
70
+ platform.defaultAparatPlayerPort;
71
+ final attempt = _attempt;
72
+ return Directionality(
73
+ textDirection: TextDirection.rtl,
74
+ child: Card(
75
+ child: Padding(
76
+ padding: const EdgeInsets.all(16),
77
+ child: SingleChildScrollView(
78
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
79
+ Text(widget.title,
80
+ style: Theme.of(context).textTheme.titleMedium),
81
+ const SizedBox(height: 8),
82
+ const Text(
83
+ 'این ویدئو از سرویس آپارات بیرون از برنامه پخش میشود. با بارگذاری، '
84
+ 'نشانی اینترنتی دستگاه و اطلاعات فنی اتصال برای آپارات '
85
+ 'ارسال میشود؛ حریم خصوصی، کوکیها و تبلیغات تابع این سرویس '
86
+ 'است. اطلاعات حساب لایفگاید ارسال نمیشود.'),
87
+ const SizedBox(height: 12),
88
+ if (uri == null)
89
+ const Text('شناسهٔ ویدئو معتبر نیست؛ پخشکننده باز نشد.')
90
+ else if (_loaded) ...[
91
+ TextButton(
92
+ onPressed: () => setState(_reset),
93
+ child: const Text('بستن پخشکننده')),
94
+ AspectRatio(
95
+ aspectRatio: 16 / 9,
96
+ child: KeyedSubtree(
97
+ key: ValueKey('${widget.videoHash}:$attempt'),
98
+ child: port.buildFrame(context,
99
+ uri: uri,
100
+ title: widget.title,
101
+ onFrameReady: () {}, onError: (_) {
102
+ if (!mounted || attempt != _attempt) return;
103
+ setState(() {
104
+ _loaded = false;
105
+ _error = 'بارگذاری آپارات انجام نشد. اتصال '
106
+ 'اینترنت یا دسترسی به سرویس را بررسی کنید.';
107
+ });
108
+ }))),
109
+ ] else ...[
110
+ if (_error != null)
111
+ Padding(
112
+ padding: const EdgeInsets.only(bottom: 8),
113
+ child: Text(_error!,
114
+ style: TextStyle(
115
+ color: Theme.of(context).colorScheme.error))),
116
+ FilledButton.icon(
117
+ onPressed: () => setState(() {
118
+ if (!port.isSupported) {
119
+ _error = 'پخش در این نسخه پشتیبانی نمیشود؛ '
120
+ 'از نسخهٔ وب یا اندروید لایفگاید استفاده کنید.';
121
+ return;
122
+ }
123
+ _attempt++;
124
+ _error = null;
125
+ _loaded = true;
126
+ }),
127
+ icon: const Icon(Icons.play_circle_outline),
128
+ label: Text(_error == null
129
+ ? 'بارگذاری ویدئو از آپارات'
130
+ : 'تلاش دوباره')),
131
+ ],
132
+ const SizedBox(height: 8),
133
+ const Text(
134
+ 'پخش خودکار فعال نیست؛ برای پخش از دکمهٔ داخل قاب استفاده '
135
+ 'کنید. باز شدن قاب یا زمان ویدئو، اثبات مطالعه نیست.'),
136
+ ])))));
137
+ }
138
+}
apps/lifemate/lib/aparat_player_fullscreen.dart
new
+80
@@ -0,0 +1,80 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:flutter/scheduler.dart';
3
+
4
+/// Owns one native custom-view route. Provider hide events must never pop an
5
+/// unrelated app route, and a user Back/close must return the native view.
6
+class AparatFullscreenPresenter {
7
+ AparatFullscreenPresenter({required this.navigator});
8
+
9
+ final NavigatorState navigator;
10
+ Route<void>? _route;
11
+ VoidCallback? _returnNativeView;
12
+ bool _disposed = false;
13
+
14
+ void show(Widget view, VoidCallback returnNativeView) {
15
+ if (_disposed || !navigator.mounted) {
16
+ returnNativeView();
17
+ return;
18
+ }
19
+ _dismiss(notifyNative: true);
20
+ late final Route<void> route;
21
+ route = MaterialPageRoute<void>(
22
+ fullscreenDialog: true,
23
+ builder: (_) => Scaffold(
24
+ backgroundColor: Colors.black,
25
+ body: SafeArea(
26
+ child: Stack(fit: StackFit.expand, children: [
27
+ view,
28
+ Positioned(
29
+ top: 8,
30
+ right: 8,
31
+ child: IconButton.filled(
32
+ tooltip: 'خروج از تمامصفحه',
33
+ icon: const Icon(Icons.close),
34
+ onPressed: () {
35
+ if (_route == route) _dismiss(notifyNative: true);
36
+ }))
37
+ ]))));
38
+ _route = route;
39
+ _returnNativeView = returnNativeView;
40
+ navigator.push(route).then((_) {
41
+ // System Back already removed this route. A later provider hide cannot
42
+ // remove the app page beneath it.
43
+ if (_route != route) return;
44
+ final callback = _returnNativeView;
45
+ _route = null;
46
+ _returnNativeView = null;
47
+ callback?.call();
48
+ });
49
+ }
50
+
51
+ /// The provider has already hidden the native custom view.
52
+ void hide() => _dismiss(notifyNative: false);
53
+
54
+ void _dismiss({required bool notifyNative}) {
55
+ final route = _route;
56
+ final callback = _returnNativeView;
57
+ _route = null;
58
+ _returnNativeView = null;
59
+ if (notifyNative) callback?.call();
60
+ if (route == null) return;
61
+ void removeOwnedRoute() {
62
+ if (navigator.mounted && route.isActive) navigator.removeRoute(route);
63
+ }
64
+
65
+ // View disposal can happen during a build/lifecycle update. Route removal
66
+ // then waits for that frame, while ownership is revoked immediately.
67
+ final phase = SchedulerBinding.instance.schedulerPhase;
68
+ if (phase == SchedulerPhase.persistentCallbacks ||
69
+ phase == SchedulerPhase.midFrameMicrotasks) {
70
+ WidgetsBinding.instance.addPostFrameCallback((_) => removeOwnedRoute());
71
+ } else {
72
+ removeOwnedRoute();
73
+ }
74
+ }
75
+
76
+ void dispose() {
77
+ _disposed = true;
78
+ _dismiss(notifyNative: true);
79
+ }
80
+}
apps/lifemate/lib/aparat_player_native.dart
new
+145
@@ -0,0 +1,145 @@
1
+import 'dart:async';
2
+
3
+import 'package:flutter/foundation.dart';
4
+import 'package:flutter/material.dart';
5
+import 'package:webview_flutter/webview_flutter.dart';
6
+import 'package:webview_flutter_android/webview_flutter_android.dart';
7
+
8
+import 'aparat_player_policy.dart';
9
+import 'aparat_player_port.dart';
10
+import 'aparat_player_fullscreen.dart';
11
+
12
+const AparatPlayerPort defaultAparatPlayerPort = _NativePlayerPort();
13
+
14
+class _NativePlayerPort implements AparatPlayerPort {
15
+ const _NativePlayerPort();
16
+
17
+ @override
18
+ bool get isSupported =>
19
+ defaultTargetPlatform == TargetPlatform.android ||
20
+ defaultTargetPlatform == TargetPlatform.iOS;
21
+
22
+ @override
23
+ Widget buildFrame(BuildContext context,
24
+ {required Uri uri,
25
+ required String title,
26
+ required VoidCallback onFrameReady,
27
+ required ValueChanged<String> onError}) =>
28
+ _AparatWebView(uri: uri, onFrameReady: onFrameReady, onError: onError);
29
+}
30
+
31
+class _AparatWebView extends StatefulWidget {
32
+ const _AparatWebView(
33
+ {required this.uri, required this.onFrameReady, required this.onError});
34
+
35
+ final Uri uri;
36
+ final VoidCallback onFrameReady;
37
+ final ValueChanged<String> onError;
38
+
39
+ @override
40
+ State<_AparatWebView> createState() => _AparatWebViewState();
41
+}
42
+
43
+class _AparatWebViewState extends State<_AparatWebView> {
44
+ WebViewController? _controller;
45
+ Timer? _timeout;
46
+ bool _failed = false;
47
+ AparatFullscreenPresenter? _fullscreen;
48
+
49
+ @override
50
+ void initState() {
51
+ super.initState();
52
+ unawaited(_initialize());
53
+ }
54
+
55
+ void _fail(String code) {
56
+ if (!mounted || _failed) return;
57
+ _failed = true;
58
+ _timeout?.cancel();
59
+ widget.onError(code);
60
+ }
61
+
62
+ Future<void> _initialize() async {
63
+ try {
64
+ final hash = widget.uri.pathSegments[4];
65
+ if (!isAllowedAparatNavigation(widget.uri.toString(), hash)) {
66
+ _fail('invalid_frame_address');
67
+ return;
68
+ }
69
+ final controller = WebViewController(
70
+ onPermissionRequest: (request) => unawaited(request.deny()));
71
+ _controller = controller;
72
+ await controller.setJavaScriptMode(JavaScriptMode.unrestricted);
73
+ if (controller.platform is AndroidWebViewController) {
74
+ final android = controller.platform as AndroidWebViewController;
75
+ await android.setMediaPlaybackRequiresUserGesture(true);
76
+ await android.setGeolocationEnabled(false);
77
+ await android.setMixedContentMode(MixedContentMode.neverAllow);
78
+ final cookies = WebViewCookieManager();
79
+ await (cookies.platform as AndroidWebViewCookieManager)
80
+ .setAcceptThirdPartyCookies(android, false);
81
+ await android.setCustomWidgetCallbacks(
82
+ onShowCustomWidget: (view, returnNativeView) {
83
+ if (!mounted) {
84
+ returnNativeView();
85
+ return;
86
+ }
87
+ _fullscreen ??=
88
+ AparatFullscreenPresenter(navigator: Navigator.of(context));
89
+ _fullscreen!.show(view, returnNativeView);
90
+ },
91
+ onHideCustomWidget: () => _fullscreen?.hide());
92
+ }
93
+ await controller.setNavigationDelegate(NavigationDelegate(
94
+ onNavigationRequest: (request) => !request.isMainFrame ||
95
+ isAllowedAparatNavigation(request.url, hash)
96
+ ? NavigationDecision.navigate
97
+ : NavigationDecision.prevent,
98
+ onPageFinished: (url) {
99
+ if (!mounted || _failed || !isAllowedAparatNavigation(url, hash)) {
100
+ return;
101
+ }
102
+ _timeout?.cancel();
103
+ widget.onFrameReady();
104
+ },
105
+ onWebResourceError: (error) {
106
+ if (error.isForMainFrame == true ||
107
+ (error.isForMainFrame == null &&
108
+ error.url == widget.uri.toString())) {
109
+ _fail('frame_load_failed');
110
+ }
111
+ },
112
+ onHttpError: (error) {
113
+ if (error.request?.uri == widget.uri) {
114
+ _fail('frame_http_error');
115
+ }
116
+ },
117
+ onSslAuthError: (error) => unawaited(error.cancel())));
118
+ if (!mounted) return;
119
+ setState(() {});
120
+ _timeout =
121
+ Timer(const Duration(seconds: 30), () => _fail('frame_load_timeout'));
122
+ // This is the only controller-initiated remote load; no app headers,
123
+ // JavaScript bridge, cached auth or service-issued media URL is added.
124
+ await controller.loadRequest(widget.uri);
125
+ if (!mounted) await controller.loadHtmlString('');
126
+ } catch (_) {
127
+ _fail('frame_initialization_failed');
128
+ }
129
+ }
130
+
131
+ @override
132
+ Widget build(BuildContext context) => _controller == null
133
+ ? const Center(child: Text('در حال بارگذاری قاب آپارات…'))
134
+ : WebViewWidget(controller: _controller!);
135
+
136
+ @override
137
+ void dispose() {
138
+ _timeout?.cancel();
139
+ _fullscreen?.dispose();
140
+ // Blank the external document as the native platform view is removed.
141
+ // Controller loads are not navigation-delegate redirects.
142
+ unawaited(_controller?.loadHtmlString('').catchError((_) {}));
143
+ super.dispose();
144
+ }
145
+}
apps/lifemate/lib/aparat_player_policy.dart
new
+32
@@ -0,0 +1,32 @@
1
+/// The provider receives a public video hash only, never an application URL,
2
+/// token, account identifier or caller-supplied iframe markup.
3
+Uri? aparatEmbedUri(String videoHash) {
4
+ if (!RegExp(r'^[A-Za-z0-9]{5,64}$').hasMatch(videoHash) ||
5
+ videoHash.contains('\n') ||
6
+ videoHash.contains('\r')) {
7
+ return null;
8
+ }
9
+ return Uri.https(
10
+ 'www.aparat.com', '/video/video/embed/videohash/$videoHash/vt/frame');
11
+}
12
+
13
+bool isAllowedAparatNavigation(String address, String videoHash) {
14
+ // Uri normalizes percent-encoded unreserved characters; reject encodings
15
+ // before parsing so only the literal provider path can pass this boundary.
16
+ if (address.contains('%') ||
17
+ address.contains('\\') ||
18
+ address.trim() != address) {
19
+ return false;
20
+ }
21
+ final expected = aparatEmbedUri(videoHash);
22
+ final candidate = Uri.tryParse(address);
23
+ return expected != null &&
24
+ candidate != null &&
25
+ candidate.scheme == 'https' &&
26
+ (candidate.host == 'www.aparat.com' || candidate.host == 'aparat.com') &&
27
+ candidate.port == 443 &&
28
+ candidate.userInfo.isEmpty &&
29
+ !candidate.hasQuery &&
30
+ !candidate.hasFragment &&
31
+ candidate.path == expected.path;
32
+}
apps/lifemate/lib/aparat_player_port.dart
new
+27
@@ -0,0 +1,27 @@
1
+import 'package:flutter/widgets.dart';
2
+
3
+/// A platform boundary: only an already validated provider URI is passed here.
4
+/// Fixtures can replace the platform view without contacting a video service.
5
+abstract interface class AparatPlayerPort {
6
+ bool get isSupported;
7
+
8
+ Widget buildFrame(BuildContext context,
9
+ {required Uri uri,
10
+ required String title,
11
+ required VoidCallback onFrameReady,
12
+ required ValueChanged<String> onError});
13
+}
14
+
15
+class AparatPlayerPortScope extends InheritedWidget {
16
+ const AparatPlayerPortScope(
17
+ {super.key, required this.port, required super.child});
18
+
19
+ final AparatPlayerPort port;
20
+
21
+ static AparatPlayerPort? maybeOf(BuildContext context) =>
22
+ context.dependOnInheritedWidgetOfExactType<AparatPlayerPortScope>()?.port;
23
+
24
+ @override
25
+ bool updateShouldNotify(AparatPlayerPortScope oldWidget) =>
26
+ port != oldWidget.port;
27
+}
apps/lifemate/lib/aparat_player_web.dart
new
+89
@@ -0,0 +1,89 @@
1
+import 'dart:async';
2
+import 'dart:js_interop';
3
+
4
+import 'package:flutter/widgets.dart';
5
+import 'package:web/web.dart' as web;
6
+
7
+import 'aparat_player_port.dart';
8
+
9
+const AparatPlayerPort defaultAparatPlayerPort = _WebPlayerPort();
10
+
11
+class _WebPlayerPort implements AparatPlayerPort {
12
+ const _WebPlayerPort();
13
+
14
+ @override
15
+ bool get isSupported => true;
16
+
17
+ @override
18
+ Widget buildFrame(BuildContext context,
19
+ {required Uri uri,
20
+ required String title,
21
+ required VoidCallback onFrameReady,
22
+ required ValueChanged<String> onError}) =>
23
+ _AparatFrame(
24
+ uri: uri, title: title, onFrameReady: onFrameReady, onError: onError);
25
+}
26
+
27
+class _AparatFrame extends StatefulWidget {
28
+ const _AparatFrame(
29
+ {required this.uri,
30
+ required this.title,
31
+ required this.onFrameReady,
32
+ required this.onError});
33
+
34
+ final Uri uri;
35
+ final String title;
36
+ final VoidCallback onFrameReady;
37
+ final ValueChanged<String> onError;
38
+
39
+ @override
40
+ State<_AparatFrame> createState() => _AparatFrameState();
41
+}
42
+
43
+class _AparatFrameState extends State<_AparatFrame> {
44
+ web.HTMLIFrameElement? _frame;
45
+ Timer? _timeout;
46
+
47
+ @override
48
+ Widget build(BuildContext context) => HtmlElementView.fromTagName(
49
+ tagName: 'iframe',
50
+ onElementCreated: (element) {
51
+ final frame = element as web.HTMLIFrameElement;
52
+ _frame = frame;
53
+ // Set all restrictions before attachment and before assigning src.
54
+ frame.title = widget.title;
55
+ frame.referrerPolicy = 'no-referrer';
56
+ frame.setAttribute('sandbox', 'allow-scripts allow-same-origin');
57
+ frame.setAttribute('allow',
58
+ "fullscreen; autoplay 'none'; camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'");
59
+ frame.allowFullscreen = true;
60
+ frame.style
61
+ ..width = '100%'
62
+ ..height = '100%'
63
+ ..border = '0';
64
+ frame.onload = ((web.Event event) {
65
+ _timeout?.cancel();
66
+ if (mounted) widget.onFrameReady();
67
+ }).toJS;
68
+ frame.onerror = ((web.Event event) {
69
+ _timeout?.cancel();
70
+ if (mounted) widget.onError('frame_load_failed');
71
+ }).toJS;
72
+ _timeout = Timer(const Duration(seconds: 30), () {
73
+ if (mounted) widget.onError('frame_load_timeout');
74
+ });
75
+ frame.src = widget.uri.toString();
76
+ });
77
+
78
+ @override
79
+ void dispose() {
80
+ _timeout?.cancel();
81
+ final frame = _frame;
82
+ if (frame != null) {
83
+ frame.onload = null;
84
+ frame.onerror = null;
85
+ frame.remove();
86
+ }
87
+ super.dispose();
88
+ }
89
+}
apps/lifemate/lib/education_ui.dart
new
+709
@@ -0,0 +1,709 @@
1
+import 'dart:async';
2
+
3
+import 'package:flutter/material.dart';
4
+
5
+import 'api.dart';
6
+import 'aparat_player.dart';
7
+import 'learning_sync.dart';
8
+import 'learning_feedback_ui.dart';
9
+import 'learning_quiz_ui.dart';
10
+import 'offline_store.dart';
11
+import 'plan_sync.dart';
12
+import 'study_ui.dart';
13
+
14
+const learningTracks = <String, String>{
15
+ 'common': 'عمومی',
16
+ 'math': 'ریاضی و فیزیک',
17
+ 'experimental': 'علوم تجربی',
18
+ 'humanities': 'علوم انسانی',
19
+};
20
+const learningBookVariants = <String, String>{
21
+ 'standard': 'نسخه معمول',
22
+ 'experimental': 'نسخه آزمایشی',
23
+ 'religious_variant': 'نسخه دینی متفاوت',
24
+ 'gifted': 'استعدادهای درخشان',
25
+};
26
+
27
+bool isLearningAuthFailure(Object error) =>
28
+ error is ApiException &&
29
+ (error.statusCode == 401 || error.statusCode == 403);
30
+
31
+String learningError(Object error) {
32
+ if (isOfflineFailure(error)) return 'اتصال برقرار نیست؛ دوباره تلاش کن.';
33
+ if (error is ApiException) {
34
+ if (error.statusCode == 401 || error.statusCode == 403) {
35
+ return 'نشست معتبر لازم است؛ دوباره وارد حساب شو.';
36
+ }
37
+ if (error.statusCode == 409) {
38
+ return 'این درس یک تغییر معلق یا تعارض دارد؛ ابتدا وضعیت همگامسازی را بررسی کن.';
39
+ }
40
+ }
41
+ return 'عملیات تأیید نشد؛ داده را بررسی و دوباره تلاش کن.';
42
+}
43
+
44
+/// School is a selectable life context, never a role or permission grant.
45
+class EducationLibraryPage extends StatefulWidget {
46
+ const EducationLibraryPage({super.key, required this.api});
47
+ final IdentityApi api;
48
+ @override
49
+ State<EducationLibraryPage> createState() => _EducationLibraryPageState();
50
+}
51
+
52
+class _EducationLibraryPageState extends State<EducationLibraryPage> {
53
+ Map<String, dynamic>? library;
54
+ String? error;
55
+ String search = '';
56
+ bool busy = false, offline = false;
57
+ HttpIdentityApi? get api =>
58
+ widget.api is HttpIdentityApi ? widget.api as HttpIdentityApi : null;
59
+
60
+ @override
61
+ void initState() {
62
+ super.initState();
63
+ load();
64
+ }
65
+
66
+ Future<void> load() async {
67
+ if (api == null || busy) return;
68
+ setState(() => busy = true);
69
+ try {
70
+ final value = await api!.requestJson('GET', '/v1/education/library');
71
+ await OfflineStore.forApi(api!).writeList('education_library', [value]);
72
+ if (mounted) {
73
+ setState(() {
74
+ library = value;
75
+ error = null;
76
+ offline = false;
77
+ });
78
+ }
79
+ } catch (e) {
80
+ if (isLearningAuthFailure(e) && mounted) {
81
+ setState(() {
82
+ library = null;
83
+ offline = false;
84
+ });
85
+ }
86
+ if (isOfflineFailure(e)) {
87
+ try {
88
+ final cached =
89
+ await OfflineStore.forApi(api!).readList('education_library');
90
+ if (mounted && cached.isNotEmpty) {
91
+ setState(() {
92
+ library = cached.single;
93
+ offline = true;
94
+ });
95
+ }
96
+ } catch (storageError) {
97
+ if (mounted) setState(() => error = learningError(storageError));
98
+ return;
99
+ }
100
+ }
101
+ if (mounted) setState(() => error = learningError(e));
102
+ } finally {
103
+ if (mounted) setState(() => busy = false);
104
+ }
105
+ }
106
+
107
+ Future<void> editEducation() async {
108
+ if (api == null) return;
109
+ final education = library?['education'];
110
+ final saved = await showDialog<bool>(
111
+ context: context,
112
+ builder: (_) => _EducationDialog(
113
+ api: api!,
114
+ education: education is Map
115
+ ? Map<String, dynamic>.from(education)
116
+ : null));
117
+ if (saved == true) await load();
118
+ }
119
+
120
+ @override
121
+ Widget build(BuildContext context) {
122
+ if (api == null) {
123
+ return const Center(
124
+ child: Text('کتابخانه آموزشی به حساب و API واقعی نیاز دارد.'));
125
+ }
126
+ final education = library?['education'];
127
+ final courses = (library?['courses'] as List? ?? [])
128
+ .whereType<Map>()
129
+ .where((course) =>
130
+ search.isEmpty ||
131
+ '${course['titleFa']} ${course['bookCode']}'.contains(search))
132
+ .toList();
133
+ return ListView(padding: const EdgeInsets.all(16), children: [
134
+ Card(
135
+ child: Padding(
136
+ padding: const EdgeInsets.all(16),
137
+ child: Column(
138
+ crossAxisAlignment: CrossAxisAlignment.start,
139
+ children: [
140
+ Text('مدرسه من',
141
+ style: Theme.of(context).textTheme.headlineSmall),
142
+ const SizedBox(height: 8),
143
+ Text(education is Map
144
+ ? 'پایه ${education['nationalGrade']} · ${learningTracks[education['trackCode']] ?? 'رشته تعیین نشده'} · ${education['schoolYear'] ?? ''}'
145
+ : 'پایه تحصیلی را انتخاب کن تا کتابهای خودت نمایش داده شود.'),
146
+ const Text(
147
+ 'از هر درس میتوانی شروع کنی؛ تغییر پایه، برنامه و پیشرفت قبلی را پاک نمیکند.'),
148
+ TextButton.icon(
149
+ onPressed: busy ? null : editEducation,
150
+ icon: const Icon(Icons.school_outlined),
151
+ label: const Text('انتخاب پایه و رشته')),
152
+ ]))),
153
+ if (busy) const LinearProgressIndicator(),
154
+ if (error != null)
155
+ ListTile(
156
+ leading: const Icon(Icons.info_outline),
157
+ title: Text(error!),
158
+ trailing:
159
+ TextButton(onPressed: load, child: const Text('تازهسازی'))),
160
+ if (offline)
161
+ const Text('فهرست ذخیرهشده؛ اتصال و تازگی داده تأیید نشده است.'),
162
+ if (library?['fetchedAt'] != null)
163
+ Text('آخرین دریافت: ${library!['fetchedAt']}'),
164
+ TextField(
165
+ decoration: const InputDecoration(
166
+ labelText: 'جستجوی کتاب', prefixIcon: Icon(Icons.search)),
167
+ onChanged: (value) => setState(() => search = value.trim())),
168
+ TextButton.icon(
169
+ onPressed: () => Navigator.of(context).push(MaterialPageRoute(
170
+ builder: (_) => LearningFeedbackPage(api: api!))),
171
+ icon: const Icon(Icons.feedback_outlined),
172
+ label: const Text('بازخورد یا پیشنهاد آموزش')),
173
+ const SizedBox(height: 12),
174
+ if (!busy && courses.isEmpty)
175
+ const Padding(
176
+ padding: EdgeInsets.all(16),
177
+ child: Text('برای این انتخاب، آموزش ثبتشدهای پیدا نشد.')),
178
+ ...courses.map((course) => Card(
179
+ child: ListTile(
180
+ leading: const Icon(Icons.menu_book_outlined),
181
+ title: Text(course['titleFa']?.toString() ?? 'کتاب'),
182
+ subtitle: Text(
183
+ '${course['unitCount'] ?? 0} بخش فهرستشده · ${course['videoUnitCount'] ?? 0} بخش دارای ویدیو\n'
184
+ '${course['schoolYear'] ?? 'سال نسخه نامشخص'} · ${learningBookVariants[course['variant']] ?? 'نسخه نیازمند بررسی'}\n'
185
+ '${(course['unitCount'] ?? 0) == 0 ? 'آموزش این کتاب هنوز گردآوری نشده است.' : 'این شمارش، کاملبودن دوره یا کیفیت تدریس را تأیید نمیکند.'}'),
186
+ isThreeLine: true,
187
+ trailing: const Icon(Icons.chevron_left),
188
+ onTap: () => Navigator.of(context).push(MaterialPageRoute(
189
+ builder: (_) => LearningCoursePage(
190
+ api: api!, courseId: course['id'].toString())))))),
191
+ const Padding(
192
+ padding: EdgeInsets.symmetric(vertical: 16),
193
+ child: Text(
194
+ 'منابع پژوهش فعلی از آپاراتاند؛ تا بازبینی کامل تدریس و تطبیق با کتاب، پخش آموزشی منتشر نمیشود. پوشش همه کتابها و هنرستانها هنوز تکمیل نشده است.')),
195
+ ]);
196
+ }
197
+}
198
+
199
+class _EducationDialog extends StatefulWidget {
200
+ const _EducationDialog({required this.api, this.education});
201
+ final HttpIdentityApi api;
202
+ final Map<String, dynamic>? education;
203
+ @override
204
+ State<_EducationDialog> createState() => _EducationDialogState();
205
+}
206
+
207
+class _EducationDialogState extends State<_EducationDialog> {
208
+ int? grade;
209
+ String? track;
210
+ late final TextEditingController year;
211
+ bool busy = false;
212
+ String? error;
213
+ @override
214
+ void initState() {
215
+ super.initState();
216
+ grade = int.tryParse('${widget.education?['nationalGrade']}');
217
+ track = widget.education?['trackCode']?.toString();
218
+ year = TextEditingController(
219
+ text: widget.education?['schoolYear']?.toString() ?? '1405-1406');
220
+ }
221
+
222
+ @override
223
+ void dispose() {
224
+ year.dispose();
225
+ super.dispose();
226
+ }
227
+
228
+ Future<void> save() async {
229
+ if (grade == null || (grade! >= 10 && track == null)) {
230
+ setState(() => error = 'پایه و رشته را انتخاب کن.');
231
+ return;
232
+ }
233
+ setState(() => busy = true);
234
+ try {
235
+ await widget.api.requestJson('PUT', '/v1/me/education', body: {
236
+ 'nationalGrade': grade,
237
+ 'trackCode': grade! < 10 ? 'common' : track,
238
+ 'schoolYear': year.text.trim()
239
+ });
240
+ if (mounted) Navigator.pop(context, true);
241
+ } catch (e) {
242
+ if (mounted) setState(() => error = learningError(e));
243
+ } finally {
244
+ if (mounted) setState(() => busy = false);
245
+ }
246
+ }
247
+
248
+ @override
249
+ Widget build(BuildContext context) => AlertDialog(
250
+ title: const Text('پایه تحصیلی من'),
251
+ content: SingleChildScrollView(
252
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
253
+ DropdownButtonFormField<int>(
254
+ key: const ValueKey('education-grade'),
255
+ initialValue: grade,
256
+ decoration: const InputDecoration(labelText: 'پایه'),
257
+ items: List.generate(
258
+ 12,
259
+ (index) => DropdownMenuItem(
260
+ value: index + 1, child: Text('پایه ${index + 1}'))),
261
+ onChanged: busy
262
+ ? null
263
+ : (value) => setState(() {
264
+ grade = value;
265
+ if (grade! < 10) track = 'common';
266
+ if (grade! >= 10 && track == 'common') track = null;
267
+ })),
268
+ if ((grade ?? 0) >= 10)
269
+ DropdownButtonFormField<String>(
270
+ key: const ValueKey('education-track'),
271
+ initialValue: track == 'common' ? null : track,
272
+ decoration: const InputDecoration(labelText: 'رشته'),
273
+ items: learningTracks.entries
274
+ .where((entry) => entry.key != 'common')
275
+ .map((entry) => DropdownMenuItem(
276
+ value: entry.key, child: Text(entry.value)))
277
+ .toList(),
278
+ onChanged:
279
+ busy ? null : (value) => setState(() => track = value)),
280
+ TextField(
281
+ key: const ValueKey('education-year'),
282
+ controller: year,
283
+ enabled: !busy,
284
+ decoration: const InputDecoration(
285
+ labelText: 'سال تحصیلی، نمونه 1405-1406')),
286
+ if (error != null) Text(error!),
287
+ ])),
288
+ actions: [
289
+ TextButton(
290
+ onPressed: busy ? null : () => Navigator.pop(context),
291
+ child: const Text('انصراف')),
292
+ FilledButton(
293
+ onPressed: busy ? null : save, child: const Text('ذخیره'))
294
+ ]);
295
+}
296
+
297
+class LearningCoursePage extends StatefulWidget {
298
+ const LearningCoursePage(
299
+ {super.key, required this.api, required this.courseId});
300
+ final HttpIdentityApi api;
301
+ final String courseId;
302
+ @override
303
+ State<LearningCoursePage> createState() => _LearningCoursePageState();
304
+}
305
+
306
+class _LearningCoursePageState extends State<LearningCoursePage> {
307
+ late final LearningSync sync;
308
+ Map<String, dynamic>? course;
309
+ String? error;
310
+ String search = '';
311
+ bool busy = false;
312
+ Timer? poll;
313
+ @override
314
+ void initState() {
315
+ super.initState();
316
+ sync = LearningSync(widget.api);
317
+ load();
318
+ poll = Timer.periodic(
319
+ const Duration(seconds: 30), (_) => load(syncPending: true));
320
+ }
321
+
322
+ @override
323
+ void dispose() {
324
+ poll?.cancel();
325
+ super.dispose();
326
+ }
327
+
328
+ Future<void> load({bool syncPending = false}) async {
329
+ if (busy) return;
330
+ setState(() => busy = true);
331
+ try {
332
+ Object? syncError;
333
+ if (syncPending) {
334
+ try {
335
+ await sync.flush();
336
+ } catch (e) {
337
+ syncError = e;
338
+ }
339
+ }
340
+ final value = await sync.readCourse(widget.courseId);
341
+ if (mounted) {
342
+ setState(() {
343
+ course = value;
344
+ error = syncError == null ? null : learningError(syncError);
345
+ });
346
+ }
347
+ } catch (e) {
348
+ if (mounted) {
349
+ setState(() {
350
+ if (isLearningAuthFailure(e)) {
351
+ course = null;
352
+ }
353
+ error = learningError(e);
354
+ });
355
+ }
356
+ } finally {
357
+ if (mounted) setState(() => busy = false);
358
+ }
359
+ }
360
+
361
+ Future<void> openLesson(Map<String, dynamic> unit) async {
362
+ await Navigator.of(context).push(MaterialPageRoute(
363
+ builder: (_) => LearningLessonPage(
364
+ api: widget.api,
365
+ courseId: widget.courseId,
366
+ unitId: unit['id'].toString())));
367
+ if (mounted) await load();
368
+ }
369
+
370
+ @override
371
+ Widget build(BuildContext context) {
372
+ final units = (course?['units'] as List? ?? []).whereType<Map>().toList();
373
+ return Scaffold(
374
+ appBar: AppBar(
375
+ title: Text(course?['titleFa']?.toString() ?? 'درسها'),
376
+ actions: [
377
+ IconButton(onPressed: load, icon: const Icon(Icons.refresh))
378
+ ]),
379
+ body: ListView(padding: const EdgeInsets.all(16), children: [
380
+ if (busy) const LinearProgressIndicator(),
381
+ if (error != null) Text(error!),
382
+ if (course?['offline'] == true)
383
+ const Text(
384
+ 'آفلاین؛ فهرست ذخیرهشده و پیشرفت معلق ممکن است قدیمی باشد.'),
385
+ Text('نسخه کتاب: ${course?['schoolYear'] ?? 'نامشخص'}'),
386
+ if (course != null && course!['editionVerification'] != 'verified')
387
+ const Text(
388
+ 'نسخه و سال این کتاب هنوز از صفحه معتبر ناشر تأیید نشده است.'),
389
+ if ((course?['reviewCandidateCount'] as num? ?? 0) > 0)
390
+ Text(
391
+ '${course!['reviewCandidateCount']} منبع در انتظار بازبینی کامل؛ این منابع هنوز برای آموزش منتشر نشدهاند.'),
392
+ if (course?['alignmentNotesFa'] != null)
393
+ Text(course!['alignmentNotesFa'].toString()),
394
+ const Text(
395
+ 'میتوانی از هر بخش شروع کنی. پیشرفت، گزارش خودت است و اثبات یادگیری نیست.'),
396
+ TextField(
397
+ decoration:
398
+ const InputDecoration(labelText: 'جستجوی درس یا صفحه'),
399
+ onChanged: (value) => setState(() => search = value.trim())),
400
+ if (!busy && units.isEmpty)
401
+ const Text('ویدیوی منطبق برای این کتاب هنوز ثبت نشده است.'),
402
+ ...units
403
+ .where(
404
+ (u) => search.isEmpty || '${u['titleFa']}'.contains(search))
405
+ .map((u) {
406
+ final progress = u['progress'];
407
+ final pending = progress is Map && progress['pending_sync'] == true;
408
+ return Card(
409
+ child: ListTile(
410
+ leading: Icon(
411
+ progress is Map && progress['status'] == 'completed'
412
+ ? Icons.check_circle_outline
413
+ : Icons.play_lesson_outlined),
414
+ title: Text(u['titleFa']?.toString() ?? 'درس'),
415
+ subtitle: Text(
416
+ '${(u['videos'] as List? ?? []).length} منبع منتشرشده · ${u['reviewCandidateCount'] ?? 0} نامزد بازبینی${pending ? ' · تغییر ارسالنشده' : ''}'),
417
+ trailing: const Icon(Icons.chevron_left),
418
+ onTap: () => openLesson(Map<String, dynamic>.from(u))));
419
+ }),
420
+ ]));
421
+ }
422
+}
423
+
424
+class LearningLessonPage extends StatefulWidget {
425
+ const LearningLessonPage(
426
+ {super.key,
427
+ required this.api,
428
+ required this.courseId,
429
+ required this.unitId});
430
+ final HttpIdentityApi api;
431
+ final String courseId, unitId;
432
+ @override
433
+ State<LearningLessonPage> createState() => _LearningLessonPageState();
434
+}
435
+
436
+class _LearningLessonPageState extends State<LearningLessonPage> {
437
+ late final LearningSync sync;
438
+ Map<String, dynamic>? course, unit;
439
+ String? error;
440
+ bool busy = false;
441
+ int videoIndex = 0;
442
+ @override
443
+ void initState() {
444
+ super.initState();
445
+ sync = LearningSync(widget.api);
446
+ load();
447
+ }
448
+
449
+ Future<void> load({bool syncPending = false}) async {
450
+ if (busy) return;
451
+ setState(() => busy = true);
452
+ try {
453
+ Object? syncError;
454
+ if (syncPending) {
455
+ try {
456
+ await sync.flush();
457
+ } catch (e) {
458
+ syncError = e;
459
+ }
460
+ }
461
+ final value = await sync.readCourse(widget.courseId);
462
+ final units = (value['units'] as List).whereType<Map>();
463
+ final found = units.where((u) => u['id'] == widget.unitId).firstOrNull;
464
+ if (found == null) {
465
+ throw const ApiException(404, 'learning_unit_not_found');
466
+ }
467
+ if (mounted) {
468
+ setState(() {
469
+ course = value;
470
+ unit = Map<String, dynamic>.from(found);
471
+ error = syncError == null ? null : learningError(syncError);
472
+ });
473
+ }
474
+ } catch (e) {
475
+ if (mounted) {
476
+ setState(() {
477
+ if (isLearningAuthFailure(e)) {
478
+ course = null;
479
+ unit = null;
480
+ }
481
+ error = learningError(e);
482
+ });
483
+ }
484
+ } finally {
485
+ if (mounted) setState(() => busy = false);
486
+ }
487
+ }
488
+
489
+ Future<void> progress(String status) async {
490
+ if (busy || unit == null) return;
491
+ setState(() => busy = true);
492
+ Object? mutationError;
493
+ try {
494
+ final old = unit!['progress'];
495
+ await sync.setProgress(widget.unitId, status,
496
+ old is Map ? int.tryParse('${old['version']}') ?? 0 : 0);
497
+ if (mounted) setState(() => error = null);
498
+ } catch (e) {
499
+ mutationError = e;
500
+ } finally {
501
+ if (mounted) setState(() => busy = false);
502
+ }
503
+ if (mounted &&
504
+ (mutationError == null || !isLearningAuthFailure(mutationError))) {
505
+ await load();
506
+ }
507
+ if (mounted && mutationError != null) {
508
+ setState(() {
509
+ if (isLearningAuthFailure(mutationError!)) {
510
+ course = null;
511
+ unit = null;
512
+ }
513
+ error = learningError(mutationError);
514
+ });
515
+ }
516
+ }
517
+
518
+ Future<void> resolve() async {
519
+ final accept = await showDialog<bool>(
520
+ context: context,
521
+ builder: (_) => AlertDialog(
522
+ title: const Text('استفاده از پیشرفت سرور؟'),
523
+ content: const Text(
524
+ 'تغییر معلق در سابقه بازیابی نگه داشته میشود و پیشرفت فعلی سرور نمایش داده خواهد شد.'),
525
+ actions: [
526
+ TextButton(
527
+ onPressed: () => Navigator.pop(context, false),
528
+ child: const Text('انصراف')),
529
+ FilledButton(
530
+ onPressed: () => Navigator.pop(context, true),
531
+ child: const Text('استفاده از سرور'))
532
+ ]));
533
+ if (accept != true || !mounted) return;
534
+ try {
535
+ await sync.resolveUsingServer(widget.unitId);
536
+ if (mounted) await load();
537
+ } catch (e) {
538
+ if (mounted) setState(() => error = learningError(e));
539
+ }
540
+ }
541
+
542
+ Future<void> plan() async {
543
+ if (busy || unit == null) return;
544
+ final date = await showDatePicker(
545
+ context: context,
546
+ initialDate: DateTime.now(),
547
+ firstDate: DateTime.now().subtract(const Duration(days: 1)),
548
+ lastDate: DateTime.now().add(const Duration(days: 730)));
549
+ if (date == null || !mounted) return;
550
+ final minutes = await showDialog<int>(
551
+ context: context,
552
+ builder: (_) => SimpleDialog(
553
+ title: const Text('زمان برنامهریزیشده'),
554
+ children: [15, 30, 45, 60]
555
+ .map((m) => SimpleDialogOption(
556
+ onPressed: () => Navigator.pop(context, m),
557
+ child: Text('$m دقیقه')))
558
+ .toList()));
559
+ if (minutes == null || !mounted) return;
560
+ setState(() => busy = true);
561
+ try {
562
+ final outcome = await PlanSync(widget.api).create({
563
+ 'kind': 'study_session',
564
+ 'title': '${course?['titleFa']} · ${unit!['titleFa']}',
565
+ 'learningUnitId': widget.unitId,
566
+ 'visibility': 'private',
567
+ 'startsAt': DateTime(date.year, date.month, date.day,
568
+ DateTime.now().hour, DateTime.now().minute)
569
+ .toUtc()
570
+ .toIso8601String(),
571
+ 'plannedDurationSeconds': minutes * 60,
572
+ });
573
+ if (!mounted) return;
574
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
575
+ content: Text(outcome.queued
576
+ ? 'برنامه روی دستگاه ثبت شد؛ تأیید سرور هنوز دریافت نشده است.'
577
+ : 'برنامه در سرور ثبت و تأیید شد.')));
578
+ if (!outcome.queued && outcome.item != null) {
579
+ await Navigator.of(context).push(MaterialPageRoute(
580
+ builder: (_) =>
581
+ StudyTimerPage(api: widget.api, item: outcome.item!)));
582
+ }
583
+ } catch (e) {
584
+ if (mounted) setState(() => error = learningError(e));
585
+ } finally {
586
+ if (mounted) setState(() => busy = false);
587
+ }
588
+ }
589
+
590
+ @override
591
+ Widget build(BuildContext context) {
592
+ final videos = (unit?['videos'] as List? ?? []).whereType<Map>().toList();
593
+ final video =
594
+ videos.isEmpty ? null : videos[videoIndex.clamp(0, videos.length - 1)];
595
+ final current = unit?['progress'];
596
+ final pending = current is Map && current['pending_sync'] == true;
597
+ final conflict = current is Map && current['queueStatus'] == 'conflict';
598
+ final units = (course?['units'] as List? ?? []).whereType<Map>().toList();
599
+ final index = units.indexWhere((u) => u['id'] == widget.unitId);
600
+ void move(int to) =>
601
+ Navigator.of(context).pushReplacement(MaterialPageRoute(
602
+ builder: (_) => LearningLessonPage(
603
+ api: widget.api,
604
+ courseId: widget.courseId,
605
+ unitId: units[to]['id'].toString())));
606
+ return Scaffold(
607
+ appBar:
608
+ AppBar(title: Text(unit?['titleFa']?.toString() ?? 'آموزش درس')),
609
+ body: ListView(padding: const EdgeInsets.all(16), children: [
610
+ if (busy) const LinearProgressIndicator(),
611
+ if (error != null) Text(error!),
612
+ Text(course?['titleFa']?.toString() ?? ''),
613
+ if (course?['offline'] == true)
614
+ const Text('آفلاین؛ پخش ویدیو نیاز به اینترنت دارد.'),
615
+ if (video != null && video['freeAccess'] != false) ...[
616
+ AparatPlayer(
617
+ key: ValueKey(video['aparatId']),
618
+ videoHash: video['aparatId'].toString(),
619
+ title: video['titleFa']?.toString() ?? 'آموزش'),
620
+ Text('مدرس: ${video['creatorName'] ?? 'نام تأیید نشده'}'),
621
+ SelectableText(video['creatorUrl']?.toString() ?? ''),
622
+ Text(video['qualityNotesFa']?.toString() ??
623
+ 'بازبینی کامل کیفیت تدریس انجام نشده است.'),
624
+ if (video['freeAccess'] == null)
625
+ const Text('رایگانبودن و دسترسی فعلی این منبع تأیید نشده است.'),
626
+ const Text(
627
+ 'نمایش ویدیو، یادگیری یا تکمیل درس را خودکار ثبت نمیکند.'),
628
+ ] else
629
+ const Text(
630
+ 'برای این بخش، ویدیوی بازبینیشده و منتشرشده هنوز ثبت نشده است.'),
631
+ if (videos.length > 1)
632
+ Wrap(
633
+ spacing: 8,
634
+ children: List.generate(
635
+ videos.length,
636
+ (i) => ChoiceChip(
637
+ label: Text('منبع ${i + 1}'),
638
+ selected: videoIndex == i,
639
+ onSelected: (_) => setState(() => videoIndex = i)))),
640
+ const Divider(),
641
+ OutlinedButton.icon(
642
+ onPressed: unit == null
643
+ ? null
644
+ : () => Navigator.of(context).push(MaterialPageRoute(
645
+ builder: (_) => LearningQuizPage(
646
+ api: widget.api, unitId: widget.unitId))),
647
+ icon: const Icon(Icons.quiz_outlined),
648
+ label: const Text('تمرین فهم درس و مرور')),
649
+ TextButton.icon(
650
+ onPressed: unit == null
651
+ ? null
652
+ : () => Navigator.of(context).push(MaterialPageRoute(
653
+ builder: (_) => LearningFeedbackPage(
654
+ api: widget.api, unitId: widget.unitId))),
655
+ icon: const Icon(Icons.feedback_outlined),
656
+ label: const Text('گزارش ایراد این درس')),
657
+ Text('پیشرفت شخصی: ${current is Map ? {
658
+ 'not_started': 'شروع نشده',
659
+ 'in_progress': 'در حال یادگیری',
660
+ 'completed': 'تکمیل طبق گزارش من'
661
+ }[current['status']] ?? 'نامشخص' : 'شروع نشده'}'),
662
+ if (pending)
663
+ const Text(
664
+ 'تغییر روی دستگاه ذخیره شده؛ تأیید سرور دریافت نشده است.'),
665
+ if (current is Map && current['updatedAt'] != null)
666
+ Text('آخرین ثبت سرور: ${current['updatedAt']}'),
667
+ if (conflict)
668
+ TextButton(
669
+ onPressed: busy ? null : resolve,
670
+ child: const Text('حل تعارض با پیشرفت سرور')),
671
+ Wrap(spacing: 8, children: [
672
+ TextButton(
673
+ onPressed: busy || pending || unit == null
674
+ ? null
675
+ : () => progress('not_started'),
676
+ child: const Text('شروع نشده')),
677
+ OutlinedButton(
678
+ onPressed: busy || pending || unit == null
679
+ ? null
680
+ : () => progress('in_progress'),
681
+ child: const Text('در حال یادگیری')),
682
+ FilledButton(
683
+ onPressed: busy || pending || unit == null
684
+ ? null
685
+ : () => progress('completed'),
686
+ child: const Text('طبق گزارش من تکمیل شد')),
687
+ ]),
688
+ FilledButton.tonalIcon(
689
+ onPressed: busy || unit == null ? null : plan,
690
+ icon: const Icon(Icons.event_note_outlined),
691
+ label: const Text('افزودن درس به برنامه و تایمر')),
692
+ const Text(
693
+ 'برنامه بهصورت خصوصی ایجاد میشود؛ اشتراک با خانواده از تنظیمات برنامهریز انجام میشود.'),
694
+ TextButton(
695
+ onPressed: busy ? null : () => load(syncPending: true),
696
+ child: const Text('همگامسازی و تازهسازی')),
697
+ Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
698
+ TextButton(
699
+ onPressed: index > 0 ? () => move(index - 1) : null,
700
+ child: const Text('بخش قبلی')),
701
+ TextButton(
702
+ onPressed: index >= 0 && index + 1 < units.length
703
+ ? () => move(index + 1)
704
+ : null,
705
+ child: const Text('بخش بعدی')),
706
+ ]),
707
+ ]));
708
+ }
709
+}
apps/lifemate/lib/endpoint_settings.dart
+32
-4
@@ -79,20 +79,46 @@ class _EndpointSettingsState extends State<EndpointSettingsPage> {
79
child: Column(
80
crossAxisAlignment: CrossAxisAlignment.stretch,
81
children: [
82
+ Text(
83
+ widget.initialConfig.isConfigured
84
+ ? 'تنظیم اتصال'
85
+ : 'راهاندازی نسخه آزمایشی',
86
+ style:
87
+ Theme.of(context).textTheme.headlineSmall),
88
+ const SizedBox(height: 12),
89
const Text(
83
- 'نشانی سرویس خانواده را وارد کنید. تغییر سرویس شما را از حساب قبلی خارج میکند.'),
90
+ 'این نسخه به سرور مشترک خانواده متصل میشود. نشانی کامل API را فقط مطابق راهنمای مدیر سرویس وارد کنید؛ آدرس وبسایت بهتنهایی ممکن است نشانی اتصال نباشد.'),
91
+ const SizedBox(height: 12),
92
+ if (!widget.initialConfig.isConfigured) ...[
93
+ const Text(
94
+ 'بدون نشانی یک سرویس فعال و سازگار، ورود و همگامسازی در دسترس نیست. اگر هنوز نشانی تأییدشدهای دریافت نکردهاید، لازم نیست چیزی وارد کنید.'),
95
+ const SizedBox(height: 12),
96
+ ],
97
+ const Text(
98
+ 'این کادر فقط نشانی اتصال میخواهد؛ رمز عبور، کلید یا توکن وارد نکنید.'),
99
+ const SizedBox(height: 12),
100
+ const Text(
101
+ 'نشانی در همین دستگاه ذخیره میشود و در بازکردن بعدی لازم نیست دوباره آن را وارد کنید. ذخیره نشانی به معنی برقرارشدن اتصال نیست؛ اتصال هنگام ورود بررسی میشود.'),
102
+ if (widget.initialConfig.isConfigured) ...[
103
+ const SizedBox(height: 12),
104
+ const Text(
105
+ 'تغییر سرویس شما را از حساب قبلی خارج میکند. پیش از تغییر، دادههای ارسالنشده را با سرویس قبلی همگام کنید؛ با تأیید تغییر، دادههای محلی آن حساب کنار گذاشته میشوند.'),
106
+ ],
107
const SizedBox(height: 16),
108
TextField(
109
controller: primary,
110
+ enabled: !busy,
111
+ onChanged: (_) => setState(() => error = null),
112
textDirection: TextDirection.ltr,
113
keyboardType: TextInputType.url,
114
autocorrect: false,
115
decoration: const InputDecoration(
91
- labelText: 'نشانی اصلی',
92
- hintText: 'https://…')),
116
+ labelText: 'نشانی اتصال API',
117
+ hintText: 'https://…/api')),
118
const SizedBox(height: 16),
119
TextField(
120
controller: fallback,
121
+ enabled: !busy,
122
textDirection: TextDirection.ltr,
123
maxLines: 4,
124
autocorrect: false,
@@ -121,7 +147,9 @@ class _EndpointSettingsState extends State<EndpointSettingsPage> {
147
.error))),
148
const SizedBox(height: 20),
149
FilledButton(
124
- onPressed: busy ? null : save,
150
+ onPressed: busy || primary.text.trim().isEmpty
151
+ ? null
152
+ : save,
153
child: Text(
154
busy ? 'در حال ذخیره…' : 'ذخیره و ادامه')),
155
])),
apps/lifemate/lib/learning_feedback_ui.dart
new
+317
@@ -0,0 +1,317 @@
1
+import 'dart:convert';
2
+
3
+import 'package:flutter/material.dart';
4
+
5
+import 'api.dart';
6
+import 'offline_store.dart';
7
+import 'plan_sync.dart' show newMutationId;
8
+import 'education_ui.dart' show learningError;
9
+
10
+const feedbackCategories = {
11
+ 'inaccurate': 'اشتباه آموزشی',
12
+ 'edition_mismatch': 'تفاوت با کتاب درسی',
13
+ 'broken_video': 'اشکال پخش ویدیو',
14
+ 'unclear': 'توضیح نامفهوم',
15
+ 'topic_request': 'پیشنهاد موضوع آموزشی',
16
+};
17
+
18
+/// Explicitly chosen feedback only; never extracts private conversations.
19
+class LearningFeedbackSync {
20
+ LearningFeedbackSync(this.api, {OfflineStore? store})
21
+ : store = store ?? OfflineStore.forApi(api);
22
+ final HttpIdentityApi api;
23
+ final OfflineStore store;
24
+
25
+ Future<Map<String, dynamic>> submit(Map<String, dynamic> body) async {
26
+ final frozen =
27
+ Map<String, dynamic>.from(jsonDecode(jsonEncode(body)) as Map);
28
+ final mutationId = frozen['mutationId'] as String;
29
+ await store.enqueue({
30
+ 'id': mutationId,
31
+ 'entityId': mutationId,
32
+ 'entityType': 'learning_feedback',
33
+ 'operation': 'create',
34
+ 'payload': frozen,
35
+ });
36
+ try {
37
+ return await _send(mutationId, frozen);
38
+ } catch (e) {
39
+ if (isOfflineFailure(e)) return {'queued': true};
40
+ rethrow;
41
+ }
42
+ }
43
+
44
+ Future<Map<String, dynamic>> _send(
45
+ String mutationId, Map<String, dynamic> body) async {
46
+ if (api.cacheNamespace != store.scope) {
47
+ throw const ApiException(401, 'cache_scope_closed');
48
+ }
49
+ await store.readQueue();
50
+ final result =
51
+ await api.requestJson('POST', '/v1/education/feedback', body: body);
52
+ if (api.cacheNamespace != store.scope) {
53
+ throw const ApiException(401, 'cache_scope_closed');
54
+ }
55
+ final acknowledgement = result['acknowledgement'];
56
+ final feedback = result['feedback'];
57
+ final uuid =
58
+ RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$');
59
+ bool date(dynamic value) =>
60
+ value is String && DateTime.tryParse(value) != null;
61
+ if (acknowledgement is! Map ||
62
+ feedback is! Map ||
63
+ acknowledgement['mutationId'] != mutationId ||
64
+ !['accepted', 'already_applied'].contains(acknowledgement['status']) ||
65
+ feedback['mutationId'] != mutationId ||
66
+ feedback['id'] is! String ||
67
+ !uuid.hasMatch(feedback['id'] as String) ||
68
+ feedback['unitId'] != body['unitId'] ||
69
+ feedback['category'] != body['category'] ||
70
+ feedback['version'] is! int ||
71
+ feedback['version'] < 1 ||
72
+ !['received', 'triaged', 'planned', 'released', 'declined']
73
+ .contains(feedback['status']) ||
74
+ (feedback['withdrawnAt'] == null
75
+ ? (feedback['summary'] != body['summary'] ||
76
+ feedback['shareWithContentTeam'] != true)
77
+ : (!date(feedback['withdrawnAt']) ||
78
+ feedback['summary'] != null ||
79
+ feedback['shareWithContentTeam'] != false)) ||
80
+ acknowledgement['feedbackId'] != feedback['id'] ||
81
+ !date(feedback['createdAt']) ||
82
+ !date(feedback['updatedAt'])) {
83
+ throw const ApiException(502, 'invalid_sync_acknowledgement');
84
+ }
85
+ // The chosen summary remains in the durable queue until acknowledged;
86
+ // do not retain an extra offline copy after server acceptance/withdrawal.
87
+ await store.acknowledge(mutationId,
88
+ acceptedAt: feedback['createdAt'] as String);
89
+ return {'queued': false, 'feedback': feedback};
90
+ }
91
+
92
+ Future<void> flush() async {
93
+ for (final pending in await store.readQueue()) {
94
+ if (pending['entityType'] != 'learning_feedback' ||
95
+ pending['queueStatus'] != 'queued') {
96
+ continue;
97
+ }
98
+ try {
99
+ await _send(pending['id'] as String,
100
+ Map<String, dynamic>.from(pending['payload'] as Map));
101
+ } catch (e) {
102
+ if (isOfflineFailure(e)) return;
103
+ rethrow;
104
+ }
105
+ }
106
+ }
107
+}
108
+
109
+class LearningFeedbackPage extends StatefulWidget {
110
+ const LearningFeedbackPage({super.key, required this.api, this.unitId});
111
+ final HttpIdentityApi api;
112
+ final String? unitId;
113
+ @override
114
+ State<LearningFeedbackPage> createState() => _LearningFeedbackPageState();
115
+}
116
+
117
+class _LearningFeedbackPageState extends State<LearningFeedbackPage> {
118
+ final summary = TextEditingController();
119
+ String category = 'topic_request';
120
+ bool consent = false, busy = false;
121
+ String? message;
122
+ Map<String, dynamic>? pendingBody;
123
+ List<Map<String, dynamic>> history = [];
124
+ int historyEpoch = 0;
125
+ late final LearningFeedbackSync sync;
126
+ @override
127
+ void initState() {
128
+ super.initState();
129
+ sync = LearningFeedbackSync(widget.api);
130
+ restoreDraft();
131
+ loadHistory();
132
+ }
133
+
134
+ Future<void> loadHistory() async {
135
+ final epoch = ++historyEpoch;
136
+ try {
137
+ final result =
138
+ await widget.api.requestJson('GET', '/v1/me/education-feedback');
139
+ if (result['feedback'] is! List) {
140
+ throw const ApiException(502, 'invalid_api_response');
141
+ }
142
+ if (mounted &&
143
+ epoch == historyEpoch &&
144
+ widget.api.cacheNamespace == sync.store.scope) {
145
+ setState(() => history = (result['feedback'] as List)
146
+ .map((row) => Map<String, dynamic>.from(row as Map))
147
+ .toList());
148
+ }
149
+ } catch (e) {
150
+ if (mounted && epoch == historyEpoch) {
151
+ setState(() {
152
+ if (e is ApiException &&
153
+ (e.statusCode == 401 || e.statusCode == 403)) {
154
+ history = [];
155
+ }
156
+ message = learningError(e);
157
+ });
158
+ }
159
+ }
160
+ }
161
+
162
+ Future<void> withdraw(String id) async {
163
+ if (busy) return;
164
+ ++historyEpoch; // Earlier reads must not resurrect a withdrawn summary.
165
+ setState(() => busy = true);
166
+ try {
167
+ await widget.api.requestJson(
168
+ 'DELETE', '/v1/me/education-feedback/${Uri.encodeComponent(id)}');
169
+ if (mounted) {
170
+ setState(() => history.removeWhere((row) => row['id'] == id));
171
+ }
172
+ // Clear any acknowledged feedback cache from an earlier test build.
173
+ await sync.store.writeList('education_feedback', []);
174
+ if (mounted) await loadHistory();
175
+ } catch (e) {
176
+ if (mounted) setState(() => message = learningError(e));
177
+ } finally {
178
+ if (mounted) setState(() => busy = false);
179
+ }
180
+ }
181
+
182
+ Future<void> restoreDraft() async {
183
+ try {
184
+ final pending = (await sync.store.readQueue())
185
+ .where((m) =>
186
+ m['entityType'] == 'learning_feedback' &&
187
+ (m['payload'] as Map)['unitId'] == widget.unitId)
188
+ .firstOrNull;
189
+ if (pending != null && mounted) {
190
+ setState(() {
191
+ pendingBody = Map<String, dynamic>.from(pending['payload'] as Map);
192
+ summary.text = pendingBody!['summary'].toString();
193
+ category = pendingBody!['category'].toString();
194
+ consent = true;
195
+ message = 'بازخورد ارسالنشده روی این دستگاه نگه داشته شده است.';
196
+ });
197
+ }
198
+ } catch (e) {
199
+ if (mounted) setState(() => message = learningError(e));
200
+ }
201
+ }
202
+
203
+ @override
204
+ void dispose() {
205
+ summary.dispose();
206
+ super.dispose();
207
+ }
208
+
209
+ Future<void> send() async {
210
+ if (!consent || summary.text.trim().isEmpty) {
211
+ setState(() => message = 'خلاصه و رضایت ارسال را تکمیل کن.');
212
+ return;
213
+ }
214
+ setState(() => busy = true);
215
+ pendingBody ??= {
216
+ 'mutationId': newMutationId(),
217
+ 'unitId': widget.unitId,
218
+ 'category': category,
219
+ 'summary': summary.text.trim(),
220
+ 'shareWithContentTeam': true
221
+ };
222
+ try {
223
+ final result = await sync.submit(pendingBody!);
224
+ if (mounted) {
225
+ setState(() {
226
+ message = result['queued'] == true
227
+ ? 'روی دستگاه ذخیره شد؛ هنوز تأیید سرور دریافت نشده است.'
228
+ : 'بازخورد در سرور ثبت شد؛ بررسی و انتشار نتیجه هنوز انجام نشده است.';
229
+ if (result['queued'] != true) {
230
+ pendingBody = null;
231
+ summary.clear();
232
+ consent = false;
233
+ }
234
+ });
235
+ if (result['queued'] != true && mounted) await loadHistory();
236
+ }
237
+ } catch (e) {
238
+ if (mounted) setState(() => message = learningError(e));
239
+ } finally {
240
+ if (mounted) setState(() => busy = false);
241
+ }
242
+ }
243
+
244
+ @override
245
+ Widget build(BuildContext context) => Scaffold(
246
+ appBar: AppBar(title: const Text('بازخورد و پیشنهاد آموزش')),
247
+ body: ListView(padding: const EdgeInsets.all(16), children: [
248
+ const Text(
249
+ 'فقط ایراد محتوا یا نیاز آموزشی را بنویس. نام افراد، گفتوگوی خصوصی، اطلاعات سلامت یا شرح آزار را در بازخورد توسعه ننویس. این بخش مشاوره یا رسیدگی اضطراری نیست.'),
250
+ DropdownButtonFormField<String>(
251
+ initialValue: category,
252
+ items: feedbackCategories.entries
253
+ .map((entry) => DropdownMenuItem(
254
+ value: entry.key, child: Text(entry.value)))
255
+ .toList(),
256
+ onChanged: busy || pendingBody != null
257
+ ? null
258
+ : (value) => setState(() => category = value!)),
259
+ TextField(
260
+ controller: summary,
261
+ enabled: !busy && pendingBody == null,
262
+ maxLength: 1000,
263
+ maxLines: 5,
264
+ decoration:
265
+ const InputDecoration(labelText: 'خلاصه ایراد یا پیشنهاد')),
266
+ CheckboxListTile(
267
+ value: consent,
268
+ onChanged: busy || pendingBody != null
269
+ ? null
270
+ : (value) => setState(() => consent = value == true),
271
+ title: const Text(
272
+ 'میخواهم فقط همین خلاصه برای بررسی محتوا در اختیار تیم توسعه قرار گیرد.')),
273
+ if (message != null) Text(message!),
274
+ FilledButton(
275
+ onPressed: busy ? null : send,
276
+ child: Text(pendingBody == null
277
+ ? 'ارسال بازخورد'
278
+ : 'تلاش دوباره با همان بازخورد')),
279
+ if (pendingBody != null)
280
+ TextButton(
281
+ onPressed: busy
282
+ ? null
283
+ : () async {
284
+ await sync.store.discardEntityChanges(
285
+ pendingBody!['mutationId'] as String,
286
+ cacheKey: 'education_feedback',
287
+ entityType: 'learning_feedback');
288
+ if (mounted) {
289
+ setState(() {
290
+ pendingBody = null;
291
+ consent = false;
292
+ message =
293
+ 'تلاش بعدی ارسال متوقف شد و پیشنویس در سابقه بازیابی ماند. اگر پاسخ شبکه گم شده باشد، رکورد ممکن است در سرور ثبت شده باشد؛ فهرست ثبتشده را بررسی و رضایت را جدا پس بگیر.';
294
+ });
295
+ }
296
+ },
297
+ child: const Text('خارجکردن پیشنویس از صف ارسال')),
298
+ const Text(
299
+ 'این فرم فقط داده انتخابشده تو را ارسال میکند؛ گفتوگو، یادداشت و اطلاعات خصوصی حساب استخراج نمیشود.'),
300
+ const Divider(),
301
+ const Text('بازخوردهای ثبتشده من'),
302
+ ...history.map((row) => Card(
303
+ child: ListTile(
304
+ title: Text(row['withdrawnAt'] == null
305
+ ? row['summary']?.toString() ?? 'بازخورد'
306
+ : 'رضایت ارسال پس گرفته شد'),
307
+ subtitle: Text(row['withdrawnAt'] == null
308
+ ? 'وضعیت بررسی: ${row['status'] ?? 'دریافتشده'}'
309
+ : 'متن بازخورد حذف شده است.'),
310
+ trailing: row['withdrawnAt'] != null
311
+ ? null
312
+ : TextButton(
313
+ onPressed:
314
+ busy ? null : () => withdraw(row['id'].toString()),
315
+ child: const Text('پسگرفتن رضایت'))))),
316
+ ]));
317
+}
apps/lifemate/lib/learning_quiz_ui.dart
new
+612
@@ -0,0 +1,612 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+
6
+import 'api.dart';
7
+import 'offline_store.dart';
8
+import 'plan_sync.dart' show newMutationId;
9
+
10
+final _quizUuid =
11
+ RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$');
12
+final _quizKey = RegExp(r'^[a-zA-Z0-9_-]{1,80}$');
13
+const _confidences = {
14
+ 'unsure': 'مطمئن نیستم',
15
+ 'somewhat': 'تا حدی مطمئنم',
16
+ 'confident': 'مطمئنم',
17
+};
18
+
19
+bool _uuid(dynamic value) => value is String && _quizUuid.hasMatch(value);
20
+bool _key(dynamic value) => value is String && _quizKey.hasMatch(value);
21
+bool _text(dynamic value) =>
22
+ value is String &&
23
+ value.trim().isNotEmpty &&
24
+ value.length <= 2000 &&
25
+ !value.contains('\u0000');
26
+bool _fields(Map value, Set<String> fields) =>
27
+ value.length == fields.length && value.keys.every(fields.contains);
28
+
29
+Map<String, dynamic> _attemptBody(Map<String, dynamic> value) {
30
+ if (!_fields(value, {
31
+ 'mutationId',
32
+ 'assessmentId',
33
+ 'assessmentVersion',
34
+ 'answers',
35
+ 'confidence'
36
+ }) ||
37
+ !_uuid(value['mutationId']) ||
38
+ !_uuid(value['assessmentId']) ||
39
+ value['assessmentVersion'] is! int ||
40
+ value['assessmentVersion'] < 1 ||
41
+ !_confidences.containsKey(value['confidence']) ||
42
+ value['answers'] is! List) {
43
+ throw const ApiException(422, 'invalid_quiz_attempt');
44
+ }
45
+ final answers = value['answers'] as List;
46
+ final questions = <String>{};
47
+ if (answers.isEmpty || answers.length > 20) {
48
+ throw const ApiException(422, 'invalid_quiz_attempt');
49
+ }
50
+ for (final answer in answers) {
51
+ if (answer is! Map ||
52
+ !_fields(answer, {'questionId', 'choiceId'}) ||
53
+ !_key(answer['questionId']) ||
54
+ !_key(answer['choiceId']) ||
55
+ !questions.add(answer['questionId'] as String)) {
56
+ throw const ApiException(422, 'invalid_quiz_attempt');
57
+ }
58
+ }
59
+ // Own an immutable-by-caller snapshot before any asynchronous storage work.
60
+ return Map<String, dynamic>.from(jsonDecode(jsonEncode(value)) as Map);
61
+}
62
+
63
+/// Durable, account-scoped quiz answers. A quiz result never changes the
64
+/// learner's separate, explicitly reported lesson-progress state.
65
+class LearningQuizSync {
66
+ LearningQuizSync(this.api, {OfflineStore? store})
67
+ : store = store ?? OfflineStore.forApi(api);
68
+ final HttpIdentityApi api;
69
+ final OfflineStore store;
70
+ static final _tails = <String, Future<void>>{};
71
+ static const _cache = 'learning_attempts';
72
+
73
+ void _scope() {
74
+ if (api.cacheNamespace != store.scope) {
75
+ throw const ApiException(401, 'cache_scope_closed');
76
+ }
77
+ }
78
+
79
+ Future<T> _serial<T>(Future<T> Function() operation) {
80
+ final previous = _tails[store.scope];
81
+ final release = Completer<void>();
82
+ _tails[store.scope] = release.future;
83
+ return (() async {
84
+ if (previous != null) await previous;
85
+ try {
86
+ _scope();
87
+ await store.readQueue(); // Also checks the captured store generation.
88
+ _scope();
89
+ final result = await operation();
90
+ _scope();
91
+ return result;
92
+ } finally {
93
+ if (identical(_tails[store.scope], release.future)) {
94
+ _tails.remove(store.scope);
95
+ }
96
+ release.complete();
97
+ }
98
+ })();
99
+ }
100
+
101
+ Future<List<Map<String, dynamic>>> pendingForUnit(String unitId) async {
102
+ _scope();
103
+ final pending = (await store.readQueue())
104
+ .where((m) =>
105
+ m['entityType'] == 'learning_attempt' && m['unitId'] == unitId)
106
+ .toList();
107
+ _scope();
108
+ return pending;
109
+ }
110
+
111
+ Future<Map<String, dynamic>?> readAssessment(String unitId) =>
112
+ _serial(() async {
113
+ if (!_uuid(unitId)) {
114
+ throw const ApiException(400, 'invalid_unit_id');
115
+ }
116
+ final response = await api.requestJson('GET',
117
+ '/v1/education/units/${Uri.encodeComponent(unitId)}/assessment');
118
+ _scope();
119
+ // Check generation again before exposing a response to the old page.
120
+ await store.readQueue();
121
+ if (response['assessment'] == null &&
122
+ response['reason'] == 'review_pending') {
123
+ return null;
124
+ }
125
+ final raw = response['assessment'];
126
+ if (raw is! Map ||
127
+ !_fields(raw, {'id', 'unitId', 'version', 'questions'}) ||
128
+ !_uuid(raw['id']) ||
129
+ raw['unitId'] != unitId ||
130
+ raw['version'] is! int ||
131
+ raw['version'] < 1 ||
132
+ raw['questions'] is! List) {
133
+ throw const ApiException(502, 'invalid_quiz_assessment');
134
+ }
135
+ final questions = raw['questions'] as List;
136
+ final ids = <String>{};
137
+ if (questions.isEmpty || questions.length > 20) {
138
+ throw const ApiException(502, 'invalid_quiz_assessment');
139
+ }
140
+ for (final question in questions) {
141
+ if (question is! Map ||
142
+ !_fields(
143
+ question, {'id', 'objectiveId', 'promptFa', 'choices'}) ||
144
+ !_key(question['id']) ||
145
+ !ids.add(question['id'] as String) ||
146
+ !_key(question['objectiveId']) ||
147
+ !_text(question['promptFa']) ||
148
+ question['choices'] is! List) {
149
+ throw const ApiException(502, 'invalid_quiz_assessment');
150
+ }
151
+ final choices = question['choices'] as List;
152
+ final choiceIds = <String>{};
153
+ if (choices.length < 2 || choices.length > 6) {
154
+ throw const ApiException(502, 'invalid_quiz_assessment');
155
+ }
156
+ for (final choice in choices) {
157
+ if (choice is! Map ||
158
+ !_fields(choice, {'id', 'textFa'}) ||
159
+ !_key(choice['id']) ||
160
+ !choiceIds.add(choice['id'] as String) ||
161
+ !_text(choice['textFa'])) {
162
+ throw const ApiException(502, 'invalid_quiz_assessment');
163
+ }
164
+ }
165
+ }
166
+ return Map<String, dynamic>.from(raw);
167
+ });
168
+
169
+ Future<Map<String, dynamic>> submit(
170
+ Map<String, dynamic> body, String unitId) {
171
+ final frozen = _attemptBody(body);
172
+ if (!_uuid(unitId)) throw const ApiException(422, 'invalid_unit_id');
173
+ return _serial(() async {
174
+ final pending = await pendingForUnit(unitId);
175
+ if (pending.any((m) => m['id'] != frozen['mutationId'])) {
176
+ throw const ApiException(409, 'sync_pending');
177
+ }
178
+ if (pending.any((m) => m['queueStatus'] != 'queued')) {
179
+ throw const ApiException(409, 'quiz_pending_rejected');
180
+ }
181
+ final mutation = <String, dynamic>{
182
+ 'id': frozen['mutationId'],
183
+ 'entityId': frozen['mutationId'],
184
+ 'entityType': 'learning_attempt',
185
+ 'operation': 'submit',
186
+ 'unitId': unitId, // Local metadata; never put this in the POST body.
187
+ 'payload': frozen,
188
+ };
189
+ await store.enqueue(mutation);
190
+ try {
191
+ return {'queued': false, 'attempt': await _send(mutation)};
192
+ } catch (error) {
193
+ _scope();
194
+ if (!isOfflineFailure(error)) rethrow;
195
+ return {'queued': true, 'attempt': null};
196
+ }
197
+ });
198
+ }
199
+
200
+ Map<String, dynamic> _ack(
201
+ Map<String, dynamic> raw, Map<String, dynamic> body, String unitId) {
202
+ const fields = {
203
+ 'mutationId',
204
+ 'attemptId',
205
+ 'unitId',
206
+ 'assessmentId',
207
+ 'assessmentVersion',
208
+ 'correctCount',
209
+ 'total',
210
+ 'feedback',
211
+ 'resultLabel',
212
+ 'nextReviewAt',
213
+ 'schedulePolicy',
214
+ 'source',
215
+ 'acceptedAt'
216
+ };
217
+ Never invalid() =>
218
+ throw const ApiException(502, 'invalid_sync_acknowledgement');
219
+ DateTime? date(dynamic value) => value is String && value.endsWith('Z')
220
+ ? DateTime.tryParse(value)
221
+ : null;
222
+ final accepted = date(raw['acceptedAt']);
223
+ final next = date(raw['nextReviewAt']);
224
+ final answers = body['answers'] as List;
225
+ if (!_fields(raw, fields) ||
226
+ raw['mutationId'] != body['mutationId'] ||
227
+ !_uuid(raw['attemptId']) ||
228
+ raw['unitId'] != unitId ||
229
+ raw['assessmentId'] != body['assessmentId'] ||
230
+ raw['assessmentVersion'] != body['assessmentVersion'] ||
231
+ raw['total'] != answers.length ||
232
+ raw['correctCount'] is! int ||
233
+ raw['correctCount'] < 0 ||
234
+ raw['correctCount'] > answers.length ||
235
+ raw['feedback'] is! List ||
236
+ raw['source'] != 'quiz_answers' ||
237
+ raw['schedulePolicy'] != 'pilot-1-or-3-days' ||
238
+ accepted == null ||
239
+ next == null) {
240
+ invalid();
241
+ }
242
+ final allCorrect = raw['correctCount'] == answers.length;
243
+ if (raw['resultLabel'] !=
244
+ (allCorrect ? 'answered_correctly' : 'needs_practice') ||
245
+ next.difference(accepted) != Duration(days: allCorrect ? 3 : 1)) {
246
+ invalid();
247
+ }
248
+ final questionIds = answers.map((a) => a['questionId']).toSet();
249
+ final seen = <String>{};
250
+ var count = 0;
251
+ for (final feedback in raw['feedback'] as List) {
252
+ if (feedback is! Map ||
253
+ !_fields(feedback, {
254
+ 'questionId',
255
+ 'objectiveId',
256
+ 'correct',
257
+ 'explanationFa',
258
+ 'remediationFa'
259
+ }) ||
260
+ !_key(feedback['questionId']) ||
261
+ !questionIds.contains(feedback['questionId']) ||
262
+ !seen.add(feedback['questionId'] as String) ||
263
+ !_key(feedback['objectiveId']) ||
264
+ feedback['correct'] is! bool ||
265
+ !_text(feedback['explanationFa']) ||
266
+ !_text(feedback['remediationFa'])) {
267
+ invalid();
268
+ }
269
+ if (feedback['correct'] == true) count++;
270
+ }
271
+ if (seen.length != answers.length || count != raw['correctCount']) {
272
+ invalid();
273
+ }
274
+ return {...raw, 'id': raw['attemptId']};
275
+ }
276
+
277
+ Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
278
+ _scope();
279
+ if (mutation['entityType'] != 'learning_attempt' ||
280
+ mutation['operation'] != 'submit' ||
281
+ !_uuid(mutation['unitId']) ||
282
+ mutation['entityId'] != mutation['id'] ||
283
+ mutation['payload'] is! Map) {
284
+ throw const ApiException(422, 'invalid_quiz_attempt');
285
+ }
286
+ final body =
287
+ _attemptBody(Map<String, dynamic>.from(mutation['payload'] as Map));
288
+ if (body['mutationId'] != mutation['id']) {
289
+ throw const ApiException(422, 'invalid_quiz_attempt');
290
+ }
291
+ await store.readQueue();
292
+ _scope();
293
+ final Map<String, dynamic> response;
294
+ try {
295
+ response =
296
+ await api.requestJson('POST', '/v1/me/learning-attempts', body: body);
297
+ _scope();
298
+ } catch (error) {
299
+ _scope();
300
+ if (error is ApiException &&
301
+ [400, 404, 409, 422].contains(error.statusCode)) {
302
+ await store.markQueued(mutation['id'] as String,
303
+ error.statusCode == 409 ? 'conflict' : 'rejected',
304
+ error: error.code);
305
+ }
306
+ rethrow;
307
+ }
308
+ final attempt = _ack(response, body, mutation['unitId'] as String);
309
+ await store.acknowledge(mutation['id'] as String,
310
+ item: attempt,
311
+ acceptedAt: attempt['acceptedAt'] as String,
312
+ cacheKey: _cache);
313
+ _scope();
314
+ return attempt;
315
+ }
316
+
317
+ Future<void> flush() => _serial(() async {
318
+ for (final mutation in await store.readQueue()) {
319
+ if (mutation['entityType'] != 'learning_attempt') continue;
320
+ if (mutation['queueStatus'] == 'conflict') {
321
+ throw const ApiException(409, 'sync_conflict');
322
+ }
323
+ if (mutation['queueStatus'] != 'queued') continue;
324
+ try {
325
+ await _send(mutation);
326
+ } catch (error) {
327
+ if (isOfflineFailure(error)) return;
328
+ rethrow;
329
+ }
330
+ }
331
+ });
332
+
333
+ /// Explicit cancellation stops retries and journals the original answers.
334
+ /// It cannot undo an attempt that the server already accepted.
335
+ Future<void> cancelPending(String mutationId) => _serial(() async {
336
+ final queue = await store.readQueue();
337
+ if (!queue.any((m) =>
338
+ m['id'] == mutationId && m['entityType'] == 'learning_attempt')) {
339
+ return;
340
+ }
341
+ await store.discardEntityChanges(mutationId,
342
+ entityType: 'learning_attempt', cacheKey: _cache);
343
+ });
344
+}
345
+
346
+class LearningQuizPage extends StatefulWidget {
347
+ const LearningQuizPage({super.key, required this.api, required this.unitId});
348
+ final HttpIdentityApi api;
349
+ final String unitId;
350
+ @override
351
+ State<LearningQuizPage> createState() => _LearningQuizPageState();
352
+}
353
+
354
+class _LearningQuizPageState extends State<LearningQuizPage> {
355
+ late final sync = LearningQuizSync(widget.api);
356
+ Map<String, dynamic>? assessment, pending, attempt;
357
+ final answers = <String, String>{};
358
+ String? confidence, message;
359
+ bool loading = true, busy = false;
360
+
361
+ @override
362
+ void initState() {
363
+ super.initState();
364
+ load();
365
+ }
366
+
367
+ bool get matchesPending =>
368
+ pending == null ||
369
+ (assessment?['id'] == pending!['assessmentId'] &&
370
+ assessment?['version'] == pending!['assessmentVersion']);
371
+
372
+ bool get complete =>
373
+ assessment != null &&
374
+ answers.length == (assessment!['questions'] as List).length &&
375
+ confidence != null;
376
+
377
+ void failure(Object error) {
378
+ if (error is ApiException && [401, 403].contains(error.statusCode)) {
379
+ assessment = pending = attempt = null;
380
+ answers.clear();
381
+ confidence = null;
382
+ message = 'برای دیدن آزمون، دوباره وارد حساب خود شوید.';
383
+ } else if (isOfflineFailure(error)) {
384
+ message = pending == null
385
+ ? 'برای دریافت آزمون بازبینیشده، اتصال به سرور لازم است.'
386
+ : 'پاسخها روی این دستگاه نگه داشته شدهاند؛ هنوز نتیجهٔ سرور دریافت نشده است.';
387
+ } else if (error is ApiException && error.statusCode == 409) {
388
+ message =
389
+ 'این ارسال به بررسی نیاز دارد. پاسخها حفظ شدهاند؛ برای شروع دوباره، ارسال را لغو کنید.';
390
+ } else {
391
+ message =
392
+ 'آزمون یا تأیید نتیجه دریافت نشد. پاسخهای ثبتشده حذف نشدهاند.';
393
+ }
394
+ }
395
+
396
+ Future<void> load() async {
397
+ try {
398
+ final rows = await sync.pendingForUnit(widget.unitId);
399
+ if (!mounted) return;
400
+ if (rows.isNotEmpty) {
401
+ pending = _attemptBody(
402
+ Map<String, dynamic>.from(rows.first['payload'] as Map));
403
+ for (final answer in pending!['answers'] as List) {
404
+ answers[answer['questionId'] as String] =
405
+ answer['choiceId'] as String;
406
+ }
407
+ confidence = pending!['confidence'] as String;
408
+ message =
409
+ 'پاسخها روی این دستگاه نگه داشته شدهاند؛ تا تأیید یا لغو، قابل تغییر نیستند.';
410
+ }
411
+ final bank = await sync.readAssessment(widget.unitId);
412
+ if (mounted) setState(() => assessment = bank);
413
+ } catch (error) {
414
+ if (mounted) setState(() => failure(error));
415
+ } finally {
416
+ if (mounted) setState(() => loading = false);
417
+ }
418
+ }
419
+
420
+ Future<void> send() async {
421
+ if (busy || (pending == null && !complete)) return;
422
+ final body = pending ??
423
+ {
424
+ 'mutationId': newMutationId(),
425
+ 'assessmentId': assessment!['id'],
426
+ 'assessmentVersion': assessment!['version'],
427
+ 'answers': [
428
+ for (final question in assessment!['questions'] as List)
429
+ {
430
+ 'questionId': question['id'],
431
+ 'choiceId': answers[question['id']]
432
+ },
433
+ ],
434
+ 'confidence': confidence,
435
+ };
436
+ setState(() {
437
+ busy = true;
438
+ message = null;
439
+ });
440
+ try {
441
+ final result = await sync.submit(body, widget.unitId);
442
+ if (!mounted) return;
443
+ setState(() {
444
+ if (result['queued'] == true) {
445
+ pending = _attemptBody(body);
446
+ message =
447
+ 'پاسخها روی این دستگاه نگه داشته شدهاند؛ هنوز نتیجهٔ سرور دریافت نشده است.';
448
+ } else {
449
+ pending = null;
450
+ attempt = Map<String, dynamic>.from(result['attempt'] as Map);
451
+ }
452
+ });
453
+ } catch (error) {
454
+ // A permanent rejection or malformed acknowledgement also leaves a
455
+ // durable pending record, and must never unlock answers for a new ID.
456
+ try {
457
+ final rows = await sync.pendingForUnit(widget.unitId);
458
+ if (rows.isNotEmpty) pending = _attemptBody(body);
459
+ } catch (_) {/* Keep the original scope/storage error below. */}
460
+ if (mounted) setState(() => failure(error));
461
+ } finally {
462
+ if (mounted) setState(() => busy = false);
463
+ }
464
+ }
465
+
466
+ Future<void> cancel() async {
467
+ final confirmed = await showDialog<bool>(
468
+ context: context,
469
+ builder: (context) => AlertDialog(
470
+ title: const Text('لغو تلاش برای ارسال؟'),
471
+ content: const Text(
472
+ 'ممکن است سرور قبلاً این پاسخها را دریافت کرده باشد. لغو فقط تلاش بعدی این دستگاه را متوقف میکند و نتیجهٔ سرور را حذف نمیکند. پاسخها در سابقهٔ بازیابی محلی نگه داشته میشوند.'),
473
+ actions: [
474
+ TextButton(
475
+ onPressed: () => Navigator.pop(context, false),
476
+ child: const Text('بازگشت')),
477
+ TextButton(
478
+ onPressed: () => Navigator.pop(context, true),
479
+ child: const Text('لغو ارسال')),
480
+ ],
481
+ ));
482
+ if (confirmed != true || !mounted || pending == null) return;
483
+ setState(() => busy = true);
484
+ try {
485
+ await sync.cancelPending(pending!['mutationId'] as String);
486
+ if (mounted) {
487
+ setState(() {
488
+ pending = null;
489
+ answers.clear();
490
+ confidence = null;
491
+ message = 'تلاش برای ارسال لغو شد.';
492
+ });
493
+ }
494
+ } catch (error) {
495
+ if (mounted) setState(() => failure(error));
496
+ } finally {
497
+ if (mounted) setState(() => busy = false);
498
+ }
499
+ }
500
+
501
+ @override
502
+ Widget build(BuildContext context) => Directionality(
503
+ textDirection: TextDirection.rtl,
504
+ child: Scaffold(
505
+ appBar: AppBar(title: const Text('تمرین پس از درس')),
506
+ body: loading
507
+ ? const Center(child: CircularProgressIndicator())
508
+ : ListView(padding: const EdgeInsets.all(20), children: [
509
+ const Text(
510
+ 'این تمرین بر اساس پاسخهای شماست؛ نتیجه، نشانهٔ قطعی تسلط یا مطالعهٔ واقعی نیست و وضعیت درس را خودکار تغییر نمیدهد.'),
511
+ if (message != null)
512
+ Padding(
513
+ padding: const EdgeInsets.symmetric(vertical: 12),
514
+ child: Text(message!)),
515
+ if (attempt != null) ...[
516
+ Text(
517
+ '${attempt!['correctCount']} از ${attempt!['total']} پاسخ درست',
518
+ style: Theme.of(context).textTheme.titleLarge),
519
+ for (final feedback in attempt!['feedback'] as List)
520
+ Card(
521
+ child: Padding(
522
+ padding: const EdgeInsets.all(16),
523
+ child: Column(
524
+ crossAxisAlignment: CrossAxisAlignment.start,
525
+ children: [
526
+ Text(feedback['correct'] == true
527
+ ? 'پاسخ درست بود'
528
+ : 'این بخش به تمرین نیاز دارد'),
529
+ Text(feedback['explanationFa'] as String),
530
+ Text(feedback['remediationFa'] as String),
531
+ ]))),
532
+ Text(
533
+ 'مرور بعدی: ${DateTime.parse(attempt!['nextReviewAt'] as String).toLocal().toString().split(" ").first}. این زمانبندی پیشنهاد آزمایشی ۱ یا ۳ روزه است، نه تضمین بهترین زمان یادگیری.'),
534
+ ] else ...[
535
+ if (assessment == null && message == null)
536
+ const Padding(
537
+ padding: EdgeInsets.symmetric(vertical: 24),
538
+ child: Text(
539
+ 'آزمون این درس در انتظار بازبینی است. تا تأیید محتوای آن، پرسشی نمایش داده نمیشود.')),
540
+ if (assessment != null && matchesPending) ...[
541
+ for (final question in assessment!['questions'] as List)
542
+ Card(
543
+ child: Padding(
544
+ padding: const EdgeInsets.all(16),
545
+ child: Column(
546
+ crossAxisAlignment:
547
+ CrossAxisAlignment.stretch,
548
+ children: [
549
+ Text(question['promptFa'] as String,
550
+ style: Theme.of(context)
551
+ .textTheme
552
+ .titleMedium),
553
+ const SizedBox(height: 8),
554
+ for (final choice
555
+ in question['choices'] as List)
556
+ Align(
557
+ alignment: AlignmentDirectional
558
+ .centerStart,
559
+ child: ChoiceChip(
560
+ key: Key(
561
+ 'quiz-choice-${question['id']}-${choice['id']}'),
562
+ label: Text(
563
+ choice['textFa'] as String),
564
+ selected:
565
+ answers[question['id']] ==
566
+ choice['id'],
567
+ onSelected:
568
+ pending != null || busy
569
+ ? null
570
+ : (_) => setState(() =>
571
+ answers[question['id']
572
+ as String] =
573
+ choice['id']
574
+ as String),
575
+ )),
576
+ ]))),
577
+ const Text('چقدر به پاسخهایتان مطمئن هستید؟'),
578
+ Wrap(spacing: 8, children: [
579
+ for (final entry in _confidences.entries)
580
+ ChoiceChip(
581
+ key: Key('quiz-confidence-${entry.key}'),
582
+ label: Text(entry.value),
583
+ selected: confidence == entry.key,
584
+ onSelected: pending != null || busy
585
+ ? null
586
+ : (_) =>
587
+ setState(() => confidence = entry.key)),
588
+ ]),
589
+ ],
590
+ if (pending != null) ...[
591
+ if (!matchesPending)
592
+ const Text(
593
+ 'نسخهٔ پاسخهای ذخیرهشده با آزمون فعلی متفاوت است. ارسال دوباره، همان پاسخها و نسخهٔ اصلی را میفرستد.'),
594
+ FilledButton(
595
+ key: const Key('quiz-retry'),
596
+ onPressed: busy ? null : send,
597
+ child: const Text('تلاش دوباره برای همان ارسال')),
598
+ TextButton(
599
+ key: const Key('quiz-cancel'),
600
+ onPressed: busy ? null : cancel,
601
+ child: const Text('لغو تلاش برای ارسال')),
602
+ ] else if (assessment != null)
603
+ FilledButton(
604
+ key: const Key('quiz-submit'),
605
+ onPressed: complete && !busy ? send : null,
606
+ child: const Text('ثبت پاسخها و دریافت بازخورد')),
607
+ ],
608
+ if (busy) const Center(child: CircularProgressIndicator()),
609
+ ]),
610
+ ),
611
+ );
612
+}
apps/lifemate/lib/learning_sync.dart
new
+324
@@ -0,0 +1,324 @@
1
+import 'dart:async';
2
+
3
+import 'api.dart';
4
+import 'offline_store.dart';
5
+import 'plan_sync.dart' show newMutationId;
6
+
7
+/// Explicit personal reports, never inferred from playback or elapsed time.
8
+/// Pending writes are scoped to the authenticated API/account and persisted
9
+/// before delivery. Only a matching server acknowledgement removes a write.
10
+class LearningSync {
11
+ LearningSync(this.api, {OfflineStore? store})
12
+ : store = store ?? OfflineStore.forApi(api);
13
+
14
+ final HttpIdentityApi api;
15
+ final OfflineStore store;
16
+ static final _tails = <String, Future<void>>{};
17
+ static const _statuses = {'not_started', 'in_progress', 'completed'};
18
+ static const _progressCache = 'learning_progress';
19
+ static final _uuid =
20
+ RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$');
21
+
22
+ void _checkScope() {
23
+ if (api.cacheNamespace != store.scope) {
24
+ throw const ApiException(401, 'cache_scope_closed');
25
+ }
26
+ }
27
+
28
+ Future<T> _serial<T>(Future<T> Function() operation) {
29
+ final previous = _tails[store.scope];
30
+ final release = Completer<void>();
31
+ _tails[store.scope] = release.future;
32
+ return (() async {
33
+ if (previous != null) await previous;
34
+ try {
35
+ _checkScope();
36
+ // Verify the handle generation before making an authenticated request.
37
+ await store.readQueue();
38
+ _checkScope();
39
+ final result = await operation();
40
+ _checkScope();
41
+ return result;
42
+ } finally {
43
+ if (identical(_tails[store.scope], release.future)) {
44
+ _tails.remove(store.scope);
45
+ }
46
+ release.complete();
47
+ }
48
+ })();
49
+ }
50
+
51
+ static bool _timestamp(dynamic value) =>
52
+ value is String &&
53
+ RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
54
+ DateTime.tryParse(value) != null;
55
+
56
+ static Map<String, dynamic> _initialProgress(String unitId) => {
57
+ 'id': unitId,
58
+ 'unitId': unitId,
59
+ 'status': 'not_started',
60
+ 'source': 'self_reported',
61
+ 'version': 0,
62
+ 'updatedAt': null,
63
+ 'pending_sync': false,
64
+ 'acknowledged': false,
65
+ };
66
+
67
+ static Map<String, dynamic> _serverProgress(dynamic raw, String unitId) {
68
+ if (raw is! Map ||
69
+ raw['unitId'] != unitId ||
70
+ !_statuses.contains(raw['status']) ||
71
+ raw['source'] != 'self_reported' ||
72
+ raw['version'] is! int ||
73
+ raw['version'] < 0 ||
74
+ (raw['version'] > 0 && !_timestamp(raw['updatedAt']))) {
75
+ throw const ApiException(502, 'invalid_learning_progress');
76
+ }
77
+ return {
78
+ ...Map<String, dynamic>.from(raw),
79
+ 'id': unitId,
80
+ 'pending_sync': false,
81
+ 'acknowledged': raw['version'] > 0,
82
+ };
83
+ }
84
+
85
+ Future<List<Map<String, dynamic>>> pendingFor(String unitId) async {
86
+ _checkScope();
87
+ final pending = (await store.readQueue())
88
+ .where((m) =>
89
+ m['entityType'] == 'learning_progress' && m['entityId'] == unitId)
90
+ .toList();
91
+ _checkScope();
92
+ return pending;
93
+ }
94
+
95
+ Future<Map<String, dynamic>> readCourse(String id) => _serial(() async {
96
+ if (!_uuid.hasMatch(id)) {
97
+ throw const ApiException(400, 'invalid_course_id');
98
+ }
99
+ final key = 'learning.course:$id';
100
+ Map<String, dynamic> course;
101
+ var offline = false;
102
+ try {
103
+ final response = await api.requestJson(
104
+ 'GET', '/v1/education/courses/${Uri.encodeComponent(id)}');
105
+ _checkScope();
106
+ final raw = response['course'] ?? response;
107
+ if (raw is! Map || raw['id'] != id || raw['units'] is! List) {
108
+ throw const ApiException(502, 'invalid_learning_course');
109
+ }
110
+ course = Map<String, dynamic>.from(raw);
111
+ final known = await store.readList(_progressCache);
112
+ final ids = <String>{};
113
+ for (final rawUnit in course['units'] as List) {
114
+ if (rawUnit is! Map ||
115
+ rawUnit['id'] is! String ||
116
+ !_uuid.hasMatch(rawUnit['id']) ||
117
+ !ids.add(rawUnit['id'])) {
118
+ throw const ApiException(502, 'invalid_learning_course');
119
+ }
120
+ final unitId = rawUnit['id'] as String;
121
+ final progress = rawUnit['progress'];
122
+ final server = progress == null
123
+ ? _initialProgress(unitId)
124
+ : _serverProgress(progress, unitId);
125
+ known.removeWhere((p) => p['id'] == unitId);
126
+ known.add(server);
127
+ }
128
+ await store.writeList(_progressCache, known);
129
+ await store.writeList(key, [course]);
130
+ } catch (error) {
131
+ _checkScope();
132
+ if (!isOfflineFailure(error)) rethrow;
133
+ final cached = await store.readList(key);
134
+ if (cached.length != 1) rethrow;
135
+ course = cached.single;
136
+ offline = true;
137
+ }
138
+ _checkScope();
139
+ return {
140
+ ...course,
141
+ 'offline': offline,
142
+ 'units': await _overlayUnits(course['units'] as List),
143
+ };
144
+ });
145
+
146
+ Future<List<Map<String, dynamic>>> _overlayUnits(List units) async {
147
+ final known = await store.readList(_progressCache);
148
+ final pending = await store.readQueue();
149
+ return [
150
+ for (final raw in units)
151
+ {
152
+ ...Map<String, dynamic>.from(raw as Map),
153
+ 'progress': _overlayProgress(
154
+ raw['id'] as String,
155
+ known.where((p) => p['unitId'] == raw['id']).firstOrNull ??
156
+ _initialProgress(raw['id'] as String),
157
+ pending),
158
+ }
159
+ ];
160
+ }
161
+
162
+ static Map<String, dynamic> _overlayProgress(
163
+ String id, Map<String, dynamic> base, List<Map<String, dynamic>> queue) {
164
+ final mutation = queue
165
+ .where((m) =>
166
+ m['entityType'] == 'learning_progress' && m['entityId'] == id)
167
+ .firstOrNull;
168
+ if (mutation == null) return Map<String, dynamic>.from(base);
169
+ final payload = mutation['payload'] as Map;
170
+ return {
171
+ ...base,
172
+ 'id': id,
173
+ 'unitId': id,
174
+ 'status': payload['status'],
175
+ 'source': 'self_reported',
176
+ // Retain the acknowledged version; an unsent change has no new version.
177
+ 'version': payload['expectedVersion'],
178
+ 'pending_sync': true,
179
+ 'acknowledged': false,
180
+ 'mutationId': mutation['id'],
181
+ 'queueStatus': mutation['queueStatus'],
182
+ 'sync_conflict': mutation['queueStatus'] == 'conflict',
183
+ 'lastError': mutation['lastError'],
184
+ 'queuedAt': mutation['queuedAt'],
185
+ };
186
+ }
187
+
188
+ Future<Map<String, dynamic>> setProgress(
189
+ String unitId, String status, int expectedVersion) =>
190
+ _serial(() async {
191
+ if (!_uuid.hasMatch(unitId) ||
192
+ !_statuses.contains(status) ||
193
+ expectedVersion < 0) {
194
+ throw const ApiException(400, 'invalid_learning_progress');
195
+ }
196
+ if ((await pendingFor(unitId)).isNotEmpty) {
197
+ throw const ApiException(409, 'sync_pending');
198
+ }
199
+ final mutationId = newMutationId();
200
+ final mutation = <String, dynamic>{
201
+ 'id': mutationId,
202
+ 'entityId': unitId,
203
+ 'entityType': 'learning_progress',
204
+ 'operation': 'set_progress',
205
+ 'expectedVersion': expectedVersion,
206
+ 'payload': {
207
+ 'status': status,
208
+ 'source': 'self_reported',
209
+ 'mutationId': mutationId,
210
+ 'expectedVersion': expectedVersion,
211
+ },
212
+ };
213
+ // Do not use optimisticItem: that helper writes planner caches.
214
+ await store.enqueue(mutation);
215
+ try {
216
+ final accepted = await _send(mutation);
217
+ return {'queued': false, 'progress': accepted};
218
+ } catch (error) {
219
+ _checkScope();
220
+ if (!isOfflineFailure(error)) rethrow;
221
+ final known = await store.readList(_progressCache);
222
+ return {
223
+ 'queued': true,
224
+ 'progress': _overlayProgress(
225
+ unitId,
226
+ known.where((p) => p['unitId'] == unitId).firstOrNull ??
227
+ _initialProgress(unitId),
228
+ await store.readQueue()),
229
+ };
230
+ }
231
+ });
232
+
233
+ Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
234
+ _checkScope();
235
+ final payload = Map<String, dynamic>.from(mutation['payload'] as Map);
236
+ final unitId = mutation['entityId'] as String;
237
+ final expected = payload['expectedVersion'];
238
+ if (mutation['entityType'] != 'learning_progress' ||
239
+ mutation['operation'] != 'set_progress' ||
240
+ !_uuid.hasMatch(unitId) ||
241
+ payload['mutationId'] != mutation['id'] ||
242
+ expected is! int ||
243
+ expected < 0 ||
244
+ payload['source'] != 'self_reported' ||
245
+ !_statuses.contains(payload['status'])) {
246
+ throw const ApiException(422, 'invalid_learning_mutation');
247
+ }
248
+ final Map<String, dynamic> ack;
249
+ try {
250
+ ack = await api.requestJson(
251
+ 'PUT', '/v1/me/learning-progress/${Uri.encodeComponent(unitId)}',
252
+ body: payload);
253
+ _checkScope();
254
+ } catch (error) {
255
+ _checkScope();
256
+ if (error is ApiException && error.statusCode == 409) {
257
+ await store.markQueued(mutation['id'] as String, 'conflict',
258
+ error: error.code);
259
+ }
260
+ rethrow;
261
+ }
262
+ if (ack['mutationId'] != mutation['id'] ||
263
+ ack['unitId'] != unitId ||
264
+ ack['status'] != payload['status'] ||
265
+ ack['source'] != 'self_reported' ||
266
+ ack['version'] is! int ||
267
+ ack['version'] != expected + 1 ||
268
+ !_timestamp(ack['updatedAt']) ||
269
+ !_timestamp(ack['acceptedAt'])) {
270
+ throw const ApiException(502, 'invalid_sync_acknowledgement');
271
+ }
272
+ final progress = _serverProgress(ack, unitId);
273
+ await store.acknowledge(mutation['id'] as String,
274
+ item: progress,
275
+ acceptedAt: ack['acceptedAt'] as String,
276
+ cacheKey: _progressCache);
277
+ return progress;
278
+ }
279
+
280
+ Future<void> flush() => _serial(() async {
281
+ for (final pending in await store.readQueue()) {
282
+ if (pending['entityType'] != 'learning_progress') continue;
283
+ if (pending['queueStatus'] == 'conflict') {
284
+ throw const ApiException(409, 'sync_conflict');
285
+ }
286
+ if (pending['queueStatus'] != 'queued') continue;
287
+ try {
288
+ await _send(pending);
289
+ } catch (error) {
290
+ if (isOfflineFailure(error)) return;
291
+ rethrow;
292
+ }
293
+ }
294
+ });
295
+
296
+ /// User-selected server value; preserve the rejected report in the durable
297
+ /// recovery journal in the same write that removes it from the queue.
298
+ Future<void> resolveUsingServer(String unitId) => _serial(() async {
299
+ if ((await pendingFor(unitId)).isEmpty) return;
300
+ final response =
301
+ await api.requestJson('GET', '/v1/me/learning-progress');
302
+ _checkScope();
303
+ final list = response['progress'];
304
+ if (list is! List || list.any((p) => p is! Map)) {
305
+ throw const ApiException(502, 'invalid_learning_progress');
306
+ }
307
+ final matches = list.where((p) => p['unitId'] == unitId).toList();
308
+ if (matches.length != 1) {
309
+ throw const ApiException(502, 'invalid_learning_progress');
310
+ }
311
+ final progress = _serverProgress(matches.single, unitId);
312
+ // The shared store's legacy journal helper filters by entity ID. Do
313
+ // not let an independently named planner/session record be discarded
314
+ // by a choice that concerns only lesson progress.
315
+ final queue = await store.readQueue();
316
+ if (queue.any((m) =>
317
+ m['entityId'] == unitId &&
318
+ m['entityType'] != 'learning_progress')) {
319
+ throw const ApiException(409, 'sync_entity_collision');
320
+ }
321
+ await store.discardEntityChanges(unitId,
322
+ serverItem: progress, cacheKey: _progressCache);
323
+ });
324
+}
apps/lifemate/lib/main.dart
+26
-13
@@ -4,6 +4,7 @@ import 'package:flutter_localizations/flutter_localizations.dart';
4
5
import 'api.dart';
6
import 'iran_hub.dart';
7
+import 'education_ui.dart';
8
import 'phase3_ui.dart';
9
import 'runtime_controller.dart';
10
import 'endpoint_settings.dart';
@@ -1034,6 +1035,7 @@ class _HomeShellState extends State<HomeShell> {
1035
'امتحانها و نمرات',
1036
'تمرکز',
1037
'همراه هوشمند',
1038
+ 'مدرسه من',
1039
];
1040
1041
static const adultPages = [
@@ -1042,6 +1044,7 @@ class _HomeShellState extends State<HomeShell> {
1044
'خانواده',
1045
'راهنما',
1046
'من',
1047
+ 'مدرسه من',
1048
];
1049
1050
@override
@@ -1136,6 +1139,14 @@ class _HomeShellState extends State<HomeShell> {
1139
appBar: AppBar(
1140
title: Text(pages[index]),
1141
actions: [
1142
+ IconButton(
1143
+ tooltip: 'مدرسه من',
1144
+ icon: const Icon(Icons.menu_book_outlined),
1145
+ onPressed: () => Navigator.of(context).push(MaterialPageRoute(
1146
+ builder: (_) => Scaffold(
1147
+ appBar: AppBar(title: const Text('مدرسه من')),
1148
+ body: EducationLibraryPage(api: widget.api)))),
1149
+ ),
1150
IconButton(
1151
onPressed: () async {
1152
await Navigator.of(context).push(MaterialPageRoute(
@@ -1153,19 +1164,21 @@ class _HomeShellState extends State<HomeShell> {
1164
onPressed: loadContext, child: const Text('تلاش دوباره'))
1165
]),
1166
Expanded(
1156
- child: pages[index] == 'من'
1157
- ? ProfileFamilyPage(api: widget.api)
1158
- : (pages[index] == 'همراه هوشمند' ||
1159
- pages[index] == 'راهنما')
1160
- ? const CoreNotice(
1161
- title: 'همراه هوشمند',
1162
- subtitle:
1163
- 'در این مرحله فعال نیست؛ داده سلامت و گفتوگو به سرویس هوشمند ارسال نمیشود.')
1164
- : Phase3HomeContent(
1165
- api: widget.api,
1166
- page: pages[index],
1167
- adultShell: adultShell,
1168
- ))
1167
+ child: pages[index] == 'مدرسه من'
1168
+ ? EducationLibraryPage(api: widget.api)
1169
+ : pages[index] == 'من'
1170
+ ? ProfileFamilyPage(api: widget.api)
1171
+ : (pages[index] == 'همراه هوشمند' ||
1172
+ pages[index] == 'راهنما')
1173
+ ? const CoreNotice(
1174
+ title: 'همراه هوشمند',
1175
+ subtitle:
1176
+ 'در این مرحله فعال نیست؛ داده سلامت و گفتوگو به سرویس هوشمند ارسال نمیشود.')
1177
+ : Phase3HomeContent(
1178
+ api: widget.api,
1179
+ page: pages[index],
1180
+ adultShell: adultShell,
1181
+ ))
1182
]),
1183
bottomNavigationBar: NavigationBar(
1184
selectedIndex: index > 4 ? 0 : index,
apps/lifemate/lib/offline_store.dart
+8
-5
@@ -339,7 +339,9 @@ class OfflineStore {
339
});
340
341
Future<void> discardEntityChanges(String entityId,
342
- {Map<String, dynamic>? serverItem, String? cacheKey}) =>
342
+ {Map<String, dynamic>? serverItem,
343
+ String? cacheKey,
344
+ String? entityType}) =>
345
_mutate((doc) {
346
if (serverItem != null &&
347
(serverItem['id'] != entityId ||
@@ -351,8 +353,10 @@ class OfflineStore {
353
throw const ApiException(500, 'local_data_corrupt');
354
}
355
final queue = doc['queue'] as List;
354
- final removed =
355
- queue.where((m) => (m as Map)['entityId'] == entityId).toList();
356
+ bool matches(dynamic raw) =>
357
+ (raw as Map)['entityId'] == entityId &&
358
+ (entityType == null || raw['entityType'] == entityType);
359
+ final removed = queue.where(matches).toList();
360
if (removed.isEmpty) return;
361
final title = removed.reversed
362
.map((m) => (m as Map)['payload'] as Map)
@@ -369,8 +373,7 @@ class OfflineStore {
373
'recoveryTitle': title
374
}
375
];
372
- doc['queue'] =
373
- queue.where((m) => (m as Map)['entityId'] != entityId).toList();
376
+ doc['queue'] = queue.where((m) => !matches(m)).toList();
377
for (final key
378
in cacheKey == null ? ['planner', 'today'] : [cacheKey]) {
379
final list = (doc['caches'] as Map)[key] as List? ?? [];
apps/lifemate/lib/sync_changes_ui.dart
+45
@@ -5,6 +5,9 @@ import 'offline_store.dart';
5
import 'phase3_ui.dart' show uiErrorText;
6
import 'plan_sync.dart';
7
import 'study_coordinator.dart';
8
+import 'learning_sync.dart';
9
+import 'learning_feedback_ui.dart';
10
+import 'learning_quiz_ui.dart';
11
12
class SyncChangesPage extends StatefulWidget {
13
const SyncChangesPage({super.key, required this.api});
@@ -74,6 +77,21 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
77
} catch (caught) {
78
failure ??= caught;
79
}
80
+ try {
81
+ await LearningSync(api, store: store).flush();
82
+ } catch (caught) {
83
+ failure ??= caught;
84
+ }
85
+ try {
86
+ await LearningFeedbackSync(api, store: store).flush();
87
+ } catch (caught) {
88
+ failure ??= caught;
89
+ }
90
+ try {
91
+ await LearningQuizSync(api, store: store).flush();
92
+ } catch (caught) {
93
+ failure ??= caught;
94
+ }
95
}
96
if (failure != null) throw failure;
97
} catch (failure) {
@@ -98,6 +116,33 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
116
error = null;
117
});
118
try {
119
+ if (['learning_feedback', 'learning_attempt']
120
+ .contains(mutation['entityType'])) {
121
+ throw const ApiException(409, 'feedback_retry_or_edit_draft');
122
+ }
123
+ if (mutation['entityType'] == 'learning_progress') {
124
+ if (!mounted) return;
125
+ setState(() => dialogOpen = true);
126
+ final accepted = await showDialog<bool>(
127
+ context: context,
128
+ builder: (dialogContext) => AlertDialog(
129
+ title: const Text('تعارض پیشرفت درس'),
130
+ content: Text(
131
+ 'تغییر محلی: ${_details(mutation['payload'] as Map)}\n'
132
+ 'با استفاده از سرور، تغییر محلی در سابقه بازیابی نگه داشته میشود و پیشرفت تازه سرور نمایش داده خواهد شد.'),
133
+ actions: [
134
+ TextButton(
135
+ onPressed: () => Navigator.pop(dialogContext, false),
136
+ child: const Text('نگهداشتن تغییر محلی')),
137
+ FilledButton(
138
+ onPressed: () => Navigator.pop(dialogContext, true),
139
+ child: const Text('استفاده از نسخه سرور')),
140
+ ]));
141
+ if (accepted == true && mounted) {
142
+ await LearningSync(api, store: store).resolveUsingServer(id);
143
+ }
144
+ return;
145
+ }
146
Map<String, dynamic>? serverItem;
147
try {
148
serverItem = await api.requestJson(
apps/lifemate/pubspec.lock
+35
-3
@@ -539,13 +539,45 @@ packages:
539
source: hosted
540
version: "15.3.0"
541
web:
542
- dependency: transitive
542
+ dependency: "direct main"
543
description:
544
name: web
545
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
546
url: "https://pub.dev"
547
source: hosted
548
version: "1.1.1"
549
+ webview_flutter:
550
+ dependency: "direct main"
551
+ description:
552
+ name: webview_flutter
553
+ sha256: d53e1ccf5516f25017e3c9d44c39034db352d20fa34fe200674270242c2c5111
554
+ url: "https://pub.dev"
555
+ source: hosted
556
+ version: "4.14.1"
557
+ webview_flutter_android:
558
+ dependency: "direct main"
559
+ description:
560
+ name: webview_flutter_android
561
+ sha256: "4de8b3d1ff4ebe1bdb42e68a5e4f809194a3cb0117a8f495f590004f00da3964"
562
+ url: "https://pub.dev"
563
+ source: hosted
564
+ version: "4.14.1"
565
+ webview_flutter_platform_interface:
566
+ dependency: transitive
567
+ description:
568
+ name: webview_flutter_platform_interface
569
+ sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04"
570
+ url: "https://pub.dev"
571
+ source: hosted
572
+ version: "2.15.1"
573
+ webview_flutter_wkwebview:
574
+ dependency: transitive
575
+ description:
576
+ name: webview_flutter_wkwebview
577
+ sha256: a9cc3f507ee40127ed0812ca54d00701a27833f51ea0b5820f4b3e7f42518bf3
578
+ url: "https://pub.dev"
579
+ source: hosted
580
+ version: "3.27.0"
581
win32:
582
dependency: transitive
583
description:
@@ -571,5 +603,5 @@ packages:
603
source: hosted
604
version: "3.1.4"
605
sdks:
574
- dart: ">=3.12.0 <4.0.0"
575
- flutter: ">=3.44.0"
606
+ dart: ">=3.13.0 <4.0.0"
607
+ flutter: ">=3.47.0"
apps/lifemate/pubspec.yaml
+4
-1
@@ -1,5 +1,5 @@
1
name: lifemate
2
-version: 0.5.1+4
2
+version: 0.6.0+5
3
publish_to: none
4
description: LifeGuide personal, family and learning companion.
5
environment:
@@ -14,6 +14,9 @@ dependencies:
14
http: ^1.5.0
15
shared_preferences: ^2.5.3
16
flutter_secure_storage: ^10.0.0
17
+ web: ^1.1.1
18
+ webview_flutter: ^4.14.1
19
+ webview_flutter_android: ^4.14.1
20
dev_dependencies:
21
shared_preferences_platform_interface: ^2.4.2
22
flutter_test:
apps/lifemate/test/aparat_player_test.dart
new
+241
@@ -0,0 +1,241 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:flutter_test/flutter_test.dart';
3
+import 'package:lifemate/aparat_player.dart';
4
+
5
+class _PlayerPort implements AparatPlayerPort {
6
+ final List<Uri> frames = [];
7
+ ValueChanged<String>? fail;
8
+
9
+ @override
10
+ bool get isSupported => true;
11
+
12
+ @override
13
+ Widget buildFrame(BuildContext context,
14
+ {required Uri uri,
15
+ required String title,
16
+ required VoidCallback onFrameReady,
17
+ required ValueChanged<String> onError}) {
18
+ frames.add(uri);
19
+ fail = onError;
20
+ return const ColoredBox(
21
+ key: ValueKey('fixture-frame'), color: Colors.black);
22
+ }
23
+}
24
+
25
+Widget _app(_PlayerPort port, {String hash = 'rod03i6'}) => MaterialApp(
26
+ home: Scaffold(
27
+ body: AparatPlayerPortScope(
28
+ port: port,
29
+ child: AparatPlayer(videoHash: hash, title: 'درس نمونه'))));
30
+
31
+void main() {
32
+ test('hash policy rejects URLs, escaped paths and unbounded identifiers', () {
33
+ for (final hash in [
34
+ '',
35
+ 'abcd',
36
+ 'a' * 65,
37
+ 'rod03i6?autoplay=true',
38
+ 'rod03i6/other',
39
+ '%72od03i6',
40
+ 'رود۳',
41
+ 'https://www.aparat.com/v/rod03i6',
42
+ ' rod03i6',
43
+ 'rod03i6\n'
44
+ ]) {
45
+ expect(aparatEmbedUri(hash), isNull, reason: hash);
46
+ }
47
+ expect(aparatEmbedUri('rOd03i6').toString(),
48
+ 'https://www.aparat.com/video/video/embed/videohash/rOd03i6/vt/frame');
49
+ });
50
+
51
+ test('native navigation allows only the selected canonical HTTPS frame', () {
52
+ final canonical = aparatEmbedUri('rod03i6')!;
53
+ expect(isAllowedAparatNavigation(canonical.toString(), 'rod03i6'), isTrue);
54
+ expect(
55
+ isAllowedAparatNavigation(
56
+ canonical.replace(host: 'aparat.com').toString(), 'rod03i6'),
57
+ isTrue);
58
+ for (final url in [
59
+ 'http://www.aparat.com${canonical.path}',
60
+ 'https://www.aparat.com.evil.test${canonical.path}',
61
+ 'https://evil.test${canonical.path}',
62
+ 'https://user@www.aparat.com${canonical.path}',
63
+ 'https://www.aparat.com:444${canonical.path}',
64
+ 'https://www.aparat.com/video/video/embed/videohash/%72od03i6/vt/frame',
65
+ '${canonical.toString()}?autoplay=true',
66
+ '${canonical.toString()}#other',
67
+ 'https://www.aparat.com/v/rod03i6',
68
+ 'https://www.aparat.com/video/video/embed/videohash/other01/vt/frame',
69
+ 'javascript:alert(1)',
70
+ 'intent://www.aparat.com',
71
+ 'about:blank'
72
+ ]) {
73
+ expect(isAllowedAparatNavigation(url, 'rod03i6'), isFalse, reason: url);
74
+ }
75
+ });
76
+
77
+ testWidgets('no provider frame exists until the explicit load click',
78
+ (tester) async {
79
+ final port = _PlayerPort();
80
+ await tester.pumpWidget(_app(port));
81
+ expect(port.frames, isEmpty);
82
+ expect(find.textContaining('حریم خصوصی'), findsOneWidget);
83
+ await tester.tap(find.text('بارگذاری ویدئو از آپارات'));
84
+ await tester.pump();
85
+ expect(find.byKey(const ValueKey('fixture-frame')), findsOneWidget);
86
+ expect(port.frames.single.toString(),
87
+ 'https://www.aparat.com/video/video/embed/videohash/rod03i6/vt/frame');
88
+ expect(port.frames.single.hasQuery, isFalse);
89
+ expect(port.frames.single.hasFragment, isFalse);
90
+ expect(find.textContaining('اثبات مطالعه'), findsOneWidget);
91
+ });
92
+
93
+ testWidgets('invalid identifier cannot load a remote player', (tester) async {
94
+ final port = _PlayerPort();
95
+ await tester.pumpWidget(_app(port, hash: 'rod03i6?autoplay=true'));
96
+ expect(find.textContaining('شناسهٔ ویدئو معتبر نیست'), findsOneWidget);
97
+ expect(find.text('بارگذاری ویدئو از آپارات'), findsNothing);
98
+ expect(port.frames, isEmpty);
99
+ });
100
+
101
+ testWidgets('load failure removes the frame and offers an explicit retry',
102
+ (tester) async {
103
+ final port = _PlayerPort();
104
+ await tester.pumpWidget(_app(port));
105
+ await tester.tap(find.text('بارگذاری ویدئو از آپارات'));
106
+ await tester.pump();
107
+ port.fail!('network');
108
+ await tester.pump();
109
+ expect(find.byKey(const ValueKey('fixture-frame')), findsNothing);
110
+ expect(find.textContaining('بارگذاری آپارات انجام نشد'), findsOneWidget);
111
+ await tester.tap(find.text('تلاش دوباره'));
112
+ await tester.pump();
113
+ expect(find.byKey(const ValueKey('fixture-frame')), findsOneWidget);
114
+ expect(port.frames, hasLength(2));
115
+ });
116
+
117
+ testWidgets(
118
+ 'new selection requires consent again and stale errors are ignored',
119
+ (tester) async {
120
+ final port = _PlayerPort();
121
+ await tester.pumpWidget(_app(port));
122
+ await tester.tap(find.text('بارگذاری ویدئو از آپارات'));
123
+ await tester.pump();
124
+ final oldFailure = port.fail!;
125
+ await tester.pumpWidget(_app(port, hash: 'new0123'));
126
+ await tester.pump();
127
+ expect(find.byKey(const ValueKey('fixture-frame')), findsNothing);
128
+ oldFailure('late failure');
129
+ await tester.pump();
130
+ expect(find.textContaining('بارگذاری آپارات انجام نشد'), findsNothing);
131
+ expect(find.text('بارگذاری ویدئو از آپارات'), findsOneWidget);
132
+ expect(port.frames, hasLength(1));
133
+ });
134
+
135
+ testWidgets('closing the player removes remote content', (tester) async {
136
+ final port = _PlayerPort();
137
+ await tester.pumpWidget(_app(port));
138
+ await tester.tap(find.text('بارگذاری ویدئو از آپارات'));
139
+ await tester.pump();
140
+ await tester.tap(find.text('بستن پخشکننده'));
141
+ await tester.pump();
142
+ expect(find.byKey(const ValueKey('fixture-frame')), findsNothing);
143
+ expect(find.text('بارگذاری ویدئو از آپارات'), findsOneWidget);
144
+ });
145
+
146
+ testWidgets('backgrounding removes provider content and requires a new click',
147
+ (tester) async {
148
+ final port = _PlayerPort();
149
+ await tester.pumpWidget(_app(port));
150
+ await tester.tap(find.text('بارگذاری ویدئو از آپارات'));
151
+ await tester.pump();
152
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
153
+ await tester.pump();
154
+ expect(find.byKey(const ValueKey('fixture-frame')), findsNothing);
155
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
156
+ await tester.pump();
157
+ expect(find.text('بارگذاری ویدئو از آپارات'), findsOneWidget);
158
+ expect(port.frames, hasLength(1));
159
+ });
160
+
161
+ testWidgets('unsupported desktop explains the in-page limitation',
162
+ (tester) async {
163
+ await tester.pumpWidget(const MaterialApp(
164
+ home: Scaffold(
165
+ body: AparatPlayer(videoHash: 'rod03i6', title: 'درس نمونه'))));
166
+ await tester.tap(find.text('بارگذاری ویدئو از آپارات'));
167
+ await tester.pump();
168
+ expect(find.textContaining('پخش در این نسخه پشتیبانی نمیشود'),
169
+ findsOneWidget);
170
+ }, variant: TargetPlatformVariant.only(TargetPlatform.linux));
171
+
172
+ testWidgets('fullscreen Back returns the native view once', (tester) async {
173
+ final navigator = GlobalKey<NavigatorState>();
174
+ await tester.pumpWidget(MaterialApp(
175
+ navigatorKey: navigator, home: const Text('underlying app')));
176
+ final presenter =
177
+ AparatFullscreenPresenter(navigator: navigator.currentState!);
178
+ var returned = 0;
179
+ presenter.show(const Text('native fullscreen'), () {
180
+ returned++;
181
+ presenter
182
+ .hide(); // Native custom-view hide can follow the close callback.
183
+ });
184
+ await tester.pumpAndSettle();
185
+ expect(find.text('native fullscreen'), findsOneWidget);
186
+ await tester.binding.handlePopRoute();
187
+ await tester.pumpAndSettle();
188
+ expect(returned, 1);
189
+ presenter.hide();
190
+ await tester.pumpAndSettle();
191
+ expect(find.text('underlying app'), findsOneWidget);
192
+ expect(returned, 1);
193
+ presenter.dispose();
194
+ });
195
+
196
+ testWidgets('native fullscreen hide removes its route without popping others',
197
+ (tester) async {
198
+ final navigator = GlobalKey<NavigatorState>();
199
+ await tester.pumpWidget(MaterialApp(
200
+ navigatorKey: navigator, home: const Text('underlying app')));
201
+ final presenter =
202
+ AparatFullscreenPresenter(navigator: navigator.currentState!);
203
+ var returned = 0;
204
+ presenter.show(const Text('native fullscreen'), () => returned++);
205
+ await tester.pumpAndSettle();
206
+ navigator.currentState!.push(MaterialPageRoute<void>(
207
+ builder: (_) => const Scaffold(body: Text('another app route'))));
208
+ await tester.pumpAndSettle();
209
+ presenter.hide();
210
+ presenter.hide();
211
+ await tester.pumpAndSettle();
212
+ expect(find.text('another app route'), findsOneWidget);
213
+ expect(returned, 0);
214
+ navigator.currentState!.pop();
215
+ await tester.pumpAndSettle();
216
+ expect(find.text('underlying app'), findsOneWidget);
217
+ presenter.dispose();
218
+ });
219
+
220
+ testWidgets('fullscreen close and disposal notify native only once',
221
+ (tester) async {
222
+ final navigator = GlobalKey<NavigatorState>();
223
+ await tester.pumpWidget(MaterialApp(
224
+ navigatorKey: navigator, home: const Text('underlying app')));
225
+ final presenter =
226
+ AparatFullscreenPresenter(navigator: navigator.currentState!);
227
+ var returned = 0;
228
+ presenter.show(const Text('native fullscreen'), () => returned++);
229
+ await tester.pumpAndSettle();
230
+ await tester.tap(find.byTooltip('خروج از تمامصفحه'));
231
+ await tester.pumpAndSettle();
232
+ expect(returned, 1);
233
+ presenter.show(const Text('native fullscreen again'), () => returned++);
234
+ await tester.pumpAndSettle();
235
+ presenter.dispose();
236
+ presenter.hide();
237
+ await tester.pumpAndSettle();
238
+ expect(returned, 2);
239
+ expect(find.text('underlying app'), findsOneWidget);
240
+ });
241
+}
apps/lifemate/test/education_ui_test.dart
new
+236
@@ -0,0 +1,236 @@
1
+import 'dart:convert';
2
+
3
+import 'package:flutter/material.dart';
4
+import 'package:flutter/services.dart';
5
+import 'package:flutter_test/flutter_test.dart';
6
+import 'package:http/http.dart' as http;
7
+import 'package:http/testing.dart';
8
+import 'package:lifemate/api.dart';
9
+import 'package:lifemate/education_ui.dart';
10
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
11
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
12
+
13
+// Explicit HTTP/widget fixtures, not evidence of a live curriculum or playback.
14
+const courseId = '10000000-0000-4000-8000-000000000001';
15
+const firstId = '20000000-0000-4000-8000-000000000001';
16
+const lastId = '20000000-0000-4000-8000-000000000002';
17
+
18
+void main() {
19
+ TestWidgetsFlutterBinding.ensureInitialized();
20
+ setUp(() {
21
+ SharedPreferencesAsyncPlatform.instance =
22
+ InMemorySharedPreferencesAsync.withData({});
23
+ String? token;
24
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
25
+ .setMockMethodCallHandler(
26
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
27
+ if (call.method == 'getBlocked') return token != null;
28
+ if (call.method == 'beginWrite') {
29
+ return token = 'education-widget-fixture';
30
+ }
31
+ if (call.method == 'completeWrite' && call.arguments == token) {
32
+ token = null;
33
+ return true;
34
+ }
35
+ throw PlatformException(code: 'local_storage_restart_required');
36
+ });
37
+ });
38
+
39
+ Widget screen(Widget child) => MaterialApp(
40
+ home: Scaffold(
41
+ body:
42
+ Directionality(textDirection: TextDirection.rtl, child: child)));
43
+ http.Response response(Object data) => http.Response(jsonEncode(data), 200,
44
+ headers: {'content-type': 'application/json; charset=utf-8'});
45
+ HttpIdentityApi makeApi(
46
+ Future<http.Response> Function(http.Request) handler) =>
47
+ HttpIdentityApi(
48
+ baseUrl: 'https://education.example.test/api',
49
+ client: MockClient(handler))
50
+ ..accessToken = 'synthetic-fixture-token'
51
+ ..currentUserId = 'synthetic-learner';
52
+
53
+ testWidgets(
54
+ 'no education profile asks selection without silently choosing grade7',
55
+ (tester) async {
56
+ final api = makeApi((request) async => response({
57
+ 'education': null,
58
+ 'courses': [],
59
+ 'fetchedAt': '2026-10-09T10:00:00Z'
60
+ }));
61
+ await tester.pumpWidget(screen(EducationLibraryPage(api: api)));
62
+ await tester.pumpAndSettle();
63
+ expect(find.textContaining('پایه تحصیلی را انتخاب کن'), findsOneWidget);
64
+ expect(find.textContaining('پایه 7'), findsNothing);
65
+ expect(tester.takeException(), isNull);
66
+ api.close();
67
+ });
68
+
69
+ testWidgets(
70
+ 'grade and upper track are saved through real API contract, not a display-only preference',
71
+ (tester) async {
72
+ Map<String, dynamic>? saved;
73
+ final api = makeApi((request) async {
74
+ if (request.method == 'PUT') {
75
+ expect(request.url.path, '/api/v1/me/education');
76
+ saved = jsonDecode(request.body) as Map<String, dynamic>;
77
+ return response(saved!);
78
+ }
79
+ return response({
80
+ 'education': {
81
+ 'nationalGrade': 10,
82
+ 'trackCode': 'math',
83
+ 'schoolYear': '1405-1406'
84
+ },
85
+ 'courses': []
86
+ });
87
+ });
88
+ await tester.pumpWidget(screen(EducationLibraryPage(api: api)));
89
+ await tester.pumpAndSettle();
90
+ await tester.tap(find.text('انتخاب پایه و رشته'));
91
+ await tester.pumpAndSettle();
92
+ await tester.tap(find.byKey(const ValueKey('education-track')));
93
+ await tester.pumpAndSettle();
94
+ await tester.tap(find.text('علوم تجربی').last);
95
+ await tester.pumpAndSettle();
96
+ await tester.tap(find.text('ذخیره'));
97
+ await tester.pumpAndSettle();
98
+ expect(saved, {
99
+ 'nationalGrade': 10,
100
+ 'trackCode': 'experimental',
101
+ 'schoolYear': '1405-1406'
102
+ });
103
+ expect(tester.takeException(), isNull);
104
+ api.close();
105
+ });
106
+
107
+ testWidgets(
108
+ 'midyear last lesson opens in same app with no video load or automatic completion',
109
+ (tester) async {
110
+ var writes = 0;
111
+ final api = makeApi((request) async {
112
+ if (request.method != 'GET') writes++;
113
+ expect(request.url.path, '/api/v1/education/courses/$courseId');
114
+ return response({
115
+ 'id': courseId,
116
+ 'titleFa': 'کتاب آزمایشی',
117
+ 'schoolYear': null,
118
+ 'alignmentNotesFa': 'تطابق نسخه تأیید نشده',
119
+ 'fetchedAt': '2026-10-09T10:00:00Z',
120
+ 'units': [
121
+ {
122
+ 'id': firstId,
123
+ 'titleFa': 'بخش آغاز',
124
+ 'orderIndex': 1,
125
+ 'videos': [],
126
+ 'progress': null
127
+ },
128
+ {
129
+ 'id': lastId,
130
+ 'titleFa': 'بخش میانه سال',
131
+ 'orderIndex': 2,
132
+ 'progress': null,
133
+ 'videos': [
134
+ {
135
+ 'aparatId': 'rod03i6',
136
+ 'titleFa': 'منبع آزمایشی قاب',
137
+ 'creatorName': 'مدرس نمونه',
138
+ 'creatorUrl': 'https://www.aparat.com/example',
139
+ 'freeAccess': true
140
+ }
141
+ ]
142
+ }
143
+ ]
144
+ });
145
+ });
146
+ await tester
147
+ .pumpWidget(screen(LearningCoursePage(api: api, courseId: courseId)));
148
+ await tester.pumpAndSettle();
149
+ await tester.tap(find.text('بخش میانه سال'));
150
+ await tester.pumpAndSettle();
151
+ expect(find.text('بارگذاری ویدئو از آپارات'), findsOneWidget);
152
+ await tester.scrollUntilVisible(find.textContaining('پیشرفت شخصی:'), 100,
153
+ scrollable: find.byType(Scrollable).first);
154
+ expect(find.textContaining('پیشرفت شخصی: شروع نشده'), findsOneWidget);
155
+ await tester.scrollUntilVisible(find.text('بخش قبلی'), 300,
156
+ scrollable: find.byType(Scrollable).first);
157
+ expect(find.text('بخش قبلی'), findsOneWidget);
158
+ expect(writes, 0);
159
+ expect(tester.takeException(), isNull);
160
+ await tester.pumpWidget(const SizedBox());
161
+ api.close();
162
+ });
163
+
164
+ testWidgets(
165
+ 'permission denial removes previously displayed personal progress',
166
+ (tester) async {
167
+ var denied = false;
168
+ final api = makeApi((request) async {
169
+ if (denied) return http.Response('{"error":"forbidden"}', 403);
170
+ return response({
171
+ 'id': courseId,
172
+ 'titleFa': 'کتاب خصوصی آزمایشی',
173
+ 'units': [
174
+ {
175
+ 'id': firstId,
176
+ 'titleFa': 'درس خصوصی آزمایشی',
177
+ 'videos': [],
178
+ 'progress': {
179
+ 'unitId': firstId,
180
+ 'status': 'completed',
181
+ 'source': 'self_reported',
182
+ 'version': 1,
183
+ 'updatedAt': '2026-10-09T10:00:00Z'
184
+ }
185
+ }
186
+ ]
187
+ });
188
+ });
189
+ await tester.pumpWidget(screen(
190
+ LearningLessonPage(api: api, courseId: courseId, unitId: firstId)));
191
+ await tester.pumpAndSettle();
192
+ expect(find.textContaining('تکمیل طبق گزارش من'), findsOneWidget);
193
+ denied = true;
194
+ await tester.scrollUntilVisible(find.text('همگامسازی و تازهسازی'), 250,
195
+ scrollable: find.byType(Scrollable).first);
196
+ await tester.tap(find.text('همگامسازی و تازهسازی'));
197
+ await tester.pumpAndSettle();
198
+ expect(find.textContaining('تکمیل طبق گزارش من'), findsNothing);
199
+ expect(find.text('درس خصوصی آزمایشی'), findsNothing);
200
+ expect(find.textContaining('نشست معتبر لازم است'), findsOneWidget);
201
+ expect(tester.takeException(), isNull);
202
+ await tester.pumpWidget(const SizedBox());
203
+ api.close();
204
+ });
205
+
206
+ testWidgets('rejected progress remains visible after a successful read',
207
+ (tester) async {
208
+ final api = makeApi((request) async {
209
+ if (request.method == 'PUT') {
210
+ return http.Response('{"error":"version_conflict"}', 409);
211
+ }
212
+ return response({
213
+ 'id': courseId,
214
+ 'titleFa': 'کتاب آزمایشی',
215
+ 'units': [
216
+ {
217
+ 'id': firstId,
218
+ 'titleFa': 'درس آزمایشی',
219
+ 'videos': [],
220
+ 'progress': null
221
+ }
222
+ ]
223
+ });
224
+ });
225
+ await tester.pumpWidget(screen(
226
+ LearningLessonPage(api: api, courseId: courseId, unitId: firstId)));
227
+ await tester.pumpAndSettle();
228
+ await tester.tap(find.text('در حال یادگیری'));
229
+ await tester.pumpAndSettle();
230
+ expect(find.textContaining('تغییر معلق یا تعارض'), findsOneWidget);
231
+ expect(find.text('حل تعارض با پیشرفت سرور'), findsOneWidget);
232
+ expect(tester.takeException(), isNull);
233
+ await tester.pumpWidget(const SizedBox());
234
+ api.close();
235
+ });
236
+}
apps/lifemate/test/endpoint_settings_test.dart
+50
@@ -4,6 +4,54 @@ import 'package:lifemate/endpoint_settings.dart';
4
import 'package:lifemate/runtime_config.dart';
5
6
void main() {
7
+ testWidgets('fresh install explains setup and cannot save an empty endpoint',
8
+ (tester) async {
9
+ var saved = false;
10
+ await tester.pumpWidget(MaterialApp(
11
+ home: EndpointSettingsPage(
12
+ initialConfig: RuntimeConfig(),
13
+ onSaved: (_) async => saved = true)));
14
+ expect(find.text('راهاندازی نسخه آزمایشی'), findsOneWidget);
15
+ expect(find.textContaining('نشانی کامل API'), findsOneWidget);
16
+ expect(find.textContaining('رمز عبور، کلید یا توکن وارد نکنید'),
17
+ findsOneWidget);
18
+ expect(find.textContaining('به معنی برقرارشدن اتصال نیست'), findsOneWidget);
19
+ final save = tester.widget<FilledButton>(find.byType(FilledButton));
20
+ expect(save.onPressed, isNull);
21
+ expect(saved, isFalse);
22
+ expect(
23
+ tester.widget<TextField>(find.byType(TextField).first).controller!.text,
24
+ isEmpty);
25
+ });
26
+ testWidgets('an operator endpoint is normalized and saved only on submission',
27
+ (tester) async {
28
+ final saved = <RuntimeConfig>[];
29
+ await tester.pumpWidget(MaterialApp(
30
+ home: EndpointSettingsPage(
31
+ initialConfig: RuntimeConfig(),
32
+ onSaved: (config) async => saved.add(config))));
33
+ await tester.enterText(
34
+ find.byType(TextField).first, ' https://operator.example.test/api/ ');
35
+ await tester.pump();
36
+ expect(saved, isEmpty);
37
+ await tester.ensureVisible(find.text('ذخیره و ادامه'));
38
+ await tester.tap(find.text('ذخیره و ادامه'));
39
+ await tester.pumpAndSettle();
40
+ expect(saved.single.apiBaseUrl, 'https://operator.example.test/api');
41
+ expect(saved.single.apiFallbackUrls, isEmpty);
42
+ });
43
+ testWidgets('editing a saved server warns about unsent changes',
44
+ (tester) async {
45
+ await tester.pumpWidget(MaterialApp(
46
+ home: EndpointSettingsPage(
47
+ initialConfig:
48
+ RuntimeConfig(apiBaseUrl: 'https://operator.example.test/api'),
49
+ onSaved: (_) async {})));
50
+ expect(find.text('تنظیم اتصال'), findsOneWidget);
51
+ expect(find.textContaining('تغییر سرویس شما را از حساب قبلی خارج میکند'),
52
+ findsOneWidget);
53
+ expect(find.textContaining('دادههای ارسالنشده'), findsOneWidget);
54
+ });
55
testWidgets('fallback selection requires save and preserves the old primary',
56
(tester) async {
57
RuntimeConfig? saved;
@@ -35,6 +83,8 @@ void main() {
83
onSaved: (_) async => saved = true)));
84
await tester.enterText(
85
find.byType(TextField).first, 'https://user:password@api.example.test');
86
+ await tester.pump();
87
+ await tester.ensureVisible(find.text('ذخیره و ادامه'));
88
await tester.tap(find.text('ذخیره و ادامه'));
89
await tester.pumpAndSettle();
90
expect(saved, isFalse);
apps/lifemate/test/learning_feedback_test.dart
new
+198
@@ -0,0 +1,198 @@
1
+import 'dart:convert';
2
+import 'dart:async';
3
+
4
+import 'package:flutter/material.dart';
5
+import 'package:flutter/services.dart';
6
+import 'package:flutter_test/flutter_test.dart';
7
+import 'package:http/http.dart' as http;
8
+import 'package:http/testing.dart';
9
+import 'package:lifemate/api.dart';
10
+import 'package:lifemate/learning_feedback_ui.dart';
11
+import 'package:lifemate/offline_store.dart';
12
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
13
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14
+
15
+void main() {
16
+ TestWidgetsFlutterBinding.ensureInitialized();
17
+ setUp(() {
18
+ SharedPreferencesAsyncPlatform.instance =
19
+ InMemorySharedPreferencesAsync.withData({});
20
+ String? token;
21
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
22
+ .setMockMethodCallHandler(
23
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
24
+ if (call.method == 'getBlocked') return token != null;
25
+ if (call.method == 'beginWrite') return token = 'feedback-fixture';
26
+ if (call.method == 'completeWrite' && call.arguments == token) {
27
+ token = null;
28
+ return true;
29
+ }
30
+ throw PlatformException(code: 'local_storage_restart_required');
31
+ });
32
+ });
33
+ const mutationId = '81111111-1111-4111-8111-111111111111';
34
+ const body = {
35
+ 'mutationId': mutationId,
36
+ 'unitId': null,
37
+ 'category': 'topic_request',
38
+ 'summary': 'درخواست تمرین بیشتر',
39
+ 'shareWithContentTeam': true
40
+ };
41
+
42
+ test(
43
+ 'explicit feedback survives reopening and retries the same consented summary',
44
+ () async {
45
+ var offline = true;
46
+ final sent = <Map<String, dynamic>>[];
47
+ final api = HttpIdentityApi(
48
+ baseUrl: 'https://feedback.example.test/api',
49
+ client: MockClient((request) async {
50
+ expect(request.url.path, '/api/v1/education/feedback');
51
+ if (offline) throw http.ClientException('synthetic offline');
52
+ sent.add(jsonDecode(request.body) as Map<String, dynamic>);
53
+ return http.Response(
54
+ jsonEncode({
55
+ 'feedback': {
56
+ 'id': '91111111-1111-4111-8111-111111111111',
57
+ 'mutationId': mutationId,
58
+ 'unitId': null,
59
+ 'category': 'topic_request',
60
+ 'summary': 'درخواست تمرین بیشتر',
61
+ 'shareWithContentTeam': true,
62
+ 'withdrawnAt': null,
63
+ 'status': 'received',
64
+ 'version': 1,
65
+ 'updatedAt': '2026-10-09T10:00:00Z',
66
+ 'createdAt': '2026-10-09T10:00:00Z'
67
+ },
68
+ 'acknowledgement': {
69
+ 'mutationId': mutationId,
70
+ 'feedbackId': '91111111-1111-4111-8111-111111111111',
71
+ 'status': 'already_applied'
72
+ }
73
+ }),
74
+ 200,
75
+ headers: {'content-type': 'application/json; charset=utf-8'});
76
+ }))
77
+ ..accessToken = 'synthetic-token'
78
+ ..currentUserId = 'synthetic-owner';
79
+ final scope = api.cacheNamespace!;
80
+ expect((await LearningFeedbackSync(api).submit(body))['queued'], true);
81
+ final saved = await OfflineStore.forNamespace(scope).readQueue();
82
+ expect(saved.single['payload'], body);
83
+ offline = false;
84
+ await LearningFeedbackSync(api, store: OfflineStore.forNamespace(scope))
85
+ .flush();
86
+ await LearningFeedbackSync(api).flush();
87
+ expect(sent, [body]);
88
+ expect(await OfflineStore.forNamespace(scope).readQueue(), isEmpty);
89
+ expect(await OfflineStore.forNamespace(scope).readPlanner(), isEmpty);
90
+ expect(await OfflineStore.forNamespace(scope).readLastAck(), isNotNull);
91
+ api.close();
92
+ });
93
+
94
+ test('wrong feedback acknowledgement cannot remove an unsent summary',
95
+ () async {
96
+ final api = HttpIdentityApi(
97
+ baseUrl: 'https://feedback.example.test/api',
98
+ client: MockClient((request) async => http.Response(
99
+ jsonEncode({
100
+ 'feedback': {
101
+ 'id': '91111111-1111-4111-8111-111111111111',
102
+ 'mutationId': mutationId,
103
+ 'unitId': null,
104
+ 'category': 'topic_request',
105
+ 'summary': 'درخواست تمرین بیشتر',
106
+ 'shareWithContentTeam': true,
107
+ 'withdrawnAt': null,
108
+ 'status': 'received',
109
+ 'version': 1,
110
+ 'updatedAt': '2026-10-09T10:00:00Z',
111
+ 'createdAt': '2026-10-09T10:00:00Z'
112
+ },
113
+ 'acknowledgement': {
114
+ 'mutationId': mutationId,
115
+ 'feedbackId': 'different-receipt',
116
+ 'status': 'accepted'
117
+ }
118
+ }),
119
+ 200,
120
+ headers: {'content-type': 'application/json; charset=utf-8'})))
121
+ ..accessToken = 'synthetic-token'
122
+ ..currentUserId = 'synthetic-owner';
123
+ await expectLater(
124
+ LearningFeedbackSync(api).submit(body), throwsA(isA<ApiException>()));
125
+ expect(
126
+ (await OfflineStore.forApi(api).readQueue()).single['payload'], body);
127
+ api.close();
128
+ });
129
+
130
+ testWidgets('a delayed history response cannot restore a withdrawn summary',
131
+ (tester) async {
132
+ tester.view.physicalSize = const Size(900, 1400);
133
+ tester.view.devicePixelRatio = 1;
134
+ addTearDown(tester.view.resetPhysicalSize);
135
+ addTearDown(tester.view.resetDevicePixelRatio);
136
+ final delayed = Completer<http.Response>();
137
+ var reads = 0, withdrawn = false;
138
+ final row = <String, dynamic>{
139
+ 'id': '91111111-1111-4111-8111-111111111111',
140
+ 'mutationId': mutationId,
141
+ 'unitId': null,
142
+ 'category': 'topic_request',
143
+ 'summary': body['summary'],
144
+ 'shareWithContentTeam': true,
145
+ 'withdrawnAt': null,
146
+ 'status': 'received',
147
+ 'version': 1,
148
+ 'updatedAt': '2026-10-09T10:00:00Z',
149
+ 'createdAt': '2026-10-09T10:00:00Z'
150
+ };
151
+ http.Response response(Object value, [int status = 200]) =>
152
+ http.Response(jsonEncode(value), status,
153
+ headers: {'content-type': 'application/json; charset=utf-8'});
154
+ final api = HttpIdentityApi(
155
+ baseUrl: 'https://feedback.example.test/api',
156
+ client: MockClient((request) async {
157
+ if (request.method == 'GET') {
158
+ if (++reads == 1) return delayed.future;
159
+ return response({
160
+ 'feedback': withdrawn ? [] : [row]
161
+ });
162
+ }
163
+ if (request.method == 'DELETE') {
164
+ withdrawn = true;
165
+ return http.Response('', 204);
166
+ }
167
+ final sent = jsonDecode(request.body) as Map;
168
+ row['mutationId'] = sent['mutationId'];
169
+ return response({
170
+ 'feedback': row,
171
+ 'acknowledgement': {
172
+ 'mutationId': sent['mutationId'],
173
+ 'feedbackId': row['id'],
174
+ 'status': 'accepted'
175
+ }
176
+ }, 201);
177
+ }))
178
+ ..accessToken = 'synthetic-token'
179
+ ..currentUserId = 'synthetic-owner';
180
+ await tester.pumpWidget(MaterialApp(home: LearningFeedbackPage(api: api)));
181
+ await tester.pump();
182
+ await tester.enterText(find.byType(TextField), body['summary'] as String);
183
+ await tester.tap(find.byType(Checkbox));
184
+ await tester.tap(find.text('ارسال بازخورد'));
185
+ await tester.pumpAndSettle();
186
+ expect(find.text(body['summary'] as String), findsOneWidget);
187
+ await tester.tap(find.text('پسگرفتن رضایت'));
188
+ await tester.pumpAndSettle();
189
+ expect(withdrawn, true);
190
+ delayed.complete(response({
191
+ 'feedback': [row]
192
+ }));
193
+ await tester.pumpAndSettle();
194
+ expect(find.text(body['summary'] as String), findsNothing);
195
+ await tester.pumpWidget(const SizedBox());
196
+ api.close();
197
+ });
198
+}
apps/lifemate/test/learning_quiz_test.dart
new
+295
@@ -0,0 +1,295 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+import 'package:flutter/services.dart';
6
+import 'package:flutter_test/flutter_test.dart';
7
+import 'package:http/http.dart' as http;
8
+import 'package:http/testing.dart';
9
+import 'package:lifemate/api.dart';
10
+import 'package:lifemate/learning_quiz_ui.dart';
11
+import 'package:lifemate/offline_store.dart';
12
+import 'package:lifemate/session_store.dart';
13
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
14
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
15
+
16
+// SYNTHETIC reviewed-bank substitutes only. No real questions are published.
17
+const _unit = '00000000-0000-4000-8000-000000000101';
18
+const _assessment = '00000000-0000-4000-8000-000000000102';
19
+const _mutation = '00000000-0000-4000-8000-000000000103';
20
+const _attempt = '00000000-0000-4000-8000-000000000104';
21
+
22
+Map<String, dynamic> _body() => {
23
+ 'mutationId': _mutation,
24
+ 'assessmentId': _assessment,
25
+ 'assessmentVersion': 2,
26
+ 'answers': [
27
+ {'questionId': 'q1', 'choiceId': 'a'}
28
+ ],
29
+ 'confidence': 'unsure',
30
+ };
31
+
32
+Map<String, dynamic> _bank() => {
33
+ 'id': _assessment,
34
+ 'unitId': _unit,
35
+ 'version': 2,
36
+ 'questions': [
37
+ {
38
+ 'id': 'q1',
39
+ 'objectiveId': 'objective-1',
40
+ 'promptFa': 'پرسش صرفاً آزمایشی',
41
+ 'choices': [
42
+ {'id': 'a', 'textFa': 'گزینه آزمایشی الف'},
43
+ {'id': 'b', 'textFa': 'گزینه آزمایشی ب'},
44
+ ],
45
+ }
46
+ ],
47
+ };
48
+
49
+class _Session implements SessionStore {
50
+ @override
51
+ Future<String?> read() async => null;
52
+ @override
53
+ Future<void> write(String value) async {}
54
+ @override
55
+ Future<void> clear() async {}
56
+}
57
+
58
+class _Fixture {
59
+ _Fixture() {
60
+ api = HttpIdentityApi(
61
+ baseUrl: 'https://quiz.test',
62
+ client: MockClient(handle),
63
+ sessionStore: _Session(),
64
+ )
65
+ ..accessToken = 'synthetic-token'
66
+ ..currentUserId = 'synthetic-learner-${next++}';
67
+ store = OfflineStore.forNamespace(api.cacheNamespace!,
68
+ session: OfflineSession());
69
+ sync = LearningQuizSync(api, store: store);
70
+ }
71
+ static int next = 0;
72
+ late final HttpIdentityApi api;
73
+ late final OfflineStore store;
74
+ late final LearningQuizSync sync;
75
+ bool offline = false, loseAcknowledgement = false, reviewed = true;
76
+ int? failure;
77
+ Future<void>? delay;
78
+ final posts = <Map<String, dynamic>>[];
79
+ final applied = <String, Map<String, dynamic>>{};
80
+ Map<String, dynamic> Function(Map<String, dynamic>)? alterAck;
81
+
82
+ Future<http.Response> handle(http.Request request) async {
83
+ if (request.method == 'GET') {
84
+ return http.Response(
85
+ jsonEncode({
86
+ 'assessment': reviewed ? _bank() : null,
87
+ if (!reviewed) 'reason': 'review_pending'
88
+ }),
89
+ 200,
90
+ headers: {'content-type': 'application/json; charset=utf-8'});
91
+ }
92
+ expect(request.method, 'POST');
93
+ expect(request.url.path, '/v1/me/learning-attempts');
94
+ final body = Map<String, dynamic>.from(jsonDecode(request.body) as Map);
95
+ posts.add(body);
96
+ if (delay != null) await delay;
97
+ if (offline) throw http.ClientException('synthetic offline transport');
98
+ if (failure != null) {
99
+ return http.Response(
100
+ jsonEncode({'error': 'synthetic_rejection'}), failure!);
101
+ }
102
+ final id = body['mutationId'] as String;
103
+ applied.putIfAbsent(
104
+ id,
105
+ () => {
106
+ 'mutationId': id,
107
+ 'attemptId': _attempt,
108
+ 'unitId': _unit,
109
+ 'assessmentId': _assessment,
110
+ 'assessmentVersion': 2,
111
+ 'correctCount': 1,
112
+ 'total': 1,
113
+ 'feedback': [
114
+ {
115
+ 'questionId': 'q1',
116
+ 'objectiveId': 'objective-1',
117
+ 'correct': true,
118
+ 'explanationFa': 'توضیح صرفاً آزمایشی',
119
+ 'remediationFa': 'مرور صرفاً آزمایشی',
120
+ }
121
+ ],
122
+ 'resultLabel': 'answered_correctly',
123
+ 'nextReviewAt': '2026-10-12T10:00:00Z',
124
+ 'schedulePolicy': 'pilot-1-or-3-days',
125
+ 'source': 'quiz_answers',
126
+ 'acceptedAt': '2026-10-09T10:00:00Z',
127
+ });
128
+ if (loseAcknowledgement) {
129
+ loseAcknowledgement = false;
130
+ throw http.ClientException('synthetic response lost after commit');
131
+ }
132
+ final ack = Map<String, dynamic>.from(applied[id]!);
133
+ return http.Response(jsonEncode(alterAck?.call(ack) ?? ack), 201,
134
+ headers: {'content-type': 'application/json; charset=utf-8'});
135
+ }
136
+
137
+ LearningQuizSync reopen() => LearningQuizSync(api,
138
+ store: OfflineStore.forNamespace(store.scope, session: OfflineSession()));
139
+}
140
+
141
+Matcher _error(String code) =>
142
+ throwsA(isA<ApiException>().having((e) => e.code, 'code', code));
143
+
144
+void main() {
145
+ TestWidgetsFlutterBinding.ensureInitialized();
146
+ var blocked = false;
147
+ setUp(() {
148
+ blocked = false;
149
+ SharedPreferencesAsyncPlatform.instance =
150
+ InMemorySharedPreferencesAsync.withData({});
151
+ String? token;
152
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
153
+ .setMockMethodCallHandler(
154
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
155
+ if (call.method == 'getBlocked') return blocked || token != null;
156
+ if (call.method == 'beginWrite') return token = 'synthetic-quiz-write';
157
+ if (call.method == 'completeWrite' && call.arguments == token) {
158
+ token = null;
159
+ return true;
160
+ }
161
+ throw PlatformException(code: 'local_storage_restart_required');
162
+ });
163
+ });
164
+
165
+ test(
166
+ 'durable before POST, lost acknowledgement replays exact attempt after reopen',
167
+ () async {
168
+ final blockedFixture = _Fixture();
169
+ blocked = true;
170
+ await expectLater(
171
+ blockedFixture.sync.submit(_body(), _unit), throwsA(anything));
172
+ expect(blockedFixture.posts, isEmpty);
173
+ blocked = false;
174
+ final f = _Fixture();
175
+ f.loseAcknowledgement = true;
176
+ expect((await f.sync.submit(_body(), _unit))['queued'], true);
177
+ final pending = (await f.store.readQueue()).single;
178
+ expect(pending['unitId'], _unit);
179
+ expect(pending['payload'], _body());
180
+ expect(f.posts.single.containsKey('unitId'), false);
181
+ await f.reopen().flush();
182
+ expect(f.posts, [_body(), _body()]);
183
+ expect(f.applied.length, 1);
184
+ expect(await f.store.readQueue(), isEmpty);
185
+ expect(
186
+ (await f.store.readList('learning_attempts')).single['id'], _attempt);
187
+ expect(await f.store.readList('learning_progress'), isEmpty);
188
+ expect(await f.store.readPlanner(), isEmpty);
189
+ });
190
+
191
+ test(
192
+ 'wrong acknowledgements retain answers; permanent rejection is recoverable',
193
+ () async {
194
+ for (final alter in <Map<String, dynamic> Function(Map<String, dynamic>)>[
195
+ (ack) => ack..['assessmentVersion'] = 3,
196
+ (ack) => ack..['unitId'] = _assessment,
197
+ (ack) => ack..['source'] = 'timer',
198
+ (ack) => ack..['correctCount'] = 0,
199
+ (ack) => ack..['nextReviewAt'] = '2026-10-10T10:00:00Z',
200
+ (ack) => ack..['feedback'] = [],
201
+ ]) {
202
+ final f = _Fixture()..alterAck = alter;
203
+ await expectLater(f.sync.submit(_body(), _unit),
204
+ _error('invalid_sync_acknowledgement'));
205
+ expect((await f.store.readQueue()).single['payload'], _body());
206
+ expect(await f.store.readList('learning_attempts'), isEmpty);
207
+ }
208
+ for (final status in [409, 400]) {
209
+ final f = _Fixture()..failure = status;
210
+ await expectLater(
211
+ f.sync.submit(_body(), _unit), _error('synthetic_rejection'));
212
+ expect((await f.store.readQueue()).single['queueStatus'],
213
+ status == 409 ? 'conflict' : 'rejected');
214
+ await f.sync.cancelPending(_mutation);
215
+ expect(await f.store.readQueue(), isEmpty);
216
+ expect((await f.store.readDiscardedChanges()).single['payload'], _body());
217
+ }
218
+ });
219
+
220
+ test('late response after account switch cannot acknowledge the old queue',
221
+ () async {
222
+ final f = _Fixture();
223
+ final release = Completer<void>();
224
+ f.delay = release.future;
225
+ final request = f.sync.submit(_body(), _unit);
226
+ final failed = expectLater(request, throwsA(isA<ApiException>()));
227
+ while (f.posts.isEmpty) {
228
+ await Future<void>.delayed(Duration.zero);
229
+ }
230
+ f.api.currentUserId = 'another-synthetic-account';
231
+ release.complete();
232
+ await failed;
233
+ expect((await f.store.readQueue()).single['payload'], _body());
234
+ expect(await f.store.readList('learning_attempts'), isEmpty);
235
+ final other = OfflineStore.forNamespace(f.api.cacheNamespace!);
236
+ expect(await other.readQueue(), isEmpty);
237
+ await expectLater(f.reopen().flush(), _error('cache_scope_closed'));
238
+ expect(f.posts.length, 1);
239
+ });
240
+
241
+ testWidgets('no reviewed bank means no placeholder questions or submission',
242
+ (tester) async {
243
+ final f = _Fixture()..reviewed = false;
244
+ await tester.pumpWidget(
245
+ MaterialApp(home: LearningQuizPage(api: f.api, unitId: _unit)));
246
+ await tester.pumpAndSettle();
247
+ expect(find.textContaining('در انتظار بازبینی'), findsOneWidget);
248
+ expect(find.byKey(const Key('quiz-submit')), findsNothing);
249
+ expect(find.text('پرسش صرفاً آزمایشی'), findsNothing);
250
+ expect(f.posts, isEmpty);
251
+ });
252
+
253
+ testWidgets(
254
+ 'explicit answers and confidence; reopen locks pending answers and retries',
255
+ (tester) async {
256
+ final f = _Fixture()..offline = true;
257
+ await tester.pumpWidget(
258
+ MaterialApp(home: LearningQuizPage(api: f.api, unitId: _unit)));
259
+ await tester.pumpAndSettle();
260
+ FilledButton submit() =>
261
+ tester.widget(find.byKey(const Key('quiz-submit')));
262
+ expect(submit().onPressed, isNull);
263
+ await tester.tap(find.byKey(const Key('quiz-choice-q1-a')));
264
+ await tester.pump();
265
+ expect(submit().onPressed, isNull);
266
+ await tester.tap(find.byKey(const Key('quiz-confidence-unsure')));
267
+ await tester.pump();
268
+ expect(submit().onPressed, isNotNull);
269
+ await tester.ensureVisible(find.byKey(const Key('quiz-submit')));
270
+ await tester.tap(find.byKey(const Key('quiz-submit')));
271
+ await tester.pumpAndSettle();
272
+ final sent = f.posts.single;
273
+ expect(sent.containsKey('unitId'), false);
274
+ expect(find.textContaining('روی این دستگاه'), findsOneWidget);
275
+ expect(find.textContaining('پاسخ درست'), findsNothing);
276
+ await tester.pumpWidget(const MaterialApp(home: SizedBox()));
277
+ await tester.pumpWidget(
278
+ MaterialApp(home: LearningQuizPage(api: f.api, unitId: _unit)));
279
+ await tester.pumpAndSettle();
280
+ final choice =
281
+ tester.widget<ChoiceChip>(find.byKey(const Key('quiz-choice-q1-a')));
282
+ expect(choice.selected, true);
283
+ expect(choice.onSelected, isNull);
284
+ f.offline = false;
285
+ await tester.ensureVisible(find.byKey(const Key('quiz-retry')));
286
+ await tester.tap(find.byKey(const Key('quiz-retry')));
287
+ await tester.pumpAndSettle();
288
+ expect(f.posts, [sent, sent]);
289
+ expect(find.text('توضیح صرفاً آزمایشی'), findsOneWidget);
290
+ expect(find.text('مرور صرفاً آزمایشی'), findsOneWidget);
291
+ expect(find.textContaining('پیشنهاد آزمایشی'), findsOneWidget);
292
+ expect(await f.store.readQueue(), isEmpty);
293
+ expect(f.posts.every((p) => p.keys.length == 5), true);
294
+ });
295
+}
apps/lifemate/test/learning_sync_test.dart
new
+428
@@ -0,0 +1,428 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/services.dart';
5
+import 'package:flutter_test/flutter_test.dart';
6
+import 'package:http/http.dart' as http;
7
+import 'package:http/testing.dart';
8
+import 'package:lifemate/api.dart';
9
+import 'package:lifemate/learning_sync.dart';
10
+import 'package:lifemate/offline_store.dart';
11
+import 'package:lifemate/session_store.dart';
12
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
13
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14
+
15
+const _unit = '00000000-0000-4000-8000-000000000101';
16
+const _otherUnit = '00000000-0000-4000-8000-000000000102';
17
+const _course = '00000000-0000-4000-8000-000000000200';
18
+const _time = '2026-10-09T10:00:00Z';
19
+
20
+class _Session implements SessionStore {
21
+ @override
22
+ Future<String?> read() async => null;
23
+ @override
24
+ Future<void> write(String value) async {}
25
+ @override
26
+ Future<void> clear() async {}
27
+}
28
+
29
+class _Fixture {
30
+ _Fixture({String endpoint = 'https://api.test', String? user}) {
31
+ api = HttpIdentityApi(
32
+ baseUrl: endpoint,
33
+ client: MockClient(handle),
34
+ sessionStore: _Session(),
35
+ )
36
+ ..accessToken = 'synthetic-test-token'
37
+ ..currentUserId = user ?? 'learner-${next++}';
38
+ store = OfflineStore.forNamespace(api.cacheNamespace!, session: session);
39
+ sync = LearningSync(api, store: store);
40
+ }
41
+ static var next = 0;
42
+ final session = OfflineSession();
43
+ late HttpIdentityApi api;
44
+ late OfflineStore store;
45
+ late LearningSync sync;
46
+ bool offline = false;
47
+ int? errorStatus;
48
+ bool appliedThenDisconnect = false;
49
+ Future<void>? delay;
50
+ final requests = <http.Request>[];
51
+ final applied = <String, Map<String, dynamic>>{};
52
+ final progress = <String, Map<String, dynamic>>{};
53
+ Map<String, dynamic> Function(Map<String, dynamic>)? alterAck;
54
+ Map<String, dynamic> Function(Map<String, dynamic>)? alterCourse;
55
+
56
+ Map<String, dynamic> get course => {
57
+ 'id': _course,
58
+ 'titleFa': 'ریاضی آزمایشی',
59
+ 'units': [
60
+ for (final id in [_unit, _otherUnit])
61
+ {
62
+ 'id': id,
63
+ 'titleFa': 'درس آزمایشی',
64
+ 'progress': progress[id] ??
65
+ {
66
+ 'unitId': id,
67
+ 'status': 'not_started',
68
+ 'source': 'self_reported',
69
+ 'version': 0,
70
+ 'updatedAt': null
71
+ }
72
+ }
73
+ ]
74
+ };
75
+
76
+ Future<http.Response> handle(http.Request request) async {
77
+ requests.add(request);
78
+ expect(request.headers['authorization'], 'Bearer synthetic-test-token');
79
+ if (delay != null) await delay;
80
+ if (offline) throw http.ClientException('offline substitute');
81
+ if (errorStatus != null) {
82
+ return http.Response(
83
+ jsonEncode({'error': 'synthetic_failure'}), errorStatus!);
84
+ }
85
+ if (request.method == 'GET' && request.url.path.contains('/courses/')) {
86
+ final value = alterCourse == null ? course : alterCourse!(course);
87
+ return http.Response(jsonEncode({'course': value}), 200,
88
+ headers: {'content-type': 'application/json; charset=utf-8'});
89
+ }
90
+ if (request.method == 'GET' &&
91
+ request.url.path == '/v1/me/learning-progress') {
92
+ return http.Response(
93
+ jsonEncode({'progress': progress.values.toList()}), 200);
94
+ }
95
+ final body = jsonDecode(request.body) as Map<String, dynamic>;
96
+ final id = request.url.path.split('/').last;
97
+ final mutationId = body['mutationId'] as String;
98
+ if (!applied.containsKey(mutationId)) {
99
+ final row = progress[id];
100
+ if ((row?['version'] ?? 0) != body['expectedVersion']) {
101
+ return http.Response(jsonEncode({'error': 'version_conflict'}), 409);
102
+ }
103
+ final ack = <String, dynamic>{
104
+ 'mutationId': mutationId,
105
+ 'unitId': id,
106
+ 'status': body['status'],
107
+ 'source': body['source'],
108
+ 'version': (body['expectedVersion'] as int) + 1,
109
+ 'updatedAt': _time,
110
+ 'acceptedAt': _time
111
+ };
112
+ applied[mutationId] = ack;
113
+ progress[id] = {...ack}..remove('mutationId');
114
+ }
115
+ if (appliedThenDisconnect) {
116
+ appliedThenDisconnect = false;
117
+ throw http.ClientException('acknowledgement lost after synthetic commit');
118
+ }
119
+ var ack = {...applied[mutationId]!};
120
+ if (alterAck != null) ack = alterAck!(ack);
121
+ return http.Response(jsonEncode(ack), 200);
122
+ }
123
+
124
+ LearningSync reopen() => LearningSync(api,
125
+ store: OfflineStore.forNamespace(store.scope, session: session));
126
+}
127
+
128
+Matcher _code(String code) =>
129
+ throwsA(isA<ApiException>().having((e) => e.code, 'code', code));
130
+
131
+void main() {
132
+ TestWidgetsFlutterBinding.ensureInitialized();
133
+ setUp(() {
134
+ SharedPreferencesAsyncPlatform.instance =
135
+ InMemorySharedPreferencesAsync.withData({});
136
+ String? pending;
137
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
138
+ .setMockMethodCallHandler(
139
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
140
+ if (call.method == 'getBlocked') return pending != null;
141
+ if (call.method == 'beginWrite') return pending = 'synthetic-owned-write';
142
+ if (call.method == 'completeWrite' && call.arguments == pending) {
143
+ pending = null;
144
+ return true;
145
+ }
146
+ throw PlatformException(code: 'local_storage_restart_required');
147
+ });
148
+ });
149
+
150
+ test('reading a lesson never completes it and cache survives a fresh handle',
151
+ () async {
152
+ final f = _Fixture();
153
+ final course = await f.sync.readCourse(_course);
154
+ expect(course['offline'], false);
155
+ expect(
156
+ (course['units'] as List).first['progress']['status'], 'not_started');
157
+ expect(f.requests.where((r) => r.method == 'PUT'), isEmpty);
158
+ f.offline = true;
159
+ final cached = await f.reopen().readCourse(_course);
160
+ expect(cached['offline'], true);
161
+ expect(cached['titleFa'], 'ریاضی آزمایشی');
162
+ expect(
163
+ (cached['units'] as List).first['progress']['status'], 'not_started');
164
+ });
165
+
166
+ test('enqueue precedes PUT and acknowledgement updates only progress cache',
167
+ () async {
168
+ final f = _Fixture();
169
+ final original = f.api;
170
+ f.api = HttpIdentityApi(
171
+ baseUrl: original.baseUrl,
172
+ sessionStore: _Session(),
173
+ client: MockClient((request) async {
174
+ expect(await f.store.readQueue(), hasLength(1));
175
+ return f.handle(request);
176
+ }))
177
+ ..accessToken = 'synthetic-test-token'
178
+ ..currentUserId = original.currentUserId;
179
+ final result = await LearningSync(f.api, store: f.store)
180
+ .setProgress(_unit, 'in_progress', 0);
181
+ expect(result['queued'], false);
182
+ expect(result['progress']['version'], 1);
183
+ expect(await f.store.readQueue(), isEmpty);
184
+ expect(await f.store.readPlanner(), isEmpty);
185
+ expect(await f.store.readToday(), isEmpty);
186
+ expect(
187
+ (await f.store.readList('learning_progress')).single['unitId'], _unit);
188
+ });
189
+
190
+ test('offline report survives reopening and stable retry has no duplicate',
191
+ () async {
192
+ final f = _Fixture()..offline = true;
193
+ await f.sync.readCourse(_course).catchError((_) => <String, dynamic>{});
194
+ final result = await f.sync.setProgress(_unit, 'completed', 0);
195
+ expect(result['queued'], true);
196
+ expect(result['progress']['pending_sync'], true);
197
+ expect(result['progress']['version'], 0);
198
+ final queue = await f.store.readQueue();
199
+ final payload = Map<String, dynamic>.from(queue.single['payload'] as Map);
200
+ f.offline = false;
201
+ await f.reopen().flush();
202
+ await f.reopen().flush();
203
+ expect(f.applied, hasLength(1));
204
+ expect(f.applied.keys.single, payload['mutationId']);
205
+ final sent = f.requests.where((r) => r.method == 'PUT').last;
206
+ expect(jsonDecode(sent.body), payload);
207
+ expect(await f.store.readQueue(), isEmpty);
208
+ });
209
+
210
+ test('lost acknowledgement retries exact body after synthetic server commit',
211
+ () async {
212
+ final f = _Fixture()..appliedThenDisconnect = true;
213
+ final queued = await f.sync.setProgress(_unit, 'completed', 0);
214
+ expect(queued['queued'], true);
215
+ final firstBody = f.requests.single.body;
216
+ await f.reopen().flush();
217
+ expect(f.requests.last.body, firstBody);
218
+ expect(f.applied, hasLength(1));
219
+ expect((await f.store.readList('learning_progress')).single['version'], 1);
220
+ });
221
+
222
+ test('one unresolved mutation per unit, including concurrent handles',
223
+ () async {
224
+ final f = _Fixture()..offline = true;
225
+ final first = f.sync.setProgress(_unit, 'in_progress', 0);
226
+ final second = f.reopen().setProgress(_unit, 'completed', 0);
227
+ expect((await first)['queued'], true);
228
+ await expectLater(second, _code('sync_pending'));
229
+ expect(await f.sync.pendingFor(_unit), hasLength(1));
230
+ await f.sync.setProgress(_otherUnit, 'in_progress', 0);
231
+ expect(await f.store.readQueue(), hasLength(2));
232
+ });
233
+
234
+ test('malformed acknowledgements retain exact durable mutation', () async {
235
+ final mutations = <Map<String, dynamic> Function(Map<String, dynamic>)>[
236
+ (a) => a..['mutationId'] = 'wrong',
237
+ (a) => a..['unitId'] = _otherUnit,
238
+ (a) => a..['status'] = 'completed',
239
+ (a) => a..['source'] = 'timer',
240
+ (a) => a..['version'] = 0,
241
+ (a) => a..['version'] = 2,
242
+ (a) => a..['version'] = '1',
243
+ (a) => a..['acceptedAt'] = 'not-a-date',
244
+ (a) => a..['updatedAt'] = null,
245
+ ];
246
+ for (final corrupt in mutations) {
247
+ final f = _Fixture()..alterAck = corrupt;
248
+ await expectLater(f.sync.setProgress(_unit, 'in_progress', 0),
249
+ _code('invalid_sync_acknowledgement'));
250
+ expect(await f.store.readQueue(), hasLength(1));
251
+ expect(await f.store.readList('learning_progress'), isEmpty);
252
+ final body = (await f.store.readQueue()).single['payload'];
253
+ f.alterAck = null;
254
+ await f.reopen().flush();
255
+ expect(jsonDecode(f.requests.last.body), body);
256
+ }
257
+ });
258
+
259
+ test('refresh overlays pending report without calling it acknowledged',
260
+ () async {
261
+ final f = _Fixture();
262
+ await f.sync.readCourse(_course);
263
+ f.offline = true;
264
+ await f.sync.setProgress(_unit, 'completed', 0);
265
+ f.offline = false;
266
+ final live = await f.reopen().readCourse(_course);
267
+ final row = (live['units'] as List).first['progress'];
268
+ expect(row['status'], 'completed');
269
+ expect(row['pending_sync'], true);
270
+ expect(row['acknowledged'], false);
271
+ expect(row['version'], 0);
272
+ expect(await f.store.readQueue(), hasLength(1));
273
+ });
274
+
275
+ test('409 retains conflict; explicit server choice journals before removing',
276
+ () async {
277
+ final f = _Fixture()..offline = true;
278
+ await f.sync.setProgress(_unit, 'completed', 0);
279
+ final original = (await f.store.readQueue()).single;
280
+ f.progress[_unit] = {
281
+ 'unitId': _unit,
282
+ 'status': 'in_progress',
283
+ 'source': 'self_reported',
284
+ 'version': 2,
285
+ 'updatedAt': _time,
286
+ };
287
+ f.offline = false;
288
+ await expectLater(f.sync.flush(), _code('version_conflict'));
289
+ expect((await f.store.readQueue()).single['queueStatus'], 'conflict');
290
+ await expectLater(f.sync.flush(), _code('sync_conflict'));
291
+ await f.sync.resolveUsingServer(_unit);
292
+ expect(await f.store.readQueue(), isEmpty);
293
+ final journal = await f.store.readDiscardedChanges();
294
+ expect(journal.single['payload'], original['payload']);
295
+ expect(journal.single['discardedAt'], isNotNull);
296
+ expect((await f.store.readList('learning_progress')).single['status'],
297
+ 'in_progress');
298
+ expect(await f.store.readPlanner(), isEmpty);
299
+ });
300
+
301
+ test('permission/server failures are not offline success or stale live reads',
302
+ () async {
303
+ for (final status in [403, 422, 500, 503]) {
304
+ final f = _Fixture();
305
+ await f.sync.readCourse(_course);
306
+ f.errorStatus = status;
307
+ await expectLater(f.sync.readCourse(_course), _code('synthetic_failure'));
308
+ await expectLater(f.sync.setProgress(_unit, 'completed', 0),
309
+ _code('synthetic_failure'));
310
+ expect(await f.store.readQueue(), hasLength(1));
311
+ }
312
+ });
313
+
314
+ test('account and API namespace never share metadata or unsent progress',
315
+ () async {
316
+ final child = _Fixture(user: 'child');
317
+ await child.sync.readCourse(_course);
318
+ child.offline = true;
319
+ await child.sync.setProgress(_unit, 'completed', 0);
320
+ final parent = _Fixture(user: 'parent')..offline = true;
321
+ final other = _Fixture(user: 'child', endpoint: 'https://other.test')
322
+ ..offline = true;
323
+ for (final outsider in [parent, other]) {
324
+ expect(await outsider.sync.pendingFor(_unit), isEmpty);
325
+ await expectLater(
326
+ outsider.sync.readCourse(_course), _code('network_unavailable'));
327
+ expect(await outsider.store.readList('learning_progress'), isEmpty);
328
+ }
329
+ });
330
+
331
+ test(
332
+ 'closed scope cannot acknowledge late response or erase quarantined work',
333
+ () async {
334
+ final f = _Fixture()..offline = true;
335
+ await f.sync.setProgress(_unit, 'completed', 0);
336
+ final original = (await f.store.readQueue()).single['payload'];
337
+ f.offline = false;
338
+ final delayed = Completer<void>();
339
+ f.delay = delayed.future;
340
+ final request = f.sync.flush();
341
+ await Future<void>.delayed(Duration.zero);
342
+ await OfflineStore.invalidateNamespace(f.store.scope);
343
+ delayed.complete();
344
+ await expectLater(request, _code('cache_scope_closed'));
345
+ final reopened =
346
+ OfflineStore.forNamespace(f.store.scope, session: f.session);
347
+ expect((await reopened.readQueue()).single['payload'], original);
348
+ expect(await reopened.readList('learning_progress'), isEmpty);
349
+ });
350
+
351
+ test('API identity change rejects old store without deleting its queue',
352
+ () async {
353
+ final f = _Fixture()..offline = true;
354
+ await f.sync.setProgress(_unit, 'in_progress', 0);
355
+ f.api.currentUserId = 'different-user';
356
+ await expectLater(f.sync.flush(), _code('cache_scope_closed'));
357
+ expect(await f.store.readQueue(), hasLength(1));
358
+ });
359
+
360
+ test('identity changed during offline response cannot return old progress',
361
+ () async {
362
+ final f = _Fixture();
363
+ final delayed = Completer<void>();
364
+ f.delay = delayed.future;
365
+ f.offline = true;
366
+ final request = f.sync.setProgress(_unit, 'completed', 0);
367
+ while (f.requests.isEmpty) {
368
+ await Future<void>.delayed(Duration.zero);
369
+ }
370
+ f.api.currentUserId = 'replacement-user';
371
+ delayed.complete();
372
+ await expectLater(request, _code('cache_scope_closed'));
373
+ expect(await f.store.readQueue(), hasLength(1));
374
+ });
375
+
376
+ test('malformed course response cannot replace last valid cached metadata',
377
+ () async {
378
+ final f = _Fixture();
379
+ await f.sync.readCourse(_course);
380
+ f.alterCourse = (value) => value
381
+ ..['units'] = [
382
+ {'id': 'wrong'}
383
+ ];
384
+ await expectLater(
385
+ f.sync.readCourse(_course), _code('invalid_learning_course'));
386
+ f.offline = true;
387
+ final cached = await f.sync.readCourse(_course);
388
+ expect(cached['offline'], true);
389
+ expect((cached['units'] as List).first['id'], _unit);
390
+ });
391
+
392
+ test('missing server progress never silently discards unresolved report',
393
+ () async {
394
+ final f = _Fixture()..offline = true;
395
+ await f.sync.setProgress(_unit, 'completed', 0);
396
+ final payload = (await f.store.readQueue()).single['payload'];
397
+ f.offline = false;
398
+ await expectLater(
399
+ f.sync.resolveUsingServer(_unit), _code('invalid_learning_progress'));
400
+ expect((await f.store.readQueue()).single['payload'], payload);
401
+ expect(await f.store.readDiscardedChanges(), isEmpty);
402
+ });
403
+
404
+ test('server choice does not discard an independent entity with same UUID',
405
+ () async {
406
+ final f = _Fixture()..offline = true;
407
+ await f.sync.setProgress(_unit, 'completed', 0);
408
+ await f.store.enqueue({
409
+ 'id': '00000000-0000-4000-8000-000000000300',
410
+ 'entityId': _unit,
411
+ 'entityType': 'plan_item',
412
+ 'operation': 'update',
413
+ 'payload': {'title': 'synthetic independent planner change'},
414
+ });
415
+ f.progress[_unit] = {
416
+ 'unitId': _unit,
417
+ 'status': 'in_progress',
418
+ 'source': 'self_reported',
419
+ 'version': 1,
420
+ 'updatedAt': _time,
421
+ };
422
+ f.offline = false;
423
+ await expectLater(
424
+ f.sync.resolveUsingServer(_unit), _code('sync_entity_collision'));
425
+ expect(await f.store.readQueue(), hasLength(2));
426
+ expect(await f.store.readDiscardedChanges(), isEmpty);
427
+ });
428
+}
apps/lifemate/test/online_ui_test.dart
+15
-1
@@ -167,6 +167,12 @@ void main() {
167
await tester.pumpAndSettle();
168
tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
169
await tester.pumpAndSettle();
170
+ await tester.scrollUntilVisible(find.text('تغییرهای معلق و تعارضها'), 100,
171
+ scrollable: find
172
+ .descendant(
173
+ of: find.byType(Drawer), matching: find.byType(Scrollable))
174
+ .first);
175
+ await tester.pumpAndSettle();
176
await tester.tap(find.text('تغییرهای معلق و تعارضها'));
177
await tester.pumpAndSettle();
178
expect(find.byType(SyncChangesPage), findsOneWidget);
@@ -474,6 +480,12 @@ void main() {
480
await tester.pumpAndSettle();
481
tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
482
await tester.pumpAndSettle();
483
+ await tester.scrollUntilVisible(find.text('خروج از حساب'), 100,
484
+ scrollable: find
485
+ .descendant(
486
+ of: find.byType(Drawer), matching: find.byType(Scrollable))
487
+ .first);
488
+ await tester.pumpAndSettle();
489
await tester.tap(find.text('خروج از حساب'));
490
await tester.pumpAndSettle();
491
expect(find.textContaining('تغییر معلق'), findsOneWidget);
@@ -523,8 +535,10 @@ void main() {
535
await tester.pumpAndSettle();
536
await tester.tap(find.text('تنظیم اتصال'));
537
await tester.pumpAndSettle();
526
- await tester.enterText(find.widgetWithText(TextField, 'نشانی اصلی'),
538
+ await tester.enterText(find.widgetWithText(TextField, 'نشانی اتصال API'),
539
'https://other.synthetic.example.test');
540
+ await tester.ensureVisible(find.text('ذخیره و ادامه'));
541
+ await tester.pumpAndSettle();
542
await tester.tap(find.text('ذخیره و ادامه'));
543
await tester.pumpAndSettle();
544
expect(find.textContaining('تغییر معلق'), findsOneWidget);
docker-compose.yml
+12
@@ -96,6 +96,16 @@ services:
96
restart: 'no'
97
networks: [private]
98
99
+ catalog-import:
100
+ image: ${API_IMAGE:-lifeguide-api:local}
101
+ command: [node, scripts/import-learning-catalog.js]
102
+ environment: *migration-environment
103
+ depends_on:
104
+ migrate:
105
+ condition: service_completed_successfully
106
+ restart: 'no'
107
+ networks: [private]
108
+
109
db-grants:
110
image: ${API_IMAGE:-lifeguide-api:local}
111
command: [node, scripts/provision-db-roles.js, --grants]
@@ -103,6 +113,8 @@ services:
113
depends_on:
114
migrate:
115
condition: service_completed_successfully
116
+ catalog-import:
117
+ condition: service_completed_successfully
118
restart: 'no'
119
networks: [private]
120
scripts/local-deploy.ps1
+1
@@ -86,6 +86,7 @@ if ($env:BUILD_CA_FILE) {
86
Invoke-CheckedDocker -Arguments @('compose', 'up', '-d', '--wait', '--wait-timeout', '120', 'postgres')
87
Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', '--no-deps', 'db-provision')
88
Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', '--no-deps', 'migrate')
89
+Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', '--no-deps', 'catalog-import')
90
Invoke-CheckedDocker -Arguments @('compose', 'run', '--rm', '--no-deps', 'db-grants')
91
Invoke-CheckedDocker -Arguments @('compose', 'up', '-d', '--wait', '--wait-timeout', '180', 'api', 'gateway', 'backup')
92
Invoke-CheckedDocker -Arguments @('compose', 'ps')
scripts/local-deploy.sh
+1
@@ -70,6 +70,7 @@ fi
70
docker compose up -d --wait --wait-timeout 120 postgres
71
docker compose run --rm --no-deps db-provision
72
docker compose run --rm --no-deps migrate
73
+docker compose run --rm --no-deps catalog-import
74
docker compose run --rm --no-deps db-grants
75
docker compose up -d --wait --wait-timeout 180 api gateway backup
76
docker compose ps
scripts/test-db-roles.sh
+1
-1
@@ -38,4 +38,4 @@ docker compose run --rm --no-deps --entrypoint /opt/lifeguide/backup.sh \
38
docker compose run --rm --no-deps --entrypoint pg_restore backup --list "$dump_file" >/dev/null
39
docker compose run --rm --no-deps -e "DATABASE_URL=postgresql://lifeguide_migrator@postgres:5432/$target_db" restore "$dump_file"
40
docker "${tool_args[@]}" node scripts/test-db-roles.js --verify-restored
41
-echo 'PASS local least-privilege SQL + runtime HTTP scenario + read-only dump/migrator restore with12 migrations'
41
+echo 'PASS local least-privilege SQL + runtime family/learning HTTP scenarios + read-only dump/migrator restore; checksum ledger matches migration files'