LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 315 lines 11.9 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 _details(Map row, {bool server = false}) {
227 const labels = {
228 'title': 'عنوان',
229 'status': 'وضعیت',
230 'visibility': 'اشتراک',
231 'notes': 'یادداشت',
232 'dueAt': 'مهلت',
233 'startsAt': 'شروع',
234 'endsAt': 'پایان',
235 'plannedDurationSeconds': 'زمان برنامه‌ریزی‌شده (ثانیه)',
236 };
237 const columns = {
238 'dueAt': 'due_at',
239 'startsAt': 'starts_at',
240 'endsAt': 'ends_at',
241 'plannedDurationSeconds': 'planned_duration_seconds'
242 };
243 const values = {
244 'planned': 'برنامه‌ریزی‌شده',
245 'in_progress': 'در حال انجام',
246 'completed': 'انجام‌شده',
247 'cancelled': 'بایگانی‌شده',
248 'private': 'خصوصی',
249 'family': 'خانواده',
250 'parent_guardians': 'سرپرستان',
251 'selected_members': 'اعضای انتخابی'
252 };
253 return labels.entries
254 .where((entry) => row
255 .containsKey(server ? columns[entry.key] ?? entry.key : entry.key))
256 .map((entry) {
257 final value = row[server ? columns[entry.key] ?? entry.key : entry.key];
258 return '${entry.value}: ${value == null ? 'خالی' : values[value] ?? value}';
259 }).join('\n');
260 }
261
262 @override
263 Widget build(BuildContext context) => Scaffold(
264 appBar: AppBar(title: const Text('تغییرهای معلق')),
265 body: loading
266 ? const Center(child: CircularProgressIndicator())
267 : ListView(padding: const EdgeInsets.all(16), children: [
268 if (busy && !dialogOpen) const LinearProgressIndicator(),
269 if (error != null)
270 Text(uiErrorText(error!),
271 style: TextStyle(
272 color: Theme.of(context).colorScheme.error)),
273 FilledButton.icon(
274 onPressed: busy || !storeReady ? null : _retry,
275 icon: const Icon(Icons.sync),
276 label: const Text('تلاش دوباره برای همگام‌سازی')),
277 if (queue.isEmpty)
278 const Padding(
279 padding: EdgeInsets.all(16),
280 child: Text('تغییر معلقی باقی نمانده است.')),
281 for (final mutation in queue)
282 ListTile(
283 title: Text(hiddenEntities.contains(mutation['entityId'])
284 ? 'تغییر بدون دسترسی'
285 : (mutation['payload'] as Map)['title']?.toString() ??
286 (mutation['entityType'] == 'study_session'
287 ? 'ثبت مطالعه'
288 : 'تغییر کار')),
289 subtitle: Text(_status(mutation['queueStatus'])),
290 trailing: mutation['entityType'] == 'plan_item' &&
291 ['conflict', 'rejected']
292 .contains(mutation['queueStatus']) &&
293 !hiddenEntities.contains(mutation['entityId'])
294 ? TextButton(
295 onPressed: busy ? null : () => _resolve(mutation),
296 child: const Text('بررسی و انتخاب'))
297 : null,
298 ),
299 if (journal.isNotEmpty) ...[
300 const Divider(),
301 Text('پیش‌نویس‌های نگه‌داری‌شده',
302 style: Theme.of(context).textTheme.titleMedium),
303 const Text(
304 'این تغییرها ارسال نمی‌شوند. عنوان را برای بازیابی دستی در ویرایش کار نگه داشته‌ایم.'),
305 for (final entry in journal)
306 ListTile(
307 title: Text(
308 (entry['payload'] as Map)['title']?.toString() ??
309 entry['recoveryTitle']?.toString() ??
310 'تغییر وضعیت یا جزئیات'),
311 subtitle: const Text('پیش‌نویس محلی؛ تأیید سرور نیست')),
312 ],
313 ]),
314 );
315 }