LifeMate — Personal, Family & Learning Companion

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