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 317 lines 12.2 KB
Raw
1 import 'dart:convert';
2
3 import 'package:flutter/material.dart';
4
5 import 'api.dart';
6 import 'offline_store.dart';
7 import 'plan_sync.dart' show newMutationId;
8 import 'education_ui.dart' show learningError;
9
10 const feedbackCategories = {
11 'inaccurate': 'اشتباه آموزشی',
12 'edition_mismatch': 'تفاوت با کتاب درسی',
13 'broken_video': 'اشکال پخش ویدیو',
14 'unclear': 'توضیح نامفهوم',
15 'topic_request': 'پیشنهاد موضوع آموزشی',
16 };
17
18 /// Explicitly chosen feedback only; never extracts private conversations.
19 class LearningFeedbackSync {
20 LearningFeedbackSync(this.api, {OfflineStore? store})
21 : store = store ?? OfflineStore.forApi(api);
22 final HttpIdentityApi api;
23 final OfflineStore store;
24
25 Future<Map<String, dynamic>> submit(Map<String, dynamic> body) async {
26 final frozen =
27 Map<String, dynamic>.from(jsonDecode(jsonEncode(body)) as Map);
28 final mutationId = frozen['mutationId'] as String;
29 await store.enqueue({
30 'id': mutationId,
31 'entityId': mutationId,
32 'entityType': 'learning_feedback',
33 'operation': 'create',
34 'payload': frozen,
35 });
36 try {
37 return await _send(mutationId, frozen);
38 } catch (e) {
39 if (isOfflineFailure(e)) return {'queued': true};
40 rethrow;
41 }
42 }
43
44 Future<Map<String, dynamic>> _send(
45 String mutationId, Map<String, dynamic> body) async {
46 if (api.cacheNamespace != store.scope) {
47 throw const ApiException(401, 'cache_scope_closed');
48 }
49 await store.readQueue();
50 final result =
51 await api.requestJson('POST', '/v1/education/feedback', body: body);
52 if (api.cacheNamespace != store.scope) {
53 throw const ApiException(401, 'cache_scope_closed');
54 }
55 final acknowledgement = result['acknowledgement'];
56 final feedback = result['feedback'];
57 final uuid =
58 RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$');
59 bool date(dynamic value) =>
60 value is String && DateTime.tryParse(value) != null;
61 if (acknowledgement is! Map ||
62 feedback is! Map ||
63 acknowledgement['mutationId'] != mutationId ||
64 !['accepted', 'already_applied'].contains(acknowledgement['status']) ||
65 feedback['mutationId'] != mutationId ||
66 feedback['id'] is! String ||
67 !uuid.hasMatch(feedback['id'] as String) ||
68 feedback['unitId'] != body['unitId'] ||
69 feedback['category'] != body['category'] ||
70 feedback['version'] is! int ||
71 feedback['version'] < 1 ||
72 !['received', 'triaged', 'planned', 'released', 'declined']
73 .contains(feedback['status']) ||
74 (feedback['withdrawnAt'] == null
75 ? (feedback['summary'] != body['summary'] ||
76 feedback['shareWithContentTeam'] != true)
77 : (!date(feedback['withdrawnAt']) ||
78 feedback['summary'] != null ||
79 feedback['shareWithContentTeam'] != false)) ||
80 acknowledgement['feedbackId'] != feedback['id'] ||
81 !date(feedback['createdAt']) ||
82 !date(feedback['updatedAt'])) {
83 throw const ApiException(502, 'invalid_sync_acknowledgement');
84 }
85 // The chosen summary remains in the durable queue until acknowledged;
86 // do not retain an extra offline copy after server acceptance/withdrawal.
87 await store.acknowledge(mutationId,
88 acceptedAt: feedback['createdAt'] as String);
89 return {'queued': false, 'feedback': feedback};
90 }
91
92 Future<void> flush() async {
93 for (final pending in await store.readQueue()) {
94 if (pending['entityType'] != 'learning_feedback' ||
95 pending['queueStatus'] != 'queued') {
96 continue;
97 }
98 try {
99 await _send(pending['id'] as String,
100 Map<String, dynamic>.from(pending['payload'] as Map));
101 } catch (e) {
102 if (isOfflineFailure(e)) return;
103 rethrow;
104 }
105 }
106 }
107 }
108
109 class LearningFeedbackPage extends StatefulWidget {
110 const LearningFeedbackPage({super.key, required this.api, this.unitId});
111 final HttpIdentityApi api;
112 final String? unitId;
113 @override
114 State<LearningFeedbackPage> createState() => _LearningFeedbackPageState();
115 }
116
117 class _LearningFeedbackPageState extends State<LearningFeedbackPage> {
118 final summary = TextEditingController();
119 String category = 'topic_request';
120 bool consent = false, busy = false;
121 String? message;
122 Map<String, dynamic>? pendingBody;
123 List<Map<String, dynamic>> history = [];
124 int historyEpoch = 0;
125 late final LearningFeedbackSync sync;
126 @override
127 void initState() {
128 super.initState();
129 sync = LearningFeedbackSync(widget.api);
130 restoreDraft();
131 loadHistory();
132 }
133
134 Future<void> loadHistory() async {
135 final epoch = ++historyEpoch;
136 try {
137 final result =
138 await widget.api.requestJson('GET', '/v1/me/education-feedback');
139 if (result['feedback'] is! List) {
140 throw const ApiException(502, 'invalid_api_response');
141 }
142 if (mounted &&
143 epoch == historyEpoch &&
144 widget.api.cacheNamespace == sync.store.scope) {
145 setState(() => history = (result['feedback'] as List)
146 .map((row) => Map<String, dynamic>.from(row as Map))
147 .toList());
148 }
149 } catch (e) {
150 if (mounted && epoch == historyEpoch) {
151 setState(() {
152 if (e is ApiException &&
153 (e.statusCode == 401 || e.statusCode == 403)) {
154 history = [];
155 }
156 message = learningError(e);
157 });
158 }
159 }
160 }
161
162 Future<void> withdraw(String id) async {
163 if (busy) return;
164 ++historyEpoch; // Earlier reads must not resurrect a withdrawn summary.
165 setState(() => busy = true);
166 try {
167 await widget.api.requestJson(
168 'DELETE', '/v1/me/education-feedback/${Uri.encodeComponent(id)}');
169 if (mounted) {
170 setState(() => history.removeWhere((row) => row['id'] == id));
171 }
172 // Clear any acknowledged feedback cache from an earlier test build.
173 await sync.store.writeList('education_feedback', []);
174 if (mounted) await loadHistory();
175 } catch (e) {
176 if (mounted) setState(() => message = learningError(e));
177 } finally {
178 if (mounted) setState(() => busy = false);
179 }
180 }
181
182 Future<void> restoreDraft() async {
183 try {
184 final pending = (await sync.store.readQueue())
185 .where((m) =>
186 m['entityType'] == 'learning_feedback' &&
187 (m['payload'] as Map)['unitId'] == widget.unitId)
188 .firstOrNull;
189 if (pending != null && mounted) {
190 setState(() {
191 pendingBody = Map<String, dynamic>.from(pending['payload'] as Map);
192 summary.text = pendingBody!['summary'].toString();
193 category = pendingBody!['category'].toString();
194 consent = true;
195 message = 'بازخورد ارسال‌نشده روی این دستگاه نگه داشته شده است.';
196 });
197 }
198 } catch (e) {
199 if (mounted) setState(() => message = learningError(e));
200 }
201 }
202
203 @override
204 void dispose() {
205 summary.dispose();
206 super.dispose();
207 }
208
209 Future<void> send() async {
210 if (!consent || summary.text.trim().isEmpty) {
211 setState(() => message = 'خلاصه و رضایت ارسال را تکمیل کن.');
212 return;
213 }
214 setState(() => busy = true);
215 pendingBody ??= {
216 'mutationId': newMutationId(),
217 'unitId': widget.unitId,
218 'category': category,
219 'summary': summary.text.trim(),
220 'shareWithContentTeam': true
221 };
222 try {
223 final result = await sync.submit(pendingBody!);
224 if (mounted) {
225 setState(() {
226 message = result['queued'] == true
227 ? 'روی دستگاه ذخیره شد؛ هنوز تأیید سرور دریافت نشده است.'
228 : 'بازخورد در سرور ثبت شد؛ بررسی و انتشار نتیجه هنوز انجام نشده است.';
229 if (result['queued'] != true) {
230 pendingBody = null;
231 summary.clear();
232 consent = false;
233 }
234 });
235 if (result['queued'] != true && mounted) await loadHistory();
236 }
237 } catch (e) {
238 if (mounted) setState(() => message = learningError(e));
239 } finally {
240 if (mounted) setState(() => busy = false);
241 }
242 }
243
244 @override
245 Widget build(BuildContext context) => Scaffold(
246 appBar: AppBar(title: const Text('بازخورد و پیشنهاد آموزش')),
247 body: ListView(padding: const EdgeInsets.all(16), children: [
248 const Text(
249 'فقط ایراد محتوا یا نیاز آموزشی را بنویس. نام افراد، گفت‌وگوی خصوصی، اطلاعات سلامت یا شرح آزار را در بازخورد توسعه ننویس. این بخش مشاوره یا رسیدگی اضطراری نیست.'),
250 DropdownButtonFormField<String>(
251 initialValue: category,
252 items: feedbackCategories.entries
253 .map((entry) => DropdownMenuItem(
254 value: entry.key, child: Text(entry.value)))
255 .toList(),
256 onChanged: busy || pendingBody != null
257 ? null
258 : (value) => setState(() => category = value!)),
259 TextField(
260 controller: summary,
261 enabled: !busy && pendingBody == null,
262 maxLength: 1000,
263 maxLines: 5,
264 decoration:
265 const InputDecoration(labelText: 'خلاصه ایراد یا پیشنهاد')),
266 CheckboxListTile(
267 value: consent,
268 onChanged: busy || pendingBody != null
269 ? null
270 : (value) => setState(() => consent = value == true),
271 title: const Text(
272 'می‌خواهم فقط همین خلاصه برای بررسی محتوا در اختیار تیم توسعه قرار گیرد.')),
273 if (message != null) Text(message!),
274 FilledButton(
275 onPressed: busy ? null : send,
276 child: Text(pendingBody == null
277 ? 'ارسال بازخورد'
278 : 'تلاش دوباره با همان بازخورد')),
279 if (pendingBody != null)
280 TextButton(
281 onPressed: busy
282 ? null
283 : () async {
284 await sync.store.discardEntityChanges(
285 pendingBody!['mutationId'] as String,
286 cacheKey: 'education_feedback',
287 entityType: 'learning_feedback');
288 if (mounted) {
289 setState(() {
290 pendingBody = null;
291 consent = false;
292 message =
293 'تلاش بعدی ارسال متوقف شد و پیش‌نویس در سابقه بازیابی ماند. اگر پاسخ شبکه گم شده باشد، رکورد ممکن است در سرور ثبت شده باشد؛ فهرست ثبت‌شده را بررسی و رضایت را جدا پس بگیر.';
294 });
295 }
296 },
297 child: const Text('خارج‌کردن پیش‌نویس از صف ارسال')),
298 const Text(
299 'این فرم فقط داده انتخاب‌شده تو را ارسال می‌کند؛ گفت‌وگو، یادداشت و اطلاعات خصوصی حساب استخراج نمی‌شود.'),
300 const Divider(),
301 const Text('بازخوردهای ثبت‌شده من'),
302 ...history.map((row) => Card(
303 child: ListTile(
304 title: Text(row['withdrawnAt'] == null
305 ? row['summary']?.toString() ?? 'بازخورد'
306 : 'رضایت ارسال پس گرفته شد'),
307 subtitle: Text(row['withdrawnAt'] == null
308 ? 'وضعیت بررسی: ${row['status'] ?? 'دریافت‌شده'}'
309 : 'متن بازخورد حذف شده است.'),
310 trailing: row['withdrawnAt'] != null
311 ? null
312 : TextButton(
313 onPressed:
314 busy ? null : () => withdraw(row['id'].toString()),
315 child: const Text('پس‌گرفتن رضایت'))))),
316 ]));
317 }