forked from eatvio/eatvio_app
Compare commits
20 Commits
issue-1122
...
issue-1140
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47b81fba5a | ||
|
|
5308c11ca6 | ||
| 1e8c1ab2eb | |||
|
|
29ee8ae5a8 | ||
|
|
ce073b5a95 | ||
|
|
b05d3b891b | ||
| 87d383152d | |||
| dbe0369d4d | |||
| 4f0ba5c864 | |||
| f9b862f4ad | |||
| 2ea711844f | |||
| 3519595ebf | |||
| 30932d9f28 | |||
| b30bf037db | |||
| bfb43104d8 | |||
| 4aadc8a9d8 | |||
| 7308e3e972 | |||
| 76c26457fc | |||
| 1255c9658c | |||
| 85cfcc519e |
64
.gitea/workflows/contract-sync.yml
Normal file
64
.gitea/workflows/contract-sync.yml
Normal file
@@ -0,0 +1,64 @@
|
||||
name: "Contract sync: flutter manifest -> eatvio (backend)"
|
||||
|
||||
# Автоматический перенос манифеста API-контракта из eatvio_app в eatvio-web.
|
||||
# Триггер: push в main с изменениями api_contract/**.
|
||||
# Результат: PR в eatvio-web с обновлённым tests/Fixtures/Contract/flutter_model_contract.json.
|
||||
# Далее CI eatvio-web сам прогонит FlutterApiContractTest и покажет,
|
||||
# выполняет ли бэкенд требования новых моделей.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "api_contract/**"
|
||||
workflow_dispatch: # ручной запуск для проверки секрета/прав: Actions → Contract sync → Run workflow
|
||||
|
||||
jobs:
|
||||
sync-manifest:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Open PR in eatvio-web with updated manifest
|
||||
env:
|
||||
TOKEN: ${{ secrets.CONTRACT_SYNC_TOKEN }} # PAT с write на eatvio/eatvio
|
||||
API: http://gitea.office.local:3000/api/v1
|
||||
BACKEND_REPO: eatvio/eatvio
|
||||
SRC: api_contract/flutter_model_contract.json
|
||||
DST: tests/Fixtures/Contract/flutter_model_contract.json
|
||||
run: |
|
||||
set -e
|
||||
SHORT_SHA="${GITHUB_SHA::8}"
|
||||
BRANCH="contract-sync/manifest-${SHORT_SHA}"
|
||||
auth="Authorization: token ${TOKEN}"
|
||||
|
||||
DEFAULT_BRANCH=$(curl -sf -H "$auth" "${API}/repos/${BACKEND_REPO}" | grep -o '"default_branch":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
|
||||
# Файл не изменился относительно предыдущего синка — выходим тихо.
|
||||
REMOTE_SHA=$(curl -sf -H "$auth" "${API}/repos/${BACKEND_REPO}/contents/${DST}?ref=${DEFAULT_BRANCH}" | grep -o '"sha":"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
LOCAL_SHA=$(git hash-object -- "${SRC}")
|
||||
if [ "${REMOTE_SHA}" = "${LOCAL_SHA}" ]; then
|
||||
echo "Manifest already in sync with ${BACKEND_REPO}."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 1. Ветка от дефолтной (если уже существует — переиспользуем).
|
||||
curl -sf -X POST -H "$auth" -H "Content-Type: application/json" \
|
||||
-d "{\"new_branch_name\":\"${BRANCH}\",\"old_branch_name\":\"${DEFAULT_BRANCH}\"}" \
|
||||
"${API}/repos/${BACKEND_REPO}/branches" || echo "branch ${BRANCH} already exists"
|
||||
|
||||
# 2. Обновить файл (contents API требует sha текущего файла).
|
||||
CONTENT_B64=$(base64 -w0 "${SRC}")
|
||||
curl -sf -X PUT -H "$auth" -H "Content-Type: application/json" \
|
||||
-d "{\"content\":\"${CONTENT_B64}\",\"message\":\"chore(contract): sync flutter manifest (${SHORT_SHA})\",\"sha\":\"${REMOTE_SHA}\",\"branch\":\"${BRANCH}\"}" \
|
||||
"${API}/repos/${BACKEND_REPO}/contents/${DST}" > /dev/null
|
||||
|
||||
# 3. PR (если уже открыт — пропускаем).
|
||||
curl -sf -X POST -H "$auth" -H "Content-Type: application/json" \
|
||||
-d "{\"title\":\"[contract-sync] flutter manifest ${SHORT_SHA}\",\"head\":\"${BRANCH}\",\"base\":\"${DEFAULT_BRANCH}\",\"body\":\"Автоматический синк манифеста из eatvio_app@${GITHUB_SHA}.\\n\\nCI бэкенда прогонит FlutterApiContractTest — если бэкенд не выполняет новые требования моделей, тест упадёт на этом PR.\"}" \
|
||||
"${API}/repos/${BACKEND_REPO}/pulls" > /dev/null \
|
||||
|| echo "PR already exists for ${BRANCH}"
|
||||
|
||||
echo "Sync PR opened: ${BACKEND_REPO} <- ${BRANCH}"
|
||||
@@ -182,6 +182,15 @@ jobs:
|
||||
flutter pub get
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
|
||||
# Контракт манифеста API: манифест обязан быть регенерирован из исходников freezed-моделей.
|
||||
# Diff после регенерации = PR менял модели, но не обновил api_contract/flutter_model_contract.json.
|
||||
# Обновлённый манифест нужно также синхронизировать в eatvio-web: tests/Fixtures/Contract/.
|
||||
- name: API contract manifest check
|
||||
run: |
|
||||
dart run tool/export_api_contract.dart api_contract/flutter_model_contract.json
|
||||
git diff --exit-code api_contract/flutter_model_contract.json \
|
||||
|| (echo "::error::api_contract/flutter_model_contract.json устарел. Регенерируй манифест (make export-api-contract) и синхронизируй его в eatvio-web: tests/Fixtures/Contract/flutter_model_contract.json" && exit 1)
|
||||
|
||||
- name: Native Analyze
|
||||
run: flutter analyze
|
||||
|
||||
|
||||
76
AGENTS.md
Normal file
76
AGENTS.md
Normal file
@@ -0,0 +1,76 @@
|
||||
# AGENTS.md
|
||||
|
||||
Flutter/Dart mobile app (iOS + Android, Russian-market nutrition/consulting product).
|
||||
Gitea-hosted; CI is Gitea Actions in `.gitea/workflows/` (not GitHub Actions, though it references `github.com/actions/*`).
|
||||
|
||||
## Toolchain (trust these over README — README version numbers are stale)
|
||||
|
||||
- CI runs **Flutter 3.41.2 stable**, **Java/JDK 21** (`.gitea/workflows/test.yml`).
|
||||
- `pubspec.yaml` requires **Dart SDK ^3.10.4**; app version is `1.3.23+105` (README claims 1.3.0+79 — wrong).
|
||||
- Build/test/lint via Flutter directly or the `Makefile`. The repo has a `package.json` **only** to wire a git pre-push hook via `simple-git-hooks`; it is not a Node project.
|
||||
|
||||
## CRITICAL: generated code is NOT committed
|
||||
|
||||
`.gitignore` excludes `*.g.dart`, `*.freezed.dart`, `*.gr.dart`, `*.mocks.dart`. After any checkout / pull / model change you **must regenerate** before `flutter analyze`, `flutter test`, or any build, or they fail on missing files:
|
||||
|
||||
```bash
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
# or: make build-generated-files
|
||||
```
|
||||
|
||||
Generators in use: `freezed`, `json_serializable`, `retrofit_generator`, `mockito` (`build_runner`).
|
||||
Exception: `lib/generated/` (l10n output from `intl_utils` / `flutter_intl`) **is** committed — don't regenerate-and-clobber it casually.
|
||||
|
||||
## `.env` (required for running the app, NOT for unit tests)
|
||||
|
||||
- The app loads `.env` at startup (`lib/core/app_initializer.dart` → `dotenv.load`) and ships it as a Flutter asset (`pubspec.yaml` assets).
|
||||
- There is **no `env.example` in the repo** despite README/`ENV_SETUP.md` saying `cp env.example .env`. Locally you must obtain `.env` from the team. In CI it is checked out from a **private `eatvio/eatvio_app_env` repo**.
|
||||
- `flutter test` does **not** need `.env`: tests seed env via `dotenv.loadFromString(...)` (see `test/core/app_config_test.dart`). Access values only through `lib/core/env_config.dart` (`EnvConfig`).
|
||||
- Build types: `AppBuildType { prod, tests, dev }` (`lib/core/app_initializer.dart`). `prod` → `BASE_URL`; `tests`/`dev` → `DEV_BASE_URL`. `main.dart` hardcodes `prod`.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
make run-analyse # flutter analyze
|
||||
make run-tests # flutter test
|
||||
make run-checks # analyze THEN test (also the pre-push hook)
|
||||
make build-generated-files # build_runner --delete-conflicting-outputs
|
||||
make clean-coverage # strips generated files from coverage/lcov.info
|
||||
```
|
||||
|
||||
Run a single test file / single test:
|
||||
```bash
|
||||
flutter test test/core/app_config_test.dart
|
||||
flutter test test/core/app_config_test.dart --plain-name "creates config with prod build type"
|
||||
```
|
||||
|
||||
Coverage (must be run with the flag): `flutter test --coverage`, then `make clean-coverage`. `analyze_coverage.py` / `analyze_coverage_by_uncovered.py` summarize `coverage/lcov.info`.
|
||||
|
||||
## CI gate (binding constraint on PRs)
|
||||
|
||||
`.gitea/workflows/test.yml` runs on every PR, in order:
|
||||
1. `flutter clean` → `flutter pub get` → `dart run build_runner build --delete-conflicting-outputs`
|
||||
2. `flutter analyze`
|
||||
3. `flutter test --coverage`
|
||||
4. **Coverage must be ≥ 70%** (generated files excluded) or the job fails — keep this in mind when adding untested code.
|
||||
5. `flutter build apk --release --dart-define=HIDE_PLANS=false --dart-define=BUILD_DATE=...`
|
||||
|
||||
Note: other workflow files (`build.yml`, `docker-run-tests.yml`) are simpler/older and do **not** run `build_runner`; `test.yml` is the authoritative one.
|
||||
|
||||
## Architecture map
|
||||
|
||||
- Entry: `lib/main.dart` → `AppInitializer.initialize` (env → DI → Sentry → Firebase → analytics) → runs app under Sentry.
|
||||
- DI: `get_it` (`sl` global), registered in `lib/core/locator_service.dart` via `lib/core/di/*_registrations.dart` (app_config, external, service, repository, cubit).
|
||||
- State: `flutter_bloc` (Cubits/Blocs). Global providers declared in `lib/core/app_config.dart` (`globalBlocProviders`).
|
||||
- Routing: `go_router` (`lib/core/app_router.dart`), with deep-link/push handling in `lib/core/notifications/`.
|
||||
- Networking: `dio` + `retrofit` (→ `.gr.dart`); auth token interceptor in `lib/core/interceptors/`.
|
||||
- Models: `freezed` + `json_serializable` (→ `.freezed.dart` / `.g.dart`).
|
||||
- Realtime: Pusher channels via `lib/core/websockets/` (`WsManager`).
|
||||
- Features: ~40 self-contained folders under `lib/features/<feature>/`, conventionally `.../presentation/bloc/<name>_cubit/<name>_cubit.dart`. Tests mirror `lib/` under `test/` with fixtures in `test/fixtures/`.
|
||||
- Localization: Russian only (`ru`); strings via generated `S` class from `lib/generated/l10n.dart`.
|
||||
|
||||
## Conventions / gotchas
|
||||
|
||||
- `analysis_options.yaml` enables `flutter_lints` + extra `prefer_const_*` rules and **excludes generated + l10n files** from analysis. `dart_code_metrics` is also configured (cyclomatic ≤20, ≤50 lines executable, ≤4 params, nesting ≤5) but metrics exclude `test/**`.
|
||||
- Don't commit secrets: `.env`, `android/key.properties`, `*.jks` keystores are all gitignored.
|
||||
- Comments and many code identifiers are in Russian (UI strings, doc comments like `/// Загрузка переменных окружения`); match surrounding style.
|
||||
11
Makefile
11
Makefile
@@ -11,3 +11,14 @@ build-generated-files:
|
||||
|
||||
clean-coverage:
|
||||
@./scripts/remove_generated_from_coverage.sh
|
||||
|
||||
# Регенерация манифеста API-контракта из исходников freezed-моделей.
|
||||
# Манифест — источник требований мобильных моделей для eatvio-web
|
||||
# (tests/Fixtures/Contract/flutter_model_contract.json).
|
||||
export-api-contract:
|
||||
dart run tool/export_api_contract.dart api_contract/flutter_model_contract.json
|
||||
|
||||
# Проверка актуальности манифеста (для CI): регенерирует и диффает с закоммиченным.
|
||||
check-api-contract: export-api-contract
|
||||
@git diff --exit-code api_contract/flutter_model_contract.json \
|
||||
|| (echo "api_contract/flutter_model_contract.json устарел: регенерируй (make export-api-contract) и синхронизируй в eatvio-web tests/Fixtures/Contract/" && exit 1)
|
||||
|
||||
91
api_contract/README.md
Normal file
91
api_contract/README.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# Регламент синхронизации API-контракта (eatvio/eatvio ↔ eatvio/eatvio_app)
|
||||
|
||||
> В тексте «eatvio-web» — локальное имя бэкенд-репозитория **eatvio/eatvio** (не slug!).
|
||||
|
||||
## Стороны и артефакты
|
||||
|
||||
| Репозиторий | Артефакт | Роль |
|
||||
|---|---|---|
|
||||
| eatvio_app | `tool/export_api_contract.dart` | генератор: парсит freezed-декларации из **исходников** (не из `*.g.dart`) |
|
||||
| eatvio_app | `api_contract/flutter_model_contract.json` | **источник истины**: требования мобильных моделей к JSON (required/optional ключи) |
|
||||
| eatvio-web | `tests/Fixtures/Contract/flutter_model_contract.json` | синхронизированная копия, по ней CI бэка валидирует API-ресурсы |
|
||||
| eatvio-web | `tests/Feature/Contract/FlutterApiContractTest.php` | контрактные тесты: worst-case сериализация ресурса ↔ манифест |
|
||||
|
||||
Контракт односторонний по данным: бэкенд отдаёт JSON → flutter читает (`fromJson`). Экстремальный случай — nullable-колонка на бэке при required-поле во flutter: ровно он дал продовой баг FLUTTER-1BX (`satiety: null` → `TypeError` в `_$MealModelFromJson`, дневник мобильных клиентов не работал, КБЖУ-информер показал нули).
|
||||
|
||||
## Направление 1: backend → frontend (бэк меняет ответ API)
|
||||
|
||||
1. Дев меняет API-ресурс в eatvio-web (например, делает поле nullable / удаляет ключ).
|
||||
2. `FlutterApiContractTest` падает, если новое поведение нарушает манифест — **это и есть фильтр обратной несовместимости**.
|
||||
3. Дальше два осознанных пути:
|
||||
- **Сохранить совместимость** (предпочтительно): вернуть значение/дефолт на бэке (`?? 0`, как с `time` → `'00:00:00'`). Манифест не меняется.
|
||||
- **Ломать сознательно**: мержится mobile-first — сначала в eatvio_app поле становится nullable/опциональным, выходит релиз приложения; затем PR в eatvio-web меняет ресурс и копию манифеста. Пока старые версии приложения в рынке — бэк держит старый формат.
|
||||
4. Коммит копии манифеста в eatvio-web без изменения ресурса бессмысленен и не проходит ревью: манифест меняется только вместе с ресурсом.
|
||||
|
||||
## Направление 2: frontend → backend (фронт ужесточает требования)
|
||||
|
||||
1. Дев меняет freezed-модель в eatvio_app (например, добавляет `required int nutrition`).
|
||||
2. CI eatvio_app (`test.yml`, шаг `API contract manifest check`) регенерирует манифест и диффает: устарел → PR не проходит.
|
||||
3. Дев обновляет манифест (`make export-api-contract`) и **в том же PR** синхронизирует копию в eatvio-web (`tests/Fixtures/Contract/`).
|
||||
4. CI eatvio-web прогоняет `FlutterApiContractTest` против новой копии: если бэк не выдаёт новые required-ключи — падает уже там, и бэк добавляет гарантии **до** релиза приложения.
|
||||
5. Порядок релизов: бэк докручивается первым (он назад-совместим), затем выходит приложение.
|
||||
|
||||
## Правила совместимости (шпаргалка)
|
||||
|
||||
| Изменение на бэке | Ломает приложение? | Действие |
|
||||
|---|---|---|
|
||||
| Поле остаётся non-null | нет | ничего |
|
||||
| Добавлен новый ключ | нет (flutter игнорирует лишнее) | ничего; добавить в модель отдельно при необходимости |
|
||||
| non-null → nullable / ключ удалён | **да** | mobile-first: релиз приложения, потом бэк |
|
||||
| flutter: `int` → `int?` | нет | `make export-api-contract` + синк манифеста |
|
||||
| flutter: добавлен `required`-ключ | **бэк может не выполнять** | синк манифеста → бэк добавляет ключ/дефолт до релиза |
|
||||
|
||||
## Автоматика
|
||||
|
||||
| Где | Что | Когда срабатывает |
|
||||
|---|---|---|
|
||||
| eatvio_app, CI | шаг `API contract manifest check` (test.yml) | каждый PR: манифест обязан быть регенерирован из исходников |
|
||||
| eatvio_app, CI | `contract-sync.yml` | push в main с изменениями `api_contract/**` → авто-PR в eatvio (бэкенд) с новой копией манифеста |
|
||||
| eatvio_app, локально | `make export-api-contract` / `make check-api-contract` | руками при работе над моделями |
|
||||
| eatvio-web, CI | `FlutterApiContractTest` (12 тестов) | каждый PR: worst-case сериализация ресурсов ↔ манифест |
|
||||
| eatvio-web, CI | `contract-drift-check.yaml` | еженощно: сравнение локальной копии манифеста с eatvio_app@main, при дрейфе — issue |
|
||||
| eatvio-web, локально | `make sync-flutter-contract` | руками, если авто-PR не пришёл |
|
||||
|
||||
Секреты: `CONTRACT_SYNC_TOKEN` — PAT с write на eatvio/eatvio (для contract-sync) и read eatvio/eatvio_app + issues на eatvio/eatvio (для drift-check).
|
||||
|
||||
## Как команды держат друг друга в рабочем состоянии (три слоя)
|
||||
|
||||
1. **Предотвращение (до мержа).** Контрактные тесты на обеих сторонах: flutter не смержит модели без регенерации манифеста; бэкенд не смержит ресурс, отдающий null/не тот тип там, где приложение требует non-null.
|
||||
2. **Синхронизация (при мерже).** Авто-PR из `contract-sync.yml` приносит новую копию манифеста в бэкенд; CI бэкенда на этом PR показывает, выполняет ли сервер новые требования. Ночной drift-check ловит всё, что проскочило мимо автоматики.
|
||||
3. **Обнаружение (после релиза).** Sentry: группа `TypeError ... in _$XxxFromJson` (проект flutter) = нарушение контракта в проде. Такой issue должен ссылаться на контрактную пару и закрываться фиксом ресурса + контрак тестом.
|
||||
|
||||
Ритуалы:
|
||||
- Меняешь модель в приложении → `make export-api-contract` в том же PR; манифест уедет в бэкенд автоматически.
|
||||
- Меняешь API-ресурс → прогоняй контрактный тест; красный = либо делай совместимо (дефолты), либо mobile-first релиз.
|
||||
- WARNING генератора о коллизии имён моделей (`Step`, `Users`, ...) — повод переименовать Dart-классы: под одним именем могут скрываться разные контракты.
|
||||
|
||||
## Формат манифеста
|
||||
|
||||
Каждая модель: `required` / `optional` (JSON-ключи), `types` (Dart-тип поля) и `kinds`
|
||||
(JSON-вид значения, по которому бэкенд-чекер валидирует payload):
|
||||
|
||||
| kind | Dart-типы | Ожидание в JSON |
|
||||
|---|---|---|
|
||||
| `number` | `int`, `double`, `num` | число (int или float) |
|
||||
| `string` | `String` | строка |
|
||||
| `boolean` | `bool` | строго true/false (int 0/1 — нарушение) |
|
||||
| `list` | `List<...>` | массив |
|
||||
| `map` | `Map<...>` | объект |
|
||||
| `model` | вложенная freezed-модель | объект |
|
||||
| `enum` | Dart enum | строка-имя или int |
|
||||
| `any` / `unknown` | `dynamic` и прочее | не проверяется |
|
||||
|
||||
Это закрывает второй класс мобильных крашей: жёсткие касты (`json['from_diet'] as bool`,
|
||||
`json['quantity'] as num`) роняют приложение даже на non-null значениях — например,
|
||||
если PHP отдаст tinyint `0/1` вместо bool или строку `"150"` вместо числа.
|
||||
|
||||
## Границы подхода
|
||||
|
||||
- Манифест покрывает **ответы** API (fromJson). Контракт запросов (retrofit → FormRequest) пока не формализован.
|
||||
- Новый ключ бэкенда не требует изменения манифеста — flutter молча игнорирует лишнее; расширять модели — добровольно.
|
||||
- `kinds: unknown` не проверяется (неклассифицированные типы), чтобы не давать ложных срабатываний.
|
||||
4383
api_contract/flutter_model_contract.json
Normal file
4383
api_contract/flutter_model_contract.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -18,21 +18,22 @@ class AppInitializer {
|
||||
static Future<void> initialize({required AppBuildType buildType}) async {
|
||||
await _initializeEnvironment();
|
||||
await _initializeDependencyInjection(buildType: buildType);
|
||||
await _initializeSentry();
|
||||
_preserveSplash();
|
||||
await _initializeFirebase();
|
||||
await _initializeDebugMode();
|
||||
await _initializeAnalytics();
|
||||
}
|
||||
|
||||
/// Инициализация Sentry
|
||||
static Future<void> _initializeSentry() async {
|
||||
static void _preserveSplash() {
|
||||
final widgetsBinding = SentryWidgetsFlutterBinding.ensureInitialized();
|
||||
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
|
||||
}
|
||||
|
||||
/// Загрузка переменных окружения
|
||||
static Future<void> _initializeEnvironment() async {
|
||||
await dotenv.load(fileName: ".env");
|
||||
if (!dotenv.isInitialized) {
|
||||
await dotenv.load(fileName: '.env');
|
||||
}
|
||||
}
|
||||
|
||||
/// Инициализация Firebase
|
||||
@@ -64,20 +65,25 @@ class AppInitializer {
|
||||
|
||||
/// Инициализация аналитики
|
||||
static Future<void> _initializeAnalytics() async {
|
||||
AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey));
|
||||
AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey, flutterCrashReporting: false));
|
||||
AppMetrica.reportEvent('Application started');
|
||||
}
|
||||
|
||||
/// Запуск приложения с Sentry
|
||||
static Future<void> runAppWithSentry(VoidCallback appRunner) async {
|
||||
static Future<void> runAppWithSentry(
|
||||
FutureOr<void> Function() appRunner,
|
||||
) async {
|
||||
SentryWidgetsFlutterBinding.ensureInitialized();
|
||||
await _initializeEnvironment();
|
||||
const sendInDebug = bool.fromEnvironment('SENTRY_IN_DEBUG');
|
||||
await SentryFlutter.init((options) {
|
||||
options.dsn = EnvConfig.sentryDsn;
|
||||
options.tracesSampleRate = 1.0;
|
||||
options.debug = false;
|
||||
if (kDebugMode && sendInDebug) options.environment = 'debug';
|
||||
options.beforeSend = (event, hint) {
|
||||
if (kDebugMode) return null;
|
||||
if (!ErrorReportPolicy.allowSentryEvent(event, hint)) return null;
|
||||
return event;
|
||||
if (kDebugMode && !sendInDebug) return null;
|
||||
return ErrorReportPolicy.prepareSentryEvent(event, hint);
|
||||
};
|
||||
}, appRunner: appRunner);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'comments_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class CommentsService {
|
||||
factory CommentsService(Dio dio, {String baseUrl}) = _CommentsService;
|
||||
factory CommentsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _CommentsService;
|
||||
|
||||
@DELETE('/api/comments/{id}')
|
||||
Future<void> deleteComment(@Path('id') int id);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/constants/app_constants.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_dio.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/sentry_error_reporter.dart';
|
||||
import 'package:eatvio_app/core/interceptors/phone_verify_error_interceptor.dart';
|
||||
@@ -18,14 +20,15 @@ class ExternalRegistrations {
|
||||
/// Регистрация всех внешних зависимостей
|
||||
static void registerAll() {
|
||||
sl.registerLazySingleton<ErrorReporter>(SentryErrorReporter.new);
|
||||
sl.registerLazySingleton(() => ApiResponseErrorReporter(sl()));
|
||||
_registerDio();
|
||||
_registerPrefs();
|
||||
}
|
||||
|
||||
/// Регистрация Dio HTTP клиента
|
||||
static void _registerDio() {
|
||||
sl.registerLazySingleton(
|
||||
() => Dio(
|
||||
sl.registerLazySingleton<Dio>(
|
||||
() => ApiResponseDio(
|
||||
BaseOptions(
|
||||
baseUrl: sl<AppConfig>().baseUrl,
|
||||
headers: {'accept': 'application/json', 'content-type': 'application/json'},
|
||||
@@ -33,6 +36,7 @@ class ExternalRegistrations {
|
||||
receiveTimeout: AppConstants.pendingDelay,
|
||||
sendTimeout: AppConstants.pendingDelay,
|
||||
),
|
||||
sl(),
|
||||
)..interceptors.addAll([TokenInterceptor(), PhoneVerifyErrorInterceptor()])
|
||||
..addSentry(
|
||||
failedRequestStatusCodes: const [SentryStatusCode.defaultRange()],
|
||||
|
||||
@@ -86,7 +86,9 @@ class RepositoryRegistrations {
|
||||
sl.registerLazySingleton<CommentsRepository>(() => CommentsRepository(service: sl()));
|
||||
sl.registerLazySingleton<NotificationSettingsRepository>(() => NotificationSettingsRepository(sl()));
|
||||
sl.registerLazySingleton<SbpRepository>(() => SbpRepository(sbpService: sl()));
|
||||
sl.registerLazySingleton<PaymentRepository>(() => PaymentRepository(chatService: sl()));
|
||||
sl.registerLazySingleton<PaymentRepository>(
|
||||
() => PaymentRepository(chatService: sl(), responseErrors: sl()),
|
||||
);
|
||||
sl.registerLazySingleton<PersonalDietSuggestionRepository>(() => PersonalDietSuggestionRepository(personalDietSuggestionService: sl()));
|
||||
sl.registerLazySingleton<RegistrationRepositoryV2>(() => RegistrationRepositoryV2(registrationService: sl()));
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart';
|
||||
import 'package:eatvio_app/core/comments/services/comments_service.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/views/service/views_service.dart';
|
||||
@@ -56,37 +57,83 @@ class ServiceRegistrations {
|
||||
/// Регистрация Service как синглтонов
|
||||
static void _registerSingletonServices() {
|
||||
// Core services
|
||||
sl.registerLazySingleton<ChatService>(() => ChatService(sl()));
|
||||
sl.registerLazySingleton<VideoCallService>(() => VideoCallService(sl()));
|
||||
sl.registerLazySingleton<ChatService>(
|
||||
() => ChatService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<VideoCallService>(
|
||||
() => VideoCallService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<PublicDownloadsSaver>(
|
||||
() => const PublicDownloadsSaver(),
|
||||
);
|
||||
sl.registerLazySingleton<VideoCallRecordingFileService>(
|
||||
() => VideoCallRecordingFileService(dio: sl(), downloadsSaver: sl()),
|
||||
);
|
||||
sl.registerLazySingleton<FeedService>(() => FeedService(sl()));
|
||||
sl.registerLazySingleton<ProfileService>(() => ProfileService(sl()));
|
||||
sl.registerLazySingleton<InsightsService>(() => InsightsService(sl()));
|
||||
sl.registerLazySingleton<CalendarService>(() => CalendarService(sl()));
|
||||
sl.registerLazySingleton<SettingsService>(() => SettingsService(sl()));
|
||||
sl.registerLazySingleton<ConsultantService>(() => ConsultantService(sl()));
|
||||
sl.registerLazySingleton<DiaryService>(() => DiaryService(sl()));
|
||||
sl.registerLazySingleton<GlossaryService>(() => GlossaryService(sl()));
|
||||
sl.registerLazySingleton<BarcodeService>(() => BarcodeService(sl()));
|
||||
sl.registerLazySingleton<DietService>(() => DietService(sl()));
|
||||
sl.registerLazySingleton<PlansService>(() => PlansService(sl()));
|
||||
sl.registerLazySingleton<PlanService>(() => PlanService(sl()));
|
||||
sl.registerLazySingleton<MyDietsService>(() => MyDietsService(sl()));
|
||||
sl.registerLazySingleton<MyPlansService>(() => MyPlansService(sl()));
|
||||
sl.registerLazySingleton<WsService>(() => WsService(sl()));
|
||||
sl.registerLazySingleton<AboutRecipeService>(() => AboutRecipeService(sl()));
|
||||
sl.registerLazySingleton<ComplainingService>(() => ComplainingService(sl()));
|
||||
sl.registerLazySingleton<AuthService>(() => AuthService(sl()));
|
||||
sl.registerLazySingleton<CardsService>(() => CardsService(sl()));
|
||||
sl.registerLazySingleton<FeedService>(
|
||||
() => FeedService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<ProfileService>(
|
||||
() => ProfileService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<InsightsService>(
|
||||
() => InsightsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<CalendarService>(
|
||||
() => CalendarService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<SettingsService>(
|
||||
() => SettingsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<ConsultantService>(
|
||||
() => ConsultantService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<DiaryService>(
|
||||
() => DiaryService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<GlossaryService>(
|
||||
() => GlossaryService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<BarcodeService>(
|
||||
() => BarcodeService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<DietService>(
|
||||
() => DietService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<PlansService>(
|
||||
() => PlansService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<PlanService>(
|
||||
() => PlanService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<MyDietsService>(
|
||||
() => MyDietsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<MyPlansService>(
|
||||
() => MyPlansService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<WsService>(() => WsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()));
|
||||
sl.registerLazySingleton<AboutRecipeService>(
|
||||
() => AboutRecipeService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<ComplainingService>(
|
||||
() => ComplainingService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<AuthService>(
|
||||
() => AuthService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<CardsService>(
|
||||
() => CardsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<ConsultationService>(() => ConsultationService(sl()));
|
||||
sl.registerLazySingleton<CancelPlanService>(() => CancelPlanService(sl()));
|
||||
sl.registerLazySingleton<CreatePlanService>(() => CreatePlanService(sl()));
|
||||
sl.registerLazySingleton<NotificationsService>(() => NotificationsService(sl()));
|
||||
sl.registerLazySingleton<CancelPlanService>(
|
||||
() => CancelPlanService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<CreatePlanService>(
|
||||
() => CreatePlanService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<NotificationsService>(
|
||||
() => NotificationsService(sl(), responseErrors: sl()),
|
||||
);
|
||||
sl.registerLazySingleton<FirebaseApi>(() => FirebaseApi(errorReporter: sl()));
|
||||
sl.registerLazySingleton<VideoCallCallKitCoordinator>(
|
||||
() => VideoCallCallKitCoordinator(firebaseApi: sl()),
|
||||
@@ -94,23 +141,49 @@ class ServiceRegistrations {
|
||||
sl.registerLazySingleton<VideoCallSystemPipCoordinator>(
|
||||
() => VideoCallSystemPipCoordinator(),
|
||||
);
|
||||
sl.registerLazySingleton<ResetPasswordService>(() => ResetPasswordService(sl()));
|
||||
sl.registerLazySingleton<BlockedUserService>(() => BlockedUserService(sl()));
|
||||
sl.registerLazySingleton<CommentsService>(() => CommentsService(sl()));
|
||||
sl.registerLazySingleton<MyRecipesService>(() => MyRecipesService(sl()));
|
||||
sl.registerLazySingleton<ConsultantRatingService>(() => ConsultantRatingService(sl()));
|
||||
sl.registerLazySingleton<NotificationSettingsService>(() => NotificationSettingsService(sl()));
|
||||
sl.registerLazySingleton<ViewsService>(() => ViewsService(sl()));
|
||||
sl.registerLazySingleton<ResetPasswordService>(
|
||||
() => ResetPasswordService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<BlockedUserService>(
|
||||
() => BlockedUserService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<CommentsService>(
|
||||
() => CommentsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<MyRecipesService>(
|
||||
() => MyRecipesService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<ConsultantRatingService>(
|
||||
() => ConsultantRatingService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<NotificationSettingsService>(
|
||||
() => NotificationSettingsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<ViewsService>(
|
||||
() => ViewsService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<SbpService>(() => const SbpServiceImpl());
|
||||
sl.registerLazySingleton<PersonalDietSuggestionService>(() => PersonalDietSuggestionService(sl()));
|
||||
sl.registerLazySingleton<RegistrationServiceV2>(() => RegistrationServiceV2(sl()));
|
||||
sl.registerLazySingleton<PersonalDietSuggestionService>(
|
||||
() => PersonalDietSuggestionService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<RegistrationServiceV2>(
|
||||
() => RegistrationServiceV2(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
|
||||
// Content services
|
||||
sl.registerLazySingleton<CreateRecipeService>(() => CreateRecipeService(sl()));
|
||||
sl.registerLazySingleton<BlogPostService>(() => BlogPostService(sl()));
|
||||
sl.registerLazySingleton<CreateDietService>(() => CreateDietService(sl()));
|
||||
sl.registerLazySingleton<CreateRecipeService>(
|
||||
() => CreateRecipeService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<BlogPostService>(
|
||||
() => BlogPostService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
sl.registerLazySingleton<CreateDietService>(
|
||||
() => CreateDietService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
|
||||
// Auth services
|
||||
sl.registerLazySingleton<RegistrationService>(() => RegistrationService(sl()));
|
||||
sl.registerLazySingleton<RegistrationService>(
|
||||
() => RegistrationService(sl(), errorLogger: sl<ApiResponseErrorReporter>()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
71
lib/core/error_reporting/api_response_dio.dart
Normal file
71
lib/core/error_reporting/api_response_dio.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:dio/io.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart';
|
||||
|
||||
class ApiResponseDio extends DioForNative {
|
||||
ApiResponseDio(BaseOptions super.options, this._responseErrors) {
|
||||
transformer = _ApiResponseTransformer(
|
||||
transformer,
|
||||
_responseErrors,
|
||||
_responseStatuses,
|
||||
);
|
||||
}
|
||||
|
||||
final ApiResponseErrorReporter _responseErrors;
|
||||
final _responseStatuses = Expando<int>();
|
||||
|
||||
@override
|
||||
Future<Response<T>> fetch<T>(RequestOptions requestOptions) async {
|
||||
try {
|
||||
return await super.fetch<T>(requestOptions);
|
||||
} on DioException catch (error) {
|
||||
final cause = error.error;
|
||||
final status = _responseStatuses[error.requestOptions];
|
||||
// Dio приводит тип корневого значения до вызова fromJson в Retrofit.
|
||||
if (error.type == DioExceptionType.unknown &&
|
||||
error.requestOptions.responseType == ResponseType.json &&
|
||||
cause is TypeError &&
|
||||
status != null) {
|
||||
_responseErrors.report(
|
||||
error,
|
||||
cause.stackTrace ?? error.stackTrace,
|
||||
method: error.requestOptions.method,
|
||||
statusCode: status,
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _ApiResponseTransformer implements Transformer {
|
||||
_ApiResponseTransformer(this._delegate, this._responseErrors, this._statuses);
|
||||
|
||||
final Transformer _delegate;
|
||||
final ApiResponseErrorReporter _responseErrors;
|
||||
final Expando<int> _statuses;
|
||||
|
||||
@override
|
||||
Future<String> transformRequest(RequestOptions options) =>
|
||||
_delegate.transformRequest(options);
|
||||
|
||||
@override
|
||||
Future<dynamic> transformResponse(
|
||||
RequestOptions options,
|
||||
ResponseBody response,
|
||||
) async {
|
||||
try {
|
||||
final data = await _delegate.transformResponse(options, response);
|
||||
_statuses[options] = response.statusCode;
|
||||
return data;
|
||||
} on FormatException catch (error, stackTrace) {
|
||||
_responseErrors.report(
|
||||
error,
|
||||
stackTrace,
|
||||
method: options.method,
|
||||
statusCode: response.statusCode,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
111
lib/core/error_reporting/api_response_error_reporter.dart
Normal file
111
lib/core/error_reporting/api_response_error_reporter.dart
Normal file
@@ -0,0 +1,111 @@
|
||||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
||||
import 'package:retrofit/retrofit.dart';
|
||||
|
||||
class ApiResponseErrorReporter implements ParseErrorLogger {
|
||||
ApiResponseErrorReporter(this._reporter);
|
||||
|
||||
final ErrorReporter _reporter;
|
||||
static final _capturedErrors = Expando<bool>();
|
||||
|
||||
static bool wasCaptured(Object error) =>
|
||||
_isCaptured(error) || (error is DioException && _isCaptured(error.error));
|
||||
|
||||
static bool _isCaptured(Object? error) =>
|
||||
error != null &&
|
||||
(error is Error || error is Exception) &&
|
||||
_capturedErrors[error] == true;
|
||||
|
||||
static T decode<T>(
|
||||
ApiResponseErrorReporter? reporter,
|
||||
Response<dynamic> response,
|
||||
String endpoint,
|
||||
T Function() parse,
|
||||
) {
|
||||
try {
|
||||
return parse();
|
||||
} catch (error, stackTrace) {
|
||||
reporter?.report(
|
||||
error,
|
||||
stackTrace,
|
||||
method: response.requestOptions.method,
|
||||
statusCode: response.statusCode,
|
||||
endpoint: endpoint,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void logError(
|
||||
Object error,
|
||||
StackTrace stackTrace,
|
||||
RequestOptions options, {
|
||||
Response<dynamic>? response,
|
||||
}) {
|
||||
report(
|
||||
error,
|
||||
stackTrace,
|
||||
method: options.method,
|
||||
statusCode: response?.statusCode,
|
||||
);
|
||||
}
|
||||
|
||||
void report(
|
||||
Object error,
|
||||
StackTrace stackTrace, {
|
||||
required String method,
|
||||
int? statusCode,
|
||||
String? endpoint,
|
||||
}) {
|
||||
if (error is Error || error is Exception) {
|
||||
_capturedErrors[error] = true;
|
||||
}
|
||||
// Сообщение исходного исключения может содержать значения из ответа API.
|
||||
final cause = error is DioException ? error.error ?? error : error;
|
||||
unawaited(
|
||||
_send(
|
||||
ApiResponseDecodeException(cause.runtimeType.toString()),
|
||||
stackTrace,
|
||||
{
|
||||
'http_method': method,
|
||||
'http_status_code': ?statusCode,
|
||||
'endpoint': ?endpoint,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _send(
|
||||
ApiResponseDecodeException error,
|
||||
StackTrace stackTrace,
|
||||
Map<String, Object?> context,
|
||||
) async {
|
||||
try {
|
||||
await _reporter.report(
|
||||
error,
|
||||
stackTrace,
|
||||
origin: 'api_response',
|
||||
extras: context,
|
||||
);
|
||||
} catch (reportError, reportStackTrace) {
|
||||
log(
|
||||
'Не удалось записать ошибку разбора ответа API',
|
||||
error: reportError.runtimeType,
|
||||
stackTrace: reportStackTrace,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ApiResponseDecodeException implements Exception {
|
||||
ApiResponseDecodeException(this.causeType);
|
||||
|
||||
final String causeType;
|
||||
|
||||
@override
|
||||
String toString() => 'Could not decode API response ($causeType)';
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart';
|
||||
import 'package:eatvio_app/core/push/hms_client_error.dart';
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
||||
@@ -14,6 +15,7 @@ class ErrorReportPolicy {
|
||||
/// When `false`, the error is not sent via [ErrorReporter].
|
||||
static bool shouldReport(Object? error) {
|
||||
if (error == null) return false;
|
||||
if (ApiResponseErrorReporter.wasCaptured(error)) return false;
|
||||
if (error is String) return false;
|
||||
if (error is SocketException) return false;
|
||||
if (isHmsClientUnavailable(error)) return false;
|
||||
@@ -34,11 +36,23 @@ class ErrorReportPolicy {
|
||||
final t = event.throwable;
|
||||
if (t == null) return true;
|
||||
if (t is DioException) {
|
||||
return _allowSentrySdkDio(t);
|
||||
return !ApiResponseErrorReporter.wasCaptured(t) && _allowSentrySdkDio(t);
|
||||
}
|
||||
return shouldReport(t);
|
||||
}
|
||||
|
||||
static SentryEvent? prepareSentryEvent(SentryEvent event, Hint hint) {
|
||||
if (!allowSentryEvent(event, hint)) return null;
|
||||
if (event.throwable is ApiResponseDecodeException) {
|
||||
// HTTP breadcrumbs могут содержать идентификаторы в пути и параметры запроса.
|
||||
event.breadcrumbs = event.breadcrumbs
|
||||
?.where((breadcrumb) => breadcrumb.category != 'http')
|
||||
.toList();
|
||||
event.request = null;
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
/// Cancel, timeouts, socket / connection errors — do not send (noisy, often user environment).
|
||||
static bool _isTransientDioFailure(DioException e) {
|
||||
switch (e.type) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/prefs.dart';
|
||||
@@ -103,7 +104,7 @@ class OtherRoutes {
|
||||
redirect: (context, state) async {
|
||||
try {
|
||||
// Проверка версии с таймаутом, чтобы не блокировать запуск приложения
|
||||
final versions = await sl<Dio>()
|
||||
final response = await sl<Dio>()
|
||||
.get('${sl<AppConfig>().baseUrl}/api/app_versions')
|
||||
.timeout(
|
||||
const Duration(seconds: 5),
|
||||
@@ -111,12 +112,8 @@ class OtherRoutes {
|
||||
// При таймауте пропускаем проверку и идем дальше
|
||||
throw TimeoutException('Version check timeout');
|
||||
},
|
||||
)
|
||||
.then((response) => response.data)
|
||||
.catchError((e) {
|
||||
// При любой ошибке пропускаем проверку версии
|
||||
return null;
|
||||
});
|
||||
);
|
||||
final versions = response.data;
|
||||
|
||||
if (versions == null) {
|
||||
// Если проверка не удалась, пропускаем экран обновления
|
||||
@@ -126,7 +123,15 @@ class OtherRoutes {
|
||||
PackageInfo packageInfo = await PackageInfo.fromPlatform();
|
||||
String version = packageInfo.version;
|
||||
Version currentVersion = Version.parse(version);
|
||||
Version latestVersion = Version.parse(versions['min_version']);
|
||||
final responseErrors = sl.isRegistered<ApiResponseErrorReporter>()
|
||||
? sl<ApiResponseErrorReporter>()
|
||||
: null;
|
||||
final latestVersion = ApiResponseErrorReporter.decode(
|
||||
responseErrors,
|
||||
response,
|
||||
'/api/app_versions',
|
||||
() => Version.parse(versions['min_version']),
|
||||
);
|
||||
if (latestVersion > currentVersion) {
|
||||
return null;
|
||||
} else {
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'views_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class ViewsService {
|
||||
factory ViewsService(Dio dio, {String baseUrl}) = _ViewsService;
|
||||
factory ViewsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _ViewsService;
|
||||
|
||||
@POST('/api/views')
|
||||
Future<void> viewContent({
|
||||
|
||||
@@ -8,7 +8,11 @@ part 'ws_service.g.dart';
|
||||
@RestApi()
|
||||
abstract class WsService {
|
||||
|
||||
factory WsService(Dio dio, {String baseUrl}) = _WsService;
|
||||
factory WsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _WsService;
|
||||
|
||||
@GET('/api/profile/ws/params')
|
||||
Future<WebsocketInfoModel> getWebsocket();
|
||||
|
||||
@@ -12,7 +12,11 @@ part 'auth_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class AuthService {
|
||||
factory AuthService(Dio dio, {String? baseUrl}) = _AuthService;
|
||||
factory AuthService(
|
||||
Dio dio, {
|
||||
String? baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _AuthService;
|
||||
|
||||
@POST('/api/login')
|
||||
Future<TokenModel> getTokenByCredentials({@Body() required CredentialsModel credentials});
|
||||
|
||||
@@ -5,7 +5,11 @@ part 'reset_password_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class ResetPasswordService {
|
||||
factory ResetPasswordService(Dio dio, {String baseUrl}) = _ResetPasswordService;
|
||||
factory ResetPasswordService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _ResetPasswordService;
|
||||
|
||||
@POST('/api/send_password_reset_code')
|
||||
Future<HttpResponse> sendEmailCodeForPasswordChange({
|
||||
|
||||
@@ -1,24 +1,28 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/features/barcode/models/barcode_product_model.dart';
|
||||
import 'package:retrofit/retrofit.dart';
|
||||
|
||||
part 'barcode_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class BarcodeService {
|
||||
factory BarcodeService(Dio dio, {String baseUrl}) = _BarcodeService;
|
||||
|
||||
@GET('/api/gsone/barcode/{barcode}')
|
||||
Future<BarcodeProductModel> getProductByBarcode({@Path('barcode') required String barcode});
|
||||
|
||||
@GET('/api/gsone/barcode/status/{task_id}')
|
||||
Future<BarcodeTaskStatusModel> getTaskStatus({@Path('task_id') required String taskId});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/features/barcode/models/barcode_product_model.dart';
|
||||
import 'package:retrofit/retrofit.dart';
|
||||
|
||||
part 'barcode_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class BarcodeService {
|
||||
factory BarcodeService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _BarcodeService;
|
||||
|
||||
@GET('/api/gsone/barcode/{barcode}')
|
||||
Future<BarcodeProductModel> getProductByBarcode({@Path('barcode') required String barcode});
|
||||
|
||||
@GET('/api/gsone/barcode/status/{task_id}')
|
||||
Future<BarcodeTaskStatusModel> getTaskStatus({@Path('task_id') required String taskId});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,11 @@ part 'blog_post_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class BlogPostService {
|
||||
factory BlogPostService(Dio dio, {String baseUrl}) = _BlogPostService;
|
||||
factory BlogPostService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _BlogPostService;
|
||||
|
||||
@POST('/api/v2/blogPosts/create/published')
|
||||
@MultiPart()
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'calendar_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class CalendarService {
|
||||
factory CalendarService(Dio dio, {String baseUrl}) = _CalendarService;
|
||||
factory CalendarService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _CalendarService;
|
||||
|
||||
@GET('/api/calendar/index')
|
||||
Future<List<CalendarModel>> getCalendar();
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'cancel_plan_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class CancelPlanService {
|
||||
factory CancelPlanService(Dio dio, {String baseUrl}) = _CancelPlanService;
|
||||
factory CancelPlanService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _CancelPlanService;
|
||||
|
||||
@POST('/api/chosen_plans/{id}/cancel')
|
||||
Future<void> cancelChosenPlan({
|
||||
|
||||
@@ -30,6 +30,7 @@ import 'package:eatvio_app/features/chat/utils/chat_counterpart_utils.dart';
|
||||
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
|
||||
import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart';
|
||||
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
|
||||
import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart';
|
||||
import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart';
|
||||
@@ -72,6 +73,10 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
|
||||
String? get conversationUuid => _effectiveUuid ?? widget.uuid;
|
||||
|
||||
bool _canStartVideoCall(ChosenPlanModel? chosenPlan) {
|
||||
return chosenPlan?.chosenPlanState.allowsVideoCall ?? false;
|
||||
}
|
||||
|
||||
void _onHide() {
|
||||
chatRoomCubit.cancelTimer();
|
||||
}
|
||||
@@ -205,6 +210,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
chosenPlan != null &&
|
||||
chosenPlan.chosenPlanState !=
|
||||
ChosenPlanStateEnum.stateCanceledByTheInitiator;
|
||||
final showVideoCallButton = _canStartVideoCall(chosenPlan);
|
||||
|
||||
return Scaffold(
|
||||
resizeToAvoidBottomInset: true,
|
||||
@@ -300,12 +306,14 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 8),
|
||||
child: _ChatHeaderVideoCallButton(
|
||||
onPressed: () => _openVideoCall(context, state, chatCounterpart),
|
||||
if (showVideoCallButton)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 8),
|
||||
child: _ChatHeaderVideoCallButton(
|
||||
onPressed: () =>
|
||||
_openVideoCall(context, state, chatCounterpart),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: SafeArea(
|
||||
@@ -324,8 +332,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
InfoByOrderScreen.path,
|
||||
extra: {
|
||||
'planId': chosenPlan?.id,
|
||||
'customerSlug':
|
||||
state.chatRoom.users.receiver.slug,
|
||||
'customerSlug': state.chatRoom.users.receiver.slug,
|
||||
},
|
||||
);
|
||||
return;
|
||||
@@ -1018,7 +1025,8 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
required bool? amIConsultant,
|
||||
}) {
|
||||
if (message.type == ChatMessageType.videoCallStarted &&
|
||||
!isCurrentUserAuthor) {
|
||||
!isCurrentUserAuthor &&
|
||||
_canStartVideoCall(state.chatRoom.chosenPlan)) {
|
||||
return VideoCallChatMessageWidget(
|
||||
text: message.data.trim(),
|
||||
sendTime: message.updatedAt,
|
||||
|
||||
@@ -17,7 +17,11 @@ part 'chat_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class ChatService {
|
||||
factory ChatService(Dio dio, {String baseUrl}) = _ChatService;
|
||||
factory ChatService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _ChatService;
|
||||
|
||||
@GET('/api/v2/chat/index')
|
||||
Future<ChatRoomPaginationModel> getChatRooms({
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'complaining_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class ComplainingService {
|
||||
factory ComplainingService(Dio dio, {String baseUrl}) = _ComplainingService;
|
||||
factory ComplainingService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _ComplainingService;
|
||||
|
||||
@POST('/api/plans/{slug}/complain/{category}')
|
||||
Future<void> sendPlanComplain({
|
||||
|
||||
@@ -9,7 +9,11 @@ part 'consultant_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class ConsultantService {
|
||||
factory ConsultantService(Dio dio, {String baseUrl}) = _ConsultantService;
|
||||
factory ConsultantService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _ConsultantService;
|
||||
|
||||
@POST('/api/v2/consultant_request/registration')
|
||||
Future<void> consultantRegistration({
|
||||
|
||||
@@ -8,7 +8,11 @@ part 'consultant_rating_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class ConsultantRatingService {
|
||||
factory ConsultantRatingService(Dio dio, {String baseUrl}) = _ConsultantRatingService;
|
||||
factory ConsultantRatingService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _ConsultantRatingService;
|
||||
|
||||
@GET('/api/consultants/rating/statistics')
|
||||
Future<StatisticsModel> getConsultantStatistics({@Query('filters[duration][\$gte]') String? date});
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'create_diet_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class CreateDietService {
|
||||
factory CreateDietService(Dio dio, {String baseUrl}) = _CreateDietService;
|
||||
factory CreateDietService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _CreateDietService;
|
||||
|
||||
@POST('/api/diets/create/published')
|
||||
@MultiPart()
|
||||
|
||||
@@ -5,7 +5,11 @@ part 'create_plan_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class CreatePlanService {
|
||||
factory CreatePlanService(Dio dio, {String baseUrl}) = _CreatePlanService;
|
||||
factory CreatePlanService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _CreatePlanService;
|
||||
|
||||
@POST('/api/plans/create/published')
|
||||
@MultiPart()
|
||||
|
||||
@@ -8,7 +8,11 @@ part 'recipe_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class CreateRecipeService {
|
||||
factory CreateRecipeService(Dio dio, {String baseUrl}) = _CreateRecipeService;
|
||||
factory CreateRecipeService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _CreateRecipeService;
|
||||
|
||||
@POST('/api/recipes/{slug}/like')
|
||||
Future<void> likeRecipe({
|
||||
|
||||
@@ -14,6 +14,7 @@ import 'package:eatvio_app/features/diary/models/nutrition_model.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart';
|
||||
import 'package:eatvio_app/features/diary/repositories/diary_repository.dart';
|
||||
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
|
||||
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/glossary/models/glossary_model.dart';
|
||||
import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart';
|
||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||
@@ -38,6 +39,8 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
final ChatRepository chatRepository;
|
||||
final SettingsRepository settingsRepository;
|
||||
int? diaryId;
|
||||
int _fetchGeneration = 0;
|
||||
|
||||
DiaryCubit({
|
||||
required this.chatRepository,
|
||||
required this.diaryRepository,
|
||||
@@ -61,14 +64,21 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
selectedDay = date;
|
||||
}
|
||||
|
||||
bool _isCurrentFetch(int generation) => generation == _fetchGeneration;
|
||||
|
||||
Future<bool> setSelectedDay(DateTime day) async {
|
||||
final prevDay = selectedDay;
|
||||
final prevMeal = selectedMeal;
|
||||
selectedDay = day;
|
||||
selectedMeal = 1;
|
||||
final canSelect = await fetchDiaryV2(needLoading: true);
|
||||
final generation = ++_fetchGeneration;
|
||||
final canSelect = await fetchDiaryV2(needLoading: true, generation: generation);
|
||||
|
||||
if (!canSelect) {
|
||||
if (!_isCurrentFetch(generation)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!canSelect && state is! DiaryStateError) {
|
||||
selectedDay = prevDay;
|
||||
selectedMeal = prevMeal;
|
||||
}
|
||||
@@ -76,22 +86,33 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
return canSelect;
|
||||
}
|
||||
|
||||
Future<bool> fetchDiaryV2({bool needLoading = false, int? diaryId}) async {
|
||||
Future<bool> fetchDiaryV2({bool needLoading = false, int? diaryId, int? generation}) async {
|
||||
final request = generation ?? ++_fetchGeneration;
|
||||
final requestedDay = selectedDay;
|
||||
final currentState = state;
|
||||
try {
|
||||
if (!_isCurrentFetch(request)) {
|
||||
return false;
|
||||
}
|
||||
if (needLoading) {
|
||||
emit(const DiaryState.loading());
|
||||
}
|
||||
if (diaryId != null) {
|
||||
final diaryDayById = await diaryRepository.getDiaryDay(diaryId);
|
||||
if (!_isCurrentFetch(request)) {
|
||||
return false;
|
||||
}
|
||||
final diaryEntity = diaryDayById.toEntity();
|
||||
if (diaryEntity != null) {
|
||||
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
|
||||
return true;
|
||||
await setDiary(diaryDay: diaryEntity, diaryId: diaryId, generation: request);
|
||||
return _isCurrentFetch(request);
|
||||
}
|
||||
}
|
||||
|
||||
final diaryDay = await getDiary();
|
||||
final diaryDay = await getDiary(day: requestedDay);
|
||||
if (!_isCurrentFetch(request)) {
|
||||
return false;
|
||||
}
|
||||
if (diaryDay == null) {
|
||||
emit(const DiaryState.error(errorMessage: 'Diary not found'));
|
||||
return true;
|
||||
@@ -99,16 +120,26 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
|
||||
final diaryEntity = diaryDay.toEntity();
|
||||
if (diaryEntity != null) {
|
||||
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
|
||||
return true;
|
||||
await setDiary(diaryDay: diaryEntity, diaryId: diaryId, generation: request);
|
||||
return _isCurrentFetch(request);
|
||||
}
|
||||
if (diaryDay.typeOfDiary.hasChosenDiet == true && diaryDay.typeOfDiary.diaryState == null) {
|
||||
setDiaryForDietOnly(diaryDay.toDiaryFutureDayEntity());
|
||||
return true;
|
||||
|
||||
if (_isUnsavedDietPreview(diaryDay)) {
|
||||
final shown = await setDiaryForDietOnly(diaryDay.toDiaryFutureDayEntity(), generation: request);
|
||||
if (!_isCurrentFetch(request)) {
|
||||
return false;
|
||||
}
|
||||
if (!shown && state is DiaryStateLoading) {
|
||||
emit(currentState);
|
||||
}
|
||||
return shown;
|
||||
}
|
||||
emit(currentState);
|
||||
return false;
|
||||
} catch (e, st) {
|
||||
if (!_isCurrentFetch(request)) {
|
||||
return false;
|
||||
}
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
emit(DiaryState.error(errorMessage: e.toString()));
|
||||
@@ -129,17 +160,18 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<DiaryDayModel?> getDiary() async {
|
||||
Future<DiaryDayModel?> getDiary({DateTime? day}) async {
|
||||
final requestedDay = (day ?? selectedDay).toISO8601WithTimeZoneOffset();
|
||||
try {
|
||||
await diaryRepository.createDiaryDay(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
await diaryRepository.createDiaryDay(day: requestedDay);
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: requestedDay);
|
||||
return diaryDay;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
if (e is DioException) {
|
||||
if (e.response?.statusCode == 422) {
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: requestedDay);
|
||||
return diaryDay;
|
||||
}
|
||||
}
|
||||
@@ -157,92 +189,83 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> setDiaryForDietOnly(DiaryFutureDietDayEntity diaryDay) async {
|
||||
if (!diaryDay.typeOfDiary.hasChosenDiet) {
|
||||
bool _isUnsavedDietPreview(DiaryDayModel diaryDay) {
|
||||
final diaryState = diaryDay.typeOfDiary.diaryState;
|
||||
final dayNotStarted = diaryState == null || diaryState == DiaryStateEnum.init;
|
||||
return diaryDay.typeOfDiary.hasChosenDiet && dayNotStarted;
|
||||
}
|
||||
|
||||
Future<bool> setDiaryForDietOnly(DiaryFutureDietDayEntity diaryDay, {int? generation}) async {
|
||||
final dietId = diaryDay.diet?.id;
|
||||
final dayOfChosenDiet = diaryDay.dayOfChosenDiet;
|
||||
if (!diaryDay.typeOfDiary.hasChosenDiet || dietId == null || dayOfChosenDiet == null) {
|
||||
return false;
|
||||
}
|
||||
if (generation != null && !_isCurrentFetch(generation)) {
|
||||
return false;
|
||||
}
|
||||
emit(const DiaryState.loading());
|
||||
try {
|
||||
if (diaryDay.diet?.id != null && diaryDay.dayOfChosenDiet != null) {
|
||||
final diet = await dietRepository.getDiet((diaryDay.diet?.id)!);
|
||||
final meals = diet.dailySchedule[diaryDay.dayOfChosenDiet];
|
||||
final firstMealPortions = meals?[1]?.values.map((elem) {
|
||||
return PortionModel(
|
||||
id: 0,
|
||||
productName: elem.name,
|
||||
quantity: elem.quantity,
|
||||
portion: elem.portion.getValue(),
|
||||
fromDiet: true,
|
||||
portionState: PortionState.filledDiet,
|
||||
);
|
||||
}).toList();
|
||||
final diet = await dietRepository.getDiet(dietId);
|
||||
if (generation != null && !_isCurrentFetch(generation)) {
|
||||
return false;
|
||||
}
|
||||
final meals = diet.dailySchedule[dayOfChosenDiet];
|
||||
List<PortionModel> portionsOfMeal(int mealNumber) {
|
||||
return meals?[mealNumber]?.values.map(_portionFromDiet).toList() ?? [];
|
||||
}
|
||||
|
||||
final secondMealPortions = meals?[2]?.values.map((elem) {
|
||||
return PortionModel(
|
||||
id: 0,
|
||||
productName: elem.name,
|
||||
quantity: elem.quantity,
|
||||
portion: elem.portion.getValue(),
|
||||
fromDiet: true,
|
||||
portionState: PortionState.filledDiet,
|
||||
);
|
||||
}).toList();
|
||||
MealModel meal(int mealNumber) {
|
||||
return MealModel(id: 0, time: '0', typeNumber: mealNumber, satiety: 0, mood: 0, portions: portionsOfMeal(mealNumber), photos: []);
|
||||
}
|
||||
|
||||
final thirdMealPortions = meals?[3]?.values.map((elem) {
|
||||
return PortionModel(
|
||||
id: 0,
|
||||
productName: elem.name,
|
||||
quantity: elem.quantity,
|
||||
portion: elem.portion.getValue(),
|
||||
fromDiet: true,
|
||||
portionState: PortionState.filledDiet,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
final fourthMealPortions = meals?[4]?.values.map((elem) {
|
||||
return PortionModel(
|
||||
id: 0,
|
||||
productName: elem.name,
|
||||
quantity: elem.quantity,
|
||||
portion: elem.portion.getValue(),
|
||||
fromDiet: true,
|
||||
portionState: PortionState.filledDiet,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
final fifthMealPortions = meals?[5]?.values.map((elem) {
|
||||
return PortionModel(
|
||||
id: 0,
|
||||
productName: elem.name,
|
||||
quantity: elem.quantity,
|
||||
portion: elem.portion.getValue(),
|
||||
fromDiet: true,
|
||||
portionState: PortionState.filledDiet,
|
||||
);
|
||||
}).toList();
|
||||
final firstMeal = MealModel(id: 0, time: '0', typeNumber: 1, satiety: 0, mood: 0, portions: firstMealPortions ?? [], photos: []);
|
||||
final secondMeal = MealModel(id: 0, time: '0', typeNumber: 2, satiety: 0, mood: 0, portions: secondMealPortions ?? [], photos: []);
|
||||
final thirdMeal = MealModel(id: 0, time: '0', typeNumber: 3, satiety: 0, mood: 0, portions: thirdMealPortions ?? [], photos: []);
|
||||
final fourthMeal = MealModel(id: 0, time: '0', typeNumber: 4, satiety: 0, mood: 0, portions: fourthMealPortions ?? [], photos: []);
|
||||
final fifthMeal = MealModel(id: 0, time: '0', typeNumber: 5, satiety: 0, mood: 0, portions: fifthMealPortions ?? [], photos: []);
|
||||
emit(
|
||||
DiaryState.loadedTomorrowWithDiet(
|
||||
diary: diaryDay.copyWith(meals: [firstMeal, secondMeal, thirdMeal, fourthMeal, fifthMeal]),
|
||||
diary: diaryDay.copyWith(meals: [meal(1), meal(2), meal(3), meal(4), meal(5)]),
|
||||
selectedDay: selectedDay,
|
||||
selectedMeal: selectedMeal,
|
||||
),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
if (generation != null && !_isCurrentFetch(generation)) {
|
||||
return false;
|
||||
}
|
||||
await reportFrom(e, st, this);
|
||||
emit(DiaryState.error(errorMessage: e.toString()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setDiary({int? diaryId, required DiaryDayEntity diaryDay}) async {
|
||||
PortionModel _portionFromDiet(DailySchedule elem) {
|
||||
final nutrition = elem.dailyNutrition;
|
||||
final per100 = elem.portion == Portion.grams && elem.quantity > 0 ? 100 / elem.quantity : 1.0;
|
||||
return PortionModel(
|
||||
id: 0,
|
||||
productNutritionalValueId: elem.productNutritionalValueId,
|
||||
productCaloriesInfo: nutrition == null
|
||||
? null
|
||||
: ProductCaloriesInfoModel(
|
||||
id: elem.productNutritionalValueId ?? 0,
|
||||
productName: elem.name,
|
||||
calories: nutrition.energy * per100,
|
||||
proteins: nutrition.proteins * per100,
|
||||
fats: nutrition.fats * per100,
|
||||
carbohydrates: nutrition.carbohydrates * per100,
|
||||
energyOnPortion: nutrition.energy,
|
||||
proteinsOnPortion: nutrition.proteins,
|
||||
fatsOnPortion: nutrition.fats,
|
||||
carbohydratesOnPortion: nutrition.carbohydrates,
|
||||
),
|
||||
productName: elem.name,
|
||||
quantity: elem.quantity,
|
||||
portion: elem.portion.getValue(),
|
||||
fromDiet: true,
|
||||
portionState: PortionState.filledDiet,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setDiary({int? diaryId, required DiaryDayEntity diaryDay, int? generation}) async {
|
||||
this.diaryId ??= diaryId;
|
||||
final isConsultantView = this.diaryId != null;
|
||||
try {
|
||||
@@ -270,6 +293,9 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
currentPlanDay = consultantReview.currentPlanDay;
|
||||
}
|
||||
final nutrition = await getNutrition(diaryDay.id);
|
||||
if (generation != null && !_isCurrentFetch(generation)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final isDiaryFinished = diaryDay.typeOfDiary.diaryState == DiaryStateEnum.finished || diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayFinished;
|
||||
|
||||
@@ -295,6 +321,9 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
),
|
||||
);
|
||||
} catch (e, st) {
|
||||
if (generation != null && !_isCurrentFetch(generation)) {
|
||||
return;
|
||||
}
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
emit(DiaryState.error(errorMessage: e.toString()));
|
||||
|
||||
@@ -22,12 +22,26 @@ class _CalendarWidgetState extends State<CalendarWidget> {
|
||||
CalendarFormat _calendarFormat = CalendarFormat.week;
|
||||
DateTime _focusedDay = DateTime.now();
|
||||
DateTime _selectedDay = DateTime.now();
|
||||
DateTime? _dayFromState(DiaryState state) {
|
||||
if (state is DiaryStateLoaded) {
|
||||
return state.selectedDay;
|
||||
}
|
||||
if (state is DiaryStateLoadedTomorrowWithDiet) {
|
||||
return state.selectedDay;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final selected = _dayFromState(context.read<DiaryCubit>().state);
|
||||
if (widget.date != null) {
|
||||
_selectedDay = widget.date!;
|
||||
_focusedDay = widget.date!;
|
||||
} else if (selected != null) {
|
||||
_selectedDay = selected;
|
||||
_focusedDay = selected;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,9 +61,11 @@ class _CalendarWidgetState extends State<CalendarWidget> {
|
||||
final daysOfWeekHeight = _scaledDaysOfWeekHeight(context);
|
||||
return BlocConsumer<DiaryCubit, DiaryState>(
|
||||
listener: (BuildContext context, DiaryState state) {
|
||||
if (state is DiaryStateLoaded) {
|
||||
final selected = _dayFromState(state);
|
||||
if (selected != null) {
|
||||
setState(() {
|
||||
_selectedDay = state.selectedDay;
|
||||
_selectedDay = selected;
|
||||
_focusedDay = selected;
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -77,8 +93,12 @@ class _CalendarWidgetState extends State<CalendarWidget> {
|
||||
_selectedDay = selectedDay;
|
||||
_focusedDay = focusedDay;
|
||||
});
|
||||
final canOpenNextDay = await context.read<DiaryCubit>().setSelectedDay(selectedDay);
|
||||
if (!canOpenNextDay && context.mounted) {
|
||||
final cubit = context.read<DiaryCubit>();
|
||||
final canOpenNextDay = await cubit.setSelectedDay(selectedDay);
|
||||
if (!context.mounted || cubit.state is DiaryStateError) {
|
||||
return;
|
||||
}
|
||||
if (!canOpenNextDay) {
|
||||
showErrorDialog(context, title: s.want_to_see_tomorrow, description: s.can_not_see_next_day);
|
||||
setState(() {
|
||||
_selectedDay = previousSelectedDay;
|
||||
|
||||
@@ -13,7 +13,11 @@ part 'diary_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class DiaryService {
|
||||
factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService;
|
||||
factory DiaryService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _DiaryService;
|
||||
|
||||
@GET('/api/diary/index/{date}')
|
||||
Future<List<DiaryDayModel>> getDiaryIndexByDate({@Path('date') required String date});
|
||||
|
||||
@@ -7,7 +7,11 @@ part 'diet_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class DietService {
|
||||
factory DietService(Dio dio, {String baseUrl}) = _DietService;
|
||||
factory DietService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _DietService;
|
||||
|
||||
@POST('/api/diets/{id}/like')
|
||||
Future<DietLikesModel> likeDiet({
|
||||
|
||||
@@ -14,7 +14,11 @@ part 'feed_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class FeedService {
|
||||
factory FeedService(Dio dio, {String baseUrl}) = _FeedService;
|
||||
factory FeedService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _FeedService;
|
||||
|
||||
@GET('/api/blogPosts/index')
|
||||
Future<FeedBlogPostSettingsModel> getBlogPostList({@Query('page') required int page, @Query('query_search') String? query});
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'glossary_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class GlossaryService {
|
||||
factory GlossaryService(Dio dio, {String baseUrl}) = _GlossaryService;
|
||||
factory GlossaryService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _GlossaryService;
|
||||
|
||||
@GET('/api/glossaries/search')
|
||||
Future<GlossaryPaginationModel> getGlossaryByQuery({
|
||||
|
||||
@@ -9,7 +9,11 @@ part 'insights_service.g.dart';
|
||||
/// недоступный профиль — 403.
|
||||
@RestApi()
|
||||
abstract class InsightsService {
|
||||
factory InsightsService(Dio dio, {String baseUrl}) = _InsightsService;
|
||||
factory InsightsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _InsightsService;
|
||||
|
||||
/// Свои графики целиком.
|
||||
@GET('/api/profile/insights')
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'blocked_users_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class BlockedUserService {
|
||||
factory BlockedUserService(Dio dio, {String baseUrl}) = _BlockedUserService;
|
||||
factory BlockedUserService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _BlockedUserService;
|
||||
|
||||
@GET('/api/blocked_users')
|
||||
Future<BlockedUsersModel> getBlockedUsers();
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'notification_settings_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class NotificationSettingsService {
|
||||
factory NotificationSettingsService(Dio dio, {String baseUrl}) = _NotificationSettingsService;
|
||||
factory NotificationSettingsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _NotificationSettingsService;
|
||||
|
||||
@GET('/api/profile/notification_settings')
|
||||
Future<NotificationSettingsModel> getNotificationSettings();
|
||||
|
||||
@@ -7,7 +7,11 @@ part 'my_diets_service.g.dart';
|
||||
@RestApi()
|
||||
abstract class MyDietsService {
|
||||
|
||||
factory MyDietsService(Dio dio, {String baseUrl}) = _MyDietsService;
|
||||
factory MyDietsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _MyDietsService;
|
||||
|
||||
@GET('/api/profile/my_diets')
|
||||
Future<DietsPagination> getDiets({
|
||||
|
||||
@@ -7,7 +7,11 @@ part 'cards_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class CardsService {
|
||||
factory CardsService(Dio dio, {String baseUrl}) = _CardsService;
|
||||
factory CardsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _CardsService;
|
||||
|
||||
@GET('/api/finances/cards')
|
||||
Future<List<CardModel>> getCards();
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'my_plans_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class MyPlansService {
|
||||
factory MyPlansService(Dio dio, {String baseUrl}) = _MyPlansService;
|
||||
factory MyPlansService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _MyPlansService;
|
||||
|
||||
@GET('/api/profile/my_plans')
|
||||
Future<PlanPaginationModel> getPlans({
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart';
|
||||
import 'package:eatvio_app/features/notifications/models/notification_model.dart';
|
||||
|
||||
class NotificationsService {
|
||||
final Dio dio;
|
||||
NotificationsService(this.dio);
|
||||
final ApiResponseErrorReporter? responseErrors;
|
||||
static const _endpoint = '/api/profile/notifications';
|
||||
|
||||
NotificationsService(this.dio, {this.responseErrors});
|
||||
|
||||
Future<Map<String, dynamic>?> getNotifications({required int page}) async {
|
||||
final response = await dio.get('$_endpoint?page=$page');
|
||||
try {
|
||||
final response = await dio.get('/api/profile/notifications?page=$page');
|
||||
if (response.statusCode == 200) {
|
||||
final data = response.data['data'] as List<dynamic>;
|
||||
|
||||
@@ -493,7 +497,14 @@ class NotificationsService {
|
||||
),
|
||||
NotificationType.unknown => UnknownNotification(type: type, createdAt: parseDate(createdAt)),
|
||||
};
|
||||
} catch (e) {
|
||||
} catch (error, stackTrace) {
|
||||
responseErrors?.report(
|
||||
error,
|
||||
stackTrace,
|
||||
method: response.requestOptions.method,
|
||||
statusCode: response.statusCode,
|
||||
endpoint: _endpoint,
|
||||
);
|
||||
return UnknownNotification(type: NotificationType.unknown, createdAt: DateTime.now());
|
||||
}
|
||||
}).toList();
|
||||
@@ -510,7 +521,14 @@ class NotificationsService {
|
||||
};
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
} catch (error, stackTrace) {
|
||||
responseErrors?.report(
|
||||
error,
|
||||
stackTrace,
|
||||
method: response.requestOptions.method,
|
||||
statusCode: response.statusCode,
|
||||
endpoint: _endpoint,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart';
|
||||
import 'package:eatvio_app/features/chat/models/payment_model.dart';
|
||||
import 'package:eatvio_app/features/chat/services/chat_service.dart';
|
||||
import 'package:eatvio_app/features/payment/models/promo_applied_list_response.dart';
|
||||
@@ -10,8 +11,9 @@ import 'package:eatvio_app/features/payment/models/promo_validate_response.dart'
|
||||
/// Репозиторий оплаты консультаций (chosen_plan) через Alfa Bank / СБП.
|
||||
class PaymentRepository {
|
||||
final ChatService chatService;
|
||||
final ApiResponseErrorReporter? responseErrors;
|
||||
|
||||
PaymentRepository({required this.chatService});
|
||||
PaymentRepository({required this.chatService, this.responseErrors});
|
||||
|
||||
/// Запускает процесс оплаты: POST `/api/chosen_plans/{id}/start_payment_process`
|
||||
/// с `payment_provider: alfa-bank`.
|
||||
@@ -64,9 +66,15 @@ class PaymentRepository {
|
||||
body: {'promo_code': promoCode},
|
||||
);
|
||||
} on DioException catch (e) {
|
||||
final data = e.response?.data;
|
||||
if (data is Map<String, dynamic>) {
|
||||
return PromoApplyResponse.fromJson(data);
|
||||
final response = e.response;
|
||||
final data = response?.data;
|
||||
if (response != null && data is Map<String, dynamic>) {
|
||||
return ApiResponseErrorReporter.decode(
|
||||
responseErrors,
|
||||
response,
|
||||
'/api/chosen_plans/{id}/apply_promo',
|
||||
() => PromoApplyResponse.fromJson(data),
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
@@ -77,9 +85,15 @@ class PaymentRepository {
|
||||
try {
|
||||
return await chatService.removePromoCode(id: planId);
|
||||
} on DioException catch (e) {
|
||||
final data = e.response?.data;
|
||||
if (data is Map<String, dynamic>) {
|
||||
return PromoRemoveResponse.fromJson(data);
|
||||
final response = e.response;
|
||||
final data = response?.data;
|
||||
if (response != null && data is Map<String, dynamic>) {
|
||||
return ApiResponseErrorReporter.decode(
|
||||
responseErrors,
|
||||
response,
|
||||
'/api/chosen_plans/{id}/remove_promo_code',
|
||||
() => PromoRemoveResponse.fromJson(data),
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,11 @@ part 'personal_diet_suggestion_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class PersonalDietSuggestionService {
|
||||
factory PersonalDietSuggestionService(Dio dio, {String? baseUrl}) =
|
||||
_PersonalDietSuggestionService;
|
||||
factory PersonalDietSuggestionService(
|
||||
Dio dio, {
|
||||
String? baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _PersonalDietSuggestionService;
|
||||
|
||||
@GET('/api/consultations')
|
||||
Future<ConsultationPaginationModel> getConsultationWithPersonalDiets({
|
||||
|
||||
@@ -88,6 +88,18 @@ enum ChosenPlanStateEnum {
|
||||
}
|
||||
}
|
||||
|
||||
bool get allowsVideoCall {
|
||||
switch (this) {
|
||||
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||
case ChosenPlanStateEnum.statePaymentFailed:
|
||||
case ChosenPlanStateEnum.stateDone:
|
||||
case ChosenPlanStateEnum.stateChargeWasCollected:
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
static List<ChosenPlanStateEnum> getActiveStates() {
|
||||
return [
|
||||
ChosenPlanStateEnum.statePaid,
|
||||
|
||||
@@ -7,7 +7,11 @@ part 'plan_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class PlanService {
|
||||
factory PlanService(Dio dio, {String baseUrl}) = _PlanService;
|
||||
factory PlanService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _PlanService;
|
||||
|
||||
@GET('/api/plans/show/{slug}')
|
||||
Future<PlanModel> getPlan(@Path('slug') String slug);
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'plans_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class PlansService {
|
||||
factory PlansService(Dio dio, {String baseUrl}) = _PlansService;
|
||||
factory PlansService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _PlansService;
|
||||
|
||||
@GET('/api/plans/get_by_author/{author}')
|
||||
Future<PlanPaginationModel> getPlansBySlug({
|
||||
|
||||
@@ -14,7 +14,11 @@ part 'profile_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class ProfileService {
|
||||
factory ProfileService(Dio dio, {String baseUrl}) = _ProfileService;
|
||||
factory ProfileService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _ProfileService;
|
||||
|
||||
@GET('/api/profile/show/{slug}')
|
||||
Future<ProfileModel> getProfileBySlug({@Path() required String slug});
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'about_recipe_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class AboutRecipeService {
|
||||
factory AboutRecipeService(Dio dio, {String baseUrl}) = _AboutRecipeService;
|
||||
factory AboutRecipeService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _AboutRecipeService;
|
||||
|
||||
@POST('/api/recipes/{slug}/like')
|
||||
Future<void> likeRecipe({
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'my_recipes_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class MyRecipesService {
|
||||
factory MyRecipesService(Dio dio, {String baseUrl}) = _MyRecipesService;
|
||||
factory MyRecipesService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _MyRecipesService;
|
||||
|
||||
@GET('/api/recipes/my')
|
||||
Future<MyRecipePaginationModel> getMyRecipes();
|
||||
|
||||
@@ -6,7 +6,11 @@ part 'registration_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class RegistrationService {
|
||||
factory RegistrationService(Dio dio, {String baseUrl}) = _RegistrationService;
|
||||
factory RegistrationService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _RegistrationService;
|
||||
|
||||
@POST('/api/register')
|
||||
Future<Map<String, String>> register({
|
||||
|
||||
@@ -5,7 +5,11 @@ part 'registration_service_v2.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class RegistrationServiceV2 {
|
||||
factory RegistrationServiceV2(Dio dio, {String baseUrl}) = _RegistrationServiceV2;
|
||||
factory RegistrationServiceV2(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _RegistrationServiceV2;
|
||||
|
||||
@POST('/api/register')
|
||||
Future<Map<String, String>> register({
|
||||
|
||||
@@ -9,7 +9,11 @@ part 'settings_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class SettingsService {
|
||||
factory SettingsService(Dio dio, {String baseUrl}) = _SettingsService;
|
||||
factory SettingsService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _SettingsService;
|
||||
|
||||
@GET('/api/profile/settings')
|
||||
Future<ProfileSettingsModel> getProfileSettings();
|
||||
|
||||
@@ -61,6 +61,9 @@ class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> {
|
||||
return;
|
||||
}
|
||||
final position = _scrollController.position;
|
||||
if (position.maxScrollExtent <= 0 || position.pixels < 0) {
|
||||
return;
|
||||
}
|
||||
if (position.pixels >= position.maxScrollExtent - 200) {
|
||||
context.read<VideoCallRecordingsCubit>().loadNextPage();
|
||||
}
|
||||
@@ -170,14 +173,29 @@ class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> {
|
||||
}
|
||||
|
||||
if (state.recordings.isEmpty) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
s.video_call_recordings_empty,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400),
|
||||
),
|
||||
return RefreshIndicator(
|
||||
onRefresh: () => context.read<VideoCallRecordingsCubit>().load(refresh: true),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: [
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(minHeight: constraints.maxHeight),
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
s.video_call_recordings_empty,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -186,6 +204,7 @@ class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> {
|
||||
onRefresh: () => context.read<VideoCallRecordingsCubit>().load(refresh: true),
|
||||
child: ListView.separated(
|
||||
controller: _scrollController,
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
|
||||
itemCount: state.recordings.length + (state.isLoadingMore ? 1 : 0),
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 16),
|
||||
|
||||
@@ -8,7 +8,7 @@ class PublicDownloadsSaver {
|
||||
const PublicDownloadsSaver();
|
||||
|
||||
/// Имя папки приложения в Загрузках / Files.
|
||||
static const appFolderName = 'Itvio';
|
||||
static const appFolderName = 'Eatvio';
|
||||
|
||||
Future<String> saveToDownloads({
|
||||
required String sourcePath,
|
||||
|
||||
@@ -19,7 +19,7 @@ class VideoCallRecordingFileService {
|
||||
final Dio dio;
|
||||
final PublicDownloadsSaver downloadsSaver;
|
||||
|
||||
/// Скачивает запись и сохраняет в `Загрузки/Itvio` (Android)
|
||||
/// Скачивает запись и сохраняет в `Загрузки/Eatvio` (Android)
|
||||
/// или Documents приложения (iOS, видно в Files).
|
||||
Future<String> downloadRecordingFile({
|
||||
required String fileUrl,
|
||||
|
||||
@@ -7,7 +7,11 @@ part 'video_call_service.g.dart';
|
||||
|
||||
@RestApi()
|
||||
abstract class VideoCallService {
|
||||
factory VideoCallService(Dio dio, {String baseUrl}) = _VideoCallService;
|
||||
factory VideoCallService(
|
||||
Dio dio, {
|
||||
String baseUrl,
|
||||
ParseErrorLogger? errorLogger,
|
||||
}) = _VideoCallService;
|
||||
|
||||
@GET('/api/v2/chat/{conversation}/video-call/token')
|
||||
Future<VideoCallTokenResponse> getParticipantToken({
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:intl/message_lookup_by_library.dart';
|
||||
import 'package:intl/src/intl_helpers.dart';
|
||||
@@ -21,8 +20,8 @@ import 'messages_ru.dart' as messages_ru;
|
||||
|
||||
typedef Future<dynamic> LibraryLoader();
|
||||
Map<String, LibraryLoader> _deferredLibraries = {
|
||||
'en': () => new SynchronousFuture(null),
|
||||
'ru': () => new SynchronousFuture(null),
|
||||
'en': () => new Future.value(null),
|
||||
'ru': () => new Future.value(null),
|
||||
};
|
||||
|
||||
MessageLookupByLibrary? _findExact(String localeName) {
|
||||
@@ -37,20 +36,18 @@ MessageLookupByLibrary? _findExact(String localeName) {
|
||||
}
|
||||
|
||||
/// User programs should call this before using [localeName] for messages.
|
||||
Future<bool> initializeMessages(String localeName) {
|
||||
Future<bool> initializeMessages(String localeName) async {
|
||||
var availableLocale = Intl.verifiedLocale(
|
||||
localeName,
|
||||
(locale) => _deferredLibraries[locale] != null,
|
||||
onFailure: (_) => null,
|
||||
);
|
||||
localeName, (locale) => _deferredLibraries[locale] != null,
|
||||
onFailure: (_) => null);
|
||||
if (availableLocale == null) {
|
||||
return new SynchronousFuture(false);
|
||||
return new Future.value(false);
|
||||
}
|
||||
var lib = _deferredLibraries[availableLocale];
|
||||
lib == null ? new SynchronousFuture(false) : lib();
|
||||
await (lib == null ? new Future.value(false) : lib());
|
||||
initializeInternalMessageLookup(() => new CompositeMessageLookup());
|
||||
messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor);
|
||||
return new SynchronousFuture(true);
|
||||
return new Future.value(true);
|
||||
}
|
||||
|
||||
bool _messagesExistFor(String locale) {
|
||||
@@ -62,11 +59,8 @@ bool _messagesExistFor(String locale) {
|
||||
}
|
||||
|
||||
MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) {
|
||||
var actualLocale = Intl.verifiedLocale(
|
||||
locale,
|
||||
_messagesExistFor,
|
||||
onFailure: (_) => null,
|
||||
);
|
||||
var actualLocale =
|
||||
Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null);
|
||||
if (actualLocale == null) return null;
|
||||
return _findExact(actualLocale);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -829,7 +829,7 @@
|
||||
}
|
||||
},
|
||||
"video_call_recordings_download_error": "Could not download the recording. Please try again later.",
|
||||
"video_call_recordings_download_success": "Recording saved to Downloads/Itvio",
|
||||
"video_call_recordings_download_success": "Recording saved to Downloads/Eatvio",
|
||||
"video_call_recordings_download_success_ios": "Recording saved to the Files app",
|
||||
"video_call_recordings_player_error": "Could not play the recording",
|
||||
"video_call_recordings_card_title": "Video consultation with a nutrition specialist",
|
||||
|
||||
@@ -584,7 +584,7 @@
|
||||
}
|
||||
},
|
||||
"video_call_recordings_download_error": "Не удалось скачать запись. Попробуйте позже.",
|
||||
"video_call_recordings_download_success": "Запись сохранена в Загрузки/Itvio",
|
||||
"video_call_recordings_download_success": "Запись сохранена в Загрузки/Eatvio",
|
||||
"video_call_recordings_download_success_ios": "Запись сохранена в приложении «Файлы»",
|
||||
"video_call_recordings_player_error": "Не удалось воспроизвести запись",
|
||||
"video_call_recordings_card_title": "Видеоконсультация со специалистом по питанию",
|
||||
|
||||
@@ -16,13 +16,14 @@ import 'package:flutter_portal/flutter_portal.dart';
|
||||
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
FlutterForegroundTask.initCommunicationPort();
|
||||
VideoCallForegroundBootstrap.ensureInitialized();
|
||||
await AppInitializer.initialize(buildType: AppBuildType.prod);
|
||||
await sl<VideoCallCallKitCoordinator>().initialize();
|
||||
await PushNavigationHandler.initialize();
|
||||
await AppInitializer.runAppWithSentry(() => runApp(const MyApp()));
|
||||
await AppInitializer.runAppWithSentry(() async {
|
||||
FlutterForegroundTask.initCommunicationPort();
|
||||
VideoCallForegroundBootstrap.ensureInitialized();
|
||||
await AppInitializer.initialize(buildType: AppBuildType.prod);
|
||||
await sl<VideoCallCallKitCoordinator>().initialize();
|
||||
await PushNavigationHandler.initialize();
|
||||
runApp(const MyApp());
|
||||
});
|
||||
}
|
||||
|
||||
class MyApp extends StatefulWidget {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
name: eatvio_app
|
||||
description: A new Flutter project.
|
||||
version: 1.3.72+161
|
||||
version: 1.3.75+164
|
||||
publish_to: 'none'
|
||||
|
||||
environment:
|
||||
|
||||
311
test/core/error_reporting/api_response_reporting_test.dart
Normal file
311
test/core/error_reporting/api_response_reporting_test.dart
Normal file
@@ -0,0 +1,311 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/app_initializer.dart';
|
||||
import 'package:eatvio_app/core/di/app_config_registration.dart';
|
||||
import 'package:eatvio_app/core/di/external_registrations.dart';
|
||||
import 'package:eatvio_app/core/di/repository_registrations.dart';
|
||||
import 'package:eatvio_app/core/di/service_registrations.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/error_report_policy.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||
import 'package:eatvio_app/core/routing/other_routes.dart';
|
||||
import 'package:eatvio_app/core/routing/route_constants.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/features/notifications/models/notification_model.dart';
|
||||
import 'package:eatvio_app/features/notifications/service/notifications_service.dart';
|
||||
import 'package:eatvio_app/features/payment/repositories/payment_repository.dart';
|
||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||
import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_cubit.dart';
|
||||
import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_state.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late _MemoryTransport transport;
|
||||
late List<SentryEvent> events;
|
||||
|
||||
setUp(() async {
|
||||
transport = _MemoryTransport();
|
||||
events = [];
|
||||
await Sentry.init((options) {
|
||||
options.dsn = 'https://test@example.invalid/1';
|
||||
options.transport = transport;
|
||||
options.sendClientReports = false;
|
||||
// Проверяем дедупликацию в приложении независимо от кеша SDK.
|
||||
options.enableDeduplication = false;
|
||||
options.beforeSend = (event, hint) {
|
||||
final prepared = ErrorReportPolicy.prepareSentryEvent(event, hint);
|
||||
if (prepared != null) events.add(prepared);
|
||||
return prepared;
|
||||
};
|
||||
});
|
||||
|
||||
dotenv.loadFromString(
|
||||
envString: 'DEV_BASE_URL=https://api.example.invalid',
|
||||
);
|
||||
SharedPreferences.setMockInitialValues({
|
||||
PrefsKeys.welcomeScreenWasShowed.name: true,
|
||||
'token': 'synthetic-token',
|
||||
});
|
||||
AppConfigRegistration.registerAppConfig(buildType: AppBuildType.tests);
|
||||
ExternalRegistrations.registerAll();
|
||||
ServiceRegistrations.registerAll();
|
||||
RepositoryRegistrations.registerAll();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
TokenStorage.clearCache();
|
||||
await sl.reset();
|
||||
await Sentry.close();
|
||||
});
|
||||
|
||||
test(
|
||||
'reports a missing recipe field once and keeps the original stack',
|
||||
() async {
|
||||
sl<Dio>().httpClientAdapter = _ResponseAdapter(200, '{}');
|
||||
final cubit = AboutRecipeCubit(
|
||||
recipeRepository: sl(),
|
||||
profileRepository: sl(),
|
||||
);
|
||||
addTearDown(cubit.close);
|
||||
|
||||
await cubit.initRecipe('private-recipe-id');
|
||||
await transport.waitForEvent();
|
||||
|
||||
expect(cubit.state, isA<RecipeStateError>());
|
||||
expect(events.single.tags?['origin'], 'api_response');
|
||||
expect(
|
||||
events.single.exceptions!.single.stackTrace!.frames.any(
|
||||
(frame) => frame.fileName?.endsWith('recipes_model.g.dart') ?? false,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(transport.sent, hasLength(1));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reports a malformed profile even when the welcome redirect handles it',
|
||||
() async {
|
||||
final adapter = _ResponseAdapter(200, '{}');
|
||||
sl<Dio>().httpClientAdapter = adapter;
|
||||
final route = OtherRoutes.createRoutes().whereType<GoRoute>().singleWhere(
|
||||
(route) => route.path == RouteConstants.welcomeScreen,
|
||||
);
|
||||
|
||||
expect(
|
||||
await route.redirect!(_BuildContext(), _RouterState()),
|
||||
RouteConstants.authScreen,
|
||||
);
|
||||
await transport.waitForEvent();
|
||||
|
||||
expect(adapter.requests.single.path, '/api/profile/index');
|
||||
expect(events.single.exceptions!.single.value, contains('TypeError'));
|
||||
expect(transport.sent, hasLength(1));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reports invalid JSON without sending its contents or HTTP breadcrumbs',
|
||||
() async {
|
||||
const secret = 'private-patient-data';
|
||||
sl<Dio>().httpClientAdapter = _ResponseAdapter(200, '{"$secret":');
|
||||
await Sentry.addBreadcrumb(
|
||||
Breadcrumb.http(
|
||||
url: Uri.parse('https://api.example.invalid/user/$secret'),
|
||||
method: 'GET',
|
||||
httpQuery: 'profile=$secret',
|
||||
),
|
||||
);
|
||||
|
||||
await expectLater(
|
||||
sl<ProfileRepository>().getMyProfile(),
|
||||
throwsA(isA<DioException>()),
|
||||
);
|
||||
await transport.waitForEvent();
|
||||
|
||||
final event = events.single;
|
||||
expect(event.exceptions!.single.value, contains('FormatException'));
|
||||
expect(event.exceptions!.single.stackTrace!.frames, isNotEmpty);
|
||||
expect(event.tags?['origin'], 'api_response');
|
||||
expect(
|
||||
event.contexts['report_extras'],
|
||||
containsPair('http_status_code', '200'),
|
||||
);
|
||||
expect(jsonEncode(event.toJson()), isNot(contains(secret)));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reports the wrong JSON root type before the Retrofit model parser',
|
||||
() async {
|
||||
sl<Dio>().httpClientAdapter = _ResponseAdapter(200, '[]');
|
||||
|
||||
await expectLater(
|
||||
sl<ProfileRepository>().getMyProfile(),
|
||||
throwsA(isA<DioException>()),
|
||||
);
|
||||
await transport.waitForEvent();
|
||||
|
||||
expect(events.single.exceptions!.single.value, contains('TypeError'));
|
||||
expect(
|
||||
events.single.contexts['report_extras'],
|
||||
containsPair('http_status_code', '200'),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reports a malformed notification and keeps the replacement item',
|
||||
() async {
|
||||
sl<Dio>().httpClientAdapter = _ResponseAdapter(
|
||||
200,
|
||||
'{"data":[17],"current_page":1,"last_page":1,"per_page":20,"total":1}',
|
||||
);
|
||||
|
||||
final result = await sl<NotificationsService>().getNotifications(page: 1);
|
||||
await transport.waitForEvent();
|
||||
|
||||
expect(
|
||||
(result!['notifications'] as List).single,
|
||||
isA<UnknownNotification>(),
|
||||
);
|
||||
expect(
|
||||
events.single.contexts['report_extras'],
|
||||
containsPair('endpoint', '/api/profile/notifications'),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reports an invalid minimum version and still skips the update screen',
|
||||
() async {
|
||||
PackageInfo.setMockInitialValues(
|
||||
appName: 'Eatvio',
|
||||
packageName: 'example.invalid',
|
||||
version: '1.0.0',
|
||||
buildNumber: '1',
|
||||
buildSignature: '',
|
||||
);
|
||||
sl<Dio>().httpClientAdapter = _ResponseAdapter(
|
||||
200,
|
||||
'{"min_version":"invalid"}',
|
||||
);
|
||||
final route = OtherRoutes.createRoutes().whereType<GoRoute>().singleWhere(
|
||||
(route) => route.path == RouteConstants.updateScreen,
|
||||
);
|
||||
|
||||
expect(
|
||||
await route.redirect!(_BuildContext(), _RouterState()),
|
||||
RouteConstants.welcomeScreen,
|
||||
);
|
||||
await transport.waitForEvent();
|
||||
|
||||
expect(
|
||||
events.single.contexts['report_extras'],
|
||||
containsPair('endpoint', '/api/app_versions'),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reports a malformed 422 promo response after its manual parse',
|
||||
() async {
|
||||
sl<Dio>().httpClientAdapter = _ResponseAdapter(422, '{}');
|
||||
|
||||
await expectLater(
|
||||
sl<PaymentRepository>().applyPromoCode(
|
||||
planId: 42,
|
||||
promoCode: 'private',
|
||||
),
|
||||
throwsA(isA<TypeError>()),
|
||||
);
|
||||
await transport.waitForEvent();
|
||||
|
||||
expect(
|
||||
events.single.contexts['report_extras'],
|
||||
containsPair('http_status_code', '422'),
|
||||
);
|
||||
expect(transport.sent, hasLength(1));
|
||||
},
|
||||
);
|
||||
|
||||
test('keeps expected 4xx quiet and captures a regular 5xx once', () async {
|
||||
final dio = sl<Dio>();
|
||||
final cubit = AboutRecipeCubit(
|
||||
recipeRepository: sl(),
|
||||
profileRepository: sl(),
|
||||
);
|
||||
addTearDown(cubit.close);
|
||||
|
||||
dio.httpClientAdapter = _ResponseAdapter(404, '{}');
|
||||
await cubit.initRecipe('synthetic');
|
||||
expect(events, isEmpty);
|
||||
|
||||
dio.httpClientAdapter = _ResponseAdapter(500, '{}');
|
||||
await cubit.initRecipe('synthetic');
|
||||
await transport.waitForEvent();
|
||||
|
||||
expect(
|
||||
events.single.exceptions!.first.mechanism!.type,
|
||||
'SentryDioClientAdapter',
|
||||
);
|
||||
expect(transport.sent, hasLength(1));
|
||||
});
|
||||
}
|
||||
|
||||
class _ResponseAdapter implements HttpClientAdapter {
|
||||
_ResponseAdapter(this.statusCode, this.body);
|
||||
|
||||
final int statusCode;
|
||||
final String body;
|
||||
final requests = <RequestOptions>[];
|
||||
|
||||
@override
|
||||
Future<ResponseBody> fetch(
|
||||
RequestOptions options,
|
||||
Stream<Uint8List>? requestStream,
|
||||
Future<void>? cancelFuture,
|
||||
) async {
|
||||
requests.add(options);
|
||||
return ResponseBody.fromString(
|
||||
body,
|
||||
statusCode,
|
||||
headers: {
|
||||
Headers.contentTypeHeader: [Headers.jsonContentType],
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void close({bool force = false}) {}
|
||||
}
|
||||
|
||||
class _MemoryTransport implements Transport {
|
||||
final sent = <SentryEnvelope>[];
|
||||
final _firstEvent = Completer<void>();
|
||||
|
||||
Future<void> waitForEvent() =>
|
||||
_firstEvent.future.timeout(const Duration(seconds: 2));
|
||||
|
||||
@override
|
||||
Future<SentryId?> send(SentryEnvelope envelope) async {
|
||||
sent.add(envelope);
|
||||
if (!_firstEvent.isCompleted) _firstEvent.complete();
|
||||
return envelope.header.eventId;
|
||||
}
|
||||
}
|
||||
|
||||
class _BuildContext extends Fake implements BuildContext {}
|
||||
|
||||
class _RouterState extends Fake implements GoRouterState {}
|
||||
@@ -86,6 +86,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -108,6 +109,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -131,6 +133,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -153,6 +156,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -175,6 +179,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -196,6 +201,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -217,6 +223,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -237,6 +244,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -257,6 +265,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pump();
|
||||
await tester.tap(find.byIcon(Icons.more_horiz_rounded));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/pages/chat_screen.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/video_call_chat_message_widget.dart';
|
||||
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
@@ -55,13 +61,57 @@ void main() {
|
||||
|
||||
final fakeBundle = _FakeAssetBundle({
|
||||
'assets/icons/error_icon.svg': fakeSvg,
|
||||
'assets/icons/video_call/vc_control_enter.svg': fakeSvg,
|
||||
});
|
||||
|
||||
const plan = PlanModel(
|
||||
id: 1,
|
||||
slug: 'test-plan',
|
||||
name: 'Test Plan',
|
||||
image: 'https://example.com/image.jpg',
|
||||
duration: 30,
|
||||
state: 'active',
|
||||
type: PlanType(fit: true, slim: false, behavior: false, wellness: false),
|
||||
details: 'Test details',
|
||||
packetsCount: 3,
|
||||
author: Author(
|
||||
authorSlug: 'author',
|
||||
authorName: 'Author Name',
|
||||
authorProfileIcon: 'https://example.com/icon.jpg',
|
||||
authorIsMe: false,
|
||||
),
|
||||
totalLikes: 10,
|
||||
totalViews: 100,
|
||||
totalComments: 5,
|
||||
isFavorite: false,
|
||||
minPriceOfOptions: 1000,
|
||||
maxPriceOfOptions: 2000,
|
||||
wasLikedByMe: false,
|
||||
);
|
||||
|
||||
ChosenPlanModel chosenPlan(ChosenPlanStateEnum state) {
|
||||
return ChosenPlanModel(
|
||||
id: 7,
|
||||
optionType: 'options1',
|
||||
startDate: DateTime(2025, 1, 1),
|
||||
chosenPlanState: state,
|
||||
chatId: '1',
|
||||
consultantId: 2,
|
||||
plan: plan,
|
||||
);
|
||||
}
|
||||
|
||||
Widget wrap(Widget child, ChatsCubit chatsCubit) {
|
||||
return DefaultAssetBundle(
|
||||
bundle: fakeBundle,
|
||||
child: MaterialApp(
|
||||
theme: ThemeHelper().themeData(),
|
||||
locale: const Locale('ru'),
|
||||
localizationsDelegates: const [
|
||||
S.delegate,
|
||||
...GlobalMaterialLocalizations.delegates,
|
||||
],
|
||||
supportedLocales: S.delegate.supportedLocales,
|
||||
home: BlocProvider<ChatsCubit>.value(value: chatsCubit, child: child),
|
||||
),
|
||||
);
|
||||
@@ -202,9 +252,133 @@ void main() {
|
||||
expect(find.text('sending...'), findsOneWidget);
|
||||
expect(find.text('tap to retry'), findsOneWidget);
|
||||
expect(find.text('file.pdf'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.videocam_rounded), findsNothing);
|
||||
VisibilityDetectorController.instance.notifyNow();
|
||||
await tester.pump();
|
||||
});
|
||||
|
||||
Future<void> pumpLoadedChat(
|
||||
WidgetTester tester, {
|
||||
ChosenPlanModel? plan,
|
||||
List<ChatMessageModel> messages = const [],
|
||||
}) async {
|
||||
final chatRoomCubit = MockChatRoomCubit();
|
||||
final chatsCubit = MockChatsCubit();
|
||||
const chatRoom = ChatRoomModel(
|
||||
id: '1',
|
||||
chatRoomSettings: ChatRoomSettingsModel(name: 'room', state: 'active'),
|
||||
users: Users(
|
||||
sender: ChatUserModel(
|
||||
id: 1,
|
||||
name: 'Me',
|
||||
slug: 'me',
|
||||
profilePhotoUrl: null,
|
||||
),
|
||||
receiver: ChatUserModel(
|
||||
id: 2,
|
||||
name: 'User Two',
|
||||
slug: 'user-two',
|
||||
profilePhotoUrl: null,
|
||||
),
|
||||
),
|
||||
chosenPlanId: 7,
|
||||
chosenPlan: null,
|
||||
);
|
||||
final state = ChatRoomState.loaded(
|
||||
chatRoom: chatRoom.copyWith(chosenPlan: plan),
|
||||
chatMessages: messages,
|
||||
hasCard: false,
|
||||
isTyping: false,
|
||||
isLoading: false,
|
||||
);
|
||||
|
||||
when(chatRoomCubit.state).thenReturn(state);
|
||||
when(
|
||||
chatRoomCubit.stream,
|
||||
).thenAnswer((_) => const Stream<ChatRoomState>.empty());
|
||||
when(chatRoomCubit.close()).thenAnswer((_) async => Future<void>.value());
|
||||
when(
|
||||
chatRoomCubit.initChat(
|
||||
any,
|
||||
sendInitialMessage: anyNamed('sendInitialMessage'),
|
||||
orderId: anyNamed('orderId'),
|
||||
),
|
||||
).thenAnswer((_) async => 'uuid');
|
||||
when(chatRoomCubit.setTimer()).thenReturn(null);
|
||||
when(chatRoomCubit.refreshChat()).thenAnswer((_) async {});
|
||||
|
||||
if (sl.isRegistered<ChatRoomCubit>()) {
|
||||
sl.unregister<ChatRoomCubit>();
|
||||
}
|
||||
sl.registerFactory<ChatRoomCubit>(() => chatRoomCubit);
|
||||
|
||||
when(chatsCubit.state).thenReturn(ChatsState());
|
||||
when(chatsCubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
when(chatsCubit.close()).thenAnswer((_) async => Future<void>.value());
|
||||
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
const ChatScreen(uuid: 'uuid', sendInitialMessage: false),
|
||||
chatsCubit,
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
}
|
||||
|
||||
ChatMessageModel incomingCallMessage() {
|
||||
return ChatMessageModel(
|
||||
id: 9,
|
||||
data: 'Видеозвонок',
|
||||
mediaData: const [],
|
||||
authorId: 2,
|
||||
updatedAt: DateTime(2025, 1, 2, 11),
|
||||
isRead: true,
|
||||
isCurrentUserAuthor: false,
|
||||
roomId: '1',
|
||||
type: ChatMessageType.videoCallStarted,
|
||||
messageState: MessageState.sent,
|
||||
uuid: 'call',
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('shows the call button for an active consultation', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpLoadedChat(
|
||||
tester,
|
||||
plan: chosenPlan(ChosenPlanStateEnum.stateInProgress),
|
||||
messages: [incomingCallMessage()],
|
||||
);
|
||||
|
||||
expect(find.byIcon(Icons.videocam_rounded), findsOneWidget);
|
||||
expect(find.byType(VideoCallChatMessageWidget), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('hides the call button for a finished consultation', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpLoadedChat(
|
||||
tester,
|
||||
plan: chosenPlan(ChosenPlanStateEnum.stateDone),
|
||||
messages: [incomingCallMessage()],
|
||||
);
|
||||
|
||||
expect(find.byIcon(Icons.videocam_rounded), findsNothing);
|
||||
expect(find.byType(VideoCallChatMessageWidget), findsNothing);
|
||||
expect(find.text('Видеозвонок'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('hides the call button for a canceled consultation', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpLoadedChat(
|
||||
tester,
|
||||
plan: chosenPlan(ChosenPlanStateEnum.stateCanceledByTheInitiator),
|
||||
);
|
||||
|
||||
expect(find.byIcon(Icons.videocam_rounded), findsNothing);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,11 @@ Widget _wrap(Widget child) {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pump(WidgetTester tester, Widget child) async {
|
||||
await tester.pumpWidget(_wrap(child));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('ChatConsultationHeader', () {
|
||||
testWidgets('вызывает onInfoTap по тапу на info', (tester) async {
|
||||
@@ -27,13 +32,12 @@ void main() {
|
||||
hasPersonalDiet: false,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
ChatConsultationHeader(
|
||||
progress: progress,
|
||||
showInfoButton: true,
|
||||
onInfoTap: () => tapped++,
|
||||
),
|
||||
await _pump(
|
||||
tester,
|
||||
ChatConsultationHeader(
|
||||
progress: progress,
|
||||
showInfoButton: true,
|
||||
onInfoTap: () => tapped++,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -54,13 +58,12 @@ void main() {
|
||||
expect(progress.showProgressPlank, isTrue);
|
||||
expect(progress.dietStatus, PersonalDietStatus.proposed);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
ChatConsultationHeader(
|
||||
progress: progress,
|
||||
showInfoButton: false,
|
||||
onInfoTap: () {},
|
||||
),
|
||||
await _pump(
|
||||
tester,
|
||||
ChatConsultationHeader(
|
||||
progress: progress,
|
||||
showInfoButton: false,
|
||||
onInfoTap: () {},
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@ Widget _wrap(Widget child) {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pump(WidgetTester tester, Widget child) async {
|
||||
await tester.pumpWidget(_wrap(child));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('ConsultationProgressPlank', () {
|
||||
testWidgets('не строит шаги при showProgressPlank=false', (tester) async {
|
||||
@@ -24,9 +29,7 @@ void main() {
|
||||
);
|
||||
expect(progress.showProgressPlank, isFalse);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(ConsultationProgressPlank(progress: progress)),
|
||||
);
|
||||
await _pump(tester, ConsultationProgressPlank(progress: progress));
|
||||
|
||||
expect(
|
||||
find.descendant(
|
||||
@@ -48,9 +51,7 @@ void main() {
|
||||
);
|
||||
expect(progress.showProgressPlank, isTrue);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(ConsultationProgressPlank(progress: progress)),
|
||||
);
|
||||
await _pump(tester, ConsultationProgressPlank(progress: progress));
|
||||
|
||||
final s = S.of(tester.element(find.byType(ConsultationProgressPlank)));
|
||||
|
||||
@@ -70,12 +71,11 @@ void main() {
|
||||
hasPersonalDiet: false,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
SizedBox(
|
||||
width: 360,
|
||||
child: ConsultationProgressPlank(progress: progress),
|
||||
),
|
||||
await _pump(
|
||||
tester,
|
||||
SizedBox(
|
||||
width: 360,
|
||||
child: ConsultationProgressPlank(progress: progress),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@ Widget _wrap(Widget child) {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pump(WidgetTester tester, Widget child) async {
|
||||
await tester.pumpWidget(_wrap(child));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Widget _chip(
|
||||
ChosenPlanStateEnum state, {
|
||||
bool hasPersonalDiet = true,
|
||||
@@ -32,9 +37,7 @@ Widget _chip(
|
||||
void main() {
|
||||
group('PersonalDietStatusChip', () {
|
||||
testWidgets('notRequired + active ничего не показывает', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(_chip(ChosenPlanStateEnum.stateInited, hasPersonalDiet: false)),
|
||||
);
|
||||
await _pump(tester, _chip(ChosenPlanStateEnum.stateInited, hasPersonalDiet: false));
|
||||
|
||||
expect(
|
||||
find.descendant(
|
||||
@@ -47,7 +50,7 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('proposed показывает personal_diet_proposed', (tester) async {
|
||||
await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.stateStarted)));
|
||||
await _pump(tester, _chip(ChosenPlanStateEnum.stateStarted));
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
@@ -55,12 +58,11 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('proposed с названием показывает имя диеты', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
_chip(
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
personalDietName: 'Индивидуальный план питания',
|
||||
),
|
||||
await _pump(
|
||||
tester,
|
||||
_chip(
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
personalDietName: 'Индивидуальный план питания',
|
||||
),
|
||||
);
|
||||
|
||||
@@ -75,7 +77,7 @@ void main() {
|
||||
testWidgets('notProposed показывает personal_diet_not_proposed', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.statePaid)));
|
||||
await _pump(tester, _chip(ChosenPlanStateEnum.statePaid));
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
@@ -83,9 +85,7 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('canceled показывает orderCanceled', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(_chip(ChosenPlanStateEnum.stateCanceledByTheInitiator)),
|
||||
);
|
||||
await _pump(tester, _chip(ChosenPlanStateEnum.stateCanceledByTheInitiator));
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
@@ -93,9 +93,7 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('paymentFailed показывает payment_failed', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(_chip(ChosenPlanStateEnum.statePaymentFailed)),
|
||||
);
|
||||
await _pump(tester, _chip(ChosenPlanStateEnum.statePaymentFailed));
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -34,6 +34,7 @@ void main() {
|
||||
|
||||
testWidgets('показывает заголовок Есть промокод? и кнопки Применить/Пропустить', (tester) async {
|
||||
await tester.pumpWidget(createTestWidget());
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -44,6 +45,7 @@ void main() {
|
||||
|
||||
testWidgets('Применить с пустым полем показывает ошибку и не закрывает', (tester) async {
|
||||
await tester.pumpWidget(createTestWidget());
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -64,6 +66,7 @@ void main() {
|
||||
},
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -78,6 +81,7 @@ void main() {
|
||||
|
||||
testWidgets('Пропустить закрывает шторку', (tester) async {
|
||||
await tester.pumpWidget(createTestWidget());
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -101,6 +105,7 @@ void main() {
|
||||
onRemove: () async => true,
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -128,6 +133,7 @@ void main() {
|
||||
},
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@@ -156,6 +162,7 @@ void main() {
|
||||
},
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
|
||||
@@ -98,6 +98,7 @@ void main() {
|
||||
|
||||
await tester.pumpWidget(createTestWidget(planId: planId));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byType(Loader), findsOneWidget);
|
||||
expect(find.text('Сбербанк'), findsNothing);
|
||||
|
||||
@@ -106,6 +106,7 @@ void main() {
|
||||
|
||||
Future<void> openSheet(WidgetTester tester, {double? amount}) async {
|
||||
await pumpApp(tester, amount: amount);
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('open'));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
|
||||
@@ -5,22 +5,70 @@ void main() {
|
||||
group('ChosenPlanStateEnum', () {
|
||||
test('has all expected values', () {
|
||||
expect(ChosenPlanStateEnum.values.length, 16);
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateInited));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateStartDateHasBeenSet));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateInCoordination));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateStarted));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateInProgress));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.statePendingPayment));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateConfirmedByConsultant));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.statePaid));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateCanceledByTheInitiator));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateLastDayStarted));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateLastDayFinished));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateComplained));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateDone));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.personalDietSet));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateChargeWasCollected));
|
||||
expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.statePaymentFailed));
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateInited),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateStartDateHasBeenSet),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateInCoordination),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateStarted),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateInProgress),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.statePendingPayment),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateConfirmedByConsultant),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.statePaid),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateCanceledByTheInitiator),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateLastDayStarted),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateLastDayFinished),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateComplained),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateDone),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.personalDietSet),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.stateChargeWasCollected),
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.values,
|
||||
contains(ChosenPlanStateEnum.statePaymentFailed),
|
||||
);
|
||||
});
|
||||
|
||||
test('getShowableChatBadgeStates returns correct states', () {
|
||||
@@ -40,32 +88,77 @@ void main() {
|
||||
});
|
||||
|
||||
test('isStateAfterPaidState returns false for states before paid', () {
|
||||
expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.isStateAfterPaidState(), isFalse);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateCanceledByTheInitiator.isStateAfterPaidState(),
|
||||
isFalse,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.stateInited.isStateAfterPaidState(), isFalse);
|
||||
expect(ChosenPlanStateEnum.stateInCoordination.isStateAfterPaidState(), isFalse);
|
||||
expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.isStateAfterPaidState(), isFalse);
|
||||
expect(ChosenPlanStateEnum.statePendingPayment.isStateAfterPaidState(), isFalse);
|
||||
expect(ChosenPlanStateEnum.statePaymentFailed.isStateAfterPaidState(), isFalse);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateInCoordination.isStateAfterPaidState(),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateStartDateHasBeenSet.isStateAfterPaidState(),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.statePendingPayment.isStateAfterPaidState(),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.statePaymentFailed.isStateAfterPaidState(),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('isStateAfterPaidState returns true for states after paid', () {
|
||||
expect(ChosenPlanStateEnum.statePaid.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStarted.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInProgress.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.stateLastDayStarted.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.stateLastDayFinished.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.stateComplained.isStateAfterPaidState(), isTrue);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateInProgress.isStateAfterPaidState(),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateLastDayStarted.isStateAfterPaidState(),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateLastDayFinished.isStateAfterPaidState(),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateComplained.isStateAfterPaidState(),
|
||||
isTrue,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.stateDone.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.personalDietSet.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.stateChargeWasCollected.isStateAfterPaidState(), isTrue);
|
||||
expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isStateAfterPaidState(), isTrue);
|
||||
expect(
|
||||
ChosenPlanStateEnum.personalDietSet.isStateAfterPaidState(),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateChargeWasCollected.isStateAfterPaidState(),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateConfirmedByConsultant.isStateAfterPaidState(),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('canShowCancelAction returns true for cancellable states', () {
|
||||
expect(ChosenPlanStateEnum.stateInited.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInCoordination.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.statePendingPayment.canShowCancelAction, isTrue);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateInCoordination.canShowCancelAction,
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateStartDateHasBeenSet.canShowCancelAction,
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.statePendingPayment.canShowCancelAction,
|
||||
isTrue,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.statePaid.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStarted.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInProgress.canShowCancelAction, isTrue);
|
||||
@@ -73,33 +166,129 @@ void main() {
|
||||
|
||||
test('canShowCancelAction returns false for non-cancellable states', () {
|
||||
expect(ChosenPlanStateEnum.personalDietSet.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayStarted.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayFinished.canShowCancelAction, isFalse);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateLastDayStarted.canShowCancelAction,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateLastDayFinished.canShowCancelAction,
|
||||
isFalse,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.stateComplained.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateDone.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateChargeWasCollected.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.statePaymentFailed.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateConfirmedByConsultant.canShowCancelAction, isFalse);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateChargeWasCollected.canShowCancelAction,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateCanceledByTheInitiator.canShowCancelAction,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.statePaymentFailed.canShowCancelAction,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateConfirmedByConsultant.canShowCancelAction,
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('isCancelAfterPaidState returns true only for post-paid cancellable states', () {
|
||||
expect(ChosenPlanStateEnum.statePaid.isCancelAfterPaidState, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStarted.isCancelAfterPaidState, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInProgress.isCancelAfterPaidState, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInited.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateInCoordination.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.statePendingPayment.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.statePaymentFailed.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.personalDietSet.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayStarted.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayFinished.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateComplained.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateDone.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateChargeWasCollected.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.isCancelAfterPaidState, isFalse);
|
||||
test(
|
||||
'isCancelAfterPaidState returns true only for post-paid cancellable states',
|
||||
() {
|
||||
expect(ChosenPlanStateEnum.statePaid.isCancelAfterPaidState, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStarted.isCancelAfterPaidState, isTrue);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateInProgress.isCancelAfterPaidState,
|
||||
isTrue,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.stateInited.isCancelAfterPaidState, isFalse);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateInCoordination.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateStartDateHasBeenSet.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.statePendingPayment.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.statePaymentFailed.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateConfirmedByConsultant.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.personalDietSet.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateLastDayStarted.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateLastDayFinished.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateComplained.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.stateDone.isCancelAfterPaidState, isFalse);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateChargeWasCollected.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
ChosenPlanStateEnum
|
||||
.stateCanceledByTheInitiator
|
||||
.isCancelAfterPaidState,
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'allowsVideoCall is false for finished and canceled consultations',
|
||||
() {
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateCanceledByTheInitiator.allowsVideoCall,
|
||||
isFalse,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.statePaymentFailed.allowsVideoCall, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateDone.allowsVideoCall, isFalse);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateChargeWasCollected.allowsVideoCall,
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('allowsVideoCall is true while the consultation is not finished', () {
|
||||
expect(ChosenPlanStateEnum.stateInited.allowsVideoCall, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInCoordination.allowsVideoCall, isTrue);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateStartDateHasBeenSet.allowsVideoCall,
|
||||
isTrue,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.statePendingPayment.allowsVideoCall, isTrue);
|
||||
expect(
|
||||
ChosenPlanStateEnum.stateConfirmedByConsultant.allowsVideoCall,
|
||||
isTrue,
|
||||
);
|
||||
expect(ChosenPlanStateEnum.statePaid.allowsVideoCall, isTrue);
|
||||
expect(ChosenPlanStateEnum.personalDietSet.allowsVideoCall, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStarted.allowsVideoCall, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInProgress.allowsVideoCall, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateLastDayStarted.allowsVideoCall, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateLastDayFinished.allowsVideoCall, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateComplained.allowsVideoCall, isTrue);
|
||||
});
|
||||
|
||||
test('getActiveStates returns correct states', () {
|
||||
@@ -114,8 +303,10 @@ void main() {
|
||||
expect(activeStates, contains(ChosenPlanStateEnum.stateComplained));
|
||||
expect(activeStates, contains(ChosenPlanStateEnum.stateDone));
|
||||
expect(activeStates, contains(ChosenPlanStateEnum.personalDietSet));
|
||||
expect(activeStates, isNot(contains(ChosenPlanStateEnum.statePaymentFailed)));
|
||||
expect(
|
||||
activeStates,
|
||||
isNot(contains(ChosenPlanStateEnum.statePaymentFailed)),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/models/pagination_model.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/recording_status.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
import 'package:network_image_mock/network_image_mock.dart';
|
||||
|
||||
class _MockRecordingsRepository extends Mock implements VideoCallRecordingsRepository {}
|
||||
|
||||
void main() {
|
||||
late _MockRecordingsRepository repository;
|
||||
|
||||
VideoCallRecordingsPagination page(
|
||||
List<VideoCallRecordingModel> data, {
|
||||
int lastPage = 1,
|
||||
}) {
|
||||
return VideoCallRecordingsPagination(
|
||||
data: data,
|
||||
links: const Links(
|
||||
first: 'https://example.com?page=1',
|
||||
last: 'https://example.com?page=1',
|
||||
prev: null,
|
||||
next: null,
|
||||
),
|
||||
meta: Meta(
|
||||
currentPage: 1,
|
||||
from: data.isEmpty ? null : 1,
|
||||
lastPage: lastPage,
|
||||
links: const [],
|
||||
perPage: 20,
|
||||
to: data.isEmpty ? null : data.length,
|
||||
total: data.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
VideoCallRecordingModel recording(int id) {
|
||||
return VideoCallRecordingModel(
|
||||
id: id,
|
||||
status: RecordingStatus.ready,
|
||||
durationSeconds: 60,
|
||||
createdAt: DateTime.utc(2026, 9, 21, 10),
|
||||
previewUrl: 'https://example.com/preview.jpg',
|
||||
fileUrl: 'https://example.com/file.mp4',
|
||||
counterpart: const VideoCallRecordingCounterpartModel(name: 'Сидни', slug: 'sydney'),
|
||||
);
|
||||
}
|
||||
|
||||
setUp(() async {
|
||||
await sl.reset();
|
||||
repository = _MockRecordingsRepository();
|
||||
sl.registerFactory<VideoCallRecordingsCubit>(
|
||||
() => VideoCallRecordingsCubit(repository: repository),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await sl.reset();
|
||||
});
|
||||
|
||||
Widget wrap(Widget child) {
|
||||
return MaterialApp(
|
||||
theme: ThemeHelper().themeData(),
|
||||
localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates],
|
||||
supportedLocales: const [Locale('ru')],
|
||||
home: child,
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('short list can be pulled to refresh', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
when(() => repository.getRecordings(page: 1, period: null)).thenAnswer(
|
||||
(_) async => page([recording(1)]),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(wrap(const VideoCallRecordingsScreen()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final list = tester.widget<ListView>(find.byType(ListView));
|
||||
expect(list.physics, isA<AlwaysScrollableScrollPhysics>());
|
||||
|
||||
await tester.fling(find.byType(ListView), const Offset(0, 400), 1200);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
verify(() => repository.getRecordings(page: 1, period: null)).called(2);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('pull on a short list does not request the next page', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
when(() => repository.getRecordings(page: 1, period: null)).thenAnswer(
|
||||
(_) async => page([recording(1)], lastPage: 2),
|
||||
);
|
||||
when(() => repository.getRecordings(page: 2, period: null)).thenAnswer(
|
||||
(_) async => page([recording(2)], lastPage: 2),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(wrap(const VideoCallRecordingsScreen()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.fling(find.byType(ListView), const Offset(0, 400), 1200);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
verifyNever(() => repository.getRecordings(page: 2, period: null));
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('empty state text stays visible at a large text scale', (tester) async {
|
||||
tester.view.physicalSize = const Size(320, 240);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
when(() => repository.getRecordings(page: 1, period: null)).thenAnswer(
|
||||
(_) async => page(const []),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
const MediaQuery(
|
||||
data: MediaQueryData(textScaler: TextScaler.linear(3)),
|
||||
child: VideoCallRecordingsScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Пока нет видеоконсультаций'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('empty list can be pulled to refresh', (tester) async {
|
||||
when(() => repository.getRecordings(page: 1, period: null)).thenAnswer(
|
||||
(_) async => page(const []),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(wrap(const VideoCallRecordingsScreen()));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Пока нет видеоконсультаций'), findsOneWidget);
|
||||
final list = tester.widget<ListView>(find.byType(ListView));
|
||||
expect(list.physics, isA<AlwaysScrollableScrollPhysics>());
|
||||
|
||||
await tester.fling(find.text('Пока нет видеоконсультаций'), const Offset(0, 400), 1200);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
verify(() => repository.getRecordings(page: 1, period: null)).called(2);
|
||||
});
|
||||
}
|
||||
@@ -14,6 +14,7 @@ class _MockDio extends Mock implements Dio {}
|
||||
class _FakeDownloadsSaver extends Fake implements PublicDownloadsSaver {
|
||||
String? lastSourcePath;
|
||||
String? lastFileName;
|
||||
String? lastSubfolder;
|
||||
|
||||
@override
|
||||
Future<String> saveToDownloads({
|
||||
@@ -24,7 +25,8 @@ class _FakeDownloadsSaver extends Fake implements PublicDownloadsSaver {
|
||||
}) async {
|
||||
lastSourcePath = sourcePath;
|
||||
lastFileName = fileName;
|
||||
return 'content://downloads/Itvio/$fileName';
|
||||
lastSubfolder = subfolder;
|
||||
return 'content://downloads/$subfolder/$fileName';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +159,8 @@ void main() {
|
||||
);
|
||||
|
||||
expect(downloadsSaver.lastFileName, 'recording_1.mp4');
|
||||
expect(saved, contains('Itvio'));
|
||||
expect(downloadsSaver.lastSubfolder, 'Eatvio');
|
||||
expect(saved, contains('Eatvio'));
|
||||
expect(File(downloadsSaver.lastSourcePath!).existsSync(), isFalse);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ void main() {
|
||||
testWidgets('VideoCallParticipantNameLabel renders consultant role above name', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
locale: const Locale('en'),
|
||||
localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates],
|
||||
supportedLocales: S.delegate.supportedLocales,
|
||||
home: const Scaffold(
|
||||
@@ -26,6 +27,7 @@ void main() {
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('Alex'), findsOneWidget);
|
||||
expect(find.text('Eatvio consultant'), findsOneWidget);
|
||||
|
||||
242
tool/export_api_contract.dart
Normal file
242
tool/export_api_contract.dart
Normal file
@@ -0,0 +1,242 @@
|
||||
// FILE: tool/export_api_contract.dart
|
||||
// VERSION: 1.0.0
|
||||
// PURPOSE: Экспорт контракта мобильных моделей для бэкенд-репозитория (eatvio-web).
|
||||
//
|
||||
// Обходит lib/**/*.dart, находит @freezed фабрики (const factory XModel({...}))
|
||||
// и извлекает JSON-контракт каждой модели: какие ключи обязательны (required),
|
||||
// а какие допускают null/отсутствие.
|
||||
//
|
||||
// Источник истины — исходные декларации, НЕ сгенерированные *.g.dart:
|
||||
// nullability = "?" в типе Dart; отсутствие ключа безопасно при @Default(...);
|
||||
// JSON-имя = @JsonKey(name: "...") либо имя поля (дефолт json_serializable).
|
||||
//
|
||||
// USAGE:
|
||||
// dart run tool/export_api_contract.dart # манифест в stdout
|
||||
// dart run tool/export_api_contract.dart out.json # манифест в файл
|
||||
//
|
||||
// CI (flutter-репо): регенерить и сравнивать с закоммиченной копией;
|
||||
// diff → fail с требованием обновить манифест и синхронизировать его
|
||||
// в eatvio-web: tests/Fixtures/Contract/flutter_model_contract.json
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
void main(List<String> args) {
|
||||
final root = Directory('lib');
|
||||
if (!root.existsSync()) {
|
||||
stderr.writeln('Run from the flutter app root (directory "lib" not found).');
|
||||
exit(2);
|
||||
}
|
||||
|
||||
final sources = <File, String>{};
|
||||
final enumNames = <String>{};
|
||||
|
||||
final files = root.listSync(recursive: true).whereType<File>().toList();
|
||||
// ДЕТЕРМИНИЗМ: сортируем по пути — порядок Directory.listSync зависит от файловой системы,
|
||||
// а при коллизии имён моделей побеждает последняя обработанная. Без сортировки локально
|
||||
// и на CI получаются разные манифесты (баг, из-за которого CI падал на чистом PR).
|
||||
files.sort((a, b) => a.path.compareTo(b.path));
|
||||
|
||||
for (final file in files) {
|
||||
if (!file.path.endsWith('.dart') || file.path.endsWith('.g.dart') || file.path.endsWith('.freezed.dart')) {
|
||||
continue;
|
||||
}
|
||||
final source = file.readAsStringSync();
|
||||
sources[file] = source;
|
||||
enumNames.addAll(
|
||||
RegExp(r'^\s*enum\s+(\w+)', multiLine: true)
|
||||
.allMatches(source)
|
||||
.map((m) => m.group(1)!),
|
||||
);
|
||||
}
|
||||
|
||||
final contract = <String, Map<String, dynamic>>{};
|
||||
// modelOrigin: имя модели -> файл, из которого она взята (для предупреждений о коллизиях).
|
||||
final modelOrigin = <String, String>{};
|
||||
for (final entry in sources.entries) {
|
||||
final extracted = extractModels(entry.value);
|
||||
for (final modelName in extracted.keys) {
|
||||
if (contract.containsKey(modelName)) {
|
||||
stderr.writeln(
|
||||
'WARNING: model "$modelName" defined in both "${modelOrigin[modelName]}" '
|
||||
'and "${entry.key.path}" — keeping the one from "${entry.key.path}" (sorted-order last wins). '
|
||||
'Consider renaming the Dart classes to make the contract unambiguous.',
|
||||
);
|
||||
}
|
||||
modelOrigin[modelName] = entry.key.path;
|
||||
contract[modelName] = extracted[modelName]!;
|
||||
}
|
||||
}
|
||||
|
||||
// kinds считаются второй проходкой: нужны все имена моделей (contract.keys) и enum'ов.
|
||||
final modelNames = contract.keys.toSet();
|
||||
for (final entry in contract.entries) {
|
||||
final types = (entry.value['types'] ?? <String, String>{}) as Map<String, String>;
|
||||
entry.value['kinds'] = {
|
||||
for (final e in types.entries) e.key: jsonKindFor(e.value, modelNames, enumNames),
|
||||
};
|
||||
}
|
||||
|
||||
final sorted = <String, Map<String, dynamic>>{
|
||||
for (final key in contract.keys.toList()..sort()) key: contract[key]!,
|
||||
};
|
||||
const encoder = JsonEncoder.withIndent(' ');
|
||||
final output = encoder.convert(sorted);
|
||||
|
||||
if (args.isNotEmpty) {
|
||||
File(args.first).writeAsStringSync('$output\n');
|
||||
stdout.writeln('Contract written to ${args.first} (${sorted.length} models)');
|
||||
} else {
|
||||
stdout.writeln(output);
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON-вид значения для Dart-типа — по нему бэкенд-чекер валидирует payload:
|
||||
/// number (int/double), string, boolean, list, map, model (JSON-объект),
|
||||
/// enum (строка-имя или int), any (не проверяем).
|
||||
String jsonKindFor(String dartType, Set<String> modelNames, Set<String> enumNames) {
|
||||
final type = dartType.trim();
|
||||
if (type == 'dynamic' || type == 'Object') {
|
||||
return 'any';
|
||||
}
|
||||
if (type.startsWith('List<')) {
|
||||
return 'list';
|
||||
}
|
||||
if (type.startsWith('Map<')) {
|
||||
return 'map';
|
||||
}
|
||||
if (const {'int', 'double', 'num'}.contains(type)) {
|
||||
return 'number';
|
||||
}
|
||||
if (type == 'String') {
|
||||
return 'string';
|
||||
}
|
||||
if (type == 'bool') {
|
||||
return 'boolean';
|
||||
}
|
||||
if (enumNames.contains(type)) {
|
||||
return 'enum';
|
||||
}
|
||||
if (modelNames.contains(type)) {
|
||||
return 'model';
|
||||
}
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
/// Извлекает все @freezed-модели из исходника.
|
||||
/// Возвращает {ModelName: {required: [...], optional: [...]}}.
|
||||
Map<String, Map<String, dynamic>> extractModels(String source) {
|
||||
final result = <String, Map<String, dynamic>>{};
|
||||
|
||||
// Блоки "const factory ModelName({ ... }) = _ModelName[...];" (одно- и многострочные).
|
||||
final factoryRe = RegExp(r'const\s+factory\s+(\w+)\(\s*\{(.*?)\}\s*\)\s*=', dotAll: true);
|
||||
for (final match in factoryRe.allMatches(source)) {
|
||||
final modelName = match.group(1)!;
|
||||
final body = match.group(2)!;
|
||||
|
||||
final required = <String>[];
|
||||
final optional = <String>[];
|
||||
final types = <String, String>{};
|
||||
|
||||
for (final rawLine in _splitTopLevel(body)) {
|
||||
final line = rawLine.trim();
|
||||
if (line.isEmpty || line.startsWith('//')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final field = _parseField(line);
|
||||
if (field == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
(field.required ? required : optional).add(field.jsonName);
|
||||
types[field.jsonName] = field.dartType;
|
||||
}
|
||||
|
||||
if (required.isNotEmpty || optional.isNotEmpty) {
|
||||
result[modelName] = {
|
||||
'required': required,
|
||||
'optional': optional,
|
||||
'types': types,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Разбивает тело фабрики по запятым верхнего уровня,
|
||||
/// не разрывая дженерики (`List<int, String>`) и вложенные скобки.
|
||||
List<String> _splitTopLevel(String body) {
|
||||
final parts = <String>[];
|
||||
final current = StringBuffer();
|
||||
var angleDepth = 0;
|
||||
var parenDepth = 0;
|
||||
var braceDepth = 0;
|
||||
|
||||
for (final char in body.runes) {
|
||||
final ch = String.fromCharCode(char);
|
||||
if (ch == '<') {
|
||||
angleDepth++;
|
||||
} else if (ch == '>') {
|
||||
angleDepth = (angleDepth - 1).clamp(0, 1 << 30);
|
||||
} else if (ch == '(') {
|
||||
parenDepth++;
|
||||
} else if (ch == ')') {
|
||||
parenDepth = (parenDepth - 1).clamp(0, 1 << 30);
|
||||
} else if (ch == '{') {
|
||||
braceDepth++;
|
||||
} else if (ch == '}') {
|
||||
braceDepth = (braceDepth - 1).clamp(0, 1 << 30);
|
||||
} else if (ch == ',' && angleDepth == 0 && parenDepth == 0 && braceDepth == 0) {
|
||||
parts.add(current.toString());
|
||||
current.clear();
|
||||
|
||||
continue;
|
||||
}
|
||||
current.write(ch);
|
||||
}
|
||||
parts.add(current.toString());
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
class _Field {
|
||||
_Field(this.jsonName, this.required, this.dartType);
|
||||
|
||||
final String jsonName;
|
||||
final bool required;
|
||||
final String dartType;
|
||||
}
|
||||
|
||||
_Field? _parseField(String line) {
|
||||
// Убираем комментарии в конце строки.
|
||||
final code = line.split('//').first.trim();
|
||||
if (code.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// JSON-имя: @JsonKey(name: "type_no") или имя поля (одинарные и двойные кавычки).
|
||||
final jsonKeyMatch =
|
||||
RegExp(r'''@JsonKey\([^)]*?\bname:\s*["']([^"']+)["']''').firstMatch(code);
|
||||
// Убираем аннотации, оставляем "модификаторы тип поле".
|
||||
final declaration = code.replaceAll(RegExp(r'@\w+\([^)]*\)'), '').trim();
|
||||
|
||||
final fieldMatch = RegExp(r'^(?:(?:required|final|const)\s+)*([\w<>?,\s]+?)\s+(\w+)$').firstMatch(declaration);
|
||||
if (fieldMatch == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final type = fieldMatch.group(1)!.trim();
|
||||
final dartName = fieldMatch.group(2)!;
|
||||
|
||||
// Метаданные исходной строки.
|
||||
final hasDefault = RegExp(r'@Default\(').hasMatch(line);
|
||||
final isNullable = type.endsWith('?') || type == 'dynamic';
|
||||
|
||||
return _Field(
|
||||
jsonKeyMatch?.group(1) ?? dartName,
|
||||
!isNullable && !hasDefault,
|
||||
type.endsWith('?') ? type.substring(0, type.length - 1) : type,
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user