forked from eatvio/eatvio_app
Compare commits
31 Commits
issue-1122
...
issue-851
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65219bce77 | ||
|
|
ad122ed2f7 | ||
| 8a8a01721e | |||
| 61b77bfaec | |||
| 78192b742d | |||
| ca59186e63 | |||
| 608016c8ad | |||
| 0df474b2b5 | |||
|
|
47b81fba5a | ||
|
|
5308c11ca6 | ||
| 23f24c0be0 | |||
| 1e8c1ab2eb | |||
|
|
29ee8ae5a8 | ||
|
|
ce073b5a95 | ||
|
|
b05d3b891b | ||
| 87d383152d | |||
| dbe0369d4d | |||
| 4f0ba5c864 | |||
| f9b862f4ad | |||
| 2ea711844f | |||
| 66d7028d0f | |||
| 0c66994644 | |||
| 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);
|
||||
|
||||
@@ -183,7 +183,10 @@ class CubitRegistrations {
|
||||
),
|
||||
);
|
||||
sl.registerFactory<profile_plans.PlansCubit>(
|
||||
() => profile_plans.PlansCubit(plansRepository: sl()),
|
||||
() => profile_plans.PlansCubit(
|
||||
plansRepository: sl(),
|
||||
planRepository: sl(),
|
||||
),
|
||||
);
|
||||
sl.registerFactory<SubCubit>(() => SubCubit(profileRepository: sl()));
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -44,6 +44,7 @@ class CustomPopup extends StatelessWidget {
|
||||
final PlanModel? plan;
|
||||
final String userSlug;
|
||||
final VoidCallback? onPostsChanged;
|
||||
final VoidCallback? onPlanChanged;
|
||||
|
||||
const CustomPopup({
|
||||
super.key,
|
||||
@@ -59,6 +60,7 @@ class CustomPopup extends StatelessWidget {
|
||||
this.plan,
|
||||
required this.userSlug,
|
||||
this.onPostsChanged,
|
||||
this.onPlanChanged,
|
||||
});
|
||||
|
||||
bool get _isAdminAuthor =>
|
||||
@@ -166,9 +168,13 @@ class CustomPopup extends StatelessWidget {
|
||||
try {
|
||||
context.read<AboutPlanCubit>().getPlan(slug: currentPlan.slug);
|
||||
} catch (_) {}
|
||||
try {
|
||||
context.read<PlansCubit>().loadPlans();
|
||||
} catch (_) {}
|
||||
if (onPlanChanged != null) {
|
||||
onPlanChanged!();
|
||||
} else {
|
||||
try {
|
||||
context.read<PlansCubit>().loadPlans();
|
||||
} catch (_) {}
|
||||
}
|
||||
try {
|
||||
context.read<MyPlansCubit>().loadPlans();
|
||||
} catch (_) {}
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -122,7 +122,10 @@ class _DiaryScreenContentState extends State<DiaryScreenContent> {
|
||||
centerTitle: true,
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.only(bottom: 16, top: 8),
|
||||
padding: EdgeInsets.only(
|
||||
bottom: 16,
|
||||
top: widget.diaryId == null ? 0 : 8,
|
||||
),
|
||||
physics: const BouncingScrollPhysics(),
|
||||
child: Column(
|
||||
children: [
|
||||
@@ -133,7 +136,12 @@ class _DiaryScreenContentState extends State<DiaryScreenContent> {
|
||||
],
|
||||
if (state is DiaryStateLoaded && _canShowInsights(state))
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(4, 12, 4, 12),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
4,
|
||||
widget.diaryId == null ? 0 : 12,
|
||||
4,
|
||||
12,
|
||||
),
|
||||
child: _DiaryInsights(
|
||||
slug: state.isConsultantView ? _ownerSlug(state) : null,
|
||||
canAdd: !state.isConsultantView,
|
||||
@@ -325,6 +333,7 @@ class _DiaryInsightsState extends State<_DiaryInsights> {
|
||||
canAdd: widget.canAdd,
|
||||
refreshToken: _refreshToken,
|
||||
initialIntraDate: widget.diaryDate,
|
||||
showShadow: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:table_calendar/table_calendar.dart';
|
||||
|
||||
class CalendarWidget extends StatefulWidget {
|
||||
@@ -15,19 +17,39 @@ class CalendarWidget extends StatefulWidget {
|
||||
State<CalendarWidget> createState() => _CalendarWidgetState();
|
||||
}
|
||||
|
||||
class _CalendarWidgetState extends State<CalendarWidget> {
|
||||
class _CalendarWidgetState extends State<CalendarWidget>
|
||||
with SingleTickerProviderStateMixin {
|
||||
static const _locale = 'ru_RU';
|
||||
static const _kDaysOfWeekHeight = 16.0;
|
||||
static const _kRowHeight = 52.0;
|
||||
static const _dayCellMargin = 6.0;
|
||||
static const _dragHandlePadding = 5.0;
|
||||
|
||||
CalendarFormat _calendarFormat = CalendarFormat.week;
|
||||
late final _expansion = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 180),
|
||||
);
|
||||
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();
|
||||
if (widget.date != null) {
|
||||
_selectedDay = widget.date!;
|
||||
_focusedDay = widget.date!;
|
||||
final selected =
|
||||
widget.date ?? _dayFromState(context.read<DiaryCubit>().state);
|
||||
if (selected != null) {
|
||||
_selectedDay = selected;
|
||||
_focusedDay = selected;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,89 +62,199 @@ class _CalendarWidgetState extends State<CalendarWidget> {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_expansion.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
final textScaler = MediaQuery.textScalerOf(context);
|
||||
final daysOfWeekHeight = _scaledDaysOfWeekHeight(context);
|
||||
return BlocConsumer<DiaryCubit, DiaryState>(
|
||||
listener: (BuildContext context, DiaryState state) {
|
||||
if (state is DiaryStateLoaded) {
|
||||
final rowHeight = MediaQuery.textScalerOf(context).scale(_kRowHeight);
|
||||
final firstOfMonth = DateTime.utc(_focusedDay.year, _focusedDay.month);
|
||||
final daysInMonth = DateTime.utc(
|
||||
_focusedDay.year,
|
||||
_focusedDay.month + 1,
|
||||
0,
|
||||
).day;
|
||||
final daysBeforeMonth = firstOfMonth.weekday - DateTime.monday;
|
||||
final weekCount = (daysBeforeMonth + daysInMonth + 6) ~/ 7;
|
||||
final focusedWeek = (daysBeforeMonth + _focusedDay.day - 1) ~/ 7;
|
||||
final extraHeight = (weekCount - 1) * rowHeight;
|
||||
final week = _buildDays(rowHeight, CalendarFormat.week);
|
||||
final month = _buildDays(rowHeight, CalendarFormat.month);
|
||||
|
||||
return BlocListener<DiaryCubit, DiaryState>(
|
||||
listener: (context, state) {
|
||||
final selected = _dayFromState(state);
|
||||
if (selected != null) {
|
||||
setState(() {
|
||||
_selectedDay = state.selectedDay;
|
||||
_selectedDay = selected;
|
||||
_focusedDay = selected;
|
||||
});
|
||||
}
|
||||
},
|
||||
builder: (BuildContext context, DiaryState state) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16),
|
||||
child: TableCalendar(
|
||||
focusedDay: _focusedDay,
|
||||
firstDay: DateTime.utc(2020, 10, 16),
|
||||
lastDay: DateTime.utc(2030, 3, 14),
|
||||
locale: 'ru_RU',
|
||||
startingDayOfWeek: StartingDayOfWeek.monday,
|
||||
calendarFormat: _calendarFormat,
|
||||
daysOfWeekHeight: daysOfWeekHeight,
|
||||
rowHeight: textScaler.scale(_kRowHeight),
|
||||
headerStyle: const HeaderStyle(titleCentered: true, formatButtonVisible: false, leftChevronVisible: false, rightChevronVisible: false),
|
||||
onDaySelected: (selectedDay, focusedDay) async {
|
||||
if (!isSameDay(_selectedDay, selectedDay)) {
|
||||
final previousSelectedDay = _selectedDay;
|
||||
final previousFocusedDay = _selectedDay;
|
||||
setState(() {
|
||||
_selectedDay = selectedDay;
|
||||
_focusedDay = focusedDay;
|
||||
});
|
||||
final canOpenNextDay = await context.read<DiaryCubit>().setSelectedDay(selectedDay);
|
||||
if (!canOpenNextDay && context.mounted) {
|
||||
showErrorDialog(context, title: s.want_to_see_tomorrow, description: s.can_not_see_next_day);
|
||||
setState(() {
|
||||
_selectedDay = previousSelectedDay;
|
||||
_focusedDay = previousFocusedDay;
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
selectedDayPredicate: (day) {
|
||||
return isSameDay(_selectedDay, day);
|
||||
},
|
||||
onPageChanged: (focusedDay) {
|
||||
setState(() {
|
||||
_focusedDay = focusedDay;
|
||||
});
|
||||
},
|
||||
onFormatChanged: (format) {
|
||||
if (_calendarFormat != format) {
|
||||
setState(() {
|
||||
_calendarFormat = format;
|
||||
});
|
||||
}
|
||||
},
|
||||
calendarStyle: CalendarStyle(
|
||||
weekendDecoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
|
||||
defaultDecoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
|
||||
selectedDecoration: BoxDecoration(color: appTheme.blueA400, shape: BoxShape.circle),
|
||||
todayTextStyle: const TextStyle(color: Colors.black),
|
||||
todayDecoration: BoxDecoration(
|
||||
border: Border.all(color: appTheme.blueA400, width: 2),
|
||||
color: Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: AnimatedBuilder(
|
||||
animation: _expansion,
|
||||
child: _buildWeekdays(context),
|
||||
builder: (context, weekdays) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_buildHeader(context),
|
||||
weekdays!,
|
||||
ClipRect(
|
||||
child: SizedBox(
|
||||
height: rowHeight + extraHeight * _expansion.value,
|
||||
child: OverflowBox(
|
||||
// При раскрытии показываем строки вокруг открытой недели.
|
||||
alignment: Alignment(
|
||||
0,
|
||||
2 * focusedWeek / (weekCount - 1) - 1,
|
||||
),
|
||||
minHeight: 0,
|
||||
maxHeight: double.infinity,
|
||||
child: _expansion.value == 0 ? week : month,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
_arrowDown(),
|
||||
],
|
||||
);
|
||||
},
|
||||
_buildDragHandle(extraHeight),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
final expanded = _expansion.value >= 0.5;
|
||||
final label = DateFormat.yMMMM(_locale).format(_focusedDay);
|
||||
|
||||
return Tooltip(
|
||||
message: expanded ? s.hide : s.expand,
|
||||
child: InkWell(
|
||||
onTap: () => _expansion.value = expanded ? 0 : 1,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(label, style: const HeaderStyle().titleTextStyle),
|
||||
const SizedBox(width: 4),
|
||||
Icon(
|
||||
expanded
|
||||
? Icons.keyboard_arrow_up_rounded
|
||||
: Icons.keyboard_arrow_down_rounded,
|
||||
size: 18,
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildWeekdays(BuildContext context) {
|
||||
const style = DaysOfWeekStyle();
|
||||
final format = DateFormat.E(_locale);
|
||||
|
||||
return ExcludeSemantics(
|
||||
child: SizedBox(
|
||||
height: _scaledDaysOfWeekHeight(context),
|
||||
child: Row(
|
||||
children: List.generate(DateTime.daysPerWeek, (index) {
|
||||
final day = DateTime.utc(
|
||||
_focusedDay.year,
|
||||
_focusedDay.month,
|
||||
_focusedDay.day - _focusedDay.weekday + DateTime.monday + index,
|
||||
);
|
||||
return Expanded(
|
||||
child: Center(
|
||||
child: Text(
|
||||
format.format(day),
|
||||
style: day.weekday >= DateTime.saturday
|
||||
? style.weekendStyle
|
||||
: style.weekdayStyle,
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDays(double rowHeight, CalendarFormat format) {
|
||||
return TableCalendar(
|
||||
key: ValueKey(format),
|
||||
focusedDay: _focusedDay,
|
||||
firstDay: DateTime.utc(2020, 10, 16),
|
||||
lastDay: DateTime.utc(2030, 3, 14),
|
||||
locale: _locale,
|
||||
startingDayOfWeek: StartingDayOfWeek.monday,
|
||||
calendarFormat: format,
|
||||
availableGestures: AvailableGestures.horizontalSwipe,
|
||||
headerVisible: false,
|
||||
daysOfWeekVisible: false,
|
||||
rowHeight: rowHeight,
|
||||
onDaySelected: _selectDay,
|
||||
selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
|
||||
onPageChanged: (focusedDay) => setState(() => _focusedDay = focusedDay),
|
||||
calendarStyle: CalendarStyle(
|
||||
cellMargin: const EdgeInsets.all(_dayCellMargin),
|
||||
weekendDecoration: const BoxDecoration(
|
||||
color: Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
defaultDecoration: const BoxDecoration(
|
||||
color: Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
selectedDecoration: BoxDecoration(
|
||||
color: appTheme.blueA400,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
todayTextStyle: const TextStyle(color: Colors.black),
|
||||
todayDecoration: BoxDecoration(
|
||||
border: Border.all(color: appTheme.blueA400, width: 2),
|
||||
color: Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _selectDay(DateTime selectedDay, DateTime focusedDay) async {
|
||||
if (isSameDay(_selectedDay, selectedDay)) return;
|
||||
|
||||
final previousSelectedDay = _selectedDay;
|
||||
final previousFocusedDay = _focusedDay;
|
||||
setState(() {
|
||||
_selectedDay = selectedDay;
|
||||
_focusedDay = focusedDay;
|
||||
});
|
||||
final cubit = context.read<DiaryCubit>();
|
||||
final canOpenNextDay = await cubit.setSelectedDay(selectedDay);
|
||||
if (!mounted || cubit.state is DiaryStateError || canOpenNextDay) return;
|
||||
|
||||
final s = S.of(context);
|
||||
showErrorDialog(
|
||||
context,
|
||||
title: s.want_to_see_tomorrow,
|
||||
description: s.can_not_see_next_day,
|
||||
);
|
||||
setState(() {
|
||||
_selectedDay = previousSelectedDay;
|
||||
_focusedDay = previousFocusedDay;
|
||||
});
|
||||
}
|
||||
|
||||
double _scaledDaysOfWeekHeight(BuildContext context) {
|
||||
final painter = TextPainter(
|
||||
text: TextSpan(text: 'Щy', style: DefaultTextStyle.of(context).style),
|
||||
@@ -135,26 +267,44 @@ class _CalendarWidgetState extends State<CalendarWidget> {
|
||||
return height.clamp(_kDaysOfWeekHeight, double.infinity);
|
||||
}
|
||||
|
||||
void _nextCalendarFormat() {
|
||||
setState(() {
|
||||
_calendarFormat = CalendarFormat.values[(_calendarFormat.index - 1) % CalendarFormat.values.length];
|
||||
});
|
||||
}
|
||||
|
||||
GestureDetector _arrowDown() {
|
||||
Widget _buildDragHandle(double extraHeight) {
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.translucent,
|
||||
onVerticalDragStart: (_) {
|
||||
_nextCalendarFormat();
|
||||
behavior: HitTestBehavior.opaque,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onVerticalDragStart: (_) => _expansion.stop(),
|
||||
onVerticalDragUpdate: (details) {
|
||||
_expansion.value = (_expansion.value + details.delta.dy / extraHeight)
|
||||
.clamp(0.0, 1.0);
|
||||
},
|
||||
onTap: () {
|
||||
_nextCalendarFormat();
|
||||
},
|
||||
child: Container(
|
||||
onVerticalDragEnd: (details) =>
|
||||
_settleExpansion(details.velocity.pixelsPerSecond.dy),
|
||||
onVerticalDragCancel: _settleExpansion,
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.only(top: 8, bottom: 16),
|
||||
child: Icon(_calendarFormat == CalendarFormat.month ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded, color: Colors.grey.shade600),
|
||||
child: Padding(
|
||||
// Отступ ячеек уже добавляет место над полоской.
|
||||
padding: const EdgeInsets.only(
|
||||
top: _dragHandlePadding,
|
||||
bottom: _dragHandlePadding + _dayCellMargin,
|
||||
),
|
||||
child: Center(
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.blueA400,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
child: const SizedBox(width: 28, height: 4),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _settleExpansion([double velocity = 0]) {
|
||||
final shouldExpand = velocity.abs() >= 400
|
||||
? velocity > 0
|
||||
: _expansion.value >= 0.5;
|
||||
_expansion.animateTo(shouldExpand ? 1 : 0, curve: Curves.easeOutCubic);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,6 +7,7 @@ import 'package:eatvio_app/core/utils/url_utils.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/profile/models/profile_model.dart';
|
||||
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
@@ -107,7 +108,9 @@ class AuthorCard extends StatelessWidget {
|
||||
backgroundColor: appTheme.cardBackground,
|
||||
children: [
|
||||
Text(
|
||||
'${author.authorPlaceInRating}-й в рейтинге',
|
||||
S.of(context).rating_place(
|
||||
author.authorPlaceInRating!,
|
||||
),
|
||||
style: TextStyles.textMMediumAuto.copyWith(
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
|
||||
@@ -66,11 +66,13 @@ class LikesState extends Equatable {
|
||||
final bool wasLikedByMe;
|
||||
final int totalLikes;
|
||||
final int index;
|
||||
final String? slug;
|
||||
|
||||
const LikesState({
|
||||
required this.wasLikedByMe,
|
||||
required this.totalLikes,
|
||||
required this.index,
|
||||
this.slug,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -78,37 +80,44 @@ class LikesState extends Equatable {
|
||||
wasLikedByMe,
|
||||
totalLikes,
|
||||
index,
|
||||
slug,
|
||||
];
|
||||
}
|
||||
|
||||
class FavoriteState extends Equatable {
|
||||
final bool isFavorite;
|
||||
final int index;
|
||||
final String? slug;
|
||||
|
||||
const FavoriteState({
|
||||
required this.isFavorite,
|
||||
required this.index,
|
||||
this.slug,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
isFavorite,
|
||||
index,
|
||||
slug,
|
||||
];
|
||||
}
|
||||
|
||||
class CommentsState extends Equatable {
|
||||
final int index;
|
||||
final int totalComments;
|
||||
final String? slug;
|
||||
|
||||
const CommentsState({
|
||||
required this.index,
|
||||
required this.totalComments,
|
||||
this.slug,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
index,
|
||||
totalComments,
|
||||
slug,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:easy_debounce/easy_debounce.dart';
|
||||
import 'package:eatvio_app/core/const.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
|
||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_state.dart';
|
||||
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
|
||||
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
|
||||
@@ -87,57 +88,51 @@ class PlansCubit extends Cubit<PlansState> {
|
||||
}
|
||||
|
||||
void _changePlanLikeState(LikesState likesState) {
|
||||
final currentPlans = state.plans;
|
||||
final plansForModification = [...currentPlans];
|
||||
final currentPlan = currentPlans[likesState.index];
|
||||
|
||||
plansForModification[likesState.index] = currentPlan.copyWith(
|
||||
totalLikes: likesState.totalLikes,
|
||||
wasLikedByMe: likesState.wasLikedByMe,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
plans: [
|
||||
...plansForModification,
|
||||
],
|
||||
isLoading: isLoading,
|
||||
errorMessage: null,
|
||||
_updatePlanAt(
|
||||
slug: likesState.slug,
|
||||
index: likesState.index,
|
||||
transform: (currentPlan) => currentPlan.copyWith(
|
||||
totalLikes: likesState.totalLikes,
|
||||
wasLikedByMe: likesState.wasLikedByMe,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _changePlanFavoriteState(FavoriteState favoriteState) {
|
||||
final currentPlans = state.plans;
|
||||
final plansForModification = [...currentPlans];
|
||||
final currentPlan = currentPlans[favoriteState.index];
|
||||
|
||||
plansForModification[favoriteState.index] = currentPlan.copyWith(
|
||||
isFavorite: favoriteState.isFavorite,
|
||||
);
|
||||
emit(
|
||||
state.copyWith(
|
||||
plans: [
|
||||
...plansForModification,
|
||||
],
|
||||
isLoading: isLoading,
|
||||
errorMessage: null,
|
||||
_updatePlanAt(
|
||||
slug: favoriteState.slug,
|
||||
index: favoriteState.index,
|
||||
transform: (currentPlan) => currentPlan.copyWith(
|
||||
isFavorite: favoriteState.isFavorite,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _changePlanCommentsState(CommentsState commentsState) {
|
||||
final currentPlans = state.plans;
|
||||
final plansForModification = [...currentPlans];
|
||||
final currentPlan = currentPlans[commentsState.index];
|
||||
|
||||
plansForModification[commentsState.index] = currentPlan.copyWith(
|
||||
totalComments: commentsState.totalComments,
|
||||
_updatePlanAt(
|
||||
slug: commentsState.slug,
|
||||
index: commentsState.index,
|
||||
transform: (currentPlan) => currentPlan.copyWith(
|
||||
totalComments: commentsState.totalComments,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _updatePlanAt({
|
||||
required String? slug,
|
||||
required int index,
|
||||
required PlanModel Function(PlanModel currentPlan) transform,
|
||||
}) {
|
||||
final currentPlans = state.plans;
|
||||
final targetIndex =
|
||||
slug != null ? currentPlans.indexWhere((plan) => plan.slug == slug) : index;
|
||||
if (targetIndex < 0 || targetIndex >= currentPlans.length) return;
|
||||
|
||||
final plansForModification = [...currentPlans];
|
||||
plansForModification[targetIndex] = transform(currentPlans[targetIndex]);
|
||||
emit(
|
||||
state.copyWith(
|
||||
plans: [
|
||||
...plansForModification,
|
||||
],
|
||||
plans: plansForModification,
|
||||
isLoading: isLoading,
|
||||
errorMessage: null,
|
||||
),
|
||||
|
||||
@@ -13,10 +13,8 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/utils/url_utils.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.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_svg/flutter_svg.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
@@ -24,8 +22,20 @@ import 'package:share_plus/share_plus.dart';
|
||||
class PlanWidget extends StatefulWidget {
|
||||
final PlanModel plan;
|
||||
final int index;
|
||||
final bool showPriceOnCover;
|
||||
final Future<void> Function(String slug)? onLikeTap;
|
||||
final Future<void> Function(String slug, bool isFavorite)? onToggleFavorite;
|
||||
final VoidCallback? onPlanChanged;
|
||||
|
||||
const PlanWidget({super.key, required this.plan, required this.index});
|
||||
const PlanWidget({
|
||||
super.key,
|
||||
required this.plan,
|
||||
required this.index,
|
||||
this.showPriceOnCover = false,
|
||||
this.onLikeTap,
|
||||
this.onToggleFavorite,
|
||||
this.onPlanChanged,
|
||||
});
|
||||
|
||||
@override
|
||||
State<PlanWidget> createState() => _PlanWidgetState();
|
||||
@@ -37,6 +47,10 @@ class _PlanWidgetState extends State<PlanWidget> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
final minPrice = widget.plan.minPriceOfOptions.toStringAsFixed(0);
|
||||
final price = widget.plan.packetsCount == 1
|
||||
? '${widget.plan.packet1Options?.price ?? minPrice}₽'
|
||||
: '${s.from} $minPrice₽';
|
||||
return InkWell(
|
||||
onTap: () => GoRouter.of(context).pushNamed(
|
||||
'aboutPlanScreen',
|
||||
@@ -71,17 +85,10 @@ class _PlanWidgetState extends State<PlanWidget> {
|
||||
left: 14,
|
||||
child: BookmarkButton(
|
||||
onTap: () async {
|
||||
if (widget.plan.isFavorite) {
|
||||
await context.read<PlansCubit>().removePlanFromFavorite(
|
||||
widget.plan.slug,
|
||||
widget.index,
|
||||
);
|
||||
} else {
|
||||
await context.read<PlansCubit>().addPlanToFavorite(
|
||||
widget.plan.slug,
|
||||
widget.index,
|
||||
);
|
||||
}
|
||||
await widget.onToggleFavorite?.call(
|
||||
widget.plan.slug,
|
||||
widget.plan.isFavorite,
|
||||
);
|
||||
},
|
||||
color: appTheme.whiteA700,
|
||||
isFavorite: widget.plan.isFavorite,
|
||||
@@ -111,20 +118,47 @@ class _PlanWidgetState extends State<PlanWidget> {
|
||||
plan: widget.plan,
|
||||
complainedContentType: ComplainedContent.plan,
|
||||
userSlug: widget.plan.author.authorSlug,
|
||||
onPlanChanged: widget.onPlanChanged,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 16,
|
||||
child: SizedBox(
|
||||
width: MediaQuery.sizeOf(context).width,
|
||||
child: InfoRow(
|
||||
plan: widget.plan,
|
||||
itemsBackgroundColor: appTheme.whiteA700,
|
||||
disableDescriptionOfTypes: true,
|
||||
type: ProductType.plan,
|
||||
),
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (widget.showPriceOnCover)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 14,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.greenA700,
|
||||
borderRadius: const BorderRadius.horizontal(
|
||||
right: Radius.circular(8),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
price,
|
||||
style: TextStyles.textSSemibold.copyWith(
|
||||
color: appTheme.whiteA700,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
InfoRow(
|
||||
plan: widget.plan,
|
||||
itemsBackgroundColor: appTheme.whiteA700,
|
||||
disableDescriptionOfTypes: true,
|
||||
type: ProductType.plan,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -200,30 +234,35 @@ class _PlanWidgetState extends State<PlanWidget> {
|
||||
),
|
||||
subtitle: Row(
|
||||
children: [
|
||||
InfoBouble(
|
||||
radius: 12,
|
||||
backgroundColor: appTheme.gray50,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 4,
|
||||
horizontal: 10,
|
||||
),
|
||||
children: [
|
||||
Text(
|
||||
'${widget.plan.author.authorPlaceInRating}-й в рейтинге',
|
||||
style: TextStyles.textXSSemibold.copyWith(
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
if (widget.plan.author.authorPlaceInRating != null)
|
||||
InfoBouble(
|
||||
radius: 12,
|
||||
backgroundColor: appTheme.gray50,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 4,
|
||||
horizontal: 10,
|
||||
),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
'${widget.plan.packetsCount == 1 ? widget.plan.packet1Options?.price : '${s.from} ${widget.plan.minPriceOfOptions.toStringAsFixed(0)}'}₽',
|
||||
style: TextStyles.headingXLSemibold.copyWith(
|
||||
color: appTheme.greenA700,
|
||||
children: [
|
||||
Text(
|
||||
s.rating_place(
|
||||
widget.plan.author.authorPlaceInRating!,
|
||||
),
|
||||
style: TextStyles.textXSSemibold.copyWith(
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
if (!widget.showPriceOnCover) ...[
|
||||
const Spacer(),
|
||||
Text(
|
||||
price,
|
||||
style: TextStyles.headingXLSemibold.copyWith(
|
||||
color: appTheme.greenA700,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
],
|
||||
],
|
||||
),
|
||||
title: Padding(
|
||||
@@ -255,10 +294,7 @@ class _PlanWidgetState extends State<PlanWidget> {
|
||||
? appTheme.transparentBlue
|
||||
: null,
|
||||
onTap: () async {
|
||||
await context.read<PlansCubit>().likePlan(
|
||||
widget.plan.slug,
|
||||
widget.index,
|
||||
);
|
||||
await widget.onLikeTap?.call(widget.plan.slug);
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
|
||||
@@ -44,7 +44,15 @@ class Plans extends StatelessWidget {
|
||||
final id = state.plans[index].id;
|
||||
handleVisibility(visibleFraction: info.visibleFraction, id: id, type: ViewableContentType.plans);
|
||||
},
|
||||
child: PlanWidget(plan: state.plans[index], index: index),
|
||||
child: PlanWidget(
|
||||
plan: state.plans[index],
|
||||
index: index,
|
||||
onLikeTap: (slug) => context.read<PlansCubit>().likePlan(slug, index),
|
||||
onToggleFavorite: (slug, isFavorite) => isFavorite
|
||||
? context.read<PlansCubit>().removePlanFromFavorite(slug, index)
|
||||
: context.read<PlansCubit>().addPlanToFavorite(slug, index),
|
||||
onPlanChanged: () => context.read<PlansCubit>().loadPlans(),
|
||||
),
|
||||
);
|
||||
},
|
||||
separatorBuilder: (context, index) {
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -39,12 +39,14 @@ class InsightsCard extends StatelessWidget {
|
||||
this.kbjuEnabled = InsightsFeatureFlags.kbjuEnabled,
|
||||
this.refreshToken = 0,
|
||||
this.initialIntraDate,
|
||||
this.showShadow = true,
|
||||
});
|
||||
|
||||
final String? slug;
|
||||
final bool canAdd;
|
||||
final InsightsRepository? repository;
|
||||
final bool kbjuEnabled;
|
||||
final bool showShadow;
|
||||
|
||||
/// При смене значения блок перезапрашивает данные (например, после правок
|
||||
/// в дневнике), сохраняя вкладку, период и выбранный день.
|
||||
@@ -68,6 +70,7 @@ class InsightsCard extends StatelessWidget {
|
||||
child: _InsightsView(
|
||||
refreshToken: refreshToken,
|
||||
initialIntraDate: initialIntraDate,
|
||||
showShadow: showShadow,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -78,10 +81,12 @@ class _InsightsView extends StatefulWidget {
|
||||
const _InsightsView({
|
||||
required this.refreshToken,
|
||||
required this.initialIntraDate,
|
||||
required this.showShadow,
|
||||
});
|
||||
|
||||
final int refreshToken;
|
||||
final String? initialIntraDate;
|
||||
final bool showShadow;
|
||||
|
||||
@override
|
||||
State<_InsightsView> createState() => _InsightsViewState();
|
||||
@@ -112,9 +117,13 @@ class _InsightsViewState extends State<_InsightsView> {
|
||||
builder: (context, state) {
|
||||
return switch (state) {
|
||||
InsightsStateLoaded() => _CardShell(
|
||||
showShadow: widget.showShadow,
|
||||
child: _LoadedContent(state: state),
|
||||
),
|
||||
InsightsStateError() => const _CardShell(child: _ErrorContent()),
|
||||
InsightsStateError() => _CardShell(
|
||||
showShadow: widget.showShadow,
|
||||
child: const _ErrorContent(),
|
||||
),
|
||||
_ => const SizedBox.shrink(),
|
||||
};
|
||||
},
|
||||
@@ -123,9 +132,10 @@ class _InsightsViewState extends State<_InsightsView> {
|
||||
}
|
||||
|
||||
class _CardShell extends StatelessWidget {
|
||||
const _CardShell({required this.child});
|
||||
const _CardShell({required this.child, required this.showShadow});
|
||||
|
||||
final Widget child;
|
||||
final bool showShadow;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -135,12 +145,13 @@ class _CardShell extends StatelessWidget {
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: InsightsColors.cardShadow,
|
||||
blurRadius: 4,
|
||||
offset: Offset(0, 2),
|
||||
),
|
||||
boxShadow: [
|
||||
if (showShadow)
|
||||
const BoxShadow(
|
||||
color: InsightsColors.cardShadow,
|
||||
blurRadius: 4,
|
||||
offset: Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: child,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -27,9 +27,9 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
Future<void> getPlan({required String slug, int? index}) async {
|
||||
try {
|
||||
final plan = await planRepository.getPlan(slug);
|
||||
if (index != null) {
|
||||
planRepository.emitCommentsStateToFeed(CommentsState(index: index, totalComments: plan.totalComments));
|
||||
}
|
||||
planRepository.emitCommentsStateToFeed(
|
||||
CommentsState(index: index ?? 0, totalComments: plan.totalComments, slug: slug),
|
||||
);
|
||||
emit(state.copyWith(planModel: plan, error: null));
|
||||
} catch (e, stackTrace) {
|
||||
await reportFrom(e, stackTrace, this);
|
||||
@@ -59,14 +59,20 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
if (currentPlan == null) return;
|
||||
if (currentPlan.wasLikedByMe) {
|
||||
emit(state.copyWith(planModel: currentPlan.copyWith(wasLikedByMe: false, totalLikes: currentPlan.totalLikes - 1), error: null));
|
||||
if (index != null) {
|
||||
planRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: false, totalLikes: currentPlan.totalLikes - 1, index: index));
|
||||
}
|
||||
planRepository.emitLikesStateToFeed(LikesState(
|
||||
wasLikedByMe: false,
|
||||
totalLikes: currentPlan.totalLikes - 1,
|
||||
index: index ?? 0,
|
||||
slug: slug,
|
||||
));
|
||||
} else {
|
||||
emit(state.copyWith(planModel: currentPlan.copyWith(wasLikedByMe: true, totalLikes: currentPlan.totalLikes + 1), error: null));
|
||||
if (index != null) {
|
||||
planRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: true, totalLikes: currentPlan.totalLikes + 1, index: index));
|
||||
}
|
||||
planRepository.emitLikesStateToFeed(LikesState(
|
||||
wasLikedByMe: true,
|
||||
totalLikes: currentPlan.totalLikes + 1,
|
||||
index: index ?? 0,
|
||||
slug: slug,
|
||||
));
|
||||
}
|
||||
|
||||
EasyDebounce.debounce('like_plan_$slug', const Duration(seconds: 1), () async {
|
||||
@@ -75,9 +81,12 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString());
|
||||
if (index != null) {
|
||||
planRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: currentPlan.wasLikedByMe, totalLikes: currentPlan.totalLikes, index: index));
|
||||
}
|
||||
planRepository.emitLikesStateToFeed(LikesState(
|
||||
wasLikedByMe: currentPlan.wasLikedByMe,
|
||||
totalLikes: currentPlan.totalLikes,
|
||||
index: index ?? 0,
|
||||
slug: slug,
|
||||
));
|
||||
emit(state.copyWith(planModel: currentPlan, error: null));
|
||||
}
|
||||
});
|
||||
@@ -88,9 +97,9 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
if (currentPlan == null) return;
|
||||
|
||||
emit(state.copyWith(planModel: currentPlan.copyWith(isFavorite: true)));
|
||||
if (index != null) {
|
||||
planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: true, index: index));
|
||||
}
|
||||
planRepository.emitFavoriteStateToFeed(
|
||||
FavoriteState(isFavorite: true, index: index ?? 0, slug: slug),
|
||||
);
|
||||
EasyDebounce.debounce('add_or_remove_plan_to_favorites', const Duration(seconds: 1), () async {
|
||||
try {
|
||||
await planRepository.addToFavorite(slug);
|
||||
@@ -98,9 +107,9 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString());
|
||||
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
|
||||
if (index != null) {
|
||||
planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentPlan.isFavorite, index: index));
|
||||
}
|
||||
planRepository.emitFavoriteStateToFeed(
|
||||
FavoriteState(isFavorite: currentPlan.isFavorite, index: index ?? 0, slug: slug),
|
||||
);
|
||||
emit(state.copyWith(planModel: currentPlan, error: null));
|
||||
}
|
||||
});
|
||||
@@ -111,9 +120,9 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
if (currentPlan == null) return;
|
||||
|
||||
emit(state.copyWith(planModel: currentPlan.copyWith(isFavorite: false)));
|
||||
if (index != null) {
|
||||
planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: false, index: index));
|
||||
}
|
||||
planRepository.emitFavoriteStateToFeed(
|
||||
FavoriteState(isFavorite: false, index: index ?? 0, slug: slug),
|
||||
);
|
||||
EasyDebounce.debounce('add_or_remove_plan_to_favorites', const Duration(seconds: 1), () async {
|
||||
try {
|
||||
await planRepository.removeFromFavorite(slug);
|
||||
@@ -121,9 +130,9 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString());
|
||||
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
|
||||
if (index != null) {
|
||||
planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentPlan.isFavorite, index: index));
|
||||
}
|
||||
planRepository.emitFavoriteStateToFeed(
|
||||
FavoriteState(isFavorite: currentPlan.isFavorite, index: index ?? 0, slug: slug),
|
||||
);
|
||||
emit(state.copyWith(planModel: currentPlan, error: null));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -12,9 +12,9 @@ class PlanRepository {
|
||||
final _planLikeStateStreamController = StreamController<LikesState>.broadcast();
|
||||
final _planFavoriteStateStreamController = StreamController<FavoriteState>.broadcast();
|
||||
final _planCommentsStateStreamController = StreamController<CommentsState>.broadcast();
|
||||
Stream get planLikeState => _planLikeStateStreamController.stream;
|
||||
Stream get planFavoriteState => _planFavoriteStateStreamController.stream;
|
||||
Stream get planCommentsState => _planCommentsStateStreamController.stream;
|
||||
Stream<LikesState> get planLikeState => _planLikeStateStreamController.stream;
|
||||
Stream<FavoriteState> get planFavoriteState => _planFavoriteStateStreamController.stream;
|
||||
Stream<CommentsState> get planCommentsState => _planCommentsStateStreamController.stream;
|
||||
|
||||
Future<PlanModel> getPlan(String slug) async {
|
||||
return planService.getPlan(slug);
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -1,25 +1,197 @@
|
||||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:easy_debounce/easy_debounce.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
|
||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
|
||||
import 'package:eatvio_app/features/plans/repositories/plans_repository.dart';
|
||||
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
|
||||
class PlansCubit extends Cubit<PlansState> {
|
||||
final PlansRepository plansRepository;
|
||||
final PlanRepository planRepository;
|
||||
|
||||
static const Duration _debounceDuration = Duration(milliseconds: 200);
|
||||
|
||||
late final StreamSubscription<LikesState> likesStateSubscription;
|
||||
late final StreamSubscription<FavoriteState> favoriteStateSubscription;
|
||||
late final StreamSubscription<CommentsState> commentsStateSubscription;
|
||||
|
||||
final Set<String> _pendingDebounceTags = {};
|
||||
|
||||
PlansCubit({
|
||||
required this.plansRepository,
|
||||
}) : super(const PlansState());
|
||||
required this.planRepository,
|
||||
}) : super(const PlansState()) {
|
||||
likesStateSubscription = planRepository.planLikeState.listen(_changePlanLikeState);
|
||||
favoriteStateSubscription = planRepository.planFavoriteState.listen(_changePlanFavoriteState);
|
||||
commentsStateSubscription = planRepository.planCommentsState.listen(_changePlanCommentsState);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() async {
|
||||
for (final tag in _pendingDebounceTags) {
|
||||
EasyDebounce.cancel(tag);
|
||||
}
|
||||
_pendingDebounceTags.clear();
|
||||
await likesStateSubscription.cancel();
|
||||
await favoriteStateSubscription.cancel();
|
||||
await commentsStateSubscription.cancel();
|
||||
await super.close();
|
||||
}
|
||||
|
||||
Future<void> getPlans(String slug) async {
|
||||
emit(const PlansState.loading());
|
||||
try {
|
||||
emit(PlansState.loaded(plansList: await plansRepository.getPlansBySlug(slug)));
|
||||
final plansList = await plansRepository.getPlansBySlug(slug);
|
||||
if (!isClosed) emit(PlansState.loaded(plansList: plansList));
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString());
|
||||
emit(PlansState.error(errorMessage: e.toString()));
|
||||
if (!isClosed) emit(PlansState.error(errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> likePlan(String slug) async {
|
||||
final plan = _planBySlug(slug);
|
||||
if (plan == null) return;
|
||||
|
||||
final wasLikedByMe = plan.wasLikedByMe;
|
||||
final totalLikes = plan.totalLikes;
|
||||
|
||||
_updatePlanBySlug(
|
||||
slug,
|
||||
(plan) => plan.copyWith(
|
||||
wasLikedByMe: !plan.wasLikedByMe,
|
||||
totalLikes: plan.wasLikedByMe ? plan.totalLikes - 1 : plan.totalLikes + 1,
|
||||
),
|
||||
);
|
||||
|
||||
_debounce('profile_like_plan_$slug', () async {
|
||||
try {
|
||||
await planRepository.likePlan(slug);
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
if (isClosed) return;
|
||||
_updatePlanBySlug(
|
||||
slug,
|
||||
(plan) => plan.copyWith(wasLikedByMe: wasLikedByMe, totalLikes: totalLikes),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> addPlanToFavorite(String slug) => _changeFavorite(slug, true);
|
||||
|
||||
Future<void> removePlanFromFavorite(String slug) => _changeFavorite(slug, false);
|
||||
|
||||
Future<void> _changeFavorite(String slug, bool isFavorite) async {
|
||||
final plan = _planBySlug(slug);
|
||||
if (plan == null) return;
|
||||
|
||||
final previousIsFavorite = plan.isFavorite;
|
||||
|
||||
_updatePlanBySlug(slug, (plan) => plan.copyWith(isFavorite: isFavorite));
|
||||
|
||||
_debounce('profile_favorite_$slug', () async {
|
||||
try {
|
||||
if (isFavorite) {
|
||||
await planRepository.addToFavorite(slug);
|
||||
} else {
|
||||
await planRepository.removeFromFavorite(slug);
|
||||
}
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
if (isClosed) return;
|
||||
_updatePlanBySlug(slug, (plan) => plan.copyWith(isFavorite: previousIsFavorite));
|
||||
showErrorToast(S.current.error_try_again_later);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _changePlanLikeState(LikesState likesState) {
|
||||
_updatePlan(
|
||||
slug: likesState.slug,
|
||||
index: likesState.index,
|
||||
transform: (plan) => plan.copyWith(
|
||||
totalLikes: likesState.totalLikes,
|
||||
wasLikedByMe: likesState.wasLikedByMe,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _changePlanFavoriteState(FavoriteState favoriteState) {
|
||||
_updatePlan(
|
||||
slug: favoriteState.slug,
|
||||
index: favoriteState.index,
|
||||
transform: (plan) => plan.copyWith(isFavorite: favoriteState.isFavorite),
|
||||
);
|
||||
}
|
||||
|
||||
void _changePlanCommentsState(CommentsState commentsState) {
|
||||
_updatePlan(
|
||||
slug: commentsState.slug,
|
||||
index: commentsState.index,
|
||||
transform: (plan) => plan.copyWith(totalComments: commentsState.totalComments),
|
||||
);
|
||||
}
|
||||
|
||||
void _updatePlan({
|
||||
required String? slug,
|
||||
required int index,
|
||||
required PlanModel Function(PlanModel plan) transform,
|
||||
}) {
|
||||
if (slug != null) {
|
||||
_updatePlanBySlug(slug, transform);
|
||||
} else {
|
||||
_updatePlanByIndex(index, transform);
|
||||
}
|
||||
}
|
||||
|
||||
void _updatePlanBySlug(String slug, PlanModel Function(PlanModel plan) transform) {
|
||||
final current = state;
|
||||
if (current is! PlansStateLoaded || isClosed) return;
|
||||
|
||||
final index = current.plansList.indexWhere((plan) => plan.slug == slug);
|
||||
if (index == -1) return;
|
||||
|
||||
_emitPlanAt(current, index, transform);
|
||||
}
|
||||
|
||||
void _updatePlanByIndex(int index, PlanModel Function(PlanModel plan) transform) {
|
||||
final current = state;
|
||||
if (current is! PlansStateLoaded || isClosed) return;
|
||||
if (index < 0 || index >= current.plansList.length) return;
|
||||
|
||||
_emitPlanAt(current, index, transform);
|
||||
}
|
||||
|
||||
void _emitPlanAt(PlansStateLoaded current, int index, PlanModel Function(PlanModel plan) transform) {
|
||||
final plansList = [...current.plansList];
|
||||
plansList[index] = transform(plansList[index]);
|
||||
emit(current.copyWith(plansList: plansList));
|
||||
}
|
||||
|
||||
PlanModel? _planBySlug(String slug) {
|
||||
final current = state;
|
||||
if (current is! PlansStateLoaded) return null;
|
||||
|
||||
for (final plan in current.plansList) {
|
||||
if (plan.slug == slug) return plan;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void _debounce(String tag, Future<void> Function() action) {
|
||||
_pendingDebounceTags.add(tag);
|
||||
EasyDebounce.debounce(tag, _debounceDuration, () async {
|
||||
_pendingDebounceTags.remove(tag);
|
||||
await action();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,6 +97,7 @@ class ProfileCubit extends Cubit<ProfileState> {
|
||||
void updateFeedBlogPostList(FeedBlogPostModel feedBlogPostModel, bool wasLikedByMe) {
|
||||
List<FeedBlogPostModel> feedBlogPostList = [...(state as ProfileStateLoaded).blogPosts];
|
||||
final int index = feedBlogPostList.indexOf(feedBlogPostModel);
|
||||
if (index == -1) return;
|
||||
feedBlogPostList[index] = feedBlogPostModel.copyWith(
|
||||
wasLikedByMe: wasLikedByMe,
|
||||
totalLikes: wasLikedByMe == false ? feedBlogPostList[index].totalLikes - 1 : feedBlogPostList[index].totalLikes + 1,
|
||||
|
||||
@@ -205,24 +205,27 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFF6FAFF),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
'${state.consultantInfo!.ratingPlace}-й в рейтинге',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: appTheme.blueA400,
|
||||
if (state.consultantInfo!.ratingPlace != null)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFF6FAFF),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
S.of(context).rating_place(
|
||||
state.consultantInfo!.ratingPlace!,
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (state
|
||||
@@ -331,6 +334,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
}
|
||||
|
||||
Scaffold _myProfileScreen(ProfileStateLoaded state) {
|
||||
final consultantInfo = state.consultantInfo;
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.grey.shade200,
|
||||
appBar: AppBar(
|
||||
@@ -360,7 +364,8 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
_header(state),
|
||||
if (state.profile.roles.contains('consultant'))
|
||||
if (state.profile.roles.contains('consultant') &&
|
||||
consultantInfo != null)
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -376,31 +381,30 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFF6FAFF),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
'${state.consultantInfo!.ratingPlace}-й в рейтинге',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: appTheme.blueA400,
|
||||
if (consultantInfo.ratingPlace != null)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFF6FAFF),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
S.of(context).rating_place(
|
||||
consultantInfo.ratingPlace!,
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (state
|
||||
.consultantInfo!
|
||||
.educationModel
|
||||
.hasMedicalEducation ==
|
||||
1)
|
||||
if (consultantInfo.educationModel.hasMedicalEducation == 1)
|
||||
const Row(
|
||||
children: [
|
||||
SizedBox(width: 16),
|
||||
@@ -451,6 +455,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
if (!state.profile.roles.contains('consultant') || hidePlans) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final profileSlug = state.profile.slug;
|
||||
return BlocBuilder<PlansCubit, PlansState>(
|
||||
bloc: plansCubit,
|
||||
builder: (BuildContext context, PlansState state) {
|
||||
@@ -486,7 +491,16 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
});
|
||||
},
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
return PlanWidget(plan: state.plansList[index], index: index);
|
||||
return PlanWidget(
|
||||
plan: state.plansList[index],
|
||||
index: index,
|
||||
showPriceOnCover: true,
|
||||
onLikeTap: (slug) => plansCubit.likePlan(slug),
|
||||
onToggleFavorite: (slug, isFavorite) => isFavorite
|
||||
? plansCubit.removePlanFromFavorite(slug)
|
||||
: plansCubit.addPlanToFavorite(slug),
|
||||
onPlanChanged: () => plansCubit.getPlans(profileSlug),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
@@ -895,10 +909,11 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
}
|
||||
|
||||
SingleChildRenderObjectWidget _socialLinks(ProfileStateLoaded state) {
|
||||
if (!state.profile.roles.contains('consultant') &&
|
||||
state.consultantInfo != null) {
|
||||
final consultantInfo = state.consultantInfo;
|
||||
if (!state.profile.roles.contains('consultant') || consultantInfo == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final educationModel = consultantInfo.educationModel;
|
||||
return Padding(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 4) +
|
||||
@@ -913,47 +928,34 @@ class _ProfileScreenState extends State<ProfileScreen> {
|
||||
_socialLinkButton(
|
||||
() {
|
||||
launchUrl(
|
||||
Uri.parse(
|
||||
state.consultantInfo!.educationModel.vkLink ?? '',
|
||||
),
|
||||
Uri.parse(educationModel.vkLink ?? ''),
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
},
|
||||
'assets/icons/vk.svg',
|
||||
state.consultantInfo!.educationModel.vkLink!.isEmpty
|
||||
? true
|
||||
: false,
|
||||
educationModel.vkLink?.isEmpty ?? true,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
_socialLinkButton(
|
||||
() {
|
||||
launchUrl(
|
||||
Uri.parse(
|
||||
state.consultantInfo!.educationModel.tgLink ?? '',
|
||||
),
|
||||
Uri.parse(educationModel.tgLink ?? ''),
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
},
|
||||
'assets/icons/telegram.svg',
|
||||
state.consultantInfo!.educationModel.tgLink!.isEmpty
|
||||
? true
|
||||
: false,
|
||||
educationModel.tgLink?.isEmpty ?? true,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
_socialLinkButton(
|
||||
() {
|
||||
launchUrl(
|
||||
Uri.parse(
|
||||
state.consultantInfo!.educationModel.personalSiteLink ??
|
||||
'',
|
||||
),
|
||||
Uri.parse(educationModel.personalSiteLink ?? ''),
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
},
|
||||
'assets/icons/web.svg',
|
||||
state.consultantInfo!.educationModel.personalSiteLink!.isEmpty
|
||||
? true
|
||||
: false,
|
||||
educationModel.personalSiteLink?.isEmpty ?? true,
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -191,21 +191,24 @@ class _ProfileBlogPostWidgetState extends State<ProfileBlogPostWidget> {
|
||||
? Colors.red.withValues(alpha: 0.8)
|
||||
: null,
|
||||
onTap: () async {
|
||||
final nextLiked = !isLiked;
|
||||
setState(() {
|
||||
isLiked = !isLiked;
|
||||
isLiked ? totalLikes++ : totalLikes--;
|
||||
isLiked = nextLiked;
|
||||
nextLiked ? totalLikes++ : totalLikes--;
|
||||
});
|
||||
isLiked
|
||||
? await context.read<FeedCubit>().likePost(
|
||||
post.id,
|
||||
)
|
||||
: await context.read<FeedCubit>().unlikedPost(
|
||||
post.id,
|
||||
);
|
||||
widget.profileCubit.updateFeedBlogPostList(
|
||||
post,
|
||||
isLiked ? false : true,
|
||||
nextLiked,
|
||||
);
|
||||
if (nextLiked) {
|
||||
await context.read<FeedCubit>().likePost(
|
||||
post.id,
|
||||
);
|
||||
} else {
|
||||
await context.read<FeedCubit>().unlikedPost(
|
||||
post.id,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -80,29 +80,33 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateProfileDetails({
|
||||
Future<bool> updateProfileDetails({
|
||||
required ProfileDetailsModel profileDetailsModel,
|
||||
}) async {
|
||||
try {
|
||||
await settingsRepository.updateProfileDetails(
|
||||
profileDetailsModel: profileDetailsModel,
|
||||
);
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
return false;
|
||||
} finally {
|
||||
await init();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateProfileSettings({
|
||||
Future<bool> updateProfileSettings({
|
||||
required ProfileSettingsModel profileSettingsModel,
|
||||
}) async {
|
||||
try {
|
||||
await settingsRepository.updateProfileSettings(
|
||||
profileSettingsModel: profileSettingsModel,
|
||||
);
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
return false;
|
||||
} finally {
|
||||
await init();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:eatvio_app/core/data/selectionPopupModel/selection_popup_model.dart';
|
||||
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_drop_down.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart';
|
||||
@@ -10,6 +11,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class GeneralInfoScreen extends StatefulWidget {
|
||||
final SettingsEntity settingsEntity;
|
||||
@@ -233,7 +235,7 @@ class _GeneralInfoScreenState extends State<GeneralInfoScreen> {
|
||||
setState(() {
|
||||
isLoading = true;
|
||||
});
|
||||
await widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
final detailsSaved = await widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith(
|
||||
firstName: firstNameController.text,
|
||||
lastName: lastNameController.text,
|
||||
@@ -244,7 +246,7 @@ class _GeneralInfoScreenState extends State<GeneralInfoScreen> {
|
||||
lang: languageController.text,
|
||||
),
|
||||
);
|
||||
await widget.settingsEntity.settingsCubit.updateProfileSettings(
|
||||
final settingsSaved = await widget.settingsEntity.settingsCubit.updateProfileSettings(
|
||||
profileSettingsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileSettings.copyWith(
|
||||
isPublicProfile: isPublicProfile.value,
|
||||
),
|
||||
@@ -253,6 +255,10 @@ class _GeneralInfoScreenState extends State<GeneralInfoScreen> {
|
||||
setState(() {
|
||||
isLoading = false;
|
||||
});
|
||||
if (detailsSaved && settingsSaved) {
|
||||
showSuccessToast(S.of(context).data_saved_successfully);
|
||||
context.pop();
|
||||
}
|
||||
},
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Ink(
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart';
|
||||
import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
@@ -137,8 +138,8 @@ class _OtherInfoScreenState extends State<OtherInfoScreen> {
|
||||
|
||||
InkWell _saveButton() {
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
onTap: () async {
|
||||
final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith(
|
||||
aboutAlergy: aboutAllergyController.text,
|
||||
aboutTakingPils: aboutTakingPillsController.text,
|
||||
@@ -148,7 +149,11 @@ class _OtherInfoScreenState extends State<OtherInfoScreen> {
|
||||
additionalInfo: additionalInfoController.text,
|
||||
),
|
||||
);
|
||||
GoRouter.of(context).pop();
|
||||
if (!mounted) return;
|
||||
if (saved) {
|
||||
showSuccessToast(S.of(context).data_saved_successfully);
|
||||
GoRouter.of(context).pop();
|
||||
}
|
||||
},
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Ink(
|
||||
|
||||
@@ -2,6 +2,8 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart';
|
||||
import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart';
|
||||
import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
@@ -200,7 +202,7 @@ class _PhysicalActivityScreenState extends State<PhysicalActivityScreen> {
|
||||
|
||||
InkWell _saveButton() {
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
onTap: () async {
|
||||
late final double activityCoefficient;
|
||||
switch (_physicalActivity) {
|
||||
case PhysicalActivity.minimum:
|
||||
@@ -221,12 +223,16 @@ class _PhysicalActivityScreenState extends State<PhysicalActivityScreen> {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith(
|
||||
activityCoefficient: activityCoefficient,
|
||||
),
|
||||
);
|
||||
GoRouter.of(context).pop();
|
||||
if (!mounted) return;
|
||||
if (saved) {
|
||||
showSuccessToast(S.of(context).data_saved_successfully);
|
||||
GoRouter.of(context).pop();
|
||||
}
|
||||
},
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Ink(
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart';
|
||||
import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -108,8 +109,8 @@ class _PhysicalFormScreenState extends State<PhysicalFormScreen> {
|
||||
|
||||
InkWell _saveButton() {
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
onTap: () async {
|
||||
final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith(
|
||||
chestCircumference: int.parse(chestCircumferenceController.text),
|
||||
waistCircumference: int.parse(waistCircumferenceController.text),
|
||||
@@ -118,7 +119,11 @@ class _PhysicalFormScreenState extends State<PhysicalFormScreen> {
|
||||
weight: double.parse(weightController.text),
|
||||
),
|
||||
);
|
||||
GoRouter.of(context).pop();
|
||||
if (!mounted) return;
|
||||
if (saved) {
|
||||
showSuccessToast(S.of(context).data_saved_successfully);
|
||||
GoRouter.of(context).pop();
|
||||
}
|
||||
},
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Ink(
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart';
|
||||
import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -114,8 +115,8 @@ class _PressureScreenState extends State<PressureScreen> {
|
||||
|
||||
InkWell _saveButton() {
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
onTap: () async {
|
||||
final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails(
|
||||
profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith(
|
||||
bloodPressureUp: int.parse(bloodPressureUpController.text),
|
||||
bloodPressureDown: int.parse(bloodPressureDownController.text),
|
||||
@@ -123,7 +124,11 @@ class _PressureScreenState extends State<PressureScreen> {
|
||||
hasHypo: hypo.value,
|
||||
),
|
||||
);
|
||||
GoRouter.of(context).pop();
|
||||
if (!mounted) return;
|
||||
if (saved) {
|
||||
showSuccessToast(S.of(context).data_saved_successfully);
|
||||
GoRouter.of(context).pop();
|
||||
}
|
||||
},
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Ink(
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -76,28 +76,30 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
static String m22(percent, amount) =>
|
||||
"Discount ${percent}% — you save ${amount} ₽";
|
||||
|
||||
static String m23(date) => "Start: ${date}";
|
||||
static String m23(place) => "#${place} in the ranking";
|
||||
|
||||
static String m24(step) => "шаг ${step} из 2";
|
||||
static String m24(date) => "Start: ${date}";
|
||||
|
||||
static String m25(planName, name) =>
|
||||
static String m25(step) => "шаг ${step} из 2";
|
||||
|
||||
static String m26(planName, name) =>
|
||||
"Завтра начинается план «${planName}» с пользователем ${name}";
|
||||
|
||||
static String m26(planName) =>
|
||||
static String m27(planName) =>
|
||||
"Завтра начнется прохождение плана «${planName}»";
|
||||
|
||||
static String m27(name, planName) =>
|
||||
static String m28(name, planName) =>
|
||||
"Пользователь ${name} отменил подписку на план «${planName}»";
|
||||
|
||||
static String m28(name, planName) =>
|
||||
static String m29(name, planName) =>
|
||||
"Пользователь ${name} оплатил план «${planName}»";
|
||||
|
||||
static String m29(name, planName) =>
|
||||
static String m30(name, planName) =>
|
||||
"Пользователь ${name} подписался на план «${planName}»";
|
||||
|
||||
static String m30(percent) => "Downloading… ${percent}%";
|
||||
static String m31(percent) => "Downloading… ${percent}%";
|
||||
|
||||
static String m31(planName) => "Вы отменили подписку на план «${planName}»";
|
||||
static String m32(planName) => "Вы отменили подписку на план «${planName}»";
|
||||
|
||||
final messages = _notInlinedMessages(_notInlinedMessages);
|
||||
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
|
||||
@@ -354,6 +356,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"customer_price": MessageLookupByLibrary.simpleMessage(
|
||||
"Цена для покупателя",
|
||||
),
|
||||
"data_saved_successfully": MessageLookupByLibrary.simpleMessage(
|
||||
"Data saved successfully",
|
||||
),
|
||||
"date_has_ben_set": MessageLookupByLibrary.simpleMessage(
|
||||
"Дата старта начала консультации установлена",
|
||||
),
|
||||
@@ -448,6 +453,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"error_desc": MessageLookupByLibrary.simpleMessage(
|
||||
"Произошла ошибка. Мы уже работаем над её устранением. Попробуйте позже",
|
||||
),
|
||||
"error_try_again_later": MessageLookupByLibrary.simpleMessage(
|
||||
"Something went wrong. Please try again later.",
|
||||
),
|
||||
"exit": MessageLookupByLibrary.simpleMessage("Выйти"),
|
||||
"expand": MessageLookupByLibrary.simpleMessage("Показать полностью"),
|
||||
"explainResonOfCancelation": MessageLookupByLibrary.simpleMessage(
|
||||
@@ -955,6 +963,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"rating_history": MessageLookupByLibrary.simpleMessage(
|
||||
"Начисление рейтинга",
|
||||
),
|
||||
"rating_place": m23,
|
||||
"reasonExample": MessageLookupByLibrary.simpleMessage("Заказал по ошибке"),
|
||||
"recipe_author": MessageLookupByLibrary.simpleMessage("Автор рецепта"),
|
||||
"recipe_publishing": MessageLookupByLibrary.simpleMessage(
|
||||
@@ -1048,13 +1057,13 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Выбрана дата старта",
|
||||
),
|
||||
"startDiet": MessageLookupByLibrary.simpleMessage("Начать диету"),
|
||||
"start_date_label": m23,
|
||||
"start_date_label": m24,
|
||||
"statistic": MessageLookupByLibrary.simpleMessage("Статистика"),
|
||||
"step": MessageLookupByLibrary.simpleMessage("Шаг"),
|
||||
"step_by_step_photo_recipe": MessageLookupByLibrary.simpleMessage(
|
||||
"Пошаговый фоторецепт",
|
||||
),
|
||||
"step_widget": m24,
|
||||
"step_widget": m25,
|
||||
"successfully_published": MessageLookupByLibrary.simpleMessage(
|
||||
"успешно опубликован",
|
||||
),
|
||||
@@ -1079,8 +1088,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"toOffer": MessageLookupByLibrary.simpleMessage("Предложить"),
|
||||
"to_draft": MessageLookupByLibrary.simpleMessage("В черновик"),
|
||||
"to_order": MessageLookupByLibrary.simpleMessage("Заказать"),
|
||||
"tommorowPlanWithUserWillStart": m25,
|
||||
"tomorrowYourPlanWillStart": m26,
|
||||
"tommorowPlanWithUserWillStart": m26,
|
||||
"tomorrowYourPlanWillStart": m27,
|
||||
"try_again": MessageLookupByLibrary.simpleMessage("Попробовать снова"),
|
||||
"try_again_2": MessageLookupByLibrary.simpleMessage("Попробуйте ещё раз"),
|
||||
"typeAmoutOfReturn": MessageLookupByLibrary.simpleMessage(
|
||||
@@ -1114,7 +1123,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Верхние показатели давления:",
|
||||
),
|
||||
"upper": MessageLookupByLibrary.simpleMessage("Верхнее"),
|
||||
"userCanceldThePlanSubscription": m27,
|
||||
"userCanceldThePlanSubscription": m28,
|
||||
"userConfirmedPlanCompletion": MessageLookupByLibrary.simpleMessage(
|
||||
"Пользователь подтвердил прохождения плана. В ближайшее время Вы получите",
|
||||
),
|
||||
@@ -1122,8 +1131,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Пользователь подтвердил прохождения плана.",
|
||||
),
|
||||
"userPaidThePlan": m28,
|
||||
"userSubscribedToPlan": m29,
|
||||
"userPaidThePlan": m29,
|
||||
"userSubscribedToPlan": m30,
|
||||
"user_authorization": MessageLookupByLibrary.simpleMessage(
|
||||
"Аутентификация",
|
||||
),
|
||||
@@ -1201,7 +1210,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
),
|
||||
"video_call_recordings_download_success":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Recording saved to Downloads/Itvio",
|
||||
"Recording saved to Downloads/Eatvio",
|
||||
),
|
||||
"video_call_recordings_download_success_ios":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
@@ -1210,7 +1219,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"video_call_recordings_downloading": MessageLookupByLibrary.simpleMessage(
|
||||
"Downloading…",
|
||||
),
|
||||
"video_call_recordings_downloading_percent": m30,
|
||||
"video_call_recordings_downloading_percent": m31,
|
||||
"video_call_recordings_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"No video consultations yet",
|
||||
),
|
||||
@@ -1304,7 +1313,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"youCanComplain": MessageLookupByLibrary.simpleMessage(
|
||||
"Если вас что-то не устроило, вы можете подать жалобу",
|
||||
),
|
||||
"youCanceledSubscriptionToPlan": m31,
|
||||
"youCanceledSubscriptionToPlan": m32,
|
||||
"youShureYouWantToCancelOrder": MessageLookupByLibrary.simpleMessage(
|
||||
"Вы уверены, что хотите отменить заказ?",
|
||||
),
|
||||
|
||||
@@ -69,9 +69,11 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
static String m22(percent, amount) =>
|
||||
"Скидка ${percent}% — вы экономите ${amount} ₽";
|
||||
|
||||
static String m23(date) => "Старт: ${date}";
|
||||
static String m23(place) => "${place}-й в рейтинге";
|
||||
|
||||
static String m30(percent) => "Скачивание… ${percent}%";
|
||||
static String m24(date) => "Старт: ${date}";
|
||||
|
||||
static String m31(percent) => "Скачивание… ${percent}%";
|
||||
|
||||
final messages = _notInlinedMessages(_notInlinedMessages);
|
||||
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
|
||||
@@ -165,6 +167,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"customer_price": MessageLookupByLibrary.simpleMessage(
|
||||
"Цена для покупателя",
|
||||
),
|
||||
"data_saved_successfully": MessageLookupByLibrary.simpleMessage(
|
||||
"Данные успешно сохранены",
|
||||
),
|
||||
"date_of_birth": MessageLookupByLibrary.simpleMessage("Дата рождения"),
|
||||
"day": MessageLookupByLibrary.simpleMessage("День"),
|
||||
"days": MessageLookupByLibrary.simpleMessage("дней"),
|
||||
@@ -224,6 +229,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"enter_promo_code": MessageLookupByLibrary.simpleMessage(
|
||||
"Введите промокод",
|
||||
),
|
||||
"error_try_again_later": MessageLookupByLibrary.simpleMessage(
|
||||
"Произошла ошибка. Попробуйте ещё раз через некоторое время",
|
||||
),
|
||||
"exit": MessageLookupByLibrary.simpleMessage("Выйти"),
|
||||
"expand": MessageLookupByLibrary.simpleMessage("Показать полностью"),
|
||||
"fats": MessageLookupByLibrary.simpleMessage("Жиры"),
|
||||
@@ -557,6 +565,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"public_diet_state": MessageLookupByLibrary.simpleMessage("Публичная"),
|
||||
"publish": MessageLookupByLibrary.simpleMessage("Опубликовать"),
|
||||
"published": MessageLookupByLibrary.simpleMessage("Опубликованные"),
|
||||
"rating_place": m23,
|
||||
"removeFromActive": MessageLookupByLibrary.simpleMessage(
|
||||
"Снять с публикации",
|
||||
),
|
||||
@@ -606,7 +615,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Выбрана дата старта",
|
||||
),
|
||||
"startDiet": MessageLookupByLibrary.simpleMessage("Начать диету"),
|
||||
"start_date_label": m23,
|
||||
"start_date_label": m24,
|
||||
"suggestDiet": MessageLookupByLibrary.simpleMessage("Предложить диету"),
|
||||
"tell_your_schedule": MessageLookupByLibrary.simpleMessage(
|
||||
"Расскажите в свободной форме о том как просыпаетесь, когда едите, когда ложитесь спать:",
|
||||
@@ -696,7 +705,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
),
|
||||
"video_call_recordings_download_success":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Запись сохранена в Загрузки/Itvio",
|
||||
"Запись сохранена в Загрузки/Eatvio",
|
||||
),
|
||||
"video_call_recordings_download_success_ios":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
@@ -705,7 +714,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"video_call_recordings_downloading": MessageLookupByLibrary.simpleMessage(
|
||||
"Скачивание…",
|
||||
),
|
||||
"video_call_recordings_downloading_percent": m30,
|
||||
"video_call_recordings_downloading_percent": m31,
|
||||
"video_call_recordings_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"Пока нет видеоконсультаций",
|
||||
),
|
||||
|
||||
@@ -134,6 +134,16 @@ class S {
|
||||
);
|
||||
}
|
||||
|
||||
/// `Data saved successfully`
|
||||
String get data_saved_successfully {
|
||||
return Intl.message(
|
||||
'Data saved successfully',
|
||||
name: 'data_saved_successfully',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Страна`
|
||||
String get country {
|
||||
return Intl.message('Страна', name: 'country', desc: '', args: []);
|
||||
@@ -5432,10 +5442,10 @@ class S {
|
||||
);
|
||||
}
|
||||
|
||||
/// `Recording saved to Downloads/Itvio`
|
||||
/// `Recording saved to Downloads/Eatvio`
|
||||
String get video_call_recordings_download_success {
|
||||
return Intl.message(
|
||||
'Recording saved to Downloads/Itvio',
|
||||
'Recording saved to Downloads/Eatvio',
|
||||
name: 'video_call_recordings_download_success',
|
||||
desc: '',
|
||||
args: [],
|
||||
@@ -5521,6 +5531,26 @@ class S {
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `#{place} in the ranking`
|
||||
String rating_place(int place) {
|
||||
return Intl.message(
|
||||
'#$place in the ranking',
|
||||
name: 'rating_place',
|
||||
desc: '',
|
||||
args: [place],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Something went wrong. Please try again later.`
|
||||
String get error_try_again_later {
|
||||
return Intl.message(
|
||||
'Something went wrong. Please try again later.',
|
||||
name: 'error_try_again_later',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AppLocalizationDelegate extends LocalizationsDelegate<S> {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"last_name": "Фамилия",
|
||||
"what_is_your_name": "Как вас зовут?",
|
||||
"date_of_birth": "Дата рождения",
|
||||
"data_saved_successfully": "Data saved successfully",
|
||||
"country": "Страна",
|
||||
"Russia": "Россия",
|
||||
"city": "Город",
|
||||
@@ -829,7 +830,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",
|
||||
@@ -837,5 +838,12 @@
|
||||
"video_call_recordings_period_week": "7 days",
|
||||
"video_call_recordings_period_current_month": "Current month",
|
||||
"video_call_recordings_period_prev_month": "Previous month",
|
||||
"video_call_recordings_period_all": "All time"
|
||||
"video_call_recordings_period_all": "All time",
|
||||
"rating_place": "#{place} in the ranking",
|
||||
"@rating_place": {
|
||||
"placeholders": {
|
||||
"place": {"type": "int"}
|
||||
}
|
||||
},
|
||||
"error_try_again_later": "Something went wrong. Please try again later."
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"last_name": "Фамилия",
|
||||
"what_is_your_name": "Как вас зовут?",
|
||||
"date_of_birth": "Дата рождения",
|
||||
"data_saved_successfully": "Данные успешно сохранены",
|
||||
"country": "Страна",
|
||||
"Russia": "Россия",
|
||||
"city": "Город",
|
||||
@@ -584,7 +585,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": "Видеоконсультация со специалистом по питанию",
|
||||
@@ -592,5 +593,12 @@
|
||||
"video_call_recordings_period_week": "7 дней",
|
||||
"video_call_recordings_period_current_month": "Текущий месяц",
|
||||
"video_call_recordings_period_prev_month": "Прошлый месяц",
|
||||
"video_call_recordings_period_all": "Всё время"
|
||||
"video_call_recordings_period_all": "Всё время",
|
||||
"rating_place": "{place}-й в рейтинге",
|
||||
"@rating_place": {
|
||||
"placeholders": {
|
||||
"place": {"type": "int"}
|
||||
}
|
||||
},
|
||||
"error_try_again_later": "Произошла ошибка. Попробуйте ещё раз через некоторое время"
|
||||
}
|
||||
|
||||
@@ -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
@@ -8,6 +8,7 @@ import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:intl/date_symbol_data_local.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:table_calendar/table_calendar.dart';
|
||||
|
||||
class FakeDiaryCubit extends Cubit<DiaryState> implements DiaryCubit {
|
||||
@@ -28,15 +29,20 @@ void main() {
|
||||
theme: ThemeHelper().themeData(),
|
||||
builder: (context, appChild) {
|
||||
return MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(textScale)),
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(textScale)),
|
||||
child: appChild!,
|
||||
);
|
||||
},
|
||||
localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates],
|
||||
localizationsDelegates: const [
|
||||
S.delegate,
|
||||
...GlobalMaterialLocalizations.delegates,
|
||||
],
|
||||
supportedLocales: const [Locale('ru')],
|
||||
home: BlocProvider<DiaryCubit>.value(
|
||||
value: cubit,
|
||||
child: Scaffold(body: child),
|
||||
child: Scaffold(body: SingleChildScrollView(child: child)),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -52,19 +58,124 @@ void main() {
|
||||
testWidgets('scales weekday row when system font is large', (tester) async {
|
||||
const textScale = 2.0;
|
||||
final cubit = FakeDiaryCubit(const DiaryState.loading());
|
||||
await tester.pumpWidget(wrap(const CalendarWidget(), cubit, textScale: textScale));
|
||||
await tester.pumpWidget(
|
||||
wrap(const CalendarWidget(), cubit, textScale: textScale),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
final calendar = tester.widget<TableCalendar<dynamic>>(find.byType(TableCalendar<dynamic>));
|
||||
expect(calendar.daysOfWeekHeight, greaterThan(16 * textScale * 0.9));
|
||||
final calendar = tester.widget<TableCalendar<dynamic>>(
|
||||
find.byType(TableCalendar<dynamic>),
|
||||
);
|
||||
expect(calendar.rowHeight, 52 * textScale);
|
||||
|
||||
expect(find.text('пн'), findsWidgets);
|
||||
final weekday = tester.renderObject<RenderParagraph>(find.text('пн').first);
|
||||
expect(weekday.size.height, lessThanOrEqualTo(calendar.daysOfWeekHeight + 0.5));
|
||||
final weekday = tester.renderObject<RenderParagraph>(
|
||||
find.text('пн').first,
|
||||
);
|
||||
expect(weekday.size.height, greaterThan(16 * textScale * 0.9));
|
||||
expect(
|
||||
tester.getBottomLeft(find.text('пн')).dy,
|
||||
lessThanOrEqualTo(
|
||||
tester.getTopLeft(find.byType(TableCalendar<dynamic>)).dy,
|
||||
),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
await cubit.close();
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'header chevron switches directly between the focused week and month',
|
||||
(tester) async {
|
||||
final cubit = FakeDiaryCubit(const DiaryState.loading());
|
||||
addTearDown(cubit.close);
|
||||
final widget = find.byType(CalendarWidget);
|
||||
final date = DateTime(2026, 11, 23);
|
||||
await tester.pumpWidget(wrap(CalendarWidget(date: date), cubit));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final header = find.text(DateFormat.yMMMM('ru_RU').format(date));
|
||||
final weekHeight = tester.getSize(widget).height;
|
||||
expect(find.text('23').hitTestable(), findsOneWidget);
|
||||
expect(find.text('9').hitTestable(), findsNothing);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.keyboard_arrow_down_rounded));
|
||||
await tester.pump();
|
||||
expect(header, findsOneWidget);
|
||||
expect(tester.getSize(widget).height, weekHeight + 5 * 52);
|
||||
expect(find.text('9').hitTestable(), findsOneWidget);
|
||||
expect(find.text('23').hitTestable(), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.keyboard_arrow_up_rounded));
|
||||
await tester.pump();
|
||||
expect(tester.getSize(widget).height, weekHeight);
|
||||
expect(find.text('23').hitTestable(), findsOneWidget);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('horizontal swipes still page by week and by month', (
|
||||
tester,
|
||||
) async {
|
||||
final cubit = FakeDiaryCubit(const DiaryState.loading());
|
||||
addTearDown(cubit.close);
|
||||
await tester.pumpWidget(
|
||||
wrap(CalendarWidget(date: DateTime(2026, 11, 23)), cubit),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final days = find.byType(TableCalendar<dynamic>);
|
||||
await tester.fling(days, const Offset(-450, 0), 1000);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('30').hitTestable(), findsOneWidget);
|
||||
expect(find.text('23').hitTestable(), findsNothing);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.keyboard_arrow_down_rounded));
|
||||
await tester.pump();
|
||||
await tester.fling(days, const Offset(-450, 0), 1000);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.text(DateFormat.yMMMM('ru_RU').format(DateTime(2026, 12))),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'dragging the bottom handle resizes the calendar before release',
|
||||
(tester) async {
|
||||
final cubit = FakeDiaryCubit(const DiaryState.loading());
|
||||
addTearDown(cubit.close);
|
||||
final widget = find.byType(CalendarWidget);
|
||||
await tester.pumpWidget(
|
||||
wrap(CalendarWidget(date: DateTime(2026, 11, 23)), cubit),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final weekBottom = tester.getBottomLeft(widget).dy;
|
||||
final centerX = tester.getCenter(widget).dx;
|
||||
final drag = await tester.startGesture(
|
||||
Offset(centerX, weekBottom - 12),
|
||||
);
|
||||
await drag.moveBy(const Offset(0, 64));
|
||||
await tester.pump();
|
||||
expect(tester.getBottomLeft(widget).dy, closeTo(weekBottom + 64, 1));
|
||||
expect(find.text('23').hitTestable(), findsOneWidget);
|
||||
|
||||
await drag.moveBy(const Offset(0, 100));
|
||||
await drag.up();
|
||||
await tester.pumpAndSettle();
|
||||
final monthBottom = weekBottom + 5 * 52;
|
||||
expect(tester.getBottomLeft(widget).dy, closeTo(monthBottom, 1));
|
||||
|
||||
final reverse = await tester.startGesture(
|
||||
Offset(centerX, monthBottom - 12),
|
||||
);
|
||||
await reverse.moveBy(const Offset(0, -160));
|
||||
await tester.pump();
|
||||
expect(tester.getBottomLeft(widget).dy, closeTo(monthBottom - 160, 1));
|
||||
await reverse.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.getBottomLeft(widget).dy, closeTo(weekBottom, 1));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import 'package:easy_debounce/easy_debounce.dart';
|
||||
import 'package:eatvio_app/core/models/pagination_model.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/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart';
|
||||
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
|
||||
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
import 'plans_cubit_slug_sync_test.mocks.dart';
|
||||
|
||||
@GenerateNiceMocks([MockSpec<FeedRepository>(), MockSpec<PlanRepository>()])
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('feed PlansCubit — slug-based stream sync', () {
|
||||
PlanModel plan({required String slug, int totalLikes = 10}) {
|
||||
return PlanModel(
|
||||
id: slug.hashCode,
|
||||
slug: slug,
|
||||
name: slug,
|
||||
image: 'https://example.com/image.jpg',
|
||||
duration: 7,
|
||||
state: 'active',
|
||||
type: const PlanType(
|
||||
fit: true,
|
||||
slim: false,
|
||||
behavior: false,
|
||||
wellness: false,
|
||||
),
|
||||
details: 'details',
|
||||
packetsCount: 1,
|
||||
minPriceOfOptions: 1000.0,
|
||||
maxPriceOfOptions: 2000.0,
|
||||
author: const Author(
|
||||
authorSlug: 'author',
|
||||
authorName: 'Author Name',
|
||||
authorProfileIcon: 'https://example.com/icon.jpg',
|
||||
authorIsMe: false,
|
||||
isEntitySubscribedByMe: null,
|
||||
authorPlaceInRating: null,
|
||||
),
|
||||
totalLikes: totalLikes,
|
||||
totalViews: 100,
|
||||
totalComments: 5,
|
||||
wasLikedByMe: false,
|
||||
isFavorite: false,
|
||||
);
|
||||
}
|
||||
|
||||
PlanPaginationModel pagination(List<PlanModel> plans) {
|
||||
return PlanPaginationModel(
|
||||
data: plans,
|
||||
links: const Links(
|
||||
first: 'https://example.com?page=1',
|
||||
last: 'https://example.com?page=1',
|
||||
prev: null,
|
||||
next: null,
|
||||
),
|
||||
meta: Meta(
|
||||
currentPage: 1,
|
||||
from: 1,
|
||||
lastPage: 1,
|
||||
links: const [],
|
||||
perPage: 10,
|
||||
to: plans.length,
|
||||
total: plans.length,
|
||||
totalMinPrice: 1000,
|
||||
totalMaxPrice: 2000,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
late MockFeedRepository feedRepository;
|
||||
late MockPlanRepository planRepository;
|
||||
late BehaviorSubject<LikesState> likeState;
|
||||
late BehaviorSubject<FavoriteState> favoriteState;
|
||||
late BehaviorSubject<CommentsState> commentsState;
|
||||
late PlansCubit cubit;
|
||||
|
||||
setUp(() async {
|
||||
feedRepository = MockFeedRepository();
|
||||
planRepository = MockPlanRepository();
|
||||
likeState = BehaviorSubject<LikesState>();
|
||||
favoriteState = BehaviorSubject<FavoriteState>();
|
||||
commentsState = BehaviorSubject<CommentsState>();
|
||||
|
||||
when(planRepository.planLikeState).thenAnswer((_) => likeState);
|
||||
when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState);
|
||||
when(planRepository.planCommentsState).thenAnswer((_) => commentsState);
|
||||
|
||||
when(
|
||||
feedRepository.getPlans(
|
||||
query: anyNamed('query'),
|
||||
types: anyNamed('types'),
|
||||
duration: anyNamed('duration'),
|
||||
minPrice: anyNamed('minPrice'),
|
||||
maxPrice: anyNamed('maxPrice'),
|
||||
),
|
||||
).thenAnswer(
|
||||
(_) async => pagination([
|
||||
plan(slug: 'plan-a'),
|
||||
plan(slug: 'plan-b'),
|
||||
]),
|
||||
);
|
||||
|
||||
cubit = PlansCubit(
|
||||
feedRepository: feedRepository,
|
||||
planRepository: planRepository,
|
||||
);
|
||||
await cubit.loadPlans();
|
||||
expect(cubit.state.plans.length, 2);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
EasyDebounce.cancel('loadPlans');
|
||||
EasyDebounce.cancel('like_plan');
|
||||
EasyDebounce.cancel('add_or_remove_plan_from_favorite');
|
||||
if (!cubit.isClosed) {
|
||||
await cubit.close();
|
||||
}
|
||||
await likeState.close();
|
||||
await favoriteState.close();
|
||||
await commentsState.close();
|
||||
});
|
||||
|
||||
test('a like event with a slug updates the matching plan, not the index', () async {
|
||||
likeState.add(
|
||||
const LikesState(
|
||||
slug: 'plan-b',
|
||||
index: 0,
|
||||
totalLikes: 42,
|
||||
wasLikedByMe: true,
|
||||
),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
expect(cubit.state.plans[0].wasLikedByMe, isFalse);
|
||||
expect(cubit.state.plans[0].totalLikes, 10);
|
||||
expect(cubit.state.plans[1].wasLikedByMe, isTrue);
|
||||
expect(cubit.state.plans[1].totalLikes, 42);
|
||||
});
|
||||
|
||||
test('a like event with an unknown slug is a no-op', () async {
|
||||
final before = cubit.state.plans;
|
||||
|
||||
likeState.add(
|
||||
const LikesState(
|
||||
slug: 'unknown-plan',
|
||||
index: 0,
|
||||
totalLikes: 42,
|
||||
wasLikedByMe: true,
|
||||
),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
expect(cubit.state.plans, before);
|
||||
});
|
||||
|
||||
test('a legacy like event without a slug keeps index behaviour', () async {
|
||||
likeState.add(
|
||||
const LikesState(index: 1, totalLikes: 42, wasLikedByMe: true),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
expect(cubit.state.plans[1].wasLikedByMe, isTrue);
|
||||
expect(cubit.state.plans[1].totalLikes, 42);
|
||||
});
|
||||
|
||||
test('a favorite event with a slug updates the matching plan', () async {
|
||||
favoriteState.add(
|
||||
const FavoriteState(slug: 'plan-b', index: 0, isFavorite: true),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
expect(cubit.state.plans[0].isFavorite, isFalse);
|
||||
expect(cubit.state.plans[1].isFavorite, isTrue);
|
||||
});
|
||||
|
||||
test('a comments event with a slug updates the matching plan', () async {
|
||||
commentsState.add(
|
||||
const CommentsState(slug: 'plan-b', index: 0, totalComments: 7),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
expect(cubit.state.plans[0].totalComments, isNot(7));
|
||||
expect(cubit.state.plans[1].totalComments, 7);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:easy_debounce/easy_debounce.dart';
|
||||
import 'package:eatvio_app/core/models/pagination_model.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/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart';
|
||||
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
|
||||
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
import 'plans_cubit_sync_guard_test.mocks.dart';
|
||||
|
||||
@GenerateNiceMocks([MockSpec<FeedRepository>(), MockSpec<PlanRepository>()])
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('feed PlansCubit — index bounds guard', () {
|
||||
const testPlan = PlanModel(
|
||||
id: 1,
|
||||
slug: 'test-plan',
|
||||
name: 'Test Plan',
|
||||
image: 'https://example.com/image.jpg',
|
||||
duration: 7,
|
||||
state: 'active',
|
||||
type: PlanType(fit: true, slim: false, behavior: false, wellness: false),
|
||||
details: 'Test details',
|
||||
packetsCount: 3,
|
||||
minPriceOfOptions: 1000.0,
|
||||
maxPriceOfOptions: 2000.0,
|
||||
author: Author(
|
||||
authorSlug: 'author',
|
||||
authorName: 'Author Name',
|
||||
authorProfileIcon: 'https://example.com/icon.jpg',
|
||||
authorIsMe: false,
|
||||
isEntitySubscribedByMe: null,
|
||||
authorPlaceInRating: null,
|
||||
),
|
||||
totalLikes: 10,
|
||||
totalViews: 100,
|
||||
totalComments: 5,
|
||||
wasLikedByMe: false,
|
||||
isFavorite: false,
|
||||
);
|
||||
|
||||
const plansPagination = PlanPaginationModel(
|
||||
data: [testPlan],
|
||||
links: Links(
|
||||
first: 'https://example.com?page=1',
|
||||
last: 'https://example.com?page=1',
|
||||
prev: null,
|
||||
next: null,
|
||||
),
|
||||
meta: Meta(
|
||||
currentPage: 1,
|
||||
from: 1,
|
||||
lastPage: 1,
|
||||
links: [],
|
||||
perPage: 10,
|
||||
to: 1,
|
||||
total: 1,
|
||||
totalMinPrice: 1000,
|
||||
totalMaxPrice: 2000,
|
||||
),
|
||||
);
|
||||
|
||||
late MockFeedRepository feedRepository;
|
||||
late MockPlanRepository planRepository;
|
||||
late BehaviorSubject<LikesState> likeState;
|
||||
late BehaviorSubject<FavoriteState> favoriteState;
|
||||
late BehaviorSubject<CommentsState> commentsState;
|
||||
|
||||
setUp(() {
|
||||
feedRepository = MockFeedRepository();
|
||||
planRepository = MockPlanRepository();
|
||||
likeState = BehaviorSubject<LikesState>();
|
||||
favoriteState = BehaviorSubject<FavoriteState>();
|
||||
commentsState = BehaviorSubject<CommentsState>();
|
||||
|
||||
when(planRepository.planLikeState).thenAnswer((_) => likeState);
|
||||
when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState);
|
||||
when(planRepository.planCommentsState).thenAnswer((_) => commentsState);
|
||||
|
||||
when(
|
||||
feedRepository.getPlans(
|
||||
query: anyNamed('query'),
|
||||
types: anyNamed('types'),
|
||||
duration: anyNamed('duration'),
|
||||
minPrice: anyNamed('minPrice'),
|
||||
maxPrice: anyNamed('maxPrice'),
|
||||
),
|
||||
).thenAnswer((_) async => plansPagination);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
EasyDebounce.cancel('loadPlans');
|
||||
EasyDebounce.cancel('like_plan');
|
||||
EasyDebounce.cancel('add_or_remove_plan_from_favorite');
|
||||
await likeState.close();
|
||||
await favoriteState.close();
|
||||
await commentsState.close();
|
||||
});
|
||||
|
||||
/// Runs [body] in its own error zone so an unhandled stream-listener error
|
||||
/// is captured instead of failing the test at teardown.
|
||||
Future<List<Object>> errorsFrom(Future<void> Function() body) async {
|
||||
final errors = <Object>[];
|
||||
final done = Completer<void>();
|
||||
runZonedGuarded(
|
||||
() async {
|
||||
try {
|
||||
await body();
|
||||
} finally {
|
||||
done.complete();
|
||||
}
|
||||
},
|
||||
(error, stackTrace) => errors.add(error),
|
||||
);
|
||||
await done.future;
|
||||
return errors;
|
||||
}
|
||||
|
||||
Future<PlansCubit> loadedCubit() async {
|
||||
final cubit = PlansCubit(
|
||||
feedRepository: feedRepository,
|
||||
planRepository: planRepository,
|
||||
);
|
||||
await cubit.loadPlans();
|
||||
expect(cubit.state.plans.length, 1);
|
||||
return cubit;
|
||||
}
|
||||
|
||||
test('an out-of-range like event is ignored instead of throwing', () async {
|
||||
final errors = await errorsFrom(() async {
|
||||
final cubit = await loadedCubit();
|
||||
likeState.add(
|
||||
const LikesState(index: 5, totalLikes: 99, wasLikedByMe: true),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await cubit.close();
|
||||
});
|
||||
|
||||
expect(errors, isEmpty);
|
||||
});
|
||||
|
||||
test('an out-of-range favorite event is ignored instead of throwing', () async {
|
||||
final errors = await errorsFrom(() async {
|
||||
final cubit = await loadedCubit();
|
||||
favoriteState.add(const FavoriteState(index: 5, isFavorite: true));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await cubit.close();
|
||||
});
|
||||
|
||||
expect(errors, isEmpty);
|
||||
});
|
||||
|
||||
test('an out-of-range comments event is ignored instead of throwing', () async {
|
||||
final errors = await errorsFrom(() async {
|
||||
final cubit = await loadedCubit();
|
||||
commentsState.add(const CommentsState(index: 5, totalComments: 99));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await cubit.close();
|
||||
});
|
||||
|
||||
expect(errors, isEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user