LifeMate — Personal, Family & Learning Companion

feat/private-planner-series-api
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 398 lines 17.3 KB
Raw
1 import 'dart:async';
2
3 import 'package:flutter/material.dart';
4 import 'package:flutter/services.dart';
5
6 import 'api.dart';
7 import 'content_review_sync.dart';
8 import 'learning_feedback_ui.dart' show feedbackCategories;
9 import 'offline_store.dart';
10 import 'plan_sync.dart' show newMutationId;
11
12 String contentReviewError(Object error) {
13 if (isOfflineFailure(error)) {
14 return 'اتصال برقرار نیست؛ متن‌های صندوق پاک شدند. دریافت تازه یا تلاش دستی لازم است.';
15 }
16 if (error is ApiException) {
17 if (error.statusCode == 401 || error.statusCode == 403) {
18 return 'مجوز معتبر بررسی محتوا لازم است. عضویت خانواده این دسترسی را نمی‌دهد.';
19 }
20 if (error.statusCode == 404) {
21 return 'این بازخورد دیگر در دسترس نیست؛ ممکن است رضایت ارسال پس گرفته شده باشد.';
22 }
23 if (error.statusCode == 409) {
24 return 'نسخه یا رضایت منبع تغییر کرده است. صندوق را تازه کن؛ تغییر یا پیشنهاد قدیمی تأیید نشد.';
25 }
26 }
27 return 'پاسخ معتبر دریافت نشد؛ متن‌های قبلی نمایش داده نمی‌شوند.';
28 }
29
30 /// Online-only operations over voluntarily shared educational feedback. Parent
31 /// and family roles do not imply reviewer access; every server call checks it.
32 class ContentReviewPage extends StatefulWidget {
33 const ContentReviewPage({super.key, required this.api});
34 final HttpIdentityApi api;
35 @override
36 State<ContentReviewPage> createState() => _ContentReviewPageState();
37 }
38
39 class _ContentReviewPageState extends State<ContentReviewPage>
40 with WidgetsBindingObserver {
41 late final ContentReviewSync sync;
42 Timer? poll;
43 Set<String> permissions = {};
44 List<Map<String, dynamic>> rows = [], pending = [];
45 Set<String> selected = {};
46 Map<String, dynamic>? brief;
47 String? filter, cursor, nextCursor, message;
48 int epoch = 0, total = 0;
49 bool loading = false, mutating = false, active = true;
50 DateTime? refreshedAt;
51
52 bool get canReview => permissions.contains('feedback.review');
53 bool get canPrepare => permissions.contains('brief.prepare');
54 bool current(int request) =>
55 mounted &&
56 active &&
57 request == epoch &&
58 widget.api.cacheNamespace == sync.store.scope;
59
60 @override
61 void initState() {
62 super.initState();
63 sync = ContentReviewSync(widget.api);
64 WidgetsBinding.instance.addObserver(this);
65 refresh();
66 poll = Timer.periodic(const Duration(seconds: 30), (_) {
67 if (active && !mutating && !loading) refresh();
68 });
69 }
70
71 void clearContent() {
72 rows = [];
73 permissions = {};
74 selected = {};
75 brief = null;
76 refreshedAt = null;
77 total = 0;
78 nextCursor = null;
79 }
80
81 @override
82 void didChangeAppLifecycleState(AppLifecycleState state) {
83 active = state == AppLifecycleState.resumed;
84 ++epoch;
85 if (!mounted) return;
86 setState(() {
87 clearContent();
88 loading = false;
89 });
90 if (active && !mutating) refresh();
91 }
92
93 @override
94 void dispose() {
95 ++epoch;
96 poll?.cancel();
97 WidgetsBinding.instance.removeObserver(this);
98 super.dispose();
99 }
100
101 Future<void> refresh({bool firstPage = false}) async {
102 if (!mounted || !active || mutating) return;
103 final request = ++epoch;
104 if (firstPage) cursor = null;
105 setState(() {
106 clearContent();
107 loading = true;
108 message = null;
109 });
110 try {
111 final granted = await sync.capabilities();
112 if (!current(request)) return;
113 final durable = await sync.pending();
114 if (!current(request)) return;
115 if (!granted.contains('feedback.read')) {
116 setState(() {
117 pending = durable;
118 message = 'مجوز بررسی محتوا برای این حساب فعال نیست.';
119 loading = false;
120 });
121 return;
122 }
123 final result = await sync.inbox(status: filter, cursor: cursor);
124 if (!current(request)) return;
125 setState(() {
126 permissions = granted;
127 pending = durable;
128 rows = List<Map<String, dynamic>>.from(result['feedback'] as List);
129 nextCursor = result['nextCursor'] as String?;
130 total = result['total'] as int;
131 refreshedAt = DateTime.now();
132 loading = false;
133 });
134 } catch (error) {
135 if (!current(request)) return;
136 setState(() {
137 clearContent();
138 message = contentReviewError(error);
139 loading = false;
140 if (error is ApiException && error.statusCode == 404) cursor = null;
141 });
142 }
143 }
144
145 Future<void> action(Future<Map<String, dynamic>> Function() operation,
146 {bool showBrief = false}) async {
147 if (mutating || !active) return;
148 final request = ++epoch;
149 setState(() {
150 mutating = true;
151 clearContent();
152 message = null;
153 });
154 Map<String, dynamic>? prepared;
155 String? outcome;
156 try {
157 final result = await operation();
158 if (!current(request)) return;
159 prepared = result['brief'] as Map<String, dynamic>?;
160 outcome =
161 'تأیید سرور دریافت شد. این عملیات انتشار آموزش یا اجرای توسعه نیست.';
162 } catch (error) {
163 if (!current(request)) return;
164 outcome = contentReviewError(error);
165 } finally {
166 if (mounted) setState(() => mutating = false);
167 }
168 if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) {
169 return;
170 }
171 await refresh(firstPage: false);
172 if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) {
173 return;
174 }
175 // A failed refresh must not reintroduce a brief or hide revoked access.
176 setState(() {
177 if (showBrief && canPrepare && prepared != null) brief = prepared;
178 message ??= outcome;
179 });
180 }
181
182 Future<void> copyBrief() async {
183 final id = brief?['id'] as String?;
184 if (id == null || mutating || !active) return;
185 final request = ++epoch;
186 setState(() {
187 mutating = true;
188 brief = null;
189 message = 'اعتبار رضایت و نسخه منابع در سرور دوباره بررسی می‌شود.';
190 });
191 try {
192 final fresh = await sync.readBrief(id);
193 if (!current(request)) return;
194 final lines = <String>[
195 fresh['title'] as String,
196 'زمان تهیه: ${fresh['createdAt']}',
197 'تعداد منابع رضایت‌داده: ${fresh['sourceCount']}',
198 ...(fresh['categories'] as List).map(
199 (row) => '${feedbackCategories[row['category']]}: ${row['count']}'),
200 ...(fresh['units'] as List).map((row) =>
201 'پایه ${row['gradeLevel']}، ${row['bookTitle']} (${row['bookCode']})، ${row['title']}؛ نسخه ${row['editionYear'] ?? 'نامشخص'}، ${row['editionStatus'] == 'verified' ? 'منبع بررسی‌شده' : 'نسخه تأییدنشده'}'),
202 ...(fresh['tasks'] as List).cast<String>(),
203 fresh['notice'] as String,
204 ];
205 await Clipboard.setData(ClipboardData(text: lines.join('\n')));
206 if (!current(request)) return;
207 setState(() {
208 brief = fresh;
209 message =
210 'پیشنهاد ساختاری پس از بررسی تازه سرور کپی شد؛ متن بازخورد در آن نیست.';
211 });
212 } catch (error) {
213 if (current(request)) {
214 setState(() {
215 clearContent();
216 message = contentReviewError(error);
217 });
218 }
219 } finally {
220 if (mounted) setState(() => mutating = false);
221 }
222 }
223
224 @override
225 Widget build(BuildContext context) => Directionality(
226 textDirection: TextDirection.rtl,
227 child: Scaffold(
228 appBar: AppBar(title: const Text('بررسی محتوای آموزشی'), actions: [
229 IconButton(
230 key: const Key('content-refresh'),
231 tooltip: 'دریافت تازه از سرور',
232 onPressed: mutating ? null : () => refresh(),
233 icon: const Icon(Icons.refresh))
234 ]),
235 body: ListView(padding: const EdgeInsets.all(16), children: [
236 const Text(
237 'فقط خلاصه‌ای که کاربر با رضایت برای تیم محتوا فرستاده است نمایش داده می‌شود. این صندوق شامل گفت‌وگوها، یادداشت‌ها یا اطلاعات سلامت نیست.'),
238 const SizedBox(height: 8),
239 const Text(
240 'متن‌های صندوق فقط هنگام اتصال در حافظه‌اند. پیشنهاد توسعه به‌صورت دستی بازبینی می‌شود؛ هوش مصنوعی، پیام‌رسانی و انتشار خودکار اجرا نمی‌شوند.'),
241 if (loading || mutating) const LinearProgressIndicator(),
242 Text(refreshedAt == null
243 ? 'داده تازه تأییدشده در دسترس نیست.'
244 : 'آخرین دریافت: ${refreshedAt!.hour.toString().padLeft(2, '0')}:${refreshedAt!.minute.toString().padLeft(2, '0')}؛ تازه‌سازی هر ۳۰ ثانیه، مجموع $total بازخورد.'),
245 if (message != null)
246 Padding(
247 padding: const EdgeInsets.symmetric(vertical: 8),
248 child: Text(message!)),
249 DropdownButtonFormField<String>(
250 key: ValueKey('content-filter-${filter ?? 'all'}'),
251 initialValue: filter ?? 'all',
252 decoration: const InputDecoration(labelText: 'فیلتر وضعیت'),
253 items: [
254 const DropdownMenuItem(
255 value: 'all', child: Text('همه وضعیت‌ها')),
256 ...contentReviewStatuses.entries.map((entry) =>
257 DropdownMenuItem(
258 value: entry.key, child: Text(entry.value)))
259 ],
260 onChanged: mutating
261 ? null
262 : (value) {
263 filter = value == 'all' ? null : value;
264 refresh(firstPage: true);
265 }),
266 ...rows.map((row) => Card(
267 child: Padding(
268 padding: const EdgeInsets.all(12),
269 child: Column(
270 crossAxisAlignment: CrossAxisAlignment.start,
271 children: [
272 Text(row['summary'] as String),
273 const SizedBox(height: 6),
274 Text(
275 '${feedbackCategories[row['category']]} · ${contentReviewStatuses[row['status']]} · نسخه ${row['version']}'),
276 Text('زمان ثبت در سرور: ${row['createdAt']}'),
277 if (row['unitId'] == null)
278 const Text('پیشنهاد عمومی آموزش'),
279 if (canReview &&
280 contentReviewTransitions
281 .containsKey(row['status']))
282 DropdownButtonFormField<String>(
283 key: Key('review-status-${row['id']}'),
284 decoration: const InputDecoration(
285 labelText: 'تغییر مرحله بررسی'),
286 hint: const Text('انتخاب مرحله بعد'),
287 items: contentReviewTransitions[row['status']]!
288 .map((status) => DropdownMenuItem(
289 value: status,
290 child: Text(
291 contentReviewStatuses[status]!)))
292 .toList(),
293 onChanged: mutating
294 ? null
295 : (value) {
296 if (value == null) return;
297 final body = {
298 'mutationId': newMutationId(),
299 'expectedVersion': row['version'],
300 'status': value
301 };
302 action(() => sync.review(
303 row['id'] as String, body));
304 }),
305 if (canPrepare && row['status'] == 'planned')
306 CheckboxListTile(
307 contentPadding: EdgeInsets.zero,
308 title: const Text(
309 'انتخاب برای پیشنهاد ساختاری توسعه'),
310 value: selected.contains(row['id']),
311 onChanged: mutating
312 ? null
313 : (value) => setState(() {
314 if (value == true &&
315 selected.length < 20) {
316 selected.add(row['id'] as String);
317 }
318 if (value != true) {
319 selected.remove(row['id']);
320 }
321 })),
322 ])))),
323 if (!loading &&
324 permissions.contains('feedback.read') &&
325 rows.isEmpty)
326 const Text('بازخورد رضایت‌داده‌ای در این صفحه نیست.'),
327 if (nextCursor != null)
328 TextButton(
329 onPressed: mutating
330 ? null
331 : () {
332 cursor = nextCursor;
333 refresh();
334 },
335 child: const Text('صفحه بعد')),
336 if (cursor != null)
337 TextButton(
338 onPressed: mutating ? null : () => refresh(firstPage: true),
339 child: const Text('بازگشت به صفحه اول')),
340 if (canPrepare)
341 FilledButton(
342 onPressed: selected.isEmpty || mutating
343 ? null
344 : () {
345 final sources = rows
346 .where((row) => selected.contains(row['id']))
347 .map((row) => {
348 'id': row['id'],
349 'expectedVersion': row['version']
350 })
351 .toList();
352 final body = {
353 'mutationId': newMutationId(),
354 'feedback': sources
355 };
356 action(() => sync.prepareBrief(body),
357 showBrief: true);
358 },
359 child: const Text('تهیه پیشنهاد توسعه، بدون متن بازخورد')),
360 if (brief != null)
361 Card(
362 child: Padding(
363 padding: const EdgeInsets.all(12),
364 child: Column(
365 crossAxisAlignment: CrossAxisAlignment.start,
366 children: [
367 Text(brief!['title'] as String),
368 Text('تعداد منابع: ${brief!['sourceCount']}'),
369 Text(brief!['notice'] as String),
370 TextButton(
371 key: const Key('copy-content-brief'),
372 onPressed: mutating ? null : copyBrief,
373 child: const Text(
374 'بررسی دوباره منابع و کپی پیشنهاد')),
375 ]))),
376 if (pending.isNotEmpty) ...[
377 const Divider(),
378 Text(
379 '${pending.length} عملیات بدون دریافت تأیید سرور یا با تعارض روی این دستگاه مانده است. فقط شناسه‌ها و مرحله در صف‌اند؛ ارسال خودکار انجام نمی‌شود.'),
380 ...pending.map((row) => ListTile(
381 title: Text(row['entityType'] == 'content_review'
382 ? 'تغییر مرحله بررسی'
383 : 'تهیه پیشنهاد توسعه'),
384 subtitle: const Text(
385 'تلاش دستی با همان شناسه و نسخه؛ ممکن است عملیات قبلاً در سرور ثبت شده باشد.'),
386 trailing: TextButton(
387 onPressed: mutating ||
388 !permissions.contains('feedback.read') ||
389 !(row['entityType'] == 'content_review'
390 ? canReview
391 : canPrepare)
392 ? null
393 : () => action(() => sync.retry(row),
394 showBrief: row['entityType'] == 'content_brief'),
395 child: const Text('تلاش دوباره')))),
396 ],
397 ])));
398 }