LifeMate — Personal, Family & Learning Companion

feat/standalone-weekly-planner
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 373 lines 14.6 KB
Raw
1 import 'package:flutter/material.dart';
2
3 import 'api.dart';
4 import 'offline_store.dart';
5 import 'phase3_ui.dart' show uiErrorText;
6 import 'plan_sync.dart';
7 import 'study_coordinator.dart';
8 import 'learning_sync.dart';
9 import 'learning_feedback_ui.dart';
10 import 'learning_quiz_ui.dart';
11 import 'planner_series.dart';
12
13 class SyncChangesPage extends StatefulWidget {
14 const SyncChangesPage({super.key, required this.api});
15 final IdentityApi api;
16
17 @override
18 State<SyncChangesPage> createState() => _SyncChangesPageState();
19 }
20
21 class _SyncChangesPageState extends State<SyncChangesPage> {
22 late final OfflineStore store;
23 List<Map<String, dynamic>> queue = [], journal = [];
24 bool loading = true, busy = false, dialogOpen = false, storeReady = false;
25 Object? error;
26 final hiddenEntities = <String>{};
27
28 @override
29 void initState() {
30 super.initState();
31 try {
32 store = OfflineStore.forApi(widget.api);
33 storeReady = true;
34 _load();
35 } catch (failure) {
36 error = failure;
37 loading = false;
38 }
39 }
40
41 Future<void> _load() async {
42 try {
43 final pending = await store.readQueue();
44 final discarded = await store.readDiscardedChanges();
45 if (!mounted) return;
46 setState(() {
47 queue = pending;
48 journal = discarded;
49 loading = false;
50 });
51 } catch (failure) {
52 if (mounted) {
53 setState(() {
54 error = failure;
55 loading = false;
56 });
57 }
58 }
59 }
60
61 Future<void> _retry() async {
62 if (busy) return;
63 setState(() {
64 busy = true;
65 error = null;
66 });
67 try {
68 Object? failure;
69 try {
70 await PlanSync(widget.api, store: store).flush();
71 } catch (caught) {
72 failure = caught;
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) {
84 failure ??= caught;
85 }
86 try {
87 await LearningSync(api, store: store).flush();
88 } catch (caught) {
89 failure ??= caught;
90 }
91 try {
92 await LearningFeedbackSync(api, store: store).flush();
93 } catch (caught) {
94 failure ??= caught;
95 }
96 try {
97 await LearningQuizSync(api, store: store).flush();
98 } catch (caught) {
99 failure ??= caught;
100 }
101 }
102 if (failure != null) throw failure;
103 } catch (failure) {
104 if (mounted) setState(() => error = failure);
105 } finally {
106 await _load();
107 if (mounted) setState(() => busy = false);
108 }
109 }
110
111 Future<void> _resolve(Map<String, dynamic> mutation) async {
112 if (busy) return;
113 final api = widget.api;
114 if (api is! HttpIdentityApi) {
115 setState(
116 () => error = const ApiException(503, 'configured_api_required'));
117 return;
118 }
119 final id = mutation['entityId'] as String;
120 setState(() {
121 busy = true;
122 error = null;
123 });
124 try {
125 if (['learning_feedback', 'learning_attempt']
126 .contains(mutation['entityType'])) {
127 throw const ApiException(409, 'feedback_retry_or_edit_draft');
128 }
129 if (mutation['entityType'] == 'learning_progress') {
130 if (!mounted) return;
131 setState(() => dialogOpen = true);
132 final accepted = await showDialog<bool>(
133 context: context,
134 builder: (dialogContext) => AlertDialog(
135 title: const Text('تعارض پیشرفت درس'),
136 content: Text(
137 'تغییر محلی: ${_details(mutation['payload'] as Map)}\n'
138 'با استفاده از سرور، تغییر محلی در سابقه بازیابی نگه داشته می‌شود و پیشرفت تازه سرور نمایش داده خواهد شد.'),
139 actions: [
140 TextButton(
141 onPressed: () => Navigator.pop(dialogContext, false),
142 child: const Text('نگه‌داشتن تغییر محلی')),
143 FilledButton(
144 onPressed: () => Navigator.pop(dialogContext, true),
145 child: const Text('استفاده از نسخه سرور')),
146 ]));
147 if (accepted == true && mounted) {
148 await LearningSync(api, store: store).resolveUsingServer(id);
149 }
150 return;
151 }
152 Map<String, dynamic>? serverItem;
153 final isSeries = mutation['entityType'] == 'planner_series';
154 try {
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');
171 if (failure.statusCode != 404 || !isUnsent) rethrow;
172 }
173 if (serverItem != null &&
174 (serverItem['id'] != id ||
175 int.tryParse(serverItem['version'].toString()) == null)) {
176 throw const ApiException(502, 'invalid_api_response');
177 }
178 if (!mounted) return;
179 final payload = mutation['payload'] as Map;
180 final local = _details(payload);
181 setState(() => dialogOpen = true);
182 final accepted = await showDialog<bool>(
183 context: context,
184 builder: (dialogContext) => AlertDialog(
185 title: const Text('بررسی تعارض'),
186 content: SingleChildScrollView(
187 child: Column(
188 mainAxisSize: MainAxisSize.min,
189 crossAxisAlignment: CrossAxisAlignment.start,
190 children: [
191 Text('تغییر محلی: $local'),
192 const SizedBox(height: 12),
193 Text(serverItem == null
194 ? 'این کار هنوز در سرور موجود نیست.'
195 : 'نسخه سرور ${serverItem['version']}: ${serverItem['title'] ?? ''}'),
196 if (serverItem != null)
197 Text(_details(serverItem, server: true)),
198 const SizedBox(height: 12),
199 const Text(
200 'با این انتخاب، تمام تغییرهای معلق همین کار از صف خارج می‌شوند. متن تغییرها در پیش‌نویس‌های نگه‌داری‌شده می‌ماند تا بعداً دستی ویرایش کنی.'),
201 ])),
202 actions: [
203 TextButton(
204 onPressed: () => Navigator.pop(dialogContext, false),
205 child: const Text('نگه‌داشتن تغییر محلی')),
206 FilledButton(
207 onPressed: () => Navigator.pop(dialogContext, true),
208 child: Text(serverItem == null
209 ? 'خارج‌کردن از صف و نگه‌داشتن پیش‌نویس'
210 : 'استفاده از نسخه سرور')),
211 ],
212 ));
213 if (mounted) setState(() => dialogOpen = false);
214 if (accepted == true) {
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) {
222 setState(() {
223 error = failure;
224 if (failure is ApiException &&
225 (failure.statusCode == 403 || failure.statusCode == 401)) {
226 hiddenEntities.add(id);
227 }
228 });
229 }
230 } finally {
231 await _load();
232 if (mounted) {
233 setState(() {
234 busy = false;
235 dialogOpen = false;
236 });
237 }
238 }
239 }
240
241 String _status(dynamic value) => switch (value) {
242 'conflict' => 'تعارض؛ نیازمند انتخاب',
243 'rejected' => 'سرور نپذیرفت',
244 _ => 'در انتظار تأیید سرور',
245 };
246
247 String _entityTitle(Map<String, dynamic> mutation) =>
248 switch (mutation['entityType']) {
249 'planner_series' => 'برنامهٔ تکراری',
250 'study_session' => 'ثبت مطالعه',
251 'learning_progress' => 'پیشرفت درس',
252 'learning_attempt' => 'پاسخ آزمون',
253 'learning_feedback' => 'بازخورد آموزشی',
254 'learning_goal' => 'هدف یادگیری',
255 'family_operation' => 'تغییر خانواده',
256 'content_review' => 'بررسی بازخورد',
257 'content_brief' => 'درخواست برنامه توسعه محتوا',
258 'school_lifecycle_contexts' => 'فضای تحصیلی',
259 'school_lifecycle_years' => 'سال تحصیلی',
260 'school_lifecycle_terms' => 'نیم‌سال تحصیلی',
261 _ => 'تغییر کار',
262 };
263
264 String? _manualRetryPage(Map<String, dynamic> mutation) =>
265 switch (mutation['entityType']) {
266 'learning_goal' => 'اهداف یادگیری',
267 'family_operation' => 'مدیریت خانواده',
268 'content_review' || 'content_brief' => 'بررسی محتوای آموزشی',
269 'school_lifecycle_contexts' ||
270 'school_lifecycle_years' ||
271 'school_lifecycle_terms' =>
272 'مدیریت فضای تحصیلی',
273 _ => null,
274 };
275
276 String _details(Map row, {bool server = false}) {
277 const labels = {
278 'title': 'عنوان',
279 'status': 'وضعیت',
280 'visibility': 'اشتراک',
281 'notes': 'یادداشت',
282 'dueAt': 'مهلت',
283 'startsAt': 'شروع',
284 'endsAt': 'پایان',
285 'plannedDurationSeconds': 'زمان برنامه‌ریزی‌شده (ثانیه)',
286 };
287 const columns = {
288 'dueAt': 'due_at',
289 'startsAt': 'starts_at',
290 'endsAt': 'ends_at',
291 'plannedDurationSeconds': 'planned_duration_seconds'
292 };
293 const values = {
294 'planned': 'برنامه‌ریزی‌شده',
295 'in_progress': 'در حال انجام',
296 'completed': 'انجام‌شده',
297 'cancelled': 'بایگانی‌شده',
298 'private': 'خصوصی',
299 'family': 'خانواده',
300 'parent_guardians': 'سرپرستان',
301 'selected_members': 'اعضای انتخابی'
302 };
303 return labels.entries
304 .where((entry) => row
305 .containsKey(server ? columns[entry.key] ?? entry.key : entry.key))
306 .map((entry) {
307 final value = row[server ? columns[entry.key] ?? entry.key : entry.key];
308 return '${entry.value}: ${value == null ? 'خالی' : values[value] ?? value}';
309 }).join('\n');
310 }
311
312 @override
313 Widget build(BuildContext context) => Scaffold(
314 appBar: AppBar(title: const Text('تغییرهای معلق')),
315 body: loading
316 ? const Center(child: CircularProgressIndicator())
317 : ListView(padding: const EdgeInsets.all(16), children: [
318 if (busy && !dialogOpen) const LinearProgressIndicator(),
319 if (error != null)
320 Text(uiErrorText(error!),
321 style: TextStyle(
322 color: Theme.of(context).colorScheme.error)),
323 FilledButton.icon(
324 onPressed: busy || !storeReady ? null : _retry,
325 icon: const Icon(Icons.sync),
326 label: const Text('تلاش دوباره برای همگام‌سازی')),
327 if (queue.any((row) => _manualRetryPage(row) != null))
328 const Padding(
329 padding: EdgeInsets.symmetric(vertical: 12),
330 child: Text(
331 'تغییرهای خانواده، اهداف و مدیریت محتوا یا تحصیل از صفحه مربوط بررسی و دوباره ارسال می‌شوند. این دکمه آن‌ها را ارسال نمی‌کند.')),
332 if (queue.isEmpty)
333 const Padding(
334 padding: EdgeInsets.all(16),
335 child: Text('تغییر معلقی باقی نمانده است.')),
336 for (final mutation in queue)
337 ListTile(
338 title: Text(hiddenEntities.contains(mutation['entityId'])
339 ? 'تغییر بدون دسترسی'
340 : (mutation['payload'] as Map)['title']?.toString() ??
341 _entityTitle(mutation)),
342 subtitle: Text([
343 _status(mutation['queueStatus']),
344 if (_manualRetryPage(mutation) case final page?)
345 'بررسی و ارسال از «$page»',
346 ].join('\n')),
347 trailing: ['plan_item', 'planner_series']
348 .contains(mutation['entityType']) &&
349 ['conflict', 'rejected']
350 .contains(mutation['queueStatus']) &&
351 !hiddenEntities.contains(mutation['entityId'])
352 ? TextButton(
353 onPressed: busy ? null : () => _resolve(mutation),
354 child: const Text('بررسی و انتخاب'))
355 : null,
356 ),
357 if (journal.isNotEmpty) ...[
358 const Divider(),
359 Text('پیش‌نویس‌های نگه‌داری‌شده',
360 style: Theme.of(context).textTheme.titleMedium),
361 const Text(
362 'این تغییرها ارسال نمی‌شوند. اطلاعات آن‌ها برای بازیابی دستی در صفحه مربوط نگه داشته شده است.'),
363 for (final entry in journal)
364 ListTile(
365 title: Text(
366 (entry['payload'] as Map)['title']?.toString() ??
367 entry['recoveryTitle']?.toString() ??
368 'تغییر وضعیت یا جزئیات'),
369 subtitle: const Text('پیش‌نویس محلی؛ تأیید سرور نیست')),
370 ],
371 ]),
372 );
373 }