LifeMate — Personal, Family & Learning Companion

feat/weekly-planner-android
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 458 lines 18.6 KB
Raw
1 import 'dart:convert';
2
3 import 'package:flutter/material.dart';
4
5 import 'api.dart';
6 import 'phase3_ui.dart' show faKind, uiErrorText;
7 import 'plan_sync.dart' show newMutationId;
8 import 'planner_series.dart';
9 import 'sync_changes_ui.dart';
10
11 typedef CreatePlannerSeries = Future<PlannerSeriesOutcome>
12 Function(Map<String, dynamic> payload, {String? id});
13
14 /// Creates private occurrences. Editing one occurrence is handled separately by
15 /// PlanItemDialog; this form never changes family visibility or permissions.
16 class PlannerSeriesDialog extends StatefulWidget {
17 const PlannerSeriesDialog({
18 super.key,
19 required this.api,
20 this.initialDate,
21 this.onCreate,
22 this.clock = DateTime.now,
23 });
24
25 final HttpIdentityApi api;
26 final DateTime? initialDate;
27 final CreatePlannerSeries? onCreate;
28 final DateTime Function() clock;
29
30 @override
31 State<PlannerSeriesDialog> createState() => _PlannerSeriesDialogState();
32 }
33
34 class _TimeSlot {
35 const _TimeSlot({
36 this.start = const TimeOfDay(hour: 8, minute: 0),
37 this.end = const TimeOfDay(hour: 9, minute: 0),
38 });
39 final TimeOfDay start, end;
40
41 bool get valid => end.hour * 60 + end.minute > start.hour * 60 + start.minute;
42 Map<String, dynamic> get payload =>
43 {'start': _clock(start), 'end': _clock(end)};
44 }
45
46 String _clock(TimeOfDay time) =>
47 '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
48 String _calendarDate(DateTime date) =>
49 '${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
50
51 class _PlannerSeriesDialogState extends State<PlannerSeriesDialog> {
52 static const weekdays = <int, String>{
53 6: 'شنبه',
54 7: 'یکشنبه',
55 1: 'دوشنبه',
56 2: 'سه‌شنبه',
57 3: 'چهارشنبه',
58 4: 'پنجشنبه',
59 5: 'جمعه',
60 };
61 final title = TextEditingController();
62 final id = newMutationId();
63 final selected = <int>{};
64 final slots = <int, _TimeSlot>{};
65 _TimeSlot dailySlot = const _TimeSlot();
66 late DateTime startsOn, untilOn;
67 String kind = 'routine', frequency = 'weekly';
68 int intervalDays = 1, reminderMinutes = -1;
69 bool hasEnd = false, busy = false, terminal = false;
70 String? error;
71 Map<String, dynamic>? frozenPayload;
72
73 bool get editable => !busy && frozenPayload == null;
74
75 // The server accepts ±730 Tehran calendar days. A UTC reference and a one-day
76 // margin avoid offering an unsupported boundary near midnight or a time-zone
77 // change. This is a UI guard; the API remains authoritative.
78 DateTime get referenceDay {
79 final now = widget.clock().toUtc();
80 return DateTime(now.year, now.month, now.day);
81 }
82
83 DateTime get firstDate => referenceDay.subtract(const Duration(days: 729));
84 DateTime get lastDate => referenceDay.add(const Duration(days: 729));
85 bool supportedDate(DateTime value) =>
86 !value.isBefore(firstDate) && !value.isAfter(lastDate);
87
88 @override
89 void initState() {
90 super.initState();
91 final date = widget.initialDate ?? widget.clock();
92 startsOn = DateTime(date.year, date.month, date.day);
93 untilOn = startsOn.add(const Duration(days: 90));
94 selected.add(startsOn.weekday);
95 slots[startsOn.weekday] = const _TimeSlot();
96 }
97
98 @override
99 void dispose() {
100 title.dispose();
101 super.dispose();
102 }
103
104 Future<void> pickDate({required bool end}) async {
105 if (!editable) return;
106 final selectedDate = end ? untilOn : startsOn;
107 final first = firstDate, last = lastDate;
108 final initial = selectedDate.isBefore(first)
109 ? first
110 : selectedDate.isAfter(last)
111 ? last
112 : selectedDate;
113 final date = await showDatePicker(
114 context: context,
115 initialDate: initial,
116 firstDate: first,
117 lastDate: last,
118 );
119 if (date != null && mounted && editable) {
120 setState(() => end ? untilOn = date : startsOn = date);
121 }
122 }
123
124 Future<void> pickTime(int? weekday, {required bool end}) async {
125 if (!editable) return;
126 final slot = weekday == null ? dailySlot : slots[weekday]!;
127 final time = await showTimePicker(
128 context: context,
129 initialTime: end ? slot.end : slot.start,
130 initialEntryMode: TimePickerEntryMode.input,
131 builder: (context, child) => MediaQuery(
132 data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
133 child: child!,
134 ),
135 );
136 if (time == null || !mounted || !editable) return;
137 final changed = _TimeSlot(
138 start: end ? slot.start : time,
139 end: end ? time : slot.end,
140 );
141 setState(
142 () => weekday == null ? dailySlot = changed : slots[weekday] = changed);
143 }
144
145 Map<String, dynamic>? payload() {
146 if (title.text.trim().isEmpty) {
147 error = 'عنوان را وارد کن.';
148 return null;
149 }
150 if (!supportedDate(startsOn)) {
151 error = 'تاریخ شروع باید در بازهٔ مجاز دو ساله باشد.';
152 return null;
153 }
154 if (hasEnd && !supportedDate(untilOn)) {
155 error = 'تاریخ پایان باید در بازهٔ مجاز دو ساله باشد.';
156 return null;
157 }
158 if (hasEnd && untilOn.isBefore(startsOn)) {
159 error = 'تاریخ پایان نباید پیش از تاریخ شروع باشد.';
160 return null;
161 }
162 if (frequency == 'weekly' && selected.isEmpty) {
163 error = 'دست‌کم یک روز هفته را انتخاب کن.';
164 return null;
165 }
166 final activeSlots =
167 frequency == 'daily' ? [dailySlot] : selected.map((day) => slots[day]!);
168 if (activeSlots.any((slot) => !slot.valid)) {
169 error = 'پایان هر نوبت باید پس از شروع و در همان روز باشد.';
170 return null;
171 }
172 final sortedDays = selected.toList()..sort();
173 return <String, dynamic>{
174 'title': title.text.trim(),
175 'kind': kind,
176 'timezone': 'Asia/Tehran',
177 'startsOn': _calendarDate(startsOn),
178 if (hasEnd) 'untilOn': _calendarDate(untilOn),
179 'frequency': frequency,
180 'intervalDays': frequency == 'daily' ? intervalDays : 1,
181 'slots': frequency == 'daily'
182 ? [dailySlot.payload]
183 : [
184 for (final day in sortedDays)
185 {'weekday': day, ...slots[day]!.payload}
186 ],
187 'reminderMinutes': reminderMinutes < 0 ? <int>[] : [reminderMinutes],
188 };
189 }
190
191 Future<void> save() async {
192 if (busy || terminal) return;
193 final draft = frozenPayload ?? payload();
194 if (draft == null) {
195 setState(() {});
196 return;
197 }
198 // Freeze both identity and exact body before awaiting durable enqueue/HTTP.
199 // An unknown response can mean that the original request already committed.
200 frozenPayload ??= jsonDecode(jsonEncode(draft)) as Map<String, dynamic>;
201 setState(() {
202 busy = true;
203 error = null;
204 });
205 try {
206 final create = widget.onCreate ?? PlannerSeriesSync(widget.api).create;
207 final result = await create(
208 jsonDecode(jsonEncode(frozenPayload)) as Map<String, dynamic>,
209 id: id);
210 if (mounted) Navigator.of(context).pop(result);
211 } catch (failure) {
212 if (mounted) {
213 setState(() {
214 terminal = failure is ApiException &&
215 [400, 409, 422].contains(failure.statusCode);
216 error = uiErrorText(failure);
217 });
218 }
219 } finally {
220 if (mounted) setState(() => busy = false);
221 }
222 }
223
224 void openRecovery() {
225 final navigator = Navigator.of(context);
226 navigator.pop();
227 navigator.push(MaterialPageRoute<void>(
228 builder: (_) => SyncChangesPage(api: widget.api),
229 ));
230 }
231
232 Widget timeSlot(int? weekday) {
233 final slot = weekday == null ? dailySlot : slots[weekday]!;
234 final prefix = weekday == null ? 'daily' : '$weekday';
235 return Card(
236 child: Padding(
237 padding: const EdgeInsets.all(12),
238 child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
239 Text(weekday == null ? 'ساعت هر نوبت' : weekdays[weekday]!,
240 style:
241 const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
242 const SizedBox(height: 8),
243 Wrap(spacing: 8, runSpacing: 8, children: [
244 for (final end in [false, true])
245 OutlinedButton(
246 key: ValueKey('series-day-$prefix-${end ? 'end' : 'start'}'),
247 style:
248 OutlinedButton.styleFrom(minimumSize: const Size(100, 48)),
249 onPressed: editable ? () => pickTime(weekday, end: end) : null,
250 child: Text(
251 '${end ? 'پایان' : 'شروع'}: ${_clock(end ? slot.end : slot.start)}'),
252 ),
253 ]),
254 ]),
255 ),
256 );
257 }
258
259 @override
260 Widget build(BuildContext context) => PopScope(
261 canPop: !busy,
262 child: AlertDialog(
263 title: const Text('برنامهٔ تکرارشونده',
264 style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
265 content: SizedBox(
266 width: 440,
267 child: SingleChildScrollView(
268 child: DefaultTextStyle.merge(
269 style: const TextStyle(fontSize: 14, height: 1.6),
270 child: Column(
271 mainAxisSize: MainAxisSize.min,
272 crossAxisAlignment: CrossAxisAlignment.stretch,
273 children: [
274 const Text(
275 'این برنامه خصوصی است. هر نوبت تیک و ساعت مستقل دارد؛ تغییر یک نوبت، روزهای دیگر را عوض نمی‌کند.'),
276 const SizedBox(height: 12),
277 TextField(
278 key: const ValueKey('series-title'),
279 controller: title,
280 enabled: editable,
281 maxLength: 200,
282 style: const TextStyle(fontSize: 16),
283 decoration: const InputDecoration(labelText: 'عنوان'),
284 ),
285 DropdownButtonFormField<String>(
286 key: const ValueKey('series-kind'),
287 initialValue: kind,
288 decoration: const InputDecoration(labelText: 'نوع'),
289 items: [
290 for (final value in ['task', 'event', 'routine'])
291 DropdownMenuItem(
292 value: value, child: Text(faKind(value))),
293 ],
294 onChanged: editable
295 ? (value) => setState(() => kind = value ?? kind)
296 : null,
297 ),
298 const SizedBox(height: 12),
299 const Text('زمان‌ها به وقت تهران (Asia/Tehran) هستند.'),
300 const SizedBox(height: 8),
301 OutlinedButton.icon(
302 key: const ValueKey('series-start-date'),
303 style: OutlinedButton.styleFrom(
304 minimumSize: const Size(48, 48)),
305 onPressed: editable ? () => pickDate(end: false) : null,
306 icon: const Icon(Icons.calendar_today_outlined),
307 label: Text('شروع: ${_calendarDate(startsOn)}'),
308 ),
309 CheckboxListTile(
310 key: const ValueKey('series-has-end'),
311 value: hasEnd,
312 contentPadding: EdgeInsets.zero,
313 title: const Text('تاریخ پایان دارد'),
314 onChanged: editable
315 ? (value) => setState(() => hasEnd = value ?? false)
316 : null,
317 ),
318 if (hasEnd)
319 OutlinedButton.icon(
320 key: const ValueKey('series-end-date'),
321 style: OutlinedButton.styleFrom(
322 minimumSize: const Size(48, 48)),
323 onPressed: editable ? () => pickDate(end: true) : null,
324 icon: const Icon(Icons.event_outlined),
325 label: Text('پایان: ${_calendarDate(untilOn)}'),
326 ),
327 DropdownButtonFormField<String>(
328 key: const ValueKey('series-frequency'),
329 initialValue: frequency,
330 decoration: const InputDecoration(labelText: 'تکرار'),
331 items: const [
332 DropdownMenuItem(value: 'weekly', child: Text('هفتگی')),
333 DropdownMenuItem(value: 'daily', child: Text('روزانه')),
334 ],
335 onChanged: editable
336 ? (value) =>
337 setState(() => frequency = value ?? frequency)
338 : null,
339 ),
340 const SizedBox(height: 12),
341 if (frequency == 'daily') ...[
342 DropdownButtonFormField<int>(
343 key: const ValueKey('series-interval'),
344 initialValue: intervalDays,
345 decoration:
346 const InputDecoration(labelText: 'فاصلهٔ روزها'),
347 items: const [
348 DropdownMenuItem(value: 1, child: Text('هر روز')),
349 DropdownMenuItem(
350 value: 2, child: Text('یک روز در میان')),
351 ],
352 onChanged: editable
353 ? (value) =>
354 setState(() => intervalDays = value ?? 1)
355 : null,
356 ),
357 const SizedBox(height: 8),
358 timeSlot(null),
359 ] else ...[
360 const Text('روزهای برنامه را انتخاب کن:'),
361 const SizedBox(height: 8),
362 Wrap(spacing: 8, runSpacing: 8, children: [
363 for (final day in weekdays.keys)
364 ConstrainedBox(
365 constraints: const BoxConstraints(
366 minWidth: 48, minHeight: 48),
367 child: FilterChip(
368 key: ValueKey('series-weekday-$day'),
369 label: Text(weekdays[day]!),
370 selected: selected.contains(day),
371 materialTapTargetSize:
372 MaterialTapTargetSize.padded,
373 onSelected: editable
374 ? (value) => setState(() {
375 if (value) {
376 selected.add(day);
377 slots.putIfAbsent(
378 day, () => const _TimeSlot());
379 } else {
380 selected.remove(day);
381 }
382 })
383 : null,
384 ),
385 ),
386 ]),
387 const SizedBox(height: 8),
388 for (final day in weekdays.keys)
389 if (selected.contains(day)) timeSlot(day),
390 ],
391 const SizedBox(height: 12),
392 DropdownButtonFormField<int>(
393 key: const ValueKey('series-reminder'),
394 initialValue: reminderMinutes,
395 decoration:
396 const InputDecoration(labelText: 'یادآوری هر نوبت'),
397 isExpanded: true,
398 items: const [
399 DropdownMenuItem(
400 value: -1, child: Text('بدون یادآوری')),
401 DropdownMenuItem(value: 0, child: Text('هنگام شروع')),
402 DropdownMenuItem(
403 value: 5, child: Text('۵ دقیقه پیش از شروع')),
404 DropdownMenuItem(
405 value: 10, child: Text('۱۰ دقیقه پیش از شروع')),
406 DropdownMenuItem(
407 value: 15, child: Text('۱۵ دقیقه پیش از شروع')),
408 ],
409 onChanged: editable
410 ? (value) => setState(() => reminderMinutes = value!)
411 : null,
412 ),
413 const SizedBox(height: 8),
414 const Text(
415 'برای اعلان روی گوشی، اجازهٔ اعلان و تنظیمات یادآوری دستگاه هم باید فعال باشند. انتخاب ساعت، تضمین نمایش اعلان نیست.'),
416 if (frozenPayload != null) ...[
417 const SizedBox(height: 12),
418 const Text(
419 'درخواست با همان شناسه نگه داشته شد. تا روشن‌شدن نتیجه، جزئیات قابل تغییر نیست؛ شناسهٔ تازه نساز.'),
420 ],
421 if (error != null) ...[
422 const SizedBox(height: 12),
423 Text(error!,
424 style: TextStyle(
425 color: Theme.of(context).colorScheme.error)),
426 ],
427 if (terminal)
428 TextButton(
429 style: TextButton.styleFrom(
430 minimumSize: const Size(48, 48)),
431 onPressed: busy ? null : openRecovery,
432 child: const Text('بررسی تغییرات در انتظار'),
433 ),
434 ],
435 ),
436 ),
437 ),
438 ),
439 actions: [
440 TextButton(
441 style: TextButton.styleFrom(minimumSize: const Size(48, 48)),
442 onPressed: busy ? null : () => Navigator.of(context).pop(),
443 child: Text(frozenPayload == null ? 'انصراف' : 'بستن'),
444 ),
445 FilledButton(
446 key: const ValueKey('series-save'),
447 style: FilledButton.styleFrom(minimumSize: const Size(96, 48)),
448 onPressed: busy || terminal ? null : save,
449 child: Text(busy
450 ? 'در حال بررسی…'
451 : frozenPayload == null
452 ? 'ثبت برنامه'
453 : 'تلاش دوباره'),
454 ),
455 ],
456 ),
457 );
458 }