LifeMate — Personal, Family & Learning Companion
feat(planner): connect weekly navigation and independent occurrence actions
Quinn White committed
Oct 18, 2026 at 21:51 UTC
d0d52275bdd0f2650e82e95f1d51ba312acf6aa4
9 files changed
+789
-130
apps/lifemate/lib/main.dart
+18
@@ -6,6 +6,7 @@ import 'package:flutter_localizations/flutter_localizations.dart';
6
7
import 'api.dart';
8
import 'mobile_home.dart';
9
+import 'device_reminder_settings.dart';
10
import 'study_ui.dart';
11
import 'dashboard_ui.dart';
12
import 'iran_hub.dart';
@@ -1228,6 +1229,13 @@ class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1229
retry: loadContext);
1230
}
1231
if (page == 'خانه') {
1232
+ if (!adultShell) {
1233
+ return TodayPage(
1234
+ api: widget.api,
1235
+ home: true,
1236
+ displayName: displayName,
1237
+ onOpenPlanner: () => selectPage('برنامه من'));
1238
+ }
1239
return MobileHomeMenu(
1240
displayName: displayName, adult: adultShell, onOpen: openHomeMenu);
1241
}
@@ -1349,6 +1357,16 @@ class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1357
builder: (_) =>
1358
NotificationInboxPage(api: widget.api)));
1359
}),
1360
+ if (httpApi != null)
1361
+ ListTile(
1362
+ leading: const Icon(Icons.alarm),
1363
+ title: const Text('اعلان روی این گوشی'),
1364
+ onTap: () {
1365
+ Navigator.pop(context);
1366
+ Navigator.of(context).push(MaterialPageRoute(
1367
+ builder: (_) => DeviceReminderSettingsPage(
1368
+ api: httpApi!)));
1369
+ }),
1370
ListTile(
1371
leading: const Icon(Icons.sync_problem_outlined),
1372
title: const Text('تغییرهای معلق و تعارضها'),
apps/lifemate/lib/phase3_ui.dart
+392
-58
@@ -7,6 +7,9 @@ import 'plan_details_ui.dart';
7
import 'study_ui.dart';
8
import 'dashboard_ui.dart';
9
import 'school_management_ui.dart';
10
+import 'planner_series.dart';
11
+import 'planner_series_ui.dart';
12
+import 'device_reminder_coordinator.dart';
13
14
String faKind(String kind) => switch (kind) {
15
'assignment' => 'تکلیف',
@@ -176,10 +179,23 @@ class SyncNotice extends StatelessWidget {
179
}
180
181
class TodayPage extends StatelessWidget {
179
- const TodayPage({super.key, required this.api});
182
+ const TodayPage(
183
+ {super.key,
184
+ required this.api,
185
+ this.home = false,
186
+ this.displayName = '',
187
+ this.onOpenPlanner});
188
final IdentityApi api;
189
+ final bool home;
190
+ final String displayName;
191
+ final VoidCallback? onOpenPlanner;
192
@override
182
- Widget build(BuildContext context) => _PlanList(api: api, today: true);
193
+ Widget build(BuildContext context) => _PlanList(
194
+ api: api,
195
+ today: true,
196
+ home: home,
197
+ displayName: displayName,
198
+ onOpenPlanner: onOpenPlanner);
199
}
200
201
class PlannerPage extends StatelessWidget {
@@ -190,9 +206,17 @@ class PlannerPage extends StatelessWidget {
206
}
207
208
class _PlanList extends StatefulWidget {
193
- const _PlanList({required this.api, required this.today});
209
+ const _PlanList(
210
+ {required this.api,
211
+ required this.today,
212
+ this.home = false,
213
+ this.displayName = '',
214
+ this.onOpenPlanner});
215
final IdentityApi api;
216
final bool today;
217
+ final bool home;
218
+ final String displayName;
219
+ final VoidCallback? onOpenPlanner;
220
@override
221
State<_PlanList> createState() => _PlanListState();
222
}
@@ -203,6 +227,9 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
227
bool loading = false;
228
String? busyId;
229
String? operationError;
230
+ String? reminderError;
231
+ String? materializedWeek;
232
+ DateTime selectedDay = DateTime.now();
233
Set<String> ownedCreates = {};
234
ValueNotifier<Map<String, dynamic>?>? sharedDetail;
235
String? sharedDetailId;
@@ -243,6 +270,24 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
270
try {
271
final store = OfflineStore.forApi(widget.api);
272
await PlanSync(widget.api, store: store).flush();
273
+ final http = widget.api;
274
+ if (http is HttpIdentityApi) {
275
+ final series = PlannerSeriesSync(http, store: store);
276
+ await series.flush();
277
+ try {
278
+ final days =
279
+ plannerWeekDays(widget.today ? DateTime.now() : selectedDay);
280
+ final key = plannerDate(days.first);
281
+ if (materializedWeek != key) {
282
+ await series.materialize(days.first, days.last);
283
+ materializedWeek = key;
284
+ }
285
+ } catch (error) {
286
+ // A missing/new API route is a real compatibility error. Only a
287
+ // transport failure may use this account's existing offline rows.
288
+ if (!isOfflineFailure(error)) rethrow;
289
+ }
290
+ }
291
final now = DateTime.now();
292
final from = DateTime(now.year, now.month, now.day);
293
final to = from.add(const Duration(days: 1));
@@ -250,10 +295,26 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
295
var reminders = <Map<String, dynamic>>[];
296
bool offline = false;
297
try {
253
- items = widget.today
254
- ? await widget.api.getToday(from: from, to: to)
255
- : await widget.api.listPlanItems();
298
+ items = widget.home
299
+ ? await widget.api.listPlanItems(from: from, to: to)
300
+ : widget.today
301
+ ? await widget.api.getToday(from: from, to: to)
302
+ : await widget.api.listPlanItems();
303
+ if (widget.home && http is HttpIdentityApi) {
304
+ items = items
305
+ .where((row) => row['owner_user_id'] == http.currentUserId)
306
+ .toList();
307
+ }
308
if (widget.today) reminders = await widget.api.claimDueReminders();
309
+ if (http is HttpIdentityApi) {
310
+ try {
311
+ await DeviceReminderCoordinator(http).reconcile();
312
+ reminderError = null;
313
+ } catch (_) {
314
+ reminderError =
315
+ 'برنامه دریافت شد؛ تازهسازی اعلان این گوشی موفق نشد. تنظیمات اعلان را بررسی کن.';
316
+ }
317
+ }
318
// The store merges queued mutations atomically with each fresh cache.
319
if (widget.today) {
320
await store.cacheToday(items);
@@ -306,7 +367,10 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
367
[Map<String, dynamic>? item, bool notify = true]) async {
368
final outcome = await showDialog<MutationOutcome>(
369
context: context,
309
- builder: (_) => PlanItemDialog(api: widget.api, item: item));
370
+ builder: (_) => PlanItemDialog(
371
+ api: widget.api,
372
+ item: item,
373
+ initialDate: widget.today ? null : selectedDay));
374
if (outcome != null && mounted) {
375
if (notify) {
376
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
@@ -328,6 +392,90 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
392
(owner == null && ownedCreates.contains(item['id'])));
393
}
394
395
+ Future<void> addSeries() async {
396
+ final api = widget.api;
397
+ if (api is! HttpIdentityApi) return;
398
+ final result = await showDialog<PlannerSeriesOutcome>(
399
+ context: context,
400
+ barrierDismissible: false,
401
+ builder: (_) =>
402
+ PlannerSeriesDialog(api: api, initialDate: selectedDay));
403
+ if (result != null && mounted) {
404
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
405
+ content: Text(result.queued
406
+ ? 'پیشنویس روی دستگاه ماند؛ نوبتها و اعلان پس از تأیید سرور آماده میشوند.'
407
+ : 'برنامهٔ تکراری و نوبتهای آن در سرور ثبت شد.')));
408
+ await reload();
409
+ }
410
+ }
411
+
412
+ List<Map<String, dynamic>> visibleItems(LoadResult data) {
413
+ if (widget.today) {
414
+ return widget.home ? data.items.take(4).toList() : data.items;
415
+ }
416
+ final rows = data.items.where((row) {
417
+ final date = parseDate(
418
+ row['starts_at'] ?? row['startsAt'] ?? row['due_at'] ?? row['dueAt']);
419
+ return date != null && plannerDate(date) == plannerDate(selectedDay);
420
+ }).toList();
421
+ rows.sort((a, b) => (a['starts_at'] ?? a['due_at'] ?? '')
422
+ .toString()
423
+ .compareTo((b['starts_at'] ?? b['due_at'] ?? '').toString()));
424
+ return rows;
425
+ }
426
+
427
+ Widget weekSelector() =>
428
+ Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
429
+ Row(children: [
430
+ IconButton(
431
+ tooltip: 'هفتهٔ قبل',
432
+ onPressed: () => setState(() {
433
+ selectedDay = selectedDay.subtract(const Duration(days: 7));
434
+ future = load();
435
+ }),
436
+ icon: const Icon(Icons.chevron_right)),
437
+ Expanded(
438
+ child: Text('هفتهٔ من',
439
+ style: Theme.of(context).textTheme.titleLarge)),
440
+ TextButton(
441
+ onPressed: () => setState(() {
442
+ selectedDay = DateTime.now();
443
+ future = load();
444
+ }),
445
+ child: const Text('امروز')),
446
+ IconButton(
447
+ tooltip: 'هفتهٔ بعد',
448
+ onPressed: () => setState(() {
449
+ selectedDay = selectedDay.add(const Duration(days: 7));
450
+ future = load();
451
+ }),
452
+ icon: const Icon(Icons.chevron_left))
453
+ ]),
454
+ SingleChildScrollView(
455
+ scrollDirection: Axis.horizontal,
456
+ child: Row(children: [
457
+ for (final day in plannerWeekDays(selectedDay))
458
+ Padding(
459
+ padding: const EdgeInsets.only(left: 8),
460
+ child: ChoiceChip(
461
+ key: ValueKey('planner-day-${day.weekday}'),
462
+ label: Text('${const {
463
+ 6: 'شنبه',
464
+ 7: 'یکشنبه',
465
+ 1: 'دوشنبه',
466
+ 2: 'سهشنبه',
467
+ 3: 'چهارشنبه',
468
+ 4: 'پنجشنبه',
469
+ 5: 'جمعه'
470
+ }[day.weekday]}\n${shortDay(day)}'),
471
+ selected: plannerDate(day) == plannerDate(selectedDay),
472
+ onSelected: (_) => setState(() => selectedDay = day)))
473
+ ])),
474
+ const SizedBox(height: 12),
475
+ ]);
476
+
477
+ String shortDay(DateTime day) => '${day.month}/${day.day}';
478
+
479
Future<void> openDetails(Map<String, dynamic> item, bool offline) async {
480
final canEdit = owns(item);
481
final updates = canEdit ? null : ValueNotifier<Map<String, dynamic>?>(item);
@@ -412,7 +560,11 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
560
final sync = PlanSync(widget.api);
561
final outcome = action == 'archive'
562
? await sync.archive(item)
415
- : await sync.complete(item);
563
+ : action == 'start'
564
+ ? await sync.update(item, {'status': 'in_progress'})
565
+ : action == 'uncomplete'
566
+ ? await sync.update(item, {'status': 'planned'})
567
+ : await sync.complete(item);
568
if (mounted) {
569
// Detail has an inline receipt; avoid covering its action controls.
570
if (!rethrowFailure || action == 'archive') {
@@ -440,6 +592,11 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
592
if (s.hasError) return LoadError(error: s.error!, retry: reload);
593
if (!s.hasData) return const Center(child: CircularProgressIndicator());
594
final data = s.data!;
595
+ final visible = visibleItems(data);
596
+ final completed =
597
+ data.items.where((row) => row['status'] == 'completed').length;
598
+ final next =
599
+ data.items.where((row) => row['status'] != 'completed').firstOrNull;
600
return RefreshIndicator(
601
onRefresh: reload,
602
child: ListView(padding: const EdgeInsets.all(16), children: [
@@ -453,6 +610,42 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
610
offline: data.offline,
611
pending: data.pending,
612
syncedAt: data.syncedAt),
613
+ if (reminderError != null)
614
+ Card(
615
+ child: Padding(
616
+ padding: const EdgeInsets.all(12),
617
+ child: Text(reminderError!))),
618
+ if (widget.home) ...[
619
+ Text('سلام ${widget.displayName}',
620
+ style: Theme.of(context).textTheme.headlineSmall),
621
+ const SizedBox(height: 12),
622
+ Card(
623
+ child: Padding(
624
+ padding: const EdgeInsets.all(16),
625
+ child: Column(
626
+ crossAxisAlignment: CrossAxisAlignment.start,
627
+ children: [
628
+ Text('قدم بعدی',
629
+ style:
630
+ Theme.of(context).textTheme.titleLarge),
631
+ const SizedBox(height: 8),
632
+ Text(next?['title']?.toString() ??
633
+ 'امروز کاری نداری؛ میتوانی برنامهٔ فردا را آماده کنی.'),
634
+ if (next != null)
635
+ FilledButton(
636
+ onPressed: busyId == null && owns(next)
637
+ ? () => action(next, 'start')
638
+ : null,
639
+ child: const Text('شروع')),
640
+ const SizedBox(height: 12),
641
+ Text(
642
+ '$completed از ${data.items.length} کار امروز انجام شده'),
643
+ LinearProgressIndicator(
644
+ value: data.items.isEmpty
645
+ ? 0
646
+ : completed / data.items.length),
647
+ ]))),
648
+ ],
649
if (operationError != null)
650
Card(
651
child: Padding(
@@ -462,7 +655,7 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
655
color: Theme.of(context).colorScheme.error)))),
656
Row(children: [
657
Expanded(
465
- child: Text(widget.today ? 'امروز' : 'برنامهریز',
658
+ child: Text(widget.today ? 'کارهای امروز' : 'برنامهریز',
659
style: Theme.of(context).textTheme.headlineSmall)),
660
if (!widget.today)
661
FilledButton.icon(
@@ -470,16 +663,47 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
663
icon: const Icon(Icons.add),
664
label: const Text('جدید'))
665
]),
473
- if (data.items.isEmpty)
666
+ if (widget.home)
667
+ Align(
668
+ alignment: AlignmentDirectional.centerEnd,
669
+ child: TextButton(
670
+ key: const ValueKey('home-plan'),
671
+ onPressed: widget.onOpenPlanner,
672
+ child: const Text('دیدن برنامهٔ هفته'))),
673
+ if (!widget.today) ...[
674
+ weekSelector(),
675
+ if (widget.api is HttpIdentityApi)
676
+ OutlinedButton.icon(
677
+ onPressed: busyId == null ? addSeries : null,
678
+ icon: const Icon(Icons.repeat),
679
+ label: const Text('برنامهٔ تکراری')),
680
+ const Text(
681
+ 'تیک و ویرایش هر نوبت فقط همان روز را تغییر میدهد.'),
682
+ ],
683
+ if (visible.isEmpty)
684
const EmptyCard(
685
icon: Icons.task_alt,
686
title: 'موردی در این برنامه نیست',
687
subtitle: 'از برنامهریز کار یا تکلیف جدید اضافه کن.'),
478
- ...data.items.map((item) => Card(
688
+ ...visible.map((item) => Card(
689
child: ListTile(
480
- leading: Icon(item['status'] == 'completed'
481
- ? Icons.check_circle_outline
482
- : Icons.radio_button_unchecked),
690
+ leading: !owns(item)
691
+ ? const Icon(Icons.visibility_outlined)
692
+ : IconButton(
693
+ key: ValueKey('tick-${item['id']}'),
694
+ tooltip: item['status'] == 'completed'
695
+ ? 'برگرداندن به برنامه'
696
+ : 'انجام شد',
697
+ onPressed: busyId == null
698
+ ? () => action(
699
+ item,
700
+ item['status'] == 'completed'
701
+ ? 'uncomplete'
702
+ : 'complete')
703
+ : null,
704
+ icon: Icon(item['status'] == 'completed'
705
+ ? Icons.check_circle
706
+ : Icons.radio_button_unchecked)),
707
onTap: busyId == null
708
? () => openDetails(item, data.offline)
709
: null,
@@ -491,31 +715,54 @@ class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
715
width: 24,
716
height: 24,
717
child: CircularProgressIndicator())
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
- ]),
718
+ : widget.home &&
719
+ owns(item) &&
720
+ item['status'] != 'completed'
721
+ ? TextButton(
722
+ onPressed: busyId == null
723
+ ? () => action(item, 'start')
724
+ : null,
725
+ child: const Text('شروع'))
726
+ : !owns(item)
727
+ ? const Icon(Icons.visibility_outlined)
728
+ : PopupMenuButton<String>(
729
+ onSelected: (v) => action(item, v),
730
+ itemBuilder: (_) => [
731
+ const PopupMenuItem(
732
+ value: 'edit',
733
+ child: Text('ویرایش')),
734
+ const PopupMenuItem(
735
+ value: 'complete',
736
+ child: Text('انجام شد')),
737
+ if (item['pending_sync'] != true &&
738
+ widget.api is HttpIdentityApi &&
739
+ [
740
+ 'assignment',
741
+ 'task',
742
+ 'study_session'
743
+ ].contains(item['kind']))
744
+ const PopupMenuItem(
745
+ value: 'study',
746
+ child: Text('تایمر مطالعه')),
747
+ const PopupMenuItem(
748
+ value: 'archive',
749
+ child: Text('بایگانی')),
750
+ ]),
751
))),
752
+ if (!widget.today &&
753
+ data.items.any((row) =>
754
+ parseDate(row['starts_at'] ?? row['due_at']) ==
755
+ null)) ...[
756
+ const SizedBox(height: 12),
757
+ Text('بدون زمان مشخص',
758
+ style: Theme.of(context).textTheme.titleMedium),
759
+ for (final item in data.items.where((row) =>
760
+ parseDate(row['starts_at'] ?? row['due_at']) == null))
761
+ Card(
762
+ child: ListTile(
763
+ title: Text(item['title']?.toString() ?? ''),
764
+ onTap: () => openDetails(item, data.offline))),
765
+ ],
766
]));
767
});
768
}
@@ -525,10 +772,12 @@ class PlanItemDialog extends StatefulWidget {
772
{super.key,
773
required this.api,
774
this.item,
775
+ this.initialDate,
776
this.initialKind = 'task',
777
this.subjects = const []});
778
final IdentityApi api;
779
final Map<String, dynamic>? item;
780
+ final DateTime? initialDate;
781
final String initialKind;
782
final List<Map<String, dynamic>> subjects;
783
@override
@@ -540,6 +789,9 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
789
late String kind;
790
String priority = 'normal', status = 'planned';
791
late DateTime when;
792
+ late DateTime endsWhen;
793
+ bool hasRange = false, rangeChanged = false, reminderChanged = false;
794
+ int reminderBefore = -1;
795
bool shared = false, busy = false, sharingChanged = false;
796
String originalVisibility = 'private';
797
String? subjectId;
@@ -564,8 +816,15 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
816
kind = i?['kind']?.toString() ?? widget.initialKind;
817
priority = i?['priority']?.toString() ?? 'normal';
818
status = i?['status']?.toString() ?? 'planned';
567
- when = parseDate(i?['due_at'] ?? i?['dueAt'] ?? i?['starts_at']) ??
568
- DateTime.now().add(const Duration(hours: 1));
819
+ when = parseDate(
820
+ i?['starts_at'] ?? i?['startsAt'] ?? i?['due_at'] ?? i?['dueAt']) ??
821
+ (widget.initialDate == null
822
+ ? DateTime.now().add(const Duration(hours: 1))
823
+ : DateTime(widget.initialDate!.year, widget.initialDate!.month,
824
+ widget.initialDate!.day, 9));
825
+ hasRange = i == null || i['starts_at'] != null || i['startsAt'] != null;
826
+ endsWhen = parseDate(i?['ends_at'] ?? i?['endsAt']) ??
827
+ when.add(Duration(minutes: int.tryParse(minutes.text) ?? 30));
828
originalVisibility = i?['visibility']?.toString() ?? 'private';
829
shared = originalVisibility != 'private';
830
subjectId = i?['subject_id']?.toString() ?? i?['subjectId']?.toString();
@@ -573,7 +832,7 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
832
subjectId = widget.subjects.first['id'].toString();
833
}
834
familyId = i?['family_id']?.toString() ?? i?['familyId']?.toString();
576
- loadFamilies();
835
+ if (i?['series_id'] == null) loadFamilies();
836
}
837
838
Future<void> loadFamilies() async {
@@ -605,8 +864,25 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
864
final time = await showTimePicker(
865
context: context, initialTime: TimeOfDay.fromDateTime(when));
866
if (time != null && mounted) {
608
- setState(() => when =
609
- DateTime(date.year, date.month, date.day, time.hour, time.minute));
867
+ setState(() {
868
+ when =
869
+ DateTime(date.year, date.month, date.day, time.hour, time.minute);
870
+ endsWhen = DateTime(
871
+ date.year, date.month, date.day, endsWhen.hour, endsWhen.minute);
872
+ rangeChanged = true;
873
+ });
874
+ }
875
+ }
876
+
877
+ Future<void> pickEnd() async {
878
+ final time = await showTimePicker(
879
+ context: context, initialTime: TimeOfDay.fromDateTime(endsWhen));
880
+ if (time != null && mounted) {
881
+ setState(() {
882
+ endsWhen =
883
+ DateTime(when.year, when.month, when.day, time.hour, time.minute);
884
+ rangeChanged = true;
885
+ });
886
}
887
}
888
@@ -616,7 +892,13 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
892
setState(() => error = 'عنوان را وارد کن.');
893
return;
894
}
619
- final duration = int.tryParse(numberInput(minutes.text));
895
+ final duration = hasRange
896
+ ? endsWhen.difference(when).inMinutes
897
+ : int.tryParse(numberInput(minutes.text));
898
+ if (hasRange && (duration == null || duration <= 0 || duration > 1440)) {
899
+ setState(() => error = 'پایان باید پس از شروع و در همان روز باشد.');
900
+ return;
901
+ }
902
if (duration == null || duration < 0 || duration > 1440) {
903
setState(
904
() => error = 'زمان برنامهریزیشده باید بین صفر و ۱۴۴۰ دقیقه باشد.');
@@ -662,7 +944,17 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
944
'priority': priority,
945
'status': status,
946
'notes': notes.text.trim(),
665
- 'dueAt': when.toUtc().toIso8601String(),
947
+ 'dueAt': (hasRange ? endsWhen : when).toUtc().toIso8601String(),
948
+ if (item == null ||
949
+ rangeChanged ||
950
+ item['starts_at'] != null ||
951
+ item['startsAt'] != null) ...{
952
+ 'startsAt': hasRange ? when.toUtc().toIso8601String() : null,
953
+ 'endsAt': hasRange ? endsWhen.toUtc().toIso8601String() : null,
954
+ },
955
+ if (item == null || reminderChanged)
956
+ 'reminderMinutesBefore':
957
+ reminderBefore < 0 ? <int>[] : [reminderBefore],
958
'plannedDurationSeconds': duration * 60,
959
'visibility': visibility,
960
'familyId': visibility != 'private' ? familyId : null,
@@ -760,7 +1052,7 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
1052
const SizedBox(height: 12),
1053
TextField(
1054
controller: minutes,
763
- enabled: !busy,
1055
+ enabled: !busy && !hasRange,
1056
keyboardType: TextInputType.number,
1057
decoration: const InputDecoration(
1058
labelText: 'زمان برنامهریزیشده (دقیقه)')),
@@ -780,10 +1072,48 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
1072
decoration: const InputDecoration(
1073
labelText: 'سقف نمره (اختیاری)')),
1074
],
1075
+ CheckboxListTile(
1076
+ key: const ValueKey('plan-time-range'),
1077
+ title: const Text('ساعت شروع و پایان'),
1078
+ value: hasRange,
1079
+ onChanged: busy
1080
+ ? null
1081
+ : (value) => setState(() {
1082
+ hasRange = value ?? false;
1083
+ rangeChanged = true;
1084
+ })),
1085
TextButton.icon(
1086
onPressed: busy ? null : pickDate,
1087
icon: const Icon(Icons.calendar_month),
786
- label: Text('موعد · ${shortDate(when.toIso8601String())}')),
1088
+ label: Text(
1089
+ '${hasRange ? 'شروع' : 'موعد'} · ${shortDate(when.toIso8601String())}')),
1090
+ if (hasRange)
1091
+ TextButton.icon(
1092
+ key: const ValueKey('plan-end-time'),
1093
+ onPressed: busy ? null : pickEnd,
1094
+ icon: const Icon(Icons.schedule),
1095
+ label: Text(
1096
+ 'پایان · ${shortDate(endsWhen.toIso8601String())}')),
1097
+ DropdownButtonFormField<int>(
1098
+ key: const ValueKey('plan-reminder'),
1099
+ initialValue: reminderBefore,
1100
+ decoration: InputDecoration(
1101
+ labelText: widget.item != null && !reminderChanged
1102
+ ? 'یادآوری (فقط در صورت تغییر جایگزین میشود)'
1103
+ : 'یادآوری'),
1104
+ items: const [
1105
+ DropdownMenuItem(value: -1, child: Text('بدون یادآوری')),
1106
+ DropdownMenuItem(value: 0, child: Text('زمان شروع')),
1107
+ DropdownMenuItem(value: 5, child: Text('۵ دقیقه قبل')),
1108
+ DropdownMenuItem(value: 10, child: Text('۱۰ دقیقه قبل')),
1109
+ DropdownMenuItem(value: 15, child: Text('۱۵ دقیقه قبل'))
1110
+ ],
1111
+ onChanged: busy
1112
+ ? null
1113
+ : (value) => setState(() {
1114
+ reminderBefore = value ?? -1;
1115
+ reminderChanged = true;
1116
+ })),
1117
TextField(
1118
controller: notes,
1119
enabled: !busy,
@@ -792,17 +1122,21 @@ class _PlanItemDialogState extends State<PlanItemDialog> {
1122
labelText: 'یادداشت خصوصی',
1123
helperText:
1124
'یادداشت در گزارش والد نمایش داده نمیشود.')),
795
- SwitchListTile(
796
- title: const Text('اشتراک تکلیف با والد / سرپرست'),
797
- subtitle: const Text(
798
- 'عنوان، وضعیت و زمان ثبتشده برای سرپرست مجاز دیده میشود.'),
799
- value: shared,
800
- onChanged: busy
801
- ? null
802
- : (v) => setState(() {
803
- shared = v;
804
- sharingChanged = true;
805
- })),
1125
+ if (widget.item?['series_id'] != null)
1126
+ const Text(
1127
+ 'این نوبت خصوصی است؛ ویرایش و تیک فقط همین روز را تغییر میدهد.'),
1128
+ if (widget.item?['series_id'] == null)
1129
+ SwitchListTile(
1130
+ title: const Text('اشتراک تکلیف با والد / سرپرست'),
1131
+ subtitle: const Text(
1132
+ 'عنوان، وضعیت و زمان ثبتشده برای سرپرست مجاز دیده میشود.'),
1133
+ value: shared,
1134
+ onChanged: busy
1135
+ ? null
1136
+ : (v) => setState(() {
1137
+ shared = v;
1138
+ sharingChanged = true;
1139
+ })),
1140
if (widget.item != null &&
1141
!['private', 'parent_guardian']
1142
.contains(originalVisibility) &&
apps/lifemate/lib/planner_series.dart
+14
-2
@@ -65,6 +65,9 @@ class PlannerSeriesSync {
65
.where((s) => s['id'] == seriesId)
66
.firstOrNull;
67
if (accepted != null) {
68
+ if (_canonical(accepted['_create_payload']) != _canonical(body)) {
69
+ throw const ApiException(409, 'mutation_id_reused');
70
+ }
71
return PlannerSeriesOutcome(queued: false, id: seriesId);
72
}
73
await store.enqueue({
@@ -94,7 +97,12 @@ class PlannerSeriesSync {
97
Future<void> _flush() async {
98
for (final queued in await store.readQueue()) {
99
if (queued['entityType'] != 'planner_series') continue;
97
- _throwTerminal(queued);
100
+ // A rejected draft stays visible in the recovery journal; it must not
101
+ // prevent unrelated plans from loading or other drafts from syncing.
102
+ if (queued['queueStatus'] == 'conflict' ||
103
+ queued['queueStatus'] == 'rejected') {
104
+ continue;
105
+ }
106
_checkScope();
107
try {
108
final response = await api.requestJson('POST', '/v1/planner-series',
@@ -115,7 +123,10 @@ class PlannerSeriesSync {
123
throw const ApiException(502, 'invalid_series_acknowledgement');
124
}
125
await store.acknowledge(queued['id'] as String,
118
- item: Map<String, dynamic>.from(series),
126
+ item: {
127
+ ...Map<String, dynamic>.from(series),
128
+ '_create_payload': queued['payload']
129
+ },
130
cacheKey: 'planner_series');
131
// Fresh occurrence rows merge with other queued item edits in the store.
132
final planner = await store.readPlanner();
@@ -129,6 +140,7 @@ class PlannerSeriesSync {
140
if (error is ApiException &&
141
error.statusCode >= 400 &&
142
error.statusCode < 500 &&
143
+ error.statusCode != 401 &&
144
error.statusCode != 429) {
145
await store.markQueued(queued['id'] as String,
146
error.statusCode == 409 ? 'conflict' : 'rejected',
apps/lifemate/lib/sync_changes_ui.dart
+27
-4
@@ -8,6 +8,7 @@ import 'study_coordinator.dart';
8
import 'learning_sync.dart';
9
import 'learning_feedback_ui.dart';
10
import 'learning_quiz_ui.dart';
11
+import 'planner_series.dart';
12
13
class SyncChangesPage extends StatefulWidget {
14
const SyncChangesPage({super.key, required this.api});
@@ -72,6 +73,11 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
73
}
74
final api = widget.api;
75
if (api is HttpIdentityApi) {
76
+ try {
77
+ await PlannerSeriesSync(api, store: store).flush();
78
+ } catch (caught) {
79
+ failure ??= caught;
80
+ }
81
try {
82
await StudySync(api, store: store).flush();
83
} catch (caught) {
@@ -144,9 +150,21 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
150
return;
151
}
152
Map<String, dynamic>? serverItem;
153
+ final isSeries = mutation['entityType'] == 'planner_series';
154
try {
148
- serverItem = await api.requestJson(
149
- 'GET', '/v1/plan-items/${Uri.encodeComponent(id)}');
155
+ final response = await api.requestJson('GET',
156
+ '/v1/${isSeries ? 'planner-series' : 'plan-items'}/${Uri.encodeComponent(id)}');
157
+ if (isSeries) {
158
+ if (response['series'] is! Map) {
159
+ throw const ApiException(502, 'invalid_series_response');
160
+ }
161
+ serverItem = Map<String, dynamic>.from(response['series'] as Map);
162
+ if (serverItem['owner_user_id'] != api.currentUserId) {
163
+ throw const ApiException(502, 'invalid_series_response');
164
+ }
165
+ } else {
166
+ serverItem = response;
167
+ }
168
} on ApiException catch (failure) {
169
final isUnsent =
170
queue.any((m) => m['entityId'] == id && m['operation'] == 'create');
@@ -194,7 +212,10 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
212
));
213
if (mounted) setState(() => dialogOpen = false);
214
if (accepted == true) {
197
- await store.discardEntityChanges(id, serverItem: serverItem);
215
+ await store.discardEntityChanges(id,
216
+ serverItem: serverItem,
217
+ cacheKey: isSeries ? 'planner_series' : null,
218
+ entityType: isSeries ? 'planner_series' : null);
219
}
220
} catch (failure) {
221
if (mounted) {
@@ -225,6 +246,7 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
246
247
String _entityTitle(Map<String, dynamic> mutation) =>
248
switch (mutation['entityType']) {
249
+ 'planner_series' => 'برنامهٔ تکراری',
250
'study_session' => 'ثبت مطالعه',
251
'learning_progress' => 'پیشرفت درس',
252
'learning_attempt' => 'پاسخ آزمون',
@@ -322,7 +344,8 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
344
if (_manualRetryPage(mutation) case final page?)
345
'بررسی و ارسال از «$page»',
346
].join('\n')),
325
- trailing: mutation['entityType'] == 'plan_item' &&
347
+ trailing: ['plan_item', 'planner_series']
348
+ .contains(mutation['entityType']) &&
349
['conflict', 'rejected']
350
.contains(mutation['queueStatus']) &&
351
!hiddenEntities.contains(mutation['entityId'])
apps/lifemate/test/mobile_navigation_test.dart
+18
-24
@@ -70,7 +70,7 @@ void main() {
70
71
for (final size in [const Size(390, 844), const Size(320, 740)]) {
72
testWidgets(
73
- 'compact home menus open separate destinations and back at $size',
73
+ 'today home and bottom destinations open separate pages at $size',
74
(tester) async {
75
tester.view.physicalSize = size;
76
tester.view.devicePixelRatio = 1;
@@ -78,15 +78,16 @@ void main() {
78
addTearDown(tester.view.resetDevicePixelRatio);
79
await shell(tester, MenuApi());
80
expect(find.textContaining('کاربر نمونه'), findsOneWidget);
81
+ expect(find.text('قدم بعدی'), findsOneWidget);
82
for (final entry in {
82
- 'plan': PlannerPage,
83
- 'courses': EducationLibraryPage,
84
- 'focus': StudyHub,
85
- 'family': ProfileFamilyPage
83
+ 'برنامه': PlannerPage,
84
+ 'درسها': EducationLibraryPage,
85
+ 'تمرکز': StudyHub,
86
+ 'خانواده': ProfileFamilyPage
87
}.entries) {
87
- final menu = find.byKey(ValueKey('home-${entry.key}'));
88
+ final menu = find.descendant(
89
+ of: find.byType(NavigationBar), matching: find.text(entry.key));
90
expect(menu.hitTestable(), findsOneWidget);
89
- expect(tester.getRect(menu).bottom, lessThan(size.height - 50));
91
await tester.tap(menu);
92
await tester.pumpAndSettle();
93
expect(find.byType(entry.value), findsOneWidget);
@@ -95,14 +96,11 @@ void main() {
96
await tester.pumpAndSettle();
97
expect(find.byKey(const ValueKey('home-plan')), findsOneWidget);
98
}
98
- for (final key in ['report', 'reminders']) {
99
- expect(find.byKey(ValueKey('home-$key')).hitTestable(), findsOneWidget);
100
- await tester.tap(find.byKey(ValueKey('home-$key')));
101
- await tester.pumpAndSettle();
102
- expect(find.byKey(const ValueKey('home-plan')), findsNothing);
103
- await tester.tap(find.byTooltip('برگشت به خانه'));
104
- await tester.pumpAndSettle();
105
- }
99
+ await tester.tap(find.byTooltip('یادآوریها'));
100
+ await tester.pumpAndSettle();
101
+ expect(find.byKey(const ValueKey('home-plan')), findsNothing);
102
+ await tester.tap(find.byTooltip('برگشت به خانه'));
103
+ await tester.pumpAndSettle();
104
expect(tester.takeException(), isNull);
105
await tester.pumpWidget(const SizedBox());
106
});
@@ -123,14 +121,9 @@ void main() {
121
child: HomeShell(api: MenuApi())))));
122
await tester.pumpAndSettle();
123
await tester.scrollUntilVisible(
126
- find.byKey(const ValueKey('home-reminders')), 150,
127
- scrollable: find
128
- .descendant(
129
- of: find.byKey(const ValueKey('home-scroll')),
130
- matching: find.byType(Scrollable))
131
- .first);
132
- expect(find.byKey(const ValueKey('home-reminders')).hitTestable(),
133
- findsOneWidget);
124
+ find.byKey(const ValueKey('home-plan')), 150);
125
+ expect(
126
+ find.byKey(const ValueKey('home-plan')).hitTestable(), findsOneWidget);
127
expect(tester.takeException(), isNull);
128
await tester.pumpWidget(const SizedBox());
129
});
@@ -152,7 +145,8 @@ void main() {
145
(tester) async {
146
final api = MenuApi();
147
await shell(tester, api);
155
- await tester.tap(find.byKey(const ValueKey('home-family')));
148
+ await tester.tap(find.descendant(
149
+ of: find.byType(NavigationBar), matching: find.text('خانواده')));
150
await tester.pumpAndSettle();
151
api.offlineProfile = true;
152
await tester.tap(find.byTooltip('برگشت به خانه'));
apps/lifemate/test/plan_details_test.dart
+50
-42
@@ -189,7 +189,9 @@ void main() {
189
baseUrl: 'https://timer-detail.example.test/api',
190
client: MockClient((req) async {
191
Object body;
192
- if (req.url.path.endsWith('/study/sessions')) {
192
+ if (req.url.path.endsWith('/planner-series')) {
193
+ body = {'series': []};
194
+ } else if (req.url.path.endsWith('/study/sessions')) {
195
body = {'sessions': []};
196
} else if (req.method == 'POST') {
197
final mutation =
@@ -241,21 +243,23 @@ void main() {
243
final api = HttpIdentityApi(
244
baseUrl: 'https://visibility-detail.example.test/api',
245
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
- }),
246
+ jsonEncode(req.url.path.endsWith('/planner-series')
247
+ ? {'series': []}
248
+ : {
249
+ 'items': visible
250
+ ? [
251
+ {
252
+ 'id': '30000000-0000-4000-8000-000000000005',
253
+ 'owner_user_id': 'other-owner',
254
+ 'title': 'اشتراک موقت ساختگی',
255
+ 'kind': 'assignment',
256
+ 'status': 'planned',
257
+ 'visibility': 'family',
258
+ 'version': 1
259
+ }
260
+ ]
261
+ : []
262
+ }),
263
200,
264
headers: {'content-type': 'application/json; charset=utf-8'})))
265
..accessToken = 'synthetic-token'
@@ -275,19 +279,21 @@ void main() {
279
final api = HttpIdentityApi(
280
baseUrl: 'https://background-detail.example.test/api',
281
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
- }),
282
+ jsonEncode(req.url.path.endsWith('/planner-series')
283
+ ? {'series': []}
284
+ : {
285
+ 'items': [
286
+ {
287
+ 'id': '30000000-0000-4000-8000-000000000006',
288
+ 'owner_user_id': 'other-owner',
289
+ 'title': 'اشتراک پسزمینه ساختگی',
290
+ 'kind': 'assignment',
291
+ 'status': 'planned',
292
+ 'visibility': 'family',
293
+ 'version': 1
294
+ }
295
+ ]
296
+ }),
297
200,
298
headers: {'content-type': 'application/json; charset=utf-8'})))
299
..accessToken = 'synthetic-token'
@@ -307,19 +313,21 @@ void main() {
313
final api = HttpIdentityApi(
314
baseUrl: 'https://detail.example.test/api',
315
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
- }),
316
+ jsonEncode(req.url.path.endsWith('/planner-series')
317
+ ? {'series': []}
318
+ : {
319
+ 'items': [
320
+ {
321
+ 'id': '30000000-0000-4000-8000-000000000003',
322
+ 'owner_user_id': 'other-owner',
323
+ 'title': 'کار مشترک',
324
+ 'kind': 'assignment',
325
+ 'status': 'planned',
326
+ 'visibility': 'family',
327
+ 'version': 1
328
+ }
329
+ ]
330
+ }),
331
200,
332
headers: {'content-type': 'application/json; charset=utf-8'})))
333
..accessToken = 'synthetic-token'
apps/lifemate/test/planner_series_test.dart
+23
@@ -169,6 +169,29 @@ void main() {
169
sync.create(payload, id: seriesId), throwsA(isA<ApiException>()));
170
expect(f.requests, isEmpty);
171
});
172
+ test('rejected draft does not block other sync and keeps recoverable journal',
173
+ () async {
174
+ final f = Fixture()..status = 400;
175
+ await expectLater(
176
+ f.reopen().create(payload, id: seriesId), throwsA(isA<ApiException>()));
177
+ f.status = null;
178
+ await f.reopen().flush();
179
+ expect(f.requests.length, 1);
180
+ await f.store.discardEntityChanges(seriesId,
181
+ entityType: 'planner_series', cacheKey: 'planner_series');
182
+ expect(await f.store.readQueue(), isEmpty);
183
+ expect((await f.store.readDiscardedChanges()).single['entityType'],
184
+ 'planner_series');
185
+ });
186
+ test('acknowledged UUID cannot silently accept edited payload', () async {
187
+ final f = Fixture();
188
+ await f.reopen().create(payload, id: seriesId);
189
+ await expectLater(
190
+ f.reopen().create({...payload, 'title': 'changed'}, id: seriesId),
191
+ throwsA(isA<ApiException>()
192
+ .having((e) => e.code, 'code', 'mutation_id_reused')));
193
+ expect(f.requests.length, 1);
194
+ });
195
test('Saturday week and dates retain selected calendar day', () {
196
final days = plannerWeekDays(DateTime(2026, 10, 18));
197
expect(days.first.weekday, DateTime.saturday);
apps/lifemate/test/sync_changes_test.dart
+38
@@ -24,6 +24,16 @@ class _ConflictApi extends HttpIdentityApi {
24
{Map<String, dynamic>? body, bool auth = true}) async {
25
reads++;
26
if (denied) throw const ApiException(403, 'forbidden');
27
+ if (path.contains('/planner-series/')) {
28
+ return {
29
+ 'series': {
30
+ 'id': path.split('/').last,
31
+ 'owner_user_id': currentUserId,
32
+ 'title': 'Server recurring',
33
+ 'version': 2,
34
+ }
35
+ };
36
+ }
37
return {
38
'id': path.split('/').last,
39
'title': 'Server current',
@@ -130,6 +140,34 @@ void main() {
140
expect(await store.readDiscardedChanges(), isEmpty);
141
});
142
143
+ testWidgets(
144
+ 'rejected series can leave queue only after explicit recoverable choice',
145
+ (tester) async {
146
+ final api = _ConflictApi();
147
+ final store = OfflineStore.forApi(api);
148
+ const id = '00000000-0000-4000-8000-000000000100';
149
+ final draft = {
150
+ ...mutation(1, id, operation: 'create'),
151
+ 'entityType': 'planner_series'
152
+ };
153
+ await store.enqueue(draft);
154
+ await store.markQueued(draft['id'] as String, 'rejected');
155
+ await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
156
+ await tester.pumpAndSettle();
157
+ await tester.tap(find.text('بررسی و انتخاب'));
158
+ await tester.pumpAndSettle();
159
+ expect(find.text('نسخه سرور 2: Server recurring'), findsOneWidget);
160
+ expect(await store.readQueue(), hasLength(1));
161
+ await tester.tap(find.text('استفاده از نسخه سرور'));
162
+ await tester.pumpAndSettle();
163
+ expect(await store.readQueue(), isEmpty);
164
+ expect((await store.readDiscardedChanges()).single['payload'],
165
+ draft['payload']);
166
+ expect((await store.readList('planner_series')).single['title'],
167
+ 'Server recurring');
168
+ expect(await store.readPlanner(), isEmpty);
169
+ await tester.pumpWidget(const SizedBox());
170
+ });
171
testWidgets(
172
'conflict dialog preserves local changes until explicit use-server choice',
173
(tester) async {
apps/lifemate/test/weekly_planner_ui_test.dart
new
+209
@@ -0,0 +1,209 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:flutter/services.dart';
3
+import 'package:flutter_test/flutter_test.dart';
4
+import 'package:lifemate/phase3_ui.dart';
5
+import 'package:lifemate/plan_sync.dart';
6
+import 'package:lifemate/planner_series.dart';
7
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
8
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
9
+import 'app_test.dart' show FakeApi;
10
+
11
+class PlannerFixture extends FakeApi {
12
+ final writes = <Map<String, dynamic>>[];
13
+ final rows = <Map<String, dynamic>>[];
14
+ @override
15
+ Future<List<Map<String, dynamic>>> listFamilies() async => [];
16
+ @override
17
+ Future<List<Map<String, dynamic>>> listPlanItems(
18
+ {DateTime? from, DateTime? to, String? kind}) async =>
19
+ rows;
20
+ @override
21
+ Future<List<Map<String, dynamic>>> getToday(
22
+ {DateTime? from, DateTime? to}) async =>
23
+ rows
24
+ .where((row) =>
25
+ row['status'] != 'completed' && row['status'] != 'cancelled')
26
+ .toList();
27
+ @override
28
+ Future<Map<String, dynamic>> submitSyncMutations(
29
+ List<Map<String, dynamic>> changes) async {
30
+ writes.addAll(changes);
31
+ final m = changes.single;
32
+ final payload = m['payload'] as Map<String, dynamic>;
33
+ final old = rows.where((row) => row['id'] == m['entityId']).firstOrNull;
34
+ final row = <String, dynamic>{
35
+ ...?(old),
36
+ 'id': m['entityId'],
37
+ 'version': (m['expectedVersion'] as int) + 1,
38
+ 'title': payload['title'] ?? old?['title'],
39
+ 'status': payload['status'] ?? 'planned',
40
+ 'starts_at': payload['startsAt'] ?? old?['starts_at'],
41
+ 'ends_at': payload['endsAt'] ?? old?['ends_at']
42
+ };
43
+ rows.removeWhere((item) => item['id'] == row['id']);
44
+ rows.add(row);
45
+ return {
46
+ 'results': [
47
+ {
48
+ 'id': m['id'],
49
+ 'status': 'accepted',
50
+ 'item': row,
51
+ 'acceptedAt': DateTime.now().toUtc().toIso8601String()
52
+ }
53
+ ]
54
+ };
55
+ }
56
+}
57
+
58
+void main() {
59
+ TestWidgetsFlutterBinding.ensureInitialized();
60
+ setUp(() {
61
+ SharedPreferencesAsyncPlatform.instance =
62
+ InMemorySharedPreferencesAsync.withData({});
63
+ String? token;
64
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
65
+ .setMockMethodCallHandler(
66
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
67
+ if (call.method == 'getBlocked') return token != null;
68
+ if (call.method == 'beginWrite') return token = 'weekly-widget-write';
69
+ if (call.method == 'completeWrite' && call.arguments == token) {
70
+ token = null;
71
+ return true;
72
+ }
73
+ throw PlatformException(code: 'local_storage_restart_required');
74
+ });
75
+ });
76
+ Future<void> dialog(WidgetTester tester, PlannerFixture api,
77
+ {Map<String, dynamic>? item, DateTime? date}) async {
78
+ await tester.pumpWidget(MaterialApp(
79
+ home: Scaffold(
80
+ body: Builder(
81
+ builder: (context) => TextButton(
82
+ onPressed: () => showDialog<MutationOutcome>(
83
+ context: context,
84
+ builder: (_) => PlanItemDialog(
85
+ api: api, item: item, initialDate: date)),
86
+ child: const Text('open'))))));
87
+ await tester.tap(find.text('open'));
88
+ await tester.pumpAndSettle();
89
+ }
90
+
91
+ testWidgets('selected calendar day creates explicit start and end',
92
+ (tester) async {
93
+ final api = PlannerFixture();
94
+ final date = DateTime.now().add(const Duration(days: 3));
95
+ await dialog(tester, api, date: date);
96
+ await tester.enterText(
97
+ find.widgetWithText(TextField, 'عنوان'), 'برنامه ساختگی');
98
+ await tester.tap(find.text('ذخیره'));
99
+ await tester.pumpAndSettle();
100
+ final body = api.writes.single['payload'] as Map;
101
+ expect(plannerDate(DateTime.parse(body['startsAt']).toLocal()),
102
+ plannerDate(date));
103
+ expect(
104
+ DateTime.parse(body['endsAt'])
105
+ .difference(DateTime.parse(body['startsAt']))
106
+ .inMinutes,
107
+ 30);
108
+ expect(body['visibility'], 'private');
109
+ await tester.pumpWidget(const SizedBox());
110
+ });
111
+ testWidgets('home retains completed count after a fresh read',
112
+ (tester) async {
113
+ final api = PlannerFixture();
114
+ api.rows.add({
115
+ 'id': '40000000-0000-4000-8000-000000000001',
116
+ 'title': 'کار ساختگی',
117
+ 'kind': 'task',
118
+ 'status': 'planned',
119
+ 'version': 1,
120
+ 'starts_at': DateTime.now().toUtc().toIso8601String()
121
+ });
122
+ await tester.pumpWidget(MaterialApp(
123
+ home: Scaffold(
124
+ body:
125
+ TodayPage(api: api, home: true, displayName: 'کاربر ساختگی'))));
126
+ await tester.pumpAndSettle();
127
+ expect(find.text('0 از 1 کار امروز انجام شده'), findsOneWidget);
128
+ final tick =
129
+ find.byKey(const ValueKey('tick-40000000-0000-4000-8000-000000000001'));
130
+ await tester.ensureVisible(tick);
131
+ await tester.tap(tick);
132
+ await tester.pumpAndSettle();
133
+ expect(find.text('1 از 1 کار امروز انجام شده'), findsOneWidget);
134
+ await tester.pumpWidget(const SizedBox());
135
+ });
136
+ testWidgets('removing time range clears both endpoints, not just end',
137
+ (tester) async {
138
+ final api = PlannerFixture();
139
+ final start = DateTime.now().add(const Duration(hours: 1));
140
+ await dialog(tester, api, item: {
141
+ 'id': 'synthetic-plan',
142
+ 'title': 'برنامه ساختگی',
143
+ 'kind': 'task',
144
+ 'status': 'planned',
145
+ 'visibility': 'private',
146
+ 'version': 1,
147
+ 'starts_at': start.toUtc().toIso8601String(),
148
+ 'ends_at': start.add(const Duration(hours: 1)).toUtc().toIso8601String()
149
+ });
150
+ final range = find.byKey(const ValueKey('plan-time-range'));
151
+ await tester.ensureVisible(range);
152
+ await tester.tap(range);
153
+ await tester.pumpAndSettle();
154
+ await tester.tap(find.text('ذخیره'));
155
+ await tester.pumpAndSettle();
156
+ final body = api.writes.single['payload'] as Map;
157
+ expect(body.containsKey('startsAt'), true);
158
+ expect(body['startsAt'], isNull);
159
+ expect(body.containsKey('endsAt'), true);
160
+ expect(body['endsAt'], isNull);
161
+ await tester.pumpWidget(const SizedBox());
162
+ });
163
+ testWidgets('tick changes one occurrence only and week day switches',
164
+ (tester) async {
165
+ final api = PlannerFixture();
166
+ final now = DateTime.now();
167
+ final tomorrow = now.add(const Duration(days: 1));
168
+ api.rows.addAll([
169
+ {
170
+ 'id': 'occurrence-a',
171
+ 'series_id': 'synthetic-series',
172
+ 'title': 'امروز ساختگی',
173
+ 'status': 'planned',
174
+ 'version': 1,
175
+ 'starts_at': now.toUtc().toIso8601String()
176
+ },
177
+ {
178
+ 'id': 'occurrence-b',
179
+ 'series_id': 'synthetic-series',
180
+ 'title': 'فردا ساختگی',
181
+ 'status': 'planned',
182
+ 'version': 1,
183
+ 'starts_at': tomorrow.toUtc().toIso8601String()
184
+ },
185
+ ]);
186
+ await tester
187
+ .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
188
+ await tester.pumpAndSettle();
189
+ expect(find.text('امروز ساختگی'), findsOneWidget);
190
+ expect(find.text('فردا ساختگی'), findsNothing);
191
+ await tester.ensureVisible(find.byKey(const ValueKey('tick-occurrence-a')));
192
+ await tester.tap(find.byKey(const ValueKey('tick-occurrence-a')));
193
+ await tester.pumpAndSettle();
194
+ expect(api.rows.firstWhere((row) => row['id'] == 'occurrence-a')['status'],
195
+ 'completed');
196
+ expect(api.rows.firstWhere((row) => row['id'] == 'occurrence-b')['status'],
197
+ 'planned');
198
+ if (tomorrow.weekday == DateTime.saturday) {
199
+ await tester.tap(find.byTooltip('هفتهٔ بعد'));
200
+ await tester.pumpAndSettle();
201
+ }
202
+ final day = find.byKey(ValueKey('planner-day-${tomorrow.weekday}'));
203
+ await tester.ensureVisible(day);
204
+ await tester.tap(day);
205
+ await tester.pumpAndSettle();
206
+ expect(find.text('فردا ساختگی'), findsOneWidget);
207
+ await tester.pumpWidget(const SizedBox());
208
+ });
209
+}