LifeMate — Personal, Family & Learning Companion
feat(client): connect LifeGuide profiles, planner and parent PWA to shared API
Codex committed
Oct 8, 2026 at 16:17 UTC
eb921c1bb46b36f8acb8bb7035f1c05d222d7bcf
65 files changed
+7820
-1191
.gitattributes
new
+2
@@ -0,0 +1,2 @@
1
+# Preserve the upstream license text verbatim, including its line-end spaces.
2
+apps/lifemate/assets/fonts/*.txt whitespace=-blank-at-eol
apps/lifemate/README.md
new
+3
@@ -0,0 +1,3 @@
1
+# LifeGuide Flutter client
2
+
3
+Android and Persian RTL iPhone/iPad PWA use the shared authenticated API. See the repository README and docs/operations/STAGE0.md. Runtime endpoint settings, scoped cache and pending mutations do not replace PostgreSQL server authority. Real-device acceptance and signed release are UNVERIFIED until recorded in PROJECT_STATE.md.
apps/lifemate/analysis_options.yaml
+5
@@ -1,3 +1,8 @@
1
+analyzer:
2
+ exclude:
3
+ - build/**
4
+ - android/**
5
+ - web/**
6
include: package:flutter_lints/flutter.yaml
7
linter:
8
rules:
apps/lifemate/android/app/build.gradle.kts
+46
-5
@@ -1,11 +1,45 @@
1
+import java.util.Base64
2
+import java.security.KeyStore
3
+import java.security.cert.X509Certificate
4
+import javax.naming.ldap.LdapName
5
+
6
plugins {
7
id("com.android.application")
8
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
9
id("dev.flutter.flutter-gradle-plugin")
10
}
11
12
+val releaseRequested = gradle.startParameter.taskNames.any { it.contains("release", ignoreCase = true) }
13
+val releaseEnvironment = listOf("LIFEGUIDE_KEYSTORE_PATH", "LIFEGUIDE_KEYSTORE_PASSWORD", "LIFEGUIDE_KEY_ALIAS", "LIFEGUIDE_KEY_PASSWORD")
14
+val signingValues = releaseEnvironment.associateWith { System.getenv(it) }
15
+if (releaseRequested) {
16
+ val missing = signingValues.filterValues { it.isNullOrBlank() }.keys
17
+ if (missing.isNotEmpty()) throw GradleException("Release signing requires environment variables: ${missing.joinToString()}")
18
+ val keyFile = file(signingValues.getValue("LIFEGUIDE_KEYSTORE_PATH")!!)
19
+ val releaseAlias = signingValues.getValue("LIFEGUIDE_KEY_ALIAS")!!
20
+ if (!keyFile.isFile || keyFile.name.equals("debug.keystore", ignoreCase = true) || releaseAlias.equals("androiddebugkey", ignoreCase = true)) {
21
+ throw GradleException("A real owner-supplied release keystore is required.")
22
+ }
23
+ val keyStore = try {
24
+ KeyStore.getInstance(keyFile, signingValues.getValue("LIFEGUIDE_KEYSTORE_PASSWORD")!!.toCharArray())
25
+ } catch (_: Exception) {
26
+ throw GradleException("The owner-supplied release keystore could not be opened.")
27
+ }
28
+ val certificate = keyStore.getCertificate(releaseAlias) as? X509Certificate
29
+ if (!keyStore.isKeyEntry(releaseAlias) || certificate == null) {
30
+ throw GradleException("The release signing alias must contain a private key and certificate.")
31
+ }
32
+ if (LdapName(certificate.subjectX500Principal.name).rdns.any { it.type.equals("CN", ignoreCase = true) && it.value.toString().equals("Android Debug", ignoreCase = true) }) {
33
+ throw GradleException("Android debug certificates are forbidden for release signing.")
34
+ }
35
+ val defines = providers.gradleProperty("dart-defines").orNull.orEmpty().split(',').filter { it.isNotBlank() }
36
+ if (defines.any { String(Base64.getDecoder().decode(it)).startsWith("LIFEGUIDE_DEBUG_CA_BASE64=") && String(Base64.getDecoder().decode(it)).substringAfter('=').isNotEmpty() }) {
37
+ throw GradleException("Development CA input is forbidden in release builds.")
38
+ }
39
+}
40
+
41
android {
8
- namespace = "com.example.lifemate"
42
+ namespace = "ir.lifeguide.app"
43
compileSdk = flutter.compileSdkVersion
44
ndkVersion = flutter.ndkVersion
45
@@ -16,7 +50,7 @@ android {
50
51
defaultConfig {
52
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
19
- applicationId = "com.example.lifemate"
53
+ applicationId = "ir.lifeguide.app"
54
// You can update the following values to match your application needs.
55
// For more information, see: https://flutter.dev/to/review-gradle-config.
56
minSdk = flutter.minSdkVersion
@@ -29,11 +63,18 @@ android {
63
versionName = flutter.versionName
64
}
65
66
+ signingConfigs {
67
+ create("release") {
68
+ signingValues["LIFEGUIDE_KEYSTORE_PATH"]?.let { storeFile = file(it) }
69
+ storePassword = signingValues["LIFEGUIDE_KEYSTORE_PASSWORD"]
70
+ keyAlias = signingValues["LIFEGUIDE_KEY_ALIAS"]
71
+ keyPassword = signingValues["LIFEGUIDE_KEY_PASSWORD"]
72
+ }
73
+ }
74
+
75
buildTypes {
76
release {
34
- // TODO: Add your own signing config for the release build.
35
- // Signing with the debug keys for now, so `flutter run --release` works.
36
- signingConfig = signingConfigs.getByName("debug")
77
+ signingConfig = signingConfigs.getByName("release")
78
}
79
}
80
}
apps/lifemate/android/app/src/main/AndroidManifest.xml
+4
-1
@@ -1,6 +1,9 @@
1
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET"/>
3
<application
3
- android:label="LifeMate"
4
+ android:label="لایفگاید"
5
+ android:allowBackup="false"
6
+ android:usesCleartextTraffic="false"
7
android:name="${applicationName}"
8
android:icon="@drawable/lifemate_logo">
9
<activity
apps/lifemate/android/app/src/main/kotlin/com/example/lifemate/MainActivity.kt
deleted
-5
@@ -1,5 +0,0 @@
1
-package com.example.lifemate
2
-
3
-import io.flutter.embedding.android.FlutterActivity
4
-
5
-class MainActivity : FlutterActivity()
apps/lifemate/android/app/src/main/kotlin/ir/lifeguide/app/LocalWriteGuard.kt
new
+26
@@ -0,0 +1,26 @@
1
+package ir.lifeguide.app
2
+
3
+import java.util.UUID
4
+
5
+/** Pending local write ownership lives for the whole Android process. */
6
+object LocalWriteGuard {
7
+ private var pendingToken: String? = null
8
+
9
+ @Synchronized
10
+ fun getBlocked(): Boolean = pendingToken != null
11
+
12
+ @Synchronized
13
+ fun beginWrite(): String? {
14
+ if (pendingToken != null) return null
15
+ val token = UUID.randomUUID().toString()
16
+ pendingToken = token
17
+ return token
18
+ }
19
+
20
+ @Synchronized
21
+ fun completeWrite(token: String): Boolean {
22
+ if (pendingToken == null || pendingToken != token) return false
23
+ pendingToken = null
24
+ return true
25
+ }
26
+}
apps/lifemate/android/app/src/main/kotlin/ir/lifeguide/app/MainActivity.kt
new
+34
@@ -0,0 +1,34 @@
1
+package ir.lifeguide.app
2
+
3
+import io.flutter.embedding.android.FlutterActivity
4
+import io.flutter.embedding.engine.FlutterEngine
5
+import io.flutter.plugin.common.MethodChannel
6
+
7
+class MainActivity : FlutterActivity() {
8
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
9
+ super.configureFlutterEngine(flutterEngine)
10
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/local_write_guard")
11
+ .setMethodCallHandler { call, result ->
12
+ when (call.method) {
13
+ "getBlocked" -> result.success(LocalWriteGuard.getBlocked())
14
+ "beginWrite" -> {
15
+ val token = LocalWriteGuard.beginWrite()
16
+ if (token == null) {
17
+ result.error("local_storage_restart_required", null, null)
18
+ } else {
19
+ result.success(token)
20
+ }
21
+ }
22
+ "completeWrite" -> {
23
+ val token = call.arguments as? String
24
+ if (token != null && LocalWriteGuard.completeWrite(token)) {
25
+ result.success(true)
26
+ } else {
27
+ result.error("local_storage_restart_required", null, null)
28
+ }
29
+ }
30
+ else -> result.notImplemented()
31
+ }
32
+ }
33
+ }
34
+}
apps/lifemate/assets/fonts/LICENSE-Noto-Emoji.txt
new
+93
@@ -0,0 +1,93 @@
1
+Copyright 2013 Google LLC
2
+
3
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+This license is copied below, and is also available with a FAQ at:
5
+https://scripts.sil.org/OFL
6
+
7
+
8
+-----------------------------------------------------------
9
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+-----------------------------------------------------------
11
+
12
+PREAMBLE
13
+The goals of the Open Font License (OFL) are to stimulate worldwide
14
+development of collaborative font projects, to support the font creation
15
+efforts of academic and linguistic communities, and to provide a free and
16
+open framework in which fonts may be shared and improved in partnership
17
+with others.
18
+
19
+The OFL allows the licensed fonts to be used, studied, modified and
20
+redistributed freely as long as they are not sold by themselves. The
21
+fonts, including any derivative works, can be bundled, embedded,
22
+redistributed and/or sold with any software provided that any reserved
23
+names are not used by derivative works. The fonts and derivatives,
24
+however, cannot be released under any other type of license. The
25
+requirement for fonts to remain under this license does not apply
26
+to any document created using the fonts or their derivatives.
27
+
28
+DEFINITIONS
29
+"Font Software" refers to the set of files released by the Copyright
30
+Holder(s) under this license and clearly marked as such. This may
31
+include source files, build scripts and documentation.
32
+
33
+"Reserved Font Name" refers to any names specified as such after the
34
+copyright statement(s).
35
+
36
+"Original Version" refers to the collection of Font Software components as
37
+distributed by the Copyright Holder(s).
38
+
39
+"Modified Version" refers to any derivative made by adding to, deleting,
40
+or substituting -- in part or in whole -- any of the components of the
41
+Original Version, by changing formats or by porting the Font Software to a
42
+new environment.
43
+
44
+"Author" refers to any designer, engineer, programmer, technical
45
+writer or other person who contributed to the Font Software.
46
+
47
+PERMISSION & CONDITIONS
48
+Permission is hereby granted, free of charge, to any person obtaining
49
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+redistribute, and sell modified and unmodified copies of the Font
51
+Software, subject to the following conditions:
52
+
53
+1) Neither the Font Software nor any of its individual components,
54
+in Original or Modified Versions, may be sold by itself.
55
+
56
+2) Original or Modified Versions of the Font Software may be bundled,
57
+redistributed and/or sold with any software, provided that each copy
58
+contains the above copyright notice and this license. These can be
59
+included either as stand-alone text files, human-readable headers or
60
+in the appropriate machine-readable metadata fields within text or
61
+binary files as long as those fields can be easily viewed by the user.
62
+
63
+3) No Modified Version of the Font Software may use the Reserved Font
64
+Name(s) unless explicit written permission is granted by the corresponding
65
+Copyright Holder. This restriction only applies to the primary font name as
66
+presented to the users.
67
+
68
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+Software shall not be used to promote, endorse or advertise any
70
+Modified Version, except to acknowledge the contribution(s) of the
71
+Copyright Holder(s) and the Author(s) or with their explicit written
72
+permission.
73
+
74
+5) The Font Software, modified or unmodified, in part or in whole,
75
+must be distributed entirely under this license, and must not be
76
+distributed under any other license. The requirement for fonts to
77
+remain under this license does not apply to any document created
78
+using the Font Software.
79
+
80
+TERMINATION
81
+This license becomes null and void if any of the above conditions are
82
+not met.
83
+
84
+DISCLAIMER
85
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+OTHER DEALINGS IN THE FONT SOFTWARE.
apps/lifemate/assets/fonts/LICENSE-Roboto.txt
new
+201
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
apps/lifemate/assets/fonts/LifeGuideEmoji.ttf
Binary files /dev/null and b/apps/lifemate/assets/fonts/LifeGuideEmoji.ttf differ
apps/lifemate/assets/fonts/LifeGuideLatin.ttf
Binary files /dev/null and b/apps/lifemate/assets/fonts/LifeGuideLatin.ttf differ
apps/lifemate/assets/fonts/LifeGuidePersian.ttf
Binary files /dev/null and b/apps/lifemate/assets/fonts/LifeGuidePersian.ttf differ
apps/lifemate/assets/fonts/OFL-Noto-Arabic.txt
new
+93
@@ -0,0 +1,93 @@
1
+Copyright 2022 The Noto Project Authors (https://github.com/notofonts/arabic)
2
+
3
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+This license is copied below, and is also available with a FAQ at:
5
+https://openfontlicense.org
6
+
7
+
8
+-----------------------------------------------------------
9
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+-----------------------------------------------------------
11
+
12
+PREAMBLE
13
+The goals of the Open Font License (OFL) are to stimulate worldwide
14
+development of collaborative font projects, to support the font creation
15
+efforts of academic and linguistic communities, and to provide a free and
16
+open framework in which fonts may be shared and improved in partnership
17
+with others.
18
+
19
+The OFL allows the licensed fonts to be used, studied, modified and
20
+redistributed freely as long as they are not sold by themselves. The
21
+fonts, including any derivative works, can be bundled, embedded,
22
+redistributed and/or sold with any software provided that any reserved
23
+names are not used by derivative works. The fonts and derivatives,
24
+however, cannot be released under any other type of license. The
25
+requirement for fonts to remain under this license does not apply
26
+to any document created using the fonts or their derivatives.
27
+
28
+DEFINITIONS
29
+"Font Software" refers to the set of files released by the Copyright
30
+Holder(s) under this license and clearly marked as such. This may
31
+include source files, build scripts and documentation.
32
+
33
+"Reserved Font Name" refers to any names specified as such after the
34
+copyright statement(s).
35
+
36
+"Original Version" refers to the collection of Font Software components as
37
+distributed by the Copyright Holder(s).
38
+
39
+"Modified Version" refers to any derivative made by adding to, deleting,
40
+or substituting -- in part or in whole -- any of the components of the
41
+Original Version, by changing formats or by porting the Font Software to a
42
+new environment.
43
+
44
+"Author" refers to any designer, engineer, programmer, technical
45
+writer or other person who contributed to the Font Software.
46
+
47
+PERMISSION & CONDITIONS
48
+Permission is hereby granted, free of charge, to any person obtaining
49
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+redistribute, and sell modified and unmodified copies of the Font
51
+Software, subject to the following conditions:
52
+
53
+1) Neither the Font Software nor any of its individual components,
54
+in Original or Modified Versions, may be sold by itself.
55
+
56
+2) Original or Modified Versions of the Font Software may be bundled,
57
+redistributed and/or sold with any software, provided that each copy
58
+contains the above copyright notice and this license. These can be
59
+included either as stand-alone text files, human-readable headers or
60
+in the appropriate machine-readable metadata fields within text or
61
+binary files as long as those fields can be easily viewed by the user.
62
+
63
+3) No Modified Version of the Font Software may use the Reserved Font
64
+Name(s) unless explicit written permission is granted by the corresponding
65
+Copyright Holder. This restriction only applies to the primary font name as
66
+presented to the users.
67
+
68
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+Software shall not be used to promote, endorse or advertise any
70
+Modified Version, except to acknowledge the contribution(s) of the
71
+Copyright Holder(s) and the Author(s) or with their explicit written
72
+permission.
73
+
74
+5) The Font Software, modified or unmodified, in part or in whole,
75
+must be distributed entirely under this license, and must not be
76
+distributed under any other license. The requirement for fonts to
77
+remain under this license does not apply to any document created
78
+using the Font Software.
79
+
80
+TERMINATION
81
+This license becomes null and void if any of the above conditions are
82
+not met.
83
+
84
+DISCLAIMER
85
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+OTHER DEALINGS IN THE FONT SOFTWARE.
apps/lifemate/lib/api.dart
+313
-32
@@ -1,6 +1,10 @@
1
+import 'dart:async';
2
import 'dart:convert';
3
4
import 'package:http/http.dart' as http;
5
+import 'runtime_config.dart';
6
+import 'runtime_http_client.dart';
7
+import 'session_store.dart';
8
9
abstract class IdentityApi {
10
String? get accessToken;
@@ -11,7 +15,7 @@ abstract class IdentityApi {
15
required String password,
16
});
17
14
- Future<void> verifyEmail(String token);
18
+ Future<void> verifyEmail(String token, {required String newPassword});
19
Future<void> login(String email, String password);
20
Future<void> forgotPassword(String email);
21
Future<void> resetPassword(String token, String newPassword);
@@ -21,6 +25,7 @@ abstract class IdentityApi {
25
String? displayName,
26
String? birthDate,
27
String? themePreference,
28
+ String? profileCategory,
29
});
30
Future<List<Map<String, dynamic>>> listFamilies();
31
Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId);
@@ -124,9 +129,10 @@ abstract class IdentityApi {
129
}
130
131
class ApiException implements Exception {
127
- const ApiException(this.statusCode, this.code);
132
+ const ApiException(this.statusCode, this.code, {this.details = const {}});
133
final int statusCode;
134
final String code;
135
+ final Map<String, dynamic> details;
136
137
@override
138
String toString() => 'ApiException($statusCode, $code)';
@@ -136,21 +142,163 @@ class HttpIdentityApi implements IdentityApi {
142
HttpIdentityApi({
143
String? baseUrl,
144
http.Client? client,
139
- }) : baseUrl = baseUrl ??
140
- const String.fromEnvironment(
141
- 'LIFEMATE_API_URL',
142
- defaultValue: 'http://localhost:8080',
143
- ),
144
- _client = client ?? http.Client();
145
+ SessionStore? sessionStore,
146
+ this.onSessionChanged,
147
+ this.onScopeDiscarded,
148
+ }) : baseUrl = normalizeApiUrl(
149
+ baseUrl ?? (throw ArgumentError('API configuration is required.'))),
150
+ _client = client ?? createRuntimeHttpClient(),
151
+ _sessionStore = sessionStore == null
152
+ ? createSessionStore()
153
+ : sessionStore is SerializedSessionStore
154
+ ? sessionStore
155
+ : SerializedSessionStore(sessionStore);
156
157
final String baseUrl;
158
final http.Client _client;
159
+ final SessionStore _sessionStore;
160
+ void Function()? onSessionChanged;
161
+ Future<void> Function(String)? onScopeDiscarded;
162
+ Future<void>? _refreshing;
163
+ int _sessionGeneration = 0;
164
+ String? currentUserId;
165
+ String get endpointIdentity => baseUrl;
166
+ String? get cacheNamespace => accessToken == null || currentUserId == null
167
+ ? null
168
+ : '$endpointIdentity|$currentUserId';
169
170
@override
171
String? accessToken;
172
String? _refreshToken;
173
153
- Uri _uri(String path) => Uri.parse('$baseUrl$path');
174
+ Uri _uri(String path) {
175
+ if (!path.startsWith('/') ||
176
+ path.startsWith('//') ||
177
+ path.contains('://')) {
178
+ throw ArgumentError('Requests must use a path on the configured API.');
179
+ }
180
+ return Uri.parse('$baseUrl$path');
181
+ }
182
+
183
+ Future<Map<String, dynamic>> requestJson(String method, String path,
184
+ {Map<String, dynamic>? body, bool auth = true}) =>
185
+ _json(method, path, body: body, auth: auth);
186
+
187
+ void close() {
188
+ _sessionGeneration++;
189
+ _client.close();
190
+ }
191
+
192
+ Future<void> _acceptTokens(Map<String, dynamic> result,
193
+ {int? generation}) async {
194
+ if (generation != null && generation != _sessionGeneration) {
195
+ throw const ApiException(401, 'session_expired');
196
+ }
197
+ final access = result['accessToken'];
198
+ final refresh = result['refreshToken'];
199
+ String? userId;
200
+ try {
201
+ final claims = jsonDecode(utf8.decode(base64Url.decode(
202
+ base64Url.normalize((access as String).split('.')[1])))) as Map;
203
+ userId = claims['sub'] as String?;
204
+ } catch (_) {
205
+ throw const ApiException(502, 'invalid_api_response');
206
+ }
207
+ if (refresh is! String ||
208
+ refresh.isEmpty ||
209
+ userId == null ||
210
+ userId.isEmpty) {
211
+ throw const ApiException(502, 'invalid_api_response');
212
+ }
213
+ if (currentUserId != null && currentUserId != userId) {
214
+ await _clearSession();
215
+ }
216
+ if (generation != null && generation != _sessionGeneration) {
217
+ throw const ApiException(401, 'session_expired');
218
+ }
219
+ await _sessionStore.write(jsonEncode({
220
+ 'endpoint': endpointIdentity,
221
+ 'refreshToken': refresh,
222
+ 'userId': userId
223
+ }));
224
+ if (generation != null && generation != _sessionGeneration) {
225
+ throw const ApiException(401, 'session_expired');
226
+ }
227
+ accessToken = access;
228
+ _refreshToken = refresh;
229
+ currentUserId = userId;
230
+ onSessionChanged?.call();
231
+ }
232
+
233
+ Future<bool> restoreSession() async {
234
+ final raw = await _sessionStore.read();
235
+ if (raw == null) return false;
236
+ late Map<String, dynamic> session;
237
+ try {
238
+ session = jsonDecode(raw) as Map<String, dynamic>;
239
+ } catch (_) {
240
+ await logout(revoke: false);
241
+ return false;
242
+ }
243
+ if (session['endpoint'] != endpointIdentity ||
244
+ session['refreshToken'] is! String ||
245
+ (session['refreshToken'] as String).isEmpty ||
246
+ session['userId'] is! String) {
247
+ if (session['endpoint'] is String && session['userId'] is String) {
248
+ await onScopeDiscarded
249
+ ?.call('${session['endpoint']}|${session['userId']}');
250
+ }
251
+ await logout(revoke: false);
252
+ return false;
253
+ }
254
+ _refreshToken = session['refreshToken'] as String;
255
+ currentUserId = session['userId'] as String;
256
+ try {
257
+ await _refresh();
258
+ return true;
259
+ } on ApiException catch (error) {
260
+ if (error.statusCode == 401 || error.statusCode == 403) return false;
261
+ rethrow;
262
+ }
263
+ }
264
+
265
+ Future<void> logout({bool revoke = true}) async {
266
+ final token = _refreshToken;
267
+ _sessionGeneration++;
268
+ await _clearSession();
269
+ if (revoke && token != null) {
270
+ try {
271
+ await _json('POST', '/v1/auth/logout',
272
+ body: {'refreshToken': token}, retry: false);
273
+ } catch (_) {/* Local credentials are cleared even when offline. */}
274
+ }
275
+ }
276
+
277
+ Future<void> _clearSession() async {
278
+ final scope =
279
+ currentUserId == null ? null : '$endpointIdentity|$currentUserId';
280
+ accessToken = null;
281
+ _refreshToken = null;
282
+ currentUserId = null;
283
+ onSessionChanged?.call();
284
+ Object? failure;
285
+ StackTrace? failureStack;
286
+ try {
287
+ await _sessionStore.clear();
288
+ } catch (error, stack) {
289
+ failure = error;
290
+ failureStack = stack;
291
+ }
292
+ try {
293
+ if (scope != null) await onScopeDiscarded?.call(scope);
294
+ } catch (error, stack) {
295
+ failure ??= error;
296
+ failureStack ??= stack;
297
+ }
298
+ if (failure != null) {
299
+ Error.throwWithStackTrace(failure, failureStack!);
300
+ }
301
+ }
302
303
Map<String, String> _headers({bool auth = false}) => {
304
'content-type': 'application/json',
@@ -164,12 +312,28 @@ class HttpIdentityApi implements IdentityApi {
312
bool auth = false,
313
bool retry = true,
314
}) async {
315
+ final requestGeneration = _sessionGeneration;
316
+ if (auth && accessToken == null) {
317
+ throw const ApiException(401, 'session_expired');
318
+ }
319
final request = http.Request(method, _uri(path))
320
..headers.addAll(_headers(auth: auth));
321
if (body != null) request.body = jsonEncode(body);
322
171
- final streamed = await _client.send(request);
172
- final response = await http.Response.fromStream(streamed);
323
+ late http.Response response;
324
+ try {
325
+ response = await (() async =>
326
+ http.Response.fromStream(await _client.send(request)))()
327
+ .timeout(const Duration(seconds: 20));
328
+ } on TimeoutException {
329
+ throw const ApiException(0, 'request_timeout');
330
+ } on http.ClientException {
331
+ throw const ApiException(0, 'network_unavailable');
332
+ }
333
+
334
+ if (auth && requestGeneration != _sessionGeneration) {
335
+ throw const ApiException(401, 'session_changed');
336
+ }
337
338
if (response.statusCode == 401 && auth && retry && _refreshToken != null) {
339
await _refresh();
@@ -177,32 +341,48 @@ class HttpIdentityApi implements IdentityApi {
341
}
342
343
if (response.statusCode < 200 || response.statusCode >= 300) {
344
+ if (response.statusCode == 401 && auth) await logout(revoke: false);
345
var code = 'request_failed';
346
+ var details = <String, dynamic>{};
347
if (response.body.isNotEmpty) {
348
try {
183
- code = (jsonDecode(response.body) as Map<String, dynamic>)['error']
184
- ?.toString() ??
185
- code;
349
+ details = jsonDecode(response.body) as Map<String, dynamic>;
350
+ code = details['error']?.toString() ?? code;
351
} catch (_) {}
352
}
188
- throw ApiException(response.statusCode, code);
353
+ throw ApiException(response.statusCode, code, details: details);
354
}
355
356
if (response.body.isEmpty) return <String, dynamic>{};
192
- return jsonDecode(response.body) as Map<String, dynamic>;
357
+ try {
358
+ return jsonDecode(response.body) as Map<String, dynamic>;
359
+ } catch (_) {
360
+ throw const ApiException(502, 'invalid_api_response');
361
+ }
362
}
363
195
- Future<void> _refresh() async {
364
+ Future<void> _refresh() =>
365
+ _refreshing ??= _performRefresh().whenComplete(() => _refreshing = null);
366
+
367
+ Future<void> _performRefresh() async {
368
final token = _refreshToken;
369
if (token == null) throw const ApiException(401, 'session_expired');
198
- final result = await _json(
199
- 'POST',
200
- '/v1/auth/refresh',
201
- body: {'refreshToken': token},
202
- retry: false,
203
- );
204
- accessToken = result['accessToken']?.toString();
205
- _refreshToken = result['refreshToken']?.toString();
370
+ final generation = _sessionGeneration;
371
+ try {
372
+ final result = await _json(
373
+ 'POST',
374
+ '/v1/auth/refresh',
375
+ body: {'refreshToken': token},
376
+ retry: false,
377
+ );
378
+ await _acceptTokens(result, generation: generation);
379
+ } on ApiException catch (error) {
380
+ if (generation == _sessionGeneration &&
381
+ (error.statusCode == 401 || error.statusCode == 403)) {
382
+ await logout(revoke: false);
383
+ }
384
+ rethrow;
385
+ }
386
}
387
388
@override
@@ -219,18 +399,100 @@ class HttpIdentityApi implements IdentityApi {
399
}
400
401
@override
222
- Future<void> verifyEmail(String token) async {
223
- await _json('POST', '/v1/auth/verify-email', body: {'token': token});
402
+ Future<void> verifyEmail(String token, {required String newPassword}) async {
403
+ await _json('POST', '/v1/auth/verify-email',
404
+ body: {'token': token, 'newPassword': newPassword});
405
}
406
407
@override
408
Future<void> login(String email, String password) async {
409
+ final generation = ++_sessionGeneration;
410
final result = await _json('POST', '/v1/auth/login', body: {
229
- 'email': email,
411
+ 'identifier': email,
412
+ 'password': password,
413
+ });
414
+ await _acceptTokens(result, generation: generation);
415
+ }
416
+
417
+ Future<Map<String, dynamic>> registerContact(
418
+ {required String displayName,
419
+ required String password,
420
+ String? email,
421
+ String? phone}) {
422
+ return _json('POST', '/v1/auth/register', body: {
423
+ 'displayName': displayName,
424
'password': password,
425
+ if (email != null) 'email': email,
426
+ if (phone != null) 'phone': phone
427
});
232
- accessToken = result['accessToken']?.toString();
233
- _refreshToken = result['refreshToken']?.toString();
428
+ }
429
+
430
+ Future<Map<String, dynamic>> authCapabilities() =>
431
+ _json('GET', '/v1/auth/capabilities');
432
+ Future<Map<String, dynamic>> resendVerification(String email) =>
433
+ _json('POST', '/v1/auth/resend-verification', body: {'email': email});
434
+ Future<Map<String, dynamic>> requestPhoneOtp(String phone,
435
+ {String purpose = 'login'}) =>
436
+ _json('POST', '/v1/auth/phone/request-otp',
437
+ body: {'phone': phone, 'purpose': purpose});
438
+ Future<void> verifyPhoneOtp(String challengeId, String code,
439
+ {String? newPassword}) async {
440
+ final generation = ++_sessionGeneration;
441
+ final result = await _json('POST', '/v1/auth/phone/verify-otp', body: {
442
+ 'challengeId': challengeId,
443
+ 'code': code,
444
+ if (newPassword != null) 'newPassword': newPassword
445
+ });
446
+ await _acceptTokens(result, generation: generation);
447
+ }
448
+
449
+ Future<Map<String, dynamic>> startStudySession(Map<String, dynamic> body) =>
450
+ requestJson('POST', '/v1/study/sessions', body: body);
451
+ Future<Map<String, dynamic>> recordStudySessionEvent(
452
+ String id, Map<String, dynamic> body) =>
453
+ requestJson(
454
+ 'POST', '/v1/study/sessions/${Uri.encodeComponent(id)}/events',
455
+ body: body);
456
+ Future<List<Map<String, dynamic>>> listStudySessions(
457
+ {String? planItemId}) async {
458
+ final suffix = planItemId == null
459
+ ? ''
460
+ : '?${Uri(queryParameters: {'planItemId': planItemId}).query}';
461
+ final result = await requestJson('GET', '/v1/study/sessions$suffix');
462
+ return (result['sessions'] as List)
463
+ .map((item) => Map<String, dynamic>.from(item as Map))
464
+ .toList();
465
+ }
466
+
467
+ Future<Map<String, dynamic>> getStudySession(String id) async =>
468
+ Map<String, dynamic>.from((await requestJson('GET',
469
+ '/v1/study/sessions/${Uri.encodeComponent(id)}'))['session'] as Map);
470
+ Future<Map<String, dynamic>> archiveStudySession(
471
+ String id, Map<String, dynamic> body) =>
472
+ requestJson('DELETE', '/v1/study/sessions/${Uri.encodeComponent(id)}',
473
+ body: body);
474
+ Future<Map<String, dynamic>> recordActivityState(
475
+ String id, Map<String, dynamic> body) =>
476
+ requestJson(
477
+ 'POST', '/v1/plan-items/${Uri.encodeComponent(id)}/activity-state',
478
+ body: body);
479
+ Future<Map<String, dynamic>> getActivityState(String id) => requestJson(
480
+ 'GET', '/v1/plan-items/${Uri.encodeComponent(id)}/activity-state');
481
+ Future<Map<String, dynamic>> updateStudySession(
482
+ String id, Map<String, dynamic> body) =>
483
+ requestJson('PATCH', '/v1/study/sessions/${Uri.encodeComponent(id)}',
484
+ body: body);
485
+ Future<Map<String, dynamic>> getLearningReport(
486
+ String familyId, String childId,
487
+ {DateTime? from, DateTime? to}) {
488
+ final params = <String, String>{
489
+ if (from != null) 'from': from.toUtc().toIso8601String(),
490
+ if (to != null) 'to': to.toUtc().toIso8601String()
491
+ };
492
+ final suffix =
493
+ params.isEmpty ? '' : '?${Uri(queryParameters: params).query}';
494
+ return requestJson('GET',
495
+ '/v1/families/${Uri.encodeComponent(familyId)}/children/${Uri.encodeComponent(childId)}/learning-report$suffix');
496
}
497
498
@override
@@ -266,11 +528,13 @@ class HttpIdentityApi implements IdentityApi {
528
String? displayName,
529
String? birthDate,
530
String? themePreference,
531
+ String? profileCategory,
532
}) =>
533
_json('PATCH', '/v1/profile', auth: true, body: {
534
if (displayName != null) 'displayName': displayName,
535
if (birthDate != null) 'birthDate': birthDate,
536
if (themePreference != null) 'themePreference': themePreference,
537
+ if (profileCategory != null) 'profileCategory': profileCategory,
538
});
539
540
@override
@@ -324,6 +588,22 @@ class HttpIdentityApi implements IdentityApi {
588
);
589
}
590
591
+ Future<Map<String, dynamic>> createFamilyInvitation({
592
+ required String familyId,
593
+ String? email,
594
+ String? phone,
595
+ required String role,
596
+ String? themePreference,
597
+ }) =>
598
+ requestJson(
599
+ 'POST', '/v1/families/${Uri.encodeComponent(familyId)}/invitations',
600
+ body: {
601
+ if (email != null) 'email': email,
602
+ if (phone != null) 'phone': phone,
603
+ 'role': role,
604
+ if (themePreference != null) 'themePreference': themePreference,
605
+ });
606
+
607
@override
608
Future<void> acceptInvitation(String token) async {
609
await _json(
@@ -350,6 +630,7 @@ class HttpIdentityApi implements IdentityApi {
630
},
631
);
632
}
633
+
634
@override
635
Future<List<Map<String, dynamic>>> getToday({
636
required DateTime from,
@@ -375,7 +656,8 @@ class HttpIdentityApi implements IdentityApi {
656
if (from != null) params['from'] = from.toUtc().toIso8601String();
657
if (to != null) params['to'] = to.toUtc().toIso8601String();
658
if (kind != null) params['kind'] = kind;
378
- final suffix = params.isEmpty ? '' : '?${Uri(queryParameters: params).query}';
659
+ final suffix =
660
+ params.isEmpty ? '' : '?${Uri(queryParameters: params).query}';
661
final result = await _json('GET', '/v1/plan-items$suffix', auth: true);
662
return (result['items'] as List<dynamic>? ?? const [])
663
.map((item) => Map<String, dynamic>.from(item as Map))
@@ -628,5 +910,4 @@ class HttpIdentityApi implements IdentityApi {
910
auth: true,
911
body: {'question': question},
912
);
631
-
913
}
apps/lifemate/lib/dashboard_ui.dart
new
+283
@@ -0,0 +1,283 @@
1
+import 'dart:async';
2
+import 'package:flutter/material.dart';
3
+import 'api.dart';
4
+import 'phase3_ui.dart';
5
+import 'offline_store.dart';
6
+
7
+class ParentFamilyDashboard extends StatefulWidget {
8
+ const ParentFamilyDashboard({super.key, required this.api});
9
+ final IdentityApi api;
10
+ @override
11
+ State<ParentFamilyDashboard> createState() => _ParentFamilyDashboardState();
12
+}
13
+
14
+class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
15
+ late Future<List<Map<String, dynamic>>> data;
16
+ @override
17
+ void initState() {
18
+ super.initState();
19
+ data = load();
20
+ }
21
+
22
+ Future<List<Map<String, dynamic>>> load() async {
23
+ final rows = <Map<String, dynamic>>[];
24
+ for (final f in await widget.api.listFamilies()) {
25
+ if (f['role'] != 'parent_guardian') continue;
26
+ for (final child
27
+ in await widget.api.listFamilyMembers(f['id'].toString())) {
28
+ if (child['role'] == 'teen_minor') {
29
+ rows.add({...child, 'familyId': f['id'], 'familyName': f['name']});
30
+ }
31
+ }
32
+ }
33
+ return rows;
34
+ }
35
+
36
+ void reload() {
37
+ setState(() {
38
+ data = load();
39
+ });
40
+ }
41
+
42
+ @override
43
+ Widget build(BuildContext context) =>
44
+ FutureBuilder<List<Map<String, dynamic>>>(
45
+ future: data,
46
+ builder: (context, s) {
47
+ if (s.hasError) return LoadError(error: s.error!, retry: reload);
48
+ if (!s.hasData) {
49
+ return const Center(child: CircularProgressIndicator());
50
+ }
51
+ return ListView(padding: const EdgeInsets.all(16), children: [
52
+ const Text(
53
+ 'فقط اطلاعاتی که سرور طبق رابطه سرپرستی و اشتراک هر تکلیف مجاز بداند نمایش داده میشود.'),
54
+ if (s.data!.isEmpty)
55
+ const EmptyCard(
56
+ icon: Icons.family_restroom,
57
+ title: 'فرزند متصل نمایش داده نشد',
58
+ subtitle:
59
+ 'عضویت خانواده و رابطه سرپرستی را در پروفایل بررسی کن.'),
60
+ ...s.data!.map((child) => Card(
61
+ child: ListTile(
62
+ title: Text(child['display_name']?.toString() ?? 'فرزند'),
63
+ subtitle: Text(child['familyName']?.toString() ?? ''),
64
+ trailing: const Icon(Icons.chevron_left),
65
+ onTap: () {
66
+ if (widget.api is HttpIdentityApi) {
67
+ Navigator.push(
68
+ context,
69
+ MaterialPageRoute(
70
+ builder: (_) => LearningReportPage(
71
+ api: widget.api as HttpIdentityApi,
72
+ familyId: child['familyId'].toString(),
73
+ childId: child['user_id'].toString(),
74
+ childName:
75
+ child['display_name']?.toString() ??
76
+ 'فرزند')));
77
+ }
78
+ }))),
79
+ TextButton(onPressed: reload, child: const Text('تازهسازی اعضا'))
80
+ ]);
81
+ });
82
+}
83
+
84
+class LearningReportPage extends StatefulWidget {
85
+ const LearningReportPage(
86
+ {super.key,
87
+ required this.api,
88
+ required this.familyId,
89
+ required this.childId,
90
+ required this.childName});
91
+ final HttpIdentityApi api;
92
+ final String familyId, childId, childName;
93
+ @override
94
+ State<LearningReportPage> createState() => _LearningReportPageState();
95
+}
96
+
97
+class _LearningReportPageState extends State<LearningReportPage>
98
+ with WidgetsBindingObserver {
99
+ Map<String, dynamic>? report;
100
+ bool busy = false;
101
+ String? error;
102
+ int days = 7;
103
+ Timer? poll;
104
+ @override
105
+ void initState() {
106
+ super.initState();
107
+ WidgetsBinding.instance.addObserver(this);
108
+ startPoll();
109
+ load();
110
+ }
111
+
112
+ void startPoll() {
113
+ poll?.cancel();
114
+ poll = Timer.periodic(const Duration(seconds: 15), (_) => load());
115
+ }
116
+
117
+ @override
118
+ void didChangeAppLifecycleState(AppLifecycleState s) {
119
+ if (s == AppLifecycleState.resumed) {
120
+ startPoll();
121
+ load();
122
+ } else {
123
+ poll?.cancel();
124
+ }
125
+ }
126
+
127
+ @override
128
+ void dispose() {
129
+ poll?.cancel();
130
+ WidgetsBinding.instance.removeObserver(this);
131
+ super.dispose();
132
+ }
133
+
134
+ Future<void> load() async {
135
+ if (busy) return;
136
+ setState(() => busy = true);
137
+ try {
138
+ final to = DateTime.now().toUtc();
139
+ final result = await widget.api.getLearningReport(
140
+ widget.familyId, widget.childId,
141
+ from: to.subtract(Duration(days: days)), to: to);
142
+ if (mounted) {
143
+ setState(() {
144
+ report = result;
145
+ error = null;
146
+ });
147
+ }
148
+ } catch (e) {
149
+ if (mounted) {
150
+ setState(() {
151
+ error = uiErrorText(e);
152
+ if (isOfflineFailure(e) ||
153
+ (e is ApiException &&
154
+ e.statusCode >= 400 &&
155
+ e.statusCode < 500)) {
156
+ report = null;
157
+ }
158
+ });
159
+ }
160
+ } finally {
161
+ if (mounted) setState(() => busy = false);
162
+ }
163
+ }
164
+
165
+ String minutes(dynamic seconds) =>
166
+ '${((seconds as num? ?? 0) / 60).round()} دقیقه';
167
+ @override
168
+ Widget build(BuildContext context) {
169
+ final r = report;
170
+ final m = r?['metrics'] as Map? ?? {};
171
+ final items = r?['items'] as List? ?? [];
172
+ final daily = r?['daily'] as List? ?? [];
173
+ final max = daily.fold<num>(
174
+ 1,
175
+ (v, row) => (row['recordedDurationSeconds'] as num? ?? 0) > v
176
+ ? row['recordedDurationSeconds'] as num
177
+ : v);
178
+ final tehranNow =
179
+ DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
180
+ final todayCount = items.where((raw) {
181
+ final i = raw as Map;
182
+ final at =
183
+ DateTime.tryParse((i['dueAt'] ?? i['startsAt'] ?? '').toString())
184
+ ?.toUtc()
185
+ .add(const Duration(hours: 3, minutes: 30));
186
+ return at != null &&
187
+ at.year == tehranNow.year &&
188
+ at.month == tehranNow.month &&
189
+ at.day == tehranNow.day;
190
+ }).length;
191
+ return Scaffold(
192
+ appBar: AppBar(title: Text('گزارش یادگیری · ${widget.childName}')),
193
+ body: ListView(padding: const EdgeInsets.all(16), children: [
194
+ const Text(
195
+ 'زمان ثبتشده، گزارش شخصی است و اثبات مطالعه نیست. تأیید سرپرست فقط در صورت ثبت صریح سرور نمایش داده میشود.'),
196
+ SegmentedButton<int>(
197
+ segments: const [
198
+ ButtonSegment(value: 7, label: Text('هفتگی')),
199
+ ButtonSegment(value: 30, label: Text('ماهانه'))
200
+ ],
201
+ selected: {
202
+ days
203
+ },
204
+ onSelectionChanged: busy
205
+ ? null
206
+ : (v) {
207
+ setState(() => days = v.first);
208
+ load();
209
+ }),
210
+ if (busy) const LinearProgressIndicator(),
211
+ if (error != null)
212
+ Card(
213
+ child: ListTile(
214
+ leading: const Icon(Icons.warning_amber),
215
+ title: Text(error!),
216
+ subtitle: Text(report == null
217
+ ? 'اطلاعات فرزند بدون تأیید مجوز فعلی نمایش داده نمیشود.'
218
+ : 'داده قبلی بهروز نیست؛ وضعیت زنده تأیید نشده است.'))),
219
+ if (r != null) ...[
220
+ Text(
221
+ 'دریافت سرور: ${shortDate(r['asOf'])} · آخرین ثبت: ${shortDate(r['lastSyncAt'])}'),
222
+ Wrap(spacing: 8, children: [
223
+ Chip(label: Text('$todayCount مورد امروز (تهران)')),
224
+ Chip(label: Text('${m['totalTasks'] ?? 0} تکلیف')),
225
+ Chip(label: Text('${m['completedTasks'] ?? 0} انجامشده')),
226
+ Chip(label: Text('${m['overdueTasks'] ?? 0} عقبافتاده')),
227
+ Chip(label: Text('${m['completionPercent'] ?? 0}٪ تکمیل'))
228
+ ]),
229
+ Text(
230
+ 'زمان برنامهریزیشده: ${minutes(m['plannedInRangeDurationSeconds'] ?? m['plannedDurationSeconds'])}'),
231
+ Text('زمان ثبتشده: ${minutes(m['recordedDurationSeconds'])}'),
232
+ Text('روند زمان ثبتشده',
233
+ style: Theme.of(context).textTheme.titleLarge),
234
+ ...daily.map((raw) {
235
+ final row = raw as Map;
236
+ return Padding(
237
+ padding: const EdgeInsets.symmetric(vertical: 4),
238
+ child: Row(children: [
239
+ SizedBox(width: 100, child: Text(row['date'].toString())),
240
+ Expanded(
241
+ child: LinearProgressIndicator(
242
+ value:
243
+ (row['recordedDurationSeconds'] as num? ?? 0) /
244
+ max)),
245
+ const SizedBox(width: 8),
246
+ Text(minutes(row['recordedDurationSeconds']))
247
+ ]));
248
+ }),
249
+ Text('درسها', style: Theme.of(context).textTheme.titleLarge),
250
+ ...(r['subjects'] as List? ?? []).map((raw) {
251
+ final row = raw as Map;
252
+ return ListTile(
253
+ title: Text(row['subjectName']?.toString() ?? 'بدون درس'),
254
+ subtitle: Text(
255
+ '${row['completedTasks']}/${row['totalTasks']} تکمیل · ${minutes(row['recordedDurationSeconds'])}'));
256
+ }),
257
+ Text('تکلیفها و امتحانها',
258
+ style: Theme.of(context).textTheme.titleLarge),
259
+ ...items.map((raw) {
260
+ final i = raw as Map;
261
+ final verified = i['activityState'] == 'verified' &&
262
+ i['activitySource'] == 'guardian_confirmation';
263
+ final state = verified
264
+ ? 'تأیید صریح سرپرست'
265
+ : switch (i['activityState']) {
266
+ 'started' => 'شروع ثبتشده',
267
+ 'paused' => 'مکث ثبتشده',
268
+ 'completed' => 'انجامشده به گزارش فرزند',
269
+ _ => 'برنامهریزیشده'
270
+ };
271
+ return Card(
272
+ child: ListTile(
273
+ title: Text(i['title']?.toString() ?? ''),
274
+ subtitle: Text(
275
+ '${faKind(i['kind']?.toString() ?? 'task')} · $state\nآخرین ثبت وضعیت: ${shortDate(i['activityAt'])}\nموعد: ${shortDate(i['dueAt'] ?? i['startsAt'])}\nبرنامه ${minutes(i['plannedDurationSeconds'])} · ثبت ${minutes(i['recordedDurationSeconds'])}${i['gradePoints'] == null ? '' : '\nنمره ${i['gradePoints']}/${i['gradeOutOf']}'}')));
276
+ }),
277
+ ],
278
+ TextButton(
279
+ onPressed: busy ? null : load,
280
+ child: const Text('تازهسازی گزارش')),
281
+ ]));
282
+ }
283
+}
apps/lifemate/lib/endpoint_settings.dart
new
+130
@@ -0,0 +1,130 @@
1
+import 'package:flutter/material.dart';
2
+import 'runtime_config.dart';
3
+
4
+class EndpointSettingsPage extends StatefulWidget {
5
+ const EndpointSettingsPage(
6
+ {super.key, required this.initialConfig, required this.onSaved});
7
+ final RuntimeConfig initialConfig;
8
+ final Future<void> Function(RuntimeConfig) onSaved;
9
+ @override
10
+ State<EndpointSettingsPage> createState() => _EndpointSettingsState();
11
+}
12
+
13
+class _EndpointSettingsState extends State<EndpointSettingsPage> {
14
+ late final TextEditingController primary =
15
+ TextEditingController(text: widget.initialConfig.apiBaseUrl);
16
+ late final TextEditingController fallback = TextEditingController(
17
+ text: widget.initialConfig.apiFallbackUrls.join('\n'));
18
+ bool busy = false;
19
+ String? error;
20
+ void selectFallback(String selected) {
21
+ final alternatives = <String>[
22
+ primary.text.trim(),
23
+ ...fallback.text.split('\n').map((line) => line.trim())
24
+ ].where((url) => url.isNotEmpty && url != selected).toSet();
25
+ setState(() {
26
+ primary.text = selected;
27
+ fallback.text = alternatives.join('\n');
28
+ error = null;
29
+ });
30
+ }
31
+
32
+ Future<void> save() async {
33
+ setState(() {
34
+ busy = true;
35
+ error = null;
36
+ });
37
+ try {
38
+ final config = RuntimeConfig(
39
+ apiBaseUrl: primary.text,
40
+ apiFallbackUrls: fallback.text
41
+ .split('\n')
42
+ .map((line) => line.trim())
43
+ .where((line) => line.isNotEmpty)
44
+ .toList());
45
+ if (!config.isConfigured) {
46
+ throw ArgumentError('Primary endpoint is required.');
47
+ }
48
+ await widget.onSaved(config);
49
+ } on ArgumentError {
50
+ if (mounted) {
51
+ setState(() => error =
52
+ 'نشانی HTTPS معتبر وارد کنید؛ بدون نام کاربری، رمز یا پارامتر اضافی.');
53
+ }
54
+ } catch (_) {
55
+ if (mounted) {
56
+ setState(() => error = 'تنظیمات ذخیره نشد. دوباره تلاش کنید.');
57
+ }
58
+ } finally {
59
+ if (mounted) setState(() => busy = false);
60
+ }
61
+ }
62
+
63
+ @override
64
+ void dispose() {
65
+ primary.dispose();
66
+ fallback.dispose();
67
+ super.dispose();
68
+ }
69
+
70
+ @override
71
+ Widget build(BuildContext context) => Scaffold(
72
+ appBar: AppBar(title: const Text('اتصال لایفگاید')),
73
+ body: SafeArea(
74
+ child: SingleChildScrollView(
75
+ padding: const EdgeInsets.all(20),
76
+ child: Center(
77
+ child: ConstrainedBox(
78
+ constraints: const BoxConstraints(maxWidth: 520),
79
+ child: Column(
80
+ crossAxisAlignment: CrossAxisAlignment.stretch,
81
+ children: [
82
+ const Text(
83
+ 'نشانی سرویس خانواده را وارد کنید. تغییر سرویس شما را از حساب قبلی خارج میکند.'),
84
+ const SizedBox(height: 16),
85
+ TextField(
86
+ controller: primary,
87
+ textDirection: TextDirection.ltr,
88
+ keyboardType: TextInputType.url,
89
+ autocorrect: false,
90
+ decoration: const InputDecoration(
91
+ labelText: 'نشانی اصلی',
92
+ hintText: 'https://…')),
93
+ const SizedBox(height: 16),
94
+ TextField(
95
+ controller: fallback,
96
+ textDirection: TextDirection.ltr,
97
+ maxLines: 4,
98
+ autocorrect: false,
99
+ decoration: const InputDecoration(
100
+ labelText: 'نشانیهای جایگزین (اختیاری)',
101
+ helperText:
102
+ 'هر نشانی در یک سطر؛ انتخاب سرویس جایگزین با تأیید شما انجام میشود.')),
103
+ for (final endpoint
104
+ in widget.initialConfig.apiFallbackUrls)
105
+ Padding(
106
+ padding: const EdgeInsets.only(top: 8),
107
+ child: OutlinedButton(
108
+ onPressed: busy
109
+ ? null
110
+ : () => selectFallback(endpoint),
111
+ child: Text(endpoint,
112
+ textDirection: TextDirection.ltr))),
113
+ if (error != null)
114
+ Padding(
115
+ padding:
116
+ const EdgeInsets.symmetric(vertical: 12),
117
+ child: Text(error!,
118
+ style: TextStyle(
119
+ color: Theme.of(context)
120
+ .colorScheme
121
+ .error))),
122
+ const SizedBox(height: 20),
123
+ FilledButton(
124
+ onPressed: busy ? null : save,
125
+ child: Text(
126
+ busy ? 'در حال ذخیره…' : 'ذخیره و ادامه')),
127
+ ])),
128
+ ))),
129
+ );
130
+}
apps/lifemate/lib/iran_hub.dart
+235
-7
@@ -1,9 +1,237 @@
1
-import 'dart:convert';
1
import 'package:flutter/material.dart';
3
-import 'package:http/http.dart' as http;
2
import 'api.dart';
5
-String iranStageLabel(int grade){if(grade<=3)return'دوره اول ابتدایی';if(grade<=6)return'دوره دوم ابتدایی';if(grade<=9)return'دوره اول متوسطه';return'دوره دوم متوسطه';}
6
-int iranLocalYear(int grade){if(grade<=3)return grade;if(grade<=6)return grade-3;if(grade<=9)return grade-6;return grade-9;}
7
-class IranianFamilyLearningHub extends StatefulWidget{const IranianFamilyLearningHub({super.key,required this.identity});final IdentityApi identity;@override State<IranianFamilyLearningHub> createState()=>_State();}
8
-class _State extends State<IranianFamilyLearningHub>{int grade=7;String persona='child';String sex='unspecified';String birthDate='';late Future<List<Map<String,dynamic>>> data;String get baseUrl=>const String.fromEnvironment('LIFEMATE_API_URL',defaultValue:'http://localhost:8080');Future<Map<String,dynamic>> request(String method,String path,{Map<String,dynamic>? body})async{final req=http.Request(method,Uri.parse('$baseUrl$path'))..headers.addAll({'content-type':'application/json','authorization':'Bearer ${widget.identity.accessToken??''}'});if(body!=null){req.body=jsonEncode(body);}final res=await http.Response.fromStream(await req.send());if(res.statusCode<200||res.statusCode>=300){throw Exception('request_failed_${res.statusCode}');}return res.body.isEmpty?<String,dynamic>{}:jsonDecode(res.body)as Map<String,dynamic>;}@override void initState(){super.initState();data=load();}Future<List<Map<String,dynamic>>>load()async=>[await request('GET','/v1/me/iran-profile'),await request('GET','/v1/education/catalog?grade=$grade&schoolYear=1405-1406'),await request('GET','/v1/calendar/iran?year=1405'),await request('GET','/v1/me/notification-preferences'),await request('GET','/v1/me/menstrual-cycles')];void reload()=>setState(()=>data=load());Future<void>saveProfile()async{await request('PATCH','/v1/me/iran-profile',body:{'householdPersona':persona,'sex':sex,'birthDate':birthDate.isEmpty?null:birthDate});if(persona=='child'){await request('PUT','/v1/me/education',body:{'nationalGrade':grade,'schoolYear':'1405-1406'});}reload();}Future<void>pref(String key,bool value)async{await request('PATCH','/v1/me/notification-preferences',body:{key:value});reload();}Future<void>addCycle()async{final d=DateTime.now();final date='${d.year}-${d.month.toString().padLeft(2,'0')}-${d.day.toString().padLeft(2,'0')}';await request('POST','/v1/me/menstrual-cycles',body:{'startsOn':date,'reminderEnabled':false});reload();}
9
-@override Widget build(BuildContext context)=>Scaffold(appBar:AppBar(title:const Text('خانواده و یادگیری ایران')),body:FutureBuilder<List<Map<String,dynamic>>>(future:data,builder:(context,s){if(!s.hasData){return const Center(child:CircularProgressIndicator());}final prefs=s.data![3];final catalog=s.data![1]['subjects']as List<dynamic>? ?? const [];final events=s.data![2]['events']as List<dynamic>? ?? const [];final cycles=s.data![4]['entries']as List<dynamic>? ?? const [];return ListView(padding:const EdgeInsets.all(16),children:[Text('پروفایل ایرانی',style:Theme.of(context).textTheme.titleLarge),DropdownButtonFormField<String>(initialValue:persona,decoration:const InputDecoration(labelText:'نقش'),items:const[DropdownMenuItem(value:'mother',child:Text('مادر')),DropdownMenuItem(value:'father',child:Text('پدر')),DropdownMenuItem(value:'child',child:Text('فرزند')),DropdownMenuItem(value:'adult',child:Text('بزرگسال'))],onChanged:(v)=>setState(()=>persona=v??persona)),DropdownButtonFormField<String>(initialValue:sex,decoration:const InputDecoration(labelText:'جنسیت'),items:const[DropdownMenuItem(value:'female',child:Text('دختر / زن')),DropdownMenuItem(value:'male',child:Text('پسر / مرد')),DropdownMenuItem(value:'unspecified',child:Text('ذکر نشود'))],onChanged:(v)=>setState(()=>sex=v??sex)),TextFormField(initialValue:birthDate,decoration:const InputDecoration(labelText:'تاریخ تولد (YYYY-MM-DD)'),onChanged:(v)=>birthDate=v),if(persona=='child')DropdownButtonFormField<int>(initialValue:grade,decoration:const InputDecoration(labelText:'پایه تحصیلی'),items:[for(var g=1;g<=12;g++)DropdownMenuItem(value:g,child:Text('پایه $g — ${iranStageLabel(g)}، سال ${iranLocalYear(g)}'))],onChanged:(v)=>setState(()=>grade=v??grade)),FilledButton(onPressed:saveProfile,child:const Text('ذخیره پروفایل')),const Divider(),Text('کتابها و درسها',style:Theme.of(context).textTheme.titleLarge),const Text('منبع رسمی کتابها لینک میشود؛ PDF بدون مجوز بازتوزیع بستهبندی نمیشود.'),...catalog.map((raw){final r=Map<String,dynamic>.from(raw as Map);return ListTile(leading:const Icon(Icons.menu_book_outlined),title:Text(r['name_fa']?.toString()??''),subtitle:Text(r['source_url']?.toString()??''));}),const Divider(),Text('تقویم جلالی ۱۴۰۵',style:Theme.of(context).textTheme.titleLarge),const Text('هفته از شنبه آغاز میشود؛ پنجشنبه و جمعه آخرهفته پیشفرضاند.'),...events.take(40).map((raw){final r=Map<String,dynamic>.from(raw as Map);return ListTile(leading:Icon(r['is_official_holiday']==true?Icons.event_busy_outlined:Icons.event_outlined),title:Text(r['title_fa']?.toString()??''),subtitle:Text('${r['jalali_month']}/${r['jalali_day']}'));}),const Divider(),Text('یادآوری و اعلان',style:Theme.of(context).textTheme.titleLarge),SwitchListTile(title:const Text('بنر داخل برنامه'),value:prefs['in_app_banner']==true,onChanged:(v)=>pref('inAppBanner',v)),SwitchListTile(title:const Text('یادآوری مدرسه'),value:prefs['school_reminders']!=false,onChanged:(v)=>pref('schoolReminders',v)),SwitchListTile(title:const Text('یادآوری تقویم'),value:prefs['calendar_reminders']!=false,onChanged:(v)=>pref('calendarReminders',v)),SwitchListTile(title:const Text('نمایش متن حساس روی اعلان'),value:prefs['sensitive_preview']==true,onChanged:(v)=>pref('sensitivePreview',v)),const Divider(),Text('چرخه شخصی',style:Theme.of(context).textTheme.titleLarge),const Text('فقط برای صاحب حساب؛ ابزار ثبت و یادآوری است و کاربرد تشخیصی ندارد.'),FilledButton.icon(onPressed:addCycle,icon:const Icon(Icons.add),label:const Text('ثبت شروع امروز')),Text('${cycles.length} ثبت خصوصی')]);}));}
3
+import 'phase3_ui.dart';
4
+
5
+String iranStageLabel(int grade) => grade <= 3
6
+ ? 'دوره اول ابتدایی'
7
+ : grade <= 6
8
+ ? 'دوره دوم ابتدایی'
9
+ : grade <= 9
10
+ ? 'دوره اول متوسطه'
11
+ : 'دوره دوم متوسطه';
12
+int iranLocalYear(int grade) => grade <= 3
13
+ ? grade
14
+ : grade <= 6
15
+ ? grade - 3
16
+ : grade <= 9
17
+ ? grade - 6
18
+ : grade - 9;
19
+
20
+class IranianFamilyLearningHub extends StatefulWidget {
21
+ const IranianFamilyLearningHub({super.key, required this.identity});
22
+ final IdentityApi identity;
23
+ @override
24
+ State<IranianFamilyLearningHub> createState() => _IranHubState();
25
+}
26
+
27
+class _IranHubState extends State<IranianFamilyLearningHub> {
28
+ int grade = 7;
29
+ String persona = 'child', sex = 'unspecified';
30
+ final birth = TextEditingController();
31
+ late Future<List<Map<String, dynamic>>> data;
32
+ bool busy = false, profileLoaded = false;
33
+ String? error;
34
+ Future<Map<String, dynamic>> request(String method, String path,
35
+ {Map<String, dynamic>? body}) {
36
+ final api = widget.identity;
37
+ if (api is! HttpIdentityApi) {
38
+ throw const ApiException(503, 'configured_api_required');
39
+ }
40
+ return api.requestJson(method, path, body: body);
41
+ }
42
+
43
+ @override
44
+ void initState() {
45
+ super.initState();
46
+ data = load();
47
+ }
48
+
49
+ @override
50
+ void dispose() {
51
+ birth.dispose();
52
+ super.dispose();
53
+ }
54
+
55
+ Future<List<Map<String, dynamic>>> load() async {
56
+ final profile = await request('GET', '/v1/me/iran-profile');
57
+ if (!profileLoaded) {
58
+ final row = profile['profile'] as Map? ?? profile;
59
+ persona = row['household_persona']?.toString() ??
60
+ row['householdPersona']?.toString() ??
61
+ persona;
62
+ sex = row['sex']?.toString() ?? sex;
63
+ birth.text =
64
+ row['birth_date']?.toString() ?? row['birthDate']?.toString() ?? '';
65
+ profileLoaded = true;
66
+ }
67
+ return [
68
+ profile,
69
+ await request(
70
+ 'GET', '/v1/education/catalog?grade=$grade&schoolYear=1405-1406'),
71
+ await request('GET', '/v1/calendar/iran?year=1405'),
72
+ await request('GET', '/v1/me/notification-preferences')
73
+ ];
74
+ }
75
+
76
+ void reload() {
77
+ setState(() {
78
+ data = load();
79
+ });
80
+ }
81
+
82
+ Future<void> mutate(Future<void> Function() action) async {
83
+ if (busy) return;
84
+ setState(() {
85
+ busy = true;
86
+ error = null;
87
+ });
88
+ try {
89
+ await action();
90
+ if (mounted) {
91
+ reload();
92
+ ScaffoldMessenger.of(context).showSnackBar(
93
+ const SnackBar(content: Text('سرور تغییر را تأیید کرد.')));
94
+ }
95
+ } catch (e) {
96
+ if (mounted) setState(() => error = uiErrorText(e));
97
+ } finally {
98
+ if (mounted) setState(() => busy = false);
99
+ }
100
+ }
101
+
102
+ Future<void> save() => mutate(() async {
103
+ await request('PATCH', '/v1/me/iran-profile', body: {
104
+ 'householdPersona': persona,
105
+ 'sex': sex,
106
+ 'birthDate': birth.text.trim().isEmpty ? null : birth.text.trim()
107
+ });
108
+ if (persona == 'child') {
109
+ await request('PUT', '/v1/me/education',
110
+ body: {'nationalGrade': grade, 'schoolYear': '1405-1406'});
111
+ }
112
+ });
113
+ Future<void> preference(String key, bool value) => mutate(() async {
114
+ await request('PATCH', '/v1/me/notification-preferences',
115
+ body: {key: value});
116
+ });
117
+ @override
118
+ Widget build(BuildContext context) => Scaffold(
119
+ appBar: AppBar(title: const Text('خانواده و یادگیری ایران')),
120
+ body: FutureBuilder<List<Map<String, dynamic>>>(
121
+ future: data,
122
+ builder: (context, s) {
123
+ if (s.hasError) return LoadError(error: s.error!, retry: reload);
124
+ if (!s.hasData) {
125
+ return const Center(child: CircularProgressIndicator());
126
+ }
127
+ final prefs = s.data![3]['preferences'] as Map? ?? s.data![3];
128
+ final catalog = s.data![1]['subjects'] as List? ?? [];
129
+ final events = s.data![2]['events'] as List? ?? [];
130
+ return ListView(padding: const EdgeInsets.all(16), children: [
131
+ if (busy) const LinearProgressIndicator(),
132
+ if (error != null)
133
+ Text(error!,
134
+ style:
135
+ TextStyle(color: Theme.of(context).colorScheme.error)),
136
+ Text('پروفایل ایرانی',
137
+ style: Theme.of(context).textTheme.titleLarge),
138
+ const Text(
139
+ 'این انتخاب، نقش خانواده یا دسترسی سرپرستی ایجاد نمیکند.'),
140
+ DropdownButtonFormField<String>(
141
+ initialValue: persona,
142
+ decoration: const InputDecoration(labelText: 'نقش نمایشی'),
143
+ items: const [
144
+ DropdownMenuItem(value: 'mother', child: Text('مادر')),
145
+ DropdownMenuItem(value: 'father', child: Text('پدر')),
146
+ DropdownMenuItem(value: 'child', child: Text('فرزند')),
147
+ DropdownMenuItem(value: 'adult', child: Text('بزرگسال'))
148
+ ],
149
+ onChanged: busy
150
+ ? null
151
+ : (v) => setState(() => persona = v ?? persona)),
152
+ DropdownButtonFormField<String>(
153
+ initialValue: sex,
154
+ decoration: const InputDecoration(labelText: 'جنسیت'),
155
+ items: const [
156
+ DropdownMenuItem(value: 'female', child: Text('دختر / زن')),
157
+ DropdownMenuItem(value: 'male', child: Text('پسر / مرد')),
158
+ DropdownMenuItem(
159
+ value: 'unspecified', child: Text('ذکر نشود'))
160
+ ],
161
+ onChanged:
162
+ busy ? null : (v) => setState(() => sex = v ?? sex)),
163
+ TextField(
164
+ controller: birth,
165
+ enabled: !busy,
166
+ decoration: const InputDecoration(
167
+ labelText: 'تاریخ تولد (YYYY-MM-DD)')),
168
+ if (persona == 'child')
169
+ DropdownButtonFormField<int>(
170
+ initialValue: grade,
171
+ decoration: const InputDecoration(labelText: 'پایه تحصیلی'),
172
+ items: [
173
+ for (var g = 1; g <= 12; g++)
174
+ DropdownMenuItem(
175
+ value: g,
176
+ child: Text(
177
+ 'پایه $g — ${iranStageLabel(g)}، سال ${iranLocalYear(g)}'))
178
+ ],
179
+ onChanged: busy
180
+ ? null
181
+ : (v) {
182
+ setState(() => grade = v ?? grade);
183
+ reload();
184
+ }),
185
+ FilledButton(
186
+ onPressed: busy ? null : save,
187
+ child: const Text('ذخیره پروفایل')),
188
+ const Divider(),
189
+ Text('کتابها و درسها',
190
+ style: Theme.of(context).textTheme.titleLarge),
191
+ const Text(
192
+ 'منبع رسمی کتابها لینک میشود؛ PDF بدون مجوز بازتوزیع بستهبندی نمیشود. اعتبار هر منبع نیازمند بررسی ناشر است.'),
193
+ ...catalog.map((raw) {
194
+ final r = raw as Map;
195
+ return ListTile(
196
+ leading: const Icon(Icons.menu_book_outlined),
197
+ title: Text(r['name_fa']?.toString() ?? ''),
198
+ subtitle:
199
+ SelectableText(r['source_url']?.toString() ?? ''));
200
+ }),
201
+ const Divider(),
202
+ Text('تقویم جلالی ۱۴۰۵',
203
+ style: Theme.of(context).textTheme.titleLarge),
204
+ const Text(
205
+ 'هفته از شنبه آغاز میشود؛ پنجشنبه و جمعه آخرهفته پیشفرضاند.'),
206
+ ...events.take(40).map((raw) {
207
+ final r = raw as Map;
208
+ return ListTile(
209
+ leading: Icon(r['is_official_holiday'] == true
210
+ ? Icons.event_busy_outlined
211
+ : Icons.event_outlined),
212
+ title: Text(r['title_fa']?.toString() ?? ''),
213
+ subtitle: Text('${r['jalali_month']}/${r['jalali_day']}'));
214
+ }),
215
+ const Divider(),
216
+ Text('یادآوری و اعلان',
217
+ style: Theme.of(context).textTheme.titleLarge),
218
+ for (final entry in {
219
+ 'inAppBanner': 'بنر داخل برنامه',
220
+ 'schoolReminders': 'یادآوری مدرسه',
221
+ 'calendarReminders': 'یادآوری تقویم'
222
+ }.entries)
223
+ SwitchListTile(
224
+ title: Text(entry.value),
225
+ value: prefs[switch (entry.key) {
226
+ 'inAppBanner' => 'in_app_banner',
227
+ 'schoolReminders' => 'school_reminders',
228
+ _ => 'calendar_reminders'
229
+ }] ==
230
+ true,
231
+ onChanged: busy ? null : (v) => preference(entry.key, v)),
232
+ const Divider(),
233
+ const Text(
234
+ 'قابلیتهای سلامت، چرخه شخصی و راهنمای هوشمند در این مرحله فعال نیستند.'),
235
+ ]);
236
+ }));
237
+}
apps/lifemate/lib/local_write_guard.dart
new
+35
@@ -0,0 +1,35 @@
1
+import 'package:flutter/foundation.dart';
2
+import 'package:flutter/services.dart';
3
+
4
+/// Android process lifetime protection, independent of a Flutter engine/isolate.
5
+/// An unconfirmed write can only be recovered by killing the Android process.
6
+final class LocalWriteGuard {
7
+ const LocalWriteGuard();
8
+
9
+ static const _channel = MethodChannel('lifeguide/local_write_guard');
10
+ bool get _native =>
11
+ !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
12
+
13
+ Future<bool> getBlocked() async {
14
+ if (!_native) return false;
15
+ // A missing/invalid native response must never grant access to cached data.
16
+ return await _channel.invokeMethod<bool>('getBlocked') ?? true;
17
+ }
18
+
19
+ Future<String?> beginWrite() async {
20
+ if (!_native) return null;
21
+ final token = await _channel.invokeMethod<String>('beginWrite');
22
+ if (token == null || token.isEmpty) {
23
+ throw StateError('Native local write guard did not grant ownership');
24
+ }
25
+ return token;
26
+ }
27
+
28
+ Future<void> completeWrite(String? token) async {
29
+ if (!_native) return;
30
+ if (token == null ||
31
+ await _channel.invokeMethod<bool>('completeWrite', token) != true) {
32
+ throw StateError('Native local write guard did not confirm completion');
33
+ }
34
+ }
35
+}
apps/lifemate/lib/main.dart
+998
-317
@@ -1,32 +1,113 @@
1
+import 'package:flutter/services.dart';
2
import 'package:flutter/material.dart';
3
import 'package:flutter_localizations/flutter_localizations.dart';
4
5
import 'api.dart';
6
import 'iran_hub.dart';
7
import 'phase3_ui.dart';
7
-import 'phase4_ui.dart';
8
+import 'runtime_controller.dart';
9
+import 'endpoint_settings.dart';
10
+import 'offline_store.dart';
11
+import 'notifications_ui.dart';
12
+import 'sync_changes_ui.dart';
13
+import 'package:flutter/foundation.dart';
14
9
-void main() => runApp(LifeMateApp());
15
+void main() {
16
+ WidgetsFlutterBinding.ensureInitialized();
17
+ runApp(const LifeMateApp());
18
+}
19
11
-class LifeMateApp extends StatelessWidget {
12
- LifeMateApp({super.key, IdentityApi? api}) : api = api ?? HttpIdentityApi();
13
- final IdentityApi api;
20
+class LifeMateApp extends StatefulWidget {
21
+ const LifeMateApp({super.key, this.api, this.runtime});
22
+ final IdentityApi? api;
23
+ final RuntimeController? runtime;
24
25
@override
16
- Widget build(BuildContext context) {
26
+ State<LifeMateApp> createState() => _LifeMateAppState();
27
+}
28
+
29
+class _LifeMateAppState extends State<LifeMateApp> {
30
+ RuntimeController? runtime;
31
+ bool invitationAccepted = false;
32
+ GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
33
+ Object? navigatorScope;
34
+
35
+ @override
36
+ void initState() {
37
+ super.initState();
38
+ if (widget.api == null) {
39
+ runtime = widget.runtime ??
40
+ RuntimeController(onScopeDiscarded: OfflineStore.clearNamespace);
41
+ if (!runtime!.initialized) runtime!.initialize();
42
+ }
43
+ }
44
+
45
+ @override
46
+ void dispose() {
47
+ if (widget.runtime == null) runtime?.dispose();
48
+ super.dispose();
49
+ }
50
+
51
+ Future<void> editEndpoints() async {
52
+ final controller = runtime!;
53
+ await navigatorKey.currentState!.push(MaterialPageRoute(
54
+ builder: (_) => EndpointSettingsPage(
55
+ initialConfig: controller.config,
56
+ onSaved: (next) async {
57
+ final api = controller.api;
58
+ if (api?.accessToken != null &&
59
+ !await confirmScopeDiscard(
60
+ navigatorKey.currentState!.overlay!.context, api!)) {
61
+ return;
62
+ }
63
+ await controller.updateEndpoints(next);
64
+ },
65
+ ),
66
+ ));
67
+ }
68
+
69
+ Widget entry(IdentityApi api, {bool managed = false}) {
70
final uri = Uri.base;
71
final token = uri.queryParameters['token'];
19
- Widget entry = SignInPage(
20
- api: api,
21
- invitationToken:
22
- token != null && uri.path.contains('accept-invitation') ? token : null,
23
- );
72
+ final invitation =
73
+ token != null && uri.path.contains('accept-invitation') ? token : null;
74
+ if (api.accessToken != null) {
75
+ if (managed && invitation != null && !invitationAccepted) {
76
+ return _InvitationGate(
77
+ api: api,
78
+ token: invitation,
79
+ onAccepted: () {
80
+ if (mounted) setState(() => invitationAccepted = true);
81
+ });
82
+ }
83
+ return HomeShell(
84
+ api: api,
85
+ onSignOut: managed ? runtime!.signOut : null,
86
+ onEndpointSettings: managed ? editEndpoints : null);
87
+ }
88
if (token != null && uri.path.contains('verify-email')) {
25
- entry = VerifyEmailPage(api: api, token: token);
26
- } else if (token != null && uri.path.contains('reset-password')) {
27
- entry = ResetPasswordPage(api: api, token: token);
89
+ return VerifyEmailPage(api: api, token: token);
90
+ }
91
+ if (token != null && uri.path.contains('reset-password')) {
92
+ return ResetPasswordPage(api: api, token: token);
93
+ }
94
+ return SignInPage(
95
+ api: api,
96
+ invitationToken: invitation,
97
+ runtimeManaged: managed,
98
+ onEndpointSettings: managed ? editEndpoints : null);
99
+ }
100
+
101
+ Widget app(Widget home, {Object? scope}) {
102
+ if (navigatorScope != scope) {
103
+ navigatorScope = scope;
104
+ navigatorKey = GlobalKey<NavigatorState>();
105
+ invitationAccepted = false;
106
}
107
return MaterialApp(
108
+ navigatorKey: navigatorKey,
109
+ key: ValueKey(scope),
110
+ title: 'LifeGuide · لایفگاید',
111
debugShowCheckedModeBanner: false,
112
locale: const Locale('fa'),
113
supportedLocales: const [Locale('fa'), Locale('en')],
@@ -36,26 +117,161 @@ class LifeMateApp extends StatelessWidget {
117
GlobalCupertinoLocalizations.delegate,
118
],
119
theme: ThemeData(
120
+ fontFamily: 'LifeGuidePersian',
121
+ fontFamilyFallback: const ['LifeGuideLatin', 'LifeGuideEmoji'],
122
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)),
123
scaffoldBackgroundColor: const Color(0xFFF8FAFD),
124
inputDecorationTheme:
125
const InputDecorationTheme(border: OutlineInputBorder()),
126
useMaterial3: true,
127
),
45
- home: Directionality(textDirection: TextDirection.rtl, child: entry),
128
+ home: Directionality(textDirection: TextDirection.rtl, child: home),
129
);
130
}
131
+
132
+ @override
133
+ Widget build(BuildContext context) {
134
+ if (widget.api != null) return app(entry(widget.api!));
135
+ return AnimatedBuilder(
136
+ animation: runtime!,
137
+ builder: (_, __) {
138
+ final controller = runtime!;
139
+ Widget home;
140
+ if (!controller.initialized) {
141
+ home = const Scaffold(
142
+ body: Center(child: CircularProgressIndicator()));
143
+ } else if (kIsWeb && controller.error != null) {
144
+ home = Scaffold(
145
+ appBar: AppBar(title: const Text('اتصال لایفگاید')),
146
+ body: LoadError(
147
+ error: controller.error!, retry: controller.initialize));
148
+ } else if (!controller.config.isConfigured ||
149
+ controller.api == null) {
150
+ home = EndpointSettingsPage(
151
+ initialConfig: controller.config,
152
+ onSaved: controller.updateEndpoints);
153
+ } else if (controller.error != null &&
154
+ controller.api!.accessToken == null) {
155
+ home = Scaffold(
156
+ appBar: AppBar(title: const Text('اتصال لایفگاید')),
157
+ body: Center(
158
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
159
+ const Text('بازیابی اتصال یا ورود انجام نشد.'),
160
+ Text(errorText(controller.error!)),
161
+ TextButton(
162
+ onPressed: controller.initialize,
163
+ child: const Text('تلاش دوباره')),
164
+ TextButton(
165
+ onPressed: editEndpoints, child: const Text('تنظیم اتصال')),
166
+ ])),
167
+ );
168
+ } else {
169
+ home = entry(controller.api!, managed: true);
170
+ }
171
+ return app(home,
172
+ scope:
173
+ '${controller.config.apiBaseUrl}|${controller.cacheNamespace ?? 'signed-out'}');
174
+ });
175
+ }
176
+}
177
+
178
+class _InvitationGate extends StatefulWidget {
179
+ const _InvitationGate(
180
+ {required this.api, required this.token, required this.onAccepted});
181
+ final IdentityApi api;
182
+ final String token;
183
+ final VoidCallback onAccepted;
184
+ @override
185
+ State<_InvitationGate> createState() => _InvitationGateState();
186
+}
187
+
188
+class _InvitationGateState extends State<_InvitationGate> {
189
+ bool busy = false;
190
+ String? error;
191
+ @override
192
+ void initState() {
193
+ super.initState();
194
+ accept();
195
+ }
196
+
197
+ Future<void> accept() async {
198
+ if (busy) return;
199
+ setState(() {
200
+ busy = true;
201
+ error = null;
202
+ });
203
+ try {
204
+ await widget.api.acceptInvitation(widget.token);
205
+ if (mounted) widget.onAccepted();
206
+ } catch (failure) {
207
+ if (mounted) setState(() => error = errorText(failure));
208
+ } finally {
209
+ if (mounted) setState(() => busy = false);
210
+ }
211
+ }
212
+
213
+ @override
214
+ Widget build(BuildContext context) => Scaffold(
215
+ appBar: AppBar(title: const Text('پذیرش دعوت خانواده')),
216
+ body: Center(
217
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
218
+ if (busy) const CircularProgressIndicator(),
219
+ if (error != null) Text(error!),
220
+ if (!busy)
221
+ TextButton(onPressed: accept, child: const Text('تلاش دوباره')),
222
+ ])),
223
+ );
224
+}
225
+
226
+Future<bool> confirmScopeDiscard(BuildContext context, IdentityApi api) async {
227
+ int? pending;
228
+ try {
229
+ pending = await OfflineStore.forApi(api).pendingCount();
230
+ } catch (_) {
231
+ /* Unknown storage must also require an explicit discard choice. */
232
+ }
233
+ if (pending == 0) return true;
234
+ if (!context.mounted) return false;
235
+ return await showDialog<bool>(
236
+ context: context,
237
+ builder: (c) => AlertDialog(
238
+ title: const Text('تغییرهای تأییدنشده'),
239
+ content: Text(pending == null
240
+ ? 'وضعیت تغییر معلق دستگاه قابل خواندن نیست. خروج یا تغییر سرویس، داده و تغییرهای تأییدنشده این حساب را از دستگاه حذف میکند.'
241
+ : '$pending تغییر معلق هنوز در سرور تأیید نشده است. خروج یا تغییر سرویس، این تغییرها و نسخه ذخیرهشده حساب را از دستگاه حذف میکند.'),
242
+ actions: [
243
+ TextButton(
244
+ onPressed: () => Navigator.pop(c, false),
245
+ child: const Text('انصراف')),
246
+ FilledButton(
247
+ onPressed: () => Navigator.pop(c, true),
248
+ child: const Text('ادامه و حذف تغییرها'))
249
+ ])) ??
250
+ false;
251
}
252
253
String errorText(Object error) {
254
if (error is ApiException) {
255
+ if (error.code.startsWith('local_') ||
256
+ error.statusCode == 0 ||
257
+ error.statusCode >= 500 ||
258
+ error.statusCode == 403 ||
259
+ [
260
+ 'sync_conflict',
261
+ 'version_conflict',
262
+ 'sms_unavailable',
263
+ 'invalid_or_expired_otp',
264
+ 'rate_limited'
265
+ ].contains(error.code)) {
266
+ return uiErrorText(error);
267
+ }
268
switch (error.code) {
269
case 'invalid_credentials':
270
return 'ایمیل یا رمز عبور صحیح نیست.';
271
case 'email_not_verified':
272
return 'ابتدا ایمیل حساب را تأیید کن.';
273
case 'account_exists':
58
- return 'برای این ایمیل قبلاً حساب ساخته شده است.';
274
+ return 'عملیات انجام نشد. دوباره تلاش کن.';
275
case 'invalid_password':
276
return 'رمز عبور باید حداقل ۱۰ کاراکتر باشد.';
277
case 'invalid_current_password':
@@ -70,9 +286,16 @@ String errorText(Object error) {
286
}
287
288
class SignInPage extends StatefulWidget {
73
- const SignInPage({super.key, required this.api, this.invitationToken});
289
+ const SignInPage(
290
+ {super.key,
291
+ required this.api,
292
+ this.invitationToken,
293
+ this.runtimeManaged = false,
294
+ this.onEndpointSettings});
295
final IdentityApi api;
296
final String? invitationToken;
297
+ final bool runtimeManaged;
298
+ final Future<void> Function()? onEndpointSettings;
299
@override
300
State<SignInPage> createState() => _SignInPageState();
301
}
@@ -90,10 +313,10 @@ class _SignInPageState extends State<SignInPage> {
313
});
314
try {
315
await widget.api.login(email.text, password.text);
93
- if (widget.invitationToken != null) {
316
+ if (!widget.runtimeManaged && widget.invitationToken != null) {
317
await widget.api.acceptInvitation(widget.invitationToken!);
318
}
96
- if (!mounted) return;
319
+ if (!mounted || widget.runtimeManaged) return;
320
Navigator.of(context).pushReplacement(
321
MaterialPageRoute(builder: (_) => HomeShell(api: widget.api)),
322
);
@@ -116,11 +339,11 @@ class _SignInPageState extends State<SignInPage> {
339
children: [
340
const Icon(Icons.route_rounded, size: 64),
341
const SizedBox(height: 16),
119
- const Text('LifeMate',
342
+ const Text('LifeGuide',
343
textAlign: TextAlign.center,
344
style:
345
TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
123
- const Text('همراه شخصی، تحصیلی و خانوادگی',
346
+ const Text('لایفگاید · همراه تحصیلی و خانوادگی',
347
textAlign: TextAlign.center),
348
const SizedBox(height: 28),
349
if (widget.invitationToken != null) ...[
@@ -136,7 +359,8 @@ class _SignInPageState extends State<SignInPage> {
359
TextField(
360
controller: email,
361
keyboardType: TextInputType.emailAddress,
139
- decoration: const InputDecoration(labelText: 'ایمیل'),
362
+ decoration:
363
+ const InputDecoration(labelText: 'ایمیل یا شماره تلفن'),
364
),
365
const SizedBox(height: 12),
366
TextField(
@@ -169,12 +393,42 @@ class _SignInPageState extends State<SignInPage> {
393
builder: (_) => RegistrationPage(api: widget.api))),
394
child: const Text('ساخت حساب جدید'),
395
),
396
+ if (widget.api is HttpIdentityApi) ...[
397
+ TextButton(
398
+ onPressed: busy
399
+ ? null
400
+ : () => Navigator.push(
401
+ context,
402
+ MaterialPageRoute(
403
+ builder: (_) => PhoneOtpPage(
404
+ api: widget.api as HttpIdentityApi))),
405
+ child: const Text('ورود با کد پیامکی')),
406
+ TextButton(
407
+ onPressed: busy
408
+ ? null
409
+ : () => Navigator.push(
410
+ context,
411
+ MaterialPageRoute(
412
+ builder: (_) => ResendVerificationPage(
413
+ api: widget.api as HttpIdentityApi))),
414
+ child: const Text('ارسال دوباره ایمیل تأیید')),
415
+ ],
416
+ if (widget.onEndpointSettings != null && !kIsWeb)
417
+ TextButton(
418
+ onPressed: busy ? null : widget.onEndpointSettings,
419
+ child: const Text('تنظیم اتصال')),
420
],
421
),
422
),
423
),
424
),
425
);
426
+ @override
427
+ void dispose() {
428
+ email.dispose();
429
+ password.dispose();
430
+ super.dispose();
431
+ }
432
}
433
434
class RegistrationPage extends StatefulWidget {
@@ -185,14 +439,18 @@ class RegistrationPage extends StatefulWidget {
439
}
440
441
class _RegistrationPageState extends State<RegistrationPage> {
188
- final name = TextEditingController();
189
- final email = TextEditingController();
190
- final password = TextEditingController();
191
- final confirm = TextEditingController();
192
- bool busy = false;
193
- String? error;
194
-
442
+ final name = TextEditingController(),
443
+ contact = TextEditingController(),
444
+ password = TextEditingController(),
445
+ confirm = TextEditingController();
446
+ bool phone = false, busy = false;
447
+ String? error, message;
448
Future<void> submit() async {
449
+ if (busy) return;
450
+ if (name.text.trim().isEmpty || contact.text.trim().isEmpty) {
451
+ setState(() => error = 'نام و یک راه تماس را وارد کن.');
452
+ return;
453
+ }
454
if (password.text != confirm.text) {
455
setState(() => error = 'تکرار رمز عبور یکسان نیست.');
456
return;
@@ -200,15 +458,26 @@ class _RegistrationPageState extends State<RegistrationPage> {
458
setState(() {
459
busy = true;
460
error = null;
461
+ message = null;
462
});
463
try {
205
- await widget.api.register(
206
- displayName: name.text, email: email.text, password: password.text);
207
- if (!mounted) return;
208
- ScaffoldMessenger.of(context).showSnackBar(
209
- const SnackBar(content: Text('حساب ساخته شد. ایمیل تأیید را بررسی کن.')),
210
- );
211
- Navigator.pop(context);
464
+ if (widget.api is HttpIdentityApi) {
465
+ await (widget.api as HttpIdentityApi).registerContact(
466
+ displayName: name.text.trim(),
467
+ password: password.text,
468
+ email: phone ? null : contact.text.trim(),
469
+ phone: phone ? contact.text.trim() : null);
470
+ } else {
471
+ await widget.api.register(
472
+ displayName: name.text.trim(),
473
+ email: contact.text.trim(),
474
+ password: password.text);
475
+ }
476
+ if (mounted) {
477
+ setState(() => message = phone
478
+ ? 'درخواست بررسی شد. تحویل پیامک تنها پس از پاسخ سرویس ارسال مشخص میشود.'
479
+ : 'درخواست بررسی شد. اگر این راه تماس واجد شرایط باشد، پیام تأیید ارسال میشود؛ تحویل ایمیل تأیید نشده است.');
480
+ }
481
} catch (e) {
482
if (mounted) setState(() => error = errorText(e));
483
} finally {
@@ -216,31 +485,243 @@ class _RegistrationPageState extends State<RegistrationPage> {
485
}
486
}
487
488
+ @override
489
+ void dispose() {
490
+ name.dispose();
491
+ contact.dispose();
492
+ password.dispose();
493
+ confirm.dispose();
494
+ super.dispose();
495
+ }
496
+
497
@override
498
Widget build(BuildContext context) => SimpleFormPage(
221
- title: 'ساخت حساب',
222
- busy: busy,
223
- error: error,
224
- action: 'ثبتنام و ارسال ایمیل تأیید',
225
- onPressed: submit,
226
- fields: [
227
- TextField(
228
- controller: name,
229
- decoration: const InputDecoration(labelText: 'نام')),
230
- TextField(
231
- controller: email,
232
- keyboardType: TextInputType.emailAddress,
233
- decoration: const InputDecoration(labelText: 'ایمیل')),
234
- TextField(
235
- controller: password,
236
- obscureText: true,
237
- decoration: const InputDecoration(labelText: 'رمز عبور')),
238
- TextField(
239
- controller: confirm,
240
- obscureText: true,
241
- decoration: const InputDecoration(labelText: 'تکرار رمز عبور')),
242
- ],
243
- );
499
+ title: 'ساخت حساب',
500
+ busy: busy,
501
+ error: error,
502
+ action: 'ثبت درخواست',
503
+ onPressed: submit,
504
+ fields: [
505
+ TextField(
506
+ controller: name,
507
+ decoration: const InputDecoration(labelText: 'نام')),
508
+ if (widget.api is HttpIdentityApi)
509
+ SegmentedButton<bool>(
510
+ segments: const [
511
+ ButtonSegment(value: false, label: Text('ایمیل')),
512
+ ButtonSegment(value: true, label: Text('تلفن'))
513
+ ],
514
+ selected: {
515
+ phone
516
+ },
517
+ onSelectionChanged:
518
+ busy ? null : (v) => setState(() => phone = v.first)),
519
+ TextField(
520
+ controller: contact,
521
+ keyboardType:
522
+ phone ? TextInputType.phone : TextInputType.emailAddress,
523
+ decoration: InputDecoration(
524
+ labelText: phone ? 'شماره تلفن' : 'ایمیل',
525
+ helperText: 'فقط یک راه تماس برای این حساب ثبت میشود.')),
526
+ TextField(
527
+ controller: password,
528
+ obscureText: true,
529
+ decoration: const InputDecoration(
530
+ labelText: 'رمز عبور', helperText: 'حداقل ۱۰ کاراکتر')),
531
+ TextField(
532
+ controller: confirm,
533
+ obscureText: true,
534
+ decoration: const InputDecoration(labelText: 'تکرار رمز عبور')),
535
+ if (message != null) Text(message!),
536
+ if (message != null && phone && widget.api is HttpIdentityApi)
537
+ TextButton(
538
+ onPressed: () => Navigator.push(
539
+ context,
540
+ MaterialPageRoute(
541
+ builder: (_) => PhoneOtpPage(
542
+ api: widget.api as HttpIdentityApi,
543
+ initialPhone: contact.text,
544
+ purpose: 'verify'))),
545
+ child: const Text('تأیید شماره تلفن')),
546
+ ]);
547
+}
548
+
549
+class ResendVerificationPage extends StatefulWidget {
550
+ const ResendVerificationPage({super.key, required this.api});
551
+ final HttpIdentityApi api;
552
+ @override
553
+ State<ResendVerificationPage> createState() => _ResendVerificationPageState();
554
+}
555
+
556
+class _ResendVerificationPageState extends State<ResendVerificationPage> {
557
+ final email = TextEditingController();
558
+ bool busy = false;
559
+ String? error, message;
560
+ Future<void> send() async {
561
+ setState(() {
562
+ busy = true;
563
+ error = null;
564
+ message = null;
565
+ });
566
+ try {
567
+ await widget.api.resendVerification(email.text.trim());
568
+ if (mounted) {
569
+ setState(() => message =
570
+ 'درخواست بررسی شد. اگر این ایمیل واجد شرایط باشد، پیام تأیید ارسال میشود؛ تحویل آن تأیید نشده است.');
571
+ }
572
+ } catch (e) {
573
+ if (mounted) setState(() => error = errorText(e));
574
+ } finally {
575
+ if (mounted) setState(() => busy = false);
576
+ }
577
+ }
578
+
579
+ @override
580
+ void dispose() {
581
+ email.dispose();
582
+ super.dispose();
583
+ }
584
+
585
+ @override
586
+ Widget build(BuildContext context) => SimpleFormPage(
587
+ title: 'ارسال دوباره ایمیل تأیید',
588
+ busy: busy,
589
+ error: error,
590
+ action: 'ثبت درخواست ارسال',
591
+ onPressed: send,
592
+ fields: [
593
+ TextField(
594
+ controller: email,
595
+ keyboardType: TextInputType.emailAddress,
596
+ decoration: const InputDecoration(labelText: 'ایمیل')),
597
+ if (message != null) Text(message!)
598
+ ]);
599
+}
600
+
601
+class PhoneOtpPage extends StatefulWidget {
602
+ const PhoneOtpPage(
603
+ {super.key,
604
+ required this.api,
605
+ this.initialPhone = '',
606
+ this.purpose = 'login'});
607
+ final HttpIdentityApi api;
608
+ final String initialPhone, purpose;
609
+ @override
610
+ State<PhoneOtpPage> createState() => _PhoneOtpPageState();
611
+}
612
+
613
+class _PhoneOtpPageState extends State<PhoneOtpPage> {
614
+ late final TextEditingController phone;
615
+ final code = TextEditingController(), password = TextEditingController();
616
+ String? challenge, error, message;
617
+ bool busy = false;
618
+ String purpose = 'login';
619
+ @override
620
+ void initState() {
621
+ super.initState();
622
+ phone = TextEditingController(text: widget.initialPhone);
623
+ purpose = widget.purpose;
624
+ }
625
+
626
+ Future<void> request() async {
627
+ setState(() {
628
+ busy = true;
629
+ error = null;
630
+ message = null;
631
+ challenge = null;
632
+ });
633
+ try {
634
+ final response =
635
+ await widget.api.requestPhoneOtp(phone.text.trim(), purpose: purpose);
636
+ final id = response['challengeId'];
637
+ if (id is! String || id.isEmpty) {
638
+ throw const ApiException(502, 'invalid_otp_response');
639
+ }
640
+ if (mounted) {
641
+ setState(() {
642
+ challenge = id;
643
+ message = 'درخواست کد پذیرفته شد. تحویل پیامک تأیید نشده است.';
644
+ });
645
+ }
646
+ } catch (e) {
647
+ if (mounted) setState(() => error = errorText(e));
648
+ } finally {
649
+ if (mounted) setState(() => busy = false);
650
+ }
651
+ }
652
+
653
+ Future<void> verify() async {
654
+ setState(() {
655
+ busy = true;
656
+ error = null;
657
+ });
658
+ try {
659
+ await widget.api.verifyPhoneOtp(challenge!, code.text.trim(),
660
+ newPassword: password.text.isEmpty ? null : password.text);
661
+ if (mounted) {
662
+ Navigator.pop(context);
663
+ }
664
+ } catch (e) {
665
+ if (mounted) setState(() => error = errorText(e));
666
+ } finally {
667
+ if (mounted) setState(() => busy = false);
668
+ }
669
+ }
670
+
671
+ @override
672
+ void dispose() {
673
+ phone.dispose();
674
+ code.dispose();
675
+ password.dispose();
676
+ super.dispose();
677
+ }
678
+
679
+ @override
680
+ Widget build(BuildContext context) => SimpleFormPage(
681
+ title: 'ورود و تأیید تلفن',
682
+ busy: busy,
683
+ error: error,
684
+ action: challenge == null ? 'درخواست کد' : 'تأیید کد',
685
+ onPressed: challenge == null ? request : verify,
686
+ fields: [
687
+ if (challenge == null)
688
+ DropdownButtonFormField<String>(
689
+ initialValue: purpose,
690
+ decoration: const InputDecoration(labelText: 'هدف درخواست'),
691
+ items: const [
692
+ DropdownMenuItem(value: 'login', child: Text('ورود')),
693
+ DropdownMenuItem(
694
+ value: 'verify', child: Text('تأیید شماره')),
695
+ DropdownMenuItem(
696
+ value: 'recovery', child: Text('بازیابی رمز'))
697
+ ],
698
+ onChanged: busy
699
+ ? null
700
+ : (v) => setState(() => purpose = v ?? purpose)),
701
+ TextField(
702
+ controller: phone,
703
+ enabled: challenge == null && !busy,
704
+ keyboardType: TextInputType.phone,
705
+ decoration: const InputDecoration(labelText: 'شماره تلفن')),
706
+ if (challenge != null)
707
+ TextField(
708
+ controller: code,
709
+ keyboardType: TextInputType.number,
710
+ decoration: const InputDecoration(labelText: 'کد پیامکی')),
711
+ if (challenge != null)
712
+ TextField(
713
+ controller: password,
714
+ obscureText: true,
715
+ decoration: const InputDecoration(
716
+ labelText: 'رمز عبور جدید',
717
+ helperText:
718
+ 'برای تأیید اولیه و بازیابی، حداقل ۱۰ کاراکتر لازم است.')),
719
+ if (message != null) Text(message!),
720
+ if (challenge != null)
721
+ TextButton(
722
+ onPressed: busy ? null : request,
723
+ child: const Text('درخواست کد تازه')),
724
+ ]);
725
}
726
727
class RecoveryPage extends StatefulWidget {
@@ -276,7 +757,7 @@ class _RecoveryPageState extends State<RecoveryPage> {
757
title: 'بازیابی رمز عبور',
758
busy: busy,
759
error: error,
279
- action: sent ? 'لینک ارسال شد' : 'ارسال لینک بازیابی',
760
+ action: sent ? 'درخواست بررسی شد' : 'ارسال لینک بازیابی',
761
onPressed: sent ? null : submit,
762
fields: [
763
TextField(
@@ -299,25 +780,56 @@ class VerifyEmailPage extends StatefulWidget {
780
}
781
782
class _VerifyEmailPageState extends State<VerifyEmailPage> {
302
- String message = 'در حال تأیید ایمیل...';
303
- @override
304
- void initState() {
305
- super.initState();
306
- verify();
307
- }
308
-
783
+ final password = TextEditingController(), confirm = TextEditingController();
784
+ bool busy = false, done = false;
785
+ String? error;
786
Future<void> verify() async {
787
+ if (password.text != confirm.text) {
788
+ setState(() => error = 'تکرار رمز عبور یکسان نیست.');
789
+ return;
790
+ }
791
+ setState(() {
792
+ busy = true;
793
+ error = null;
794
+ });
795
try {
311
- await widget.api.verifyEmail(widget.token);
312
- if (mounted) setState(() => message = 'ایمیل با موفقیت تأیید شد.');
796
+ await widget.api.verifyEmail(widget.token, newPassword: password.text);
797
+ if (mounted) setState(() => done = true);
798
} catch (e) {
314
- if (mounted) setState(() => message = errorText(e));
799
+ if (mounted) setState(() => error = errorText(e));
800
+ } finally {
801
+ if (mounted) setState(() => busy = false);
802
}
803
}
804
805
@override
319
- Widget build(BuildContext context) =>
320
- Scaffold(body: Center(child: Text(message)));
806
+ void dispose() {
807
+ password.dispose();
808
+ confirm.dispose();
809
+ super.dispose();
810
+ }
811
+
812
+ @override
813
+ Widget build(BuildContext context) => SimpleFormPage(
814
+ title: 'تأیید مالکیت ایمیل',
815
+ busy: busy,
816
+ error: error,
817
+ action: done ? 'ایمیل تأیید شد' : 'تأیید و تعیین رمز عبور',
818
+ onPressed: done ? null : verify,
819
+ fields: [
820
+ const Text(
821
+ 'برای تکمیل مالکیت این حساب، رمز عبور جدید خودت را تعیین کن.'),
822
+ TextField(
823
+ controller: password,
824
+ obscureText: true,
825
+ decoration: const InputDecoration(
826
+ labelText: 'رمز عبور جدید',
827
+ helperText: 'حداقل ۱۰ کاراکتر')),
828
+ TextField(
829
+ controller: confirm,
830
+ obscureText: true,
831
+ decoration: const InputDecoration(labelText: 'تکرار رمز عبور'))
832
+ ]);
833
}
834
835
class ResetPasswordPage extends StatefulWidget {
@@ -481,8 +993,11 @@ class SimpleFormPage extends StatelessWidget {
993
}
994
995
class HomeShell extends StatefulWidget {
484
- const HomeShell({super.key, required this.api});
996
+ const HomeShell(
997
+ {super.key, required this.api, this.onSignOut, this.onEndpointSettings});
998
final IdentityApi api;
999
+ final Future<void> Function()? onSignOut;
1000
+ final Future<void> Function()? onEndpointSettings;
1001
1002
@override
1003
State<HomeShell> createState() => _HomeShellState();
@@ -492,6 +1007,7 @@ class _HomeShellState extends State<HomeShell> {
1007
int index = 0;
1008
String themePreference = 'adult_blue';
1009
bool adultShell = false;
1010
+ String? contextError;
1011
1012
static const studentPages = [
1013
'امروز',
@@ -520,21 +1036,21 @@ class _HomeShellState extends State<HomeShell> {
1036
Future<void> loadContext() async {
1037
try {
1038
final profile = await widget.api.getProfile();
523
- final families = await widget.api.listFamilies();
524
- final hasAdultRole = families.any(
525
- (family) =>
526
- family['role'] == 'parent_guardian' ||
527
- family['role'] == 'adult_member',
528
- );
1039
if (mounted) {
1040
setState(() {
1041
themePreference =
1042
profile['theme_preference']?.toString() ?? 'adult_blue';
533
- adultShell = hasAdultRole;
534
- index = 0;
1043
+ final category = profile['profile_category']?.toString();
1044
+ adultShell = category == 'adult' ||
1045
+ (!['girl_minor', 'boy_minor'].contains(category) &&
1046
+ !['girl_pink', 'boy_blue'].contains(themePreference));
1047
+ contextError = null;
1048
+ if (index >= pages.length) index = pages.length - 1;
1049
});
1050
}
537
- } catch (_) {}
1051
+ } catch (error) {
1052
+ if (mounted) setState(() => contextError = errorText(error));
1053
+ }
1054
}
1055
1056
List<String> get pages => adultShell ? adultPages : studentPages;
@@ -604,22 +1120,36 @@ class _HomeShellState extends State<HomeShell> {
1120
title: Text(pages[index]),
1121
actions: [
1122
IconButton(
607
- onPressed: () => Navigator.of(context).push(
608
- MaterialPageRoute(
609
- builder: (_) => ProfileFamilyPage(api: widget.api),
610
- ),
611
- ),
1123
+ onPressed: () async {
1124
+ await Navigator.of(context).push(MaterialPageRoute(
1125
+ builder: (_) => ProfileFamilyPage(api: widget.api)));
1126
+ if (mounted) await loadContext();
1127
+ },
1128
icon: const Icon(Icons.person_outline),
1129
),
1130
],
1131
),
616
- body: (pages[index] == 'همراه هوشمند' || pages[index] == 'راهنما')
617
- ? Phase4Hub(api: widget.api, adultShell: adultShell)
618
- : Phase3HomeContent(
619
- api: widget.api,
620
- page: pages[index],
621
- adultShell: adultShell,
622
- ),
1132
+ body: Column(children: [
1133
+ if (contextError != null)
1134
+ MaterialBanner(content: Text(contextError!), actions: [
1135
+ TextButton(
1136
+ onPressed: loadContext, child: const Text('تلاش دوباره'))
1137
+ ]),
1138
+ Expanded(
1139
+ child: pages[index] == 'من'
1140
+ ? ProfileFamilyPage(api: widget.api)
1141
+ : (pages[index] == 'همراه هوشمند' ||
1142
+ pages[index] == 'راهنما')
1143
+ ? const CoreNotice(
1144
+ title: 'همراه هوشمند',
1145
+ subtitle:
1146
+ 'در این مرحله فعال نیست؛ داده سلامت و گفتوگو به سرویس هوشمند ارسال نمیشود.')
1147
+ : Phase3HomeContent(
1148
+ api: widget.api,
1149
+ page: pages[index],
1150
+ adultShell: adultShell,
1151
+ ))
1152
+ ]),
1153
bottomNavigationBar: NavigationBar(
1154
selectedIndex: index > 4 ? 0 : index,
1155
onDestinationSelected: selectPage,
@@ -630,7 +1160,7 @@ class _HomeShellState extends State<HomeShell> {
1160
child: ListView(
1161
children: [
1162
const ListTile(
633
- title: Text('LifeMate'),
1163
+ title: Text('LifeGuide'),
1164
subtitle: Text('منوی اصلی'),
1165
),
1166
...pages.asMap().entries.map(
@@ -642,6 +1172,50 @@ class _HomeShellState extends State<HomeShell> {
1172
},
1173
),
1174
),
1175
+ ListTile(
1176
+ leading: const Icon(Icons.notifications_outlined),
1177
+ title: const Text('اعلانهای درون برنامه'),
1178
+ onTap: () {
1179
+ Navigator.pop(context);
1180
+ Navigator.of(context).push(MaterialPageRoute(
1181
+ builder: (_) =>
1182
+ NotificationInboxPage(api: widget.api)));
1183
+ }),
1184
+ ListTile(
1185
+ leading: const Icon(Icons.sync_problem_outlined),
1186
+ title: const Text('تغییرهای معلق و تعارضها'),
1187
+ onTap: () {
1188
+ Navigator.pop(context);
1189
+ Navigator.of(context).push(MaterialPageRoute(
1190
+ builder: (_) => SyncChangesPage(api: widget.api)));
1191
+ }),
1192
+ if (widget.onEndpointSettings != null && !kIsWeb)
1193
+ ListTile(
1194
+ leading: const Icon(Icons.settings_ethernet),
1195
+ title: const Text('تنظیم اتصال'),
1196
+ onTap: () {
1197
+ Navigator.pop(context);
1198
+ widget.onEndpointSettings!();
1199
+ }),
1200
+ if (widget.onSignOut != null)
1201
+ ListTile(
1202
+ leading: const Icon(Icons.logout),
1203
+ title: const Text('خروج از حساب'),
1204
+ onTap: () async {
1205
+ Navigator.pop(context);
1206
+ try {
1207
+ if (!await confirmScopeDiscard(
1208
+ context, widget.api)) {
1209
+ return;
1210
+ }
1211
+ await widget.onSignOut!();
1212
+ } catch (e) {
1213
+ if (context.mounted) {
1214
+ ScaffoldMessenger.of(context).showSnackBar(
1215
+ SnackBar(content: Text(errorText(e))));
1216
+ }
1217
+ }
1218
+ }),
1219
if (!adultShell) ...[
1220
const Divider(),
1221
ListTile(
@@ -681,156 +1255,37 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1255
[await widget.api.getProfile(), await widget.api.listFamilies()];
1256
1257
Future<void> editProfile(Map<String, dynamic> profile) async {
684
- final name = TextEditingController(
685
- text: profile['display_name']?.toString() ?? '');
686
- final theme = ValueNotifier<String>(
687
- profile['theme_preference']?.toString() ?? 'adult_blue');
1258
final saved = await showDialog<bool>(
689
- context: context,
690
- builder: (dialogContext) => AlertDialog(
691
- title: const Text('ویرایش پروفایل'),
692
- content: Column(mainAxisSize: MainAxisSize.min, children: [
693
- TextField(
694
- controller: name,
695
- decoration: const InputDecoration(labelText: 'نام')),
696
- const SizedBox(height: 12),
697
- ValueListenableBuilder<String>(
698
- valueListenable: theme,
699
- builder: (_, value, __) => DropdownButtonFormField<String>(
700
- initialValue: value,
701
- decoration: const InputDecoration(labelText: 'تم'),
702
- items: const [
703
- DropdownMenuItem(
704
- value: 'girl_pink', child: Text('سفید / صورتی')),
705
- DropdownMenuItem(
706
- value: 'boy_blue', child: Text('سفید / آبی نوجوان')),
707
- DropdownMenuItem(
708
- value: 'adult_blue', child: Text('سفید / آبی بزرگسال')),
709
- ],
710
- onChanged: (v) {
711
- if (v != null) theme.value = v;
712
- },
713
- ),
714
- ),
715
- ]),
716
- actions: [
717
- TextButton(
718
- onPressed: () => Navigator.pop(dialogContext, false),
719
- child: const Text('انصراف')),
720
- FilledButton(
721
- onPressed: () async {
722
- await widget.api.updateProfile(
723
- displayName: name.text.trim(),
724
- themePreference: theme.value);
725
- if (dialogContext.mounted) Navigator.pop(dialogContext, true);
726
- },
727
- child: const Text('ذخیره'),
728
- ),
729
- ],
730
- ),
731
- );
732
- name.dispose();
733
- theme.dispose();
734
- if (saved == true && mounted) setState(() => data = load());
1259
+ context: context,
1260
+ builder: (_) =>
1261
+ _AccountDialog(api: widget.api, mode: 'profile', profile: profile));
1262
+ if (saved == true && mounted) {
1263
+ setState(() {
1264
+ data = load();
1265
+ });
1266
+ }
1267
}
1268
1269
Future<void> createFamily() async {
738
- final name = TextEditingController();
739
- final created = await showDialog<bool>(
740
- context: context,
741
- builder: (dialogContext) => AlertDialog(
742
- title: const Text('ساخت فضای خانواده'),
743
- content: TextField(
744
- controller: name,
745
- decoration: const InputDecoration(labelText: 'نام خانواده')),
746
- actions: [
747
- TextButton(
748
- onPressed: () => Navigator.pop(dialogContext, false),
749
- child: const Text('انصراف')),
750
- FilledButton(
751
- onPressed: () async {
752
- if (name.text.trim().isEmpty) return;
753
- await widget.api
754
- .createFamily(name.text.trim(), role: 'parent_guardian');
755
- if (dialogContext.mounted) Navigator.pop(dialogContext, true);
756
- },
757
- child: const Text('ساخت'),
758
- ),
759
- ],
760
- ),
761
- );
762
- name.dispose();
763
- if (created == true && mounted) setState(() => data = load());
1270
+ final saved = await showDialog<bool>(
1271
+ context: context,
1272
+ builder: (_) => _AccountDialog(api: widget.api, mode: 'family'));
1273
+ if (saved == true && mounted) {
1274
+ setState(() {
1275
+ data = load();
1276
+ });
1277
+ }
1278
}
1279
1280
Future<void> invite(String familyId) async {
767
- final email = TextEditingController();
768
- final choice = ValueNotifier<String>('daughter');
769
- final sent = await showDialog<bool>(
770
- context: context,
771
- builder: (dialogContext) => AlertDialog(
772
- title: const Text('دعوت فرزند / عضو'),
773
- content: Column(mainAxisSize: MainAxisSize.min, children: [
774
- TextField(
775
- controller: email,
776
- keyboardType: TextInputType.emailAddress,
777
- decoration: const InputDecoration(labelText: 'ایمیل')),
778
- const SizedBox(height: 12),
779
- ValueListenableBuilder<String>(
780
- valueListenable: choice,
781
- builder: (_, value, __) => DropdownButtonFormField<String>(
782
- initialValue: value,
783
- decoration: const InputDecoration(labelText: 'نوع عضو'),
784
- items: const [
785
- DropdownMenuItem(
786
- value: 'daughter', child: Text('فرزند دختر — سفید / صورتی')),
787
- DropdownMenuItem(
788
- value: 'son', child: Text('فرزند پسر — سفید / آبی')),
789
- DropdownMenuItem(
790
- value: 'parent', child: Text('والد / سرپرست — سفید / آبی')),
791
- DropdownMenuItem(
792
- value: 'adult', child: Text('عضو بزرگسال — سفید / آبی')),
793
- ],
794
- onChanged: (v) {
795
- if (v != null) choice.value = v;
796
- },
797
- ),
798
- ),
799
- ]),
800
- actions: [
801
- TextButton(
802
- onPressed: () => Navigator.pop(dialogContext, false),
803
- child: const Text('انصراف')),
804
- FilledButton(
805
- onPressed: () async {
806
- final selected = choice.value;
807
- final role = selected == 'parent'
808
- ? 'parent_guardian'
809
- : selected == 'adult'
810
- ? 'adult_member'
811
- : 'teen_minor';
812
- final theme = selected == 'daughter'
813
- ? 'girl_pink'
814
- : selected == 'son'
815
- ? 'boy_blue'
816
- : 'adult_blue';
817
- await widget.api.inviteMember(
818
- familyId: familyId,
819
- email: email.text,
820
- role: role,
821
- themePreference: theme);
822
- if (dialogContext.mounted) Navigator.pop(dialogContext, true);
823
- },
824
- child: const Text('ارسال دعوت'),
825
- ),
826
- ],
827
- ),
828
- );
829
- email.dispose();
830
- choice.dispose();
831
- if (sent == true && mounted) {
832
- ScaffoldMessenger.of(context)
833
- .showSnackBar(const SnackBar(content: Text('دعوت ارسال شد.')));
1281
+ final saved = await showDialog<bool>(
1282
+ context: context,
1283
+ builder: (_) => _AccountDialog(
1284
+ api: widget.api, mode: 'invite', familyId: familyId));
1285
+ if (saved == true && mounted) {
1286
+ ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
1287
+ content:
1288
+ Text('درخواست دعوت پذیرفته شد؛ تحویل پیام تأیید نشده است.')));
1289
}
1290
}
1291
@@ -841,7 +1296,13 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1296
future: data,
1297
builder: (context, snapshot) {
1298
if (snapshot.hasError) {
844
- return Center(child: Text(errorText(snapshot.error!)));
1299
+ return LoadError(
1300
+ error: snapshot.error!,
1301
+ retry: () {
1302
+ setState(() {
1303
+ data = load();
1304
+ });
1305
+ });
1306
}
1307
if (!snapshot.hasData) {
1308
return const Center(child: CircularProgressIndicator());
@@ -870,16 +1331,14 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1331
leading: const Icon(Icons.family_restroom),
1332
title: const Text('هنوز فضای خانواده ساخته نشده'),
1333
trailing: IconButton(
873
- onPressed: createFamily,
874
- icon: const Icon(Icons.add)),
1334
+ onPressed: createFamily, icon: const Icon(Icons.add)),
1335
),
1336
)
1337
else
1338
...families.map((family) => Card(
1339
child: ListTile(
1340
leading: const Icon(Icons.family_restroom),
881
- title:
882
- Text(family['name']?.toString() ?? 'خانواده'),
1341
+ title: Text(family['name']?.toString() ?? 'خانواده'),
1342
subtitle: Text(
1343
'${family['is_admin'] == true ? 'مدیر خانواده · ' : ''}${family['role'] ?? ''}'),
1344
onTap: () => Navigator.of(context).push(
@@ -894,16 +1353,20 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1353
),
1354
),
1355
trailing: IconButton(
897
- onPressed: () => invite(family['id'].toString()),
1356
+ onPressed: family['is_admin'] == true
1357
+ ? () => invite(family['id'].toString())
1358
+ : null,
1359
icon: const Icon(Icons.person_add_alt)),
1360
),
1361
)),
1362
ListTile(
1363
leading: const Icon(Icons.public),
1364
title: const Text('خانواده و یادگیری ایران'),
904
- subtitle: const Text('نقشها، پایه تحصیلی، کتابها، تقویم و یادآوری'),
1365
+ subtitle: const Text(
1366
+ 'نقشها، پایه تحصیلی، کتابها، تقویم و یادآوری'),
1367
onTap: () => Navigator.of(context).push(MaterialPageRoute(
906
- builder: (_) => IranianFamilyLearningHub(identity: widget.api),
1368
+ builder: (_) =>
1369
+ IranianFamilyLearningHub(identity: widget.api),
1370
)),
1371
),
1372
ListTile(
@@ -961,77 +1424,20 @@ class _FamilyMembersPageState extends State<FamilyMembersPage> {
1424
};
1425
1426
Future<void> configureGuardian(List<Map<String, dynamic>> items) async {
964
- final guardians =
965
- items.where((m) => m['role'] == 'parent_guardian').toList();
966
- final minors = items.where((m) => m['role'] == 'teen_minor').toList();
967
- if (guardians.isEmpty || minors.isEmpty) {
1427
+ if (!items.any((m) => m['role'] == 'parent_guardian') ||
1428
+ !items.any((m) => m['role'] == 'teen_minor')) {
1429
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
969
- content: Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
1430
+ content:
1431
+ Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
1432
return;
1433
}
972
- final guardianId =
973
- ValueNotifier<String>(guardians.first['user_id'].toString());
974
- final minorId = ValueNotifier<String>(minors.first['user_id'].toString());
975
- final saved = await showDialog<bool>(
976
- context: context,
977
- builder: (dialogContext) => AlertDialog(
978
- title: const Text('رابطه والد و فرزند'),
979
- content: Column(mainAxisSize: MainAxisSize.min, children: [
980
- ValueListenableBuilder<String>(
981
- valueListenable: guardianId,
982
- builder: (_, value, __) => DropdownButtonFormField<String>(
983
- initialValue: value,
984
- decoration: const InputDecoration(labelText: 'والد / سرپرست'),
985
- items: guardians
986
- .map((m) => DropdownMenuItem(
987
- value: m['user_id'].toString(),
988
- child: Text(m['display_name']?.toString() ?? 'والد')))
989
- .toList(),
990
- onChanged: (v) {
991
- if (v != null) guardianId.value = v;
992
- },
993
- ),
994
- ),
995
- const SizedBox(height: 12),
996
- ValueListenableBuilder<String>(
997
- valueListenable: minorId,
998
- builder: (_, value, __) => DropdownButtonFormField<String>(
999
- initialValue: value,
1000
- decoration: const InputDecoration(labelText: 'فرزند'),
1001
- items: minors
1002
- .map((m) => DropdownMenuItem(
1003
- value: m['user_id'].toString(),
1004
- child: Text(m['display_name']?.toString() ?? 'فرزند')))
1005
- .toList(),
1006
- onChanged: (v) {
1007
- if (v != null) minorId.value = v;
1008
- },
1009
- ),
1010
- ),
1011
- ]),
1012
- actions: [
1013
- TextButton(
1014
- onPressed: () => Navigator.pop(dialogContext, false),
1015
- child: const Text('انصراف')),
1016
- FilledButton(
1017
- onPressed: () async {
1018
- await widget.api.setGuardian(
1019
- familyId: widget.familyId,
1020
- guardianUserId: guardianId.value,
1021
- minorUserId: minorId.value);
1022
- if (dialogContext.mounted) Navigator.pop(dialogContext, true);
1023
- },
1024
- child: const Text('ثبت رابطه'),
1025
- ),
1026
- ],
1027
- ),
1028
- );
1029
- guardianId.dispose();
1030
- minorId.dispose();
1031
- if (saved == true && mounted) {
1032
- ScaffoldMessenger.of(context).showSnackBar(
1033
- const SnackBar(content: Text('رابطه سرپرستی ثبت شد.')));
1034
- }
1434
+ await showDialog<bool>(
1435
+ context: context,
1436
+ builder: (_) => _AccountDialog(
1437
+ api: widget.api,
1438
+ mode: 'guardian',
1439
+ familyId: widget.familyId,
1440
+ members: items));
1441
}
1442
1443
@override
@@ -1041,7 +1447,13 @@ class _FamilyMembersPageState extends State<FamilyMembersPage> {
1447
future: members,
1448
builder: (context, snapshot) {
1449
if (snapshot.hasError) {
1044
- return Center(child: Text(errorText(snapshot.error!)));
1450
+ return LoadError(
1451
+ error: snapshot.error!,
1452
+ retry: () {
1453
+ setState(() {
1454
+ members = widget.api.listFamilyMembers(widget.familyId);
1455
+ });
1456
+ });
1457
}
1458
if (!snapshot.hasData) {
1459
return const Center(child: CircularProgressIndicator());
@@ -1054,8 +1466,7 @@ class _FamilyMembersPageState extends State<FamilyMembersPage> {
1466
Card(
1467
child: ListTile(
1468
leading: const CircleAvatar(child: Icon(Icons.person)),
1057
- title:
1058
- Text(member['display_name']?.toString() ?? 'عضو'),
1469
+ title: Text(member['display_name']?.toString() ?? 'عضو'),
1470
subtitle:
1471
Text(roleLabel(member['role']?.toString() ?? '')),
1472
trailing: member['is_admin'] == true
@@ -1077,3 +1488,273 @@ class _FamilyMembersPageState extends State<FamilyMembersPage> {
1488
),
1489
);
1490
}
1491
+
1492
+class _AccountDialog extends StatefulWidget {
1493
+ const _AccountDialog(
1494
+ {required this.api,
1495
+ required this.mode,
1496
+ this.profile,
1497
+ this.familyId,
1498
+ this.members = const []});
1499
+ final IdentityApi api;
1500
+ final String mode;
1501
+ final Map<String, dynamic>? profile;
1502
+ final String? familyId;
1503
+ final List<Map<String, dynamic>> members;
1504
+ @override
1505
+ State<_AccountDialog> createState() => _AccountDialogState();
1506
+}
1507
+
1508
+class _AccountDialogState extends State<_AccountDialog> {
1509
+ late final TextEditingController name;
1510
+ String theme = 'adult_blue', choice = 'daughter', category = 'adult';
1511
+ bool phoneInvitation = false;
1512
+ String? invitationLink;
1513
+ String? guardian, minor, error;
1514
+ bool busy = false;
1515
+ @override
1516
+ void initState() {
1517
+ super.initState();
1518
+ name = TextEditingController(
1519
+ text: widget.profile?['display_name']?.toString() ?? '');
1520
+ theme = widget.profile?['theme_preference']?.toString() ?? theme;
1521
+ category = widget.profile?['profile_category']?.toString() ??
1522
+ (theme == 'girl_pink'
1523
+ ? 'girl_minor'
1524
+ : theme == 'boy_blue'
1525
+ ? 'boy_minor'
1526
+ : 'adult');
1527
+ final gs = widget.members.where((m) => m['role'] == 'parent_guardian');
1528
+ final ms = widget.members.where((m) => m['role'] == 'teen_minor');
1529
+ guardian = gs.isEmpty ? null : gs.first['user_id'].toString();
1530
+ minor = ms.isEmpty ? null : ms.first['user_id'].toString();
1531
+ }
1532
+
1533
+ @override
1534
+ void dispose() {
1535
+ name.dispose();
1536
+ super.dispose();
1537
+ }
1538
+
1539
+ Future<void> save() async {
1540
+ if (busy) return;
1541
+ if (widget.mode != 'guardian' && name.text.trim().isEmpty) {
1542
+ setState(() => error = 'این فیلد را وارد کن.');
1543
+ return;
1544
+ }
1545
+ setState(() {
1546
+ busy = true;
1547
+ error = null;
1548
+ });
1549
+ try {
1550
+ switch (widget.mode) {
1551
+ case 'profile':
1552
+ await widget.api.updateProfile(
1553
+ displayName: name.text.trim(),
1554
+ themePreference: theme,
1555
+ profileCategory: category);
1556
+ case 'family':
1557
+ await widget.api
1558
+ .createFamily(name.text.trim(), role: 'parent_guardian');
1559
+ case 'invite':
1560
+ final role = choice == 'parent'
1561
+ ? 'parent_guardian'
1562
+ : choice == 'adult'
1563
+ ? 'adult_member'
1564
+ : 'teen_minor';
1565
+ final memberTheme = choice == 'daughter'
1566
+ ? 'girl_pink'
1567
+ : choice == 'son'
1568
+ ? 'boy_blue'
1569
+ : 'adult_blue';
1570
+ if (widget.api is HttpIdentityApi) {
1571
+ final result = await (widget.api as HttpIdentityApi)
1572
+ .createFamilyInvitation(
1573
+ familyId: widget.familyId!,
1574
+ email: phoneInvitation ? null : name.text.trim(),
1575
+ phone: phoneInvitation ? name.text.trim() : null,
1576
+ role: role,
1577
+ themePreference: memberTheme);
1578
+ final link = result['invitationLink'];
1579
+ if (link is! String || link.isEmpty) {
1580
+ throw const ApiException(502, 'invalid_invitation_response');
1581
+ }
1582
+ if (mounted) setState(() => invitationLink = link);
1583
+ } else {
1584
+ await widget.api.inviteMember(
1585
+ familyId: widget.familyId!,
1586
+ email: name.text.trim(),
1587
+ role: role,
1588
+ themePreference: memberTheme);
1589
+ }
1590
+ case 'guardian':
1591
+ await widget.api.setGuardian(
1592
+ familyId: widget.familyId!,
1593
+ guardianUserId: guardian!,
1594
+ minorUserId: minor!);
1595
+ }
1596
+ if (mounted && invitationLink == null) Navigator.pop(context, true);
1597
+ } catch (e) {
1598
+ if (mounted) setState(() => error = errorText(e));
1599
+ } finally {
1600
+ if (mounted) setState(() => busy = false);
1601
+ }
1602
+ }
1603
+
1604
+ @override
1605
+ Widget build(BuildContext context) => PopScope(
1606
+ canPop: !busy,
1607
+ child: AlertDialog(
1608
+ title: Text(switch (widget.mode) {
1609
+ 'profile' => 'ویرایش پروفایل',
1610
+ 'family' => 'ساخت فضای خانواده',
1611
+ 'invite' => 'دعوت فرزند / عضو',
1612
+ _ => 'رابطه والد و فرزند'
1613
+ }),
1614
+ content: SizedBox(
1615
+ width: 440,
1616
+ child: SingleChildScrollView(
1617
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
1618
+ if (invitationLink != null) ...[
1619
+ const Text(
1620
+ 'پیوند دعوت آماده شد. تحویل ایمیل یا پیامک تأیید نشده است؛ پیوند را خودت به عضو موردنظر برسان.'),
1621
+ SelectableText(invitationLink!),
1622
+ TextButton.icon(
1623
+ onPressed: () async {
1624
+ await Clipboard.setData(
1625
+ ClipboardData(text: invitationLink!));
1626
+ },
1627
+ icon: const Icon(Icons.copy),
1628
+ label: const Text('کپی پیوند دعوت'))
1629
+ ],
1630
+ if (invitationLink == null &&
1631
+ widget.mode == 'invite' &&
1632
+ widget.api is HttpIdentityApi)
1633
+ SegmentedButton<bool>(
1634
+ segments: const [
1635
+ ButtonSegment(value: false, label: Text('ایمیل')),
1636
+ ButtonSegment(value: true, label: Text('تلفن'))
1637
+ ],
1638
+ selected: {
1639
+ phoneInvitation
1640
+ },
1641
+ onSelectionChanged: busy
1642
+ ? null
1643
+ : (v) => setState(() => phoneInvitation = v.first)),
1644
+ if (invitationLink == null && widget.mode != 'guardian')
1645
+ TextField(
1646
+ controller: name,
1647
+ enabled: !busy,
1648
+ decoration: InputDecoration(
1649
+ labelText: widget.mode == 'invite'
1650
+ ? (phoneInvitation ? 'شماره تلفن' : 'ایمیل')
1651
+ : widget.mode == 'family'
1652
+ ? 'نام خانواده'
1653
+ : 'نام')),
1654
+ if (widget.mode == 'profile') ...[
1655
+ DropdownButtonFormField<String>(
1656
+ initialValue: category,
1657
+ decoration:
1658
+ const InputDecoration(labelText: 'نوع پروفایل'),
1659
+ items: const [
1660
+ DropdownMenuItem(
1661
+ value: 'girl_minor', child: Text('دختر / نوجوان')),
1662
+ DropdownMenuItem(
1663
+ value: 'boy_minor', child: Text('پسر / نوجوان')),
1664
+ DropdownMenuItem(value: 'adult', child: Text('بزرگسال'))
1665
+ ],
1666
+ onChanged: busy
1667
+ ? null
1668
+ : (v) => setState(() => category = v ?? category)),
1669
+ const Text(
1670
+ 'نوع پروفایل، نقش یا اجازه سرپرستی خانواده ایجاد نمیکند.')
1671
+ ],
1672
+ if (widget.mode == 'profile')
1673
+ DropdownButtonFormField<String>(
1674
+ initialValue: theme,
1675
+ decoration: const InputDecoration(labelText: 'تم'),
1676
+ items: const [
1677
+ DropdownMenuItem(
1678
+ value: 'girl_pink', child: Text('سفید / صورتی')),
1679
+ DropdownMenuItem(
1680
+ value: 'boy_blue',
1681
+ child: Text('سفید / آبی نوجوان')),
1682
+ DropdownMenuItem(
1683
+ value: 'adult_blue',
1684
+ child: Text('سفید / آبی بزرگسال'))
1685
+ ],
1686
+ onChanged: busy
1687
+ ? null
1688
+ : (v) => setState(() => theme = v ?? theme)),
1689
+ if (invitationLink == null && widget.mode == 'invite')
1690
+ DropdownButtonFormField<String>(
1691
+ initialValue: choice,
1692
+ decoration: const InputDecoration(labelText: 'نوع عضو'),
1693
+ items: const [
1694
+ DropdownMenuItem(
1695
+ value: 'daughter',
1696
+ child: Text('فرزند دختر — سفید / صورتی')),
1697
+ DropdownMenuItem(
1698
+ value: 'son',
1699
+ child: Text('فرزند پسر — سفید / آبی')),
1700
+ DropdownMenuItem(
1701
+ value: 'parent',
1702
+ child: Text('والد / سرپرست — سفید / آبی')),
1703
+ DropdownMenuItem(
1704
+ value: 'adult',
1705
+ child: Text('عضو بزرگسال — سفید / آبی'))
1706
+ ],
1707
+ onChanged: busy
1708
+ ? null
1709
+ : (v) => setState(() => choice = v ?? choice)),
1710
+ if (widget.mode == 'guardian') ...[
1711
+ DropdownButtonFormField<String>(
1712
+ initialValue: guardian,
1713
+ decoration:
1714
+ const InputDecoration(labelText: 'والد / سرپرست'),
1715
+ items: widget.members
1716
+ .where((m) => m['role'] == 'parent_guardian')
1717
+ .map((m) => DropdownMenuItem(
1718
+ value: m['user_id'].toString(),
1719
+ child: Text(
1720
+ m['display_name']?.toString() ?? 'والد')))
1721
+ .toList(),
1722
+ onChanged:
1723
+ busy ? null : (v) => setState(() => guardian = v)),
1724
+ DropdownButtonFormField<String>(
1725
+ initialValue: minor,
1726
+ decoration: const InputDecoration(labelText: 'فرزند'),
1727
+ items: widget.members
1728
+ .where((m) => m['role'] == 'teen_minor')
1729
+ .map((m) => DropdownMenuItem(
1730
+ value: m['user_id'].toString(),
1731
+ child: Text(
1732
+ m['display_name']?.toString() ?? 'فرزند')))
1733
+ .toList(),
1734
+ onChanged:
1735
+ busy ? null : (v) => setState(() => minor = v)),
1736
+ const Text(
1737
+ 'ثبت رابطه فقط پس از بررسی مجوز سرور انجام میشود.'),
1738
+ ],
1739
+ if (error != null)
1740
+ Text(error!,
1741
+ style: TextStyle(
1742
+ color: Theme.of(context).colorScheme.error)),
1743
+ ]))),
1744
+ actions: [
1745
+ TextButton(
1746
+ onPressed: busy ? null : () => Navigator.pop(context, false),
1747
+ child: const Text('انصراف')),
1748
+ FilledButton(
1749
+ onPressed: busy
1750
+ ? null
1751
+ : invitationLink != null
1752
+ ? () => Navigator.pop(context, true)
1753
+ : save,
1754
+ child: Text(busy
1755
+ ? 'در حال ثبت...'
1756
+ : invitationLink != null
1757
+ ? 'بستن'
1758
+ : 'ذخیره'))
1759
+ ]));
1760
+}
apps/lifemate/lib/notification_delivery.dart
new
+25
@@ -0,0 +1,25 @@
1
+import 'api.dart';
2
+
3
+/// Delivery is replaceable; correctness never depends on FCM or an external SDK.
4
+abstract interface class NotificationDeliveryPort {
5
+ bool get supportsBackgroundPush;
6
+ Future<List<Map<String, dynamic>>> fetch();
7
+}
8
+
9
+class PollingInAppNotificationDelivery implements NotificationDeliveryPort {
10
+ PollingInAppNotificationDelivery(this.api);
11
+ final HttpIdentityApi api;
12
+ @override
13
+ bool get supportsBackgroundPush => false;
14
+ @override
15
+ Future<List<Map<String, dynamic>>> fetch() async {
16
+ final response = await api.requestJson('GET', '/v1/notification-outbox');
17
+ final entries = response['notifications'];
18
+ if (entries is! List) {
19
+ throw const ApiException(502, 'invalid_notification_response');
20
+ }
21
+ return entries
22
+ .map((entry) => Map<String, dynamic>.from(entry as Map))
23
+ .toList();
24
+ }
25
+}
apps/lifemate/lib/notifications_ui.dart
new
+99
@@ -0,0 +1,99 @@
1
+import 'dart:async';
2
+import 'package:flutter/material.dart';
3
+import 'api.dart';
4
+import 'notification_delivery.dart';
5
+
6
+class NotificationInboxPage extends StatefulWidget {
7
+ const NotificationInboxPage({super.key, required this.api, this.delivery});
8
+ final IdentityApi api;
9
+ final NotificationDeliveryPort? delivery;
10
+ @override
11
+ State<NotificationInboxPage> createState() => _NotificationInboxPageState();
12
+}
13
+
14
+class _NotificationInboxPageState extends State<NotificationInboxPage>
15
+ with WidgetsBindingObserver {
16
+ Timer? timer;
17
+ List<Map<String, dynamic>> items = [];
18
+ Object? error;
19
+ DateTime? refreshedAt;
20
+ bool loading = false;
21
+ late final NotificationDeliveryPort? delivery;
22
+ @override
23
+ void initState() {
24
+ super.initState();
25
+ delivery = widget.delivery ??
26
+ (widget.api is HttpIdentityApi
27
+ ? PollingInAppNotificationDelivery(widget.api as HttpIdentityApi)
28
+ : null);
29
+ WidgetsBinding.instance.addObserver(this);
30
+ reload();
31
+ timer = Timer.periodic(const Duration(seconds: 30), (_) => reload());
32
+ }
33
+
34
+ @override
35
+ void didChangeAppLifecycleState(AppLifecycleState state) {
36
+ timer?.cancel();
37
+ if (state == AppLifecycleState.resumed) {
38
+ reload();
39
+ timer = Timer.periodic(const Duration(seconds: 30), (_) => reload());
40
+ }
41
+ }
42
+
43
+ Future<void> reload() async {
44
+ if (loading) return;
45
+ setState(() => loading = true);
46
+ try {
47
+ if (delivery == null) {
48
+ throw const ApiException(503, 'notification_provider_unavailable');
49
+ }
50
+ final next = await delivery!.fetch();
51
+ if (!mounted) return;
52
+ setState(() {
53
+ items = next;
54
+ error = null;
55
+ refreshedAt = DateTime.now();
56
+ });
57
+ } catch (failure) {
58
+ if (mounted) setState(() => error = failure);
59
+ } finally {
60
+ if (mounted) setState(() => loading = false);
61
+ }
62
+ }
63
+
64
+ @override
65
+ void dispose() {
66
+ timer?.cancel();
67
+ WidgetsBinding.instance.removeObserver(this);
68
+ super.dispose();
69
+ }
70
+
71
+ @override
72
+ Widget build(BuildContext context) => Scaffold(
73
+ appBar: AppBar(title: const Text('یادآوریهای لایفگاید'), actions: [
74
+ IconButton(
75
+ onPressed: loading ? null : reload,
76
+ icon: const Icon(Icons.refresh))
77
+ ]),
78
+ body: ListView(padding: const EdgeInsets.all(16), children: [
79
+ const Text(
80
+ 'این یادآوریها هنگام باز بودن برنامه تازه میشوند. اعلان پسزمینه فعال نیست.'),
81
+ if (loading) const LinearProgressIndicator(),
82
+ if (error != null)
83
+ const Text(
84
+ 'تازهسازی انجام نشد؛ موارد زیر آخرین داده دریافتشدهاند، زنده نیستند.'),
85
+ if (refreshedAt != null)
86
+ Text('آخرین دریافت: ${refreshedAt!.toLocal()}'),
87
+ if (!loading && items.isEmpty) const Text('یادآوری دریافت نشده است.'),
88
+ ...items.map((item) {
89
+ final payload =
90
+ item['payload'] is Map ? item['payload'] as Map : const {};
91
+ return Card(
92
+ child: ListTile(
93
+ title:
94
+ Text(payload['title']?.toString() ?? 'یادآوری برنامه'),
95
+ subtitle: Text(item['created_at']?.toString() ?? '')));
96
+ }),
97
+ ]),
98
+ );
99
+}
apps/lifemate/lib/offline_store.dart
+385
-39
@@ -1,60 +1,406 @@
1
+import 'dart:async';
2
import 'dart:convert';
3
4
+import 'package:http/http.dart' as http;
5
import 'package:shared_preferences/shared_preferences.dart';
6
5
-class OfflineStore {
6
- OfflineStore._();
7
- static final OfflineStore instance = OfflineStore._();
7
+import 'api.dart';
8
+import 'local_write_guard.dart';
9
+
10
+bool isOfflineFailure(Object error) =>
11
+ error is TimeoutException ||
12
+ error is http.ClientException ||
13
+ (error is ApiException &&
14
+ error.statusCode == 0 &&
15
+ const {'network_unavailable', 'request_timeout'}.contains(error.code));
16
+
17
+/// One isolate's serialization, with native protection across Android engines.
18
+class OfflineSession {
19
+ Future<void>? _tail;
20
+ bool _uncertain = false;
21
+ final _guard = const LocalWriteGuard();
22
+ Future<void> available() async {
23
+ try {
24
+ if (!_uncertain) _uncertain = await _guard.getBlocked();
25
+ } catch (_) {
26
+ _uncertain = true;
27
+ }
28
+ if (_uncertain) {
29
+ throw const ApiException(500, 'local_storage_restart_required');
30
+ }
31
+ }
32
9
- static const _todayKey = 'phase3.today.cache';
10
- static const _plannerKey = 'phase3.planner.cache';
11
- static const _schoolKey = 'phase3.school.cache';
12
- static const _queueKey = 'phase3.sync.queue';
33
+ Future<T> run<T>(Future<T> Function() operation) {
34
+ final previous = _tail;
35
+ final release = Completer<void>();
36
+ _tail = release.future;
37
+ Future<T> execute() async {
38
+ if (previous != null) await previous;
39
+ try {
40
+ await available();
41
+ return await operation();
42
+ } finally {
43
+ if (identical(_tail, release.future)) _tail = null;
44
+ release.complete();
45
+ }
46
+ }
47
14
- Future<void> writeList(String key, List<Map<String, dynamic>> value) async {
15
- final prefs = await SharedPreferences.getInstance();
16
- await prefs.setString(key, jsonEncode(value));
48
+ return execute();
49
}
50
19
- Future<List<Map<String, dynamic>>> readList(String key) async {
20
- final prefs = await SharedPreferences.getInstance();
21
- final raw = prefs.getString(key);
22
- if (raw == null || raw.isEmpty) return [];
51
+ Future<void> write(
52
+ SharedPreferencesAsync prefs, String key, String raw) async {
53
try {
24
- final decoded = jsonDecode(raw) as List<dynamic>;
25
- return decoded
26
- .map((item) => Map<String, dynamic>.from(item as Map))
27
- .toList();
54
+ final token = await _guard.beginWrite();
55
+ await prefs.setString(key, raw);
56
+ await _guard.completeWrite(token);
57
} catch (_) {
29
- return [];
58
+ _uncertain = true;
59
+ throw const ApiException(500, 'local_storage_restart_required');
60
}
61
}
62
+}
63
33
- Future<void> cacheToday(List<Map<String, dynamic>> items) =>
34
- writeList(_todayKey, items);
35
- Future<List<Map<String, dynamic>>> readToday() => readList(_todayKey);
64
+/// Cache and pending queue scoped to authenticated server and user.
65
+/// Shared data and permissions remain server-authoritative.
66
+class OfflineStore {
67
+ OfflineStore.forNamespace(this.scope, {OfflineSession? session})
68
+ : _session = session ?? _processSession,
69
+ _generation = _generations[scope] ?? 0 {
70
+ if (scope.isEmpty || scope.length > 4096) {
71
+ throw ArgumentError('Invalid cache scope');
72
+ }
73
+ }
74
+ factory OfflineStore.forApi(IdentityApi api) {
75
+ if (api is HttpIdentityApi) {
76
+ final scope = api.cacheNamespace;
77
+ if (scope == null) {
78
+ throw const ApiException(401, 'authenticated_cache_required');
79
+ }
80
+ return OfflineStore.forNamespace(scope);
81
+ }
82
+ return OfflineStore.forNamespace('injected-api:${identityHashCode(api)}');
83
+ }
84
+ static final _processSession = OfflineSession();
85
+ static final _generations = <String, int>{};
86
+ final int _generation;
87
+ final OfflineSession _session;
88
+ final String scope;
89
+ String get _key =>
90
+ 'lifeguide.offline.v2.${base64Url.encode(utf8.encode(scope))}';
91
+ static Future<void> clearNamespace(String scope) {
92
+ // Invalidate old stores immediately, including futures waiting for the lock.
93
+ _generations[scope] = (_generations[scope] ?? 0) + 1;
94
+ final current = OfflineStore.forNamespace(scope);
95
+ return current._session.run(() => current._save(current._empty()));
96
+ }
97
37
- Future<void> cachePlanner(List<Map<String, dynamic>> items) =>
38
- writeList(_plannerKey, items);
39
- Future<List<Map<String, dynamic>>> readPlanner() => readList(_plannerKey);
98
+ void _checkGeneration() {
99
+ if ((_generations[scope] ?? 0) != _generation) {
100
+ throw const ApiException(401, 'cache_scope_closed');
101
+ }
102
+ }
103
41
- Future<void> cacheSchool(List<Map<String, dynamic>> items) =>
42
- writeList(_schoolKey, items);
43
- Future<List<Map<String, dynamic>>> readSchool() => readList(_schoolKey);
104
+ Map<String, dynamic> _empty() => {
105
+ 'version': 2,
106
+ 'scope': scope,
107
+ 'caches': <String, dynamic>{},
108
+ 'queue': <dynamic>[],
109
+ 'lastSyncAt': null,
110
+ 'lastAckAt': null
111
+ };
112
+ Future<Map<String, dynamic>> _read() async {
113
+ _checkGeneration();
114
+ final String? raw;
115
+ try {
116
+ raw = await SharedPreferencesAsync().getString(_key);
117
+ } catch (_) {
118
+ throw const ApiException(500, 'local_storage_failed');
119
+ }
120
+ await _session.available();
121
+ _checkGeneration();
122
+ if (raw == null) return _empty();
123
+ try {
124
+ final doc = jsonDecode(raw) as Map<String, dynamic>;
125
+ if (doc['version'] != 2 ||
126
+ doc['scope'] != scope ||
127
+ doc['caches'] is! Map ||
128
+ doc['queue'] is! List) {
129
+ throw const FormatException();
130
+ }
131
+ for (final entry in doc['queue'] as List) {
132
+ if (entry is! Map ||
133
+ entry['id'] is! String ||
134
+ entry['payload'] is! Map ||
135
+ entry['entityId'] is! String) {
136
+ throw const FormatException();
137
+ }
138
+ }
139
+ return doc;
140
+ } catch (_) {
141
+ throw const ApiException(500, 'local_data_corrupt');
142
+ }
143
+ }
144
45
- Future<List<Map<String, dynamic>>> readQueue() => readList(_queueKey);
145
+ Future<void> _save(Map<String, dynamic> doc) async {
146
+ _checkGeneration();
147
+ final raw = jsonEncode(doc);
148
+ if (utf8.encode(raw).length > 2 * 1024 * 1024 ||
149
+ (doc['queue'] as List).length > 100) {
150
+ throw const ApiException(413, 'offline_capacity_exceeded');
151
+ }
152
+ await _session.write(SharedPreferencesAsync(), _key, raw);
153
+ }
154
47
- Future<void> enqueue(Map<String, dynamic> mutation) async {
48
- final queue = await readQueue();
49
- queue.add(mutation);
50
- await writeList(_queueKey, queue);
155
+ Future<T> _mutate<T>(T Function(Map<String, dynamic>) change) =>
156
+ _session.run(() async {
157
+ final doc = await _read();
158
+ final result = change(doc);
159
+ await _save(doc);
160
+ return result;
161
+ });
162
+ Future<void> writeList(String key, List<Map<String, dynamic>> value) =>
163
+ _mutate((doc) {
164
+ (doc['caches'] as Map)[key] = key == 'planner' || key == 'today'
165
+ ? _overlayPending(doc, value, todayOnly: key == 'today')
166
+ : value;
167
+ doc['lastSyncAt'] = DateTime.now().toUtc().toIso8601String();
168
+ });
169
+ Future<List<Map<String, dynamic>>> readList(String key) =>
170
+ _session.run(() async {
171
+ final doc = await _read();
172
+ final list = (doc['caches'] as Map)[key] as List? ?? [];
173
+ return list
174
+ .map((item) => Map<String, dynamic>.from(item as Map))
175
+ .toList();
176
+ });
177
+ Future<void> cacheToday(List<Map<String, dynamic>> items) =>
178
+ writeList('today', items);
179
+ Future<List<Map<String, dynamic>>> readToday() => readList('today');
180
+ Future<void> cachePlanner(List<Map<String, dynamic>> items) =>
181
+ writeList('planner', items);
182
+ Future<List<Map<String, dynamic>>> readPlanner() => readList('planner');
183
+ Future<void> cacheSchool(List<Map<String, dynamic>> items) =>
184
+ writeList('school', items);
185
+ Future<List<Map<String, dynamic>>> readSchool() => readList('school');
186
+ Future<List<Map<String, dynamic>>> readQueue() =>
187
+ _session.run(() async => ((await _read())['queue'] as List)
188
+ .map((m) => Map<String, dynamic>.from(m as Map))
189
+ .toList());
190
+ Future<int> pendingCount() async => (await readQueue()).length;
191
+ Future<DateTime?> _timestamp(String field) => _session.run(
192
+ () async => DateTime.tryParse((await _read())[field] as String? ?? ''));
193
+ Future<DateTime?> readLastSync() => _timestamp('lastSyncAt');
194
+ Future<DateTime?> readLastAck() => _timestamp('lastAckAt');
195
+ Future<void> enqueue(Map<String, dynamic> mutation,
196
+ {Map<String, dynamic>? optimisticItem}) =>
197
+ _mutate((doc) {
198
+ final id = mutation['id'];
199
+ if (id is! String ||
200
+ !RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$')
201
+ .hasMatch(id) ||
202
+ mutation['entityId'] is! String ||
203
+ mutation['payload'] is! Map) {
204
+ throw const ApiException(400, 'invalid_offline_mutation');
205
+ }
206
+ final queue = doc['queue'] as List;
207
+ final existing = queue.where((m) => (m as Map)['id'] == id);
208
+ if (existing.isNotEmpty) {
209
+ final prior = Map<String, dynamic>.from(existing.single as Map)
210
+ ..remove('queueStatus')
211
+ ..remove('queuedAt')
212
+ ..remove('lastError');
213
+ if (jsonEncode(prior) != jsonEncode(mutation)) {
214
+ throw const ApiException(409, 'mutation_id_reused');
215
+ }
216
+ return;
217
+ }
218
+ queue.add({
219
+ ...mutation,
220
+ 'queueStatus': 'queued',
221
+ 'queuedAt': DateTime.now().toUtc().toIso8601String()
222
+ });
223
+ if (optimisticItem != null) _saveOptimistic(doc, optimisticItem);
224
+ });
225
+ Future<void> markQueued(String id, String status, {String? error}) =>
226
+ _mutate((doc) {
227
+ for (final entry in doc['queue'] as List) {
228
+ if ((entry as Map)['id'] == id) {
229
+ entry['queueStatus'] = status;
230
+ entry['lastError'] = error;
231
+ }
232
+ }
233
+ });
234
+ Future<void> removeQueued(Set<String> ids) => _mutate((doc) {
235
+ doc['queue'] = (doc['queue'] as List)
236
+ .where((m) => !ids.contains((m as Map)['id']))
237
+ .toList();
238
+ });
239
+ Future<void> acknowledge(String id,
240
+ {Map<String, dynamic>? item, String? acceptedAt, String? cacheKey}) =>
241
+ _mutate((doc) {
242
+ doc['queue'] = (doc['queue'] as List)
243
+ .where((m) => (m as Map)['id'] != id)
244
+ .toList();
245
+ doc['lastAckAt'] =
246
+ acceptedAt ?? DateTime.now().toUtc().toIso8601String();
247
+ if (item != null) {
248
+ for (final key
249
+ in cacheKey == null ? ['planner', 'today'] : [cacheKey]) {
250
+ final list = (doc['caches'] as Map)[key] as List? ?? [];
251
+ final index =
252
+ list.indexWhere((x) => (x as Map)['id'] == item['id']);
253
+ if (index >= 0) {
254
+ list[index] = item;
255
+ } else if (key != 'today') {
256
+ list.add(item);
257
+ }
258
+ (doc['caches'] as Map)[key] = key == 'planner' || key == 'today'
259
+ ? _overlayPending(
260
+ doc,
261
+ list
262
+ .map((x) => Map<String, dynamic>.from(x as Map))
263
+ .toList(),
264
+ todayOnly: key == 'today')
265
+ : list;
266
+ }
267
+ }
268
+ });
269
+ void _saveOptimistic(Map<String, dynamic> doc, Map<String, dynamic> item) {
270
+ final list = (doc['caches'] as Map)['planner'] as List? ?? [];
271
+ final index = list.indexWhere((x) => (x as Map)['id'] == item['id']);
272
+ if (index >= 0) {
273
+ list[index] = item;
274
+ } else {
275
+ list.add(item);
276
+ }
277
+ (doc['caches'] as Map)['planner'] = list;
278
}
279
53
- Future<void> removeQueued(Set<String> ids) async {
54
- final queue = await readQueue();
55
- await writeList(
56
- _queueKey,
57
- queue.where((item) => !ids.contains(item['id']?.toString())).toList(),
58
- );
280
+ Future<void> saveOptimisticItem(Map<String, dynamic> item) =>
281
+ _mutate((doc) => _saveOptimistic(doc, item));
282
+ List<Map<String, dynamic>> _overlayPending(
283
+ Map<String, dynamic> doc, List<Map<String, dynamic>> items,
284
+ {bool todayOnly = false}) {
285
+ final result = items.map((x) => Map<String, dynamic>.from(x)).toList();
286
+ final prior = ((doc['caches'] as Map)['planner'] as List? ?? [])
287
+ .map((x) => Map<String, dynamic>.from(x as Map));
288
+ for (final raw in doc['queue'] as List) {
289
+ final mutation = raw as Map;
290
+ if (mutation['entityType'] != 'plan_item' ||
291
+ mutation['queueStatus'] == 'rejected') {
292
+ continue;
293
+ }
294
+ final id = mutation['entityId'];
295
+ final index = result.indexWhere((x) => x['id'] == id);
296
+ final old = prior.where((x) => x['id'] == id).firstOrNull;
297
+ final base =
298
+ index < 0 ? old ?? <String, dynamic>{'id': id} : result[index];
299
+ final overlay = optimisticPlanItem(base, mutation);
300
+ if (todayOnly && index < 0) {
301
+ final date = DateTime.tryParse(
302
+ (overlay['due_at'] ?? overlay['starts_at'] ?? '').toString());
303
+ final now = DateTime.now();
304
+ if (date == null ||
305
+ date.toLocal().year != now.year ||
306
+ date.toLocal().month != now.month ||
307
+ date.toLocal().day != now.day) {
308
+ continue;
309
+ }
310
+ }
311
+ if (index < 0) {
312
+ result.add(overlay);
313
+ } else {
314
+ result[index] = overlay;
315
+ }
316
+ }
317
+ return result;
318
}
319
+
320
+ Future<void> clear() => clearNamespace(scope);
321
+
322
+ Future<List<Map<String, dynamic>>> readDiscardedChanges() =>
323
+ _session.run(() async {
324
+ final journal = (await _read())['discardedChanges'];
325
+ if (journal == null) return [];
326
+ if (journal is! List ||
327
+ journal.any((m) => m is! Map || m['payload'] is! Map)) {
328
+ throw const ApiException(500, 'local_data_corrupt');
329
+ }
330
+ return journal.map((m) => Map<String, dynamic>.from(m as Map)).toList();
331
+ });
332
+
333
+ Future<void> discardEntityChanges(String entityId,
334
+ {Map<String, dynamic>? serverItem, String? cacheKey}) =>
335
+ _mutate((doc) {
336
+ if (serverItem != null &&
337
+ (serverItem['id'] != entityId ||
338
+ int.tryParse(serverItem['version'].toString()) == null)) {
339
+ throw const ApiException(400, 'invalid_server_item');
340
+ }
341
+ final rawJournal = doc['discardedChanges'];
342
+ if (rawJournal != null && rawJournal is! List) {
343
+ throw const ApiException(500, 'local_data_corrupt');
344
+ }
345
+ final queue = doc['queue'] as List;
346
+ final removed =
347
+ queue.where((m) => (m as Map)['entityId'] == entityId).toList();
348
+ if (removed.isEmpty) return;
349
+ final title = removed.reversed
350
+ .map((m) => (m as Map)['payload'] as Map)
351
+ .map((p) => p['title'])
352
+ .whereType<String>()
353
+ .firstOrNull;
354
+ final discardedAt = DateTime.now().toUtc().toIso8601String();
355
+ doc['discardedChanges'] = [
356
+ ...?rawJournal as List?,
357
+ for (final mutation in removed)
358
+ {
359
+ ...mutation as Map,
360
+ 'discardedAt': discardedAt,
361
+ 'recoveryTitle': title
362
+ }
363
+ ];
364
+ doc['queue'] =
365
+ queue.where((m) => (m as Map)['entityId'] != entityId).toList();
366
+ for (final key
367
+ in cacheKey == null ? ['planner', 'today'] : [cacheKey]) {
368
+ final list = (doc['caches'] as Map)[key] as List? ?? [];
369
+ final hadItem = list.any((m) => (m as Map)['id'] == entityId);
370
+ final replacement =
371
+ list.where((m) => (m as Map)['id'] != entityId).toList();
372
+ if (serverItem != null && (key != 'today' || hadItem)) {
373
+ replacement.add(Map<String, dynamic>.from(serverItem));
374
+ }
375
+ (doc['caches'] as Map)[key] = replacement;
376
+ }
377
+ });
378
+}
379
+
380
+Map<String, dynamic> optimisticPlanItem(
381
+ Map<String, dynamic> base, Map mutation) {
382
+ final payload = Map<String, dynamic>.from(mutation['payload'] as Map);
383
+ const columns = {
384
+ 'subjectId': 'subject_id',
385
+ 'durationMinutes': 'duration_minutes',
386
+ 'gradePoints': 'grade_points',
387
+ 'gradeOutOf': 'grade_out_of',
388
+ 'parentItemId': 'parent_item_id',
389
+ 'dueAt': 'due_at',
390
+ 'startsAt': 'starts_at',
391
+ 'endsAt': 'ends_at',
392
+ 'familyId': 'family_id',
393
+ 'schoolSubjectId': 'school_subject_id',
394
+ 'plannedDurationSeconds': 'planned_duration_seconds'
395
+ };
396
+ final expected = int.tryParse(mutation['expectedVersion'].toString()) ?? 0;
397
+ return {
398
+ ...base,
399
+ for (final entry in payload.entries)
400
+ columns[entry.key] ?? entry.key: entry.value,
401
+ 'version': mutation['operation'] == 'create' ? 1 : expected + 1,
402
+ 'pending_sync': true,
403
+ 'acknowledged': false,
404
+ 'sync_conflict': mutation['queueStatus'] == 'conflict'
405
+ };
406
}
apps/lifemate/lib/phase3_ui.dart
+803
-725
@@ -1,412 +1,754 @@
1
-// ignore_for_file: prefer_interpolation_to_compose_strings, curly_braces_in_flow_control_structures, use_build_context_synchronously
2
-
3
-import 'dart:math';
1
+import 'dart:async';
2
import 'package:flutter/material.dart';
3
import 'api.dart';
4
import 'offline_store.dart';
5
+import 'plan_sync.dart';
6
+import 'study_ui.dart';
7
+import 'dashboard_ui.dart';
8
+
9
+String faKind(String kind) => switch (kind) {
10
+ 'assignment' => 'تکلیف',
11
+ 'exam' => 'امتحان',
12
+ 'study_session' => 'مطالعه',
13
+ 'event' => 'رویداد',
14
+ 'routine' => 'روتین',
15
+ 'goal' => 'هدف',
16
+ _ => 'کار',
17
+ };
18
+DateTime? parseDate(dynamic value) =>
19
+ value == null ? null : DateTime.tryParse(value.toString())?.toLocal();
20
+String shortDate(dynamic value) {
21
+ final d = parseDate(value);
22
+ return d == null
23
+ ? ''
24
+ : '${d.month}/${d.day} · ${d.hour}:${d.minute.toString().padLeft(2, '0')}';
25
+}
26
8
-String faKind(String kind) {
9
- switch (kind) {
10
- case 'assignment': return 'تکلیف';
11
- case 'exam': return 'امتحان';
12
- case 'study_session': return 'مطالعه';
13
- case 'event': return 'رویداد';
14
- case 'routine': return 'روتین';
15
- case 'goal': return 'هدف';
16
- default: return 'کار';
27
+String uiErrorText(Object error) {
28
+ if (error is ApiException) {
29
+ if (error.code == 'local_storage_restart_required') {
30
+ return 'وضعیت ذخیره نامشخص است. برنامه را از تنظیمات دستگاه «توقف اجباری» کن و دوباره باز کن.';
31
+ }
32
+ if (error.code == 'local_storage_failed' ||
33
+ error.code == 'local_data_corrupt') {
34
+ return 'خواندن یا ذخیره داده دستگاه انجام نشد. تغییر تأیید نشده است.';
35
+ }
36
+ if (error.statusCode == 401) return 'نشست ورود معتبر نیست. دوباره وارد شو.';
37
+ if (error.statusCode == 403) {
38
+ return 'برای این اطلاعات یا عملیات دسترسی نداری.';
39
+ }
40
+ if (error.code == 'sync_conflict' || error.code == 'version_conflict') {
41
+ return 'نسخه داده تغییر کرده است. تغییر معلق نگه داشته شد؛ ابتدا اطلاعات سرور را بررسی کن.';
42
+ }
43
+ if (error.code == 'sync_pending') {
44
+ return 'تغییر قبلی هنوز تأیید نشده است. ابتدا همگامسازی را دوباره امتحان کن.';
45
+ }
46
+ if (error.code == 'sms_unavailable') {
47
+ return 'سرویس پیامک فعال نیست. ارسال کد تأیید نشده است.';
48
+ }
49
+ if (error.code == 'invalid_or_expired_otp') {
50
+ return 'کد معتبر نیست یا منقضی شده است.';
51
+ }
52
+ if (error.code == 'rate_limited') {
53
+ return 'درخواستها زیاد است. کمی صبر کن و دوباره تلاش کن.';
54
+ }
55
+ if (error.statusCode >= 500) {
56
+ return 'سرور پاسخ معتبر نداد. اطلاعات تازه دریافت نشده است.';
57
+ }
58
}
59
+ if (isOfflineFailure(error)) {
60
+ return 'اتصال برقرار نیست. اطلاعات تازه دریافت نشده است.';
61
+ }
62
+ return 'عملیات انجام نشد. دوباره تلاش کن.';
63
}
64
20
-DateTime? parseDate(dynamic value) {
21
- if (value == null) return null;
22
- return DateTime.tryParse(value.toString())?.toLocal();
65
+Future<List<Map<String, dynamic>>> ownedPlanFallback(
66
+ IdentityApi api, OfflineStore store,
67
+ {required bool today}) async {
68
+ final rows = today ? await store.readToday() : await store.readPlanner();
69
+ if (api is! HttpIdentityApi) return rows;
70
+ final userId = api.currentUserId;
71
+ if (userId == null) {
72
+ throw const ApiException(401, 'authenticated_cache_required');
73
+ }
74
+ // Only locally generated creates can establish ownership before an ACK.
75
+ final ownPending = (await store.readQueue())
76
+ .where((m) =>
77
+ m['entityType'] == 'plan_item' &&
78
+ m['operation'] == 'create' &&
79
+ m['queueStatus'] != 'rejected')
80
+ .map((m) => m['entityId'])
81
+ .toSet();
82
+ return rows
83
+ .where((row) =>
84
+ row['owner_user_id'] == userId ||
85
+ row['ownerUserId'] == userId ||
86
+ ownPending.contains(row['id']))
87
+ .toList();
88
}
89
25
-String shortDate(dynamic value) {
26
- final d = parseDate(value);
27
- if (d == null) return '';
28
- final minute = d.minute.toString().padLeft(2, '0');
29
- return d.month.toString() + '/' + d.day.toString() + ' · ' +
30
- d.hour.toString() + ':' + minute;
90
+String numberInput(String value) {
91
+ const digits = '۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩';
92
+ return value
93
+ .trim()
94
+ .split('')
95
+ .map((c) {
96
+ final i = digits.indexOf(c);
97
+ return i < 0 ? c : (i % 10).toString();
98
+ })
99
+ .join()
100
+ .replaceAll('٫', '.')
101
+ .replaceAll('٬', '');
102
}
103
104
class Phase3HomeContent extends StatelessWidget {
34
- const Phase3HomeContent({
35
- super.key,
36
- required this.api,
37
- required this.page,
38
- required this.adultShell,
39
- });
105
+ const Phase3HomeContent(
106
+ {super.key,
107
+ required this.api,
108
+ required this.page,
109
+ required this.adultShell});
110
final IdentityApi api;
111
final String page;
112
final bool adultShell;
43
-
113
@override
114
Widget build(BuildContext context) {
115
if (page == 'امروز') return TodayPage(api: api);
47
- if (page == 'برنامهریز' || page == 'برنامه هفتگی' || page == 'تقویم' || page == 'تکالیف و کارها') {
116
+ if (['برنامهریز', 'برنامه هفتگی', 'تقویم', 'تکالیف و کارها']
117
+ .contains(page)) {
118
return PlannerPage(api: api);
119
}
120
if (page == 'خانواده') return ParentFamilyDashboard(api: api);
121
+ if (page == 'تمرکز') return StudyHub(api: api);
122
if (page == 'امتحانها و نمرات') return SchoolPage(api: api);
52
- if (page == 'تمرکز') {
53
- return const CoreNotice(
54
- title: 'تمرکز',
55
- subtitle: 'جلسه مطالعه در برنامهریز فعال است؛ تایمر پیشرفته در فاز بعد اضافه میشود.',
56
- );
57
- }
58
- if (page == 'همراه هوشمند' || page == 'راهنما') {
59
- return const CoreNotice(
60
- title: 'راهنمای هوشمند',
61
- subtitle: 'هسته برنامهریزی این فاز مستقل از AI است و راهنمای هوشمند در فاز ۴ فعال میشود.',
62
- );
63
- }
64
- return SchoolPage(api: api);
123
+ return const CoreNotice(
124
+ title: 'لایفگاید', subtitle: 'این بخش در این مرحله فعال نیست.');
125
}
126
}
127
128
class CoreNotice extends StatelessWidget {
129
const CoreNotice({super.key, required this.title, required this.subtitle});
70
- final String title;
71
- final String subtitle;
130
+ final String title, subtitle;
131
@override
132
Widget build(BuildContext context) => Center(
74
- child: Card(
133
+ child: Card(
134
margin: const EdgeInsets.all(20),
135
child: Padding(
77
- padding: const EdgeInsets.all(24),
78
- child: Column(mainAxisSize: MainAxisSize.min, children: [
79
- Text(title, style: Theme.of(context).textTheme.headlineSmall),
80
- const SizedBox(height: 8),
81
- Text(subtitle, textAlign: TextAlign.center),
82
- ]),
83
- ),
84
- ),
85
- );
136
+ padding: const EdgeInsets.all(24),
137
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
138
+ Text(title, style: Theme.of(context).textTheme.headlineSmall),
139
+ const SizedBox(height: 8),
140
+ Text(subtitle, textAlign: TextAlign.center)
141
+ ]))));
142
+}
143
+
144
+class LoadError extends StatelessWidget {
145
+ const LoadError({super.key, required this.error, required this.retry});
146
+ final Object error;
147
+ final VoidCallback retry;
148
+ @override
149
+ Widget build(BuildContext context) => Center(
150
+ child: Padding(
151
+ padding: const EdgeInsets.all(20),
152
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
153
+ Text(uiErrorText(error), textAlign: TextAlign.center),
154
+ TextButton(onPressed: retry, child: const Text('تلاش دوباره'))
155
+ ])));
156
+}
157
+
158
+class SyncNotice extends StatelessWidget {
159
+ const SyncNotice(
160
+ {super.key, required this.offline, required this.pending, this.syncedAt});
161
+ final bool offline;
162
+ final int pending;
163
+ final DateTime? syncedAt;
164
+ @override
165
+ Widget build(BuildContext context) => Card(
166
+ child: ListTile(
167
+ leading: Icon(
168
+ offline ? Icons.cloud_off_outlined : Icons.cloud_done_outlined),
169
+ title: Text(offline
170
+ ? 'نسخه ذخیرهشده؛ داده زنده نیست'
171
+ : 'آخرین دریافت از سرور'),
172
+ subtitle: Text(
173
+ '${syncedAt == null ? 'زمان دریافت نامشخص' : shortDate(syncedAt!.toIso8601String())}${pending > 0 ? '\n$pending تغییر در انتظار تأیید سرور' : ''}')));
174
}
175
88
-class TodayPage extends StatefulWidget {
176
+class TodayPage extends StatelessWidget {
177
const TodayPage({super.key, required this.api});
178
final IdentityApi api;
179
@override
92
- State<TodayPage> createState() => _TodayPageState();
180
+ Widget build(BuildContext context) => _PlanList(api: api, today: true);
181
+}
182
+
183
+class PlannerPage extends StatelessWidget {
184
+ const PlannerPage({super.key, required this.api});
185
+ final IdentityApi api;
186
+ @override
187
+ Widget build(BuildContext context) => _PlanList(api: api, today: false);
188
+}
189
+
190
+class _PlanList extends StatefulWidget {
191
+ const _PlanList({required this.api, required this.today});
192
+ final IdentityApi api;
193
+ final bool today;
194
+ @override
195
+ State<_PlanList> createState() => _PlanListState();
196
}
197
95
-class _TodayPageState extends State<TodayPage> {
198
+class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
199
late Future<LoadResult> future;
200
+ Timer? poll;
201
+ bool loading = false;
202
+ String? busyId;
203
+ String? operationError;
204
@override
205
void initState() {
206
super.initState();
207
+ WidgetsBinding.instance.addObserver(this);
208
future = load();
209
+ startPoll();
210
+ }
211
+
212
+ void startPoll() {
213
+ poll?.cancel();
214
+ poll = Timer.periodic(const Duration(seconds: 15), (_) {
215
+ if (!loading && busyId == null) reload();
216
+ });
217
+ }
218
+
219
+ @override
220
+ void didChangeAppLifecycleState(AppLifecycleState state) {
221
+ if (state == AppLifecycleState.resumed) {
222
+ startPoll();
223
+ reload();
224
+ } else {
225
+ poll?.cancel();
226
+ }
227
+ }
228
+
229
+ @override
230
+ void dispose() {
231
+ poll?.cancel();
232
+ WidgetsBinding.instance.removeObserver(this);
233
+ super.dispose();
234
}
235
236
Future<LoadResult> load() async {
104
- final now = DateTime.now();
105
- final from = DateTime(now.year, now.month, now.day);
106
- final to = from.add(const Duration(days: 1));
237
+ loading = true;
238
try {
108
- final items = await widget.api.getToday(from: from, to: to);
109
- final reminders = await widget.api.claimDueReminders();
110
- await OfflineStore.instance.cacheToday(items);
111
- return LoadResult(items, false, reminders: reminders);
112
- } catch (_) {
113
- return LoadResult(await OfflineStore.instance.readToday(), true);
239
+ final store = OfflineStore.forApi(widget.api);
240
+ await PlanSync(widget.api, store: store).flush();
241
+ final now = DateTime.now();
242
+ final from = DateTime(now.year, now.month, now.day);
243
+ final to = from.add(const Duration(days: 1));
244
+ List<Map<String, dynamic>> items;
245
+ var reminders = <Map<String, dynamic>>[];
246
+ bool offline = false;
247
+ try {
248
+ items = widget.today
249
+ ? await widget.api.getToday(from: from, to: to)
250
+ : await widget.api.listPlanItems();
251
+ if (widget.today) reminders = await widget.api.claimDueReminders();
252
+ // The store merges queued mutations atomically with each fresh cache.
253
+ if (widget.today) {
254
+ await store.cacheToday(items);
255
+ items = await store.readToday();
256
+ } else {
257
+ await store.cachePlanner(items);
258
+ items = await store.readPlanner();
259
+ }
260
+ } catch (error) {
261
+ if (!isOfflineFailure(error)) rethrow;
262
+ offline = true;
263
+ items = await ownedPlanFallback(widget.api, store, today: widget.today);
264
+ }
265
+ return LoadResult(
266
+ items.where((i) => i['status'] != 'cancelled').toList(), offline,
267
+ pending: await store.pendingCount(),
268
+ syncedAt: await store.readLastSync(),
269
+ reminders: reminders);
270
+ } finally {
271
+ loading = false;
272
}
273
}
274
117
- Future<void> refresh() async {
118
- setState(() => future = load());
119
- await future;
275
+ Future<void> reload() async {
276
+ if (!mounted) return;
277
+ setState(() {
278
+ future = load();
279
+ });
280
+ try {
281
+ await future;
282
+ } catch (_) {/* FutureBuilder renders the error. */}
283
}
284
122
- Future<void> complete(Map<String, dynamic> item) async {
285
+ Future<void> edit([Map<String, dynamic>? item]) async {
286
+ final outcome = await showDialog<MutationOutcome>(
287
+ context: context,
288
+ builder: (_) => PlanItemDialog(api: widget.api, item: item));
289
+ if (outcome != null && mounted) {
290
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
291
+ content: Text(outcome.queued
292
+ ? 'تغییر روی دستگاه ثبت شد؛ در انتظار تأیید سرور.'
293
+ : 'تغییر توسط سرور تأیید شد.')));
294
+ await reload();
295
+ }
296
+ }
297
+
298
+ Future<void> action(Map<String, dynamic> item, String action) async {
299
+ if (busyId != null) return;
300
+ if (action == 'edit') {
301
+ await edit(item);
302
+ return;
303
+ }
304
+ if (action == 'study') {
305
+ if (item['pending_sync'] == true) {
306
+ setState(() => operationError =
307
+ 'تکلیف هنوز در سرور تأیید نشده است؛ تایمر پس از همگامسازی فعال میشود.');
308
+ return;
309
+ }
310
+ if (widget.api is! HttpIdentityApi) {
311
+ setState(() => operationError = 'اتصال مطالعه در دسترس نیست.');
312
+ return;
313
+ }
314
+ await Navigator.of(context).push(MaterialPageRoute(
315
+ builder: (_) =>
316
+ StudyTimerPage(api: widget.api as HttpIdentityApi, item: item)));
317
+ if (mounted) await reload();
318
+ return;
319
+ }
320
+ if (action == 'archive') {
321
+ final confirmed = await showDialog<bool>(
322
+ context: context,
323
+ builder: (c) => AlertDialog(
324
+ title: const Text('بایگانی مورد'),
325
+ content: Text('«${item['title']}» بایگانی شود؟'),
326
+ actions: [
327
+ TextButton(
328
+ onPressed: () => Navigator.pop(c, false),
329
+ child: const Text('انصراف')),
330
+ FilledButton(
331
+ onPressed: () => Navigator.pop(c, true),
332
+ child: const Text('بایگانی'))
333
+ ]));
334
+ if (confirmed != true || !mounted) return;
335
+ }
336
+ setState(() {
337
+ busyId = item['id'].toString();
338
+ operationError = null;
339
+ });
340
try {
124
- await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
125
- await refresh();
126
- } catch (_) {
127
- await OfflineStore.instance.enqueue({
128
- 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
129
- 'entityType': 'plan_item',
130
- 'entityId': item['id'],
131
- 'operation': 'complete',
132
- 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
133
- 'payload': {'status': 'completed'},
134
- });
341
+ final sync = PlanSync(widget.api);
342
+ final outcome = action == 'archive'
343
+ ? await sync.archive(item)
344
+ : await sync.complete(item);
345
if (mounted) {
136
- ScaffoldMessenger.of(context).showSnackBar(
137
- const SnackBar(content: Text('آفلاین هستی؛ تغییر برای همگامسازی ذخیره شد.')),
138
- );
346
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
347
+ content: Text(outcome.queued
348
+ ? 'تغییر در انتظار تأیید سرور است.'
349
+ : 'سرور تغییر را تأیید کرد.')));
350
+ await reload();
351
}
352
+ } catch (error) {
353
+ if (mounted) setState(() => operationError = uiErrorText(error));
354
+ } finally {
355
+ if (mounted) setState(() => busyId = null);
356
}
357
}
358
359
@override
360
Widget build(BuildContext context) => FutureBuilder<LoadResult>(
145
- future: future,
146
- builder: (context, snapshot) {
147
- if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
148
- final result = snapshot.data!;
149
- return RefreshIndicator(
150
- onRefresh: refresh,
151
- child: ListView(
152
- padding: const EdgeInsets.all(16),
153
- children: [
154
- if (result.offline)
155
- const Card(child: ListTile(
156
- leading: Icon(Icons.cloud_off_outlined),
157
- title: Text('نمایش نسخه آفلاین'),
158
- )),
159
- if (result.reminders.isNotEmpty)
160
- ...result.reminders.map((reminder) => Card(
161
- child: ListTile(
361
+ future: future,
362
+ builder: (context, s) {
363
+ if (s.hasError) return LoadError(error: s.error!, retry: reload);
364
+ if (!s.hasData) return const Center(child: CircularProgressIndicator());
365
+ final data = s.data!;
366
+ return RefreshIndicator(
367
+ onRefresh: reload,
368
+ child: ListView(padding: const EdgeInsets.all(16), children: [
369
+ ...data.reminders.map((r) => Card(
370
+ child: ListTile(
371
leading: const Icon(Icons.notifications_active_outlined),
163
- title: Text('یادآوری · ' + (reminder['title']?.toString() ?? 'برنامه')),
164
- subtitle: const Text('زمان این مورد رسیده یا نزدیک است.'),
165
- ),
166
- )),
372
+ title: Text('یادآوری · ${r['title'] ?? 'برنامه'}'),
373
+ subtitle:
374
+ const Text('موعد این مورد رسیده یا نزدیک است.')))),
375
+ SyncNotice(
376
+ offline: data.offline,
377
+ pending: data.pending,
378
+ syncedAt: data.syncedAt),
379
+ if (operationError != null)
380
Card(
168
- child: Padding(
169
- padding: const EdgeInsets.all(18),
170
- child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
171
- Text('امروز', style: Theme.of(context).textTheme.headlineSmall),
172
- const SizedBox(height: 6),
173
- Text(result.items.length.toString() + ' مورد در برنامه امروز'),
174
- ]),
175
- ),
176
- ),
177
- const SizedBox(height: 8),
178
- if (result.items.isEmpty)
179
- const EmptyCard(
180
- icon: Icons.check_circle_outline,
181
- title: 'امروز خلوت است',
182
- subtitle: 'از برنامهریز یک کار، رویداد یا جلسه مطالعه اضافه کن.',
183
- )
184
- else
185
- ...result.items.map((item) => Card(
186
- child: ListTile(
187
- leading: const Icon(Icons.radio_button_unchecked),
188
- title: Text(item['title']?.toString() ?? ''),
189
- subtitle: Text(
190
- faKind(item['kind']?.toString() ?? 'task') +
191
- (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
192
- ),
193
- trailing: IconButton(
194
- onPressed: () => complete(item),
195
- icon: const Icon(Icons.check_circle_outline),
196
- ),
197
- ),
198
- )),
199
- ],
200
- ),
201
- );
202
- },
203
- );
381
+ child: Padding(
382
+ padding: const EdgeInsets.all(12),
383
+ child: Text(operationError!,
384
+ style: TextStyle(
385
+ color: Theme.of(context).colorScheme.error)))),
386
+ Row(children: [
387
+ Expanded(
388
+ child: Text(widget.today ? 'امروز' : 'برنامهریز',
389
+ style: Theme.of(context).textTheme.headlineSmall)),
390
+ if (!widget.today)
391
+ FilledButton.icon(
392
+ onPressed: busyId == null ? () => edit() : null,
393
+ icon: const Icon(Icons.add),
394
+ label: const Text('جدید'))
395
+ ]),
396
+ if (data.items.isEmpty)
397
+ const EmptyCard(
398
+ icon: Icons.task_alt,
399
+ title: 'موردی در این برنامه نیست',
400
+ subtitle: 'از برنامهریز کار یا تکلیف جدید اضافه کن.'),
401
+ ...data.items.map((item) => Card(
402
+ child: ListTile(
403
+ leading: Icon(item['status'] == 'completed'
404
+ ? Icons.check_circle_outline
405
+ : Icons.radio_button_unchecked),
406
+ title: Text(item['title']?.toString() ?? ''),
407
+ subtitle: Text(
408
+ '${faKind(item['kind']?.toString() ?? 'task')} · ${shortDate(item['startsAt'] ?? item['starts_at'] ?? item['dueAt'] ?? item['due_at'])}${item['pending_sync'] == true ? '\nدر انتظار تأیید سرور' : ''}'),
409
+ trailing: busyId == item['id']
410
+ ? const SizedBox(
411
+ width: 24,
412
+ height: 24,
413
+ child: CircularProgressIndicator())
414
+ : PopupMenuButton<String>(
415
+ onSelected: (v) => action(item, v),
416
+ itemBuilder: (_) => [
417
+ const PopupMenuItem(
418
+ value: 'edit', child: Text('ویرایش')),
419
+ const PopupMenuItem(
420
+ value: 'complete',
421
+ child: Text('انجام شد')),
422
+ if (item['pending_sync'] != true &&
423
+ widget.api is HttpIdentityApi &&
424
+ ['assignment', 'task', 'study_session']
425
+ .contains(item['kind']))
426
+ const PopupMenuItem(
427
+ value: 'study',
428
+ child: Text('تایمر مطالعه')),
429
+ const PopupMenuItem(
430
+ value: 'archive', child: Text('بایگانی')),
431
+ ]),
432
+ ))),
433
+ ]));
434
+ });
435
}
436
206
-class PlannerPage extends StatefulWidget {
207
- const PlannerPage({super.key, required this.api});
437
+class PlanItemDialog extends StatefulWidget {
438
+ const PlanItemDialog(
439
+ {super.key,
440
+ required this.api,
441
+ this.item,
442
+ this.initialKind = 'task',
443
+ this.subjects = const []});
444
final IdentityApi api;
445
+ final Map<String, dynamic>? item;
446
+ final String initialKind;
447
+ final List<Map<String, dynamic>> subjects;
448
@override
210
- State<PlannerPage> createState() => _PlannerPageState();
449
+ State<PlanItemDialog> createState() => _PlanItemDialogState();
450
}
451
213
-class _PlannerPageState extends State<PlannerPage> {
214
- late Future<LoadResult> future;
452
+class _PlanItemDialogState extends State<PlanItemDialog> {
453
+ late final TextEditingController title, notes, minutes, points, outOf;
454
+ late String kind;
455
+ String priority = 'normal', status = 'planned';
456
+ late DateTime when;
457
+ bool shared = false, busy = false, sharingChanged = false;
458
+ String originalVisibility = 'private';
459
+ String? subjectId;
460
+ String? familyId, error;
461
+ List<Map<String, dynamic>> families = [];
462
@override
463
void initState() {
464
super.initState();
218
- future = load();
219
- flushQueue();
220
- }
221
-
222
- Future<void> flushQueue() async {
223
- final queue = await OfflineStore.instance.readQueue();
224
- if (queue.isEmpty) return;
225
- try {
226
- final result = await widget.api.submitSyncMutations(queue);
227
- final applied = <String>{};
228
- for (final raw in (result['results'] as List<dynamic>? ?? const [])) {
229
- final row = Map<String, dynamic>.from(raw as Map);
230
- if (row['status'] == 'accepted' || row['status'] == 'already_applied') {
231
- applied.add(row['id'].toString());
232
- }
233
- }
234
- await OfflineStore.instance.removeQueued(applied);
235
- } catch (_) {}
465
+ final i = widget.item;
466
+ title = TextEditingController(text: i?['title']?.toString() ?? '');
467
+ notes = TextEditingController(text: i?['notes']?.toString() ?? '');
468
+ points = TextEditingController(
469
+ text: (i?['grade_points'] ?? i?['gradePoints'])?.toString() ?? '');
470
+ outOf = TextEditingController(
471
+ text: (i?['grade_out_of'] ?? i?['gradeOutOf'])?.toString() ?? '');
472
+ minutes = TextEditingController(
473
+ text: (((i?['planned_duration_seconds'] ??
474
+ i?['plannedDurationSeconds'] ??
475
+ 1800) as num) ~/
476
+ 60)
477
+ .toString());
478
+ kind = i?['kind']?.toString() ?? widget.initialKind;
479
+ priority = i?['priority']?.toString() ?? 'normal';
480
+ status = i?['status']?.toString() ?? 'planned';
481
+ when = parseDate(i?['due_at'] ?? i?['dueAt'] ?? i?['starts_at']) ??
482
+ DateTime.now().add(const Duration(hours: 1));
483
+ originalVisibility = i?['visibility']?.toString() ?? 'private';
484
+ shared = originalVisibility != 'private';
485
+ subjectId = i?['subject_id']?.toString() ?? i?['subjectId']?.toString();
486
+ if (subjectId == null && widget.subjects.isNotEmpty) {
487
+ subjectId = widget.subjects.first['id'].toString();
488
+ }
489
+ familyId = i?['family_id']?.toString() ?? i?['familyId']?.toString();
490
+ loadFamilies();
491
}
492
238
- Future<LoadResult> load() async {
239
- final now = DateTime.now();
240
- final from = DateTime(now.year, now.month, now.day).subtract(const Duration(days: 1));
241
- final to = from.add(const Duration(days: 15));
493
+ Future<void> loadFamilies() async {
494
try {
243
- final items = await widget.api.listPlanItems(from: from, to: to);
244
- await OfflineStore.instance.cachePlanner(items);
245
- return LoadResult(items, false);
246
- } catch (_) {
247
- return LoadResult(await OfflineStore.instance.readPlanner(), true);
495
+ final rows = await widget.api.listFamilies();
496
+ if (mounted) setState(() => families = rows);
497
+ } catch (e) {
498
+ if (mounted) setState(() => error = uiErrorText(e));
499
}
500
}
501
251
- Future<void> reload() async {
252
- setState(() => future = load());
253
- await future;
502
+ @override
503
+ void dispose() {
504
+ title.dispose();
505
+ notes.dispose();
506
+ minutes.dispose();
507
+ points.dispose();
508
+ outOf.dispose();
509
+ super.dispose();
510
}
511
256
- Future<void> createItem() async {
257
- final title = TextEditingController();
258
- final kind = ValueNotifier<String>('task');
259
- final visibility = ValueNotifier<String>('private');
260
- final families = await widget.api.listFamilies();
261
- final familyId = families.isEmpty ? null : families.first['id']?.toString();
262
- final when = DateTime.now().add(const Duration(hours: 1));
263
-
264
- final saved = await showDialog<bool>(
265
- context: context,
266
- builder: (dialogContext) => AlertDialog(
267
- title: const Text('مورد جدید'),
268
- content: Column(mainAxisSize: MainAxisSize.min, children: [
269
- TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
270
- const SizedBox(height: 12),
271
- ValueListenableBuilder<String>(
272
- valueListenable: kind,
273
- builder: (_, value, __) => DropdownButtonFormField<String>(
274
- initialValue: value,
275
- decoration: const InputDecoration(labelText: 'نوع'),
276
- items: const [
277
- DropdownMenuItem(value: 'task', child: Text('کار')),
278
- DropdownMenuItem(value: 'event', child: Text('رویداد')),
279
- DropdownMenuItem(value: 'routine', child: Text('روتین')),
280
- DropdownMenuItem(value: 'goal', child: Text('هدف')),
281
- DropdownMenuItem(value: 'study_session', child: Text('جلسه مطالعه')),
282
- ],
283
- onChanged: (v) { if (v != null) kind.value = v; },
284
- ),
285
- ),
286
- const SizedBox(height: 12),
287
- ValueListenableBuilder<String>(
288
- valueListenable: visibility,
289
- builder: (_, value, __) => DropdownButtonFormField<String>(
290
- initialValue: value,
291
- decoration: const InputDecoration(labelText: 'اشتراک'),
292
- items: const [
293
- DropdownMenuItem(value: 'private', child: Text('خصوصی')),
294
- DropdownMenuItem(value: 'family', child: Text('خانواده')),
295
- DropdownMenuItem(value: 'parent_guardian', child: Text('والد / سرپرست')),
296
- ],
297
- onChanged: (v) { if (v != null) visibility.value = v; },
298
- ),
299
- ),
300
- ]),
301
- actions: [
302
- TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
303
- FilledButton(
304
- onPressed: () async {
305
- if (title.text.trim().isEmpty) return;
306
- final shared = visibility.value != 'private';
307
- await widget.api.createPlanItem({
308
- 'kind': kind.value,
309
- 'title': title.text.trim(),
310
- 'startsAt': when.toUtc().toIso8601String(),
311
- 'dueAt': when.add(const Duration(hours: 1)).toUtc().toIso8601String(),
312
- 'visibility': visibility.value,
313
- if (shared && familyId != null) 'familyId': familyId,
314
- 'reminderMinutesBefore': [15],
315
- });
316
- if (dialogContext.mounted) Navigator.pop(dialogContext, true);
317
- },
318
- child: const Text('ذخیره'),
319
- ),
320
- ],
321
- ),
322
- );
323
- title.dispose();
324
- kind.dispose();
325
- visibility.dispose();
326
- if (saved == true && mounted) await reload();
512
+ Future<void> pickDate() async {
513
+ final date = await showDatePicker(
514
+ context: context,
515
+ initialDate: when,
516
+ firstDate: DateTime(2020),
517
+ lastDate: DateTime(2100));
518
+ if (date == null || !mounted) return;
519
+ final time = await showTimePicker(
520
+ context: context, initialTime: TimeOfDay.fromDateTime(when));
521
+ if (time != null && mounted) {
522
+ setState(() => when =
523
+ DateTime(date.year, date.month, date.day, time.hour, time.minute));
524
+ }
525
}
526
329
- Future<void> reschedule(Map<String, dynamic> item) async {
330
- final base = parseDate(item['due_at'] ?? item['starts_at']) ?? DateTime.now();
331
- final next = base.add(const Duration(days: 1));
527
+ Future<void> save() async {
528
+ if (busy) return;
529
+ if (title.text.trim().isEmpty) {
530
+ setState(() => error = 'عنوان را وارد کن.');
531
+ return;
532
+ }
533
+ final duration = int.tryParse(numberInput(minutes.text));
534
+ if (duration == null || duration < 0 || duration > 1440) {
535
+ setState(
536
+ () => error = 'زمان برنامهریزیشده باید بین صفر و ۱۴۴۰ دقیقه باشد.');
537
+ return;
538
+ }
539
+ final graded = ['assignment', 'exam'].contains(kind);
540
+ final hasGrade =
541
+ points.text.trim().isNotEmpty || outOf.text.trim().isNotEmpty;
542
+ final gradePoints = num.tryParse(numberInput(points.text)),
543
+ gradeOutOf = num.tryParse(numberInput(outOf.text));
544
+ if (graded &&
545
+ hasGrade &&
546
+ (gradePoints == null ||
547
+ gradeOutOf == null ||
548
+ !gradePoints.isFinite ||
549
+ !gradeOutOf.isFinite ||
550
+ gradePoints < 0 ||
551
+ gradeOutOf <= 0 ||
552
+ gradePoints > gradeOutOf ||
553
+ gradeOutOf > 999999.99)) {
554
+ setState(() => error =
555
+ 'نمره و سقف نمره را با هم وارد کن؛ نمره باید بین صفر و سقف باشد.');
556
+ return;
557
+ }
558
+ if (shared && familyId == null) {
559
+ setState(() => error = 'خانوادهای را برای اشتراک با والد انتخاب کن.');
560
+ return;
561
+ }
562
+ setState(() {
563
+ busy = true;
564
+ error = null;
565
+ });
566
try {
333
- await widget.api.updatePlanItem(item['id'].toString(), {
334
- if (item['starts_at'] != null) 'startsAt': next.toUtc().toIso8601String(),
335
- if (item['due_at'] != null) 'dueAt': next.toUtc().toIso8601String(),
336
- });
337
- await reload();
338
- } catch (_) {
339
- await OfflineStore.instance.enqueue({
340
- 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
341
- 'entityType': 'plan_item',
342
- 'entityId': item['id'],
343
- 'operation': 'reschedule',
344
- 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
345
- 'payload': {'dueAt': next.toUtc().toIso8601String()},
346
- });
567
+ final item = widget.item;
568
+ final visibility = widget.item != null && !sharingChanged
569
+ ? originalVisibility
570
+ : shared
571
+ ? 'parent_guardian'
572
+ : 'private';
573
+ final payload = <String, dynamic>{
574
+ 'kind': kind,
575
+ 'title': title.text.trim(),
576
+ 'priority': priority,
577
+ 'status': status,
578
+ 'notes': notes.text.trim(),
579
+ 'dueAt': when.toUtc().toIso8601String(),
580
+ 'plannedDurationSeconds': duration * 60,
581
+ 'visibility': visibility,
582
+ 'familyId': visibility != 'private' ? familyId : null,
583
+ if (subjectId != null) 'subjectId': subjectId,
584
+ if (graded &&
585
+ (hasGrade ||
586
+ widget.item?['grade_points'] != null ||
587
+ widget.item?['gradePoints'] != null)) ...{
588
+ 'gradePoints': hasGrade ? gradePoints : null,
589
+ 'gradeOutOf': hasGrade ? gradeOutOf : null
590
+ }
591
+ };
592
+ final sync = PlanSync(widget.api);
593
+ final result = item == null
594
+ ? await sync.create(payload)
595
+ : await sync.update(item, payload);
596
+ if (mounted) Navigator.pop(context, result);
597
+ } catch (e) {
598
+ if (mounted) setState(() => error = uiErrorText(e));
599
+ } finally {
600
+ if (mounted) setState(() => busy = false);
601
}
602
}
603
604
@override
351
- Widget build(BuildContext context) => FutureBuilder<LoadResult>(
352
- future: future,
353
- builder: (context, snapshot) {
354
- if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
355
- final result = snapshot.data!;
356
- return Scaffold(
357
- backgroundColor: Colors.transparent,
358
- floatingActionButton: FloatingActionButton.extended(
359
- onPressed: createItem,
360
- icon: const Icon(Icons.add),
361
- label: const Text('جدید'),
362
- ),
363
- body: RefreshIndicator(
364
- onRefresh: reload,
365
- child: ListView(
366
- padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
367
- children: [
368
- if (result.offline)
369
- const Card(child: ListTile(
370
- leading: Icon(Icons.cloud_off_outlined),
371
- title: Text('حالت آفلاین'),
372
- subtitle: Text('آخرین برنامه ذخیرهشده نمایش داده میشود.'),
373
- )),
374
- if (result.items.isEmpty)
375
- const EmptyCard(
376
- icon: Icons.event_note_outlined,
377
- title: 'هنوز برنامهای نداری',
378
- subtitle: 'کار، رویداد، روتین، هدف یا جلسه مطالعه اضافه کن.',
379
- )
380
- else
381
- ...result.items.map((item) => Card(
382
- child: ListTile(
383
- title: Text(item['title']?.toString() ?? ''),
384
- subtitle: Text(
385
- faKind(item['kind']?.toString() ?? 'task') +
386
- (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
387
- ),
388
- trailing: PopupMenuButton<String>(
389
- onSelected: (value) async {
390
- if (value == 'complete') {
391
- await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
392
- await reload();
393
- } else if (value == 'tomorrow') {
394
- await reschedule(item);
395
- }
396
- },
397
- itemBuilder: (_) => const [
398
- PopupMenuItem(value: 'complete', child: Text('انجام شد')),
399
- PopupMenuItem(value: 'tomorrow', child: Text('انتقال به فردا')),
400
- ],
401
- ),
402
- ),
403
- )),
605
+ Widget build(BuildContext context) => PopScope(
606
+ canPop: !busy,
607
+ child: AlertDialog(
608
+ title: Text(widget.item == null ? 'مورد جدید' : 'ویرایش مورد'),
609
+ content: SizedBox(
610
+ width: 440,
611
+ child: SingleChildScrollView(
612
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
613
+ TextField(
614
+ controller: title,
615
+ enabled: !busy,
616
+ decoration: const InputDecoration(labelText: 'عنوان')),
617
+ const SizedBox(height: 12),
618
+ DropdownButtonFormField<String>(
619
+ initialValue: kind,
620
+ decoration: const InputDecoration(labelText: 'نوع'),
621
+ items: [
622
+ for (final k in [
623
+ 'task',
624
+ 'assignment',
625
+ 'exam',
626
+ 'event',
627
+ 'routine',
628
+ 'goal',
629
+ 'study_session'
630
+ ])
631
+ DropdownMenuItem(value: k, child: Text(faKind(k)))
632
+ ],
633
+ onChanged:
634
+ busy ? null : (v) => setState(() => kind = v ?? kind)),
635
+ if (widget.subjects.isNotEmpty)
636
+ DropdownButtonFormField<String>(
637
+ initialValue: subjectId,
638
+ decoration: const InputDecoration(labelText: 'درس'),
639
+ items: widget.subjects
640
+ .map((row) => DropdownMenuItem(
641
+ value: row['id'].toString(),
642
+ child: Text(row['name']?.toString() ?? 'درس')))
643
+ .toList(),
644
+ onChanged:
645
+ busy ? null : (v) => setState(() => subjectId = v)),
646
+ const SizedBox(height: 12),
647
+ DropdownButtonFormField<String>(
648
+ initialValue: priority,
649
+ decoration: const InputDecoration(labelText: 'اولویت'),
650
+ items: const [
651
+ DropdownMenuItem(value: 'low', child: Text('کم')),
652
+ DropdownMenuItem(value: 'normal', child: Text('معمولی')),
653
+ DropdownMenuItem(value: 'high', child: Text('زیاد')),
654
+ DropdownMenuItem(value: 'urgent', child: Text('فوری'))
655
+ ],
656
+ onChanged: busy
657
+ ? null
658
+ : (v) => setState(() => priority = v ?? priority)),
659
+ if (widget.item != null)
660
+ DropdownButtonFormField<String>(
661
+ initialValue: status,
662
+ decoration: const InputDecoration(labelText: 'وضعیت'),
663
+ items: const [
664
+ DropdownMenuItem(
665
+ value: 'planned', child: Text('برنامهریزیشده')),
666
+ DropdownMenuItem(
667
+ value: 'in_progress', child: Text('در حال انجام')),
668
+ DropdownMenuItem(
669
+ value: 'completed', child: Text('انجامشده'))
670
+ ],
671
+ onChanged: busy
672
+ ? null
673
+ : (v) => setState(() => status = v ?? status)),
674
+ const SizedBox(height: 12),
675
+ TextField(
676
+ controller: minutes,
677
+ enabled: !busy,
678
+ keyboardType: TextInputType.number,
679
+ decoration: const InputDecoration(
680
+ labelText: 'زمان برنامهریزیشده (دقیقه)')),
681
+ if (['assignment', 'exam'].contains(kind)) ...[
682
+ TextField(
683
+ controller: points,
684
+ enabled: !busy,
685
+ keyboardType:
686
+ const TextInputType.numberWithOptions(decimal: true),
687
+ decoration:
688
+ const InputDecoration(labelText: 'نمره (اختیاری)')),
689
+ TextField(
690
+ controller: outOf,
691
+ enabled: !busy,
692
+ keyboardType:
693
+ const TextInputType.numberWithOptions(decimal: true),
694
+ decoration: const InputDecoration(
695
+ labelText: 'سقف نمره (اختیاری)')),
696
],
405
- ),
406
- ),
407
- );
408
- },
409
- );
697
+ TextButton.icon(
698
+ onPressed: busy ? null : pickDate,
699
+ icon: const Icon(Icons.calendar_month),
700
+ label: Text('موعد · ${shortDate(when.toIso8601String())}')),
701
+ TextField(
702
+ controller: notes,
703
+ enabled: !busy,
704
+ maxLines: 2,
705
+ decoration: const InputDecoration(
706
+ labelText: 'یادداشت خصوصی',
707
+ helperText:
708
+ 'یادداشت در گزارش والد نمایش داده نمیشود.')),
709
+ SwitchListTile(
710
+ title: const Text('اشتراک تکلیف با والد / سرپرست'),
711
+ subtitle: const Text(
712
+ 'عنوان، وضعیت و زمان ثبتشده برای سرپرست مجاز دیده میشود.'),
713
+ value: shared,
714
+ onChanged: busy
715
+ ? null
716
+ : (v) => setState(() {
717
+ shared = v;
718
+ sharingChanged = true;
719
+ })),
720
+ if (widget.item != null &&
721
+ !['private', 'parent_guardian']
722
+ .contains(originalVisibility) &&
723
+ !sharingChanged)
724
+ const Text(
725
+ 'دامنه اشتراک فعلی با ذخیره حفظ میشود؛ تغییر کلید، آن را به والد یا خصوصی تغییر میدهد.'),
726
+ if (shared)
727
+ DropdownButtonFormField<String>(
728
+ initialValue: familyId,
729
+ decoration: const InputDecoration(labelText: 'خانواده'),
730
+ items: families
731
+ .map((f) => DropdownMenuItem(
732
+ value: f['id'].toString(),
733
+ child: Text(f['name']?.toString() ?? 'خانواده')))
734
+ .toList(),
735
+ onChanged:
736
+ busy ? null : (v) => setState(() => familyId = v)),
737
+ if (error != null)
738
+ Padding(
739
+ padding: const EdgeInsets.only(top: 12),
740
+ child: Text(error!,
741
+ style: TextStyle(
742
+ color: Theme.of(context).colorScheme.error))),
743
+ ]))),
744
+ actions: [
745
+ TextButton(
746
+ onPressed: busy ? null : () => Navigator.pop(context),
747
+ child: const Text('انصراف')),
748
+ FilledButton(
749
+ onPressed: busy ? null : save,
750
+ child: Text(busy ? 'در حال ثبت...' : 'ذخیره'))
751
+ ]));
752
}
753
754
class SchoolPage extends StatefulWidget {
@@ -418,6 +760,8 @@ class SchoolPage extends StatefulWidget {
760
761
class _SchoolPageState extends State<SchoolPage> {
762
late Future<SchoolLoad> future;
763
+ bool writing = false;
764
+ String? writeError;
765
@override
766
void initState() {
767
super.initState();
@@ -430,14 +774,18 @@ class _SchoolPageState extends State<SchoolPage> {
774
if (userId.isEmpty) return SchoolLoad(userId, const {}, false);
775
try {
776
final overview = await widget.api.getSchoolOverview(userId);
433
- await OfflineStore.instance.cacheSchool([{'userId': userId, 'overview': overview}]);
777
+ await OfflineStore.forApi(widget.api).cacheSchool([
778
+ {'userId': userId, 'overview': overview}
779
+ ]);
780
return SchoolLoad(userId, overview, false);
435
- } catch (_) {
436
- final cached = await OfflineStore.instance.readSchool();
781
+ } catch (failure) {
782
+ if (!isOfflineFailure(failure)) rethrow;
783
+ final cached = await OfflineStore.forApi(widget.api).readSchool();
784
if (cached.isNotEmpty) {
785
return SchoolLoad(
786
cached.first['userId']?.toString() ?? userId,
440
- Map<String, dynamic>.from(cached.first['overview'] as Map? ?? const {}),
787
+ Map<String, dynamic>.from(
788
+ cached.first['overview'] as Map? ?? const {}),
789
true,
790
);
791
}
@@ -446,111 +794,104 @@ class _SchoolPageState extends State<SchoolPage> {
794
}
795
796
Future<void> reload() async {
449
- setState(() => future = load());
450
- await future;
797
+ setState(() {
798
+ future = load();
799
+ });
800
+ try {
801
+ await future;
802
+ } catch (_) {/* FutureBuilder renders retry failure. */}
803
}
804
805
Future<void> quickSetup() async {
454
- var contexts = await widget.api.listLifeContexts();
455
- Map<String, dynamic>? student;
456
- for (final row in contexts) {
457
- if (row['kind'] == 'student') { student = row; break; }
458
- }
459
- student ??= await widget.api.createLifeContext(kind: 'student', title: 'مدرسه');
460
- final now = DateTime.now();
461
- final year = await widget.api.createAcademicYear({
462
- 'lifeContextId': student['id'],
463
- 'title': 'سال تحصیلی ' + now.year.toString() + '-' + (now.year + 1).toString(),
464
- 'startsOn': now.year.toString() + '-09-01',
465
- 'endsOn': (now.year + 1).toString() + '-06-30',
466
- });
467
- final term = await widget.api.createAcademicTerm(year['id'].toString(), {
468
- 'title': 'نیمسال اول',
469
- 'startsOn': now.year.toString() + '-09-01',
470
- 'endsOn': (now.year + 1).toString() + '-01-31',
806
+ if (writing) return;
807
+ setState(() {
808
+ writing = true;
809
+ writeError = null;
810
});
472
- await widget.api.createSubject(term['id'].toString(), {'name': 'ریاضی'});
473
- await reload();
811
+ try {
812
+ var contexts = await widget.api.listLifeContexts();
813
+ Map<String, dynamic>? student;
814
+ for (final row in contexts) {
815
+ if (row['kind'] == 'student') {
816
+ student = row;
817
+ break;
818
+ }
819
+ }
820
+ student ??=
821
+ await widget.api.createLifeContext(kind: 'student', title: 'مدرسه');
822
+ final now = DateTime.now();
823
+ final year = await widget.api.createAcademicYear({
824
+ 'lifeContextId': student['id'],
825
+ 'title': 'سال تحصیلی ${now.year}-${now.year + 1}',
826
+ 'startsOn': '${now.year}-09-01',
827
+ 'endsOn': '${now.year + 1}-06-30',
828
+ });
829
+ final term = await widget.api.createAcademicTerm(year['id'].toString(), {
830
+ 'title': 'نیمسال اول',
831
+ 'startsOn': '${now.year}-09-01',
832
+ 'endsOn': '${now.year + 1}-01-31',
833
+ });
834
+ await widget.api.createSubject(term['id'].toString(), {'name': 'ریاضی'});
835
+ await reload();
836
+ } catch (error) {
837
+ if (mounted) setState(() => writeError = uiErrorText(error));
838
+ } finally {
839
+ if (mounted) setState(() => writing = false);
840
+ }
841
}
842
843
Future<void> addSchoolItem(String kind) async {
477
- final data = await future;
478
- final subjects = data.overview['subjects'] as List<dynamic>? ?? const [];
479
- if (subjects.isEmpty) return;
480
- final title = TextEditingController();
481
- final first = Map<String, dynamic>.from(subjects.first as Map);
482
- final selected = ValueNotifier<String>(first['id'].toString());
483
- final saved = await showDialog<bool>(
484
- context: context,
485
- builder: (dialogContext) => AlertDialog(
486
- title: Text(kind == 'exam' ? 'امتحان جدید' : 'تکلیف جدید'),
487
- content: Column(mainAxisSize: MainAxisSize.min, children: [
488
- TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
489
- const SizedBox(height: 12),
490
- ValueListenableBuilder<String>(
491
- valueListenable: selected,
492
- builder: (_, value, __) => DropdownButtonFormField<String>(
493
- initialValue: value,
494
- decoration: const InputDecoration(labelText: 'درس'),
495
- items: subjects.map((raw) {
496
- final row = Map<String, dynamic>.from(raw as Map);
497
- return DropdownMenuItem<String>(
498
- value: row['id'].toString(),
499
- child: Text(row['name']?.toString() ?? ''),
500
- );
501
- }).toList(),
502
- onChanged: (v) { if (v != null) selected.value = v; },
503
- ),
504
- ),
505
- ]),
506
- actions: [
507
- TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
508
- FilledButton(
509
- onPressed: () async {
510
- if (title.text.trim().isEmpty) return;
511
- final due = DateTime.now().add(const Duration(days: 2));
512
- await widget.api.createPlanItem({
513
- 'kind': kind,
514
- 'title': title.text.trim(),
515
- 'subjectId': selected.value,
516
- 'dueAt': due.toUtc().toIso8601String(),
517
- 'visibility': 'private',
518
- 'reminderMinutesBefore': [60, 1440],
519
- });
520
- if (dialogContext.mounted) Navigator.pop(dialogContext, true);
521
- },
522
- child: const Text('ذخیره'),
523
- ),
524
- ],
525
- ),
526
- );
527
- title.dispose();
528
- selected.dispose();
529
- if (saved == true && mounted) await reload();
844
+ try {
845
+ final overview = await future;
846
+ if (!mounted) return;
847
+ final subjects = (overview.overview['subjects'] as List? ?? [])
848
+ .map((raw) => Map<String, dynamic>.from(raw as Map))
849
+ .toList();
850
+ final saved = await showDialog<MutationOutcome>(
851
+ context: context,
852
+ builder: (_) => PlanItemDialog(
853
+ api: widget.api, initialKind: kind, subjects: subjects));
854
+ if (saved != null && mounted) await reload();
855
+ } catch (error) {
856
+ if (mounted) setState(() => writeError = uiErrorText(error));
857
+ }
858
}
859
860
@override
861
Widget build(BuildContext context) => FutureBuilder<SchoolLoad>(
862
future: future,
863
builder: (context, snapshot) {
536
- if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
864
+ if (snapshot.hasError) {
865
+ return LoadError(error: snapshot.error!, retry: reload);
866
+ }
867
+ if (!snapshot.hasData) {
868
+ return const Center(child: CircularProgressIndicator());
869
+ }
870
final data = snapshot.data!;
871
final years = data.overview['years'] as List<dynamic>? ?? const [];
539
- final subjects = data.overview['subjects'] as List<dynamic>? ?? const [];
540
- final workload = data.overview['workload'] as List<dynamic>? ?? const [];
872
+ final subjects =
873
+ data.overview['subjects'] as List<dynamic>? ?? const [];
874
+ final workload =
875
+ data.overview['workload'] as List<dynamic>? ?? const [];
876
final grades = data.overview['grades'] as List<dynamic>? ?? const [];
877
return ListView(
878
padding: const EdgeInsets.all(16),
879
children: [
880
+ if (writing) const LinearProgressIndicator(),
881
+ if (writeError != null) Text(writeError!),
882
if (data.offline)
546
- const Card(child: ListTile(leading: Icon(Icons.cloud_off_outlined), title: Text('اطلاعات مدرسه از کش نمایش داده میشود'))),
883
+ const Card(
884
+ child: ListTile(
885
+ leading: Icon(Icons.cloud_off_outlined),
886
+ title: Text('اطلاعات مدرسه از کش نمایش داده میشود'))),
887
if (years.isEmpty)
888
EmptyCard(
889
icon: Icons.school_outlined,
890
title: 'مدرسه را آماده کن',
551
- subtitle: 'سال تحصیلی، نیمسال و اولین درس را با شروع سریع بساز.',
891
+ subtitle:
892
+ 'سال تحصیلی، نیمسال و اولین درس را با شروع سریع بساز.',
893
action: FilledButton.icon(
553
- onPressed: quickSetup,
894
+ onPressed: writing ? null : quickSetup,
895
icon: const Icon(Icons.auto_fix_high),
896
label: const Text('شروع سریع'),
897
),
@@ -559,48 +900,61 @@ class _SchoolPageState extends State<SchoolPage> {
900
Card(
901
child: Padding(
902
padding: const EdgeInsets.all(16),
562
- child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
563
- Text('مدرسه', style: Theme.of(context).textTheme.headlineSmall),
564
- const SizedBox(height: 10),
565
- Wrap(spacing: 8, runSpacing: 8, children: [
566
- Chip(label: Text(subjects.length.toString() + ' درس')),
567
- Chip(label: Text(workload.length.toString() + ' کار درسی پیشرو')),
568
- Chip(label: Text(grades.length.toString() + ' نمره')),
569
- ]),
570
- const SizedBox(height: 12),
571
- Row(children: [
572
- Expanded(child: FilledButton.icon(
573
- onPressed: () => addSchoolItem('assignment'),
574
- icon: const Icon(Icons.assignment_add),
575
- label: const Text('تکلیف'),
576
- )),
577
- const SizedBox(width: 8),
578
- Expanded(child: OutlinedButton.icon(
579
- onPressed: () => addSchoolItem('exam'),
580
- icon: const Icon(Icons.quiz_outlined),
581
- label: const Text('امتحان'),
582
- )),
583
- ]),
584
- ]),
903
+ child: Column(
904
+ crossAxisAlignment: CrossAxisAlignment.stretch,
905
+ children: [
906
+ Text('مدرسه',
907
+ style: Theme.of(context).textTheme.headlineSmall),
908
+ const SizedBox(height: 10),
909
+ Wrap(spacing: 8, runSpacing: 8, children: [
910
+ Chip(label: Text('${subjects.length} درس')),
911
+ Chip(
912
+ label:
913
+ Text('${workload.length} کار درسی پیشرو')),
914
+ Chip(label: Text('${grades.length} نمره')),
915
+ ]),
916
+ const SizedBox(height: 12),
917
+ Row(children: [
918
+ Expanded(
919
+ child: FilledButton.icon(
920
+ onPressed: () => addSchoolItem('assignment'),
921
+ icon: const Icon(Icons.assignment_add),
922
+ label: const Text('تکلیف'),
923
+ )),
924
+ const SizedBox(width: 8),
925
+ Expanded(
926
+ child: OutlinedButton.icon(
927
+ onPressed: () => addSchoolItem('exam'),
928
+ icon: const Icon(Icons.quiz_outlined),
929
+ label: const Text('امتحان'),
930
+ )),
931
+ ]),
932
+ ]),
933
),
934
),
935
const SizedBox(height: 12),
936
Text('درسها', style: Theme.of(context).textTheme.titleMedium),
937
...subjects.map((raw) {
938
final row = Map<String, dynamic>.from(raw as Map);
591
- return Card(child: ListTile(
939
+ return Card(
940
+ child: ListTile(
941
leading: const Icon(Icons.menu_book_outlined),
942
title: Text(row['name']?.toString() ?? ''),
594
- subtitle: Text(row['teacher_name']?.toString() ?? row['term_title']?.toString() ?? ''),
943
+ subtitle: Text(row['teacher_name']?.toString() ??
944
+ row['term_title']?.toString() ??
945
+ ''),
946
));
947
}),
948
const SizedBox(height: 12),
598
- Text('کارهای درسی پیشرو', style: Theme.of(context).textTheme.titleMedium),
949
+ Text('کارهای درسی پیشرو',
950
+ style: Theme.of(context).textTheme.titleMedium),
951
...workload.map((raw) {
952
final row = Map<String, dynamic>.from(raw as Map);
601
- return Card(child: ListTile(
953
+ return Card(
954
+ child: ListTile(
955
title: Text(row['title']?.toString() ?? ''),
603
- subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
956
+ subtitle: Text(
957
+ '${faKind(row['kind']?.toString() ?? '')} · ${shortDate(row['due_at'] ?? row['starts_at'])}'),
958
));
959
}),
960
],
@@ -610,312 +964,36 @@ class _SchoolPageState extends State<SchoolPage> {
964
);
965
}
966
613
-class ParentFamilyDashboard extends StatefulWidget {
614
- const ParentFamilyDashboard({super.key, required this.api});
615
- final IdentityApi api;
616
- @override
617
- State<ParentFamilyDashboard> createState() => _ParentFamilyDashboardState();
618
-}
619
-
620
-class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
621
- late Future<List<Map<String, dynamic>>> families;
622
- @override
623
- void initState() {
624
- super.initState();
625
- families = widget.api.listFamilies();
626
- }
627
-
628
- @override
629
- Widget build(BuildContext context) => FutureBuilder<List<Map<String, dynamic>>>(
630
- future: families,
631
- builder: (context, snapshot) {
632
- if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
633
- if (snapshot.data!.isEmpty) {
634
- return const EmptyCard(
635
- icon: Icons.family_restroom,
636
- title: 'خانوادهای متصل نیست',
637
- subtitle: 'از بخش پروفایل فضای خانواده بساز یا به آن بپیوند.',
638
- );
639
- }
640
- return ListView(
641
- padding: const EdgeInsets.all(16),
642
- children: snapshot.data!.map((family) => FamilyDashboardCard(api: widget.api, family: family)).toList(),
643
- );
644
- },
645
- );
646
-}
647
-
648
-class FamilyDashboardCard extends StatefulWidget {
649
- const FamilyDashboardCard({super.key, required this.api, required this.family});
650
- final IdentityApi api;
651
- final Map<String, dynamic> family;
652
- @override
653
- State<FamilyDashboardCard> createState() => _FamilyDashboardCardState();
654
-}
655
-
656
-class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
657
- late Future<List<Map<String, dynamic>>> members;
658
- @override
659
- void initState() {
660
- super.initState();
661
- members = widget.api.listFamilyMembers(widget.family['id'].toString());
662
- }
663
-
664
- Future<void> openFamilyGuidance(
665
- String familyId,
666
- String childId,
667
- String childName,
668
- ) async {
669
- final question = TextEditingController();
670
- String? advice;
671
- bool busy = false;
672
- await showDialog<void>(
673
- context: context,
674
- builder: (dialogContext) => StatefulBuilder(
675
- builder: (context, setLocalState) => AlertDialog(
676
- title: Text('مشورت درباره $childName'),
677
- content: SizedBox(
678
- width: 520,
679
- child: Column(
680
- mainAxisSize: MainAxisSize.min,
681
- children: [
682
- const Text(
683
- 'راهنما فقط از خلاصههای مجاز استفاده میکند و متن خصوصی فرزند را نمیبیند.',
684
- ),
685
- const SizedBox(height: 12),
686
- TextField(
687
- controller: question,
688
- maxLines: 4,
689
- decoration: const InputDecoration(
690
- labelText: 'سؤال شما',
691
- hintText: 'مثلاً چطور بدون فشار درباره امتحانها با او صحبت کنم؟',
692
- ),
693
- ),
694
- if (advice != null) ...[
695
- const SizedBox(height: 14),
696
- Align(
697
- alignment: Alignment.centerRight,
698
- child: Text(
699
- advice!,
700
- style: Theme.of(context).textTheme.bodyLarge,
701
- ),
702
- ),
703
- ],
704
- ],
705
- ),
706
- ),
707
- actions: [
708
- TextButton(
709
- onPressed: busy ? null : () => Navigator.pop(dialogContext),
710
- child: const Text('بستن'),
711
- ),
712
- FilledButton(
713
- onPressed: busy
714
- ? null
715
- : () async {
716
- if (question.text.trim().isEmpty) return;
717
- setLocalState(() => busy = true);
718
- try {
719
- final result = await widget.api.requestFamilyGuidance(
720
- familyId,
721
- childId,
722
- question.text.trim(),
723
- );
724
- setLocalState(() {
725
- advice = result['advice']?.toString() ??
726
- 'پیشنهادی دریافت نشد.';
727
- });
728
- } catch (_) {
729
- setLocalState(() {
730
- advice = 'دریافت راهنمایی انجام نشد. دوباره تلاش کنید.';
731
- });
732
- } finally {
733
- setLocalState(() => busy = false);
734
- }
735
- },
736
- child: Text(busy ? 'در حال بررسی...' : 'دریافت راهنمایی'),
737
- ),
738
- ],
739
- ),
740
- ),
741
- );
742
- question.dispose();
743
- }
744
-
745
- Future<void> openChild(Map<String, dynamic> child) async {
746
- final familyId = widget.family['id'].toString();
747
- final childId = child['user_id'].toString();
748
- final summary = await widget.api.getChildSupportSummary(familyId, childId);
749
- Map<String, dynamic>? wellbeing;
750
- try {
751
- wellbeing = await widget.api.getGuardianWellbeingSummary(familyId, childId);
752
- } catch (_) {
753
- wellbeing = null;
754
- }
755
- if (!mounted) return;
756
- final metrics = Map<String, dynamic>.from(summary['metrics'] as Map? ?? const {});
757
- final upcoming = summary['upcoming'] as List<dynamic>? ?? const [];
758
- final wellbeingSummary = wellbeing == null
759
- ? const <String, dynamic>{}
760
- : Map<String, dynamic>.from(
761
- wellbeing['summary'] as Map? ?? const <String, dynamic>{},
762
- );
763
- final safety = wellbeing == null
764
- ? const <String, dynamic>{}
765
- : Map<String, dynamic>.from(
766
- wellbeing['safety'] as Map? ?? const <String, dynamic>{},
767
- );
768
- await showDialog<void>(
769
- context: context,
770
- builder: (dialogContext) => AlertDialog(
771
- title: Text('خلاصه حمایت · ' + (child['display_name']?.toString() ?? 'فرزند')),
772
- content: SizedBox(
773
- width: 520,
774
- child: SingleChildScrollView(
775
- child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
776
- Wrap(spacing: 8, runSpacing: 8, children: [
777
- Chip(label: Text((metrics['overdue'] ?? 0).toString() + ' عقبافتاده')),
778
- Chip(label: Text((metrics['completedLast7Days'] ?? 0).toString() + ' انجامشده')),
779
- Chip(label: Text((metrics['studyMinutesLast7Days'] ?? 0).toString() + ' دقیقه مطالعه')),
780
- if (metrics['gradePercent'] != null) Chip(label: Text('میانگین ' + metrics['gradePercent'].toString() + '٪')),
781
- ]),
782
- if (wellbeing != null) ...[
783
- const SizedBox(height: 14),
784
- Text('خلاصه حال خوب', style: Theme.of(context).textTheme.titleMedium),
785
- const SizedBox(height: 8),
786
- Wrap(spacing: 8, runSpacing: 8, children: [
787
- Chip(
788
- label: Text(
789
- (wellbeingSummary['checkin_count'] ?? 0).toString() +
790
- ' ثبت مجاز',
791
- ),
792
- ),
793
- if (wellbeingSummary['mood_average'] != null)
794
- Chip(
795
- label: Text(
796
- 'حال ' + wellbeingSummary['mood_average'].toString() + '/5',
797
- ),
798
- ),
799
- if (wellbeingSummary['stress_average'] != null)
800
- Chip(
801
- label: Text(
802
- 'استرس ' +
803
- wellbeingSummary['stress_average'].toString() +
804
- '/5',
805
- ),
806
- ),
807
- if ((safety['open_urgent_count'] ?? 0) != 0)
808
- Chip(
809
- avatar: const Icon(Icons.warning_amber_rounded, size: 18),
810
- label: Text(
811
- safety['open_urgent_count'].toString() +
812
- ' هشدار ایمنی نیازمند توجه',
813
- ),
814
- ),
815
- ]),
816
- const SizedBox(height: 6),
817
- const Text(
818
- 'این بخش فقط خلاصه مجاز و سیگنال ایمنی را نشان میدهد؛ متن خصوصی گفتوگو یا یادداشت نمایش داده نمیشود.',
819
- ),
820
- ],
821
- const SizedBox(height: 10),
822
- const Text('موارد پیشرو'),
823
- ...upcoming.take(8).map((raw) {
824
- final row = Map<String, dynamic>.from(raw as Map);
825
- return ListTile(
826
- dense: true,
827
- title: Text(row['title']?.toString() ?? ''),
828
- subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
829
- );
830
- }),
831
- ]),
832
- ),
833
- ),
834
- actions: [
835
- TextButton(
836
- onPressed: () => Navigator.pop(dialogContext),
837
- child: const Text('بستن'),
838
- ),
839
- FilledButton.icon(
840
- onPressed: () {
841
- Navigator.pop(dialogContext);
842
- openFamilyGuidance(
843
- familyId,
844
- childId,
845
- child['display_name']?.toString() ?? 'فرزند',
846
- );
847
- },
848
- icon: const Icon(Icons.psychology_alt_outlined),
849
- label: const Text('مشورت با راهنمای خانواده'),
850
- ),
851
- ],
852
- ),
853
- );
854
- }
855
-
856
- @override
857
- Widget build(BuildContext context) => Card(
858
- child: Padding(
859
- padding: const EdgeInsets.all(14),
860
- child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
861
- Text(widget.family['name']?.toString() ?? 'خانواده', style: Theme.of(context).textTheme.titleLarge),
862
- const SizedBox(height: 8),
863
- FutureBuilder<List<Map<String, dynamic>>>(
864
- future: members,
865
- builder: (context, snapshot) {
866
- if (!snapshot.hasData) return const LinearProgressIndicator();
867
- final children = snapshot.data!.where((row) => row['role'] == 'teen_minor').toList();
868
- if (children.isEmpty) return const Text('هنوز فرزند/نوجوانی به این خانواده متصل نیست.');
869
- return Column(
870
- children: children.map((child) => ListTile(
871
- leading: const CircleAvatar(child: Icon(Icons.school_outlined)),
872
- title: Text(child['display_name']?.toString() ?? 'فرزند'),
873
- subtitle: const Text('برنامه، تکالیف، امتحانها و پیشرفت مجاز'),
874
- trailing: const Icon(Icons.chevron_left),
875
- onTap: () => openChild(child),
876
- )).toList(),
877
- );
878
- },
879
- ),
880
- ]),
881
- ),
882
- );
883
-}
884
-
967
class EmptyCard extends StatelessWidget {
886
- const EmptyCard({
887
- super.key,
888
- required this.icon,
889
- required this.title,
890
- required this.subtitle,
891
- this.action,
892
- });
968
+ const EmptyCard(
969
+ {super.key,
970
+ required this.icon,
971
+ required this.title,
972
+ required this.subtitle,
973
+ this.action});
974
final IconData icon;
894
- final String title;
895
- final String subtitle;
975
+ final String title, subtitle;
976
final Widget? action;
897
-
977
@override
978
Widget build(BuildContext context) => Card(
900
- child: Padding(
979
+ child: Padding(
980
padding: const EdgeInsets.all(22),
981
child: Column(children: [
982
Icon(icon, size: 42),
904
- const SizedBox(height: 10),
983
Text(title, style: Theme.of(context).textTheme.titleMedium),
984
const SizedBox(height: 6),
985
Text(subtitle, textAlign: TextAlign.center),
908
- if (action != null) ...[const SizedBox(height: 14), action!],
909
- ]),
910
- ),
911
- );
986
+ if (action != null) action!
987
+ ])));
988
}
989
990
class LoadResult {
915
- const LoadResult(this.items, this.offline, {this.reminders = const []});
916
- final List<Map<String, dynamic>> items;
991
+ const LoadResult(this.items, this.offline,
992
+ {this.pending = 0, this.syncedAt, this.reminders = const []});
993
+ final List<Map<String, dynamic>> items, reminders;
994
final bool offline;
918
- final List<Map<String, dynamic>> reminders;
995
+ final int pending;
996
+ final DateTime? syncedAt;
997
}
998
999
class SchoolLoad {
apps/lifemate/lib/phase4_ui.dart
+8
-4
@@ -37,7 +37,8 @@ class _Phase4HubState extends State<Phase4Hub> {
37
const SizedBox(height: 12),
38
TextField(
39
controller: target,
40
- decoration: const InputDecoration(labelText: 'هدف یا نتیجه مطلوب'),
40
+ decoration:
41
+ const InputDecoration(labelText: 'هدف یا نتیجه مطلوب'),
42
),
43
],
44
),
@@ -213,7 +214,8 @@ class _Phase4HubState extends State<Phase4Hub> {
214
note.dispose();
215
if (saved == true && mounted) {
216
ScaffoldMessenger.of(context).showSnackBar(
216
- const SnackBar(content: Text('ثبت شد. متن یادداشت خصوصی باقی میماند.')),
217
+ const SnackBar(
218
+ content: Text('ثبت شد. متن یادداشت خصوصی باقی میماند.')),
219
);
220
}
221
}
@@ -258,7 +260,8 @@ class _Phase4HubState extends State<Phase4Hub> {
260
_GuideCard(
261
icon: Icons.self_improvement_rounded,
262
title: 'همراه حال خوب',
261
- subtitle: 'گفتوگوی حمایتی و غیرتشخیصی برای حال، ارتباط و فشار روزمره.',
263
+ subtitle:
264
+ 'گفتوگوی حمایتی و غیرتشخیصی برای حال، ارتباط و فشار روزمره.',
265
onTap: () => openGuide('wellbeing', 'همراه حال خوب'),
266
),
267
const SizedBox(height: 8),
@@ -293,7 +296,8 @@ class _Phase4HubState extends State<Phase4Hub> {
296
),
297
),
298
const SizedBox(height: 12),
296
- Text('هدفهای یادگیری', style: Theme.of(context).textTheme.titleMedium),
299
+ Text('هدفهای یادگیری',
300
+ style: Theme.of(context).textTheme.titleMedium),
301
FutureBuilder<List<Map<String, dynamic>>>(
302
future: goals,
303
builder: (context, snapshot) {
apps/lifemate/lib/plan_sync.dart
new
+160
@@ -0,0 +1,160 @@
1
+import 'dart:async';
2
+import 'dart:math';
3
+import 'api.dart';
4
+import 'offline_store.dart';
5
+
6
+String newMutationId() {
7
+ final random = Random.secure();
8
+ final bytes = List.generate(16, (_) => random.nextInt(256));
9
+ bytes[6] = (bytes[6] & 15) | 64;
10
+ bytes[8] = (bytes[8] & 63) | 128;
11
+ final hex = bytes.map((n) => n.toRadixString(16).padLeft(2, '0')).join();
12
+ return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';
13
+}
14
+
15
+class MutationOutcome {
16
+ const MutationOutcome({required this.queued, this.item});
17
+ final bool queued;
18
+ final Map<String, dynamic>? item;
19
+}
20
+
21
+class PlanSync {
22
+ PlanSync(this.api, {OfflineStore? store})
23
+ : store = store ?? OfflineStore.forApi(api);
24
+ final IdentityApi api;
25
+ final OfflineStore store;
26
+ static final _tails = <String, Future<void>>{};
27
+ Future<T> _serial<T>(Future<T> Function() operation) {
28
+ final previous = _tails[store.scope];
29
+ final release = Completer<void>();
30
+ _tails[store.scope] = release.future;
31
+ return (() async {
32
+ if (previous != null) await previous;
33
+ try {
34
+ return await operation();
35
+ } finally {
36
+ if (identical(_tails[store.scope], release.future)) {
37
+ _tails.remove(store.scope);
38
+ }
39
+ release.complete();
40
+ }
41
+ })();
42
+ }
43
+
44
+ Future<MutationOutcome> create(Map<String, dynamic> payload) {
45
+ final item = <String, dynamic>{
46
+ 'id': newMutationId(),
47
+ 'kind': payload['kind'] ?? 'task',
48
+ 'title': payload['title'],
49
+ 'status': 'planned',
50
+ 'visibility': payload['visibility'] ?? 'private',
51
+ 'due_at': payload['dueAt'],
52
+ 'starts_at': payload['startsAt'],
53
+ 'version': 0,
54
+ 'pending_sync': true,
55
+ 'acknowledged': false
56
+ };
57
+ return _change('create', item, payload);
58
+ }
59
+
60
+ Future<MutationOutcome> update(
61
+ Map<String, dynamic> item, Map<String, dynamic> changes) =>
62
+ _change('update', item, changes);
63
+ Future<MutationOutcome> complete(Map<String, dynamic> item) =>
64
+ _change('complete', item, {'status': 'completed'});
65
+ Future<MutationOutcome> archive(Map<String, dynamic> item) =>
66
+ _change('archive', item, {'status': 'cancelled'});
67
+ Future<MutationOutcome> _change(String operation, Map<String, dynamic> item,
68
+ Map<String, dynamic> payload) =>
69
+ _serial(() async {
70
+ final expected = int.tryParse(item['version'].toString()) ?? 0;
71
+ final mutation = <String, dynamic>{
72
+ 'id': newMutationId(),
73
+ 'entityType': 'plan_item',
74
+ 'entityId': item['id'],
75
+ 'operation': operation,
76
+ 'expectedVersion': expected,
77
+ 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
78
+ 'payload': payload
79
+ };
80
+ final optimistic = optimisticPlanItem(item, mutation);
81
+ await store.enqueue(mutation, optimisticItem: optimistic);
82
+ try {
83
+ await _flushQueue();
84
+ final pending =
85
+ (await store.readQueue()).any((m) => m['id'] == mutation['id']);
86
+ final cached = (await store.readPlanner())
87
+ .where((m) => m['id'] == item['id'])
88
+ .firstOrNull;
89
+ return MutationOutcome(queued: pending, item: cached ?? optimistic);
90
+ } catch (error) {
91
+ if (isOfflineFailure(error)) {
92
+ return MutationOutcome(queued: true, item: optimistic);
93
+ }
94
+ rethrow;
95
+ }
96
+ });
97
+
98
+ Future<MutationOutcome> _send(Map<String, dynamic> mutation) async {
99
+ final response = await api.submitSyncMutations([mutation]);
100
+ final results = response['results'];
101
+ if (results is! List ||
102
+ results.length != 1 ||
103
+ results.single is! Map ||
104
+ (results.single as Map)['id'] != mutation['id']) {
105
+ throw const ApiException(502, 'invalid_sync_acknowledgement');
106
+ }
107
+ final result = results.single as Map;
108
+ if (result['status'] == 'accepted' ||
109
+ result['status'] == 'already_applied') {
110
+ final rawItem = result['item'];
111
+ final version =
112
+ rawItem is Map ? int.tryParse(rawItem['version'].toString()) : null;
113
+ final expected =
114
+ int.tryParse(mutation['expectedVersion'].toString()) ?? 0;
115
+ final acceptedAt = result['acceptedAt'];
116
+ if (rawItem is! Map ||
117
+ rawItem['id'] != mutation['entityId'] ||
118
+ version == null ||
119
+ version < expected + 1 ||
120
+ acceptedAt is! String ||
121
+ DateTime.tryParse(acceptedAt) == null) {
122
+ throw const ApiException(502, 'invalid_sync_acknowledgement');
123
+ }
124
+ final item = Map<String, dynamic>.from(rawItem);
125
+ await store.acknowledge(mutation['id'] as String,
126
+ item: item, acceptedAt: result['acceptedAt'] as String?);
127
+ return MutationOutcome(queued: false, item: item);
128
+ }
129
+ final conflict = result['status'] == 'conflict';
130
+ await store.markQueued(
131
+ mutation['id'] as String, conflict ? 'conflict' : 'rejected',
132
+ error: result['error']?.toString());
133
+ throw ApiException(
134
+ conflict ? 409 : 422,
135
+ conflict
136
+ ? 'sync_conflict'
137
+ : (result['error']?.toString() ?? 'sync_rejected'));
138
+ }
139
+
140
+ Future<void> flush() => _serial(_flushQueue);
141
+ Future<void> _flushQueue() async {
142
+ for (final queued in await store.readQueue()) {
143
+ if (queued['entityType'] != 'plan_item') continue;
144
+ if (queued['queueStatus'] == 'conflict') {
145
+ throw const ApiException(409, 'sync_conflict');
146
+ }
147
+ if (queued['queueStatus'] != 'queued') continue;
148
+ final mutation = Map<String, dynamic>.from(queued)
149
+ ..remove('queuedAt')
150
+ ..remove('queueStatus')
151
+ ..remove('lastError');
152
+ try {
153
+ await _send(mutation);
154
+ } catch (error) {
155
+ if (isOfflineFailure(error)) return;
156
+ rethrow;
157
+ }
158
+ }
159
+ }
160
+}
apps/lifemate/lib/runtime_config.dart
new
+116
@@ -0,0 +1,116 @@
1
+import 'dart:convert';
2
+
3
+import 'package:flutter/foundation.dart';
4
+import 'package:http/http.dart' as http;
5
+import 'package:shared_preferences/shared_preferences.dart';
6
+
7
+String normalizeApiUrl(String value, {Uri? webOrigin}) {
8
+ var uri = Uri.tryParse(value.trim());
9
+ if (uri != null &&
10
+ !uri.hasScheme &&
11
+ value.trim().startsWith('/') &&
12
+ !value.trim().startsWith('//') &&
13
+ webOrigin != null) {
14
+ uri = webOrigin.resolve(value.trim());
15
+ }
16
+ if (uri == null ||
17
+ uri.scheme != 'https' ||
18
+ uri.host.isEmpty ||
19
+ uri.userInfo.isNotEmpty ||
20
+ uri.hasQuery ||
21
+ uri.hasFragment) {
22
+ throw ArgumentError(
23
+ 'API address must be HTTPS without credentials, query or fragment.');
24
+ }
25
+ uri = uri.normalizePath();
26
+ return uri.toString().replaceFirst(RegExp(r'/+$'), '');
27
+}
28
+
29
+class RuntimeConfig {
30
+ RuntimeConfig(
31
+ {String? apiBaseUrl,
32
+ List<String> apiFallbackUrls = const [],
33
+ Uri? webOrigin})
34
+ : apiBaseUrl = apiBaseUrl == null || apiBaseUrl.trim().isEmpty
35
+ ? null
36
+ : normalizeApiUrl(apiBaseUrl, webOrigin: webOrigin),
37
+ apiFallbackUrls = List.unmodifiable(apiFallbackUrls
38
+ .map((url) => normalizeApiUrl(url, webOrigin: webOrigin))
39
+ .toSet()) {
40
+ if (this.apiBaseUrl == null && this.apiFallbackUrls.isNotEmpty ||
41
+ endpoints.length > 6) {
42
+ throw ArgumentError(
43
+ 'Choose a primary API and at most five alternatives.');
44
+ }
45
+ }
46
+ final String? apiBaseUrl;
47
+ final List<String> apiFallbackUrls;
48
+ bool get isConfigured => apiBaseUrl != null;
49
+ List<String> get endpoints => [
50
+ if (apiBaseUrl != null) apiBaseUrl!,
51
+ ...apiFallbackUrls.where((url) => url != apiBaseUrl)
52
+ ];
53
+ Map<String, dynamic> toJson() =>
54
+ {'apiBaseUrl': apiBaseUrl, 'apiFallbackUrls': apiFallbackUrls};
55
+ factory RuntimeConfig.fromJson(Map<String, dynamic> json, {Uri? webOrigin}) {
56
+ final base = json['apiBaseUrl'];
57
+ final fallback = json['apiFallbackUrls'] ?? const <String>[];
58
+ if ((base != null && base is! String) ||
59
+ fallback is! List ||
60
+ fallback.any((item) => item is! String)) {
61
+ throw const FormatException('Invalid runtime config.');
62
+ }
63
+ return RuntimeConfig(
64
+ apiBaseUrl: base as String?,
65
+ apiFallbackUrls: fallback.cast<String>(),
66
+ webOrigin: webOrigin);
67
+ }
68
+}
69
+
70
+class RuntimeConfigStore {
71
+ RuntimeConfigStore(
72
+ {http.Client? client,
73
+ bool? web,
74
+ Uri? webOrigin,
75
+ SharedPreferencesAsync? preferences})
76
+ : _client = client ?? http.Client(),
77
+ _web = web ?? kIsWeb,
78
+ _origin = webOrigin ?? Uri.base,
79
+ _preferences = preferences;
80
+ static const key = 'lifeguide.api_endpoints.v1';
81
+ final http.Client _client;
82
+ final bool _web;
83
+ final Uri _origin;
84
+ final SharedPreferencesAsync? _preferences;
85
+ SharedPreferencesAsync get preferences =>
86
+ _preferences ?? SharedPreferencesAsync();
87
+
88
+ Future<RuntimeConfig> load() async {
89
+ if (!_web) {
90
+ final raw = await preferences.getString(key);
91
+ return raw == null
92
+ ? RuntimeConfig()
93
+ : RuntimeConfig.fromJson(jsonDecode(raw) as Map<String, dynamic>);
94
+ }
95
+ if (_origin.scheme != 'https') {
96
+ throw StateError('LifeGuide web startup requires HTTPS.');
97
+ }
98
+ final uri = _origin.resolve('/config.json').replace(queryParameters: {
99
+ 'fresh': DateTime.now().microsecondsSinceEpoch.toString()
100
+ });
101
+ final response = await _client.get(uri, headers: {
102
+ 'Cache-Control': 'no-store'
103
+ }).timeout(const Duration(seconds: 15));
104
+ if (response.statusCode != 200 || response.body.length > 16384) {
105
+ throw const FormatException('Runtime configuration is unavailable.');
106
+ }
107
+ return RuntimeConfig.fromJson(
108
+ jsonDecode(response.body) as Map<String, dynamic>,
109
+ webOrigin: _origin);
110
+ }
111
+
112
+ Future<void> saveAndroid(RuntimeConfig config) async {
113
+ if (_web) throw StateError('Web configuration is managed by config.json.');
114
+ await preferences.setString(key, jsonEncode(config.toJson()));
115
+ }
116
+}
apps/lifemate/lib/runtime_controller.dart
new
+105
@@ -0,0 +1,105 @@
1
+import 'package:flutter/foundation.dart';
2
+import 'api.dart';
3
+import 'runtime_config.dart';
4
+import 'session_store.dart';
5
+
6
+class RuntimeController extends ChangeNotifier {
7
+ RuntimeController(
8
+ {RuntimeConfigStore? configStore,
9
+ SessionStore? sessionStore,
10
+ this.onScopeDiscarded,
11
+ HttpIdentityApi Function(RuntimeConfig)? apiFactory})
12
+ : _configStore = configStore ?? RuntimeConfigStore(),
13
+ _sessionStore = sessionStore ?? createSessionStore(),
14
+ _apiFactory = apiFactory;
15
+ final RuntimeConfigStore _configStore;
16
+ final SessionStore _sessionStore;
17
+ final Future<void> Function(String)? onScopeDiscarded;
18
+ final HttpIdentityApi Function(RuntimeConfig)? _apiFactory;
19
+ RuntimeConfig config = RuntimeConfig();
20
+ HttpIdentityApi? api;
21
+ Object? error;
22
+ bool initialized = false;
23
+ bool _disposed = false;
24
+ int _generation = 0;
25
+ String? get cacheNamespace => api?.cacheNamespace;
26
+ void _notify() {
27
+ if (!_disposed) notifyListeners();
28
+ }
29
+
30
+ HttpIdentityApi _createApi(RuntimeConfig config) {
31
+ final next = _apiFactory?.call(config) ??
32
+ HttpIdentityApi(
33
+ baseUrl: config.apiBaseUrl!, sessionStore: _sessionStore);
34
+ next.onSessionChanged = _notify;
35
+ next.onScopeDiscarded = onScopeDiscarded;
36
+ return next;
37
+ }
38
+
39
+ Future<void> initialize() async {
40
+ if (_disposed) return;
41
+ final generation = ++_generation;
42
+ error = null;
43
+ api?.close();
44
+ api = null;
45
+ try {
46
+ final loaded = await _configStore.load();
47
+ if (_disposed || generation != _generation) return;
48
+ config = loaded;
49
+ if (config.isConfigured) {
50
+ api = _createApi(config);
51
+ await api!.restoreSession();
52
+ }
53
+ } catch (failure) {
54
+ if (_disposed || generation != _generation) return;
55
+ error = failure;
56
+ }
57
+ if (_disposed || generation != _generation) return;
58
+ initialized = true;
59
+ _notify();
60
+ }
61
+
62
+ /// Server switches invalidate the session before any new endpoint is used.
63
+ /// Caller discards its previous user/endpoint cache and queued mutations.
64
+ Future<void> updateEndpoints(RuntimeConfig next) async {
65
+ if (_disposed) return;
66
+ _generation++;
67
+ try {
68
+ await api?.logout(revoke: false);
69
+ await _sessionStore.clear();
70
+ api?.close();
71
+ api = null;
72
+ await _configStore.saveAndroid(next);
73
+ config = next;
74
+ error = null;
75
+ if (next.isConfigured && !_disposed) {
76
+ api = _createApi(next);
77
+ }
78
+ } catch (failure) {
79
+ error = failure;
80
+ rethrow;
81
+ } finally {
82
+ _notify();
83
+ }
84
+ }
85
+
86
+ Future<void> signOut() async {
87
+ try {
88
+ await api?.logout();
89
+ error = null;
90
+ } catch (failure) {
91
+ error = failure;
92
+ rethrow;
93
+ } finally {
94
+ _notify();
95
+ }
96
+ }
97
+
98
+ @override
99
+ void dispose() {
100
+ _disposed = true;
101
+ _generation++;
102
+ api?.close();
103
+ super.dispose();
104
+ }
105
+}
apps/lifemate/lib/runtime_http_client.dart
new
+5
@@ -0,0 +1,5 @@
1
+import 'package:http/http.dart' as http;
2
+import 'runtime_http_client_native.dart'
3
+ if (dart.library.js_interop) 'runtime_http_client_web.dart' as platform;
4
+
5
+http.Client createRuntimeHttpClient() => platform.createClient();
apps/lifemate/lib/runtime_http_client_native.dart
new
+25
@@ -0,0 +1,25 @@
1
+import 'dart:convert';
2
+import 'dart:io';
3
+import 'package:flutter/foundation.dart';
4
+import 'package:http/io_client.dart';
5
+
6
+IOClient createClient() {
7
+ const publicCa = String.fromEnvironment('LIFEGUIDE_DEBUG_CA_BASE64');
8
+ if (publicCa.isNotEmpty && !kDebugMode) {
9
+ throw StateError(
10
+ 'Custom development CA is forbidden outside debug builds.');
11
+ }
12
+ final context = SecurityContext(withTrustedRoots: true);
13
+ if (publicCa.isNotEmpty) {
14
+ final bytes = base64Decode(publicCa);
15
+ if (bytes.length > 65536) {
16
+ throw ArgumentError('Public development CA exceeds 64 KiB.');
17
+ }
18
+ if (utf8.decode(bytes).contains('PRIVATE KEY')) {
19
+ throw ArgumentError('Only a public CA certificate may be supplied.');
20
+ }
21
+ context.setTrustedCertificatesBytes(bytes);
22
+ }
23
+ return IOClient(HttpClient(context: context)
24
+ ..connectionTimeout = const Duration(seconds: 15));
25
+}
apps/lifemate/lib/runtime_http_client_web.dart
new
+10
@@ -0,0 +1,10 @@
1
+import 'package:flutter/foundation.dart';
2
+import 'package:http/browser_client.dart';
3
+
4
+BrowserClient createClient() {
5
+ const publicCa = String.fromEnvironment('LIFEGUIDE_DEBUG_CA_BASE64');
6
+ if (publicCa.isNotEmpty && !kDebugMode) {
7
+ throw StateError('Development CA is forbidden in release.');
8
+ }
9
+ return BrowserClient();
10
+}
apps/lifemate/lib/session_store.dart
new
+30
@@ -0,0 +1,30 @@
1
+import 'session_store_native.dart'
2
+ if (dart.library.js_interop) 'session_store_web.dart' as platform;
3
+
4
+abstract class SessionStore {
5
+ Future<String?> read();
6
+ Future<void> write(String value);
7
+ Future<void> clear();
8
+}
9
+
10
+SessionStore createSessionStore() =>
11
+ SerializedSessionStore(platform.PlatformSessionStore());
12
+const sessionStorageKey = 'lifeguide.refresh_session.v1';
13
+
14
+class SerializedSessionStore implements SessionStore {
15
+ SerializedSessionStore(this.inner);
16
+ final SessionStore inner;
17
+ static Future<void> _tail = Future.value();
18
+ Future<T> _locked<T>(Future<T> Function() operation) {
19
+ final next = _tail.then((_) => operation());
20
+ _tail = next.then<void>((_) {}, onError: (Object _, StackTrace __) {});
21
+ return next;
22
+ }
23
+
24
+ @override
25
+ Future<String?> read() => _locked(inner.read);
26
+ @override
27
+ Future<void> write(String value) => _locked(() => inner.write(value));
28
+ @override
29
+ Future<void> clear() => _locked(inner.clear);
30
+}
apps/lifemate/lib/session_store_native.dart
new
+13
@@ -0,0 +1,13 @@
1
+import 'package:flutter_secure_storage/flutter_secure_storage.dart';
2
+import 'session_store.dart';
3
+
4
+class PlatformSessionStore implements SessionStore {
5
+ final FlutterSecureStorage _storage = const FlutterSecureStorage();
6
+ @override
7
+ Future<String?> read() => _storage.read(key: sessionStorageKey);
8
+ @override
9
+ Future<void> write(String value) =>
10
+ _storage.write(key: sessionStorageKey, value: value);
11
+ @override
12
+ Future<void> clear() => _storage.delete(key: sessionStorageKey);
13
+}
apps/lifemate/lib/session_store_web.dart
new
+22
@@ -0,0 +1,22 @@
1
+import 'dart:js_interop';
2
+import 'session_store.dart';
3
+
4
+@JS('localStorage')
5
+external _Storage get _storage;
6
+extension type _Storage(JSObject _) implements JSObject {
7
+ external String? getItem(String key);
8
+ external void setItem(String key, String value);
9
+ external void removeItem(String key);
10
+}
11
+
12
+/// One opaque refresh token, bound to its configured HTTPS endpoint. Access
13
+/// tokens stay in memory. This requires the host's HTTPS and strict CSP gates.
14
+class PlatformSessionStore implements SessionStore {
15
+ @override
16
+ Future<String?> read() async => _storage.getItem(sessionStorageKey);
17
+ @override
18
+ Future<void> write(String value) async =>
19
+ _storage.setItem(sessionStorageKey, value);
20
+ @override
21
+ Future<void> clear() async => _storage.removeItem(sessionStorageKey);
22
+}
apps/lifemate/lib/study_coordinator.dart
new
+135
@@ -0,0 +1,135 @@
1
+import 'api.dart';
2
+import 'offline_store.dart';
3
+import 'plan_sync.dart';
4
+
5
+/// Mutations are persisted before sending. Pending events retain their exact
6
+/// body and version, and must be acknowledged before another event is sent.
7
+class StudySync {
8
+ StudySync(this.api, {OfflineStore? store})
9
+ : store = store ?? OfflineStore.forApi(api);
10
+ final HttpIdentityApi api;
11
+ final OfflineStore store;
12
+ Future<void>? _flush;
13
+ Future<MutationOutcome> start(String planItemId) async {
14
+ final sessionId = newMutationId();
15
+ final mutationId = newMutationId();
16
+ return _change(
17
+ 'study_start',
18
+ sessionId,
19
+ {
20
+ 'id': sessionId,
21
+ 'mutationId': mutationId,
22
+ 'planItemId': planItemId,
23
+ 'source': 'timer',
24
+ 'startedAt': DateTime.now().toUtc().toIso8601String()
25
+ },
26
+ mutationId,
27
+ 0);
28
+ }
29
+
30
+ Future<MutationOutcome> event(
31
+ Map<String, dynamic> session, String action) async {
32
+ final id = newMutationId();
33
+ final version = int.tryParse(session['version'].toString()) ?? 0;
34
+ return _change(
35
+ 'study_event',
36
+ session['id'].toString(),
37
+ {
38
+ 'mutationId': id,
39
+ 'expectedVersion': version,
40
+ 'action': action,
41
+ 'occurredAt': DateTime.now().toUtc().toIso8601String()
42
+ },
43
+ id,
44
+ version);
45
+ }
46
+
47
+ Future<MutationOutcome> archive(Map<String, dynamic> session) async {
48
+ final id = newMutationId();
49
+ final version = int.tryParse(session['version'].toString()) ?? 0;
50
+ return _change('study_archive', session['id'].toString(),
51
+ {'mutationId': id, 'expectedVersion': version}, id, version);
52
+ }
53
+
54
+ Future<MutationOutcome> _change(String operation, String entityId,
55
+ Map<String, dynamic> payload, String id, int version) async {
56
+ if ((await store.readQueue())
57
+ .any((m) => m['entityType'] == 'study_session')) {
58
+ throw const ApiException(409, 'sync_pending');
59
+ }
60
+ final mutation = <String, dynamic>{
61
+ 'id': id,
62
+ 'entityType': 'study_session',
63
+ 'entityId': entityId,
64
+ 'operation': operation,
65
+ 'payload': payload,
66
+ 'expectedVersion': version
67
+ };
68
+ await store.enqueue(mutation);
69
+ try {
70
+ return await _send(mutation);
71
+ } catch (error) {
72
+ if (isOfflineFailure(error)) return const MutationOutcome(queued: true);
73
+ rethrow;
74
+ }
75
+ }
76
+
77
+ Future<MutationOutcome> _send(Map<String, dynamic> mutation) async {
78
+ final body = Map<String, dynamic>.from(mutation['payload'] as Map);
79
+ final id = mutation['entityId'].toString();
80
+ Map<String, dynamic> response;
81
+ try {
82
+ response = switch (mutation['operation']) {
83
+ 'study_start' => await api.startStudySession(body),
84
+ 'study_event' => await api.recordStudySessionEvent(id, body),
85
+ 'study_archive' => await api.archiveStudySession(id, body),
86
+ _ => throw const ApiException(422, 'invalid_study_mutation'),
87
+ };
88
+ } catch (error) {
89
+ if (error is ApiException && error.statusCode == 409) {
90
+ await store.markQueued(mutation['id'].toString(), 'conflict',
91
+ error: error.code);
92
+ }
93
+ rethrow;
94
+ }
95
+ final ack = response['acknowledgement'];
96
+ if (ack is! Map ||
97
+ ack['mutationId'] != mutation['id'] ||
98
+ !['accepted', 'already_applied'].contains(ack['status'])) {
99
+ throw const ApiException(502, 'invalid_sync_acknowledgement');
100
+ }
101
+ final raw = response['session'];
102
+ final acceptedAt = ack['acceptedAt'];
103
+ final expected = int.tryParse(mutation['expectedVersion'].toString()) ?? 0;
104
+ if (raw is! Map ||
105
+ raw['id'] != mutation['entityId'] ||
106
+ raw['version'] is! int ||
107
+ raw['version'] < expected + 1 ||
108
+ acceptedAt is! String ||
109
+ DateTime.tryParse(acceptedAt) == null) {
110
+ throw const ApiException(502, 'invalid_sync_acknowledgement');
111
+ }
112
+ final session = Map<String, dynamic>.from(raw);
113
+ await store.acknowledge(mutation['id'].toString(),
114
+ item: session, acceptedAt: acceptedAt, cacheKey: 'study.sessions');
115
+ return MutationOutcome(queued: false, item: session);
116
+ }
117
+
118
+ Future<void> flush() =>
119
+ _flush ??= _flushQueue().whenComplete(() => _flush = null);
120
+ Future<void> _flushQueue() async {
121
+ for (final m in await store.readQueue()) {
122
+ if (m['entityType'] != 'study_session') continue;
123
+ if (m['queueStatus'] == 'conflict') {
124
+ throw const ApiException(409, 'sync_conflict');
125
+ }
126
+ if (m['queueStatus'] != 'queued') continue;
127
+ try {
128
+ await _send(m);
129
+ } catch (error) {
130
+ if (isOfflineFailure(error)) return;
131
+ rethrow;
132
+ }
133
+ }
134
+ }
135
+}
apps/lifemate/lib/study_ui.dart
new
+245
@@ -0,0 +1,245 @@
1
+import 'dart:async';
2
+import 'package:flutter/material.dart';
3
+import 'api.dart';
4
+import 'offline_store.dart';
5
+import 'phase3_ui.dart';
6
+import 'study_coordinator.dart';
7
+
8
+class StudyHub extends StatelessWidget {
9
+ const StudyHub({super.key, required this.api});
10
+ final IdentityApi api;
11
+ @override
12
+ Widget build(BuildContext context) => Column(children: [
13
+ const Padding(
14
+ padding: EdgeInsets.all(16),
15
+ child: Text(
16
+ 'تایمر را از منوی هر تکلیف در برنامهریز باز کن. زمان ثبتشده، گزارش شخصی است و اثبات مطالعه نیست.')),
17
+ Expanded(child: PlannerPage(api: api))
18
+ ]);
19
+}
20
+
21
+class StudyTimerPage extends StatefulWidget {
22
+ const StudyTimerPage({super.key, required this.api, required this.item});
23
+ final HttpIdentityApi api;
24
+ final Map<String, dynamic> item;
25
+ @override
26
+ State<StudyTimerPage> createState() => _StudyTimerPageState();
27
+}
28
+
29
+class _StudyTimerPageState extends State<StudyTimerPage>
30
+ with WidgetsBindingObserver {
31
+ late final StudySync sync;
32
+ List<Map<String, dynamic>> sessions = [];
33
+ bool busy = false, loaded = false, offline = false, pending = false;
34
+ String? error;
35
+ Timer? ticker, poll;
36
+ DateTime? fetchedAt;
37
+ @override
38
+ void initState() {
39
+ super.initState();
40
+ sync = StudySync(widget.api);
41
+ WidgetsBinding.instance.addObserver(this);
42
+ timers();
43
+ load();
44
+ }
45
+
46
+ void timers() {
47
+ ticker?.cancel();
48
+ poll?.cancel();
49
+ ticker = Timer.periodic(const Duration(seconds: 1), (_) {
50
+ if (mounted) setState(() {});
51
+ });
52
+ poll = Timer.periodic(const Duration(seconds: 15), (_) {
53
+ if (!busy) load();
54
+ });
55
+ }
56
+
57
+ @override
58
+ void didChangeAppLifecycleState(AppLifecycleState s) {
59
+ if (s == AppLifecycleState.resumed) {
60
+ timers();
61
+ load();
62
+ } else {
63
+ ticker?.cancel();
64
+ poll?.cancel();
65
+ }
66
+ }
67
+
68
+ @override
69
+ void dispose() {
70
+ ticker?.cancel();
71
+ poll?.cancel();
72
+ WidgetsBinding.instance.removeObserver(this);
73
+ super.dispose();
74
+ }
75
+
76
+ Map<String, dynamic>? get current {
77
+ final active = sessions
78
+ .where((s) => s['status'] == 'running' || s['status'] == 'paused');
79
+ return active.isEmpty ? null : active.first;
80
+ }
81
+
82
+ Future<void> load() async {
83
+ if (busy) return;
84
+ setState(() {
85
+ busy = true;
86
+ error = null;
87
+ });
88
+ try {
89
+ await sync.flush();
90
+ final rows = await widget.api
91
+ .listStudySessions(planItemId: widget.item['id'].toString());
92
+ final store = sync.store;
93
+ final all = await store.readList('study.sessions');
94
+ all.removeWhere((s) => s['planItemId'] == widget.item['id']);
95
+ all.addAll(rows);
96
+ await store.writeList('study.sessions', all);
97
+ final hasPending = (await store.readQueue())
98
+ .any((m) => m['entityType'] == 'study_session');
99
+ if (mounted) {
100
+ setState(() {
101
+ sessions = rows;
102
+ loaded = true;
103
+ offline = false;
104
+ pending = hasPending;
105
+ fetchedAt = DateTime.now();
106
+ });
107
+ }
108
+ } catch (e) {
109
+ if (isOfflineFailure(e)) {
110
+ try {
111
+ final cache = await sync.store.readList('study.sessions');
112
+ final queue = await sync.store.readQueue();
113
+ if (mounted) {
114
+ setState(() {
115
+ sessions = cache
116
+ .where((s) => s['planItemId'] == widget.item['id'])
117
+ .toList();
118
+ loaded = true;
119
+ offline = true;
120
+ pending = queue.any((m) => m['entityType'] == 'study_session');
121
+ error = uiErrorText(e);
122
+ });
123
+ }
124
+ } catch (storage) {
125
+ if (mounted) setState(() => error = uiErrorText(storage));
126
+ }
127
+ } else {
128
+ if (mounted) {
129
+ setState(() {
130
+ error = uiErrorText(e);
131
+ offline = true;
132
+ });
133
+ }
134
+ }
135
+ } finally {
136
+ if (mounted) setState(() => busy = false);
137
+ }
138
+ }
139
+
140
+ Future<void> act(String action) async {
141
+ if (busy || pending) return;
142
+ setState(() {
143
+ busy = true;
144
+ error = null;
145
+ });
146
+ try {
147
+ final outcome = action == 'start'
148
+ ? await sync.start(widget.item['id'].toString())
149
+ : await sync.event(current!, action);
150
+ if (mounted) {
151
+ setState(() {
152
+ pending = outcome.queued;
153
+ if (outcome.item != null) {
154
+ sessions.removeWhere((s) => s['id'] == outcome.item!['id']);
155
+ sessions.add(outcome.item!);
156
+ }
157
+ if (outcome.queued) {
158
+ offline = true;
159
+ error =
160
+ 'رویداد روی دستگاه ثبت شد؛ شروع یا پایان در سرور هنوز تأیید نشده است.';
161
+ }
162
+ });
163
+ }
164
+ } catch (e) {
165
+ if (mounted) setState(() => error = uiErrorText(e));
166
+ } finally {
167
+ if (mounted) setState(() => busy = false);
168
+ }
169
+ }
170
+
171
+ int elapsed(Map<String, dynamic> session) {
172
+ var seconds = (session['recordedDurationSeconds'] as num? ?? 0).toInt();
173
+ if (session['status'] == 'running' && !offline && !pending) {
174
+ final intervals = session['intervals'] as List? ?? [];
175
+ if (intervals.isNotEmpty) {
176
+ final last = intervals.last as Map;
177
+ if (last['end'] == null) {
178
+ final start = DateTime.tryParse(last['start'].toString());
179
+ if (start != null) {
180
+ final difference =
181
+ DateTime.now().toUtc().difference(start).inSeconds;
182
+ if (difference > 0) seconds += difference;
183
+ }
184
+ }
185
+ }
186
+ }
187
+ return seconds;
188
+ }
189
+
190
+ String duration(int seconds) =>
191
+ '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}';
192
+ @override
193
+ Widget build(BuildContext context) => Scaffold(
194
+ appBar: AppBar(title: const Text('تایمر مطالعه')),
195
+ body: ListView(padding: const EdgeInsets.all(20), children: [
196
+ Text(widget.item['title']?.toString() ?? '',
197
+ style: Theme.of(context).textTheme.headlineSmall),
198
+ const Text(
199
+ 'زمان ثبتشده، گزارش شخصی است و اثبات مطالعه نیست. توقف تایمر تکلیف را انجامشده نمیکند.'),
200
+ SyncNotice(
201
+ offline: offline, pending: pending ? 1 : 0, syncedAt: fetchedAt),
202
+ if (error != null)
203
+ Card(
204
+ child: Padding(
205
+ padding: const EdgeInsets.all(12), child: Text(error!))),
206
+ if (!loaded && busy) const LinearProgressIndicator(),
207
+ if (current != null) ...[
208
+ Text(duration(elapsed(current!)),
209
+ textAlign: TextAlign.center,
210
+ style: Theme.of(context).textTheme.displayMedium),
211
+ Text(
212
+ offline
213
+ ? 'زمان دریافتشده قبلی؛ وضعیت فعلی تأیید نشده'
214
+ : 'نمایش زمان دستگاه؛ مقدار نهایی پس از تأیید سرور ثبت میشود.',
215
+ textAlign: TextAlign.center),
216
+ Row(children: [
217
+ Expanded(
218
+ child: FilledButton(
219
+ onPressed: busy || pending
220
+ ? null
221
+ : () => act(current!['status'] == 'running'
222
+ ? 'pause'
223
+ : 'resume'),
224
+ child: Text(
225
+ current!['status'] == 'running' ? 'مکث' : 'ادامه'))),
226
+ const SizedBox(width: 12),
227
+ Expanded(
228
+ child: OutlinedButton(
229
+ onPressed: busy || pending ? null : () => act('stop'),
230
+ child: const Text('پایان')))
231
+ ]),
232
+ ] else
233
+ FilledButton.icon(
234
+ onPressed: !loaded || busy || pending ? null : () => act('start'),
235
+ icon: const Icon(Icons.play_arrow),
236
+ label: const Text('شروع مطالعه')),
237
+ TextButton(
238
+ onPressed: busy ? null : load,
239
+ child: const Text('همگامسازی و تلاش دوباره')),
240
+ ...sessions.where((s) => s['status'] == 'completed').map((s) => ListTile(
241
+ title: const Text('جلسه پایانیافته'),
242
+ subtitle: Text(
243
+ '${duration(elapsed(s))} ثبتشده · ${shortDate(s['endedAt'])}'))),
244
+ ]));
245
+}
apps/lifemate/lib/sync_changes_ui.dart
new
+270
@@ -0,0 +1,270 @@
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
+
9
+class SyncChangesPage extends StatefulWidget {
10
+ const SyncChangesPage({super.key, required this.api});
11
+ final IdentityApi api;
12
+
13
+ @override
14
+ State<SyncChangesPage> createState() => _SyncChangesPageState();
15
+}
16
+
17
+class _SyncChangesPageState extends State<SyncChangesPage> {
18
+ late final OfflineStore store;
19
+ List<Map<String, dynamic>> queue = [], journal = [];
20
+ bool loading = true, busy = false, dialogOpen = false, storeReady = false;
21
+ Object? error;
22
+ final hiddenEntities = <String>{};
23
+
24
+ @override
25
+ void initState() {
26
+ super.initState();
27
+ try {
28
+ store = OfflineStore.forApi(widget.api);
29
+ storeReady = true;
30
+ _load();
31
+ } catch (failure) {
32
+ error = failure;
33
+ loading = false;
34
+ }
35
+ }
36
+
37
+ Future<void> _load() async {
38
+ try {
39
+ final pending = await store.readQueue();
40
+ final discarded = await store.readDiscardedChanges();
41
+ if (!mounted) return;
42
+ setState(() {
43
+ queue = pending;
44
+ journal = discarded;
45
+ loading = false;
46
+ });
47
+ } catch (failure) {
48
+ if (mounted) {
49
+ setState(() {
50
+ error = failure;
51
+ loading = false;
52
+ });
53
+ }
54
+ }
55
+ }
56
+
57
+ Future<void> _retry() async {
58
+ if (busy) return;
59
+ setState(() {
60
+ busy = true;
61
+ error = null;
62
+ });
63
+ try {
64
+ Object? failure;
65
+ try {
66
+ await PlanSync(widget.api, store: store).flush();
67
+ } catch (caught) {
68
+ failure = caught;
69
+ }
70
+ final api = widget.api;
71
+ if (api is HttpIdentityApi) {
72
+ try {
73
+ await StudySync(api, store: store).flush();
74
+ } catch (caught) {
75
+ failure ??= caught;
76
+ }
77
+ }
78
+ if (failure != null) throw failure;
79
+ } catch (failure) {
80
+ if (mounted) setState(() => error = failure);
81
+ } finally {
82
+ await _load();
83
+ if (mounted) setState(() => busy = false);
84
+ }
85
+ }
86
+
87
+ Future<void> _resolve(Map<String, dynamic> mutation) async {
88
+ if (busy) return;
89
+ final api = widget.api;
90
+ if (api is! HttpIdentityApi) {
91
+ setState(
92
+ () => error = const ApiException(503, 'configured_api_required'));
93
+ return;
94
+ }
95
+ final id = mutation['entityId'] as String;
96
+ setState(() {
97
+ busy = true;
98
+ error = null;
99
+ });
100
+ try {
101
+ Map<String, dynamic>? serverItem;
102
+ try {
103
+ serverItem = await api.requestJson(
104
+ 'GET', '/v1/plan-items/${Uri.encodeComponent(id)}');
105
+ } on ApiException catch (failure) {
106
+ final isUnsent =
107
+ queue.any((m) => m['entityId'] == id && m['operation'] == 'create');
108
+ if (failure.statusCode != 404 || !isUnsent) rethrow;
109
+ }
110
+ if (serverItem != null &&
111
+ (serverItem['id'] != id ||
112
+ int.tryParse(serverItem['version'].toString()) == null)) {
113
+ throw const ApiException(502, 'invalid_api_response');
114
+ }
115
+ if (!mounted) return;
116
+ final payload = mutation['payload'] as Map;
117
+ final local = _details(payload);
118
+ setState(() => dialogOpen = true);
119
+ final accepted = await showDialog<bool>(
120
+ context: context,
121
+ builder: (dialogContext) => AlertDialog(
122
+ title: const Text('بررسی تعارض'),
123
+ content: SingleChildScrollView(
124
+ child: Column(
125
+ mainAxisSize: MainAxisSize.min,
126
+ crossAxisAlignment: CrossAxisAlignment.start,
127
+ children: [
128
+ Text('تغییر محلی: $local'),
129
+ const SizedBox(height: 12),
130
+ Text(serverItem == null
131
+ ? 'این کار هنوز در سرور موجود نیست.'
132
+ : 'نسخه سرور ${serverItem['version']}: ${serverItem['title'] ?? ''}'),
133
+ if (serverItem != null)
134
+ Text(_details(serverItem, server: true)),
135
+ const SizedBox(height: 12),
136
+ const Text(
137
+ 'با این انتخاب، تمام تغییرهای معلق همین کار از صف خارج میشوند. متن تغییرها در پیشنویسهای نگهداریشده میماند تا بعداً دستی ویرایش کنی.'),
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: Text(serverItem == null
146
+ ? 'خارجکردن از صف و نگهداشتن پیشنویس'
147
+ : 'استفاده از نسخه سرور')),
148
+ ],
149
+ ));
150
+ if (mounted) setState(() => dialogOpen = false);
151
+ if (accepted == true) {
152
+ await store.discardEntityChanges(id, serverItem: serverItem);
153
+ }
154
+ } catch (failure) {
155
+ if (mounted) {
156
+ setState(() {
157
+ error = failure;
158
+ if (failure is ApiException &&
159
+ (failure.statusCode == 403 || failure.statusCode == 401)) {
160
+ hiddenEntities.add(id);
161
+ }
162
+ });
163
+ }
164
+ } finally {
165
+ await _load();
166
+ if (mounted) {
167
+ setState(() {
168
+ busy = false;
169
+ dialogOpen = false;
170
+ });
171
+ }
172
+ }
173
+ }
174
+
175
+ String _status(dynamic value) => switch (value) {
176
+ 'conflict' => 'تعارض؛ نیازمند انتخاب',
177
+ 'rejected' => 'سرور نپذیرفت',
178
+ _ => 'در انتظار تأیید سرور',
179
+ };
180
+
181
+ String _details(Map row, {bool server = false}) {
182
+ const labels = {
183
+ 'title': 'عنوان',
184
+ 'status': 'وضعیت',
185
+ 'visibility': 'اشتراک',
186
+ 'notes': 'یادداشت',
187
+ 'dueAt': 'مهلت',
188
+ 'startsAt': 'شروع',
189
+ 'endsAt': 'پایان',
190
+ 'plannedDurationSeconds': 'زمان برنامهریزیشده (ثانیه)',
191
+ };
192
+ const columns = {
193
+ 'dueAt': 'due_at',
194
+ 'startsAt': 'starts_at',
195
+ 'endsAt': 'ends_at',
196
+ 'plannedDurationSeconds': 'planned_duration_seconds'
197
+ };
198
+ const values = {
199
+ 'planned': 'برنامهریزیشده',
200
+ 'in_progress': 'در حال انجام',
201
+ 'completed': 'انجامشده',
202
+ 'cancelled': 'بایگانیشده',
203
+ 'private': 'خصوصی',
204
+ 'family': 'خانواده',
205
+ 'parent_guardians': 'سرپرستان',
206
+ 'selected_members': 'اعضای انتخابی'
207
+ };
208
+ return labels.entries
209
+ .where((entry) => row
210
+ .containsKey(server ? columns[entry.key] ?? entry.key : entry.key))
211
+ .map((entry) {
212
+ final value = row[server ? columns[entry.key] ?? entry.key : entry.key];
213
+ return '${entry.value}: ${value == null ? 'خالی' : values[value] ?? value}';
214
+ }).join('\n');
215
+ }
216
+
217
+ @override
218
+ Widget build(BuildContext context) => Scaffold(
219
+ appBar: AppBar(title: const Text('تغییرهای معلق')),
220
+ body: loading
221
+ ? const Center(child: CircularProgressIndicator())
222
+ : ListView(padding: const EdgeInsets.all(16), children: [
223
+ if (busy && !dialogOpen) const LinearProgressIndicator(),
224
+ if (error != null)
225
+ Text(uiErrorText(error!),
226
+ style: TextStyle(
227
+ color: Theme.of(context).colorScheme.error)),
228
+ FilledButton.icon(
229
+ onPressed: busy || !storeReady ? null : _retry,
230
+ icon: const Icon(Icons.sync),
231
+ label: const Text('تلاش دوباره برای همگامسازی')),
232
+ if (queue.isEmpty)
233
+ const Padding(
234
+ padding: EdgeInsets.all(16),
235
+ child: Text('تغییر معلقی باقی نمانده است.')),
236
+ for (final mutation in queue)
237
+ ListTile(
238
+ title: Text(hiddenEntities.contains(mutation['entityId'])
239
+ ? 'تغییر بدون دسترسی'
240
+ : (mutation['payload'] as Map)['title']?.toString() ??
241
+ (mutation['entityType'] == 'study_session'
242
+ ? 'ثبت مطالعه'
243
+ : 'تغییر کار')),
244
+ subtitle: Text(_status(mutation['queueStatus'])),
245
+ trailing: mutation['entityType'] == 'plan_item' &&
246
+ ['conflict', 'rejected']
247
+ .contains(mutation['queueStatus']) &&
248
+ !hiddenEntities.contains(mutation['entityId'])
249
+ ? TextButton(
250
+ onPressed: busy ? null : () => _resolve(mutation),
251
+ child: const Text('بررسی و انتخاب'))
252
+ : null,
253
+ ),
254
+ if (journal.isNotEmpty) ...[
255
+ const Divider(),
256
+ Text('پیشنویسهای نگهداریشده',
257
+ style: Theme.of(context).textTheme.titleMedium),
258
+ const Text(
259
+ 'این تغییرها ارسال نمیشوند. عنوان را برای بازیابی دستی در ویرایش کار نگه داشتهایم.'),
260
+ for (final entry in journal)
261
+ ListTile(
262
+ title: Text(
263
+ (entry['payload'] as Map)['title']?.toString() ??
264
+ entry['recoveryTitle']?.toString() ??
265
+ 'تغییر وضعیت یا جزئیات'),
266
+ subtitle: const Text('پیشنویس محلی؛ تأیید سرور نیست')),
267
+ ],
268
+ ]),
269
+ );
270
+}
apps/lifemate/pubspec.lock
new
+575
@@ -0,0 +1,575 @@
1
+# Generated by pub
2
+# See https://dart.dev/tools/pub/glossary#lockfile
3
+packages:
4
+ args:
5
+ dependency: transitive
6
+ description:
7
+ name: args
8
+ sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
9
+ url: "https://pub.dev"
10
+ source: hosted
11
+ version: "2.7.0"
12
+ async:
13
+ dependency: transitive
14
+ description:
15
+ name: async
16
+ sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
17
+ url: "https://pub.dev"
18
+ source: hosted
19
+ version: "2.13.1"
20
+ boolean_selector:
21
+ dependency: transitive
22
+ description:
23
+ name: boolean_selector
24
+ sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
25
+ url: "https://pub.dev"
26
+ source: hosted
27
+ version: "2.1.2"
28
+ characters:
29
+ dependency: transitive
30
+ description:
31
+ name: characters
32
+ sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
33
+ url: "https://pub.dev"
34
+ source: hosted
35
+ version: "1.4.1"
36
+ clock:
37
+ dependency: transitive
38
+ description:
39
+ name: clock
40
+ sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e
41
+ url: "https://pub.dev"
42
+ source: hosted
43
+ version: "1.1.3"
44
+ code_assets:
45
+ dependency: transitive
46
+ description:
47
+ name: code_assets
48
+ sha256: "828110d598123b5ea96c00c9f3c72105bf79f8ee36c20a39b26209ade421ec57"
49
+ url: "https://pub.dev"
50
+ source: hosted
51
+ version: "2.1.0"
52
+ collection:
53
+ dependency: transitive
54
+ description:
55
+ name: collection
56
+ sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
57
+ url: "https://pub.dev"
58
+ source: hosted
59
+ version: "1.19.1"
60
+ crypto:
61
+ dependency: transitive
62
+ description:
63
+ name: crypto
64
+ sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
65
+ url: "https://pub.dev"
66
+ source: hosted
67
+ version: "3.0.7"
68
+ cupertino_icons:
69
+ dependency: "direct main"
70
+ description:
71
+ name: cupertino_icons
72
+ sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
73
+ url: "https://pub.dev"
74
+ source: hosted
75
+ version: "1.0.9"
76
+ fake_async:
77
+ dependency: transitive
78
+ description:
79
+ name: fake_async
80
+ sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
81
+ url: "https://pub.dev"
82
+ source: hosted
83
+ version: "1.3.3"
84
+ ffi:
85
+ dependency: transitive
86
+ description:
87
+ name: ffi
88
+ sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
89
+ url: "https://pub.dev"
90
+ source: hosted
91
+ version: "2.2.0"
92
+ ffi_leak_tracker:
93
+ dependency: transitive
94
+ description:
95
+ name: ffi_leak_tracker
96
+ sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
97
+ url: "https://pub.dev"
98
+ source: hosted
99
+ version: "0.1.2"
100
+ file:
101
+ dependency: transitive
102
+ description:
103
+ name: file
104
+ sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
105
+ url: "https://pub.dev"
106
+ source: hosted
107
+ version: "7.0.1"
108
+ flutter:
109
+ dependency: "direct main"
110
+ description: flutter
111
+ source: sdk
112
+ version: "0.0.0"
113
+ flutter_lints:
114
+ dependency: "direct dev"
115
+ description:
116
+ name: flutter_lints
117
+ sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"
118
+ url: "https://pub.dev"
119
+ source: hosted
120
+ version: "6.0.0"
121
+ flutter_localizations:
122
+ dependency: "direct main"
123
+ description: flutter
124
+ source: sdk
125
+ version: "0.0.0"
126
+ flutter_secure_storage:
127
+ dependency: "direct main"
128
+ description:
129
+ name: flutter_secure_storage
130
+ sha256: fe638107c5f69119156ada2db5a57734385fac3f64430bd7252a00d3ead2ca4b
131
+ url: "https://pub.dev"
132
+ source: hosted
133
+ version: "10.3.4"
134
+ flutter_secure_storage_darwin:
135
+ dependency: transitive
136
+ description:
137
+ name: flutter_secure_storage_darwin
138
+ sha256: "82329fa5cdf343773b1b6897dea959105a29f092454259edff92f9f6637e8149"
139
+ url: "https://pub.dev"
140
+ source: hosted
141
+ version: "0.3.2"
142
+ flutter_secure_storage_linux:
143
+ dependency: transitive
144
+ description:
145
+ name: flutter_secure_storage_linux
146
+ sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea
147
+ url: "https://pub.dev"
148
+ source: hosted
149
+ version: "3.0.3"
150
+ flutter_secure_storage_platform_interface:
151
+ dependency: transitive
152
+ description:
153
+ name: flutter_secure_storage_platform_interface
154
+ sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045"
155
+ url: "https://pub.dev"
156
+ source: hosted
157
+ version: "2.1.1"
158
+ flutter_secure_storage_web:
159
+ dependency: transitive
160
+ description:
161
+ name: flutter_secure_storage_web
162
+ sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c"
163
+ url: "https://pub.dev"
164
+ source: hosted
165
+ version: "2.1.1"
166
+ flutter_secure_storage_windows:
167
+ dependency: transitive
168
+ description:
169
+ name: flutter_secure_storage_windows
170
+ sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1"
171
+ url: "https://pub.dev"
172
+ source: hosted
173
+ version: "4.2.2"
174
+ flutter_test:
175
+ dependency: "direct dev"
176
+ description: flutter
177
+ source: sdk
178
+ version: "0.0.0"
179
+ flutter_web_plugins:
180
+ dependency: transitive
181
+ description: flutter
182
+ source: sdk
183
+ version: "0.0.0"
184
+ hooks:
185
+ dependency: transitive
186
+ description:
187
+ name: hooks
188
+ sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f
189
+ url: "https://pub.dev"
190
+ source: hosted
191
+ version: "2.2.0"
192
+ http:
193
+ dependency: "direct main"
194
+ description:
195
+ name: http
196
+ sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
197
+ url: "https://pub.dev"
198
+ source: hosted
199
+ version: "1.6.0"
200
+ http_parser:
201
+ dependency: transitive
202
+ description:
203
+ name: http_parser
204
+ sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
205
+ url: "https://pub.dev"
206
+ source: hosted
207
+ version: "4.1.2"
208
+ intl:
209
+ dependency: "direct main"
210
+ description:
211
+ name: intl
212
+ sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
213
+ url: "https://pub.dev"
214
+ source: hosted
215
+ version: "0.20.3"
216
+ jni:
217
+ dependency: transitive
218
+ description:
219
+ name: jni
220
+ sha256: "6b9ca0602fef0230e83149afbe3f9f8227e94f2bbe84a1da4f14d699742f402d"
221
+ url: "https://pub.dev"
222
+ source: hosted
223
+ version: "1.1.0"
224
+ jni_flutter:
225
+ dependency: transitive
226
+ description:
227
+ name: jni_flutter
228
+ sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191"
229
+ url: "https://pub.dev"
230
+ source: hosted
231
+ version: "1.0.4+1"
232
+ jni_util:
233
+ dependency: transitive
234
+ description:
235
+ name: jni_util
236
+ sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f"
237
+ url: "https://pub.dev"
238
+ source: hosted
239
+ version: "1.0.0"
240
+ leak_tracker:
241
+ dependency: transitive
242
+ description:
243
+ name: leak_tracker
244
+ sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
245
+ url: "https://pub.dev"
246
+ source: hosted
247
+ version: "11.0.2"
248
+ leak_tracker_flutter_testing:
249
+ dependency: transitive
250
+ description:
251
+ name: leak_tracker_flutter_testing
252
+ sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
253
+ url: "https://pub.dev"
254
+ source: hosted
255
+ version: "3.0.10"
256
+ leak_tracker_testing:
257
+ dependency: transitive
258
+ description:
259
+ name: leak_tracker_testing
260
+ sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
261
+ url: "https://pub.dev"
262
+ source: hosted
263
+ version: "3.0.2"
264
+ lints:
265
+ dependency: transitive
266
+ description:
267
+ name: lints
268
+ sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df"
269
+ url: "https://pub.dev"
270
+ source: hosted
271
+ version: "6.1.0"
272
+ logging:
273
+ dependency: transitive
274
+ description:
275
+ name: logging
276
+ sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
277
+ url: "https://pub.dev"
278
+ source: hosted
279
+ version: "1.3.0"
280
+ matcher:
281
+ dependency: transitive
282
+ description:
283
+ name: matcher
284
+ sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
285
+ url: "https://pub.dev"
286
+ source: hosted
287
+ version: "0.12.20"
288
+ material_color_utilities:
289
+ dependency: transitive
290
+ description:
291
+ name: material_color_utilities
292
+ sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
293
+ url: "https://pub.dev"
294
+ source: hosted
295
+ version: "0.13.0"
296
+ meta:
297
+ dependency: transitive
298
+ description:
299
+ name: meta
300
+ sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
301
+ url: "https://pub.dev"
302
+ source: hosted
303
+ version: "1.19.0"
304
+ objective_c:
305
+ dependency: transitive
306
+ description:
307
+ name: objective_c
308
+ sha256: "5c80c2ad6e2c0397de5db38c6d653e69616a3397e13aa7633bf39eb668f2041b"
309
+ url: "https://pub.dev"
310
+ source: hosted
311
+ version: "9.6.2"
312
+ package_config:
313
+ dependency: transitive
314
+ description:
315
+ name: package_config
316
+ sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
317
+ url: "https://pub.dev"
318
+ source: hosted
319
+ version: "3.0.0"
320
+ path:
321
+ dependency: transitive
322
+ description:
323
+ name: path
324
+ sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
325
+ url: "https://pub.dev"
326
+ source: hosted
327
+ version: "1.9.1"
328
+ path_provider:
329
+ dependency: transitive
330
+ description:
331
+ name: path_provider
332
+ sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
333
+ url: "https://pub.dev"
334
+ source: hosted
335
+ version: "2.1.6"
336
+ path_provider_android:
337
+ dependency: transitive
338
+ description:
339
+ name: path_provider_android
340
+ sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"
341
+ url: "https://pub.dev"
342
+ source: hosted
343
+ version: "2.3.1"
344
+ path_provider_foundation:
345
+ dependency: transitive
346
+ description:
347
+ name: path_provider_foundation
348
+ sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
349
+ url: "https://pub.dev"
350
+ source: hosted
351
+ version: "2.6.0"
352
+ path_provider_linux:
353
+ dependency: transitive
354
+ description:
355
+ name: path_provider_linux
356
+ sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
357
+ url: "https://pub.dev"
358
+ source: hosted
359
+ version: "2.2.2"
360
+ path_provider_platform_interface:
361
+ dependency: transitive
362
+ description:
363
+ name: path_provider_platform_interface
364
+ sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
365
+ url: "https://pub.dev"
366
+ source: hosted
367
+ version: "2.1.3"
368
+ path_provider_windows:
369
+ dependency: transitive
370
+ description:
371
+ name: path_provider_windows
372
+ sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
373
+ url: "https://pub.dev"
374
+ source: hosted
375
+ version: "2.3.0"
376
+ platform:
377
+ dependency: transitive
378
+ description:
379
+ name: platform
380
+ sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec
381
+ url: "https://pub.dev"
382
+ source: hosted
383
+ version: "3.2.0"
384
+ plugin_platform_interface:
385
+ dependency: transitive
386
+ description:
387
+ name: plugin_platform_interface
388
+ sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
389
+ url: "https://pub.dev"
390
+ source: hosted
391
+ version: "2.1.8"
392
+ pub_semver:
393
+ dependency: transitive
394
+ description:
395
+ name: pub_semver
396
+ sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
397
+ url: "https://pub.dev"
398
+ source: hosted
399
+ version: "2.2.1"
400
+ record_use:
401
+ dependency: transitive
402
+ description:
403
+ name: record_use
404
+ sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2"
405
+ url: "https://pub.dev"
406
+ source: hosted
407
+ version: "1.1.1"
408
+ shared_preferences:
409
+ dependency: "direct main"
410
+ description:
411
+ name: shared_preferences
412
+ sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
413
+ url: "https://pub.dev"
414
+ source: hosted
415
+ version: "2.5.6"
416
+ shared_preferences_android:
417
+ dependency: transitive
418
+ description:
419
+ name: shared_preferences_android
420
+ sha256: "1e12aafe408aa50da80edfd679a2a6bf63ba7ab37c7fa98286da459a757b3399"
421
+ url: "https://pub.dev"
422
+ source: hosted
423
+ version: "2.4.28"
424
+ shared_preferences_foundation:
425
+ dependency: transitive
426
+ description:
427
+ name: shared_preferences_foundation
428
+ sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea"
429
+ url: "https://pub.dev"
430
+ source: hosted
431
+ version: "2.5.7"
432
+ shared_preferences_linux:
433
+ dependency: transitive
434
+ description:
435
+ name: shared_preferences_linux
436
+ sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
437
+ url: "https://pub.dev"
438
+ source: hosted
439
+ version: "2.4.1"
440
+ shared_preferences_platform_interface:
441
+ dependency: "direct dev"
442
+ description:
443
+ name: shared_preferences_platform_interface
444
+ sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9"
445
+ url: "https://pub.dev"
446
+ source: hosted
447
+ version: "2.4.2"
448
+ shared_preferences_web:
449
+ dependency: transitive
450
+ description:
451
+ name: shared_preferences_web
452
+ sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
453
+ url: "https://pub.dev"
454
+ source: hosted
455
+ version: "2.4.3"
456
+ shared_preferences_windows:
457
+ dependency: transitive
458
+ description:
459
+ name: shared_preferences_windows
460
+ sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
461
+ url: "https://pub.dev"
462
+ source: hosted
463
+ version: "2.4.1"
464
+ sky_engine:
465
+ dependency: transitive
466
+ description: flutter
467
+ source: sdk
468
+ version: "0.0.0"
469
+ source_span:
470
+ dependency: transitive
471
+ description:
472
+ name: source_span
473
+ sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
474
+ url: "https://pub.dev"
475
+ source: hosted
476
+ version: "1.10.2"
477
+ stack_trace:
478
+ dependency: transitive
479
+ description:
480
+ name: stack_trace
481
+ sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490"
482
+ url: "https://pub.dev"
483
+ source: hosted
484
+ version: "1.12.2"
485
+ stream_channel:
486
+ dependency: transitive
487
+ description:
488
+ name: stream_channel
489
+ sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
490
+ url: "https://pub.dev"
491
+ source: hosted
492
+ version: "2.1.4"
493
+ string_scanner:
494
+ dependency: transitive
495
+ description:
496
+ name: string_scanner
497
+ sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
498
+ url: "https://pub.dev"
499
+ source: hosted
500
+ version: "1.4.1"
501
+ term_glyph:
502
+ dependency: transitive
503
+ description:
504
+ name: term_glyph
505
+ sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
506
+ url: "https://pub.dev"
507
+ source: hosted
508
+ version: "1.2.2"
509
+ test_api:
510
+ dependency: transitive
511
+ description:
512
+ name: test_api
513
+ sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
514
+ url: "https://pub.dev"
515
+ source: hosted
516
+ version: "0.7.12"
517
+ typed_data:
518
+ dependency: transitive
519
+ description:
520
+ name: typed_data
521
+ sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
522
+ url: "https://pub.dev"
523
+ source: hosted
524
+ version: "1.4.0"
525
+ vector_math:
526
+ dependency: transitive
527
+ description:
528
+ name: vector_math
529
+ sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d"
530
+ url: "https://pub.dev"
531
+ source: hosted
532
+ version: "2.4.3"
533
+ vm_service:
534
+ dependency: transitive
535
+ description:
536
+ name: vm_service
537
+ sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0"
538
+ url: "https://pub.dev"
539
+ source: hosted
540
+ version: "15.3.0"
541
+ web:
542
+ dependency: transitive
543
+ description:
544
+ name: web
545
+ sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
546
+ url: "https://pub.dev"
547
+ source: hosted
548
+ version: "1.1.1"
549
+ win32:
550
+ dependency: transitive
551
+ description:
552
+ name: win32
553
+ sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d
554
+ url: "https://pub.dev"
555
+ source: hosted
556
+ version: "6.4.0"
557
+ xdg_directories:
558
+ dependency: transitive
559
+ description:
560
+ name: xdg_directories
561
+ sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
562
+ url: "https://pub.dev"
563
+ source: hosted
564
+ version: "1.1.0"
565
+ yaml:
566
+ dependency: transitive
567
+ description:
568
+ name: yaml
569
+ sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
570
+ url: "https://pub.dev"
571
+ source: hosted
572
+ version: "3.1.4"
573
+sdks:
574
+ dart: ">=3.12.0 <4.0.0"
575
+ flutter: ">=3.44.0"
apps/lifemate/pubspec.yaml
+23
-2
@@ -1,7 +1,7 @@
1
name: lifemate
2
-version: 0.1.0+1
2
+version: 0.5.0+3
3
publish_to: none
4
-description: LifeMate personal, family and learning companion.
4
+description: LifeGuide personal, family and learning companion.
5
environment:
6
sdk: '>=3.4.0 <4.0.0'
7
dependencies:
@@ -9,12 +9,33 @@ dependencies:
9
sdk: flutter
10
flutter_localizations:
11
sdk: flutter
12
+ cupertino_icons: ^1.0.8
13
intl: ^0.20.2
14
http: ^1.5.0
15
shared_preferences: ^2.5.3
16
+ flutter_secure_storage: ^10.0.0
17
dev_dependencies:
18
+ shared_preferences_platform_interface: ^2.4.2
19
flutter_test:
20
sdk: flutter
21
flutter_lints: ^6.0.0
22
flutter:
23
uses-material-design: true
24
+ assets:
25
+ - assets/fonts/OFL-Noto-Arabic.txt
26
+ - assets/fonts/LICENSE-Noto-Emoji.txt
27
+ - assets/fonts/LICENSE-Roboto.txt
28
+ fonts:
29
+ - family: LifeGuidePersian
30
+ fonts:
31
+ - asset: assets/fonts/LifeGuidePersian.ttf
32
+ - family: LifeGuideLatin
33
+ fonts:
34
+ - asset: assets/fonts/LifeGuideLatin.ttf
35
+ # CanvasKit needs a named Roboto fallback even with an application font.
36
+ - family: Roboto
37
+ fonts:
38
+ - asset: assets/fonts/LifeGuideLatin.ttf
39
+ - family: LifeGuideEmoji
40
+ fonts:
41
+ - asset: assets/fonts/LifeGuideEmoji.ttf
apps/lifemate/test/app_test.dart
+199
-45
@@ -1,4 +1,6 @@
1
-import 'package:flutter/material.dart';
1
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
2
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
3
+import 'package:flutter/services.dart';
4
import 'package:flutter_test/flutter_test.dart';
5
import 'package:lifemate/api.dart';
6
import 'package:lifemate/main.dart';
@@ -8,60 +10,212 @@ class FakeApi implements IdentityApi {
10
FakeApi({this.role = 'teen_minor', this.themePreference = 'girl_pink'});
11
final String role;
12
final String themePreference;
11
- @override String? accessToken;
12
- @override Future<void> login(String email, String password) async { accessToken = 'test-token'; }
13
- @override Future<void> register({required String displayName, required String email, required String password}) async {}
14
- @override Future<void> verifyEmail(String token) async {}
15
- @override Future<void> forgotPassword(String email) async {}
16
- @override Future<void> resetPassword(String token, String newPassword) async {}
17
- @override Future<void> changePassword(String currentPassword, String newPassword) async {}
18
- @override Future<Map<String,dynamic>> getProfile() async => {'display_name': role == 'teen_minor' ? 'آرام' : 'والد','email_normalized':'user@example.test','user_id':role == 'teen_minor' ? 'teen-1':'parent-1','theme_preference':themePreference};
19
- @override Future<Map<String,dynamic>> updateProfile({String? displayName,String? birthDate,String? themePreference}) async => {'display_name':displayName ?? 'والد','theme_preference':themePreference ?? 'adult_blue'};
20
- @override Future<List<Map<String,dynamic>>> listFamilies() async => [{'id':'family-1','name':'خانواده','role':role,'is_admin':role == 'parent_guardian'}];
21
- @override Future<List<Map<String,dynamic>>> listFamilyMembers(String familyId) async => [];
22
- @override Future<Map<String,dynamic>> createFamily(String name,{String? role}) async => {'id':'family-1','name':name};
23
- @override Future<void> inviteMember({required String familyId,required String email,required String role,String? themePreference}) async {}
24
- @override Future<void> acceptInvitation(String token) async {}
25
- @override Future<void> setGuardian({required String familyId,required String guardianUserId,required String minorUserId}) async {}
26
- @override Future<List<Map<String,dynamic>>> getToday({required DateTime from,required DateTime to}) async => [];
27
- @override Future<List<Map<String,dynamic>>> listPlanItems({DateTime? from,DateTime? to,String? kind}) async => [];
28
- @override Future<Map<String,dynamic>> createPlanItem(Map<String,dynamic> data) async => {'id':'new-plan',...data};
29
- @override Future<Map<String,dynamic>> updatePlanItem(String itemId,Map<String,dynamic> data) async => {'id':itemId,...data};
30
- @override Future<List<Map<String,dynamic>>> listLifeContexts() async => [];
31
- @override Future<Map<String,dynamic>> createLifeContext({required String kind,required String title}) async => {'id':'ctx-1','kind':kind,'title':title};
32
- @override Future<Map<String,dynamic>> createAcademicYear(Map<String,dynamic> data) async => {'id':'year-1',...data};
33
- @override Future<Map<String,dynamic>> createAcademicTerm(String yearId,Map<String,dynamic> data) async => {'id':'term-1',...data};
34
- @override Future<Map<String,dynamic>> createSubject(String termId,Map<String,dynamic> data) async => {'id':'subject-1',...data};
35
- @override Future<Map<String,dynamic>> createClassSession(String subjectId,Map<String,dynamic> data) async => {'id':'class-1',...data};
36
- @override Future<Map<String,dynamic>> setGrade(String itemId,{required num points,required num outOf}) async => {'id':itemId};
37
- @override Future<List<Map<String,dynamic>>> claimDueReminders() async => [];
38
- @override Future<Map<String,dynamic>> getSchoolOverview(String studentUserId) async => {'years':[],'subjects':[],'workload':[],'grades':[]};
39
- @override Future<List<Map<String,dynamic>>> getTimetable(String studentUserId) async => [];
40
- @override Future<List<Map<String,dynamic>>> getFamilyCalendar(String familyId) async => [];
41
- @override Future<Map<String,dynamic>> getChildSupportSummary(String familyId,String studentUserId) async => {'upcoming':[],'metrics':{}};
42
- @override Future<Map<String,dynamic>> submitSyncMutations(List<Map<String,dynamic>> mutations) async => {'results':[]};
43
- @override Future<Map<String,dynamic>> createLearningGoal({required String title,String? target,String? subjectId}) async => {'id':'goal-1','title':title};
44
- @override Future<List<Map<String,dynamic>>> listLearningGoals() async => [];
45
- @override Future<Map<String,dynamic>> createLearningCheckin({String? learningGoalId,required int confidence,required int difficulty,String? note}) async => {'id':'checkin-1'};
46
- @override Future<Map<String,dynamic>> createWellbeingCheckin({required int mood,required int energy,required int stress,String? note,String visibility='private'}) async => {'id':'wellbeing-1'};
47
- @override Future<List<Map<String,dynamic>>> listWellbeingCheckins() async => [];
48
- @override Future<Map<String,dynamic>> createAiSession(String kind) async => {'id':'session-1'};
49
- @override Future<Map<String,dynamic>> sendAiMessage(String sessionId,String message) async => {'id':'message-1','body':'پاسخ آزمایشی همراه هوشمند'};
50
- @override Future<Map<String,dynamic>> getGuardianWellbeingSummary(String familyId,String minorUserId) async => {'summary':{},'safety':{},'rawNotesIncluded':false,'rawConversationIncluded':false};
51
- @override Future<Map<String,dynamic>> requestFamilyGuidance(String familyId,String minorUserId,String question) async => {'advice':'پیشنهاد آزمایشی','advisory':true,'medicalDiagnosis':false};
13
+ @override
14
+ String? accessToken;
15
+ @override
16
+ Future<void> login(String email, String password) async {
17
+ accessToken = 'test-token';
18
+ }
19
+
20
+ @override
21
+ Future<void> register(
22
+ {required String displayName,
23
+ required String email,
24
+ required String password}) async {}
25
+ @override
26
+ Future<void> verifyEmail(String token, {required String newPassword}) async {}
27
+ @override
28
+ Future<void> forgotPassword(String email) async {}
29
+ @override
30
+ Future<void> resetPassword(String token, String newPassword) async {}
31
+ @override
32
+ Future<void> changePassword(
33
+ String currentPassword, String newPassword) async {}
34
+ @override
35
+ Future<Map<String, dynamic>> getProfile() async => {
36
+ 'display_name': role == 'teen_minor' ? 'آرام' : 'والد',
37
+ 'email_normalized': 'user@example.test',
38
+ 'user_id': role == 'teen_minor' ? 'teen-1' : 'parent-1',
39
+ 'theme_preference': themePreference
40
+ };
41
+ @override
42
+ Future<Map<String, dynamic>> updateProfile(
43
+ {String? displayName,
44
+ String? birthDate,
45
+ String? themePreference,
46
+ String? profileCategory}) async =>
47
+ {
48
+ 'display_name': displayName ?? 'والد',
49
+ 'theme_preference': themePreference ?? 'adult_blue'
50
+ };
51
+ @override
52
+ Future<List<Map<String, dynamic>>> listFamilies() async => [
53
+ {
54
+ 'id': 'family-1',
55
+ 'name': 'خانواده',
56
+ 'role': role,
57
+ 'is_admin': role == 'parent_guardian'
58
+ }
59
+ ];
60
+ @override
61
+ Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId) async =>
62
+ [];
63
+ @override
64
+ Future<Map<String, dynamic>> createFamily(String name,
65
+ {String? role}) async =>
66
+ {'id': 'family-1', 'name': name};
67
+ @override
68
+ Future<void> inviteMember(
69
+ {required String familyId,
70
+ required String email,
71
+ required String role,
72
+ String? themePreference,
73
+ String? profileCategory}) async {}
74
+ @override
75
+ Future<void> acceptInvitation(String token) async {}
76
+ @override
77
+ Future<void> setGuardian(
78
+ {required String familyId,
79
+ required String guardianUserId,
80
+ required String minorUserId}) async {}
81
+ @override
82
+ Future<List<Map<String, dynamic>>> getToday(
83
+ {required DateTime from, required DateTime to}) async =>
84
+ [];
85
+ @override
86
+ Future<List<Map<String, dynamic>>> listPlanItems(
87
+ {DateTime? from, DateTime? to, String? kind}) async =>
88
+ [];
89
+ @override
90
+ Future<Map<String, dynamic>> createPlanItem(
91
+ Map<String, dynamic> data) async =>
92
+ {'id': 'new-plan', ...data};
93
+ @override
94
+ Future<Map<String, dynamic>> updatePlanItem(
95
+ String itemId, Map<String, dynamic> data) async =>
96
+ {'id': itemId, ...data};
97
+ @override
98
+ Future<List<Map<String, dynamic>>> listLifeContexts() async => [];
99
+ @override
100
+ Future<Map<String, dynamic>> createLifeContext(
101
+ {required String kind, required String title}) async =>
102
+ {'id': 'ctx-1', 'kind': kind, 'title': title};
103
+ @override
104
+ Future<Map<String, dynamic>> createAcademicYear(
105
+ Map<String, dynamic> data) async =>
106
+ {'id': 'year-1', ...data};
107
+ @override
108
+ Future<Map<String, dynamic>> createAcademicTerm(
109
+ String yearId, Map<String, dynamic> data) async =>
110
+ {'id': 'term-1', ...data};
111
+ @override
112
+ Future<Map<String, dynamic>> createSubject(
113
+ String termId, Map<String, dynamic> data) async =>
114
+ {'id': 'subject-1', ...data};
115
+ @override
116
+ Future<Map<String, dynamic>> createClassSession(
117
+ String subjectId, Map<String, dynamic> data) async =>
118
+ {'id': 'class-1', ...data};
119
+ @override
120
+ Future<Map<String, dynamic>> setGrade(String itemId,
121
+ {required num points, required num outOf}) async =>
122
+ {'id': itemId};
123
+ @override
124
+ Future<List<Map<String, dynamic>>> claimDueReminders() async => [];
125
+ @override
126
+ Future<Map<String, dynamic>> getSchoolOverview(String studentUserId) async =>
127
+ {'years': [], 'subjects': [], 'workload': [], 'grades': []};
128
+ @override
129
+ Future<List<Map<String, dynamic>>> getTimetable(String studentUserId) async =>
130
+ [];
131
+ @override
132
+ Future<List<Map<String, dynamic>>> getFamilyCalendar(String familyId) async =>
133
+ [];
134
+ @override
135
+ Future<Map<String, dynamic>> getChildSupportSummary(
136
+ String familyId, String studentUserId) async =>
137
+ {'upcoming': [], 'metrics': {}};
138
+ @override
139
+ Future<Map<String, dynamic>> submitSyncMutations(
140
+ List<Map<String, dynamic>> mutations) async =>
141
+ {'results': []};
142
+ @override
143
+ Future<Map<String, dynamic>> createLearningGoal(
144
+ {required String title, String? target, String? subjectId}) async =>
145
+ {'id': 'goal-1', 'title': title};
146
+ @override
147
+ Future<List<Map<String, dynamic>>> listLearningGoals() async => [];
148
+ @override
149
+ Future<Map<String, dynamic>> createLearningCheckin(
150
+ {String? learningGoalId,
151
+ required int confidence,
152
+ required int difficulty,
153
+ String? note}) async =>
154
+ {'id': 'checkin-1'};
155
+ @override
156
+ Future<Map<String, dynamic>> createWellbeingCheckin(
157
+ {required int mood,
158
+ required int energy,
159
+ required int stress,
160
+ String? note,
161
+ String visibility = 'private'}) async =>
162
+ {'id': 'wellbeing-1'};
163
+ @override
164
+ Future<List<Map<String, dynamic>>> listWellbeingCheckins() async => [];
165
+ @override
166
+ Future<Map<String, dynamic>> createAiSession(String kind) async =>
167
+ {'id': 'session-1'};
168
+ @override
169
+ Future<Map<String, dynamic>> sendAiMessage(
170
+ String sessionId, String message) async =>
171
+ {'id': 'message-1', 'body': 'پاسخ آزمایشی همراه هوشمند'};
172
+ @override
173
+ Future<Map<String, dynamic>> getGuardianWellbeingSummary(
174
+ String familyId, String minorUserId) async =>
175
+ {
176
+ 'summary': {},
177
+ 'safety': {},
178
+ 'rawNotesIncluded': false,
179
+ 'rawConversationIncluded': false
180
+ };
181
+ @override
182
+ Future<Map<String, dynamic>> requestFamilyGuidance(
183
+ String familyId, String minorUserId, String question) async =>
184
+ {
185
+ 'advice': 'پیشنهاد آزمایشی',
186
+ 'advisory': true,
187
+ 'medicalDiagnosis': false
188
+ };
189
}
190
191
void main() {
55
- setUp(() { SharedPreferences.setMockInitialValues({}); });
192
+ setUp(() {
193
+ SharedPreferences.setMockInitialValues({});
194
+ SharedPreferencesAsyncPlatform.instance =
195
+ InMemorySharedPreferencesAsync.withData({});
196
+ String? pending;
197
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
198
+ .setMockMethodCallHandler(
199
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
200
+ if (call.method == 'getBlocked') return pending != null;
201
+ if (call.method == 'beginWrite') return pending = 'owned-ui-test-token';
202
+ if (call.method == 'completeWrite' && call.arguments == pending) {
203
+ pending = null;
204
+ return true;
205
+ }
206
+ throw PlatformException(code: 'local_storage_restart_required');
207
+ });
208
+ });
209
210
testWidgets('starts in Persian RTL with identity actions', (tester) async {
211
await tester.pumpWidget(LifeMateApp(api: FakeApi()));
59
- expect(find.text('LifeMate'), findsOneWidget);
212
+ expect(find.text('LifeGuide'), findsOneWidget);
213
expect(find.text('ورود'), findsOneWidget);
214
expect(find.text('رمز عبور را فراموش کردهام'), findsOneWidget);
215
});
216
64
- testWidgets('registration explains 10-character password requirement', (tester) async {
217
+ testWidgets('registration explains 10-character password requirement',
218
+ (tester) async {
219
await tester.pumpWidget(LifeMateApp(api: FakeApi()));
220
await tester.tap(find.text('ساخت حساب جدید'));
221
await tester.pumpAndSettle();
apps/lifemate/test/endpoint_settings_test.dart
new
+43
@@ -0,0 +1,43 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:flutter_test/flutter_test.dart';
3
+import 'package:lifemate/endpoint_settings.dart';
4
+import 'package:lifemate/runtime_config.dart';
5
+
6
+void main() {
7
+ testWidgets('fallback selection requires save and preserves the old primary',
8
+ (tester) async {
9
+ RuntimeConfig? saved;
10
+ await tester.pumpWidget(MaterialApp(
11
+ home: EndpointSettingsPage(
12
+ initialConfig: RuntimeConfig(
13
+ apiBaseUrl: 'https://primary.example.test/api',
14
+ apiFallbackUrls: ['https://backup.example.test/api']),
15
+ onSaved: (config) async => saved = config)));
16
+ await tester.ensureVisible(find.byType(OutlinedButton));
17
+ await tester.tap(find.byType(OutlinedButton));
18
+ await tester.pump();
19
+ expect(saved, isNull);
20
+ expect(
21
+ tester.widget<TextField>(find.byType(TextField).first).controller!.text,
22
+ 'https://backup.example.test/api');
23
+ await tester.ensureVisible(find.text('ذخیره و ادامه'));
24
+ await tester.tap(find.text('ذخیره و ادامه'));
25
+ await tester.pumpAndSettle();
26
+ expect(saved!.apiBaseUrl, 'https://backup.example.test/api');
27
+ expect(saved!.apiFallbackUrls, ['https://primary.example.test/api']);
28
+ });
29
+ testWidgets('invalid HTTPS address never reaches the saved callback',
30
+ (tester) async {
31
+ var saved = false;
32
+ await tester.pumpWidget(MaterialApp(
33
+ home: EndpointSettingsPage(
34
+ initialConfig: RuntimeConfig(),
35
+ onSaved: (_) async => saved = true)));
36
+ await tester.enterText(
37
+ find.byType(TextField).first, 'https://user:password@api.example.test');
38
+ await tester.tap(find.text('ذخیره و ادامه'));
39
+ await tester.pumpAndSettle();
40
+ expect(saved, isFalse);
41
+ expect(find.textContaining('نشانی HTTPS معتبر'), findsOneWidget);
42
+ });
43
+}
apps/lifemate/test/notification_delivery_test.dart
new
+64
@@ -0,0 +1,64 @@
1
+import 'dart:convert';
2
+import 'package:flutter_test/flutter_test.dart';
3
+import 'package:http/http.dart' as http;
4
+import 'package:http/testing.dart';
5
+import 'package:lifemate/api.dart';
6
+import 'package:lifemate/notification_delivery.dart';
7
+import 'package:lifemate/session_store.dart';
8
+
9
+class _MemorySession implements SessionStore {
10
+ String? value;
11
+ @override
12
+ Future<String?> read() async => value;
13
+ @override
14
+ Future<void> write(String next) async {
15
+ value = next;
16
+ }
17
+
18
+ @override
19
+ Future<void> clear() async {
20
+ value = null;
21
+ }
22
+}
23
+
24
+void main() {
25
+ test('polling uses the configured authenticated API, with no push SDK',
26
+ () async {
27
+ final requests = <http.Request>[];
28
+ final token = 'header.${base64Url.encode(utf8.encode(jsonEncode({
29
+ 'sub': 'synthetic-child'
30
+ })))}.signature';
31
+ final client = MockClient((request) async {
32
+ requests.add(request);
33
+ if (request.url.path.endsWith('/login')) {
34
+ return http.Response(
35
+ jsonEncode({'accessToken': token, 'refreshToken': 'synthetic'}),
36
+ 200,
37
+ headers: {'content-type': 'application/json; charset=utf-8'});
38
+ }
39
+ return http.Response(
40
+ jsonEncode({
41
+ 'notifications': [
42
+ {
43
+ 'id': 'notification',
44
+ 'payload': {'title': 'ریاضی'}
45
+ }
46
+ ]
47
+ }),
48
+ 200,
49
+ headers: {'content-type': 'application/json; charset=utf-8'});
50
+ });
51
+ final api = HttpIdentityApi(
52
+ baseUrl: 'https://lan.test/api',
53
+ client: client,
54
+ sessionStore: _MemorySession());
55
+ await api.login('synthetic@example.test', 'SyntheticPass!123');
56
+ final port = PollingInAppNotificationDelivery(api);
57
+ expect(port.supportsBackgroundPush, isFalse);
58
+ expect((await port.fetch()).single['id'], 'notification');
59
+ expect(requests.last.url.toString(),
60
+ 'https://lan.test/api/v1/notification-outbox');
61
+ expect(requests.last.headers['authorization'], 'Bearer $token');
62
+ api.close();
63
+ });
64
+}
apps/lifemate/test/online_sync_test.dart
new
+222
@@ -0,0 +1,222 @@
1
+import 'package:flutter_test/flutter_test.dart';
2
+import 'package:flutter/services.dart';
3
+import 'package:lifemate/api.dart';
4
+import 'package:lifemate/offline_store.dart';
5
+import 'package:lifemate/plan_sync.dart';
6
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
7
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
8
+
9
+class _SyncApi implements IdentityApi {
10
+ bool offline = true;
11
+ bool conflict = false;
12
+ String? malformedAck;
13
+ final sent = <Map<String, dynamic>>[];
14
+ final items = <String, Map<String, dynamic>>{};
15
+ final applied = <String>{};
16
+ @override
17
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
18
+ @override
19
+ Future<Map<String, dynamic>> submitSyncMutations(
20
+ List<Map<String, dynamic>> mutations) async {
21
+ if (offline) throw const ApiException(0, 'network_unavailable');
22
+ return {
23
+ 'results': mutations.map((m) {
24
+ sent.add(Map<String, dynamic>.from(m));
25
+ if (conflict) {
26
+ return {
27
+ 'id': m['id'],
28
+ 'status': 'conflict',
29
+ 'error': 'version_conflict'
30
+ };
31
+ }
32
+ if (m['operation'] != 'create' && !items.containsKey(m['entityId'])) {
33
+ return {'id': m['id'], 'status': 'rejected', 'error': 'not_found'};
34
+ }
35
+ final item = items.putIfAbsent(
36
+ m['entityId'] as String,
37
+ () => {
38
+ 'id': m['entityId'],
39
+ 'title': (m['payload'] as Map)['title'],
40
+ 'kind': 'assignment',
41
+ 'status': 'planned',
42
+ 'visibility': 'private',
43
+ 'version': 1,
44
+ });
45
+ if (applied.add(m['id'] as String) && m['operation'] != 'create') {
46
+ if (item['version'] != m['expectedVersion']) {
47
+ return {
48
+ 'id': m['id'],
49
+ 'status': 'conflict',
50
+ 'error': 'version_conflict'
51
+ };
52
+ }
53
+ item.addAll(Map<String, dynamic>.from(m['payload'] as Map));
54
+ item['version'] = (item['version'] as int) + 1;
55
+ }
56
+ return {
57
+ 'id': m['id'],
58
+ 'status': 'accepted',
59
+ if (malformedAck != 'missing')
60
+ 'item': {
61
+ ...item,
62
+ if (malformedAck == 'wrong') 'id': 'wrong-entity'
63
+ },
64
+ 'acceptedAt': '2026-10-08T10:00:00Z'
65
+ };
66
+ }).toList()
67
+ };
68
+ }
69
+}
70
+
71
+void main() {
72
+ TestWidgetsFlutterBinding.ensureInitialized();
73
+ setUp(() {
74
+ SharedPreferencesAsyncPlatform.instance =
75
+ InMemorySharedPreferencesAsync.withData({});
76
+ String? pending;
77
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
78
+ .setMockMethodCallHandler(
79
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
80
+ if (call.method == 'getBlocked') return pending != null;
81
+ if (call.method == 'beginWrite') return pending = 'owned-test-token';
82
+ if (call.method == 'completeWrite' && call.arguments == pending) {
83
+ pending = null;
84
+ return true;
85
+ }
86
+ throw PlatformException(code: 'local_storage_restart_required');
87
+ });
88
+ });
89
+
90
+ test(
91
+ 'offline create survives reopening then acknowledges once with stable IDs',
92
+ () async {
93
+ final api = _SyncApi();
94
+ final store = OfflineStore.forNamespace('test|child');
95
+ final result = await PlanSync(api, store: store)
96
+ .create({'kind': 'assignment', 'title': 'ریاضی'});
97
+ expect(result.queued, isTrue);
98
+ final reopened = OfflineStore.forNamespace('test|child');
99
+ final queue = await reopened.readQueue();
100
+ expect(queue, hasLength(1));
101
+ expect(queue.single['id'], matches(RegExp(r'^[a-f0-9-]{36}$')));
102
+ expect(queue.single['entityId'], result.item!['id']);
103
+ api.offline = false;
104
+ await PlanSync(api, store: reopened).flush();
105
+ await PlanSync(api, store: reopened).flush();
106
+ expect(api.sent, hasLength(1));
107
+ expect(api.sent.single['id'], queue.single['id']);
108
+ expect(await reopened.pendingCount(), 0);
109
+ expect(await reopened.readLastAck(), isNotNull);
110
+ });
111
+
112
+ test('separate account/server scopes never share cache or pending changes',
113
+ () async {
114
+ final first = OfflineStore.forNamespace('https://one.test/api|child');
115
+ final parent = OfflineStore.forNamespace('https://one.test/api|parent');
116
+ final other = OfflineStore.forNamespace('https://two.test/api|child');
117
+ await first.cachePlanner([
118
+ {'id': 'private', 'notes': 'synthetic private note'}
119
+ ]);
120
+ expect(await parent.readPlanner(), isEmpty);
121
+ expect(await other.readPlanner(), isEmpty);
122
+ await first.clear();
123
+ expect(await OfflineStore.forNamespace(first.scope).readPlanner(), isEmpty);
124
+ await expectLater(
125
+ first.cachePlanner([
126
+ {'id': 'stale'}
127
+ ]),
128
+ throwsA(isA<ApiException>()));
129
+ });
130
+
131
+ test('offline create then complete survives restart and both acknowledge',
132
+ () async {
133
+ final api = _SyncApi();
134
+ final store = OfflineStore.forNamespace('chain|child');
135
+ final created = await PlanSync(api, store: store)
136
+ .create({'kind': 'assignment', 'title': 'ریاضی'});
137
+ await PlanSync(api, store: store).complete(created.item!);
138
+ api.offline = false;
139
+ final reopened = OfflineStore.forNamespace(store.scope);
140
+ await PlanSync(api, store: reopened).flush();
141
+ expect(await reopened.pendingCount(), 0);
142
+ expect(api.items.values.single['status'], 'completed');
143
+ expect(api.items.values.single['version'], 2);
144
+ });
145
+
146
+ test('reconnection drains the pending create before a new completion',
147
+ () async {
148
+ final api = _SyncApi();
149
+ final store = OfflineStore.forNamespace('reconnect|child');
150
+ final created =
151
+ await PlanSync(api, store: store).create({'title': 'ریاضی'});
152
+ api.offline = false;
153
+ await PlanSync(api, store: store).complete(created.item!);
154
+ expect(api.sent.map((m) => m['operation']), ['create', 'complete']);
155
+ expect(await store.pendingCount(), 0);
156
+ });
157
+
158
+ test('malformed acknowledgement never removes the pending change', () async {
159
+ for (final malformed in ['missing', 'wrong']) {
160
+ final api = _SyncApi()
161
+ ..offline = false
162
+ ..malformedAck = malformed;
163
+ final store = OfflineStore.forNamespace('ack-$malformed|child');
164
+ await expectLater(
165
+ PlanSync(api, store: store).create({'title': 'ریاضی'}),
166
+ throwsA(isA<ApiException>()
167
+ .having((e) => e.code, 'code', 'invalid_sync_acknowledgement')));
168
+ expect(await store.pendingCount(), 1);
169
+ }
170
+ });
171
+
172
+ test('fresh server cache does not erase an unsent optimistic update',
173
+ () async {
174
+ final api = _SyncApi();
175
+ final store = OfflineStore.forNamespace('overlay|child');
176
+ await store.cachePlanner([
177
+ {
178
+ 'id': '00000000-0000-4000-8000-000000000111',
179
+ 'title': 'old',
180
+ 'version': 1
181
+ }
182
+ ]);
183
+ await PlanSync(api, store: store)
184
+ .update((await store.readPlanner()).single, {'title': 'offline edit'});
185
+ await store.cachePlanner([
186
+ {
187
+ 'id': '00000000-0000-4000-8000-000000000111',
188
+ 'title': 'old',
189
+ 'version': 1
190
+ }
191
+ ]);
192
+ expect((await store.readPlanner()).single['title'], 'offline edit');
193
+ expect((await store.readPlanner()).single['pending_sync'], isTrue);
194
+ });
195
+
196
+ test('conflicts retain the change and never become an offline success',
197
+ () async {
198
+ final api = _SyncApi();
199
+ final store = OfflineStore.forNamespace('test|child');
200
+ await PlanSync(api, store: store)
201
+ .create({'kind': 'assignment', 'title': 'ریاضی'});
202
+ api.offline = false;
203
+ api.conflict = true;
204
+ await expectLater(
205
+ PlanSync(api, store: store).flush(),
206
+ throwsA(isA<ApiException>()
207
+ .having((e) => e.code, 'code', 'sync_conflict')));
208
+ expect(await store.pendingCount(), 1);
209
+ expect((await store.readQueue()).single['queueStatus'], 'conflict');
210
+ });
211
+
212
+ test('HTTP permission, validation, server and storage errors are not offline',
213
+ () {
214
+ for (final status in [401, 403, 409, 422, 500, 503]) {
215
+ expect(isOfflineFailure(ApiException(status, 'failure')), isFalse);
216
+ }
217
+ expect(
218
+ isOfflineFailure(const ApiException(0, 'network_unavailable')), isTrue);
219
+ expect(isOfflineFailure(const ApiException(0, 'local_storage_failed')),
220
+ isFalse);
221
+ });
222
+}
apps/lifemate/test/online_ui_test.dart
new
+629
@@ -0,0 +1,629 @@
1
+import 'dart:convert';
2
+import 'package:http/http.dart' as http;
3
+import 'package:http/testing.dart';
4
+import 'package:lifemate/runtime_config.dart';
5
+import 'package:lifemate/runtime_controller.dart';
6
+import 'package:lifemate/session_store.dart';
7
+import 'package:lifemate/offline_store.dart';
8
+import 'package:lifemate/plan_sync.dart';
9
+import 'package:flutter/services.dart';
10
+import 'package:flutter/material.dart';
11
+import 'package:flutter_test/flutter_test.dart';
12
+import 'package:lifemate/api.dart';
13
+import 'package:lifemate/main.dart';
14
+import 'package:lifemate/phase3_ui.dart';
15
+import 'package:lifemate/phase4_ui.dart';
16
+import 'package:lifemate/sync_changes_ui.dart';
17
+import 'package:shared_preferences/shared_preferences.dart';
18
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
19
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
20
+
21
+import 'app_test.dart' show FakeApi;
22
+
23
+class _FailingProfileApi extends FakeApi {
24
+ @override
25
+ Future<Map<String, dynamic>> updateProfile(
26
+ {String? displayName,
27
+ String? birthDate,
28
+ String? themePreference,
29
+ String? profileCategory}) async =>
30
+ throw const ApiException(500, 'server_failed');
31
+}
32
+
33
+class _MemorySession extends SessionStore {
34
+ String? value;
35
+ @override
36
+ Future<String?> read() async => value;
37
+ @override
38
+ Future<void> write(String next) async {
39
+ value = next;
40
+ }
41
+
42
+ @override
43
+ Future<void> clear() async {
44
+ value = null;
45
+ }
46
+}
47
+
48
+class _ServerFailureApi extends FakeApi {
49
+ @override
50
+ Future<List<Map<String, dynamic>>> listPlanItems(
51
+ {DateTime? from, DateTime? to, String? kind}) async =>
52
+ throw const ApiException(500, 'server_failed');
53
+}
54
+
55
+class _PlannerWritesApi extends FakeApi {
56
+ final mutations = <Map<String, dynamic>>[];
57
+ @override
58
+ Future<Map<String, dynamic>> submitSyncMutations(
59
+ List<Map<String, dynamic>> changes) async {
60
+ mutations.addAll(changes);
61
+ return {
62
+ 'results': changes
63
+ .map((m) => {
64
+ 'id': m['id'],
65
+ 'status': 'accepted',
66
+ 'item': {
67
+ 'id': m['entityId'],
68
+ ...(m['payload'] as Map),
69
+ 'version': (m['expectedVersion'] as int) + 1,
70
+ 'status': 'planned'
71
+ },
72
+ 'acceptedAt': '2026-10-08T10:00:00Z'
73
+ })
74
+ .toList()
75
+ };
76
+ }
77
+}
78
+
79
+class _CategoryApi extends FakeApi {
80
+ _CategoryApi(this.category, {super.role});
81
+ String category;
82
+ @override
83
+ Future<Map<String, dynamic>> getProfile() async =>
84
+ {...await super.getProfile(), 'profile_category': category};
85
+ @override
86
+ Future<Map<String, dynamic>> updateProfile(
87
+ {String? displayName,
88
+ String? birthDate,
89
+ String? themePreference,
90
+ String? profileCategory}) async {
91
+ if (profileCategory != null) category = profileCategory;
92
+ return {
93
+ ...await super.updateProfile(
94
+ displayName: displayName,
95
+ birthDate: birthDate,
96
+ themePreference: themePreference),
97
+ 'profile_category': category
98
+ };
99
+ }
100
+}
101
+
102
+class _OfflinePlannerApi extends FakeApi {
103
+ @override
104
+ Future<List<Map<String, dynamic>>> listPlanItems(
105
+ {DateTime? from, DateTime? to, String? kind}) async =>
106
+ throw const ApiException(0, 'network_unavailable');
107
+ @override
108
+ Future<Map<String, dynamic>> submitSyncMutations(
109
+ List<Map<String, dynamic>> changes) async =>
110
+ throw const ApiException(0, 'network_unavailable');
111
+}
112
+
113
+class _CategoryWithoutFamiliesApi extends _CategoryApi {
114
+ _CategoryWithoutFamiliesApi() : super('adult');
115
+ @override
116
+ Future<List<Map<String, dynamic>>> listFamilies() async =>
117
+ throw const ApiException(500, 'server_failed');
118
+}
119
+
120
+void main() {
121
+ setUp(() {
122
+ SharedPreferences.setMockInitialValues({});
123
+ SharedPreferencesAsyncPlatform.instance =
124
+ InMemorySharedPreferencesAsync.withData({});
125
+ String? pending;
126
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
127
+ .setMockMethodCallHandler(
128
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
129
+ if (call.method == 'getBlocked') return pending != null;
130
+ if (call.method == 'beginWrite') return pending = 'owned-ui-test-token';
131
+ if (call.method == 'completeWrite' && call.arguments == pending) {
132
+ pending = null;
133
+ return true;
134
+ }
135
+ throw PlatformException(code: 'local_storage_restart_required');
136
+ });
137
+ });
138
+
139
+ testWidgets('empty runtime endpoints open setup before constructing an API',
140
+ (tester) async {
141
+ await tester.pumpWidget(LifeMateApp());
142
+ await tester.pumpAndSettle();
143
+ expect(find.text('اتصال لایفگاید'), findsOneWidget);
144
+ expect(find.text('ورود'), findsNothing);
145
+ });
146
+
147
+ test('auth errors do not disclose an existing account', () {
148
+ expect(errorText(const ApiException(409, 'account_exists')),
149
+ 'عملیات انجام نشد. دوباره تلاش کن.');
150
+ });
151
+
152
+ testWidgets('authenticated notification inbox is offered only in home drawer',
153
+ (tester) async {
154
+ await tester.pumpWidget(LifeMateApp(api: FakeApi()));
155
+ await tester.pumpAndSettle();
156
+ expect(find.text('اعلانهای درون برنامه'), findsNothing);
157
+ await tester.pumpWidget(MaterialApp(home: HomeShell(api: FakeApi())));
158
+ await tester.pumpAndSettle();
159
+ tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
160
+ await tester.pumpAndSettle();
161
+ expect(find.text('اعلانهای درون برنامه'), findsOneWidget);
162
+ });
163
+
164
+ testWidgets('home drawer opens durable pending changes screen',
165
+ (tester) async {
166
+ await tester.pumpWidget(MaterialApp(home: HomeShell(api: FakeApi())));
167
+ await tester.pumpAndSettle();
168
+ tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
169
+ await tester.pumpAndSettle();
170
+ await tester.tap(find.text('تغییرهای معلق و تعارضها'));
171
+ await tester.pumpAndSettle();
172
+ expect(find.byType(SyncChangesPage), findsOneWidget);
173
+ expect(find.text('تغییر معلقی باقی نمانده است.'), findsOneWidget);
174
+ });
175
+
176
+ testWidgets('sensitive guide remains disabled in the online shell',
177
+ (tester) async {
178
+ await tester.pumpWidget(MaterialApp(home: HomeShell(api: FakeApi())));
179
+ await tester.pumpAndSettle();
180
+ tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
181
+ await tester.pumpAndSettle();
182
+ await tester.tap(find.text('همراه هوشمند'));
183
+ await tester.pumpAndSettle();
184
+ expect(find.byType(Phase4Hub), findsNothing);
185
+ expect(find.textContaining('در این مرحله فعال نیست'), findsOneWidget);
186
+ });
187
+
188
+ testWidgets('online planner offers homework without school setup',
189
+ (tester) async {
190
+ await tester.pumpWidget(MaterialApp(
191
+ home: Scaffold(body: PlannerPage(api: FakeApi())),
192
+ ));
193
+ await tester.pumpAndSettle();
194
+ await tester.tap(find.text('جدید'));
195
+ await tester.pumpAndSettle();
196
+ await tester.tap(find.byType(DropdownButtonFormField<String>).first);
197
+ await tester.pumpAndSettle();
198
+ expect(find.text('تکلیف'), findsOneWidget);
199
+ });
200
+ testWidgets('profile save failure is visible and dialog remains editable',
201
+ (tester) async {
202
+ await tester.pumpWidget(
203
+ MaterialApp(home: ProfileFamilyPage(api: _FailingProfileApi())));
204
+ await tester.pumpAndSettle();
205
+ await tester.tap(find.byIcon(Icons.edit_outlined));
206
+ await tester.pumpAndSettle();
207
+ await tester.tap(find.text('ذخیره'));
208
+ await tester.pumpAndSettle();
209
+ expect(tester.takeException(), isNull);
210
+ expect(find.textContaining('سرور پاسخ معتبر نداد'), findsOneWidget);
211
+ expect(find.byType(AlertDialog), findsOneWidget);
212
+ });
213
+ testWidgets(
214
+ 'configured authenticated runtime opens home and settings uses child navigator',
215
+ (tester) async {
216
+ final session = _MemorySession();
217
+ final api = HttpIdentityApi(
218
+ baseUrl: 'https://synthetic.example.test/service',
219
+ sessionStore: session,
220
+ client: MockClient((req) async {
221
+ final value = req.url.path.endsWith('/me')
222
+ ? {
223
+ 'user_id': 'child',
224
+ 'display_name': 'فرزند',
225
+ 'theme_preference': 'girl_pink'
226
+ }
227
+ : req.url.path.endsWith('/families')
228
+ ? {'families': []}
229
+ : {'items': []};
230
+ return http.Response(jsonEncode(value), 200,
231
+ headers: {'content-type': 'application/json'});
232
+ }))
233
+ ..accessToken = 'synthetic-token'
234
+ ..currentUserId = 'child';
235
+ final runtime = RuntimeController(sessionStore: session)
236
+ ..initialized = true
237
+ ..config = RuntimeConfig(apiBaseUrl: api.baseUrl)
238
+ ..api = api;
239
+ await tester.pumpWidget(LifeMateApp(runtime: runtime));
240
+ await tester.pumpAndSettle();
241
+ expect(find.byType(HomeShell), findsOneWidget);
242
+ expect(find.text('ورود'), findsNothing);
243
+ tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
244
+ await tester.pumpAndSettle();
245
+ await tester.tap(find.text('تنظیم اتصال'));
246
+ await tester.pumpAndSettle();
247
+ expect(tester.takeException(), isNull);
248
+ expect(find.text('اتصال لایفگاید'), findsOneWidget);
249
+ await runtime.signOut();
250
+ await tester.pumpAndSettle();
251
+ expect(find.text('ورود'), findsOneWidget);
252
+ expect(find.text('اتصال لایفگاید'), findsNothing);
253
+ await tester.pumpWidget(const SizedBox());
254
+ runtime.dispose();
255
+ });
256
+ testWidgets('server failure never presents cached planner as live',
257
+ (tester) async {
258
+ final api = _ServerFailureApi();
259
+ await OfflineStore.forApi(api).cachePlanner([
260
+ {'id': 'old', 'title': 'نسخه قدیمی', 'kind': 'task', 'status': 'planned'}
261
+ ]);
262
+ await tester
263
+ .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
264
+ await tester.pumpAndSettle();
265
+ expect(find.text('نسخه قدیمی'), findsNothing);
266
+ expect(find.textContaining('سرور پاسخ معتبر نداد'), findsOneWidget);
267
+ expect(find.textContaining('نسخه ذخیرهشده'), findsNothing);
268
+ await tester.pumpWidget(const SizedBox());
269
+ });
270
+ testWidgets(
271
+ 'homework sharing requires explicit family and sends planned time',
272
+ (tester) async {
273
+ final api = _PlannerWritesApi();
274
+ await tester
275
+ .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
276
+ await tester.pumpAndSettle();
277
+ await tester.tap(find.text('جدید'));
278
+ await tester.pumpAndSettle();
279
+ await tester.enterText(find.widgetWithText(TextField, 'عنوان'), 'ریاضی');
280
+ await tester.tap(find.byType(DropdownButtonFormField<String>).first);
281
+ await tester.pumpAndSettle();
282
+ await tester.tap(find.text('تکلیف').last);
283
+ await tester.pumpAndSettle();
284
+ await tester.ensureVisible(find.byType(SwitchListTile));
285
+ await tester.tap(find.byType(SwitchListTile));
286
+ await tester.pumpAndSettle();
287
+ await tester.tap(find.text('ذخیره'));
288
+ await tester.pumpAndSettle();
289
+ expect(find.textContaining('خانوادهای را'), findsOneWidget);
290
+ expect(api.mutations, isEmpty);
291
+ await tester
292
+ .ensureVisible(find.byType(DropdownButtonFormField<String>).last);
293
+ await tester.tap(find.byType(DropdownButtonFormField<String>).last);
294
+ await tester.pumpAndSettle();
295
+ await tester.tap(find.text('خانواده').last);
296
+ await tester.pumpAndSettle();
297
+ await tester.tap(find.text('ذخیره'));
298
+ await tester.pumpAndSettle();
299
+ final payload = api.mutations.single['payload'] as Map;
300
+ expect(payload['kind'], 'assignment');
301
+ expect(payload['familyId'], 'family-1');
302
+ expect(payload['visibility'], 'parent_guardian');
303
+ expect(payload['plannedDurationSeconds'], 1800);
304
+ await tester.pumpWidget(const SizedBox());
305
+ });
306
+ testWidgets(
307
+ 'phone registration exposes actual unavailable SMS error without delivery claim',
308
+ (tester) async {
309
+ Map? payload;
310
+ final api = HttpIdentityApi(
311
+ baseUrl: 'https://synthetic.example.test',
312
+ client: MockClient((req) async {
313
+ payload = jsonDecode(req.body) as Map;
314
+ return http.Response('{"error":"sms_unavailable"}', 503,
315
+ headers: {'content-type': 'application/json'});
316
+ }));
317
+ await tester.pumpWidget(MaterialApp(home: RegistrationPage(api: api)));
318
+ await tester.pumpAndSettle();
319
+ await tester.tap(find.text('تلفن'));
320
+ await tester.pumpAndSettle();
321
+ await tester.enterText(find.widgetWithText(TextField, 'نام'), 'فرزند');
322
+ await tester.enterText(
323
+ find.widgetWithText(TextField, 'شماره تلفن'), '+989123456789');
324
+ await tester.enterText(
325
+ find.widgetWithText(TextField, 'رمز عبور'), 'synthetic-password');
326
+ await tester.enterText(
327
+ find.widgetWithText(TextField, 'تکرار رمز عبور'), 'synthetic-password');
328
+ await tester.tap(find.text('ثبت درخواست'));
329
+ await tester.pumpAndSettle();
330
+ expect(payload!['phone'], '+989123456789');
331
+ expect(payload!.containsKey('email'), isFalse);
332
+ expect(find.textContaining('سرویس پیامک فعال نیست'), findsOneWidget);
333
+ expect(find.textContaining('درخواست بررسی شد'), findsNothing);
334
+ await tester.pumpWidget(const SizedBox());
335
+ api.close();
336
+ });
337
+ testWidgets('profile category controls shell without granting family role',
338
+ (tester) async {
339
+ await tester.pumpWidget(MaterialApp(
340
+ home: HomeShell(api: _CategoryApi('adult', role: 'teen_minor'))));
341
+ await tester.pumpAndSettle();
342
+ expect(find.text('برنامهریز'), findsOneWidget);
343
+ await tester.pumpWidget(const SizedBox());
344
+ });
345
+ testWidgets(
346
+ 'offline homework can be edited while its create awaits acknowledgement',
347
+ (tester) async {
348
+ final api = _OfflinePlannerApi();
349
+ await tester
350
+ .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
351
+ await tester.pumpAndSettle();
352
+ await tester.tap(find.text('جدید'));
353
+ await tester.pumpAndSettle();
354
+ await tester.enterText(find.widgetWithText(TextField, 'عنوان'), 'ریاضی');
355
+ await tester.tap(find.text('ذخیره'));
356
+ await tester.pumpAndSettle();
357
+ await tester.tap(find.byType(PopupMenuButton<String>));
358
+ await tester.pumpAndSettle();
359
+ await tester.tap(find.text('ویرایش'));
360
+ await tester.pumpAndSettle();
361
+ await tester.enterText(
362
+ find.widgetWithText(TextField, 'عنوان'), 'ریاضی جدید');
363
+ await tester.tap(find.text('ذخیره'));
364
+ await tester.pumpAndSettle();
365
+ expect(find.byType(AlertDialog), findsNothing);
366
+ expect(find.text('ریاضی جدید'), findsOneWidget);
367
+ expect(await OfflineStore.forApi(api).pendingCount(), 2);
368
+ await tester.pumpWidget(const SizedBox());
369
+ });
370
+ testWidgets(
371
+ 'email ownership verification requires explicit new password submission',
372
+ (tester) async {
373
+ Map? submitted;
374
+ final api = HttpIdentityApi(
375
+ baseUrl: 'https://synthetic.example.test',
376
+ client: MockClient((req) async {
377
+ submitted = jsonDecode(req.body) as Map;
378
+ return http.Response('{}', 200,
379
+ headers: {'content-type': 'application/json'});
380
+ }));
381
+ await tester.pumpWidget(
382
+ MaterialApp(home: VerifyEmailPage(api: api, token: 'synthetic-proof')));
383
+ await tester.pumpAndSettle();
384
+ expect(submitted, isNull);
385
+ await tester.enterText(
386
+ find.widgetWithText(TextField, 'رمز عبور جدید'), 'synthetic-password');
387
+ await tester.enterText(
388
+ find.widgetWithText(TextField, 'تکرار رمز عبور'), 'synthetic-password');
389
+ await tester.tap(find.text('تأیید و تعیین رمز عبور'));
390
+ await tester.pumpAndSettle();
391
+ expect(submitted,
392
+ {'token': 'synthetic-proof', 'newPassword': 'synthetic-password'});
393
+ expect(find.text('ایمیل تأیید شد'), findsOneWidget);
394
+ await tester.pumpWidget(const SizedBox());
395
+ api.close();
396
+ });
397
+ testWidgets('editing a private task can explicitly change guardian sharing',
398
+ (tester) async {
399
+ final api = _PlannerWritesApi();
400
+ await tester.pumpWidget(MaterialApp(
401
+ home: Scaffold(
402
+ body: Builder(
403
+ builder: (context) => TextButton(
404
+ onPressed: () => showDialog(
405
+ context: context,
406
+ builder: (_) => PlanItemDialog(api: api, item: {
407
+ 'id': 'saved-plan',
408
+ 'title': 'ریاضی',
409
+ 'kind': 'assignment',
410
+ 'status': 'planned',
411
+ 'visibility': 'private',
412
+ 'version': 1
413
+ })),
414
+ child: const Text('باز کردن'))))));
415
+ await tester.tap(find.text('باز کردن'));
416
+ await tester.pumpAndSettle();
417
+ await tester.ensureVisible(find.byType(SwitchListTile));
418
+ await tester.tap(find.byType(SwitchListTile));
419
+ await tester.pumpAndSettle();
420
+ await tester
421
+ .ensureVisible(find.byType(DropdownButtonFormField<String>).last);
422
+ await tester.tap(find.byType(DropdownButtonFormField<String>).last);
423
+ await tester.pumpAndSettle();
424
+ await tester.tap(find.text('خانواده').last);
425
+ await tester.pumpAndSettle();
426
+ await tester.tap(find.text('ذخیره'));
427
+ await tester.pumpAndSettle();
428
+ expect((api.mutations.single['payload'] as Map)['visibility'],
429
+ 'parent_guardian');
430
+ expect(find.byType(AlertDialog), findsNothing);
431
+ await tester.pumpWidget(const SizedBox());
432
+ });
433
+ testWidgets('profile category routing does not depend on family availability',
434
+ (tester) async {
435
+ await tester.pumpWidget(
436
+ MaterialApp(home: HomeShell(api: _CategoryWithoutFamiliesApi())));
437
+ await tester.pumpAndSettle();
438
+ expect(find.text('برنامهریز'), findsOneWidget);
439
+ await tester.pumpWidget(const SizedBox());
440
+ });
441
+ testWidgets(
442
+ 'logout warns before discarding an unsent change and cancel preserves identity',
443
+ (tester) async {
444
+ final session = _MemorySession();
445
+ final api = HttpIdentityApi(
446
+ baseUrl: 'https://synthetic.example.test',
447
+ sessionStore: session,
448
+ client: MockClient((req) async => http.Response(
449
+ jsonEncode(req.url.path.endsWith('/profile')
450
+ ? {
451
+ 'profile_category': 'adult',
452
+ 'theme_preference': 'adult_blue'
453
+ }
454
+ : req.url.path.endsWith('/families')
455
+ ? {'families': []}
456
+ : {'items': []}),
457
+ 200,
458
+ headers: {'content-type': 'application/json'})))
459
+ ..accessToken = 'synthetic-token'
460
+ ..currentUserId = 'child';
461
+ final runtime = RuntimeController(sessionStore: session)
462
+ ..initialized = true
463
+ ..config = RuntimeConfig(apiBaseUrl: api.baseUrl)
464
+ ..api = api;
465
+ await OfflineStore.forApi(api).enqueue({
466
+ 'id': '9f7b762c-905f-48a1-81b3-ded3ed72d3c0',
467
+ 'entityId': '3a940940-f482-4b5a-937a-d74cc9ef9daf',
468
+ 'entityType': 'plan_item',
469
+ 'operation': 'create',
470
+ 'expectedVersion': 0,
471
+ 'payload': {'kind': 'task', 'title': 'معلق'}
472
+ });
473
+ await tester.pumpWidget(LifeMateApp(runtime: runtime));
474
+ await tester.pumpAndSettle();
475
+ tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
476
+ await tester.pumpAndSettle();
477
+ await tester.tap(find.text('خروج از حساب'));
478
+ await tester.pumpAndSettle();
479
+ expect(find.textContaining('تغییر معلق'), findsOneWidget);
480
+ expect(api.accessToken, isNotNull);
481
+ await tester.tap(find.text('انصراف'));
482
+ await tester.pumpAndSettle();
483
+ expect(api.accessToken, isNotNull);
484
+ expect(await OfflineStore.forApi(api).pendingCount(), 1);
485
+ await tester.pumpWidget(const SizedBox());
486
+ runtime.dispose();
487
+ });
488
+ testWidgets(
489
+ 'endpoint save warns before discard and cancel preserves endpoint and queue',
490
+ (tester) async {
491
+ final session = _MemorySession();
492
+ final api = HttpIdentityApi(
493
+ baseUrl: 'https://synthetic.example.test',
494
+ sessionStore: session,
495
+ client: MockClient((req) async => http.Response(
496
+ jsonEncode(req.url.path.endsWith('/profile')
497
+ ? {
498
+ 'profile_category': 'adult',
499
+ 'theme_preference': 'adult_blue'
500
+ }
501
+ : req.url.path.endsWith('/families')
502
+ ? {'families': []}
503
+ : {'items': []}),
504
+ 200,
505
+ headers: {'content-type': 'application/json'})))
506
+ ..accessToken = 'synthetic-token'
507
+ ..currentUserId = 'child';
508
+ final runtime = RuntimeController(sessionStore: session)
509
+ ..initialized = true
510
+ ..config = RuntimeConfig(apiBaseUrl: api.baseUrl)
511
+ ..api = api;
512
+ await OfflineStore.forApi(api).enqueue({
513
+ 'id': '9f7b762c-905f-48a1-81b3-ded3ed72d3c0',
514
+ 'entityId': '3a940940-f482-4b5a-937a-d74cc9ef9daf',
515
+ 'entityType': 'plan_item',
516
+ 'operation': 'create',
517
+ 'expectedVersion': 0,
518
+ 'payload': {'kind': 'task', 'title': 'معلق'}
519
+ });
520
+ await tester.pumpWidget(LifeMateApp(runtime: runtime));
521
+ await tester.pumpAndSettle();
522
+ tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
523
+ await tester.pumpAndSettle();
524
+ await tester.tap(find.text('تنظیم اتصال'));
525
+ await tester.pumpAndSettle();
526
+ await tester.enterText(find.widgetWithText(TextField, 'نشانی اصلی'),
527
+ 'https://other.synthetic.example.test');
528
+ await tester.tap(find.text('ذخیره و ادامه'));
529
+ await tester.pumpAndSettle();
530
+ expect(find.textContaining('تغییر معلق'), findsOneWidget);
531
+ await tester.tap(find.text('انصراف'));
532
+ await tester.pumpAndSettle();
533
+ expect(runtime.config.apiBaseUrl, 'https://synthetic.example.test');
534
+ expect(api.accessToken, isNotNull);
535
+ expect(await OfflineStore.forApi(api).pendingCount(), 1);
536
+ await tester.pumpWidget(const SizedBox());
537
+ runtime.dispose();
538
+ });
539
+ testWidgets(
540
+ 'offline planner fallback shows owned rows and hides shared child rows',
541
+ (tester) async {
542
+ final api = HttpIdentityApi(
543
+ baseUrl: 'https://synthetic.example.test',
544
+ client: MockClient((_) async =>
545
+ throw http.ClientException('synthetic transport failure')))
546
+ ..accessToken = 'synthetic-token'
547
+ ..currentUserId = 'parent';
548
+ await OfflineStore.forApi(api).cachePlanner([
549
+ {
550
+ 'id': 'own',
551
+ 'owner_user_id': 'parent',
552
+ 'title': 'کار خودم',
553
+ 'kind': 'task',
554
+ 'status': 'planned'
555
+ },
556
+ {
557
+ 'id': 'shared-child',
558
+ 'owner_user_id': 'child',
559
+ 'title': 'داده فرزند',
560
+ 'kind': 'assignment',
561
+ 'status': 'planned'
562
+ }
563
+ ]);
564
+ await tester
565
+ .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
566
+ await tester.pumpAndSettle();
567
+ expect(find.text('کار خودم'), findsOneWidget);
568
+ expect(find.text('داده فرزند'), findsNothing);
569
+ expect(find.textContaining('داده زنده نیست'), findsOneWidget);
570
+ await tester.pumpWidget(const SizedBox());
571
+ api.close();
572
+ });
573
+ testWidgets(
574
+ 'offline owned pending create remains visible without a server owner field',
575
+ (tester) async {
576
+ final api = HttpIdentityApi(
577
+ baseUrl: 'https://synthetic.example.test',
578
+ client: MockClient((_) async =>
579
+ throw http.ClientException('synthetic transport failure')))
580
+ ..accessToken = 'synthetic-token'
581
+ ..currentUserId = 'child';
582
+ await PlanSync(api).create(
583
+ {'kind': 'assignment', 'title': 'تکلیف خودم', 'visibility': 'private'});
584
+ await tester
585
+ .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
586
+ await tester.pumpAndSettle();
587
+ expect(find.text('تکلیف خودم'), findsOneWidget);
588
+ expect(find.textContaining('در انتظار تأیید سرور'), findsWidgets);
589
+ await tester.pumpWidget(const SizedBox());
590
+ api.close();
591
+ });
592
+ testWidgets(
593
+ 'owner exam grade edit sends normalized points and current version',
594
+ (tester) async {
595
+ final api = _PlannerWritesApi();
596
+ await tester.pumpWidget(MaterialApp(
597
+ home: Scaffold(
598
+ body: Builder(
599
+ builder: (context) => TextButton(
600
+ onPressed: () => showDialog(
601
+ context: context,
602
+ builder: (_) => PlanItemDialog(api: api, item: {
603
+ 'id': 'saved-exam',
604
+ 'title': 'امتحان ریاضی',
605
+ 'kind': 'exam',
606
+ 'status': 'planned',
607
+ 'visibility': 'private',
608
+ 'version': 4
609
+ })),
610
+ child: const Text('باز کردن'))))));
611
+ await tester.tap(find.text('باز کردن'));
612
+ await tester.pumpAndSettle();
613
+ await tester
614
+ .ensureVisible(find.widgetWithText(TextField, 'نمره (اختیاری)'));
615
+ await tester.enterText(
616
+ find.widgetWithText(TextField, 'نمره (اختیاری)'), '۱۵٫۵');
617
+ await tester
618
+ .ensureVisible(find.widgetWithText(TextField, 'سقف نمره (اختیاری)'));
619
+ await tester.enterText(
620
+ find.widgetWithText(TextField, 'سقف نمره (اختیاری)'), '۲۰');
621
+ await tester.tap(find.text('ذخیره'));
622
+ await tester.pumpAndSettle();
623
+ expect(api.mutations.single['expectedVersion'], 4);
624
+ expect((api.mutations.single['payload'] as Map)['gradePoints'], 15.5);
625
+ expect((api.mutations.single['payload'] as Map)['gradeOutOf'], 20);
626
+ expect(find.byType(AlertDialog), findsNothing);
627
+ await tester.pumpWidget(const SizedBox());
628
+ });
629
+}
apps/lifemate/test/phase4_ui_test.dart
+2
@@ -4,6 +4,8 @@ import 'package:lifemate/api.dart';
4
import 'package:lifemate/phase4_ui.dart';
5
6
class StubApi extends HttpIdentityApi {
7
+ StubApi() : super(baseUrl: 'https://fixture.example.test');
8
+
9
@override
10
Future<List<Map<String, dynamic>>> listLearningGoals() async => [];
11
}
apps/lifemate/test/runtime_config_test.dart
new
+383
@@ -0,0 +1,383 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+import 'package:flutter_test/flutter_test.dart';
4
+import 'package:http/http.dart' as http;
5
+import 'package:http/testing.dart';
6
+import 'package:lifemate/api.dart';
7
+import 'package:lifemate/runtime_config.dart';
8
+import 'package:lifemate/runtime_controller.dart';
9
+import 'package:lifemate/session_store.dart';
10
+
11
+class MemorySessionStore implements SessionStore {
12
+ String? value;
13
+ @override
14
+ Future<String?> read() async => value;
15
+ @override
16
+ Future<void> write(String next) async {
17
+ value = next;
18
+ }
19
+
20
+ @override
21
+ Future<void> clear() async {
22
+ value = null;
23
+ }
24
+}
25
+
26
+class MemoryConfigStore extends RuntimeConfigStore {
27
+ MemoryConfigStore(this.value);
28
+ RuntimeConfig value;
29
+ final saved = <RuntimeConfig>[];
30
+ @override
31
+ Future<RuntimeConfig> load() async => value;
32
+ @override
33
+ Future<void> saveAndroid(RuntimeConfig next) async {
34
+ saved.add(next);
35
+ value = next;
36
+ }
37
+}
38
+
39
+class DelayedConfigStore extends RuntimeConfigStore {
40
+ final result = Completer<RuntimeConfig>();
41
+ @override
42
+ Future<RuntimeConfig> load() => result.future;
43
+}
44
+
45
+class FailingClearSessionStore extends MemorySessionStore {
46
+ @override
47
+ Future<void> clear() async => throw StateError('storage unavailable');
48
+}
49
+
50
+String token(String user, String version) =>
51
+ 'header.${base64Url.encode(utf8.encode(jsonEncode({
52
+ 'sub': user,
53
+ 'version': version
54
+ })))}.signature';
55
+http.Response tokens(
56
+ String user, String version, String refresh) =>
57
+ http.Response(
58
+ jsonEncode(
59
+ {'accessToken': token(user, version), 'refreshToken': refresh}),
60
+ 200);
61
+
62
+void main() {
63
+ test('an insecure web page cannot load configuration or persisted sessions',
64
+ () async {
65
+ var requested = false;
66
+ final store = RuntimeConfigStore(
67
+ web: true,
68
+ webOrigin: Uri.parse('http://family.example.test/'),
69
+ client: MockClient((_) async {
70
+ requested = true;
71
+ return http.Response(
72
+ '{"apiBaseUrl":"https://api.example.test","apiFallbackUrls":[]}',
73
+ 200);
74
+ }));
75
+ await expectLater(store.load(), throwsStateError);
76
+ expect(requested, isFalse);
77
+ });
78
+ test(
79
+ 'failed cache clear blocks endpoint activation and exposes storage error',
80
+ () async {
81
+ final store = MemorySessionStore();
82
+ final configStore = MemoryConfigStore(
83
+ RuntimeConfig(apiBaseUrl: 'https://old.example.test'));
84
+ final controller = RuntimeController(
85
+ configStore: configStore,
86
+ sessionStore: store,
87
+ onScopeDiscarded: (_) async =>
88
+ throw StateError('cache write uncertain'),
89
+ apiFactory: (config) => HttpIdentityApi(
90
+ baseUrl: config.apiBaseUrl,
91
+ sessionStore: store,
92
+ client: MockClient(
93
+ (_) async => tokens('user-1', '1', 'fixture-refresh'))));
94
+ await controller.initialize();
95
+ await controller.api!.login('fixture@example.test', 'fixture-password');
96
+ await expectLater(
97
+ controller.updateEndpoints(
98
+ RuntimeConfig(apiBaseUrl: 'https://new.example.test')),
99
+ throwsStateError);
100
+ expect(controller.error, isA<StateError>());
101
+ expect(controller.api!.accessToken, isNull);
102
+ expect(controller.config.apiBaseUrl, 'https://old.example.test');
103
+ expect(configStore.saved, isEmpty);
104
+ controller.dispose();
105
+ });
106
+ test('account changes discard the old authenticated cache scope', () async {
107
+ final scopes = <String>[];
108
+ var loginCount = 0;
109
+ final api = HttpIdentityApi(
110
+ baseUrl: 'https://api.example.test',
111
+ sessionStore: MemorySessionStore(),
112
+ onScopeDiscarded: (scope) async => scopes.add(scope),
113
+ client: MockClient((_) async {
114
+ loginCount++;
115
+ return tokens(
116
+ 'user-$loginCount', '$loginCount', 'refresh-$loginCount');
117
+ }));
118
+ await api.login('first@example.test', 'fixture-password');
119
+ await api.login('second@example.test', 'fixture-password');
120
+ expect(scopes, ['https://api.example.test|user-1']);
121
+ expect(api.cacheNamespace, 'https://api.example.test|user-2');
122
+ });
123
+ test('logout notifies signed-out UI and clears cache even when storage fails',
124
+ () async {
125
+ final store = FailingClearSessionStore();
126
+ final discarded = <String>[];
127
+ final api = HttpIdentityApi(
128
+ baseUrl: 'https://api.example.test',
129
+ sessionStore: store,
130
+ onScopeDiscarded: (scope) async => discarded.add(scope),
131
+ client:
132
+ MockClient((_) async => tokens('user-1', '1', 'fixture-refresh')));
133
+ await api.login('fixture@example.test', 'fixture-password');
134
+ var notified = false;
135
+ api.onSessionChanged = () {
136
+ notified = true;
137
+ expect(api.accessToken, isNull);
138
+ };
139
+ await expectLater(api.logout(revoke: false), throwsStateError);
140
+ expect(notified, isTrue);
141
+ expect(api.cacheNamespace, isNull);
142
+ expect(discarded, ['https://api.example.test|user-1']);
143
+ });
144
+ test('disposed startup never constructs a new client or notifies listeners',
145
+ () async {
146
+ final store = DelayedConfigStore();
147
+ var constructed = 0;
148
+ final controller = RuntimeController(
149
+ configStore: store,
150
+ sessionStore: MemorySessionStore(),
151
+ apiFactory: (_) {
152
+ constructed++;
153
+ throw StateError('Must not construct after disposal.');
154
+ });
155
+ final loading = controller.initialize();
156
+ controller.dispose();
157
+ store.result
158
+ .complete(RuntimeConfig(apiBaseUrl: 'https://api.example.test'));
159
+ await loading;
160
+ expect(constructed, 0);
161
+ expect(controller.api, isNull);
162
+ });
163
+ test('endpoint changes clear old credentials and scope before using new API',
164
+ () async {
165
+ final store = MemorySessionStore();
166
+ final configStore = MemoryConfigStore(
167
+ RuntimeConfig(apiBaseUrl: 'https://old.example.test'));
168
+ final discarded = <String>[];
169
+ final requestedHosts = <String>[];
170
+ final controller = RuntimeController(
171
+ configStore: configStore,
172
+ sessionStore: store,
173
+ onScopeDiscarded: (scope) async {
174
+ expect(store.value, isNull);
175
+ discarded.add(scope);
176
+ },
177
+ apiFactory: (config) => HttpIdentityApi(
178
+ baseUrl: config.apiBaseUrl,
179
+ sessionStore: store,
180
+ client: MockClient((request) async {
181
+ requestedHosts.add(request.url.host);
182
+ return tokens('user-1', '1', 'old-refresh');
183
+ })));
184
+ await controller.initialize();
185
+ await controller.api!.login('fixture@example.test', 'fixture-password');
186
+ await controller
187
+ .updateEndpoints(RuntimeConfig(apiBaseUrl: 'https://new.example.test'));
188
+ expect(discarded, ['https://old.example.test|user-1']);
189
+ expect(store.value, isNull);
190
+ expect(controller.cacheNamespace, isNull);
191
+ expect(controller.api!.baseUrl, 'https://new.example.test');
192
+ expect(configStore.saved.single.apiBaseUrl, 'https://new.example.test');
193
+ expect(requestedHosts, ['old.example.test']);
194
+ controller.dispose();
195
+ });
196
+ test('HTTP and embedded credentials are rejected before client use', () {
197
+ for (final address in [
198
+ 'http://api.example.test',
199
+ 'https://user:pass@api.example.test',
200
+ 'https://api.example.test?q=1',
201
+ 'https://api.example.test#token'
202
+ ]) {
203
+ expect(() => HttpIdentityApi(baseUrl: address), throwsArgumentError);
204
+ }
205
+ expect(() => HttpIdentityApi(), throwsArgumentError);
206
+ });
207
+ test('HTTPS same-origin config resolves and fallback URLs are deduplicated',
208
+ () {
209
+ final config = RuntimeConfig.fromJson({
210
+ 'apiBaseUrl': '/api',
211
+ 'apiFallbackUrls': [
212
+ 'https://backup.example.test/',
213
+ 'https://backup.example.test'
214
+ ]
215
+ }, webOrigin: Uri.parse('https://family.example.test/'));
216
+ expect(config.endpoints,
217
+ ['https://family.example.test/api', 'https://backup.example.test']);
218
+ expect(
219
+ () => RuntimeConfig(
220
+ apiBaseUrl: '/api',
221
+ webOrigin: Uri.parse('http://family.example.test/')),
222
+ throwsArgumentError);
223
+ expect(RuntimeConfig().isConfigured, isFalse);
224
+ });
225
+ test('runtime web config is fetched fresh from hosting origin', () async {
226
+ final store = RuntimeConfigStore(
227
+ web: true,
228
+ webOrigin: Uri.parse(
229
+ 'https://family.example.test/reset-password?token=private'),
230
+ client: MockClient((request) async {
231
+ expect(request.url.path, '/config.json');
232
+ expect(request.url.queryParameters.containsKey('fresh'), isTrue);
233
+ expect(request.headers['Cache-Control'], 'no-store');
234
+ expect(request.url.query, isNot(contains('private')));
235
+ return http.Response(
236
+ '{"apiBaseUrl":"/api","apiFallbackUrls":[]}', 200);
237
+ }));
238
+ expect((await store.load()).apiBaseUrl, 'https://family.example.test/api');
239
+ });
240
+ test('refresh token survives API recreation and rotates before logout',
241
+ () async {
242
+ final store = MemorySessionStore();
243
+ final requests = <http.Request>[];
244
+ final client = MockClient((request) async {
245
+ requests.add(request);
246
+ if (request.url.path.endsWith('/login')) {
247
+ return tokens('user-1', '1', 'opaque-old');
248
+ }
249
+ if (request.url.path.endsWith('/refresh')) {
250
+ expect(jsonDecode(request.body)['refreshToken'], 'opaque-old');
251
+ return tokens('user-1', '2', 'opaque-new');
252
+ }
253
+ if (request.url.path.endsWith('/logout')) return http.Response('', 204);
254
+ return http.Response('{"user_id":"user-1"}', 200);
255
+ });
256
+ final first = HttpIdentityApi(
257
+ baseUrl: 'https://api.example.test/api',
258
+ client: client,
259
+ sessionStore: store);
260
+ await first.login('name@example.test', 'fixture-password');
261
+ expect(store.value, isNot(contains(token('user-1', '1'))));
262
+ expect(first.cacheNamespace, 'https://api.example.test/api|user-1');
263
+ final reopened = HttpIdentityApi(
264
+ baseUrl: first.baseUrl, client: client, sessionStore: store);
265
+ expect(reopened.cacheNamespace, isNull);
266
+ expect(await reopened.restoreSession(), isTrue);
267
+ expect(reopened.accessToken, token('user-1', '2'));
268
+ await reopened.getProfile();
269
+ expect(requests.last.headers['authorization'],
270
+ 'Bearer ${token('user-1', '2')}');
271
+ final cleared = <String>[];
272
+ reopened.onScopeDiscarded = (scope) async {
273
+ cleared.add(scope);
274
+ };
275
+ await reopened.logout();
276
+ expect(store.value, isNull);
277
+ expect(reopened.cacheNamespace, isNull);
278
+ expect(cleared, ['https://api.example.test/api|user-1']);
279
+ });
280
+ test('a stored session is never sent to another configured server', () async {
281
+ final store = MemorySessionStore()
282
+ ..value = jsonEncode({
283
+ 'endpoint': 'https://old.example.test',
284
+ 'refreshToken': 'old-refresh',
285
+ 'userId': 'user-1'
286
+ });
287
+ var sent = 0;
288
+ final discarded = <String>[];
289
+ final api = HttpIdentityApi(
290
+ baseUrl: 'https://new.example.test',
291
+ sessionStore: store,
292
+ onScopeDiscarded: (scope) async {
293
+ discarded.add(scope);
294
+ },
295
+ client: MockClient((_) async {
296
+ sent++;
297
+ return http.Response('{}', 200);
298
+ }));
299
+ expect(await api.restoreSession(), isFalse);
300
+ expect(sent, 0);
301
+ expect(store.value, isNull);
302
+ expect(discarded, ['https://old.example.test|user-1']);
303
+ });
304
+ test(
305
+ 'revoked refresh token clears the old cache scope without anonymous access',
306
+ () async {
307
+ final store = MemorySessionStore()
308
+ ..value = jsonEncode({
309
+ 'endpoint': 'https://api.example.test',
310
+ 'refreshToken': 'revoked',
311
+ 'userId': 'user-1'
312
+ });
313
+ final discarded = <String>[];
314
+ final api = HttpIdentityApi(
315
+ baseUrl: 'https://api.example.test',
316
+ sessionStore: store,
317
+ onScopeDiscarded: (scope) async {
318
+ discarded.add(scope);
319
+ },
320
+ client: MockClient((_) async =>
321
+ http.Response('{"error":"invalid_refresh_token"}', 401)));
322
+ expect(await api.restoreSession(), isFalse);
323
+ expect(store.value, isNull);
324
+ expect(api.cacheNamespace, isNull);
325
+ expect(discarded, ['https://api.example.test|user-1']);
326
+ });
327
+ test('late refresh after logout cannot revive or overwrite a new session',
328
+ () async {
329
+ final store = MemorySessionStore()
330
+ ..value = jsonEncode({
331
+ 'endpoint': 'https://old.example.test',
332
+ 'refreshToken': 'old-refresh',
333
+ 'userId': 'old-user'
334
+ });
335
+ final entered = Completer<void>();
336
+ final response = Completer<http.Response>();
337
+ final old = HttpIdentityApi(
338
+ baseUrl: 'https://old.example.test',
339
+ sessionStore: store,
340
+ client: MockClient((_) {
341
+ entered.complete();
342
+ return response.future;
343
+ }));
344
+ final restoring = old.restoreSession();
345
+ await entered.future;
346
+ await old.logout(revoke: false);
347
+ final next = HttpIdentityApi(
348
+ baseUrl: 'https://new.example.test',
349
+ sessionStore: store,
350
+ client:
351
+ MockClient((_) async => tokens('new-user', '1', 'new-refresh')));
352
+ await next.login('next@example.test', 'fixture-password');
353
+ response.complete(tokens('old-user', '2', 'late-old-refresh'));
354
+ expect(await restoring, isFalse);
355
+ expect(old.accessToken, isNull);
356
+ expect(jsonDecode(store.value!)['endpoint'], 'https://new.example.test');
357
+ expect(jsonDecode(store.value!)['refreshToken'], 'new-refresh');
358
+ });
359
+ test('transport failure does not retry a mutation on a fallback server',
360
+ () async {
361
+ var requests = 0;
362
+ final config = RuntimeConfig(
363
+ apiBaseUrl: 'https://primary.example.test',
364
+ apiFallbackUrls: ['https://backup.example.test']);
365
+ final api = HttpIdentityApi(
366
+ baseUrl: config.apiBaseUrl,
367
+ sessionStore: MemorySessionStore(),
368
+ client: MockClient((request) async {
369
+ requests++;
370
+ expect(request.url.host, 'primary.example.test');
371
+ if (request.url.path.endsWith('/login')) {
372
+ return tokens('user-1', '1', 'fixture-refresh');
373
+ }
374
+ throw http.ClientException('offline');
375
+ }));
376
+ await api.login('name@example.test', 'fixture-password');
377
+ await expectLater(
378
+ api.createPlanItem({'kind': 'task', 'title': 'Durable queued task'}),
379
+ throwsA(isA<ApiException>()
380
+ .having((error) => error.code, 'code', 'network_unavailable')));
381
+ expect(requests, 2);
382
+ });
383
+}
apps/lifemate/test/study_ui_test.dart
new
+242
@@ -0,0 +1,242 @@
1
+import 'dart:convert';
2
+import 'package:flutter/material.dart';
3
+import 'package:flutter/services.dart';
4
+import 'package:flutter_test/flutter_test.dart';
5
+import 'package:http/http.dart' as http;
6
+import 'package:http/testing.dart';
7
+import 'package:lifemate/api.dart';
8
+import 'package:lifemate/session_store.dart';
9
+import 'package:lifemate/study_coordinator.dart';
10
+import 'package:lifemate/study_ui.dart';
11
+import 'package:lifemate/dashboard_ui.dart';
12
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
13
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14
+
15
+class _MemorySession extends SessionStore {
16
+ String? value;
17
+ @override
18
+ Future<String?> read() async => value;
19
+ @override
20
+ Future<void> write(String next) async {
21
+ value = next;
22
+ }
23
+
24
+ @override
25
+ Future<void> clear() async {
26
+ value = null;
27
+ }
28
+}
29
+
30
+HttpIdentityApi apiFor(Future<http.Response> Function(http.Request) handler) =>
31
+ HttpIdentityApi(
32
+ baseUrl: 'https://synthetic.example.test/service',
33
+ client: MockClient(handler),
34
+ sessionStore: _MemorySession())
35
+ ..accessToken = 'synthetic-token'
36
+ ..currentUserId = 'synthetic-child';
37
+http.Response jsonResponse(Map<String, dynamic> json, [int status = 200]) =>
38
+ http.Response(jsonEncode(json), status,
39
+ headers: {'content-type': 'application/json'});
40
+void main() {
41
+ TestWidgetsFlutterBinding.ensureInitialized();
42
+ setUp(() {
43
+ SharedPreferencesAsyncPlatform.instance =
44
+ InMemorySharedPreferencesAsync.withData({});
45
+ String? pending;
46
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
47
+ .setMockMethodCallHandler(
48
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
49
+ if (call.method == 'getBlocked') return pending != null;
50
+ if (call.method == 'beginWrite') return pending = 'study-test-token';
51
+ if (call.method == 'completeWrite' && call.arguments == pending) {
52
+ pending = null;
53
+ return true;
54
+ }
55
+ throw PlatformException(code: 'local_storage_restart_required');
56
+ });
57
+ });
58
+ test('study acknowledgement for another session retains exact queued event',
59
+ () async {
60
+ final api = apiFor((req) async {
61
+ final body = jsonDecode(req.body) as Map;
62
+ return jsonResponse({
63
+ 'session': {'id': 'different-session', 'version': 1},
64
+ 'acknowledgement': {
65
+ 'mutationId': body['mutationId'],
66
+ 'status': 'accepted',
67
+ 'acceptedAt': '2026-10-08T10:00:00Z'
68
+ }
69
+ });
70
+ });
71
+ final sync = StudySync(api);
72
+ await expectLater(sync.start('owned-plan'), throwsA(isA<ApiException>()));
73
+ expect(await sync.store.readQueue(), hasLength(1));
74
+ api.close();
75
+ });
76
+ test('offline study start reopens and retries the same body once', () async {
77
+ bool offline = true;
78
+ final sent = <Map<String, dynamic>>[];
79
+ final api = apiFor((req) async {
80
+ final body = Map<String, dynamic>.from(jsonDecode(req.body) as Map);
81
+ sent.add(body);
82
+ if (offline) throw http.ClientException('synthetic transport failure');
83
+ return jsonResponse({
84
+ 'session': {
85
+ 'id': body['id'],
86
+ 'planItemId': body['planItemId'],
87
+ 'status': 'running',
88
+ 'version': 1,
89
+ 'recordedDurationSeconds': 0,
90
+ 'intervals': []
91
+ },
92
+ 'acknowledgement': {
93
+ 'mutationId': body['mutationId'],
94
+ 'status': 'accepted',
95
+ 'acceptedAt': '2026-10-08T10:00:00Z'
96
+ }
97
+ });
98
+ });
99
+ final first = await StudySync(api).start('owned-plan');
100
+ expect(first.queued, isTrue);
101
+ final reopened = StudySync(api);
102
+ final retained = await reopened.store.readQueue();
103
+ expect(retained, hasLength(1));
104
+ offline = false;
105
+ await reopened.flush();
106
+ expect(sent[1], sent[0]);
107
+ expect(await reopened.store.readQueue(), isEmpty);
108
+ expect((await reopened.store.readList('study.sessions')).single['status'],
109
+ 'running');
110
+ api.close();
111
+ });
112
+ testWidgets(
113
+ 'timer restores a running server session and labels recorded time',
114
+ (tester) async {
115
+ final api = apiFor((req) async => jsonResponse({
116
+ 'sessions': [
117
+ {
118
+ 'id': 'server-session',
119
+ 'planItemId': 'owned-plan',
120
+ 'status': 'running',
121
+ 'version': 3,
122
+ 'recordedDurationSeconds': 120,
123
+ 'intervals': [],
124
+ 'isEvidenceOfStudy': false
125
+ }
126
+ ],
127
+ 'asOf': '2026-10-08T10:00:00Z'
128
+ }));
129
+ await tester.pumpWidget(MaterialApp(
130
+ home: StudyTimerPage(
131
+ api: api, item: {'id': 'owned-plan', 'title': 'ریاضی'})));
132
+ await tester.pumpAndSettle();
133
+ expect(find.text('مکث'), findsOneWidget);
134
+ expect(find.text('پایان'), findsOneWidget);
135
+ expect(find.text('2:00'), findsOneWidget);
136
+ expect(find.textContaining('اثبات مطالعه نیست'), findsOneWidget);
137
+ await tester.pumpWidget(const SizedBox());
138
+ api.close();
139
+ });
140
+ testWidgets('parent polling failure labels previous report stale',
141
+ (tester) async {
142
+ var fail = false;
143
+ var calls = 0;
144
+ final api = apiFor((req) async {
145
+ calls++;
146
+ return fail
147
+ ? jsonResponse({'error': 'server_failed'}, 500)
148
+ : jsonResponse({
149
+ 'metrics': {
150
+ 'totalTasks': 1,
151
+ 'completedTasks': 0,
152
+ 'overdueTasks': 0,
153
+ 'completionPercent': 0,
154
+ 'plannedDurationSeconds': 1800,
155
+ 'recordedDurationSeconds': 120
156
+ },
157
+ 'items': [
158
+ {
159
+ 'id': 'plan',
160
+ 'title': 'ریاضی',
161
+ 'kind': 'assignment',
162
+ 'activityState': 'started',
163
+ 'activitySource': 'timer'
164
+ }
165
+ ],
166
+ 'daily': [],
167
+ 'subjects': [],
168
+ 'asOf': '2026-10-08T10:00:00Z',
169
+ 'lastSyncAt': '2026-10-08T09:00:00Z'
170
+ });
171
+ });
172
+ await tester.pumpWidget(MaterialApp(
173
+ home: LearningReportPage(
174
+ api: api,
175
+ familyId: 'family',
176
+ childId: 'child',
177
+ childName: 'فرزند')));
178
+ await tester.pumpAndSettle();
179
+ expect(find.text('ریاضی'), findsOneWidget);
180
+ fail = true;
181
+ await tester.pump(const Duration(seconds: 15));
182
+ await tester.pumpAndSettle();
183
+ expect(find.textContaining('داده قبلی بهروز نیست'), findsOneWidget);
184
+ expect(find.text('ریاضی'), findsOneWidget);
185
+ expect(calls, 2);
186
+ await tester.pumpWidget(const SizedBox());
187
+ await tester.pump(const Duration(seconds: 30));
188
+ expect(calls, 2);
189
+ api.close();
190
+ });
191
+ for (final denial in [401, 403, 0]) {
192
+ testWidgets(
193
+ 'parent refresh failure $denial clears previously displayed child data',
194
+ (tester) async {
195
+ var fail = false;
196
+ final api = apiFor((req) async {
197
+ if (fail) {
198
+ if (denial == 0) {
199
+ throw http.ClientException('synthetic transport failure');
200
+ }
201
+ return jsonResponse({'error': 'forbidden'}, denial);
202
+ }
203
+ return jsonResponse({
204
+ 'metrics': {},
205
+ 'items': [
206
+ {
207
+ 'id': 'plan',
208
+ 'title': 'اطلاعات فرزند',
209
+ 'kind': 'assignment',
210
+ 'activityState': 'started',
211
+ 'activitySource': 'timer'
212
+ }
213
+ ],
214
+ 'daily': [],
215
+ 'subjects': [],
216
+ 'asOf': '2026-10-08T10:00:00Z'
217
+ });
218
+ });
219
+ await tester.pumpWidget(MaterialApp(
220
+ home: LearningReportPage(
221
+ api: api,
222
+ familyId: 'family',
223
+ childId: 'child',
224
+ childName: 'فرزند')));
225
+ await tester.pumpAndSettle();
226
+ expect(find.text('اطلاعات فرزند'), findsOneWidget);
227
+ fail = true;
228
+ await tester.pump(const Duration(seconds: 15));
229
+ await tester.pumpAndSettle();
230
+ expect(find.text('اطلاعات فرزند'), findsNothing);
231
+ expect(
232
+ find.textContaining(denial == 401
233
+ ? 'نشست ورود'
234
+ : denial == 403
235
+ ? 'دسترسی نداری'
236
+ : 'اتصال برقرار نیست'),
237
+ findsOneWidget);
238
+ await tester.pumpWidget(const SizedBox());
239
+ api.close();
240
+ });
241
+ }
242
+}
apps/lifemate/test/sync_changes_test.dart
new
+185
@@ -0,0 +1,185 @@
1
+import 'package:flutter/services.dart';
2
+import 'package:flutter/material.dart';
3
+import 'package:flutter_test/flutter_test.dart';
4
+import 'package:http/http.dart' as http;
5
+import 'package:http/testing.dart';
6
+import 'package:lifemate/api.dart';
7
+import 'package:lifemate/offline_store.dart';
8
+import 'package:lifemate/sync_changes_ui.dart';
9
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
10
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
11
+
12
+class _ConflictApi extends HttpIdentityApi {
13
+ _ConflictApi({this.denied = false})
14
+ : super(
15
+ baseUrl: 'https://conflict.example.test',
16
+ client: MockClient((_) async => http.Response('', 503))) {
17
+ accessToken = 'synthetic-token';
18
+ currentUserId = denied ? 'denied-user' : 'test-owner';
19
+ }
20
+ final bool denied;
21
+ int reads = 0;
22
+ @override
23
+ Future<Map<String, dynamic>> requestJson(String method, String path,
24
+ {Map<String, dynamic>? body, bool auth = true}) async {
25
+ reads++;
26
+ if (denied) throw const ApiException(403, 'forbidden');
27
+ return {
28
+ 'id': path.split('/').last,
29
+ 'title': 'Server current',
30
+ 'version': 7
31
+ };
32
+ }
33
+}
34
+
35
+void main() {
36
+ TestWidgetsFlutterBinding.ensureInitialized();
37
+ setUp(() {
38
+ SharedPreferencesAsyncPlatform.instance =
39
+ InMemorySharedPreferencesAsync.withData({});
40
+ String? pending;
41
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
42
+ .setMockMethodCallHandler(
43
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
44
+ if (call.method == 'getBlocked') return pending != null;
45
+ if (call.method == 'beginWrite') return pending = 'test-owned';
46
+ if (call.method == 'completeWrite' && call.arguments == pending) {
47
+ pending = null;
48
+ return true;
49
+ }
50
+ throw PlatformException(code: 'local_storage_restart_required');
51
+ });
52
+ });
53
+
54
+ Map<String, dynamic> mutation(int id, String entity,
55
+ {String operation = 'update'}) =>
56
+ {
57
+ 'id': '00000000-0000-4000-8000-${id.toString().padLeft(12, '0')}',
58
+ 'entityType': 'plan_item',
59
+ 'entityId': entity,
60
+ 'operation': operation,
61
+ 'expectedVersion': id,
62
+ 'payload': {'title': 'Local $id', 'notes': 'Private draft $id'}
63
+ };
64
+
65
+ test(
66
+ 'explicit discard journals the complete entity chain and preserves unrelated changes',
67
+ () async {
68
+ final store = OfflineStore.forNamespace('discard|owner');
69
+ const target = '00000000-0000-4000-8000-000000000100';
70
+ const other = '00000000-0000-4000-8000-000000000200';
71
+ final first = mutation(1, target),
72
+ dependent = mutation(2, target),
73
+ unrelated = mutation(3, other);
74
+ await store.enqueue(first,
75
+ optimisticItem: {'id': target, 'title': 'Local first', 'version': 2});
76
+ await store.markQueued(first['id'] as String, 'conflict');
77
+ await store.enqueue(dependent,
78
+ optimisticItem: {'id': target, 'title': 'Local latest', 'version': 3});
79
+ await store.enqueue(unrelated,
80
+ optimisticItem: {'id': other, 'title': 'Unrelated', 'version': 4});
81
+ await store.cacheToday([
82
+ {'id': target, 'title': 'Server old', 'version': 1}
83
+ ]);
84
+ final canonical = {'id': target, 'title': 'Server current', 'version': 9};
85
+ await store.discardEntityChanges(target, serverItem: canonical);
86
+ expect((await store.readQueue()).map((m) => m['id']), [unrelated['id']]);
87
+ final reopened = OfflineStore.forNamespace(store.scope);
88
+ final journal = await reopened.readDiscardedChanges();
89
+ expect(journal, hasLength(2));
90
+ expect(journal.map((m) => m['id']), [first['id'], dependent['id']]);
91
+ expect(journal.first['payload'], first['payload']);
92
+ expect(journal.last['payload'], dependent['payload']);
93
+ expect(
94
+ journal.every(
95
+ (m) => DateTime.tryParse(m['discardedAt'] as String) != null),
96
+ isTrue);
97
+ expect((await reopened.readPlanner()).firstWhere((m) => m['id'] == target),
98
+ canonical);
99
+ expect((await reopened.readToday()).single, canonical);
100
+ expect(await reopened.readLastAck(), isNull);
101
+ });
102
+
103
+ test(
104
+ 'discarding an unsent creation removes its optimistic item and retains recovery payload',
105
+ () async {
106
+ final store = OfflineStore.forNamespace('discard-new|owner');
107
+ const id = '00000000-0000-4000-8000-000000000100';
108
+ final create = mutation(1, id, operation: 'create');
109
+ await store.enqueue(create,
110
+ optimisticItem: {'id': id, 'title': 'Never sent', 'version': 1});
111
+ await store.discardEntityChanges(id);
112
+ expect(await store.readQueue(), isEmpty);
113
+ expect(await store.readPlanner(), isEmpty);
114
+ expect((await store.readDiscardedChanges()).single['payload'],
115
+ create['payload']);
116
+ expect(await store.readLastAck(), isNull);
117
+ });
118
+
119
+ test(
120
+ 'a mismatched server entity cannot discard the queue or create a journal',
121
+ () async {
122
+ final store = OfflineStore.forNamespace('discard-invalid|owner');
123
+ const id = '00000000-0000-4000-8000-000000000100';
124
+ await store.enqueue(mutation(1, id));
125
+ await expectLater(
126
+ store.discardEntityChanges(id,
127
+ serverItem: {'id': 'other', 'version': 1}),
128
+ throwsA(isA<Exception>()));
129
+ expect(await store.readQueue(), hasLength(1));
130
+ expect(await store.readDiscardedChanges(), isEmpty);
131
+ });
132
+
133
+ testWidgets(
134
+ 'conflict dialog preserves local changes until explicit use-server choice',
135
+ (tester) async {
136
+ final api = _ConflictApi();
137
+ final store = OfflineStore.forApi(api);
138
+ const id = '00000000-0000-4000-8000-000000000100';
139
+ final pending = mutation(1, id);
140
+ await store.enqueue(pending);
141
+ await store.markQueued(pending['id'] as String, 'conflict');
142
+ await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
143
+ await tester.pumpAndSettle();
144
+ await tester.tap(find.text('بررسی و انتخاب'));
145
+ await tester.pumpAndSettle();
146
+ expect(find.text('نسخه سرور 7: Server current'), findsOneWidget);
147
+ expect(await store.readQueue(), hasLength(1));
148
+ await tester.tap(find.text('نگهداشتن تغییر محلی'));
149
+ await tester.pumpAndSettle();
150
+ expect(await store.readDiscardedChanges(), isEmpty);
151
+ await tester.tap(find.text('بررسی و انتخاب'));
152
+ await tester.pumpAndSettle();
153
+ await tester.tap(find.text('استفاده از نسخه سرور'));
154
+ await tester.pumpAndSettle();
155
+ expect(await store.readQueue(), isEmpty);
156
+ expect((await store.readDiscardedChanges()).single['payload'],
157
+ pending['payload']);
158
+ expect((await store.readPlanner()).single['version'], 7);
159
+ expect(find.text('Private draft 1'), findsNothing);
160
+ expect(await store.readLastAck(), isNull);
161
+ });
162
+
163
+ testWidgets(
164
+ '403 shows no comparison or cached title and retains every pending payload',
165
+ (tester) async {
166
+ final api = _ConflictApi(denied: true);
167
+ final store = OfflineStore.forApi(api);
168
+ const id = '00000000-0000-4000-8000-000000000100';
169
+ final pending = mutation(1, id);
170
+ await store.enqueue(pending,
171
+ optimisticItem: {'id': id, 'title': 'Cached forbidden title'});
172
+ await store.markQueued(pending['id'] as String, 'conflict');
173
+ await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
174
+ await tester.pumpAndSettle();
175
+ await tester.tap(find.text('بررسی و انتخاب'));
176
+ await tester.pumpAndSettle();
177
+ expect(
178
+ find.text('برای این اطلاعات یا عملیات دسترسی نداری.'), findsOneWidget);
179
+ expect(find.byType(AlertDialog), findsNothing);
180
+ expect(find.text('Cached forbidden title'), findsNothing);
181
+ expect(find.text('Local 1'), findsNothing);
182
+ expect(await store.readQueue(), hasLength(1));
183
+ expect(await store.readDiscardedChanges(), isEmpty);
184
+ });
185
+}
apps/lifemate/tool/export_brand_icons.mjs
new
+36
@@ -0,0 +1,36 @@
1
+// Reuses the Android vector; requires local Playwright and Chromium tooling.
2
+import {createRequire} from 'node:module';
3
+import {readFile} from 'node:fs/promises';
4
+import {execFileSync} from 'node:child_process';
5
+import {fileURLToPath} from 'node:url';
6
+import {dirname, join} from 'node:path';
7
+
8
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
9
+execFileSync('python3', [join(root, 'tool/export_brand_icons.py')], {stdio:'inherit'});
10
+const {chromium} = createRequire(import.meta.url)('playwright');
11
+const browser = await chromium.launch({executablePath:process.env.CHROMIUM_PATH || '/usr/bin/chromium', headless:true});
12
+try {
13
+ const page = await browser.newPage();
14
+ for (const [name, svgName, sizes] of [
15
+ ['Icon', 'lifeguide.svg', [192,512]],
16
+ ['Icon-maskable', 'lifeguide-maskable.svg', [192,512]],
17
+ ['favicon', 'lifeguide.svg', [32]],
18
+ ]) {
19
+ const source = (await readFile(join(root,'web/icons',svgName),'utf8'))
20
+ .replace(/<\?xml[^>]*\?>/, '');
21
+ for (const size of sizes) {
22
+ await page.setViewportSize({width:size,height:size});
23
+ await page.setContent('<style>html,body{margin:0;padding:0}</style>' + source);
24
+ await page.locator('svg').evaluate((element, pixels) => {
25
+ element.setAttribute('width', String(pixels));
26
+ element.setAttribute('height', String(pixels));
27
+ element.style.display = 'block';
28
+ },size);
29
+ const output = name === 'favicon' ? join(root,'web/favicon.png') : join(root,'web/icons',`${name}-${size}.png`);
30
+ await page.locator('svg').screenshot({path:output,omitBackground:true});
31
+ }
32
+ }
33
+} finally {
34
+ await browser.close();
35
+}
36
+console.log('PWA icons and favicon rasterized from matching Android-vector SVG sources.');
apps/lifemate/tool/export_brand_icons.py
new
+34
@@ -0,0 +1,34 @@
1
+"""Compile the existing Android vector into matching PWA launcher assets."""
2
+from pathlib import Path
3
+import xml.etree.ElementTree as ET
4
+
5
+ROOT = Path(__file__).resolve().parents[1]
6
+ANDROID = "{http://schemas.android.com/apk/res/android}"
7
+source = ET.parse(ROOT / "android/app/src/main/res/drawable/lifemate_logo.xml").getroot()
8
+svg_ns = "http://www.w3.org/2000/svg"
9
+ET.register_namespace("", svg_ns)
10
+
11
+
12
+def export_svg(maskable=False):
13
+ svg = ET.Element(f"{{{svg_ns}}}svg", {
14
+ "width": "512", "height": "512",
15
+ "viewBox": f"0 0 {source.attrib[ANDROID + 'viewportWidth']} {source.attrib[ANDROID + 'viewportHeight']}",
16
+ })
17
+ if maskable:
18
+ ET.SubElement(svg, f"{{{svg_ns}}}rect", {
19
+ "width": source.attrib[ANDROID + "viewportWidth"],
20
+ "height": source.attrib[ANDROID + "viewportHeight"],
21
+ "fill": "#4D86E8",
22
+ })
23
+ for element in source.findall("path"):
24
+ ET.SubElement(svg, f"{{{svg_ns}}}path", {
25
+ "fill": element.attrib[ANDROID + "fillColor"],
26
+ "d": element.attrib[ANDROID + "pathData"],
27
+ })
28
+ output = ROOT / "web/icons" / ("lifeguide-maskable.svg" if maskable else "lifeguide.svg")
29
+ ET.ElementTree(svg).write(output, encoding="utf-8", xml_declaration=True)
30
+ return output
31
+
32
+
33
+export_svg(), export_svg(True)
34
+print("Matching PWA SVG sources compiled from the existing Android vector.")
apps/lifemate/tool/self_host_web.mjs
new
+25
@@ -0,0 +1,25 @@
1
+import {readFile, writeFile, readdir} from 'node:fs/promises';
2
+import {join} from 'node:path';
3
+
4
+const root = process.argv[2] || 'build/web';
5
+async function walk(path) {
6
+ const files = [];
7
+ for (const entry of await readdir(path, {withFileTypes: true})) {
8
+ const location = join(path, entry.name);
9
+ if (entry.isDirectory()) files.push(...await walk(location));
10
+ else if (/\.(?:js|json|html)$/.test(entry.name)) files.push(location);
11
+ }
12
+ return files;
13
+}
14
+for (const file of await walk(root)) {
15
+ let source = await readFile(file, 'utf8');
16
+ // SDK defaults remain in generated JS despite the configured local loader.
17
+ // Neutralize these exact known defaults; never rewrite an operator API URL.
18
+ source = source.replaceAll('https://www.gstatic.com/flutter-canvaskit', 'canvaskit')
19
+ .replaceAll('https://fonts.gstatic.com/s/', 'assets/fonts/fallback/');
20
+ if (/https?:[^\s"'<>]*(?:gstatic\.com|googleapis\.com|up\.railway\.app)/i.test(source)) {
21
+ throw new Error(`Unexpected external runtime URL in ${file}`);
22
+ }
23
+ await writeFile(file, source);
24
+}
25
+console.log('Web resources use local CanvasKit/font bases; external SDK/CDN defaults removed.');
apps/lifemate/tool/test_web_bootstrap.mjs
new
+25
@@ -0,0 +1,25 @@
1
+import assert from 'node:assert/strict';
2
+import {readFile} from 'node:fs/promises';
3
+import vm from 'node:vm';
4
+
5
+const script = (await readFile(new URL('../web/flutter_bootstrap.js', import.meta.url), 'utf8'))
6
+ .replace('{{flutter_js}}', '').replace('{{flutter_build_config}}', '');
7
+let engineConfig;
8
+let removed = false;
9
+const status = {remove() { removed = true; }};
10
+const result = vm.runInNewContext(script, {
11
+ URL,
12
+ navigator: {},
13
+ document: {baseURI: 'https://family.example.test/', getElementById: () => status},
14
+ _flutter: {loader: {async load(options) {
15
+ assert.equal(options.config.canvasKitBaseUrl, 'https://family.example.test/canvaskit/');
16
+ await options.onEntrypointLoaded({async initializeEngine(config) {
17
+ engineConfig = config;
18
+ return {async runApp() {}};
19
+ }});
20
+ }}},
21
+});
22
+await result;
23
+assert.equal(engineConfig?.fontFallbackBaseUrl, 'https://family.example.test/assets/fonts/fallback/');
24
+assert.equal(removed, true);
25
+console.log('Custom bootstrap passes the local font configuration to the Flutter engine.');
apps/lifemate/tool/test_web_runtime.cjs
new
+85
@@ -0,0 +1,85 @@
1
+// Tests the actual compiled artifact at an intercepted synthetic HTTPS origin.
2
+// This does not validate real TLS, an installed PWA, Safari or an Android device.
3
+const assert = require('node:assert/strict');
4
+const {readFile} = require('node:fs/promises');
5
+const path = require('node:path');
6
+const {chromium} = require('playwright');
7
+
8
+const artifactRoot = path.resolve(process.argv[2] || 'build/web');
9
+const testUrl = new URL(process.env.LIFEGUIDE_WEB_TEST_ORIGIN || 'https://family.example.test');
10
+assert(testUrl.protocol === 'https:' && !testUrl.username && !testUrl.password &&
11
+ testUrl.pathname === '/' && !testUrl.search && !testUrl.hash,
12
+ 'The synthetic test origin must be a plain HTTPS origin.');
13
+const origin = testUrl.origin;
14
+const screenshotIndex = process.argv.indexOf('--screenshot');
15
+const screenshotPath = screenshotIndex < 0 ? null : process.argv[screenshotIndex + 1];
16
+if (screenshotIndex >= 0) assert(screenshotPath, '--screenshot requires a file path');
17
+const mime = {'.html':'text/html', '.js':'application/javascript', '.json':'application/json',
18
+ '.wasm':'application/wasm', '.ttf':'font/ttf', '.otf':'font/otf', '.woff2':'font/woff2',
19
+ '.png':'image/png', '.svg':'image/svg+xml'};
20
+const csp = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'";
21
+
22
+(async () => {
23
+ const executablePath = process.env.LIFEGUIDE_TEST_CHROMIUM_PATH;
24
+ const browser = await chromium.launch({headless:true,
25
+ ...(executablePath ? {executablePath} : {})});
26
+ try {
27
+ const context = await browser.newContext({viewport:{width:390,height:844},
28
+ ignoreHTTPSErrors:false, serviceWorkers:'block'});
29
+ const requested = [], missingAssets = [], errors = [];
30
+ await context.route('**/*', async route => {
31
+ const url = new URL(route.request().url());
32
+ requested.push(url.href);
33
+ if (url.origin !== origin) {
34
+ errors.push(`Unexpected external request: ${url.origin}`);
35
+ await route.abort();
36
+ return;
37
+ }
38
+ if (url.pathname === '/api/v1/auth/capabilities') {
39
+ await route.fulfill({contentType:'application/json', body:JSON.stringify({
40
+ emailDeliveryAvailable:false,smsAvailable:false,smsStatus:'UNVERIFIED'})});
41
+ return;
42
+ }
43
+ const local = path.resolve(artifactRoot,
44
+ '.' + (url.pathname === '/' ? '/index.html' : decodeURIComponent(url.pathname)));
45
+ assert(local.startsWith(artifactRoot + path.sep), 'Artifact requests cannot escape the output directory');
46
+ try {
47
+ await route.fulfill({contentType:mime[path.extname(local)] || 'application/octet-stream',
48
+ headers:{'content-security-policy':csp,'cache-control':'no-store'}, body:await readFile(local)});
49
+ } catch {
50
+ missingAssets.push(url.pathname);
51
+ await route.fulfill({status:404,body:'Missing synthetic artifact resource'});
52
+ }
53
+ });
54
+ const page = await context.newPage();
55
+ page.on('pageerror', error => errors.push(error.message));
56
+ page.on('console', message => {
57
+ if (message.type() === 'error') errors.push(message.text());
58
+ });
59
+ await page.goto(origin, {waitUntil:'networkidle',timeout:60000});
60
+ await page.waitForFunction(() => !document.getElementById('startup-status'), null, {timeout:60000});
61
+ await page.waitForLoadState('networkidle');
62
+ assert((await page.title()).includes('LifeGuide'), 'Built page must use the LifeGuide identity');
63
+ assert.equal(await page.locator('flt-glass-pane').count(),1,'Flutter engine must start');
64
+ if (screenshotPath) {
65
+ const enable = page.locator('flt-semantics-placeholder');
66
+ if (await enable.count()) await enable.evaluate(element => element.click());
67
+ await page.screenshot({path:screenshotPath,fullPage:true});
68
+ }
69
+ assert(requested.some(url => url.includes('/canvaskit/') && url.endsWith('.wasm')),
70
+ 'CanvasKit WASM must load locally');
71
+ for (const font of ['LifeGuidePersian.ttf','LifeGuideLatin.ttf','LifeGuideEmoji.ttf']) {
72
+ assert(requested.some(url => url.endsWith(font)), `${font} must load locally`);
73
+ }
74
+ assert(!requested.some(url => /(?:gstatic\.com|googleapis\.com)/i.test(url)),
75
+ 'Runtime requests cannot use Google font or CanvasKit hosts');
76
+ assert.equal(missingAssets.length,0,JSON.stringify(missingAssets));
77
+ assert.equal(errors.length,0,JSON.stringify(errors));
78
+ console.log(JSON.stringify({mode:'Synthetic HTTPS origin; intercepted compiled artifact responses; real TLS and service worker acceptance unverified',
79
+ requests:requested.length, fontRequests:requested.filter(url => /\.(?:ttf|otf|woff2)$/.test(url)).map(url => new URL(url).pathname),
80
+ canvasKitRequests:requested.filter(url => url.includes('/canvaskit/')).map(url => new URL(url).pathname),
81
+ externalRequests:requested.filter(url => new URL(url).origin !== origin),missingAssets,errors},null,2));
82
+ } finally {
83
+ await browser.close();
84
+ }
85
+})().catch(error => {console.error(error.message);process.exitCode=1;});
apps/lifemate/web/config.json
new
+1
@@ -0,0 +1 @@
1
+{"apiBaseUrl":"/api","apiFallbackUrls":[]}
apps/lifemate/web/favicon.png
Binary files a/apps/lifemate/web/favicon.png and b/apps/lifemate/web/favicon.png differ
apps/lifemate/web/flutter_bootstrap.js
new
+40
@@ -0,0 +1,40 @@
1
+{{flutter_js}}
2
+{{flutter_build_config}}
3
+
4
+const localBase = new URL('.', document.baseURI);
5
+const engineConfig = {
6
+ canvasKitBaseUrl: new URL('canvaskit/', localBase).href,
7
+ fontFallbackBaseUrl: new URL('assets/fonts/fallback/', localBase).href,
8
+};
9
+const showFailure = () => {
10
+ const status = document.getElementById('startup-status');
11
+ if (status) status.textContent =
12
+ 'لایفگاید بارگذاری نشد. اتصال را بررسی کنید و صفحه را دوباره باز کنید.';
13
+};
14
+
15
+// Retire the legacy generated worker, which could serve stale runtime settings.
16
+async function prepareWorker() {
17
+ if (!('serviceWorker' in navigator)) return;
18
+ try {
19
+ const registrations = await navigator.serviceWorker.getRegistrations();
20
+ for (const registration of registrations) {
21
+ const script = (registration.active || registration.waiting || registration.installing)?.scriptURL;
22
+ if (script && new URL(script).pathname.endsWith('/flutter_service_worker.js')) {
23
+ await registration.unregister();
24
+ }
25
+ }
26
+ await navigator.serviceWorker.register(new URL('lifeguide-sw.js', localBase), {updateViaCache: 'none'});
27
+ } catch (_) { /* Network-only startup still works when worker setup fails. */ }
28
+}
29
+
30
+prepareWorker();
31
+_flutter.loader.load({
32
+ config: engineConfig,
33
+ onEntrypointLoaded: async (initializer) => {
34
+ try {
35
+ const runner = await initializer.initializeEngine(engineConfig);
36
+ await runner.runApp();
37
+ document.getElementById('startup-status')?.remove();
38
+ } catch (_) { showFailure(); }
39
+ },
40
+}).catch(showFailure);
apps/lifemate/web/icons/Icon-192.png
Binary files a/apps/lifemate/web/icons/Icon-192.png and b/apps/lifemate/web/icons/Icon-192.png differ
apps/lifemate/web/icons/Icon-512.png
Binary files a/apps/lifemate/web/icons/Icon-512.png and b/apps/lifemate/web/icons/Icon-512.png differ
apps/lifemate/web/icons/Icon-maskable-192.png
Binary files a/apps/lifemate/web/icons/Icon-maskable-192.png and b/apps/lifemate/web/icons/Icon-maskable-192.png differ
apps/lifemate/web/icons/Icon-maskable-512.png
Binary files a/apps/lifemate/web/icons/Icon-maskable-512.png and b/apps/lifemate/web/icons/Icon-maskable-512.png differ
apps/lifemate/web/icons/lifeguide-maskable.svg
new
+2
@@ -0,0 +1,2 @@
1
+<?xml version='1.0' encoding='utf-8'?>
2
+<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 108 108"><rect width="108" height="108" fill="#4D86E8" /><path fill="#4D86E8" d="M54,4A50,50 0,1 1,54 104A50,50 0,1 1,54 4" /><path fill="#FFFFFF" d="M30,69C38,48 46,38 59,34C69,31 78,35 82,43C75,42 68,44 62,49C55,55 52,63 51,74L42,67C39,75 36,81 31,85Z" /><path fill="#FFFFFF" d="M70,28A7,7 0,1 1,70 42A7,7 0,1 1,70 28" /></svg>
\ No newline at end of file
apps/lifemate/web/icons/lifeguide.svg
new
+2
@@ -0,0 +1,2 @@
1
+<?xml version='1.0' encoding='utf-8'?>
2
+<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 108 108"><path fill="#4D86E8" d="M54,4A50,50 0,1 1,54 104A50,50 0,1 1,54 4" /><path fill="#FFFFFF" d="M30,69C38,48 46,38 59,34C69,31 78,35 82,43C75,42 68,44 62,49C55,55 52,63 51,74L42,67C39,75 36,81 31,85Z" /><path fill="#FFFFFF" d="M70,28A7,7 0,1 1,70 42A7,7 0,1 1,70 28" /></svg>
\ No newline at end of file
apps/lifemate/web/index.html
+5
-4
@@ -5,19 +5,20 @@
5
<meta charset="UTF-8">
6
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
7
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
8
- <meta name="description" content="LifeMate — همراه شخصی، تحصیلی و خانوادگی">
8
+ <meta name="description" content="LifeGuide / لایفگاید — همراه شخصی، تحصیلی و خانوادگی">
9
<meta name="theme-color" content="#ffffff">
10
<meta name="mobile-web-app-capable" content="yes">
11
<meta name="apple-mobile-web-app-capable" content="yes">
12
<meta name="apple-mobile-web-app-status-bar-style" content="default">
13
- <meta name="apple-mobile-web-app-title" content="LifeMate">
13
+ <meta name="apple-mobile-web-app-title" content="LifeGuide / لایفگاید">
14
<link rel="apple-touch-icon" href="icons/Icon-192.png">
15
<link rel="icon" type="image/png" href="favicon.png">
16
- <title>LifeMate</title>
16
+ <title>LifeGuide / لایفگاید</title>
17
<link rel="manifest" href="manifest.json">
18
</head>
19
<body>
20
- <noscript>برای استفاده از LifeMate جاوااسکریپت را فعال کنید.</noscript>
20
+ <noscript>برای استفاده از LifeGuide / لایفگاید جاوااسکریپت را فعال کنید.</noscript>
21
+ <p id="startup-status" role="status" style="font-family: sans-serif; padding: 24px; text-align: center">در حال بارگذاری لایفگاید…</p>
22
<script src="flutter_bootstrap.js" async></script>
23
</body>
24
</html>
apps/lifemate/web/lifeguide-sw.js
new
+36
@@ -0,0 +1,36 @@
1
+// Fresh application code/settings always come from the network. Cache only
2
+// public static resources; no API, authentication, navigation or personal data.
3
+const CACHE = 'lifeguide-static-v0.5.0-3';
4
+const BASE_PATH = new URL('.', self.location.href).pathname;
5
+const STATIC_PATH = /^(?:assets|canvaskit|icons)\//;
6
+self.addEventListener('install', () => self.skipWaiting());
7
+self.addEventListener('activate', (event) => {
8
+ event.waitUntil((async () => {
9
+ for (const key of await caches.keys()) {
10
+ if ((key.startsWith('lifeguide-static-') && key !== CACHE) || key.startsWith('flutter-')) {
11
+ await caches.delete(key);
12
+ }
13
+ }
14
+ await self.clients.claim();
15
+ })());
16
+});
17
+self.addEventListener('fetch', (event) => {
18
+ const request = event.request;
19
+ const url = new URL(request.url);
20
+ if (request.method !== 'GET' || url.origin !== self.location.origin ||
21
+ url.search || request.headers.has('authorization') ||
22
+ !url.pathname.startsWith(BASE_PATH) ||
23
+ !STATIC_PATH.test(url.pathname.slice(BASE_PATH.length))) return;
24
+ event.respondWith((async () => {
25
+ const cache = await caches.open(CACHE);
26
+ try {
27
+ const response = await fetch(request, {cache: 'no-store'});
28
+ if (response.ok) await cache.put(request, response.clone());
29
+ return response;
30
+ } catch (error) {
31
+ const stored = await cache.match(request);
32
+ if (stored) return stored;
33
+ throw error;
34
+ }
35
+ })());
36
+});
apps/lifemate/web/manifest.json
+5
-5
@@ -1,13 +1,13 @@
1
{
2
- "name": "LifeMate",
3
- "short_name": "LifeMate",
4
- "start_url": "/",
5
- "scope": "/",
2
+ "name": "LifeGuide | لایفگاید",
3
+ "short_name": "لایفگاید",
4
+ "start_url": "./",
5
+ "scope": "./",
6
"display": "standalone",
7
"background_color": "#F8FAFD",
8
"theme_color": "#4D86E8",
9
"description": "همراه شخصی، تحصیلی و خانوادگی",
10
- "orientation": "portrait-primary",
10
+ "orientation": "any",
11
"dir": "rtl",
12
"lang": "fa",
13
"prefer_related_applications": false,