@davoodmehraban89 / LifeMate / commits / e83df51
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: connect selected task details to durable planner sync

Quinn White committed Oct 16, 2026 at 13:06 UTC e83df5168b531adabf6fd4e9f282faeef70a6cb7
5 files changed +740 -39
apps/lifemate/lib/main.dart
+21 -3
@@ -1160,7 +1160,7 @@ class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1160 if (mounted) {
1161 setState(() {
1162 contextError = errorText(error);
1163 - contextLoaded = false;
1163 + if (!isOfflineFailure(error)) contextLoaded = false;
1164 });
1165 }
1166 }
@@ -1168,6 +1168,13 @@ class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1168
1169 List<String> get pages => adultShell ? adultPages : studentPages;
1170
1171 + // Keep the account's saved accent choice; category never grants permissions.
1172 + Color get accountAccent => switch (themePreference) {
1173 + 'girl_pink' => const Color(0xFFB66D88),
1174 + 'boy_blue' || 'adult_blue' => const Color(0xFF4B7995),
1175 + _ => MobileHomeMenu.accent,
1176 + };
1177 +
1178 List<String> get primaryPages => adultShell
1179 ? ['خانه', 'برنامه‌ریز', 'خانواده', 'گزارش‌ها', 'من']
1180 : ['خانه', 'برنامه من', 'درس‌ها', 'تمرکز', 'خانواده'];
@@ -1263,7 +1270,7 @@ class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1270 @override
1271 Widget build(BuildContext context) => Theme(
1272 data: Theme.of(context).copyWith(
1266 - colorScheme: ColorScheme.fromSeed(seedColor: MobileHomeMenu.accent),
1273 + colorScheme: ColorScheme.fromSeed(seedColor: accountAccent),
1274 scaffoldBackgroundColor: MobileHomeMenu.paper,
1275 appBarTheme: const AppBarTheme(
1276 backgroundColor: MobileHomeMenu.paper,
@@ -1296,7 +1303,18 @@ class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1303 onPressed: () => selectPage('من')),
1304 ],
1305 ),
1299 - body: pageContent(),
1306 + body: Column(children: [
1307 + if (contextLoaded && contextError != null)
1308 + MaterialBanner(
1309 + content: const Text(
1310 + 'اطلاعات حساب از آخرین دریافت است؛ تازه‌سازی اتصال انجام نشد.'),
1311 + actions: [
1312 + TextButton(
1313 + onPressed: loadContext,
1314 + child: const Text('تلاش دوباره'))
1315 + ]),
1316 + Expanded(child: pageContent()),
1317 + ]),
1318 bottomNavigationBar: NavigationBar(
1319 selectedIndex: primaryPages.contains(page)
1320 ? primaryPages.indexOf(page)
apps/lifemate/lib/phase3_ui.dart
+121 -36
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
3 import 'api.dart';
4 import 'offline_store.dart';
5 import 'plan_sync.dart';
6 +import 'plan_details_ui.dart';
7 import 'study_ui.dart';
8 import 'dashboard_ui.dart';
9 import 'school_management_ui.dart';
@@ -202,6 +203,9 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
203 bool loading = false;
204 String? busyId;
205 String? operationError;
206 + Set<String> ownedCreates = {};
207 + ValueNotifier<Map<String, dynamic>?>? sharedDetail;
208 + String? sharedDetailId;
209 @override
210 void initState() {
211 super.initState();
@@ -263,11 +267,26 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
267 offline = true;
268 items = await ownedPlanFallback(widget.api, store, today: widget.today);
269 }
270 + if (sharedDetailId != null) {
271 + sharedDetail?.value = offline
272 + ? null
273 + : items.where((row) => row['id'] == sharedDetailId).firstOrNull;
274 + }
275 + ownedCreates = (await store.readQueue())
276 + .where((m) =>
277 + m['entityType'] == 'plan_item' &&
278 + m['operation'] == 'create' &&
279 + m['queueStatus'] != 'rejected')
280 + .map((m) => m['entityId'].toString())
281 + .toSet();
282 return LoadResult(
283 items.where((i) => i['status'] != 'cancelled').toList(), offline,
284 pending: await store.pendingCount(),
285 syncedAt: await store.readLastSync(),
286 reminders: reminders);
287 + } catch (_) {
288 + sharedDetail?.value = null;
289 + rethrow;
290 } finally {
291 loading = false;
292 }
@@ -283,40 +302,91 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
302 } catch (_) {/* FutureBuilder renders the error. */}
303 }
304
286 - Future<void> edit([Map<String, dynamic>? item]) async {
305 + Future<MutationOutcome?> edit(
306 + [Map<String, dynamic>? item, bool notify = true]) async {
307 final outcome = await showDialog<MutationOutcome>(
308 context: context,
309 builder: (_) => PlanItemDialog(api: widget.api, item: item));
310 if (outcome != null && mounted) {
291 - ScaffoldMessenger.of(context).showSnackBar(SnackBar(
292 - content: Text(outcome.queued
293 - ? 'تغییر روی دستگاه ثبت شد؛ در انتظار تأیید سرور.'
294 - : 'تغییر توسط سرور تأیید شد.')));
311 + if (notify) {
312 + ScaffoldMessenger.of(context).showSnackBar(SnackBar(
313 + content: Text(outcome.queued
314 + ? 'تغییر روی دستگاه ثبت شد؛ در انتظار تأیید سرور.'
315 + : 'تغییر توسط سرور تأیید شد.')));
316 + }
317 await reload();
318 }
319 + return outcome;
320 }
321
299 - Future<void> action(Map<String, dynamic> item, String action) async {
300 - if (busyId != null) return;
322 + bool owns(Map<String, dynamic> item) {
323 + final api = widget.api;
324 + if (api is! HttpIdentityApi) return true;
325 + final owner = item['owner_user_id'] ?? item['ownerUserId'];
326 + return api.currentUserId != null &&
327 + (owner == api.currentUserId ||
328 + (owner == null && ownedCreates.contains(item['id'])));
329 + }
330 +
331 + Future<void> openDetails(Map<String, dynamic> item, bool offline) async {
332 + final canEdit = owns(item);
333 + final updates = canEdit ? null : ValueNotifier<Map<String, dynamic>?>(item);
334 + sharedDetail = updates;
335 + sharedDetailId = canEdit ? null : item['id'].toString();
336 + await Navigator.of(context).push(MaterialPageRoute(
337 + builder: (_) => PlanDetailsPage(
338 + item: item,
339 + sharedUpdates: updates,
340 + canEdit: canEdit,
341 + offline: offline,
342 + canStudy: canEdit &&
343 + widget.api is HttpIdentityApi &&
344 + ['assignment', 'task', 'study_session'].contains(item['kind']),
345 + onAction: (current, action) =>
346 + this.action(current, action, rethrowFailure: true),
347 + kindLabel: faKind,
348 + dateLabel: shortDate,
349 + errorLabel: uiErrorText)));
350 + if (identical(sharedDetail, updates)) {
351 + sharedDetail = null;
352 + sharedDetailId = null;
353 + }
354 + updates?.dispose();
355 + if (mounted) await reload();
356 + }
357 +
358 + Future<MutationOutcome?> action(Map<String, dynamic> item, String action,
359 + {bool rethrowFailure = false}) async {
360 + if (busyId != null) return null;
361 + if (!owns(item)) {
362 + if (rethrowFailure) throw const ApiException(403, 'forbidden');
363 + return null;
364 + }
365 if (action == 'edit') {
302 - await edit(item);
303 - return;
366 + return edit(item, !rethrowFailure);
367 }
368 if (action == 'study') {
369 if (item['pending_sync'] == true) {
370 setState(() => operationError =
371 'تکلیف هنوز در سرور تأیید نشده است؛ تایمر پس از همگام‌سازی فعال می‌شود.');
309 - return;
372 + return null;
373 }
374 if (widget.api is! HttpIdentityApi) {
375 setState(() => operationError = 'اتصال مطالعه در دسترس نیست.');
313 - return;
376 + return null;
377 }
378 await Navigator.of(context).push(MaterialPageRoute(
379 builder: (_) =>
380 StudyTimerPage(api: widget.api as HttpIdentityApi, item: item)));
318 - if (mounted) await reload();
319 - return;
381 + if (!mounted) return null;
382 + await reload();
383 + final fresh = await future;
384 + if (fresh.offline) throw const ApiException(0, 'network_unavailable');
385 + final current =
386 + fresh.items.where((row) => row['id'] == item['id']).firstOrNull;
387 + if (current == null) throw const ApiException(404, 'not_found');
388 + return MutationOutcome(
389 + queued: current['pending_sync'] == true, item: current);
390 }
391 if (action == 'archive') {
392 final confirmed = await showDialog<bool>(
@@ -332,7 +402,7 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
402 onPressed: () => Navigator.pop(c, true),
403 child: const Text('بایگانی'))
404 ]));
335 - if (confirmed != true || !mounted) return;
405 + if (confirmed != true || !mounted) return null;
406 }
407 setState(() {
408 busyId = item['id'].toString();
@@ -344,17 +414,23 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
414 ? await sync.archive(item)
415 : await sync.complete(item);
416 if (mounted) {
347 - ScaffoldMessenger.of(context).showSnackBar(SnackBar(
348 - content: Text(outcome.queued
349 - ? 'تغییر در انتظار تأیید سرور است.'
350 - : 'سرور تغییر را تأیید کرد.')));
417 + // Detail has an inline receipt; avoid covering its action controls.
418 + if (!rethrowFailure || action == 'archive') {
419 + ScaffoldMessenger.of(context).showSnackBar(SnackBar(
420 + content: Text(outcome.queued
421 + ? 'تغییر در انتظار تأیید سرور است.'
422 + : 'سرور تغییر را تأیید کرد.')));
423 + }
424 await reload();
425 }
426 + return outcome;
427 } catch (error) {
428 if (mounted) setState(() => operationError = uiErrorText(error));
429 + if (rethrowFailure) rethrow;
430 } finally {
431 if (mounted) setState(() => busyId = null);
432 }
433 + return null;
434 }
435
436 @override
@@ -404,6 +480,9 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
480 leading: Icon(item['status'] == 'completed'
481 ? Icons.check_circle_outline
482 : Icons.radio_button_unchecked),
483 + onTap: busyId == null
484 + ? () => openDetails(item, data.offline)
485 + : null,
486 title: Text(item['title']?.toString() ?? ''),
487 subtitle: Text(
488 '${faKind(item['kind']?.toString() ?? 'task')} · ${shortDate(item['startsAt'] ?? item['starts_at'] ?? item['dueAt'] ?? item['due_at'])}${item['pending_sync'] == true ? '\nدر انتظار تأیید سرور' : ''}'),
@@ -412,24 +491,30 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
491 width: 24,
492 height: 24,
493 child: CircularProgressIndicator())
415 - : PopupMenuButton<String>(
416 - onSelected: (v) => action(item, v),
417 - itemBuilder: (_) => [
418 - const PopupMenuItem(
419 - value: 'edit', child: Text('ویرایش')),
420 - const PopupMenuItem(
421 - value: 'complete',
422 - child: Text('انجام شد')),
423 - if (item['pending_sync'] != true &&
424 - widget.api is HttpIdentityApi &&
425 - ['assignment', 'task', 'study_session']
426 - .contains(item['kind']))
427 - const PopupMenuItem(
428 - value: 'study',
429 - child: Text('تایمر مطالعه')),
430 - const PopupMenuItem(
431 - value: 'archive', child: Text('بایگانی')),
432 - ]),
494 + : !owns(item)
495 + ? const Icon(Icons.visibility_outlined)
496 + : PopupMenuButton<String>(
497 + onSelected: (v) => action(item, v),
498 + itemBuilder: (_) => [
499 + const PopupMenuItem(
500 + value: 'edit', child: Text('ویرایش')),
501 + const PopupMenuItem(
502 + value: 'complete',
503 + child: Text('انجام شد')),
504 + if (item['pending_sync'] != true &&
505 + widget.api is HttpIdentityApi &&
506 + [
507 + 'assignment',
508 + 'task',
509 + 'study_session'
510 + ].contains(item['kind']))
511 + const PopupMenuItem(
512 + value: 'study',
513 + child: Text('تایمر مطالعه')),
514 + const PopupMenuItem(
515 + value: 'archive',
516 + child: Text('بایگانی')),
517 + ]),
518 ))),
519 ]));
520 });
apps/lifemate/lib/plan_details_ui.dart new
+240
@@ -0,0 +1,240 @@
1 +import 'package:flutter/material.dart';
2 +import 'package:flutter/foundation.dart';
3 +import 'mobile_home.dart';
4 +import 'plan_sync.dart';
5 +
6 +/// Displays one selected record. Mutations stay with the caller's PlanSync path.
7 +class PlanDetailsPage extends StatefulWidget {
8 + const PlanDetailsPage(
9 + {super.key,
10 + required this.item,
11 + this.sharedUpdates,
12 + required this.canEdit,
13 + required this.canStudy,
14 + required this.offline,
15 + required this.onAction,
16 + required this.kindLabel,
17 + required this.dateLabel,
18 + required this.errorLabel});
19 + final Map<String, dynamic> item;
20 + final ValueListenable<Map<String, dynamic>?>? sharedUpdates;
21 + final bool canEdit, canStudy, offline;
22 + final Future<MutationOutcome?> Function(Map<String, dynamic>, String)
23 + onAction;
24 + final String Function(String) kindLabel;
25 + final String Function(dynamic) dateLabel;
26 + final String Function(Object) errorLabel;
27 + @override
28 + State<PlanDetailsPage> createState() => _PlanDetailsPageState();
29 +}
30 +
31 +class _PlanDetailsPageState extends State<PlanDetailsPage>
32 + with WidgetsBindingObserver {
33 + late Map<String, dynamic> item = Map.of(widget.item);
34 + bool busy = false, acknowledged = false;
35 + String? error, pendingAction;
36 + bool snapshotInvalid = false, active = true;
37 + @override
38 + void initState() {
39 + super.initState();
40 + WidgetsBinding.instance.addObserver(this);
41 + widget.sharedUpdates?.addListener(sharedChanged);
42 + }
43 +
44 + void sharedChanged() {
45 + if (!mounted || !active) return;
46 + final latest = widget.sharedUpdates?.value;
47 + setState(() {
48 + snapshotInvalid = latest == null;
49 + item = latest == null ? {} : Map.of(latest);
50 + });
51 + }
52 +
53 + @override
54 + void didChangeAppLifecycleState(AppLifecycleState state) {
55 + active = state == AppLifecycleState.resumed;
56 + if (!widget.canEdit && !active && mounted) {
57 + setState(() {
58 + snapshotInvalid = true;
59 + item = {};
60 + });
61 + }
62 + }
63 +
64 + @override
65 + void dispose() {
66 + widget.sharedUpdates?.removeListener(sharedChanged);
67 + WidgetsBinding.instance.removeObserver(this);
68 + super.dispose();
69 + }
70 +
71 + Future<void> act(String action) async {
72 + if (busy) return;
73 + setState(() {
74 + busy = true;
75 + pendingAction = action;
76 + error = null;
77 + });
78 + try {
79 + final outcome = await widget.onAction(item, action);
80 + if (!mounted || outcome == null) return;
81 + if (action == 'archive') {
82 + Navigator.pop(context);
83 + return;
84 + }
85 + setState(() {
86 + item = Map.of(outcome.item ?? item);
87 + item['pending_sync'] = outcome.queued;
88 + acknowledged = !outcome.queued;
89 + });
90 + } catch (failure) {
91 + if (mounted) {
92 + setState(() {
93 + error = widget.errorLabel(failure);
94 + if (action == 'study') {
95 + snapshotInvalid = true;
96 + item = {};
97 + }
98 + });
99 + }
100 + } finally {
101 + if (mounted) setState(() => busy = false);
102 + }
103 + }
104 +
105 + @override
106 + Widget build(BuildContext context) {
107 + if (snapshotInvalid) {
108 + return Scaffold(
109 + appBar: AppBar(title: const Text('وضعیت کار')),
110 + body: Center(
111 + child: Padding(
112 + padding: const EdgeInsets.all(24),
113 + child: Column(mainAxisSize: MainAxisSize.min, children: [
114 + const Text(
115 + 'اطلاعات تازه در دسترس نیست. برای بررسی وضعیت و دسترسی، به فهرست برنامه برگرد.'),
116 + if (error != null) Text(error!),
117 + TextButton(
118 + onPressed: () => Navigator.pop(context),
119 + child: const Text('بازگشت به برنامه')),
120 + ]))));
121 + }
122 + final pending = item['pending_sync'] == true;
123 + final status = item['status']?.toString() ?? 'planned';
124 + final stateLabel = switch (status) {
125 + 'completed' => 'انجام‌شده',
126 + 'in_progress' => 'در حال انجام',
127 + 'cancelled' => 'بایگانی‌شده',
128 + _ => 'برنامه‌ریزی‌شده',
129 + };
130 + final visibility = switch (item['visibility']) {
131 + 'parent_guardian' => 'سرپرستان مجاز',
132 + 'selected_members' => 'اعضای انتخاب‌شده',
133 + 'family' => 'اعضای مجاز خانواده',
134 + _ => 'فقط من',
135 + };
136 + final seconds = num.tryParse((item['planned_duration_seconds'] ??
137 + item['plannedDurationSeconds'] ??
138 + 0)
139 + .toString()) ??
140 + 0;
141 + final minutes = seconds > 0
142 + ? (seconds / 60).round()
143 + : (num.tryParse(item['duration_minutes'].toString()) ?? 0);
144 + return PopScope(
145 + canPop: !busy,
146 + child: Scaffold(
147 + key: const ValueKey('plan-details'),
148 + backgroundColor: MobileHomeMenu.paper,
149 + appBar: AppBar(title: const Text('جزئیات تکلیف')),
150 + body: SafeArea(
151 + child: ListView(padding: const EdgeInsets.all(20), children: [
152 + Text(
153 + '${widget.kindLabel(item['kind']?.toString() ?? 'task')} · $stateLabel',
154 + style: const TextStyle(color: MobileHomeMenu.accent)),
155 + const SizedBox(height: 12),
156 + Text(item['title']?.toString() ?? '',
157 + style: Theme.of(context)
158 + .textTheme
159 + .headlineSmall
160 + ?.copyWith(color: MobileHomeMenu.ink)),
161 + const SizedBox(height: 20),
162 + Card(
163 + child: Padding(
164 + padding: const EdgeInsets.all(16),
165 + child: Column(
166 + crossAxisAlignment: CrossAxisAlignment.start,
167 + children: [
168 + const Text('زمان و برنامه'),
169 + const SizedBox(height: 8),
170 + Text(widget.dateLabel(item['starts_at'] ??
171 + item['startsAt'] ??
172 + item['due_at'] ??
173 + item['dueAt'])),
174 + Text(minutes > 0
175 + ? '$minutes دقیقه زمان برنامه‌ریزی‌شده'
176 + : 'زمان مطالعه تعیین نشده است'),
177 + ]))),
178 + Card(
179 + child: ListTile(
180 + leading: const Icon(Icons.shield_outlined),
181 + title: const Text('با چه کسی به اشتراک گذاشته شده؟'),
182 + subtitle: Text(visibility))),
183 + if (item['notes'] is String &&
184 + (item['notes'] as String).isNotEmpty)
185 + Card(
186 + child: Padding(
187 + padding: const EdgeInsets.all(16),
188 + child: Text(item['notes'] as String))),
189 + Card(
190 + color: pending ? const Color(0xFFFFF1D9) : null,
191 + child: ListTile(
192 + leading: Icon(
193 + pending ? Icons.sync : Icons.cloud_done_outlined),
194 + title: Text(pending
195 + ? 'در انتظار تأیید سرور'
196 + : acknowledged
197 + ? 'توسط سرور تأیید شد'
198 + : widget.offline
199 + ? 'نسخه ذخیره‌شده؛ داده زنده نیست'
200 + : 'آخرین دریافت از برنامه'),
201 + subtitle: const Text(
202 + 'این صفحه وضعیت رکورد انتخاب‌شده است؛ برای دریافت تغییرات دستگاه دیگر به فهرست برگرد و تازه‌سازی کن.'))),
203 + if (error != null)
204 + Padding(
205 + padding: const EdgeInsets.all(12),
206 + child: Text(error!,
207 + style: TextStyle(
208 + color: Theme.of(context).colorScheme.error))),
209 + if (!widget.canEdit)
210 + const Text(
211 + 'فقط مشاهده؛ ویرایش و ثبت زمان برای مالک این کار است.'),
212 + if (widget.canEdit) ...[
213 + if (widget.canStudy && !pending && status != 'completed')
214 + FilledButton.icon(
215 + key: const ValueKey('detail-study'),
216 + onPressed: busy ? null : () => act('study'),
217 + icon: const Icon(Icons.play_arrow_outlined),
218 + label: const Text('شروع مطالعه این تکلیف')),
219 + if (status != 'completed')
220 + FilledButton.icon(
221 + key: const ValueKey('detail-complete'),
222 + onPressed: busy ? null : () => act('complete'),
223 + icon: const Icon(Icons.check),
224 + label: const Text('انجام شد')),
225 + OutlinedButton.icon(
226 + key: const ValueKey('detail-edit'),
227 + onPressed: busy ? null : () => act('edit'),
228 + icon: const Icon(Icons.edit_outlined),
229 + label: const Text('ویرایش تکلیف')),
230 + TextButton.icon(
231 + key: const ValueKey('detail-archive'),
232 + onPressed: busy ? null : () => act('archive'),
233 + icon: const Icon(Icons.archive_outlined),
234 + label: const Text('بایگانی')),
235 + ],
236 + if (busy && pendingAction == 'complete')
237 + const Center(child: CircularProgressIndicator()),
238 + ]))));
239 + }
240 +}
apps/lifemate/test/mobile_navigation_test.dart
+19
@@ -17,8 +17,10 @@ class MenuApi extends FakeApi {
17 MenuApi({this.category = 'girl_minor'});
18 final String category;
19 bool failProfile = false;
20 + bool offlineProfile = false;
21 @override
22 Future<Map<String, dynamic>> getProfile() async {
23 + if (offlineProfile) throw const ApiException(0, 'network_unavailable');
24 if (failProfile) throw const ApiException(503, 'profile_unavailable');
25 return {
26 'user_id': 'synthetic-menu-user',
@@ -145,6 +147,23 @@ void main() {
147 expect(find.byType(LearningReportPage), findsNothing);
148 await tester.pumpWidget(const SizedBox());
149 });
150 + testWidgets(
151 + 'same-account offline profile refresh preserves cached planner access',
152 + (tester) async {
153 + final api = MenuApi();
154 + await shell(tester, api);
155 + await tester.tap(find.byKey(const ValueKey('home-family')));
156 + await tester.pumpAndSettle();
157 + api.offlineProfile = true;
158 + await tester.tap(find.byTooltip('برگشت به خانه'));
159 + await tester.pumpAndSettle();
160 + expect(
161 + find.byKey(const ValueKey('home-plan')).hitTestable(), findsOneWidget);
162 + await tester.tap(find.byKey(const ValueKey('home-plan')));
163 + await tester.pumpAndSettle();
164 + expect(find.byType(PlannerPage), findsOneWidget);
165 + await tester.pumpWidget(const SizedBox());
166 + });
167 testWidgets(
168 'profile failure does not guess a child or parent home and can retry',
169 (tester) async {
apps/lifemate/test/plan_details_test.dart new
+339
@@ -0,0 +1,339 @@
1 +import 'dart:convert';
2 +import 'package:flutter/material.dart';
3 +import 'package:flutter/services.dart';
4 +import 'package:flutter_test/flutter_test.dart';
5 +import 'package:http/http.dart' as http;
6 +import 'package:http/testing.dart';
7 +import 'package:lifemate/api.dart';
8 +import 'package:lifemate/phase3_ui.dart';
9 +import 'package:lifemate/plan_sync.dart';
10 +import 'package:shared_preferences/shared_preferences.dart';
11 +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
12 +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
13 +import 'app_test.dart' show FakeApi;
14 +
15 +// Explicit API fixtures for widget behavior; local PostgreSQL acceptance is separate.
16 +class TaskApi extends FakeApi {
17 + bool offline = false;
18 + final items = <Map<String, dynamic>>[
19 + {
20 + 'id': '30000000-0000-4000-8000-000000000001',
21 + 'title': 'تکلیف اول',
22 + 'kind': 'assignment',
23 + 'status': 'planned',
24 + 'visibility': 'private',
25 + 'planned_duration_seconds': 1500,
26 + 'version': 1
27 + },
28 + {
29 + 'id': '30000000-0000-4000-8000-000000000002',
30 + 'title': 'تکلیف دوم',
31 + 'kind': 'assignment',
32 + 'status': 'planned',
33 + 'visibility': 'selected_members',
34 + 'planned_duration_seconds': 900,
35 + 'version': 1
36 + },
37 + ];
38 + @override
39 + Future<List<Map<String, dynamic>>> listPlanItems(
40 + {DateTime? from, DateTime? to, String? kind}) async {
41 + if (offline) throw const ApiException(0, 'network_unavailable');
42 + return items
43 + .where((r) => r['status'] != 'cancelled')
44 + .map((r) => Map<String, dynamic>.from(r))
45 + .toList();
46 + }
47 +
48 + @override
49 + Future<Map<String, dynamic>> submitSyncMutations(
50 + List<Map<String, dynamic>> mutations) async {
51 + if (offline) throw const ApiException(0, 'network_unavailable');
52 + return {
53 + 'results': mutations.map((m) {
54 + final item = items.firstWhere((r) => r['id'] == m['entityId']);
55 + item.addAll(Map<String, dynamic>.from(m['payload'] as Map));
56 + item['version'] = (m['expectedVersion'] as int) + 1;
57 + return {
58 + 'id': m['id'],
59 + 'status': 'accepted',
60 + 'item': {...item},
61 + 'acceptedAt': '2026-10-16T10:00:00Z'
62 + };
63 + }).toList()
64 + };
65 + }
66 +}
67 +
68 +void main() {
69 + TestWidgetsFlutterBinding.ensureInitialized();
70 + setUp(() {
71 + WidgetController.hitTestWarningShouldBeFatal = true;
72 + SharedPreferences.setMockInitialValues({});
73 + SharedPreferencesAsyncPlatform.instance =
74 + InMemorySharedPreferencesAsync.withData({});
75 + String? token;
76 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
77 + .setMockMethodCallHandler(
78 + const MethodChannel('lifeguide/local_write_guard'), (call) async {
79 + if (call.method == 'getBlocked') return token != null;
80 + if (call.method == 'beginWrite') return token = 'synthetic-detail-write';
81 + if (call.method == 'completeWrite' && call.arguments == token) {
82 + token = null;
83 + return true;
84 + }
85 + throw PlatformException(code: 'local_storage_restart_required');
86 + });
87 + });
88 + Future<void> planner(WidgetTester tester, IdentityApi api) async {
89 + await tester.pumpWidget(MaterialApp(
90 + home: Directionality(
91 + textDirection: TextDirection.rtl,
92 + child: Scaffold(body: PlannerPage(api: api)))));
93 + await tester.pumpAndSettle();
94 + }
95 +
96 + testWidgets(
97 + 'second task opens its own detail and complete uses acknowledged sync',
98 + (tester) async {
99 + final api = TaskApi();
100 + await planner(tester, api);
101 + await tester.tap(find.text('تکلیف دوم'));
102 + await tester.pumpAndSettle();
103 + expect(find.byKey(const ValueKey('plan-details')), findsOneWidget);
104 + expect(find.text('تکلیف دوم'), findsOneWidget);
105 + expect(find.text('اعضای انتخاب‌شده'), findsOneWidget);
106 + await tester.tap(find.byKey(const ValueKey('detail-complete')));
107 + await tester.pumpAndSettle();
108 + expect(api.items[1]['status'], 'completed');
109 + expect(find.text('توسط سرور تأیید شد'), findsOneWidget);
110 + expect(find.textContaining('انجام‌شده'), findsOneWidget);
111 + await tester.pumpWidget(const SizedBox());
112 + });
113 + testWidgets('detail edits preserve sharing and archive requires confirmation',
114 + (tester) async {
115 + final api = TaskApi();
116 + await planner(tester, api);
117 + await tester.tap(find.text('تکلیف اول'));
118 + await tester.pumpAndSettle();
119 + await tester.tap(find.byKey(const ValueKey('detail-edit')));
120 + await tester.pumpAndSettle();
121 + await tester.enterText(
122 + find.widgetWithText(TextField, 'عنوان'), 'تکلیف ویرایش‌شده');
123 + await tester.tap(find.text('ذخیره'));
124 + await tester.pumpAndSettle();
125 + expect(find.text('تکلیف ویرایش‌شده'), findsOneWidget);
126 + expect(api.items.first['visibility'], 'private');
127 + await tester.pump(const Duration(seconds: 5));
128 + await tester.ensureVisible(find.byKey(const ValueKey('detail-archive')));
129 + await tester.tap(find.byKey(const ValueKey('detail-archive')));
130 + await tester.pumpAndSettle();
131 + expect(api.items.first['status'], 'planned');
132 + await tester.tap(find.text('بایگانی').last);
133 + await tester.pumpAndSettle();
134 + expect(api.items.first['status'], 'cancelled');
135 + expect(find.byKey(const ValueKey('plan-details')), findsNothing);
136 + await tester.pumpWidget(const SizedBox());
137 + });
138 + testWidgets('offline completion is pending rather than server confirmed',
139 + (tester) async {
140 + final api = TaskApi();
141 + await planner(tester, api);
142 + await tester.tap(find.text('تکلیف اول'));
143 + await tester.pumpAndSettle();
144 + api.offline = true;
145 + await tester.tap(find.byKey(const ValueKey('detail-complete')));
146 + await tester.pumpAndSettle();
147 + expect(find.text('در انتظار تأیید سرور'), findsOneWidget);
148 + expect(find.text('توسط سرور تأیید شد'), findsNothing);
149 + expect(api.items.first['status'], 'planned');
150 + expect(find.byKey(const ValueKey('detail-study')), findsNothing);
151 + await tester.pumpWidget(const SizedBox());
152 + });
153 + testWidgets('a scoped offline create remains editable and cannot start study',
154 + (tester) async {
155 + final api = HttpIdentityApi(
156 + baseUrl: 'https://pending-detail.example.test/api',
157 + client: MockClient(
158 + (_) async => throw http.ClientException('synthetic offline')))
159 + ..accessToken = 'synthetic-token'
160 + ..currentUserId = 'synthetic-owner';
161 + await PlanSync(api).create({
162 + 'title': 'تکلیف آفلاین ساختگی',
163 + 'kind': 'assignment',
164 + 'visibility': 'private'
165 + });
166 + await planner(tester, api);
167 + await tester.tap(find.text('تکلیف آفلاین ساختگی'));
168 + await tester.pumpAndSettle();
169 + expect(find.byKey(const ValueKey('detail-edit')), findsOneWidget);
170 + expect(find.byKey(const ValueKey('detail-study')), findsNothing);
171 + expect(find.text('در انتظار تأیید سرور'), findsOneWidget);
172 + await tester.pumpWidget(const SizedBox());
173 + api.close();
174 + });
175 + testWidgets(
176 + 'return from study refreshes changed server version before completion',
177 + (tester) async {
178 + var version = 1;
179 + int? sentVersion;
180 + final item = {
181 + 'id': '30000000-0000-4000-8000-000000000004',
182 + 'owner_user_id': 'synthetic-owner',
183 + 'title': 'کار با تایمر',
184 + 'kind': 'assignment',
185 + 'status': 'planned',
186 + 'visibility': 'private'
187 + };
188 + final api = HttpIdentityApi(
189 + baseUrl: 'https://timer-detail.example.test/api',
190 + client: MockClient((req) async {
191 + Object body;
192 + if (req.url.path.endsWith('/study/sessions')) {
193 + body = {'sessions': []};
194 + } else if (req.method == 'POST') {
195 + final mutation =
196 + (jsonDecode(req.body)['mutations'] as List).single as Map;
197 + sentVersion = mutation['expectedVersion'];
198 + body = {
199 + 'results': [
200 + {
201 + 'id': mutation['id'],
202 + 'status': 'accepted',
203 + 'acceptedAt': '2026-10-16T11:00:00Z',
204 + 'item': {
205 + ...item,
206 + 'version': version + 1,
207 + 'status': 'completed'
208 + }
209 + }
210 + ]
211 + };
212 + } else {
213 + body = {
214 + 'items': [
215 + {...item, 'version': version}
216 + ]
217 + };
218 + }
219 + return http.Response(jsonEncode(body), 200,
220 + headers: {'content-type': 'application/json; charset=utf-8'});
221 + }))
222 + ..accessToken = 'synthetic-token'
223 + ..currentUserId = 'synthetic-owner';
224 + await planner(tester, api);
225 + await tester.tap(find.text('کار با تایمر'));
226 + await tester.pumpAndSettle();
227 + await tester.tap(find.byKey(const ValueKey('detail-study')));
228 + await tester.pump(const Duration(milliseconds: 400));
229 + await tester.pump(const Duration(milliseconds: 400));
230 + version = 2; // server version advanced while study route was open
231 + await tester.tap(find.byType(BackButton).last);
232 + await tester.pumpAndSettle();
233 + await tester.tap(find.byKey(const ValueKey('detail-complete')));
234 + await tester.pumpAndSettle();
235 + expect(sentVersion, 2);
236 + await tester.pumpWidget(const SizedBox());
237 + api.close();
238 + });
239 + testWidgets('revoked shared details disappear on polling', (tester) async {
240 + bool visible = true;
241 + final api = HttpIdentityApi(
242 + baseUrl: 'https://visibility-detail.example.test/api',
243 + client: MockClient((req) async => http.Response(
244 + jsonEncode({
245 + 'items': visible
246 + ? [
247 + {
248 + 'id': '30000000-0000-4000-8000-000000000005',
249 + 'owner_user_id': 'other-owner',
250 + 'title': 'اشتراک موقت ساختگی',
251 + 'kind': 'assignment',
252 + 'status': 'planned',
253 + 'visibility': 'family',
254 + 'version': 1
255 + }
256 + ]
257 + : []
258 + }),
259 + 200,
260 + headers: {'content-type': 'application/json; charset=utf-8'})))
261 + ..accessToken = 'synthetic-token'
262 + ..currentUserId = 'synthetic-reader';
263 + await planner(tester, api);
264 + await tester.tap(find.text('اشتراک موقت ساختگی'));
265 + await tester.pumpAndSettle();
266 + visible = false;
267 + await tester.pump(const Duration(seconds: 16));
268 + await tester.pumpAndSettle();
269 + expect(find.text('اشتراک موقت ساختگی'), findsNothing);
270 + await tester.pumpWidget(const SizedBox());
271 + api.close();
272 + });
273 + testWidgets('shared snapshot is hidden across background and resume',
274 + (tester) async {
275 + final api = HttpIdentityApi(
276 + baseUrl: 'https://background-detail.example.test/api',
277 + client: MockClient((req) async => http.Response(
278 + jsonEncode({
279 + 'items': [
280 + {
281 + 'id': '30000000-0000-4000-8000-000000000006',
282 + 'owner_user_id': 'other-owner',
283 + 'title': 'اشتراک پس‌زمینه ساختگی',
284 + 'kind': 'assignment',
285 + 'status': 'planned',
286 + 'visibility': 'family',
287 + 'version': 1
288 + }
289 + ]
290 + }),
291 + 200,
292 + headers: {'content-type': 'application/json; charset=utf-8'})))
293 + ..accessToken = 'synthetic-token'
294 + ..currentUserId = 'synthetic-reader';
295 + await planner(tester, api);
296 + await tester.tap(find.text('اشتراک پس‌زمینه ساختگی'));
297 + await tester.pumpAndSettle();
298 + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
299 + await tester.pump();
300 + expect(find.text('اشتراک پس‌زمینه ساختگی'), findsNothing);
301 + await tester.pumpWidget(const SizedBox());
302 + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
303 + api.close();
304 + });
305 + testWidgets('shared non-owner detail is read-only and has no timer',
306 + (tester) async {
307 + final api = HttpIdentityApi(
308 + baseUrl: 'https://detail.example.test/api',
309 + client: MockClient((req) async => http.Response(
310 + jsonEncode({
311 + 'items': [
312 + {
313 + 'id': '30000000-0000-4000-8000-000000000003',
314 + 'owner_user_id': 'other-owner',
315 + 'title': 'کار مشترک',
316 + 'kind': 'assignment',
317 + 'status': 'planned',
318 + 'visibility': 'family',
319 + 'version': 1
320 + }
321 + ]
322 + }),
323 + 200,
324 + headers: {'content-type': 'application/json; charset=utf-8'})))
325 + ..accessToken = 'synthetic-token'
326 + ..currentUserId = 'synthetic-reader';
327 + await planner(tester, api);
328 + await tester.tap(find.text('کار مشترک'));
329 + await tester.pumpAndSettle();
330 + expect(find.byKey(const ValueKey('plan-details')), findsOneWidget);
331 + expect(find.byKey(const ValueKey('detail-edit')), findsNothing);
332 + expect(find.byKey(const ValueKey('detail-complete')), findsNothing);
333 + expect(find.byKey(const ValueKey('detail-archive')), findsNothing);
334 + expect(find.byKey(const ValueKey('detail-study')), findsNothing);
335 + expect(find.textContaining('فقط مشاهده'), findsOneWidget);
336 + await tester.pumpWidget(const SizedBox());
337 + api.close();
338 + });
339 +}