Cherry pick/v0.40.x fixes to master (#5082)

This commit is contained in:
Dat H. Pham authored and GitHub committed 2026-11-02 16:24:00 +07:00
1 parent 67fa909722
commit e0df685a14
31 files changed
+1384 -126

No files matched your search

+1
View File
@@ -233,6 +233,7 @@ No we do not plan to support such extensions, that are currently not standardize
- [Enable and customize the Application grid](docs/configuration/app_grid_configuration.md)
- [Change logos](docs/configuration/tmail-web-logo.md)
- [Restrict the available languages](docs/configuration/language_configuration.md)
</details>
@@ -1,6 +1,7 @@
# 103. Urgent-exception handling for Riverpod flows
Date: 2026-07-07
Updated: 2026-10-30
## Status
@@ -23,6 +24,8 @@ Add one shared primitive, `handleUrgentExceptionIfNeeded({Failure? failure, Obje
**Rule:** any Riverpod flow consuming an interactor result MUST call this on failure. The caller skips its own failure UI when it returns `true`. The `empty_folder` delegate is refactored onto it, removing the duplicated inline logic.
**Exception — optional discovery:** An optional well-known / config fetch (for example `.well-known/linagora-ecosystem` via `InteractorConsumer`) may pass `shouldRouteUrgentException` so connectivity failures (`ConnectionError`, `NoNetworkError`) soft-degrade without a connection-error toast, while auth urgent exceptions (`BadCredentialsException`, `RefreshTokenFailedException`) still route. Do not use this opt-out for session-critical interactors.
### Handler is a lifetime service, not a screen controller
The `UrgentExceptionHandler` slot was bound to `MailboxDashBoardController` (`Get.put<UrgentExceptionHandler>(Get.find<MailboxDashBoardController>())`). That controller is absent on a web reload onto a non-dashboard route (e.g. Settings, where `MailboxDashBoardBindings` does not run — cf. ADR-0085), so `getBinding` would return `null` and urgent exceptions on those screens would be silently dropped.
@@ -0,0 +1,32 @@
## Configuration Allowed Languages
### Context
- By default, users can pick any language Twake Mail ships with
(fr, en, vi, ru, ar, it, de, mn, pt).
- An operator can limit the languages offered by the web app to a chosen set. This is optional.
### How to config
In [env.file]:
- To offer only Mongolian and English:
```ALLOWED_LANGUAGES=mn,en```
- To offer every language:
```ALLOWED_LANGUAGES=```
or remove the key.
Rules:
- Comma-separated language codes. Spaces, case and quotes are ignored
(`ALLOWED_LANGUAGES="MN, en"` works).
- A region is ignored: `pt`, `pt-BR` and `pt_BR` all mean Brazilian Portuguese.
- Unknown codes are ignored. If no code is known, every language is offered.
- The language picker lists the languages in the configured order.
- When the language from the server settings, the saved choice or the
device/browser is not allowed, the app uses English if it is allowed,
otherwise the first configured language. This also applies to the login screen.
- The server language setting is never overwritten because of this option.
- Set the key in `env.file` only, not in `configurations/env.fcm`.
### Platforms
- Web only. `env.file` is served with the app, so the option can be changed per
deployment without a rebuild. It also applies to the web app opened in a phone
or tablet browser.
- The Android and iOS apps ignore this key and always offer every language.
+2 -1
View File
@@ -13,4 +13,5 @@ COZY_EXTERNAL_BRIDGE_VERSION=
SENTRY_ENABLED=false
SENTRY_DSN=
SENTRY_ENVIRONMENT=
FORCE_EMAIL_QUERY=false
FORCE_EMAIL_QUERY=false
ALLOWED_LANGUAGES=
+8 -2
View File
@@ -1,6 +1,7 @@
import 'package:core/utils/config/env_loader.dart';
import 'package:core/utils/platform_info.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:patrol/patrol.dart';
import 'package:tmail_ui_user/main/main_entry.dart';
@@ -22,6 +23,7 @@ class TestBase {
required String description,
required BaseScenario Function(PatrolIntegrationTester $, RobotFactory robots) scenarioBuilder,
List<TestTags> tags = const [TestTags.ios],
Map<String, String> envOverrides = const {},
}) {
patrolSetUp(_setup);
@@ -43,7 +45,7 @@ class TestBase {
framePolicy: LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive,
($) async {
try {
await setupTest();
await setupTest(envOverrides: envOverrides);
await scenarioBuilder($, createRobotFactory($)).execute();
} catch (_) {
dumpFailureState($);
@@ -53,8 +55,12 @@ class TestBase {
);
}
Future<void> setupTest() async {
Future<void> setupTest({
Map<String, String> envOverrides = const {},
}) async {
await EnvLoader.loadEnvFile();
// loadEnvFile clears dotenv first, so overrides never leak between tests
dotenv.env.addAll(envOverrides);
await runTmail();
final originalOnError = FlutterError.onError!;
@@ -0,0 +1,7 @@
import 'package:flutter/widgets.dart';
abstract class AbstractLanguageAssertionRobot {
Future<void> expectLanguagesListed(List<Locale> locales);
Future<void> expectLanguagesNotListed(List<Locale> locales);
Future<void> expectLanguageSelected(Locale locale);
}
@@ -0,0 +1,7 @@
import 'abstract_language_assertion_robot.dart';
abstract class AbstractLanguageRobot {
AbstractLanguageAssertionRobot get assertion;
Future<void> openLanguagePicker();
}
@@ -1,11 +1,13 @@
import 'package:tmail_ui_user/features/manage_account/presentation/model/account_menu_item.dart';
import 'abstract_language_robot.dart';
import 'abstract_preferences_robot.dart';
abstract class AbstractSettingsRobot {
final AbstractPreferencesRobot preferencesRobot;
final AbstractLanguageRobot languageRobot;
const AbstractSettingsRobot(this.preferencesRobot);
const AbstractSettingsRobot(this.preferencesRobot, this.languageRobot);
Future<void> openSettingsDetail(AccountMenuItem accountMenuItem);
}
+2 -1
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/features/base/model/ui_keys.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/language_and_region/extensions/locale_extension.dart';
import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
@@ -9,7 +10,7 @@ class LanguageRobot extends CoreRobot {
LanguageRobot(super.$);
Future<void> openLanguageContextMenu() async {
await $(#language_drop_down_button).tap();
await $(const ValueKey(UiKeys.languageDropDownButton)).tap();
}
Future<void> selectLanguage(
@@ -0,0 +1,46 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/features/base/model/ui_keys.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/language_and_region/extensions/locale_extension.dart';
import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
import '../../base/core_robot.dart';
import '../abstract/abstract_language_assertion_robot.dart';
class MobileLanguageAssertionRobot extends CoreRobot
implements AbstractLanguageAssertionRobot {
MobileLanguageAssertionRobot(super.$);
@override
Future<void> expectLanguagesListed(List<Locale> locales) async {
for (final locale in locales) {
// exists, not visible: the mobile bottom sheet scrolls on small screens
expect(
$(_languageItemText(locale)).exists,
isTrue,
reason: '${locale.toLanguageTag()} should be listed',
);
}
}
@override
Future<void> expectLanguagesNotListed(List<Locale> locales) async {
for (final locale in locales) {
expect(find.text(_languageItemText(locale)), findsNothing);
}
}
@override
Future<void> expectLanguageSelected(Locale locale) async {
final languageName = locale.getLanguageNameByCurrentLocale(AppLocalizations());
await $(const ValueKey(UiKeys.languageDropDownButton))
.$(languageName)
.waitUntilVisible();
}
String _languageItemText(Locale locale) {
final appLocalizations = AppLocalizations();
return '${locale.getLanguageNameByCurrentLocale(appLocalizations)} - '
'${locale.getSourceLanguageName()}';
}
}
@@ -0,0 +1,19 @@
import '../abstract/abstract_language_assertion_robot.dart';
import '../abstract/abstract_language_robot.dart';
import '../language_robot.dart';
import 'mobile_language_assertion_robot.dart';
class MobileLanguageRobot extends LanguageRobot
implements AbstractLanguageRobot {
MobileLanguageRobot(super.$);
@override
AbstractLanguageAssertionRobot get assertion =>
MobileLanguageAssertionRobot($);
@override
Future<void> openLanguagePicker() async {
await openLanguageContextMenu();
await $.pumpAndSettle();
}
}
@@ -2,9 +2,11 @@ import 'package:tmail_ui_user/features/manage_account/presentation/menu/widgets/
import 'package:tmail_ui_user/features/manage_account/presentation/model/account_menu_item.dart';
import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
import '../abstract/abstract_language_robot.dart';
import '../abstract/abstract_preferences_robot.dart';
import '../abstract/abstract_settings_robot.dart';
import '../setting_robot.dart';
import 'mobile_language_robot.dart';
import 'mobile_preferences_robot.dart';
class MobileSettingsRobot extends SettingRobot
@@ -14,13 +16,18 @@ class MobileSettingsRobot extends SettingRobot
@override
AbstractPreferencesRobot get preferencesRobot => MobilePreferencesRobot($);
@override
AbstractLanguageRobot get languageRobot => MobileLanguageRobot($);
@override
Future<void> openSettingsDetail(AccountMenuItem accountMenuItem) async {
await $(SettingFirstLevelTileBuilder)
final settingTile = $(SettingFirstLevelTileBuilder)
.which<SettingFirstLevelTileBuilder>(
(widget) =>
widget.title == accountMenuItem.getName(AppLocalizations()),
)
.tap();
);
// Lower tiles (e.g. Language & region) are off screen on phones
await settingTile.scrollTo();
await settingTile.tap();
}
}
@@ -0,0 +1,27 @@
import 'package:flutter/widgets.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/model/account_menu_item.dart';
import '../../../base/base_test_scenario.dart';
class AllowedLanguagesFallbackScenario extends BaseTestScenario {
const AllowedLanguagesFallbackScenario(
super.$,
super.robots, {
required this.expectedLanguage,
});
final Locale expectedLanguage;
@override
Future<void> runTestLogic() async {
final mailboxMenuRobot = robots.mailboxMenuRobot();
final settingsRobot = robots.settingsRobot();
await mailboxMenuRobot.openSetting();
await settingsRobot.openSettingsDetail(AccountMenuItem.languageAndRegion);
await settingsRobot.languageRobot.assertion.expectLanguageSelected(
expectedLanguage,
);
}
}
@@ -0,0 +1,30 @@
import 'package:flutter/widgets.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/model/account_menu_item.dart';
import '../../../base/base_test_scenario.dart';
class AllowedLanguagesScenario extends BaseTestScenario {
const AllowedLanguagesScenario(
super.$,
super.robots, {
required this.listedLanguages,
this.hiddenLanguages = const [],
});
final List<Locale> listedLanguages;
final List<Locale> hiddenLanguages;
@override
Future<void> runTestLogic() async {
final mailboxMenuRobot = robots.mailboxMenuRobot();
final settingsRobot = robots.settingsRobot();
final languageRobot = settingsRobot.languageRobot;
await mailboxMenuRobot.openSetting();
await settingsRobot.openSettingsDetail(AccountMenuItem.languageAndRegion);
await languageRobot.openLanguagePicker();
await languageRobot.assertion.expectLanguagesListed(listedLanguages);
await languageRobot.assertion.expectLanguagesNotListed(hiddenLanguages);
}
}
@@ -0,0 +1,18 @@
import 'package:flutter/widgets.dart';
import '../../../base/test_base.dart';
import '../../../models/test_tags.dart';
import '../../../scenarios/setting/language/allowed_languages_fallback_scenario.dart';
void main() {
TestBase().runPatrolTest(
description: 'Should start in the first allowed language when English is not allowed on web',
scenarioBuilder: ($, robots) => AllowedLanguagesFallbackScenario(
$,
robots,
expectedLanguage: const Locale('mn', 'MN'),
),
tags: [TestTags.web],
envOverrides: const {'ALLOWED_LANGUAGES': 'mn,fr'},
);
}
@@ -0,0 +1,18 @@
import 'package:tmail_ui_user/main/localizations/localization_service.dart';
import '../../../base/test_base.dart';
import '../../../models/test_tags.dart';
import '../../../scenarios/setting/language/allowed_languages_scenario.dart';
void main() {
TestBase().runPatrolTest(
description: 'Should list every language when ALLOWED_LANGUAGES is set on mobile',
scenarioBuilder: ($, robots) => AllowedLanguagesScenario(
$,
robots,
listedLanguages: LocalizationService.supportedLocales,
),
tags: [TestTags.android, TestTags.ios],
envOverrides: const {'ALLOWED_LANGUAGES': 'mn,en'},
);
}
@@ -0,0 +1,23 @@
import 'package:flutter/widgets.dart';
import '../../../base/test_base.dart';
import '../../../models/test_tags.dart';
import '../../../scenarios/setting/language/allowed_languages_scenario.dart';
void main() {
TestBase().runPatrolTest(
description: 'Should list only the allowed languages when ALLOWED_LANGUAGES is set on web',
scenarioBuilder: ($, robots) => AllowedLanguagesScenario(
$,
robots,
listedLanguages: const [Locale('mn', 'MN'), Locale('en', 'US')],
hiddenLanguages: const [
Locale('vi', 'VN'),
Locale('fr', 'FR'),
Locale('de', 'DE'),
],
),
tags: [TestTags.web],
envOverrides: const {'ALLOWED_LANGUAGES': 'mn,en'},
);
}
+58 -22
View File
@@ -13,60 +13,96 @@ typedef StaleGuard = bool Function();
/// Applies a terminal success.
typedef InteractorSuccessHandler = void Function(Success success);
/// Applies an already-logged, already-routed failure (UI / state only).
/// Applies an already-logged failure (UI / state only). Urgent routing may or
/// may not have run depending on [ShouldRouteUrgentException].
typedef InteractorFailureHandler = void Function(
Object error,
StackTrace stackTrace,
);
/// Whether the resolved exception should be offered to ADR-0103 urgent routing.
///
/// [InteractorConsumer] unwraps a `Left` [FeatureFailure] to
/// [FeatureFailure.exception] (or keeps a bare thrown object) before calling
/// this, matching [handleUrgentExceptionIfNeeded]. Returning `false` skips
/// urgent routing (soft-fail); `true` keeps the default route. See ADR-0103
/// optional-discovery exception.
typedef ShouldRouteUrgentException = bool Function(Object error);
/// Bundles [InteractorConsumer.consumeInteractor] inputs into one request
/// object to keep the seam signature small and stable as options grow.
class InteractorConsumeRequest {
final InteractorCall run;
final StaleGuard isStale;
final InteractorSuccessHandler onSuccess;
final InteractorFailureHandler onFailure;
final ShouldRouteUrgentException? shouldRouteUrgentException;
const InteractorConsumeRequest({
required this.run,
required this.isStale,
required this.onSuccess,
required this.onFailure,
this.shouldRouteUrgentException,
});
}
/// Riverpod analogue of `BaseController.consumeState`: the one interactor-consume
/// seam. Logs and routes urgent exceptions (ADR-0103) so consumers can't forget.
mixin InteractorConsumer {
/// Awaits [run], drops the result when [isStale], dispatches the outcome.
/// Failures are logged + routed before [onFailure], which only touches UI/state.
Future<bool> consumeInteractor(
InteractorCall run, {
required StaleGuard isStale,
required InteractorSuccessHandler onSuccess,
required InteractorFailureHandler onFailure,
}) async {
/// Awaits [InteractorConsumeRequest.run], drops the result when stale,
/// dispatches the outcome. Failures are logged + optionally routed before
/// [InteractorConsumeRequest.onFailure], which only touches UI/state.
///
/// [InteractorConsumeRequest.shouldRouteUrgentException] defaults to routing
/// every failure (ADR-0103). Pass a predicate to soft-fail selected classes
/// (e.g. connectivity on an optional discovery call) without suppressing
/// auth re-login.
Future<bool> consumeInteractor(InteractorConsumeRequest request) async {
// Scope the try to run() only: a bug thrown by onSuccess/onFailure must
// surface, not be misclassified (and maybe urgent-routed) as a failure.
final Either<Failure, Success> result;
try {
result = await run();
result = await request.run();
} catch (error, stackTrace) {
if (isStale()) return false;
_fail(error, stackTrace, onFailure);
if (request.isStale()) return false;
_fail(error, stackTrace, request);
return false;
}
if (isStale()) return false;
if (request.isStale()) return false;
var succeeded = true;
result.fold(
(failure) {
succeeded = false;
_fail(failure, StackTrace.current, onFailure);
_fail(failure, StackTrace.current, request);
},
onSuccess,
request.onSuccess,
);
return succeeded;
}
/// Logs the failure (no filter/email content), routes urgent ones through the
/// shared primitive, then delegates to [onFailure].
/// Logs the failure (no filter/email content), optionally routes urgent ones
/// through the shared primitive, then delegates to [onFailure].
void _fail(
Object error,
StackTrace stackTrace,
InteractorFailureHandler onFailure,
InteractorConsumeRequest request,
) {
logError(
'InteractorConsumer::consumeInteractor: interactor failed',
exception: error,
stackTrace: stackTrace,
);
error is Failure
? handleUrgentExceptionIfNeeded(failure: error)
: handleUrgentExceptionIfNeeded(exception: error);
onFailure(error, stackTrace);
final shouldRoute = request.shouldRouteUrgentException;
// Normalize before the predicate so type-only filters (is! ConnectionError)
// soft-fail Left(FeatureFailure(ConnectionError)) the same as a bare throw.
final routeError =
error is FeatureFailure ? (error.exception ?? error) : error;
if (shouldRoute == null || shouldRoute(routeError)) {
error is Failure
? handleUrgentExceptionIfNeeded(failure: error)
: handleUrgentExceptionIfNeeded(exception: error);
}
request.onFailure(error, stackTrace);
}
}
+3
View File
@@ -28,6 +28,9 @@ class UiKeys {
static const String recipientCcButtonSuffix = '_recipient_cc_button';
static const String recipientExpandButtonSuffix = '_recipient_expand_button';
// Language & region
static const String languageDropDownButton = 'language_drop_down_button';
// Email rules / rules filter creator
static const String createRuleButton = 'createRuleButton';
static const String emailRulesSettingMenuItem = 'setting_email_rules';
@@ -10,6 +10,7 @@ import 'package:tmail_ui_user/features/mailbox_dashboard/domain/linagora_ecosyst
import 'package:tmail_ui_user/features/mailbox_dashboard/domain/state/get_linagora_ecosystem_state.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/domain/usecases/get_linagora_system_interactor.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/providers/linagora_ecosystem_providers.dart';
import 'package:tmail_ui_user/main/exceptions/remote/network_exception.dart';
enum EcosystemUnavailableReason {
missingAccount,
@@ -101,9 +102,13 @@ EcosystemState resolveActiveEcosystem(
);
}
/// Consumes the ecosystem interactor through the shared seam so the failure is
/// logged once and urgent exceptions still reach the re-login / reconnect flow
/// (ADR-0103), exactly like `BaseController.consumeState` does for GetX.
/// Loads the optional `.well-known/linagora-ecosystem` document.
///
/// Connectivity failures (missing/CORS-blocked file → [ConnectionError] /
/// [NoNetworkError]) soft-degrade to [EcosystemUnavailable] without a
/// "Connection error" toast. Auth urgent exceptions from the shared Dio still
/// route re-login (ADR-0103). Stronger than the old GetX path, which toasted
/// [ConnectionError] before `handleGetLinagoraEcosystemFailure` could run.
class _EcosystemLoader with InteractorConsumer {
final Ref _ref;
@@ -118,17 +123,21 @@ class _EcosystemLoader with InteractorConsumer {
StackTrace? failureStackTrace;
await consumeInteractor(
() => interactor.execute(jmapUrl).firstWhere(_isTerminalEcosystemState),
isStale: () => !_ref.mounted,
onSuccess: (success) {
if (success is GetLinagoraEcosystemSuccess) {
loadedEcosystem = success.linagoraEcosystem;
}
},
onFailure: (error, stackTrace) {
failure = error;
failureStackTrace = stackTrace;
},
InteractorConsumeRequest(
run: () =>
interactor.execute(jmapUrl).firstWhere(_isTerminalEcosystemState),
isStale: () => !_ref.mounted,
shouldRouteUrgentException: shouldRouteEcosystemUrgentException,
onSuccess: (success) {
if (success is GetLinagoraEcosystemSuccess) {
loadedEcosystem = success.linagoraEcosystem;
}
},
onFailure: (error, stackTrace) {
failure = error;
failureStackTrace = stackTrace;
},
),
);
final error = failure;
@@ -147,3 +156,12 @@ bool _isTerminalEcosystemState(Either<Failure, Success> state) => state.fold(
(_) => true,
(success) => success is! GettingLinagoraEcosystem,
);
/// Soft-fails optional-discovery connectivity; keeps auth urgent routing.
///
/// [InteractorConsumer] already unwraps [FeatureFailure] before calling this;
/// the unwrap here keeps the helper correct if invoked directly (tests).
bool shouldRouteEcosystemUrgentException(Object error) {
final exception = error is FeatureFailure ? error.exception : error;
return exception is! ConnectionError && exception is! NoNetworkError;
}
@@ -46,19 +46,22 @@ class LanguageAndRegionController extends BaseController {
}
void _setUpSupportedLanguages() {
listSupportedLanguages.value = LocalizationService.supportedLocales;
listSupportedLanguages.value = LocalizationService.availableLocales;
final currentLocale = Get.locale;
log('LanguageAndRegionController::_setUpSupportedLanguages():currentLocale: $currentLocale');
if (currentLocale != null) {
languageSelected.value = currentLocale;
// Check the listed entry of the current language (fr_CA → fr_FR)
languageSelected.value = listSupportedLanguages.firstWhereOrNull(
(locale) => locale.languageCode == currentLocale.languageCode,
) ?? currentLocale;
} else {
languageSelected.value = LocalizationService.defaultLocale;
languageSelected.value = LocalizationService.availableDefaultLocale;
}
}
void selectLanguage(Locale? selectedLocale) {
languageSelected.value = selectedLocale ?? LocalizationService.defaultLocale;
languageSelected.value = selectedLocale ?? LocalizationService.availableDefaultLocale;
_saveLanguage(languageSelected.value);
}
@@ -6,6 +6,7 @@ import 'package:core/presentation/utils/theme_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_portal/flutter_portal.dart';
import 'package:get/get.dart';
import 'package:tmail_ui_user/features/base/model/ui_keys.dart';
import 'package:tmail_ui_user/features/base/widget/tmail_drop_down_widget.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/language_and_region/extensions/locale_extension.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/language_and_region/language_and_region_controller.dart';
@@ -114,6 +115,7 @@ class _ChangeLanguageButtonWidgetState extends State<ChangeLanguageButtonWidget>
),
visible: isVisible,
child: Obx(() => TMailDropDownWidget(
key: const Key(UiKeys.languageDropDownButton),
text: _languageAndRegionController
.languageSelected
.value
@@ -132,7 +134,7 @@ class _ChangeLanguageButtonWidgetState extends State<ChangeLanguageButtonWidget>
Widget _buildMobileLanguageMenu(BuildContext context) {
return Obx(() => TMailDropDownWidget(
key: const Key('language_drop_down_button'),
key: const Key(UiKeys.languageDropDownButton),
text: _languageAndRegionController
.languageSelected
.value
@@ -194,13 +194,15 @@ class SearchEmailNotifier extends _$SearchEmailNotifier with InteractorConsumer
required InteractorFailureHandler onFailure,
}) async {
final succeeded = await consumeInteractor(
runInteractor,
isStale: () => !ref.mounted || requestId != _latestRequestId,
onSuccess: (success) {
final page = _emailsOf(success);
if (page != null) onPageLoaded(page); // else intermediate — keep current
},
onFailure: onFailure,
InteractorConsumeRequest(
run: runInteractor,
isStale: () => !ref.mounted || requestId != _latestRequestId,
onSuccess: (success) {
final page = _emailsOf(success);
if (page != null) onPageLoaded(page); // else intermediate — keep current
},
onFailure: onFailure,
),
);
if (succeeded) return SearchExecutionResult.success;
// Re-check staleness after the await: a newer execute() during the
@@ -4,6 +4,7 @@ import 'package:get/get.dart';
import 'package:tmail_ui_user/features/manage_account/data/local/language_cache_manager.dart';
import 'package:tmail_ui_user/main/localizations/language_code_constants.dart';
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
import 'package:tmail_ui_user/main/utils/app_config.dart';
typedef OnServerLanguageApplied = Function(Locale locale);
@@ -40,6 +41,24 @@ class LocalizationService extends Translations {
Locale(LanguageCodeConstants.portuguese, 'BR')
];
/// Locales the user may pick or get: `ALLOWED_LANGUAGES` in its order, or
/// every supported locale when the option is unset or matches nothing.
static List<Locale> get availableLocales {
final allowedLocales = AppConfig.allowedLanguageCodes
.map(_findSupportedLocale)
.nonNulls
.toSet()
.toList();
return allowedLocales.isEmpty ? supportedLocales : allowedLocales;
}
static Locale get availableDefaultLocale {
final locales = availableLocales;
return _containsLanguage(locales, defaultLocale.languageCode)
? defaultLocale
: locales.first;
}
static void changeLocale(Locale newLocale) {
final normalizedLocale = _normalizeLocale(newLocale);
log('LocalizationService::changeLocale(): New locale is $normalizedLocale');
@@ -60,17 +79,19 @@ class LocalizationService extends Translations {
static Locale getInitialLocale() {
try {
final cachedLocale = _getCachedLocale();
if (cachedLocale != null) return _normalizeLocale(cachedLocale);
if (cachedLocale != null && _isAvailableLocale(cachedLocale)) {
return _normalizeLocale(cachedLocale);
}
final deviceLocale = _getDeviceLocale();
if (_isSupportedLocale(deviceLocale)) {
if (_isAvailableLocale(deviceLocale)) {
return _normalizeLocale(deviceLocale);
}
return defaultLocale;
return availableDefaultLocale;
} catch (e) {
logWarning('LocalizationService::getInitialLocale:Exception is $e');
return defaultLocale;
return availableDefaultLocale;
}
}
@@ -97,7 +118,7 @@ class LocalizationService extends Translations {
String? serverLanguage,
OnServerLanguageApplied? onServerLanguageApplied,
}) {
log('LocalizationService::initializeAppLanguage:Server language: $serverLanguage');
log('LocalizationService::initializeAppLanguage:Server language: $serverLanguage, allowed languages: ${AppConfig.allowedLanguageCodes}');
try {
// From server
if (serverLanguage != null &&
@@ -121,15 +142,15 @@ class LocalizationService extends Translations {
static void _useDefaultLocale() {
final currentLocale = Get.locale;
if (currentLocale == null || !_isSupportedLocale(currentLocale)) {
changeLocale(defaultLocale);
if (currentLocale == null || !_isAvailableLocale(currentLocale)) {
changeLocale(availableDefaultLocale);
}
}
static bool _useDeviceLocale() {
final deviceLocale = _getDeviceLocale();
log('LocalizationService::_useDeviceLocale: Device locale is $deviceLocale');
if (_isSupportedLocale(deviceLocale)) {
if (_isAvailableLocale(deviceLocale)) {
changeLocale(deviceLocale);
return true;
}
@@ -139,7 +160,7 @@ class LocalizationService extends Translations {
static bool _useCachedLocale() {
final cachedLocale = _getCachedLocale();
log('LocalizationService::_useCachedLocale: Cached locale is $cachedLocale');
if (cachedLocale != null && _isSupportedLocale(cachedLocale)) {
if (cachedLocale != null && _isAvailableLocale(cachedLocale)) {
changeLocale(cachedLocale);
return true;
}
@@ -152,7 +173,7 @@ class LocalizationService extends Translations {
}) {
final serverLocale = _findSupportedLocale(languageCode);
log('LocalizationService::_useServerLocale: Server locale is $serverLocale');
if (serverLocale != null && _isSupportedLocale(serverLocale)) {
if (serverLocale != null && _isAvailableLocale(serverLocale)) {
changeLocale(serverLocale);
onServerLanguageApplied?.call(serverLocale);
return true;
@@ -160,9 +181,12 @@ class LocalizationService extends Translations {
return false;
}
static bool _isSupportedLocale(Locale locale) {
return supportedLocales
.any((supported) => supported.languageCode == locale.languageCode);
static bool _isAvailableLocale(Locale locale) {
return _containsLanguage(availableLocales, locale.languageCode);
}
static bool _containsLanguage(List<Locale> locales, String languageCode) {
return locales.any((locale) => locale.languageCode == languageCode);
}
static Locale? _findSupportedLocale(String languageCode) {
+17
View File
@@ -1,5 +1,6 @@
import 'dart:io';
import 'package:core/utils/platform_info.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:tmail_ui_user/features/login/data/network/config/oidc_constant.dart';
@@ -80,6 +81,22 @@ class AppConfig {
static bool get isForceEmailQueryEnabled =>
dotenv.get('FORCE_EMAIL_QUERY', fallback: 'false') == 'true';
static final RegExp _languageRegionSeparator = RegExp('[-_]');
/// Language codes from `ALLOWED_LANGUAGES` (e.g. `mn,en`), lowercased and
/// without region (`pt-BR` → `pt`). Empty means every language is allowed.
/// Web only: the mobile apps always offer every language.
static List<String> get allowedLanguageCodes {
if (!PlatformInfo.isWeb || !dotenv.isInitialized) return [];
return dotenv
.get('ALLOWED_LANGUAGES', fallback: '')
.split(',')
.map((code) => code.trim().toLowerCase().split(_languageRegionSeparator).first)
.where((code) => code.isNotEmpty)
.toList();
}
/// Hosts an openApp deep link may point the app to.
static List<String> get deepLinkAllowedHosts => [
Uri.parse(saasRegistrationUrl).host,
+214 -24
View File
@@ -7,6 +7,7 @@ import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:tmail_ui_user/features/base/interactor_consumer.dart';
import 'package:tmail_ui_user/features/base/urgent_exception_handler.dart';
import 'package:tmail_ui_user/main/exceptions/remote/network_exception.dart';
import 'interactor_consumer_test.mocks.dart';
@@ -33,6 +34,21 @@ void main() {
exception: anyNamed('exception'),
));
InteractorConsumeRequest request({
required InteractorCall run,
required StaleGuard isStale,
required InteractorSuccessHandler onSuccess,
required InteractorFailureHandler onFailure,
ShouldRouteUrgentException? shouldRouteUrgentException,
}) =>
InteractorConsumeRequest(
run: run,
isStale: isStale,
onSuccess: onSuccess,
onFailure: onFailure,
shouldRouteUrgentException: shouldRouteUrgentException,
);
setUp(() {
handler = MockUrgentExceptionHandler();
Get.put<UrgentExceptionHandler>(handler);
@@ -47,10 +63,12 @@ void main() {
Success? received;
await consumer.consumeInteractor(
() async => Right(success),
isStale: () => false,
onSuccess: (s) => received = s,
onFailure: (_, __) => fail('should not fail'),
request(
run: () async => Right(success),
isStale: () => false,
onSuccess: (s) => received = s,
onFailure: (_, __) => fail('should not fail'),
),
);
expect(received, success);
@@ -64,10 +82,12 @@ void main() {
Object? failed;
await consumer.consumeInteractor(
() async => Left(failure),
isStale: () => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, _) => failed = error,
request(
run: () async => Left(failure),
isStale: () => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, _) => failed = error,
),
);
expect(failed, failure);
@@ -83,10 +103,12 @@ void main() {
Object? failed;
await consumer.consumeInteractor(
() async => throw exception,
isStale: () => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, _) => failed = error,
request(
run: () async => throw exception,
isStale: () => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, _) => failed = error,
),
);
expect(failed, exception);
@@ -101,10 +123,12 @@ void main() {
var dispatched = false;
await consumer.consumeInteractor(
() async => Left(_TestFailure(exception: _UrgentException())),
isStale: () => true,
onSuccess: (_) => dispatched = true,
onFailure: (_, __) => dispatched = true,
request(
run: () async => Left(_TestFailure(exception: _UrgentException())),
isStale: () => true,
onSuccess: (_) => dispatched = true,
onFailure: (_, __) => dispatched = true,
),
);
expect(dispatched, isFalse);
@@ -117,10 +141,12 @@ void main() {
var failedCalled = false;
await consumer.consumeInteractor(
() async => Left(_TestFailure(exception: exception)),
isStale: () => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (_, __) => failedCalled = true,
request(
run: () async => Left(_TestFailure(exception: exception)),
isStale: () => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (_, __) => failedCalled = true,
),
);
expect(failedCalled, isTrue);
@@ -134,14 +160,178 @@ void main() {
await expectLater(
consumer.consumeInteractor(
() async => Right(_TestSuccess()),
isStale: () => false,
onSuccess: (_) => throw bug,
onFailure: (_, __) => fail('onSuccess bug must not become a failure'),
request(
run: () async => Right(_TestSuccess()),
isStale: () => false,
onSuccess: (_) => throw bug,
onFailure: (_, __) =>
fail('onSuccess bug must not become a failure'),
),
),
throwsA(same(bug)),
);
expectNeverRouted(); // must not urgent-route a rendering/state bug
});
test('shouldRouteUrgentException: false skips routing for a Left failure',
() async {
final exception = _UrgentException();
final failure = _TestFailure(exception: exception);
when(handler.validateUrgentException(exception)).thenReturn(true);
Object? failed;
await consumer.consumeInteractor(
request(
run: () async => Left(failure),
isStale: () => false,
shouldRouteUrgentException: (_) => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, _) => failed = error,
),
);
expect(failed, failure);
expectNeverRouted();
});
test(
'shouldRouteUrgentException: false skips routing for a thrown error',
() async {
final exception = _UrgentException();
when(handler.validateUrgentException(exception)).thenReturn(true);
Object? failed;
await consumer.consumeInteractor(
request(
run: () async => throw exception,
isStale: () => false,
shouldRouteUrgentException: (_) => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, _) => failed = error,
),
);
expect(failed, same(exception));
expectNeverRouted();
});
test('shouldRouteUrgentException: true still routes an urgent failure',
() async {
final exception = _UrgentException();
final failure = _TestFailure(exception: exception);
when(handler.validateUrgentException(exception)).thenReturn(true);
Object? failed;
await consumer.consumeInteractor(
request(
run: () async => Left(failure),
isStale: () => false,
shouldRouteUrgentException: (_) => true,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, _) => failed = error,
),
);
expect(failed, failure);
verify(handler.handleUrgentException(
failure: failure,
exception: exception,
)).called(1);
});
test('soft-fail filter still invokes onFailure and returns false', () async {
final exception = _UrgentException();
final failure = _TestFailure(exception: exception);
when(handler.validateUrgentException(exception)).thenReturn(true);
Object? failed;
StackTrace? failedStack;
final succeeded = await consumer.consumeInteractor(
request(
run: () async => Left(failure),
isStale: () => false,
shouldRouteUrgentException: (_) => false,
onSuccess: (_) => fail('should not succeed'),
onFailure: (error, stackTrace) {
failed = error;
failedStack = stackTrace;
},
),
);
expect(succeeded, isFalse);
expect(failed, failure);
expect(failedStack, isNotNull);
expectNeverRouted();
});
test('stale throw skips routing even when the filter would allow it',
() async {
final exception = _UrgentException();
when(handler.validateUrgentException(exception)).thenReturn(true);
var failedCalled = false;
final succeeded = await consumer.consumeInteractor(
request(
run: () async => throw exception,
isStale: () => true,
shouldRouteUrgentException: (_) => true,
onSuccess: (_) => fail('should not succeed'),
onFailure: (_, __) => failedCalled = true,
),
);
expect(succeeded, isFalse);
expect(failedCalled, isFalse);
expectNeverRouted();
});
test('null shouldRouteUrgentException keeps default ADR-0103 routing',
() async {
final exception = _UrgentException();
final failure = _TestFailure(exception: exception);
when(handler.validateUrgentException(exception)).thenReturn(true);
await consumer.consumeInteractor(
request(
run: () async => Left(failure),
isStale: () => false,
shouldRouteUrgentException: null,
onSuccess: (_) => fail('should not succeed'),
onFailure: (_, __) {},
),
);
verify(handler.handleUrgentException(
failure: failure,
exception: exception,
)).called(1);
});
test(
'unwraps FeatureFailure before shouldRouteUrgentException so type-only '
'filters soft-fail Left carriers', () async {
const exception = ConnectionError();
final failure = _TestFailure(exception: exception);
when(handler.validateUrgentException(exception)).thenReturn(true);
Object? seenByFilter;
await consumer.consumeInteractor(
request(
run: () async => Left(failure),
isStale: () => false,
// Intentionally no FeatureFailure unwrap — seam must normalize.
shouldRouteUrgentException: (error) {
seenByFilter = error;
return error is! ConnectionError && error is! NoNetworkError;
},
onSuccess: (_) => fail('should not succeed'),
onFailure: (_, __) {},
),
);
expect(seenByFilter, same(exception));
expectNeverRouted();
});
});
}
@@ -1,4 +1,6 @@
import 'package:core/utils/platform_info.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:mockito/annotations.dart';
@@ -25,6 +27,7 @@ void main() {
setUp(() {
Get.testMode = true;
dotenv.testLoad();
Get.locale = const Locale('fr', 'FR');
Get.put<LanguageCacheManager>(languageCacheManager);
});
@@ -33,6 +36,7 @@ void main() {
Get.reset();
Get.locale = null;
Get.testMode = false;
TestWidgetsFlutterBinding.instance.platformDispatcher.clearLocaleTestValue();
TestWidgetsFlutterBinding.instance.reset();
});
@@ -423,4 +427,230 @@ void main() {
expect(Get.locale, LocalizationService.defaultLocale);
});
});
}
group('initialize app language with ALLOWED_LANGUAGES test:', () {
void allowLanguages(String value) =>
dotenv.testLoad(mergeWith: {'ALLOWED_LANGUAGES': value});
setUp(() => PlatformInfo.isTestingForWeb = true);
tearDown(() => PlatformInfo.isTestingForWeb = false);
testWidgets(
'should apply a language that is not allowed '
'when the app does not run on web',
(tester) async {
// arrange
PlatformInfo.isTestingForWeb = false;
allowLanguages('mn,en');
Locale? appliedServerLocale;
// act
LocalizationService.initializeAppLanguage(
serverLanguage: LanguageCodeConstants.vietnamese,
onServerLanguageApplied: (locale) => appliedServerLocale = locale,
);
await tester.pumpAndSettle();
// assert
expect(appliedServerLocale, const Locale('vi', 'VN'));
expect(Get.locale, const Locale('vi', 'VN'));
});
testWidgets(
'should not apply nor persist server language '
'when server language is not allowed',
(tester) async {
// arrange
allowLanguages('mn,en');
when(languageCacheManager.getStoredLanguage()).thenReturn(null);
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('mn', 'MN');
Locale? appliedServerLocale;
// act
LocalizationService.initializeAppLanguage(
serverLanguage: LanguageCodeConstants.vietnamese,
onServerLanguageApplied: (locale) => appliedServerLocale = locale,
);
await tester.pumpAndSettle();
// assert
expect(appliedServerLocale, isNull);
expect(Get.locale, const Locale('mn', 'MN'));
});
testWidgets(
'should apply server language '
'when server language is allowed',
(tester) async {
// arrange
allowLanguages('mn,en');
Locale? appliedServerLocale;
// act
LocalizationService.initializeAppLanguage(
serverLanguage: LanguageCodeConstants.mongolian,
onServerLanguageApplied: (locale) => appliedServerLocale = locale,
);
await tester.pumpAndSettle();
// assert
expect(appliedServerLocale, const Locale('mn', 'MN'));
expect(Get.locale, const Locale('mn', 'MN'));
});
testWidgets(
'should apply English '
'when server, cached, device and current languages are not allowed '
'and English is allowed',
(tester) async {
// arrange
allowLanguages('mn,en');
when(languageCacheManager.getStoredLanguage())
.thenReturn(const Locale('vi', 'VN'));
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('fr', 'FR');
// act
LocalizationService.initializeAppLanguage(
serverLanguage: LanguageCodeConstants.russian,
);
await tester.pumpAndSettle();
// assert
expect(Get.locale, LocalizationService.defaultLocale);
});
testWidgets(
'should apply the first allowed language '
'when server, cached, device and current languages are not allowed '
'and English is not allowed',
(tester) async {
// arrange
allowLanguages('mn,vi');
when(languageCacheManager.getStoredLanguage())
.thenReturn(const Locale('de', 'DE'));
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('fr', 'FR');
// act
LocalizationService.initializeAppLanguage();
await tester.pumpAndSettle();
// assert
expect(Get.locale, const Locale('mn', 'MN'));
});
testWidgets(
'should keep the device region '
'when device language is allowed',
(tester) async {
// arrange
allowLanguages('fr,en');
when(languageCacheManager.getStoredLanguage()).thenReturn(null);
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('fr', 'CA');
// act
LocalizationService.initializeAppLanguage();
await tester.pumpAndSettle();
// assert
expect(Get.locale, const Locale('fr', 'CA'));
});
testWidgets(
'should keep the device region '
'when ALLOWED_LANGUAGES is not set',
(tester) async {
// arrange
when(languageCacheManager.getStoredLanguage()).thenReturn(null);
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('en', 'GB');
// act
LocalizationService.initializeAppLanguage();
await tester.pumpAndSettle();
// assert
expect(Get.locale, const Locale('en', 'GB'));
});
testWidgets(
'getInitialLocale should skip a cached language '
'that is not allowed',
(tester) async {
// arrange
allowLanguages('mn,en');
when(languageCacheManager.getStoredLanguage())
.thenReturn(const Locale('vi', 'VN'));
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('fr', 'FR');
// act
final initialLocale = LocalizationService.getInitialLocale();
// assert
expect(initialLocale, LocalizationService.defaultLocale);
});
testWidgets(
'getInitialLocale should return the first allowed language '
'when cached and device languages are not allowed '
'and English is not allowed',
(tester) async {
// arrange
allowLanguages('mn,fr');
when(languageCacheManager.getStoredLanguage())
.thenReturn(const Locale('vi', 'VN'));
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('en', 'US');
// act
final initialLocale = LocalizationService.getInitialLocale();
// assert
expect(initialLocale, const Locale('mn', 'MN'));
});
testWidgets(
'should keep the current language '
'when server, cached and device languages are not allowed '
'and the current language is allowed',
(tester) async {
// arrange
allowLanguages('mn,fr');
Get.locale = const Locale('fr', 'FR');
when(languageCacheManager.getStoredLanguage())
.thenReturn(const Locale('vi', 'VN'));
TestWidgetsFlutterBinding
.instance
.platformDispatcher
.localeTestValue = const Locale('de', 'DE');
// act
LocalizationService.initializeAppLanguage(
serverLanguage: LanguageCodeConstants.russian,
);
await tester.pumpAndSettle();
// assert
expect(Get.locale, const Locale('fr', 'FR'));
});
});
}
@@ -0,0 +1,160 @@
import 'package:core/data/network/config/dynamic_url_interceptors.dart';
import 'package:core/presentation/resources/image_paths.dart';
import 'package:core/presentation/utils/app_toast.dart';
import 'package:core/presentation/utils/responsive_utils.dart';
import 'package:core/utils/platform_info.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:mockito/mockito.dart';
import 'package:tmail_ui_user/features/caching/caching_manager.dart';
import 'package:tmail_ui_user/features/login/data/network/interceptors/authorization_interceptors.dart';
import 'package:tmail_ui_user/features/login/domain/usecases/delete_authority_oidc_interactor.dart';
import 'package:tmail_ui_user/features/login/domain/usecases/delete_credential_interactor.dart';
import 'package:tmail_ui_user/features/manage_account/data/local/language_cache_manager.dart';
import 'package:tmail_ui_user/features/manage_account/domain/usecases/log_out_oidc_interactor.dart';
import 'package:tmail_ui_user/features/manage_account/domain/usecases/save_language_interactor.dart';
import 'package:tmail_ui_user/features/manage_account/domain/usecases/save_language_to_server_settings_interactor.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/language_and_region/language_and_region_controller.dart';
import 'package:tmail_ui_user/features/manage_account/presentation/manage_account_dashboard_controller.dart';
import 'package:tmail_ui_user/main/bindings/network/binding_tag.dart';
import 'package:tmail_ui_user/main/localizations/localization_service.dart';
import 'package:tmail_ui_user/main/utils/toast_manager.dart';
import 'package:tmail_ui_user/main/utils/twake_app_manager.dart';
import 'package:uuid/uuid.dart';
class _MockCachingManager extends Mock implements CachingManager {}
class _MockLanguageCacheManager extends Mock implements LanguageCacheManager {}
class _MockAuthorizationInterceptors extends Mock implements AuthorizationInterceptors {}
class _MockDynamicUrlInterceptors extends Mock implements DynamicUrlInterceptors {}
class _MockDeleteCredentialInteractor extends Mock implements DeleteCredentialInteractor {}
class _MockLogoutOidcInteractor extends Mock implements LogoutOidcInteractor {}
class _MockDeleteAuthorityOidcInteractor extends Mock implements DeleteAuthorityOidcInteractor {}
class _MockAppToast extends Mock implements AppToast {}
class _MockImagePaths extends Mock implements ImagePaths {}
class _MockResponsiveUtils extends Mock implements ResponsiveUtils {}
class _MockUuid extends Mock implements Uuid {}
class _MockToastManager extends Mock implements ToastManager {}
class _MockTwakeAppManager extends Mock implements TwakeAppManager {}
class _MockSaveLanguageInteractor extends Mock implements SaveLanguageInteractor {}
class _MockSaveLanguageToServerSettingsInteractor extends Mock
implements SaveLanguageToServerSettingsInteractor {}
class _MockManageAccountDashBoardController extends Mock implements ManageAccountDashBoardController {
@override
final onStart = InternalFinalCallback<void>(callback: () {});
@override
final onDelete = InternalFinalCallback<void>(callback: () {});
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late LanguageAndRegionController controller;
setUp(() {
Get.testMode = true;
PlatformInfo.isTestingForWeb = true;
dotenv.testLoad();
Get.put<CachingManager>(_MockCachingManager());
Get.put<LanguageCacheManager>(_MockLanguageCacheManager());
Get.put<AuthorizationInterceptors>(_MockAuthorizationInterceptors());
Get.put<AuthorizationInterceptors>(
_MockAuthorizationInterceptors(),
tag: BindingTag.isolateTag,
);
Get.put<DynamicUrlInterceptors>(_MockDynamicUrlInterceptors());
Get.put<DeleteCredentialInteractor>(_MockDeleteCredentialInteractor());
Get.put<LogoutOidcInteractor>(_MockLogoutOidcInteractor());
Get.put<DeleteAuthorityOidcInteractor>(_MockDeleteAuthorityOidcInteractor());
Get.put<AppToast>(_MockAppToast());
Get.put<ImagePaths>(_MockImagePaths());
Get.put<ResponsiveUtils>(_MockResponsiveUtils());
Get.put<Uuid>(_MockUuid());
Get.put<ToastManager>(_MockToastManager());
Get.put<TwakeAppManager>(_MockTwakeAppManager());
Get.put<ManageAccountDashBoardController>(_MockManageAccountDashBoardController());
controller = LanguageAndRegionController(
_MockSaveLanguageInteractor(),
_MockSaveLanguageToServerSettingsInteractor(),
);
});
tearDown(() {
Get.reset();
Get.locale = null;
Get.testMode = false;
PlatformInfo.isTestingForWeb = false;
});
group('LanguageAndRegionController supported languages test:', () {
test('should list every supported language when ALLOWED_LANGUAGES is not set', () {
Get.locale = const Locale('fr', 'FR');
controller.onReady();
expect(
controller.listSupportedLanguages,
LocalizationService.supportedLocales,
);
expect(controller.languageSelected.value, const Locale('fr', 'FR'));
});
test('should list only the allowed languages in the configured order', () {
dotenv.testLoad(mergeWith: {'ALLOWED_LANGUAGES': 'mn,en'});
Get.locale = const Locale('mn', 'MN');
controller.onReady();
expect(
controller.listSupportedLanguages,
const [Locale('mn', 'MN'), Locale('en', 'US')],
);
expect(controller.languageSelected.value, const Locale('mn', 'MN'));
});
test('should select the listed entry of the current language', () {
dotenv.testLoad(mergeWith: {'ALLOWED_LANGUAGES': 'fr,en'});
Get.locale = const Locale('fr', 'CA');
controller.onReady();
expect(controller.languageSelected.value, const Locale('fr', 'FR'));
expect(Get.locale, const Locale('fr', 'CA'));
});
test('should only change the selected entry when ALLOWED_LANGUAGES is not set', () {
Get.locale = const Locale('en', 'GB');
controller.onReady();
expect(controller.languageSelected.value, const Locale('en', 'US'));
expect(Get.locale, const Locale('en', 'GB'));
});
test('should list every supported language when the app does not run on web', () {
PlatformInfo.isTestingForWeb = false;
dotenv.testLoad(mergeWith: {'ALLOWED_LANGUAGES': 'mn,en'});
Get.locale = const Locale('vi', 'VN');
controller.onReady();
expect(
controller.listSupportedLanguages,
LocalizationService.supportedLocales,
);
expect(controller.languageSelected.value, const Locale('vi', 'VN'));
});
test('should select the first allowed language when there is no current locale', () {
dotenv.testLoad(mergeWith: {'ALLOWED_LANGUAGES': 'mn,vi'});
Get.locale = null;
controller.onReady();
expect(controller.languageSelected.value, const Locale('mn', 'MN'));
});
});
}
@@ -22,6 +22,8 @@ import 'package:tmail_ui_user/features/mailbox_dashboard/domain/usecases/get_lin
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/providers/active_ecosystem_provider.dart';
import 'package:tmail_ui_user/features/mailbox_dashboard/presentation/providers/linagora_ecosystem_providers.dart';
import 'package:tmail_ui_user/features/paywall/presentation/providers/premium_cta_provider.dart';
import 'package:tmail_ui_user/main/exceptions/remote/authentication_exception.dart';
import 'package:tmail_ui_user/main/exceptions/remote/network_exception.dart';
import 'package:tmail_ui_user/main/providers/cozy/inside_cozy_provider.dart';
import 'package:tmail_ui_user/main/providers/workplace/fqdn/workplace_fqdn_user_info_notifier.dart';
@@ -34,10 +36,11 @@ void main() {
group('premium CTA loading states', _loadingStateTests);
group('premium CTA unavailable states', _premiumCtaUnavailableTests);
group('premium CTA gating', _premiumCtaGatingTests);
group('premium CTA urgent failure routing', _urgentFailureRoutingTests);
group('ecosystem soft-fail routing', _ecosystemSoftFailRoutingTests);
group('premium CTA stream disposal', _streamDisposalTests);
group('premium CTA missing dependencies', _missingDependenciesTests);
group('premium CTA degraded inputs', _degradedInputTests);
group('ecosystem state equality', _ecosystemStateEqualityTests);
}
void _ecosystemCachingTests() {
@@ -463,41 +466,156 @@ void _premiumCtaGatingTests() {
});
}
void _urgentFailureRoutingTests() {
test('routes urgent ecosystem failures exactly once', () async {
final exception = StateError('urgent');
final handler = _registerUrgentExceptionHandler();
final container = _createContainer(
_EcosystemRepository((_) async => throw exception),
void _ecosystemSoftFailRoutingTests() {
// Missing / CORS-blocked `.well-known/linagora-ecosystem` is normal; soft-fail
// connectivity only. Auth urgent exceptions from the shared Dio still route.
test('does not urgent-route a ConnectionError from ecosystem fetch',
() async {
final loaded = await _loadEcosystemThrowing(
const ConnectionError(),
keepActiveAlive: true,
);
_keepEcosystemAlive(container, _firstTarget);
await expectLater(
_readEcosystem(container, _firstTarget),
throwsA(isA<Failure>()),
expect(loaded.handler.handledCount, 0);
expect(
loaded.container.read(
activeEcosystemProvider(_firstAccountId, _firstJmapUrl),
),
isA<EcosystemUnavailable>().having(
(state) => state.reason,
'reason',
EcosystemUnavailableReason.loadFailed,
),
);
});
test('does not urgent-route a NoNetworkError from ecosystem fetch', () async {
final loaded = await _loadEcosystemThrowing(const NoNetworkError());
expect(loaded.handler.handledCount, 0);
});
test('still urgent-routes BadCredentialsException from ecosystem fetch',
() async {
const exception = BadCredentialsException();
final loaded = await _loadEcosystemThrowing(exception);
expect(loaded.handler.handledCount, 1);
expect(loaded.handler.lastException, same(exception));
});
test('still urgent-routes RefreshTokenFailedException from ecosystem fetch',
() async {
final exception = RefreshTokenFailedException();
final loaded = await _loadEcosystemThrowing(exception);
expect(loaded.handler.handledCount, 1);
expect(loaded.handler.lastException, same(exception));
});
test('does not urgent-route a non-urgent Left(GetLinagoraEcosystemFailure)',
() async {
// Filter allows offering the failure; production validation rejects it.
final loaded =
await _loadEcosystemThrowing(StateError('ecosystem missing'));
expect(loaded.handler.handledCount, 0);
});
test('does not urgent-route a bare ConnectionError stream error', () async {
const exception = ConnectionError();
final handler = await _loadEcosystemStreamError(exception);
expect(handler.handledCount, 0);
});
test('still urgent-routes a bare BadCredentialsException stream error',
() async {
const exception = BadCredentialsException();
final handler = await _loadEcosystemStreamError(exception);
expect(handler.handledCount, 1);
expect(handler.lastException, same(exception));
});
test('routes urgent ecosystem stream errors exactly once', () async {
final exception = Exception('urgent stream error');
final handler = _registerUrgentExceptionHandler();
final repository = _succeedingRepository();
final container = _createContainer(
repository,
interactor: _StreamErrorEcosystemInteractor(repository, exception),
);
await expectLater(
_readEcosystem(container, _firstTarget),
throwsA(same(exception)),
);
expect(handler.handledCount, 1);
expect(handler.lastException, same(exception));
test('does not urgent-route non-urgent ecosystem stream errors', () async {
final handler =
await _loadEcosystemStreamError(Exception('ecosystem stream error'));
expect(handler.handledCount, 0);
});
test('shouldRouteEcosystemUrgentException soft-fails only connectivity', () {
const connectionError = ConnectionError();
const noNetwork = NoNetworkError();
const badCredentials = BadCredentialsException();
final refreshFailed = RefreshTokenFailedException();
expect(shouldRouteEcosystemUrgentException(connectionError), isFalse);
expect(shouldRouteEcosystemUrgentException(noNetwork), isFalse);
expect(
shouldRouteEcosystemUrgentException(
GetLinagoraEcosystemFailure(connectionError),
),
isFalse,
);
expect(
shouldRouteEcosystemUrgentException(
GetLinagoraEcosystemFailure(noNetwork),
),
isFalse,
);
expect(shouldRouteEcosystemUrgentException(badCredentials), isTrue);
expect(shouldRouteEcosystemUrgentException(refreshFailed), isTrue);
expect(
shouldRouteEcosystemUrgentException(
GetLinagoraEcosystemFailure(badCredentials),
),
isTrue,
);
expect(
shouldRouteEcosystemUrgentException(
GetLinagoraEcosystemFailure(refreshFailed),
),
isTrue,
);
// Non-urgent types stay eligible for ADR-0103 offer; validation rejects.
expect(shouldRouteEcosystemUrgentException(StateError('x')), isTrue);
});
}
/// Loads ecosystem with [exception] from the repository and returns the urgent
/// handler (and container when active state must be asserted).
Future<({_UrgentExceptionHandler handler, ProviderContainer container})>
_loadEcosystemThrowing(
Object exception, {
bool keepActiveAlive = false,
}) async {
final handler = _registerUrgentExceptionHandler();
final container = _createContainer(
_EcosystemRepository((_) async => throw exception),
);
_keepEcosystemAlive(container, _firstTarget);
if (keepActiveAlive) {
_keepActiveEcosystemAlive(container, _firstTarget);
}
await expectLater(
_readEcosystem(container, _firstTarget),
throwsA(isA<Failure>()),
);
if (keepActiveAlive) await container.pump();
return (handler: handler, container: container);
}
Future<_UrgentExceptionHandler> _loadEcosystemStreamError(
Object exception,
) async {
final handler = _registerUrgentExceptionHandler();
final repository = _succeedingRepository();
final container = _createContainer(
repository,
interactor: _StreamErrorEcosystemInteractor(repository, exception),
);
await expectLater(
_readEcosystem(container, _firstTarget),
throwsA(same(exception)),
);
return handler;
}
void _streamDisposalTests() {
@@ -530,7 +648,11 @@ void _streamDisposalTests() {
subscription.close();
await container.pump();
completer.completeError(StateError('failed after disposal'));
// Must pass both shouldRouteEcosystemUrgentException and
// validateUrgentException. ConnectionError is soft-failed by the predicate,
// and StateError is rejected by validation. Either would leave handledCount
// at 0 even if the stale guard failed (vacuous green).
completer.completeError(const BadCredentialsException());
await container.pump();
expect(handler.handledCount, 0);
@@ -575,6 +697,44 @@ void _missingDependenciesTests() {
_unavailableEcosystem(EcosystemUnavailableReason.dependencyUnavailable),
);
});
test('loadEcosystem throws when the interactor binding is null', () async {
final container = ProviderContainer(overrides: [
getLinagoraEcosystemInteractorProvider.overrideWithValue(null),
insideCozyProvider.overrideWith((ref) => true),
]);
addTearDown(container.dispose);
await expectLater(
container.read(
ecosystemProvider(_firstAccountId, _firstJmapUrl).future,
),
throwsA(
isA<StateError>().having(
(error) => error.message,
'message',
'GetLinagoraEcosystemInteractor is unavailable',
),
),
);
});
}
void _ecosystemStateEqualityTests() {
test('EcosystemState equality covers Equatable props', () {
// Assert props directly: identical const instances skip Equatable.==.
expect(const EcosystemLoading().props, isEmpty);
expect(
const EcosystemUnavailable(EcosystemUnavailableReason.loadFailed).props,
[EcosystemUnavailableReason.loadFailed, null],
);
final ecosystem = _ecosystem(_paywallTemplate);
expect(EcosystemAvailable(ecosystem).props, [ecosystem]);
expect(
EcosystemLoading(),
isNot(EcosystemUnavailable(EcosystemUnavailableReason.missingAccount)),
);
});
}
const _firstJmapUrl = 'https://first.domain.tld';
@@ -667,8 +827,8 @@ ProviderContainer _createContainer(
return container;
}
/// The shared seam resolves the handler through GetX (ADR-0103), so urgent
/// routing is exercised the way production wires it.
/// Registers the GetX urgent handler the way production wires it, so tests can
/// assert that optional ecosystem failures stay off the urgent path.
_UrgentExceptionHandler _registerUrgentExceptionHandler() {
final handler = _UrgentExceptionHandler(isUrgent: true);
Get.testMode = true;
@@ -887,8 +1047,16 @@ class _UrgentExceptionHandler implements UrgentExceptionHandler {
_UrgentExceptionHandler({this.isUrgent = false});
/// Mirrors `BaseController.validateUrgentException` so soft-fail vs auth
/// routing assertions stay meaningful (not an accept-all stub).
@override
bool validateUrgentException(dynamic exception) => isUrgent;
bool validateUrgentException(dynamic exception) {
if (!isUrgent) return false;
return exception is NoNetworkError
|| exception is BadCredentialsException
|| exception is ConnectionError
|| exception is RefreshTokenFailedException;
}
@override
void handleUrgentException({Failure? failure, Exception? exception}) {
@@ -0,0 +1,25 @@
import 'package:core/utils/platform_info.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/main/localizations/localization_service.dart';
// Own file: dotenv is a global that cannot be unloaded once a test loads it.
void main() {
test(
'availableLocales should return every supported locale '
'when dotenv is not loaded',
() {
PlatformInfo.isTestingForWeb = true;
addTearDown(() => PlatformInfo.isTestingForWeb = false);
expect(dotenv.isInitialized, isFalse);
expect(
LocalizationService.availableLocales,
LocalizationService.supportedLocales,
);
expect(
LocalizationService.availableDefaultLocale,
LocalizationService.defaultLocale,
);
});
}
@@ -0,0 +1,132 @@
import 'package:core/utils/platform_info.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tmail_ui_user/main/localizations/localization_service.dart';
void main() {
const mongolian = Locale('mn', 'MN');
const english = Locale('en', 'US');
void allowLanguages(String value) =>
dotenv.testLoad(mergeWith: {'ALLOWED_LANGUAGES': value});
setUp(() {
PlatformInfo.isTestingForWeb = true;
dotenv.testLoad();
});
tearDown(() => PlatformInfo.isTestingForWeb = false);
group('LocalizationService on mobile test:', () {
setUp(() => PlatformInfo.isTestingForWeb = false);
test('should ignore ALLOWED_LANGUAGES and return every supported locale', () {
allowLanguages('mn,vi');
expect(
LocalizationService.availableLocales,
LocalizationService.supportedLocales,
);
expect(LocalizationService.availableDefaultLocale, english);
});
});
group('LocalizationService.availableLocales test:', () {
test('should return every supported locale when the option is not set', () {
expect(
LocalizationService.availableLocales,
LocalizationService.supportedLocales,
);
});
for (final value in ['', ' ', ' , ,']) {
test('should return every supported locale when the option is "$value"', () {
allowLanguages(value);
expect(
LocalizationService.availableLocales,
LocalizationService.supportedLocales,
);
});
}
test('should keep the allowed locales in the configured order', () {
allowLanguages('mn,en');
expect(LocalizationService.availableLocales, [mongolian, english]);
});
test('should accept a quoted value', () {
dotenv.testLoad(fileInput: 'ALLOWED_LANGUAGES="mn,en"');
expect(LocalizationService.availableLocales, [mongolian, english]);
});
test('should trim codes and ignore their case', () {
allowLanguages(' MN , En ');
expect(LocalizationService.availableLocales, [mongolian, english]);
});
test('should drop duplicated codes', () {
allowLanguages('mn,mn,en');
expect(LocalizationService.availableLocales, [mongolian, english]);
});
test('should ignore unknown codes', () {
allowLanguages('mn,xx');
expect(LocalizationService.availableLocales, [mongolian]);
});
test('should return every supported locale when every code is unknown', () {
allowLanguages('xx,yy');
expect(
LocalizationService.availableLocales,
LocalizationService.supportedLocales,
);
});
for (final value in ['pt', 'pt-BR', 'pt_BR']) {
test('should map "$value" to Brazilian Portuguese', () {
allowLanguages(value);
expect(LocalizationService.availableLocales, [
LocalizationService.brazilianPortugueseLocale,
]);
});
}
});
group('LocalizationService.availableDefaultLocale test:', () {
test('should be English when the option is not set', () {
expect(LocalizationService.availableDefaultLocale, english);
});
test('should be English when English is allowed', () {
allowLanguages('mn,en');
expect(LocalizationService.availableDefaultLocale, english);
});
test('should be the first allowed locale when English is not allowed', () {
allowLanguages('mn,fr');
expect(LocalizationService.availableDefaultLocale, mongolian);
});
});
test('supportedLocalesToLanguageTags should keep the full catalog', () {
allowLanguages('mn,en');
expect(
LocalizationService.supportedLocalesToLanguageTags(),
LocalizationService.supportedLocales
.map((locale) => locale.toLanguageTag())
.join(', '),
);
});
}