diff --git a/.github/workflows/app-ci.yml b/.github/workflows/app-ci.yml new file mode 100644 index 0000000..d5d37d0 --- /dev/null +++ b/.github/workflows/app-ci.yml @@ -0,0 +1,81 @@ +name: App CI + +on: + push: + branches: [main] + paths: + - 'app/**' + - '.github/workflows/app-ci.yml' + pull_request: + paths: + - 'app/**' + - '.github/workflows/app-ci.yml' + +env: + FLUTTER_VERSION: '3.50.0' + +defaults: + run: + working-directory: app + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + - run: flutter pub get + - run: flutter analyze + + test: + name: Tests + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + - run: flutter pub get + - run: flutter test + + build-android: + name: Build Android + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: '17' + - uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + - run: flutter pub get + - run: flutter build apk --debug --flavor dev --dart-define-from-file=env/dev.json + - run: flutter build apk --release --flavor prod --dart-define-from-file=env/prod.json + + build-ios: + name: Build iOS + runs-on: macos-latest + timeout-minutes: 40 + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + - run: flutter pub get + - run: flutter build ios --debug --no-codesign --dart-define-from-file=env/dev.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9cb702e..f828d82 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,6 +26,14 @@ composer check # pint + phpstan (nível 8) + rector --dry-run + pest composer audit ``` +App (`app/`): + +```bash +cd app +flutter analyze +flutter test +``` + Front-admin e front-public (os mesmos comandos nos dois): ```bash @@ -44,6 +52,7 @@ O CI (`.github/workflows/`) roda os mesmos comandos em todo PR — rodar localme ## Convenções - **Backend**: módulo novo é `php artisan make:module ` seguido de `composer update phpeste/` — nunca uma pasta solta colada em `app/`. Ver `backend/CLAUDE.md` para a estrutura de pastas de um módulo (`Models/Actions/Data/Events/Listeners/Contracts/Http`) e a regra de isolamento entre módulos. +- **App**: feature nova pela skill `new-feature` (brick do Mason), no formato de `lib/src/app/features/auth/`. Ver `app/CLAUDE.md`. - **Front-admin e front-public**: módulo novo segue o formato de `app/modules/login/` (types → services → composables → components → views). Ver o `CLAUDE.md` e o `docs/ARCHITECTURE.md` de cada um. As telas do painel seguem o [design do admin](https://claude.ai/artifact/3B7ZWqjBQPDFZ5vhGgNs4N#page-dcb81aee8d83). - Commits em português, description curta e no imperativo (ex.: "Adiciona X", "Corrige Y"). - PRs pequenos e focados batem mais rápido do que um PR gigante — quando der, prefira quebrar em commits/PRs por assunto. diff --git a/README.md b/README.md index 55c813b..49f7512 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Plataforma única para organizar o [PHPeste](https://phpeste.dev), o evento anua A primeira edição a usar a plataforma é o PHPeste 2027, em João Pessoa (PB), organizado pela comunidade PHP-PB. -> **Status (27/11/2026):** Marcos 0, 1 e 2 concluídos. Já funcionam o núcleo (comunidades, edições, equipe, identidade visual, domínios), o CFP completo, a venda de ingressos com Pix e cartão no gateway da própria comunidade, e a gestão da organização (patrocinadores, fornecedores, finanças, tarefas, modelos de e-mail). No site da edição já existem o formulário do CFP, a área do palestrante, o checkout e a conta do participante. Próximo: Marco 3 (programação, check-in, site da edição e checkout embutível). O `app` (Flutter) ainda não foi iniciado. +> **Status (27/11/2026):** Marcos 0, 1 e 2 concluídos. Já funcionam o núcleo (comunidades, edições, equipe, identidade visual, domínios), o CFP completo, a venda de ingressos com Pix e cartão no gateway da própria comunidade, e a gestão da organização (patrocinadores, fornecedores, finanças, tarefas, modelos de e-mail). No site da edição já existem o formulário do CFP, a área do palestrante, o checkout e a conta do participante. Próximo: Marco 3 (programação, check-in, site da edição e checkout embutível) e o app mobile (Marco 5), cuja base já está em `app/`. ## Por que esta plataforma existe @@ -37,12 +37,13 @@ Pronto: - **Site da edição:** formulário do CFP e área do palestrante; checkout com Pix e cartão; conta do participante com os ingressos (o QR abre sem internet), crachá, transferência e histórico de pedidos. - **Gestão da organização:** patrocinadores (funil, cotas e entregas), fornecedores (cadastro global e contratos por edição), finanças (receitas, despesas, orçamento), tarefas (kanban com lembretes), modelos de e-mail por edição e trilha de auditoria. -A fazer (Marcos 3 e 4, ver o [board](https://github.com/orgs/PHPeste/projects/2)): +A fazer (Marcos 3, 4 e 5, ver o [board](https://github.com/orgs/PHPeste/projects/2)): - **Programação:** salas, sessões, grade com validação de conflitos e agenda pessoal. - **Check-in:** leitura de QR no credenciamento, com modo offline. - **Site da edição completo** (template, SEO, termos e LGPD) e **checkout embutível** no site da comunidade. -- **Push, app do participante**, feedback, certificados, sorteio, relatórios e operação (carga, backups, runbook). +- **App mobile** (Marco 5): um app só para participante (início, programação, agenda, ingresso que abre sem internet, transferência, notificações), palestrante (propostas e confirmação) e equipe (check-in com leitura de QR, busca e fila offline). +- **Push**, feedback, certificados, sorteio, relatórios e operação (carga, backups, runbook). ## Princípios @@ -59,7 +60,7 @@ A fazer (Marcos 3 e 4, ver o [board](https://github.com/orgs/PHPeste/projects/2) | Documentação da API | [Scramble](https://github.com/dedoc/scramble) (OpenAPI) | | Admin | Nuxt, a partir do [base_nuxt_modular](https://github.com/tecrodrigocastro/base_nuxt_modular) | | Site público e checkout | Nuxt (SSR) | -| App do participante | Flutter, a partir do [base_clean_arch_bloc](https://github.com/tecrodrigocastro/base_clean_arch_bloc) | +| App mobile | Flutter 3.50, a partir do [base_clean_arch_bloc](https://github.com/tecrodrigocastro/base_clean_arch_bloc) (clean architecture com BLoC) | | Autenticação | Laravel Sanctum (token Bearer) | | Filas e cache | Redis | | Qualidade | Pint, Larastan, Pest e Playwright | @@ -73,7 +74,7 @@ phpeste-platform/ ├── backend/ # Laravel: API, filas, webhooks (módulos em app-modules/) ├── front-admin/ # Nuxt: painel da organização ├── front-public/ # Nuxt SSR: área do palestrante e participante, checkout e site da edição, por host (ou só a área, quando a comunidade tem site próprio) -└── app/ # (planejado, ainda sem marco) Flutter: app do participante +└── app/ # Flutter: app do participante, palestrante e equipe de check-in ``` ## Módulos do backend @@ -144,8 +145,15 @@ composer update phpeste/ curl -H 'X-Forwarded-Host: ' http://localhost:3000/ ``` - Os testes dos três projetos rodam com `npm test` e `npm run test:e2e` (Playwright, com a API simulada) nos fronts e `composer check` no backend; o CI roda os mesmos comandos em todo PR. -- **App** (`app/`): ainda não iniciado. + Os testes dos fronts e do backend rodam com `npm test` e `npm run test:e2e` (Playwright, com a API simulada) nos fronts e `composer check` no backend; o CI roda os mesmos comandos em todo PR. +- **App** (`app/`): base pronta; as telas entram no Marco 5. + + ```bash + cd app + flutter pub get + flutter run --flavor dev --dart-define-from-file=env/dev.json # emulador Android, API local em 10.0.2.2:8000 + flutter analyze && flutter test + ``` ## Documentação @@ -159,6 +167,7 @@ Tudo o que não cabe neste README fica em [`docs/`](docs/): - [`deploy/dominios-e-tls.md`](docs/deploy/dominios-e-tls.md): proxy, domínios das edições e certificados - [`adr/`](docs/adr/): o porquê de cada decisão de arquitetura (0001–0009) - [Design do admin](https://claude.ai/artifact/3B7ZWqjBQPDFZ5vhGgNs4N#page-dcb81aee8d83): protótipo das telas do `front-admin` +- [Design do app](https://claude.ai/artifact/3yAeWXmnxFSdActqPdqt7K#page-dcb81aee8d83): telas e fluxos do `app/` (participante, palestrante e equipe) - Guia para a comunidade anfitriã: criar a edição, conectar o gateway, tematizar e abrir o CFP (a escrever) diff --git a/app/.claude/rules/architecture.md b/app/.claude/rules/architecture.md new file mode 100644 index 0000000..8a40e0c --- /dev/null +++ b/app/.claude/rules/architecture.md @@ -0,0 +1,52 @@ +# Architecture + +Clean Architecture, four layers per feature, plus a shared `core/`. + +## Dependency Rule + +``` +presentation --> domain <-- data <-- infrastructure +``` + +- `domain/` depends on nothing else in the app (no Flutter, no `dio`, no other layer). It is pure Dart. +- `data/` depends only on `domain/` (implements its repository interfaces, extends its entities into models). +- `presentation/` depends only on `domain/` (calls usecases, never talks to a datasource or repository implementation directly). +- `infrastructure/` may depend on `domain/` and `data/` (interceptors, feature-scoped services). + +If a file in `domain/` needs to import something from `data/`, `presentation/`, `material_ui/material_ui.dart`, or a package like `dio`, that's a violation - move the logic to the layer that's allowed to depend on it, or invert the dependency behind an interface in `domain/`. + +## Layer responsibilities + +**Domain** (`domain/`) +- `entities/`: immutable business objects (`final` fields, `const` constructor, extend `Equatable`). +- `dtos/`: mutable input parameters for usecases (e.g. `LoginParams` - plain fields + `set{Field}()` methods, not `copyWith`), with a static `empty()` factory and `toJson()`. +- `repositories/`: abstract interfaces only (`abstract interface class I{Feature}Repository`), methods return `AsyncResult`. +- `usecases/`: one class per action, implements `UseCase` (`lib/src/core/interfaces/usecase_interface.dart`), holds business rules that don't belong in the BLoC or the repository. +- `validators/`: `LucidValidator` subclasses, one rule per field. + +**Data** (`data/`) +- `models/`: extend the matching entity, add `fromMap`/`toMap`/`fromJson`/`toJson`. This is the only place JSON parsing happens. +- `datasources/`: talk to `IRestClient` (or local storage) and return raw responses. No business logic, no error mapping. +- `repositories/`: implement the domain interface, catch `RestClientException`/other exceptions, map them to `BaseException` subclasses, return `Success`/`Failure`. + +**Presentation** (`presentation/`) +- `bloc/`: one bloc per feature; events and states are `part of` the bloc file, both extend `Equatable`. +- `pages/`: `BlocListener` for side effects (snackbars, navigation), `BlocBuilder` for rebuilding UI - keep them separate, don't mix into one `BlocConsumer` unless the widget genuinely needs both in the same spot. +- `widgets/`: reusable UI pulled out of pages once it's used more than once. + +**Infrastructure** (`infrastructure/`) +- Interceptors and services that are specific to one feature (e.g. `auth_interceptor.dart` attaching the session token). Cross-feature infrastructure belongs in `core/`. + +## Core (`lib/src/core/`) + +Shared, feature-agnostic code: `DI/` (get_it setup), `cache/`, `client_http/` (Dio wrapper + interceptors), `errors/` (`BaseException` hierarchy), `extensions/`, `interfaces/` (`UseCase`), `services/` (e.g. `SessionService`), `utils/`. + +Never import a feature from `core/`. If `core/` needs feature-specific behavior, that's a sign the code belongs in the feature's `infrastructure/` instead. + +## Data flow + +``` +UI -> BLoC -> UseCase -> Repository (interface) -> Repository (impl) -> DataSource -> API / local storage +``` + +Errors flow back up the same chain as `Failure(BaseException)`, never as a thrown exception crossing a layer boundary. diff --git a/app/.claude/rules/naming-conventions.md b/app/.claude/rules/naming-conventions.md new file mode 100644 index 0000000..c4c703e --- /dev/null +++ b/app/.claude/rules/naming-conventions.md @@ -0,0 +1,38 @@ +# Naming Conventions + +Match these exactly - they're taken from the `auth` feature, which is the reference implementation for everything else in this template. + +| Kind | File name | Class name | Example | +|---|---|---|---| +| Entity | `{entity}_entity.dart` | `{Entity}Entity` | `user_entity.dart` -> `UserEntity` | +| DTO / params | `{action}_params.dart` | `{Action}Params` | `login_params.dart` -> `LoginParams` | +| Repository interface | `{feature}_repository_interface.dart` | `I{Feature}Repository` | `auth_repository_interface.dart` -> `IAuthRepository` | +| Repository impl | `{feature}_repository_impl.dart` | `{Feature}RepositoryImpl` | `auth_repository_impl.dart` -> `AuthRepositoryImpl` | +| Usecase | `{action}_usecase.dart` | `{Action}Usecase` | `login_usecase.dart` -> `LoginUsecase` | +| Validator | `{params}_validators.dart` | `{Params}Validators` | `login_params_validators.dart` -> `LoginParamsValidators` | +| Model | `{entity}_model.dart` | `{Entity}Model` (extends `{Entity}Entity`) | `user_model.dart` -> `UserModel` | +| Remote datasource | `{feature}_remote_datasource.dart` | `{Feature}RemoteDatasource` | `auth_remote_datasource.dart` -> `AuthRemoteDatasource` | +| Local datasource | `{feature}_local_datasource.dart` | `{Feature}LocalDatasource` | | +| Bloc | `{feature}_bloc.dart` | `{Feature}Bloc` | `auth_bloc.dart` -> `AuthBloc` | +| Bloc events | `{feature}_event.dart` (`part of`) | `{Feature}{Action}Requested` | `AuthLoginRequested` | +| Bloc states | `{feature}_state.dart` (`part of`) | `{Feature}{Status}` | `AuthLoading`, `AuthLoginSuccess`, `AuthFailure` | +| Page | `{page}_page.dart` | `{Page}Page` | `login_page.dart` -> `LoginPage` | +| Widget | `{component}_widget.dart` | `{Component}Widget` | | + +## Class modifiers + +- Everything is a plain `class` (entities, DTOs, models, repository impls, usecases, blocs, events, states) - this codebase does not use `final class`, even for types nothing currently extends. +- Repository interfaces are the one exception: `abstract interface class I{Feature}Repository`. +- Events/states base classes are `abstract class` (`AuthEvent`, `AuthState`); concrete subclasses are plain `class`. +- Prefer `const` constructors wherever the fields allow it, but don't force it where the existing feature doesn't (e.g. `LoginUsecase`'s constructor isn't `const`). + +## Tests + +Mirror the `lib/` path under `test/unit/` or `test/widget/`: + +``` +lib/src/app/features/auth/domain/usecases/login_usecase.dart +test/unit/auth/domain/usecases/login_usecase_test.dart +``` + +Mock classes: `Mock{ClassName}` using `mocktail` (`class MockAuthRepository extends Mock implements IAuthRepository {}`). BLoC tests use `bloc_test`'s `blocTest`. diff --git a/app/.claude/rules/solid-principles.md b/app/.claude/rules/solid-principles.md new file mode 100644 index 0000000..1133612 --- /dev/null +++ b/app/.claude/rules/solid-principles.md @@ -0,0 +1,18 @@ +# SOLID in This Codebase + +Concrete, not theoretical - how each principle actually shows up here. + +**Single Responsibility** +A datasource only makes HTTP calls; it doesn't parse business rules. A validator only validates. A usecase only orchestrates one action. If a class's steps have more than one reason to change independently, split it. + +**Open/Closed** +New behavior is added by creating a new usecase/repository/bloc, not by piling `if`/`switch` branches for a new scenario into an existing one (see `AuthRepositoryImpl.login`'s status-code mapping for the shape to extend, not the shape to keep growing indefinitely). + +**Liskov Substitution** +`{Entity}Model` extends `{Entity}Entity` and must be usable everywhere the entity is expected - no overridden field changes behavior in a way that breaks callers holding an `{Entity}Entity` reference. Any `I{Feature}Repository` implementation must satisfy the same contract (return `Success`/`Failure`, never throw) as every other implementation of that interface. + +**Interface Segregation** +Repository interfaces are scoped per feature (`IAuthRepository`, not one giant `IRepository`). Don't add a method to an interface for a caller that could instead depend on a narrower interface. + +**Dependency Inversion** +`presentation/` and `data/` depend on the abstract `I{Feature}Repository`, never on `{Feature}RepositoryImpl` directly. Wiring the concrete implementation to the interface happens in one place: `lib/src/core/DI/dependency_injector.dart` (get_it). This is also why `domain/` can have zero external dependencies - everything it needs from outer layers is expressed as an interface it defines and an outer layer implements. diff --git a/app/.claude/skills/new-feature/SKILL.md b/app/.claude/skills/new-feature/SKILL.md new file mode 100644 index 0000000..b8c0947 --- /dev/null +++ b/app/.claude/skills/new-feature/SKILL.md @@ -0,0 +1,345 @@ +--- +name: new-feature +description: Scaffold a complete feature (domain, data, presentation, DI wiring, tests) following this project's Clean Architecture + BLoC conventions. Use whenever the user asks to add a new feature/module/screen backed by an API, not just a standalone widget. +--- + +# New Feature Scaffold + +Generates every layer of a feature the same way `auth` is built - use `auth` (`lib/src/app/features/auth/`) as the live reference whenever a template below is ambiguous. Naming and modifier rules are in `.claude/rules/naming-conventions.md`; layer boundaries are in `.claude/rules/architecture.md`. Read both before generating files if this is the first feature you're scaffolding in a session. + +## Step 0: run the Mason brick first + +Don't hand-write the boilerplate below from scratch - `bricks/feature/` is a Mason brick that generates it in one shot (entity, DTO, repository interface/impl, usecase, validator, model, datasource, bloc+event+state, matching tests, and optionally a page). Run: + +```bash +mason get # once per clone, registers bricks/feature/ from mason.yaml +mason make feature \ + --feature_name product \ + --action_name create \ + --fields "id:String,name:String,price:double" \ + --generate_page \ + -o . +``` + +Notes: +- `entity_name` defaults to `feature_name` - only pass `--entity_name` when the entity is named differently (e.g. feature `auth`, entity `user`/`auth_response`). +- `fields` is `name:type,name:type`; supported types get sensible empty/sample values in the generated tests (`String`, `int`, `double`, `num`, `bool` - anything else falls back to `null`, which only works for nullable fields). +- Booleans need an explicit value on the CLI: pass `--generate_page` to include a page, or `--generate_page false` to skip it (omitting the flag entirely triggers an interactive prompt, which fails in non-interactive shells). +- The brick's validator only adds `.notEmpty()` rules for `String` fields - add custom rules for numeric/bool fields by hand afterward. +- The generated repository interface/usecase/bloc cover exactly one action. For a second action on the same feature (e.g. `getAll` alongside `create`), re-run `mason make feature` with the new `--action_name` and answer "skip" when prompted about conflicts on `{feature}_entity.dart`/`{feature}_repository_interface.dart`/`{feature}_bloc.dart` - then manually add the new method to the repository interface/impl and the new event/state to the bloc, following the shape the brick already generated for the first action. +- `flutter analyze` and `flutter test` are guaranteed clean for the field types above - this was verified end-to-end before the brick was committed. + +Everything from here down documents what the brick generates (and how to extend it by hand) - read it when the brick's output needs adjusting, when scaffolding a second action, or when the feature doesn't fit the brick's shape (e.g. no HTTP datasource). + +## Before writing anything + +Ask (or infer from context) if unclear: +1. Feature name (e.g. `product`, `order`) - drives folder name and class prefixes. +2. Which actions it needs (`create`, `getAll`, `getById`, `update`, `delete`, or a custom one like `login`) - don't scaffold CRUD methods nobody asked for. +3. The entity's fields. +4. Whether it needs a dedicated page/widget now, or just the domain+data+bloc layer. + +Only build what's asked - a feature that only lists items doesn't need `create`/`update`/`delete` stubs. + +## Steps + +### 1. Create the folder structure + +```bash +mkdir -p lib/src/app/features/{feature}/domain/{entities,dtos,repositories,usecases,validators} +mkdir -p lib/src/app/features/{feature}/data/{models,datasources,repositories} +mkdir -p lib/src/app/features/{feature}/infrastructure +mkdir -p lib/src/app/features/{feature}/presentation/{bloc,pages,widgets} +mkdir -p test/unit/{feature}/{domain/{entities,usecases,validators},data/{models,datasources,repositories},presentation/bloc} +mkdir -p test/widget/{feature} +``` + +Skip `infrastructure/` and its contents if the feature doesn't need a custom interceptor/service. + +### 2. Domain layer + +**Entity** (`domain/entities/{name}_entity.dart`) - immutable, extends `Equatable`: + +```dart +import 'package:equatable/equatable.dart'; + +class {Entity}Entity extends Equatable { + final String id; + final String name; // replace with real fields + + const {Entity}Entity({ + required this.id, + required this.name, + }); + + @override + String toString() => '{Entity}Entity(id: $id, name: $name)'; + + @override + List get props => [id, name]; +} +``` + +**DTO / params** (`domain/dtos/{action}_params.dart`) - mutable, setters, `empty()`, manual equality (matches `LoginParams`, not a `copyWith` style): + +```dart +class {Action}Params { + String field1; + String field2; + + {Action}Params({ + required this.field1, + required this.field2, + }); + + Map toJson() => { + 'field1': field1, + 'field2': field2, + }; + + void setField1(String value) => field1 = value; + void setField2(String value) => field2 = value; + + static {Action}Params empty() => {Action}Params(field1: '', field2: ''); + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is {Action}Params && other.field1 == field1 && other.field2 == field2; + } + + @override + int get hashCode => field1.hashCode ^ field2.hashCode; + + @override + String toString() => '{Action}Params(field1: $field1, field2: $field2)'; +} +``` + +**Repository interface** (`domain/repositories/{feature}_repository_interface.dart`): + +```dart +import 'package:result_dart/result_dart.dart'; +import '../entities/{name}_entity.dart'; +import '../dtos/{action}_params.dart'; + +abstract interface class I{Feature}Repository { + AsyncResult<{Entity}Entity> {action}({Action}Params params); +} +``` + +**Usecase** (`domain/usecases/{action}_usecase.dart`) - implements `UseCase` from `lib/src/core/interfaces/usecase_interface.dart`; only add extra logic (like `LoginUsecase` saving the session) if the feature actually needs it: + +```dart +import 'package:result_dart/result_dart.dart'; +import '../../../../core/interfaces/usecase_interface.dart'; +import '../entities/{name}_entity.dart'; +import '../dtos/{action}_params.dart'; +import '../repositories/{feature}_repository_interface.dart'; + +class {Action}Usecase implements UseCase<{Entity}Entity, {Action}Params> { + final I{Feature}Repository _{feature}Repository; + + {Action}Usecase({required I{Feature}Repository {feature}Repository}) + : _{feature}Repository = {feature}Repository; + + @override + AsyncResult<{Entity}Entity> call({Action}Params params) { + return _{feature}Repository.{action}(params); + } +} +``` + +**Validator** (`domain/validators/{action}_params_validators.dart`) - extends `LucidValidator`; reuse extensions from `lib/src/core/extensions/lucid_validator_extensions.dart` (e.g. `customValidPassword()`) instead of duplicating rules: + +```dart +import 'package:lucid_validation/lucid_validation.dart'; +import '../dtos/{action}_params.dart'; + +class {Action}ParamsValidators extends LucidValidator<{Action}Params> { + {Action}ParamsValidators() { + ruleFor((p) => p.field1, key: 'field1').notEmpty(message: 'Campo obrigatório'); + } +} +``` + +### 3. Data layer + +**Model** (`data/models/{name}_model.dart`) - extends the entity, adds (de)serialization: + +```dart +import 'dart:convert'; +import '../../domain/entities/{name}_entity.dart'; + +class {Entity}Model extends {Entity}Entity { + {Entity}Model({required super.id, required super.name}); + + Map toMap() => {'id': id, 'name': name}; + + factory {Entity}Model.fromMap(Map map) { + return {Entity}Model(id: map['id'] as String, name: map['name'] as String); + } + + String toJson() => json.encode(toMap()); + + factory {Entity}Model.fromJson(String source) => + {Entity}Model.fromMap(json.decode(source) as Map); +} +``` + +**Remote datasource** (`data/datasources/{feature}_remote_datasource.dart`) - only talks HTTP, returns the raw response, no error mapping: + +```dart +import '../../../../core/client_http/client_http.dart'; +import '../../domain/dtos/{action}_params.dart'; + +class {Feature}RemoteDatasource { + final IRestClient _restClient; + + {Feature}RemoteDatasource({required IRestClient restClient}) : _restClient = restClient; + + Future {action}({Action}Params params) { + return _restClient.post(RestClientRequest(path: '/{feature}', data: params.toJson())); + } +} +``` + +**Repository implementation** (`data/repositories/{feature}_repository_impl.dart`) - the only place that catches exceptions and maps them to `BaseException` subclasses (`lib/src/core/errors/`); follow `AuthRepositoryImpl`'s shape exactly, don't invent a different error-handling style: + +```dart +import 'package:result_dart/result_dart.dart'; +import '../../domain/dtos/{action}_params.dart'; +import '../../domain/entities/{name}_entity.dart'; +import '../../domain/repositories/{feature}_repository_interface.dart'; +import '../datasources/{feature}_remote_datasource.dart'; +import '../models/{name}_model.dart'; +import '../../../../core/client_http/client_http.dart'; +import '../../../../core/errors/errors.dart'; + +class {Feature}RepositoryImpl implements I{Feature}Repository { + final {Feature}RemoteDatasource _{feature}RemoteDatasource; + + {Feature}RepositoryImpl({required {Feature}RemoteDatasource {feature}RemoteDatasource}) + : _{feature}RemoteDatasource = {feature}RemoteDatasource; + + @override + AsyncResult<{Entity}Entity> {action}({Action}Params params) async { + try { + final response = await _{feature}RemoteDatasource.{action}(params); + return Success({Entity}Model.fromMap(response.data as Map)); + } on RestClientException catch (e) { + return Failure(DefaultException(message: e.message)); + } catch (e) { + return Failure(DefaultException(message: 'Erro inesperado: ${e.toString()}')); + } + } +} +``` + +Add a specific `BaseException` subclass under `lib/src/core/errors/` (and export it from `errors.dart`) only if the feature needs to distinguish an error case the UI reacts to differently - don't create one speculatively. + +### 4. Presentation layer + +**Bloc** (`presentation/bloc/{feature}_bloc.dart` + `_event.dart` + `_state.dart` as `part of`) - chain `validate -> flatMap -> fold`, mirroring `AuthBloc`: + +`{feature}_event.dart`: +```dart +part of '{feature}_bloc.dart'; + +abstract class {Feature}Event extends Equatable { + const {Feature}Event(); + @override + List get props => []; +} + +class {Feature}{Action}Requested extends {Feature}Event { + final {Action}Params params; + const {Feature}{Action}Requested({required this.params}); + @override + List get props => [params]; +} +``` + +`{feature}_state.dart`: +```dart +part of '{feature}_bloc.dart'; + +abstract class {Feature}State extends Equatable { + const {Feature}State(); + @override + List get props => []; +} + +class {Feature}Initial extends {Feature}State {} +class {Feature}Loading extends {Feature}State {} + +class {Feature}{Action}Success extends {Feature}State { + final {Entity}Entity entity; + const {Feature}{Action}Success(this.entity); + @override + List get props => [entity]; +} + +class {Feature}{Action}Failure extends {Feature}State { + final BaseException exception; + const {Feature}{Action}Failure({required this.exception}); + @override + List get props => [exception]; +} +``` + +`{feature}_bloc.dart`: +```dart +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:result_dart/result_dart.dart'; +import '../../domain/dtos/{action}_params.dart'; +import '../../domain/entities/{name}_entity.dart'; +import '../../domain/usecases/{action}_usecase.dart'; +import '../../domain/validators/{action}_params_validators.dart'; +import '../../../../core/errors/errors.dart'; + +part '{feature}_event.dart'; +part '{feature}_state.dart'; + +class {Feature}Bloc extends Bloc<{Feature}Event, {Feature}State> { + final {Action}Usecase _{action}Usecase; + + {Feature}Bloc({required {Action}Usecase {action}Usecase}) + : _{action}Usecase = {action}Usecase, + super({Feature}Initial()) { + on<{Feature}{Action}Requested>((event, emit) async { + emit({Feature}Loading()); + + final validator = {Action}ParamsValidators(); + + final newState = await validator + .validateResult(event.params) + .flatMap(_{action}Usecase.call) + .fold({Feature}{Action}Success.new, (e) => {Feature}{Action}Failure(exception: e as BaseException)); + + emit(newState); + }); + } +} +``` + +**Page** (`presentation/pages/{name}_page.dart`) - `BlocListener` for side effects (snackbars/navigation via `router.go`), `BlocBuilder` for rebuilding; get the bloc from `injector<{Feature}Bloc>()`, mutate the mutable DTO directly in `onChanged` (see `LoginPage`) rather than calling `setState` for every keystroke. + +### 5. Dependency injection + +Add a `setup{Feature}Dependencies()` function to `lib/src/core/DI/dependency_injector.dart` and call it from `setupDependencyInjector()`, following the existing `registerFactory`/`registerLazySingleton` pattern for the datasource, repository, and bloc - see the `auth` block already in that file for the exact shape (including the `useMocks` branch if the feature should support a mock repository for now). + +### 6. Tests + +Mirror `test/unit/auth/` and `test/widget/auth/` for structure. At minimum: +- `test/unit/{feature}/domain/usecases/{action}_usecase_test.dart` - mock the repository interface with `mocktail` (`class Mock{Feature}Repository extends Mock implements I{Feature}Repository {}`), assert `Success`/`Failure` paths. +- `test/unit/{feature}/presentation/bloc/{feature}_bloc_test.dart` - use `bloc_test`'s `blocTest`, assert the `[Loading, Success]` / `[Loading, Failure]` state sequences. +- `test/unit/{feature}/data/repositories/{feature}_repository_impl_test.dart` - mock the datasource, assert HTTP errors map to the right `BaseException`. + +### 7. Verify + +```bash +flutter analyze +flutter test test/unit/{feature}/ test/widget/{feature}/ +``` diff --git a/app/.fvmrc b/app/.fvmrc new file mode 100644 index 0000000..14bb2a9 --- /dev/null +++ b/app/.fvmrc @@ -0,0 +1,3 @@ +{ + "flutter": "3.50.0" +} diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..40edd18 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,67 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# FVM Version Cache +.fvm/ + +# Mason local brick cache +.mason/ +bricks/**/hooks/build/ + +# Environment variables +.env + +# Android signing (never commit keystores or credentials) +android/key.properties +android/app/upload-keystore.jks +*.jks +*.keystore + +# iOS / App Store Connect signing +ios/ExportOptions.plist.local +*.p8 +*.p12 +*.mobileprovision \ No newline at end of file diff --git a/app/.metadata b/app/.metadata new file mode 100644 index 0000000..391c336 --- /dev/null +++ b/app/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "5874a72aa4c779a02553007c47dacbefba2374dc" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + - platform: android + create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + - platform: ios + create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + - platform: linux + create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + - platform: macos + create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + - platform: web + create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + - platform: windows + create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/app/CLAUDE.md b/app/CLAUDE.md new file mode 100644 index 0000000..dd9a312 --- /dev/null +++ b/app/CLAUDE.md @@ -0,0 +1,79 @@ +# app + +App Flutter do PHPeste para quem vive a edição: participante, palestrante e equipe de check-in. Um app só, com a identidade de cada edição vinda da API de Branding. Parte do template [`base_clean_arch_bloc`](https://github.com/tecrodrigocastro/base_clean_arch_bloc) (clean architecture com BLoC), como o painel e o site partem do `base_nuxt_modular`. Fala HTTP com `../backend` (`/api/v1`, token Bearer), nunca toca banco. + +Design: [claude.ai/artifact/3yAeWXmnxFSdActqPdqt7K](https://claude.ai/artifact/3yAeWXmnxFSdActqPdqt7K#page-dcb81aee8d83). Ler a prancheta da tela (`project/.dc.html`) antes de cada issue com UI. Telas em 390 × 844. Issues no milestone "Marco 5 · App mobile" (M01–M23). + +As regras de camadas, nomes e SOLID do template estão em `.claude/rules/` e valem aqui. A skill `new-feature` (`.claude/skills/new-feature/`) gera uma feature inteira pelo brick do Mason (`mason get`, depois `mason make feature`); prefira ela a escrever uma feature à mão. + +## Stack + +- Estado: `flutter_bloc` + `equatable` +- Injeção: `get_it` (`lib/src/core/DI/dependency_injector.dart`) +- Rotas: `go_router` (`lib/routes.dart`) +- HTTP: `dio`, atrás de `lib/src/core/client_http/` (feature nunca importa `dio`) +- Erros: `result_dart` (`Success`/`Failure`, nada de exceção atravessando camada) +- Validação: `lucid_validation` +- Armazenamento local: `shared_preferences`, atrás de `lib/src/core/cache/` +- Widgets: `material_ui` (o pacote oficial que substitui `package:flutter/material.dart`, obsoleto desde o Flutter 3.47). Nunca importe `flutter/material.dart` + +## Estrutura + +``` +lib/ +├── main.dart # binding (Marionette em debug), DI, sessão restaurada antes do runApp +├── app_widget.dart +├── routes.dart # AppRoutes, sessionRedirect, router +└── src/ + ├── app/features/{feature}/ + │ ├── domain/ # entidades, dtos, interfaces de repositório, usecases, validators; Dart puro + │ ├── data/ # models (estendem entidades), datasources, repositórios + │ ├── infrastructure/ # interceptors e serviços da feature + │ └── presentation/ + │ ├── bloc/ + │ ├── pages/ + │ ├── widgets/ + │ └── texts/ # {feature}_texts.dart: textos da tela em pt-BR + └── core/ # config, DI, cache, client_http, errors, extensions, services, utils +``` + +`auth` é a feature de referência (todas as camadas e testes). `home` e `base` (barra inferior) são só apresentação. + +## Ambientes + +| Flavor | Configuração | Android | iOS | +| --- | --- | --- | --- | +| `dev` | `env/dev.json` (API em `10.0.2.2:8000`, o `localhost` do emulador Android; logs da API) | `dev.phpeste.app.dev`, "PHPeste Dev" | `dev.phpeste.app` | +| `prod` | `env/prod.json` (`https://api.phpeste.dev/api/v1`) | `dev.phpeste.app`, "PHPeste" | `dev.phpeste.app` | + +`AppConfig` (`lib/src/core/config/app_config.dart`) lê `FLAVOR`, `API_URL`, `USE_MOCKS` e `LOG_API` do `--dart-define-from-file`. Sem o arquivo, a API é `http://localhost:8000/api/v1`. `USE_MOCKS=true` usa o login simulado do template (`teste@teste.com`, `123456Aa!`). No iOS o identificador ainda é um só: os esquemas por flavor dependem do Xcode e entram na publicação (M22). + +## Rotas e sessão + +`SessionService.signedIn` (`ValueNotifier`) é restaurado do armazenamento antes do `runApp` e o `GoRouter` observa ele (`refreshListenable`). `sessionRedirect` manda rota privada sem sessão para `/entrar?de=` e, com sessão, devolve para o destino (só caminho interno) ou para `/inicio`. Por isso tela nenhuma navega depois de entrar ou sair: basta salvar ou remover o token. Rota nova entra em `AppRoutes`; rota aberta sem sessão entra em `AppRoutes.public`. Os links que abrem o app (B56, M21) chegam por esse mesmo roteador. + +## Comandos + +```bash +flutter pub get +flutter analyze +flutter test +flutter test test/unit/core/routes_test.dart # um arquivo +flutter run --flavor dev --dart-define-from-file=env/dev.json +flutter build apk --flavor prod --dart-define-from-file=env/prod.json +flutter build ios --no-codesign --dart-define-from-file=env/prod.json +``` + +Flutter fixado em 3.50.0 (`.fvmrc` e CI). O Android segue o que o `flutter create` dessa versão gera (Kotlin DSL, AGP 9.3.1, Kotlin 2.4.20, Gradle 9.5, Java 17); o Flutter 3.50 recusa Gradle abaixo de 9.3.1, então trocar a versão do Flutter pede gerar um projeto novo e comparar `android/`. O CI (`../.github/workflows/app-ci.yml`) roda análise, testes e os builds de Android (dev e prod) e iOS sem assinatura em todo PR que mexe em `app/`. + +Depois do `flutter run` em debug, o Marionette MCP (`MarionetteBinding` em `lib/main.dart`) deixa um agente conectado ao `ws://` impresso tocar, digitar, tirar print e ler logs, para conferir uma mudança de tela no app rodando. + +## Regras + +- Dependência: `presentation -> domain <- data <- infrastructure`. `domain/` não importa Flutter, `dio` nem outra camada. +- Repositório e usecase devolvem `AsyncResult`; só `data/` captura exceção e converte em `BaseException` (`lib/src/core/errors/`). +- Entidades imutáveis (`final`, `const`, `Equatable`); DTOs são classes mutáveis com `set{Campo}()` e `empty()`, como `LoginParams`. +- Texto que a pessoa lê fica em `presentation/texts/{feature}_texts.dart`, nunca solto na página. +- Alvo de toque de 44 px ou mais e estado nunca só por cor (design, prancheta 01). +- Dependência nova é proposta no PR e aprovada antes de entrar. +- Tela nova ou mudança de como o app fala com a API atualiza `../docs/arquitetura/` no mesmo PR. diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000..c7fbaba --- /dev/null +++ b/app/README.md @@ -0,0 +1,16 @@ +# app + +App mobile da [PHPeste Platform](../README.md) para participante, palestrante e equipe de check-in. Flutter, clean architecture com BLoC, a partir do template [`base_clean_arch_bloc`](https://github.com/tecrodrigocastro/base_clean_arch_bloc). Ver [`CLAUDE.md`](CLAUDE.md). + +> **Status:** base pronta (M01): template adaptado, ambientes `dev` e `prod`, rotas com guarda de sessão e CI. As telas do design entram nas issues M02–M23 do milestone "Marco 5 · App mobile". + +```bash +flutter pub get +flutter run --flavor dev --dart-define-from-file=env/dev.json # API local em 10.0.2.2:8000 (emulador Android) +flutter analyze +flutter test +``` + +No simulador iOS, a API local é `localhost`, que já é o padrão sem arquivo de ambiente: `flutter run` basta. + +Design das telas: [claude.ai/artifact/3yAeWXmnxFSdActqPdqt7K](https://claude.ai/artifact/3yAeWXmnxFSdActqPdqt7K#page-dcb81aee8d83). diff --git a/app/analysis_options.yaml b/app/analysis_options.yaml new file mode 100644 index 0000000..aadfa6d --- /dev/null +++ b/app/analysis_options.yaml @@ -0,0 +1,40 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + # Mustache templates, not valid Dart until Mason renders them. + - bricks/** + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/app/android/.gitignore b/app/android/.gitignore new file mode 100644 index 0000000..55afd91 --- /dev/null +++ b/app/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts new file mode 100644 index 0000000..bb74508 --- /dev/null +++ b/app/android/app/build.gradle.kts @@ -0,0 +1,76 @@ +import java.util.Properties + +plugins { + id("com.android.application") + id("dev.flutter.flutter-gradle-plugin") +} + +val keystoreProperties = Properties() +val keystorePropertiesFile = rootProject.file("key.properties") +if (keystorePropertiesFile.exists()) { + keystorePropertiesFile.inputStream().use { keystoreProperties.load(it) } +} + +android { + namespace = "dev.phpeste.app" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + applicationId = "dev.phpeste.app" + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildFeatures { + resValues = true + } + + flavorDimensions += "ambiente" + + productFlavors { + create("dev") { + dimension = "ambiente" + applicationIdSuffix = ".dev" + resValue("string", "app_name", "PHPeste Dev") + } + create("prod") { + dimension = "ambiente" + resValue("string", "app_name", "PHPeste") + } + } + + signingConfigs { + create("release") { + if (keystorePropertiesFile.exists()) { + storeFile = file(keystoreProperties["storeFile"] as String) + storePassword = keystoreProperties["storePassword"] as String + keyAlias = keystoreProperties["keyAlias"] as String + keyPassword = keystoreProperties["keyPassword"] as String + } + } + } + + buildTypes { + release { + signingConfig = if (keystorePropertiesFile.exists()) signingConfigs.getByName("release") else signingConfigs.getByName("debug") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/app/android/app/src/debug/AndroidManifest.xml b/app/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/app/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4bff20e --- /dev/null +++ b/app/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/app/android/app/src/main/kotlin/dev/phpeste/app/MainActivity.kt b/app/android/app/src/main/kotlin/dev/phpeste/app/MainActivity.kt new file mode 100644 index 0000000..d76e8ac --- /dev/null +++ b/app/android/app/src/main/kotlin/dev/phpeste/app/MainActivity.kt @@ -0,0 +1,5 @@ +package dev.phpeste.app + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() diff --git a/app/android/app/src/main/res/drawable-v21/launch_background.xml b/app/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/app/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/drawable/launch_background.xml b/app/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/app/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/values-night/styles.xml b/app/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/app/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/main/res/values/styles.xml b/app/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/app/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/profile/AndroidManifest.xml b/app/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/app/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/android/build.gradle.kts b/app/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/app/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/app/android/gradle.properties b/app/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/app/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/app/android/gradle/wrapper/gradle-wrapper.properties b/app/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..76d4386 --- /dev/null +++ b/app/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip diff --git a/app/android/settings.gradle.kts b/app/android/settings.gradle.kts new file mode 100644 index 0000000..989ac5e --- /dev/null +++ b/app/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.3.1" apply false + id("org.jetbrains.kotlin.android") version "2.4.20" apply false +} + +include(":app") diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource.dart new file mode 100644 index 0000000..743302d --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource.dart @@ -0,0 +1,17 @@ +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/core/client_http/client_http.dart'; + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource { + final IRestClient _restClient; + + {{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource({required IRestClient restClient}) : _restClient = restClient; + + Future {{#camelCase}}{{action_name}}{{/camelCase}}({{#pascalCase}}{{action_name}}{{/pascalCase}}Params params) { + return _restClient.post( + RestClientRequest( + path: '/{{#snakeCase}}{{feature_name}}{{/snakeCase}}', + data: params.toJson(), + ), + ); + } +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/models/{{entity_name}}_model.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/models/{{entity_name}}_model.dart new file mode 100644 index 0000000..f19362b --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/models/{{entity_name}}_model.dart @@ -0,0 +1,36 @@ +import 'dart:convert'; + +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart'; + +class {{#pascalCase}}{{entity_name}}{{/pascalCase}}Model extends {{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity { + const {{#pascalCase}}{{entity_name}}{{/pascalCase}}Model({ +{{#fields}} + required super.{{name}}, +{{/fields}} + }); + + Map toMap() { + return { +{{#fields}} + '{{name}}': {{name}}, +{{/fields}} + }; + } + + factory {{#pascalCase}}{{entity_name}}{{/pascalCase}}Model.fromMap(Map map) { + try { + return {{#pascalCase}}{{entity_name}}{{/pascalCase}}Model( +{{#fields}} + {{name}}: map['{{name}}'] as {{{type}}}, +{{/fields}} + ); + } catch (e, stackTrace) { + throw Exception('Error parsing {{#pascalCase}}{{entity_name}}{{/pascalCase}}Model: $e\nStack trace: $stackTrace'); + } + } + + String toJson() => json.encode(toMap()); + + factory {{#pascalCase}}{{entity_name}}{{/pascalCase}}Model.fromJson(String source) => + {{#pascalCase}}{{entity_name}}{{/pascalCase}}Model.fromMap(json.decode(source) as Map); +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/repositories/{{feature_name}}_repository_impl.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/repositories/{{feature_name}}_repository_impl.dart new file mode 100644 index 0000000..a5d87ad --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/data/repositories/{{feature_name}}_repository_impl.dart @@ -0,0 +1,27 @@ +import 'package:result_dart/result_dart.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/data/models/{{entity_name}}_model.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/repositories/{{feature_name}}_repository_interface.dart'; +import 'package:{{package_name}}/src/core/client_http/client_http.dart'; +import 'package:{{package_name}}/src/core/errors/errors.dart'; + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}RepositoryImpl implements I{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository { + final {{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource _{{#camelCase}}{{feature_name}}{{/camelCase}}RemoteDatasource; + + {{#pascalCase}}{{feature_name}}{{/pascalCase}}RepositoryImpl({required {{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource {{#camelCase}}{{feature_name}}{{/camelCase}}RemoteDatasource}) + : _{{#camelCase}}{{feature_name}}{{/camelCase}}RemoteDatasource = {{#camelCase}}{{feature_name}}{{/camelCase}}RemoteDatasource; + + @override + AsyncResult<{{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity> {{#camelCase}}{{action_name}}{{/camelCase}}({{#pascalCase}}{{action_name}}{{/pascalCase}}Params params) async { + try { + final response = await _{{#camelCase}}{{feature_name}}{{/camelCase}}RemoteDatasource.{{#camelCase}}{{action_name}}{{/camelCase}}(params); + return Success({{#pascalCase}}{{entity_name}}{{/pascalCase}}Model.fromMap(response.data as Map)); + } on RestClientException catch (e) { + return Failure(DefaultException(message: e.message)); + } catch (e) { + return Failure(DefaultException(message: 'Erro inesperado: ${e.toString()}')); + } + } +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart new file mode 100644 index 0000000..f4fa842 --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart @@ -0,0 +1,50 @@ +class {{#pascalCase}}{{action_name}}{{/pascalCase}}Params { +{{#fields}} + {{{type}}} {{name}}; +{{/fields}} + + {{#pascalCase}}{{action_name}}{{/pascalCase}}Params({ +{{#fields}} + required this.{{name}}, +{{/fields}} + }); + + Map toJson() { + return { +{{#fields}} + '{{name}}': {{name}}, +{{/fields}} + }; + } + +{{#fields}} + void set{{#pascalCase}}{{name}}{{/pascalCase}}({{{type}}} value) { + {{name}} = value; + } + +{{/fields}} + static {{#pascalCase}}{{action_name}}{{/pascalCase}}Params empty() { + return {{#pascalCase}}{{action_name}}{{/pascalCase}}Params( +{{#fields}} + {{name}}: {{{emptyValue}}}, +{{/fields}} + ); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is {{#pascalCase}}{{action_name}}{{/pascalCase}}Params{{#fields}} && + other.{{name}} == {{name}}{{/fields}}; + } + + @override + int get hashCode { + return {{#fields}}{{name}}.hashCode{{^last}} ^ {{/last}}{{/fields}}; + } + + @override + String toString() { + return '{{#pascalCase}}{{action_name}}{{/pascalCase}}Params({{#fields}}{{name}}: ${{name}}{{^last}}, {{/last}}{{/fields}})'; + } +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart new file mode 100644 index 0000000..b31d36b --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart @@ -0,0 +1,21 @@ +import 'package:equatable/equatable.dart'; + +class {{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity extends Equatable { +{{#fields}} + final {{{type}}} {{name}}; +{{/fields}} + + const {{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity({ +{{#fields}} + required this.{{name}}, +{{/fields}} + }); + + @override + String toString() { + return '{{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity({{#fields}}{{name}}: ${{name}}{{^last}}, {{/last}}{{/fields}})'; + } + + @override + List get props => [{{#fields}}{{name}}{{^last}}, {{/last}}{{/fields}}]; +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/repositories/{{feature_name}}_repository_interface.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/repositories/{{feature_name}}_repository_interface.dart new file mode 100644 index 0000000..a703127 --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/repositories/{{feature_name}}_repository_interface.dart @@ -0,0 +1,7 @@ +import 'package:result_dart/result_dart.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart'; + +abstract interface class I{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository { + AsyncResult<{{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity> {{#camelCase}}{{action_name}}{{/camelCase}}({{#pascalCase}}{{action_name}}{{/pascalCase}}Params params); +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/usecases/{{action_name}}_usecase.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/usecases/{{action_name}}_usecase.dart new file mode 100644 index 0000000..55ce396 --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/usecases/{{action_name}}_usecase.dart @@ -0,0 +1,17 @@ +import 'package:result_dart/result_dart.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/repositories/{{feature_name}}_repository_interface.dart'; +import 'package:{{package_name}}/src/core/interfaces/usecase_interface.dart'; + +class {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase implements UseCase<{{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity, {{#pascalCase}}{{action_name}}{{/pascalCase}}Params> { + final I{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository _{{#camelCase}}{{feature_name}}{{/camelCase}}Repository; + + {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase({required I{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository {{#camelCase}}{{feature_name}}{{/camelCase}}Repository}) + : _{{#camelCase}}{{feature_name}}{{/camelCase}}Repository = {{#camelCase}}{{feature_name}}{{/camelCase}}Repository; + + @override + AsyncResult<{{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity> call({{#pascalCase}}{{action_name}}{{/pascalCase}}Params params) { + return _{{#camelCase}}{{feature_name}}{{/camelCase}}Repository.{{#camelCase}}{{action_name}}{{/camelCase}}(params); + } +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/validators/{{action_name}}_params_validators.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/validators/{{action_name}}_params_validators.dart new file mode 100644 index 0000000..893d753 --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/domain/validators/{{action_name}}_params_validators.dart @@ -0,0 +1,12 @@ +import 'package:lucid_validation/lucid_validation.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; + +class {{#pascalCase}}{{action_name}}{{/pascalCase}}ParamsValidators extends LucidValidator<{{#pascalCase}}{{action_name}}{{/pascalCase}}Params> { + {{#pascalCase}}{{action_name}}{{/pascalCase}}ParamsValidators() { +{{#fields}} +{{#isString}} + ruleFor((params) => params.{{name}}, key: '{{name}}').notEmpty(message: 'Campo {{name}} é obrigatório'); +{{/isString}} +{{/fields}} + } +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc.dart new file mode 100644 index 0000000..c07b480 --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc.dart @@ -0,0 +1,33 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:result_dart/result_dart.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/usecases/{{action_name}}_usecase.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/validators/{{action_name}}_params_validators.dart'; +import 'package:{{package_name}}/src/core/errors/errors.dart'; +import 'package:{{package_name}}/src/core/extensions/lucid_validator_extensions.dart'; + +part '{{feature_name}}_event.dart'; +part '{{feature_name}}_state.dart'; + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc extends Bloc<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Event, {{#pascalCase}}{{feature_name}}{{/pascalCase}}State> { + final {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase _{{#camelCase}}{{action_name}}{{/camelCase}}Usecase; + + {{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc({required {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase {{#camelCase}}{{action_name}}{{/camelCase}}Usecase}) + : _{{#camelCase}}{{action_name}}{{/camelCase}}Usecase = {{#camelCase}}{{action_name}}{{/camelCase}}Usecase, + super({{#pascalCase}}{{feature_name}}{{/pascalCase}}Initial()) { + on<{{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Requested>((event, emit) async { + emit({{#pascalCase}}{{feature_name}}{{/pascalCase}}Loading()); + + final validator = {{#pascalCase}}{{action_name}}{{/pascalCase}}ParamsValidators(); + + final newState = await validator + .validateResult(event.params) + .flatMap(_{{#camelCase}}{{action_name}}{{/camelCase}}Usecase.call) + .fold({{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Success.new, (exception) => {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Failure(exception: exception as BaseException)); + + emit(newState); + }); + } +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_event.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_event.dart new file mode 100644 index 0000000..c31790a --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_event.dart @@ -0,0 +1,17 @@ +part of '{{feature_name}}_bloc.dart'; + +abstract class {{#pascalCase}}{{feature_name}}{{/pascalCase}}Event extends Equatable { + const {{#pascalCase}}{{feature_name}}{{/pascalCase}}Event(); + + @override + List get props => []; +} + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Requested extends {{#pascalCase}}{{feature_name}}{{/pascalCase}}Event { + final {{#pascalCase}}{{action_name}}{{/pascalCase}}Params params; + + const {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Requested({required this.params}); + + @override + List get props => [params]; +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_state.dart b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_state.dart new file mode 100644 index 0000000..f655df6 --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_state.dart @@ -0,0 +1,30 @@ +part of '{{feature_name}}_bloc.dart'; + +abstract class {{#pascalCase}}{{feature_name}}{{/pascalCase}}State extends Equatable { + const {{#pascalCase}}{{feature_name}}{{/pascalCase}}State(); + + @override + List get props => []; +} + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}Initial extends {{#pascalCase}}{{feature_name}}{{/pascalCase}}State {} + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}Loading extends {{#pascalCase}}{{feature_name}}{{/pascalCase}}State {} + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Success extends {{#pascalCase}}{{feature_name}}{{/pascalCase}}State { + final {{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity entity; + + const {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Success(this.entity); + + @override + List get props => [entity]; +} + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Failure extends {{#pascalCase}}{{feature_name}}{{/pascalCase}}State { + final BaseException exception; + + const {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Failure({required this.exception}); + + @override + List get props => [exception]; +} diff --git a/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/pages/{{#generate_page}}{{feature_name}}_page.dart{{/generate_page}} b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/pages/{{#generate_page}}{{feature_name}}_page.dart{{/generate_page}} new file mode 100644 index 0000000..902d223 --- /dev/null +++ b/app/bricks/feature/__brick__/lib/src/app/features/{{feature_name}}/presentation/pages/{{#generate_page}}{{feature_name}}_page.dart{{/generate_page}} @@ -0,0 +1,46 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc.dart'; +import 'package:{{package_name}}/src/core/DI/dependency_injector.dart'; +import 'package:{{package_name}}/src/core/utils/show_snack_bar.dart'; + +class {{#pascalCase}}{{feature_name}}{{/pascalCase}}Page extends StatefulWidget { + const {{#pascalCase}}{{feature_name}}{{/pascalCase}}Page({super.key}); + + @override + State<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Page> createState() => _{{#pascalCase}}{{feature_name}}{{/pascalCase}}PageState(); +} + +class _{{#pascalCase}}{{feature_name}}{{/pascalCase}}PageState extends State<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Page> { + final _params = {{#pascalCase}}{{action_name}}{{/pascalCase}}Params.empty(); + final _bloc = injector<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc>(); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('{{#pascalCase}}{{feature_name}}{{/pascalCase}}')), + body: BlocListener<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc, {{#pascalCase}}{{feature_name}}{{/pascalCase}}State>( + bloc: _bloc, + listener: (context, state) { + if (state is {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Failure) { + showMessageSnackBar(context, state.exception.message, icon: Icons.error, iconColor: Colors.red); + } + }, + child: BlocBuilder<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc, {{#pascalCase}}{{feature_name}}{{/pascalCase}}State>( + bloc: _bloc, + builder: (context, state) { + return Center( + child: ElevatedButton( + onPressed: () => _bloc.add({{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Requested(params: _params)), + child: state is {{#pascalCase}}{{feature_name}}{{/pascalCase}}Loading + ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2)) + : const Text('{{#pascalCase}}{{action_name}}{{/pascalCase}}'), + ), + ); + }, + ), + ), + ); + } +} diff --git a/app/bricks/feature/__brick__/test/unit/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource_test.dart b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource_test.dart new file mode 100644 index 0000000..fca844b --- /dev/null +++ b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource_test.dart @@ -0,0 +1,50 @@ +import 'package:{{package_name}}/src/app/features/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/core/client_http/rest_client_interface.dart'; +import 'package:{{package_name}}/src/core/client_http/rest_client_request.dart'; +import 'package:{{package_name}}/src/core/client_http/rest_client_response.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class MockRestClient extends Mock implements IRestClient {} + +void main() { + group('{{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource', () { + late {{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource datasource; + late MockRestClient mockRestClient; + + setUpAll(() { + registerFallbackValue(RestClientRequest(path: '')); + }); + + setUp(() { + mockRestClient = MockRestClient(); + datasource = {{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource(restClient: mockRestClient); + }); + + final params = {{#pascalCase}}{{action_name}}{{/pascalCase}}Params( +{{#fields}} + {{name}}: {{{sampleValue}}}, +{{/fields}} + ); + + final response = RestClientResponse( + data: {}, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/{{#snakeCase}}{{feature_name}}{{/snakeCase}}'), + ); + + test('should call rest client with correct parameters', () async { + when(() => mockRestClient.post(any())).thenAnswer((_) async => response); + + await datasource.{{#camelCase}}{{action_name}}{{/camelCase}}(params); + + final captured = verify(() => mockRestClient.post(captureAny())).captured; + final request = captured.first as RestClientRequest; + + expect(request.path, equals('/{{#snakeCase}}{{feature_name}}{{/snakeCase}}')); + expect(request.data, equals(params.toJson())); + }); + }); +} diff --git a/app/bricks/feature/__brick__/test/unit/{{feature_name}}/data/repositories/{{feature_name}}_repository_impl_test.dart b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/data/repositories/{{feature_name}}_repository_impl_test.dart new file mode 100644 index 0000000..8a817ca --- /dev/null +++ b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/data/repositories/{{feature_name}}_repository_impl_test.dart @@ -0,0 +1,63 @@ +import 'package:{{package_name}}/src/app/features/{{feature_name}}/data/datasources/{{feature_name}}_remote_datasource.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/data/repositories/{{feature_name}}_repository_impl.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/core/client_http/rest_client_exception.dart'; +import 'package:{{package_name}}/src/core/client_http/rest_client_request.dart'; +import 'package:{{package_name}}/src/core/client_http/rest_client_response.dart'; +import 'package:{{package_name}}/src/core/errors/default_exception.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource extends Mock implements {{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource {} + +void main() { + group('{{#pascalCase}}{{feature_name}}{{/pascalCase}}RepositoryImpl', () { + late {{#pascalCase}}{{feature_name}}{{/pascalCase}}RepositoryImpl repository; + late Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource mockDatasource; + + setUpAll(() { + registerFallbackValue({{#pascalCase}}{{action_name}}{{/pascalCase}}Params.empty()); + }); + + setUp(() { + mockDatasource = Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}RemoteDatasource(); + repository = {{#pascalCase}}{{feature_name}}{{/pascalCase}}RepositoryImpl({{#camelCase}}{{feature_name}}{{/camelCase}}RemoteDatasource: mockDatasource); + }); + + final params = {{#pascalCase}}{{action_name}}{{/pascalCase}}Params( +{{#fields}} + {{name}}: {{{sampleValue}}}, +{{/fields}} + ); + + test('should return Success when datasource call succeeds', () async { + final response = RestClientResponse( + data: { +{{#fields}} + '{{name}}': {{{sampleValue}}}, +{{/fields}} + }, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/{{#snakeCase}}{{feature_name}}{{/snakeCase}}'), + ); + + when(() => mockDatasource.{{#camelCase}}{{action_name}}{{/camelCase}}(params)).thenAnswer((_) async => response); + + final result = await repository.{{#camelCase}}{{action_name}}{{/camelCase}}(params); + + expect(result.isSuccess(), isTrue); + }); + + test('should return Failure when datasource throws RestClientException', () async { + when(() => mockDatasource.{{#camelCase}}{{action_name}}{{/camelCase}}(params)).thenThrow( + RestClientException(message: 'Request failed', statusCode: 500, error: 'Internal server error'), + ); + + final result = await repository.{{#camelCase}}{{action_name}}{{/camelCase}}(params); + + expect(result.isError(), isTrue); + expect(result.exceptionOrNull(), isA()); + }); + }); +} diff --git a/app/bricks/feature/__brick__/test/unit/{{feature_name}}/domain/usecases/{{action_name}}_usecase_test.dart b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/domain/usecases/{{action_name}}_usecase_test.dart new file mode 100644 index 0000000..01b84e0 --- /dev/null +++ b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/domain/usecases/{{action_name}}_usecase_test.dart @@ -0,0 +1,58 @@ +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/repositories/{{feature_name}}_repository_interface.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/usecases/{{action_name}}_usecase.dart'; +import 'package:{{package_name}}/src/core/errors/default_exception.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:result_dart/result_dart.dart'; + +class Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository extends Mock implements I{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository {} + +void main() { + group('{{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase', () { + late {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase usecase; + late Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository mockRepository; + + setUpAll(() { + registerFallbackValue({{#pascalCase}}{{action_name}}{{/pascalCase}}Params.empty()); + }); + + setUp(() { + mockRepository = Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository(); + usecase = {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase({{#camelCase}}{{feature_name}}{{/camelCase}}Repository: mockRepository); + }); + + final params = {{#pascalCase}}{{action_name}}{{/pascalCase}}Params( +{{#fields}} + {{name}}: {{{sampleValue}}}, +{{/fields}} + ); + + const entity = {{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity( +{{#fields}} + {{name}}: {{{sampleValue}}}, +{{/fields}} + ); + + test('should return entity when repository call succeeds', () async { + when(() => mockRepository.{{#camelCase}}{{action_name}}{{/camelCase}}(params)).thenAnswer((_) async => const Success(entity)); + + final result = await usecase.call(params); + + expect(result.isSuccess(), isTrue); + expect(result.getOrNull(), equals(entity)); + verify(() => mockRepository.{{#camelCase}}{{action_name}}{{/camelCase}}(params)).called(1); + }); + + test('should return Failure when repository call fails', () async { + const exception = DefaultException(message: 'Something went wrong'); + when(() => mockRepository.{{#camelCase}}{{action_name}}{{/camelCase}}(params)).thenAnswer((_) async => const Failure(exception)); + + final result = await usecase.call(params); + + expect(result.isError(), isTrue); + expect(result.exceptionOrNull(), equals(exception)); + }); + }); +} diff --git a/app/bricks/feature/__brick__/test/unit/{{feature_name}}/domain/validators/{{action_name}}_params_validators_test.dart b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/domain/validators/{{action_name}}_params_validators_test.dart new file mode 100644 index 0000000..afd97e1 --- /dev/null +++ b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/domain/validators/{{action_name}}_params_validators_test.dart @@ -0,0 +1,33 @@ +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/validators/{{action_name}}_params_validators.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('{{#pascalCase}}{{action_name}}{{/pascalCase}}ParamsValidators', () { + late {{#pascalCase}}{{action_name}}{{/pascalCase}}ParamsValidators validator; + + setUp(() { + validator = {{#pascalCase}}{{action_name}}{{/pascalCase}}ParamsValidators(); + }); + + test('should return invalid when required fields are empty', () { + final params = {{#pascalCase}}{{action_name}}{{/pascalCase}}Params.empty(); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + }); + + test('should return valid when all fields are filled', () { + final params = {{#pascalCase}}{{action_name}}{{/pascalCase}}Params( +{{#fields}} + {{name}}: {{{sampleValue}}}, +{{/fields}} + ); + + final result = validator.validate(params); + + expect(result.isValid, isTrue); + }); + }); +} diff --git a/app/bricks/feature/__brick__/test/unit/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc_test.dart b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc_test.dart new file mode 100644 index 0000000..fd0e96d --- /dev/null +++ b/app/bricks/feature/__brick__/test/unit/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc_test.dart @@ -0,0 +1,67 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/dtos/{{action_name}}_params.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/entities/{{entity_name}}_entity.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/repositories/{{feature_name}}_repository_interface.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/domain/usecases/{{action_name}}_usecase.dart'; +import 'package:{{package_name}}/src/app/features/{{feature_name}}/presentation/bloc/{{feature_name}}_bloc.dart'; +import 'package:{{package_name}}/src/core/errors/default_exception.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:result_dart/result_dart.dart'; + +class Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository extends Mock implements I{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository {} + +void main() { + group('{{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc', () { + late Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository mockRepository; + late {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase usecase; + + final params = {{#pascalCase}}{{action_name}}{{/pascalCase}}Params( +{{#fields}} + {{name}}: {{{sampleValue}}}, +{{/fields}} + ); + + const entity = {{#pascalCase}}{{entity_name}}{{/pascalCase}}Entity( +{{#fields}} + {{name}}: {{{sampleValue}}}, +{{/fields}} + ); + + setUpAll(() { + registerFallbackValue(params); + }); + + setUp(() { + mockRepository = Mock{{#pascalCase}}{{feature_name}}{{/pascalCase}}Repository(); + usecase = {{#pascalCase}}{{action_name}}{{/pascalCase}}Usecase({{#camelCase}}{{feature_name}}{{/camelCase}}Repository: mockRepository); + }); + + blocTest<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc, {{#pascalCase}}{{feature_name}}{{/pascalCase}}State>( + 'emits [Loading, Success] when {{#camelCase}}{{action_name}}{{/camelCase}} succeeds', + build: () { + when(() => mockRepository.{{#camelCase}}{{action_name}}{{/camelCase}}(params)).thenAnswer((_) async => const Success(entity)); + return {{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc({{#camelCase}}{{action_name}}{{/camelCase}}Usecase: usecase); + }, + act: (bloc) => bloc.add({{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Requested(params: params)), + expect: () => [ + {{#pascalCase}}{{feature_name}}{{/pascalCase}}Loading(), + const {{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Success(entity), + ], + ); + + blocTest<{{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc, {{#pascalCase}}{{feature_name}}{{/pascalCase}}State>( + 'emits [Loading, Failure] when {{#camelCase}}{{action_name}}{{/camelCase}} fails', + build: () { + const exception = DefaultException(message: 'Something went wrong'); + when(() => mockRepository.{{#camelCase}}{{action_name}}{{/camelCase}}(params)).thenAnswer((_) async => const Failure(exception)); + return {{#pascalCase}}{{feature_name}}{{/pascalCase}}Bloc({{#camelCase}}{{action_name}}{{/camelCase}}Usecase: usecase); + }, + act: (bloc) => bloc.add({{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Requested(params: params)), + expect: () => [ + {{#pascalCase}}{{feature_name}}{{/pascalCase}}Loading(), + isA<{{#pascalCase}}{{feature_name}}{{/pascalCase}}{{#pascalCase}}{{action_name}}{{/pascalCase}}Failure>(), + ], + ); + }); +} diff --git a/app/bricks/feature/brick.yaml b/app/bricks/feature/brick.yaml new file mode 100644 index 0000000..6deabe0 --- /dev/null +++ b/app/bricks/feature/brick.yaml @@ -0,0 +1,36 @@ +name: feature +description: >- + Scaffolds a Clean Architecture + BLoC feature (domain, data, presentation, + tests) matching this repo's conventions - see lib/src/app/features/auth + as the reference implementation and .claude/rules/ for the rules it follows. +version: 0.1.0 +environment: + mason: ">=0.1.0-dev <0.2.0" + +vars: + feature_name: + type: string + description: Feature name in snake_case, e.g. product, order. + prompt: Feature name (snake_case) + entity_name: + type: string + description: Entity name in snake_case. Leave blank to reuse feature_name. + default: "" + prompt: Entity name (snake_case, blank = same as feature_name) + action_name: + type: string + description: Primary action in camelCase, e.g. create, getAll, login. + default: "create" + prompt: Action name (camelCase) + fields: + type: string + description: >- + Comma-separated name:type pairs for the entity/params, + e.g. "id:String,name:String,price:double". + default: "id:String,name:String" + prompt: Fields as "name:type,name:type" + generate_page: + type: boolean + description: Generate a presentation page for this feature? + default: false + prompt: Generate a page? diff --git a/app/bricks/feature/hooks/post_gen.dart b/app/bricks/feature/hooks/post_gen.dart new file mode 100644 index 0000000..73d48d9 --- /dev/null +++ b/app/bricks/feature/hooks/post_gen.dart @@ -0,0 +1,18 @@ +import 'dart:io'; + +import 'package:mason/mason.dart'; + +void run(HookContext context) async { + final feature = context.vars['feature_name']; + + final format = await Process.run('dart', ['format', 'lib/src/app/features/$feature', 'test/unit/$feature']); + if (format.exitCode != 0) { + context.logger.warn('dart format failed - run it manually: dart format lib/src/app/features/$feature test/unit/$feature'); + } + + context.logger.info(''); + context.logger.info('Feature "$feature" scaffolded. Remaining manual steps:'); + context.logger.info('1. Wire it up in lib/src/core/DI/dependency_injector.dart (see the auth block for the shape).'); + context.logger.info('2. Add a route in lib/routes.dart if it needs a page.'); + context.logger.info('3. Run: flutter analyze && flutter test test/unit/$feature/'); +} diff --git a/app/bricks/feature/hooks/pre_gen.dart b/app/bricks/feature/hooks/pre_gen.dart new file mode 100644 index 0000000..822579e --- /dev/null +++ b/app/bricks/feature/hooks/pre_gen.dart @@ -0,0 +1,78 @@ +import 'dart:io'; + +import 'package:mason/mason.dart'; +import 'package:yaml/yaml.dart' as yaml; + +String _emptyValueFor(String type) { + switch (type) { + case 'String': + return "''"; + case 'int': + return '0'; + case 'double': + return '0.0'; + case 'num': + return '0'; + case 'bool': + return 'false'; + default: + return 'null'; + } +} + +String _sampleValueFor(String type) { + switch (type) { + case 'String': + return "'test'"; + case 'int': + return '1'; + case 'double': + return '1.0'; + case 'num': + return '1'; + case 'bool': + return 'true'; + default: + return 'null'; + } +} + +void run(HookContext context) { + final raw = context.vars['fields'] as String? ?? ''; + final rawFields = raw.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList(); + + final fields = >[]; + for (var i = 0; i < rawFields.length; i++) { + final segment = rawFields[i].split(':'); + final type = segment.length > 1 ? segment[1].trim() : 'String'; + fields.add({ + 'name': segment[0].trim(), + 'type': type, + 'last': i == rawFields.length - 1, + 'emptyValue': _emptyValueFor(type), + 'sampleValue': _sampleValueFor(type), + 'isString': type == 'String', + }); + } + + var entityName = (context.vars['entity_name'] as String?)?.trim() ?? ''; + if (entityName.isEmpty) { + entityName = context.vars['feature_name'] as String; + } + + var packageName = 'phpeste_app'; + final pubspecFile = File('pubspec.yaml'); + if (pubspecFile.existsSync()) { + final doc = yaml.loadYaml(pubspecFile.readAsStringSync()); + if (doc is Map && doc['name'] is String) { + packageName = doc['name'] as String; + } + } + + context.vars = { + ...context.vars, + 'fields': fields, + 'entity_name': entityName, + 'package_name': packageName, + }; +} diff --git a/app/bricks/feature/hooks/pubspec.lock b/app/bricks/feature/hooks/pubspec.lock new file mode 100644 index 0000000..da6d941 --- /dev/null +++ b/app/bricks/feature/hooks/pubspec.lock @@ -0,0 +1,221 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + sha256: ace891da0862b0e4cabbb064ee3fd87b2728b898949fdb366d83fe98342c9f19 + url: "https://pub.dev" + source: hosted + version: "4.2.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + io: + dependency: transitive + description: + name: io + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + mason: + dependency: "direct main" + description: + name: mason + sha256: "515b28eedc3e106bbbfb95f0ff63471003396978d3413daeba0a64bcac01367b" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + mason_logger: + dependency: transitive + description: + name: mason_logger + sha256: "1d46102c6f299c0df7fe986dd3dd3271d57c2ec7c00ae590660b7c3018810048" + url: "https://pub.dev" + source: hosted + version: "0.3.5" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.dev" + source: hosted + version: "1.19.0" + mustache_template: + dependency: transitive + description: + name: mustache_template + sha256: c689b4d59176f8c7a2860aab765d205916aa5b06cfafff7613bfcc42fa996143 + url: "https://pub.dev" + source: hosted + version: "2.0.5" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + pool: + dependency: transitive + description: + name: pool + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" + url: "https://pub.dev" + source: hosted + version: "1.5.3" + posix: + dependency: transitive + description: + name: posix + sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e + url: "https://pub.dev" + source: hosted + version: "6.5.2" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + yaml: + dependency: "direct main" + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" +sdks: + dart: ">=3.10.0 <4.0.0" diff --git a/app/bricks/feature/hooks/pubspec.yaml b/app/bricks/feature/hooks/pubspec.yaml new file mode 100644 index 0000000..cf3dc45 --- /dev/null +++ b/app/bricks/feature/hooks/pubspec.yaml @@ -0,0 +1,6 @@ +name: feature_hooks +environment: + sdk: ">=3.0.0 <4.0.0" +dependencies: + mason: ^0.1.1 + yaml: ^3.1.2 diff --git a/app/env/dev.json b/app/env/dev.json new file mode 100644 index 0000000..89e4e1d --- /dev/null +++ b/app/env/dev.json @@ -0,0 +1,6 @@ +{ + "FLAVOR": "dev", + "API_URL": "http://10.0.2.2:8000/api/v1", + "USE_MOCKS": false, + "LOG_API": true +} diff --git a/app/env/prod.json b/app/env/prod.json new file mode 100644 index 0000000..121baea --- /dev/null +++ b/app/env/prod.json @@ -0,0 +1,6 @@ +{ + "FLAVOR": "prod", + "API_URL": "https://api.phpeste.dev/api/v1", + "USE_MOCKS": false, + "LOG_API": false +} diff --git a/app/ios/.gitignore b/app/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/app/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/app/ios/ExportOptions.plist b/app/ios/ExportOptions.plist new file mode 100644 index 0000000..3c4b1df --- /dev/null +++ b/app/ios/ExportOptions.plist @@ -0,0 +1,14 @@ + + + + + method + app-store-connect + teamID + YOUR_TEAM_ID + signingStyle + automatic + uploadSymbols + + + diff --git a/app/ios/Flutter/AppFrameworkInfo.plist b/app/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..7c56964 --- /dev/null +++ b/app/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/app/ios/Flutter/Debug.xcconfig b/app/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..ec97fc6 --- /dev/null +++ b/app/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/app/ios/Flutter/Release.xcconfig b/app/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..c4855bf --- /dev/null +++ b/app/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/app/ios/Podfile b/app/ios/Podfile new file mode 100644 index 0000000..e549ee2 --- /dev/null +++ b/app/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '12.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/app/ios/Podfile.lock b/app/ios/Podfile.lock new file mode 100644 index 0000000..d5e6ab1 --- /dev/null +++ b/app/ios/Podfile.lock @@ -0,0 +1,23 @@ +PODS: + - Flutter (1.0.0) + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - Flutter (from `Flutter`) + - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + shared_preferences_foundation: + :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + +SPEC CHECKSUMS: + Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 + shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7 + +PODFILE CHECKSUM: 4305caec6b40dde0ae97be1573c53de1882a07e5 + +COCOAPODS: 1.16.2 diff --git a/app/ios/Runner.xcodeproj/project.pbxproj b/app/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..7c39e14 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,731 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 48CF5BD7D97691A808CD4651 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4C1C7A58E6736735DB3741AF /* Pods_Runner.framework */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + 986B80D372F50A98490304CF /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D1F0BAC141A9D52C59E53F78 /* Pods_RunnerTests.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 4C1C7A58E6736735DB3741AF /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5DEF7CE028004B43195CDFB9 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 7F308FC03D36ECE966630E91 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 8C504740496C66ED7232174B /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + 94AA1E5FA711D8D131FC681B /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + D1F0BAC141A9D52C59E53F78 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + DDB08D0DC602AE2B4AE4D1FF /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + FB3DC523F3B0CEFCDBB493AC /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 48CF5BD7D97691A808CD4651 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9F7FF8772AB7D5EF1FE767B8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 986B80D372F50A98490304CF /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 5F23A67F15B233BB919E0F5B /* Pods */ = { + isa = PBXGroup; + children = ( + 7F308FC03D36ECE966630E91 /* Pods-Runner.debug.xcconfig */, + DDB08D0DC602AE2B4AE4D1FF /* Pods-Runner.release.xcconfig */, + FB3DC523F3B0CEFCDBB493AC /* Pods-Runner.profile.xcconfig */, + 94AA1E5FA711D8D131FC681B /* Pods-RunnerTests.debug.xcconfig */, + 8C504740496C66ED7232174B /* Pods-RunnerTests.release.xcconfig */, + 5DEF7CE028004B43195CDFB9 /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 5F23A67F15B233BB919E0F5B /* Pods */, + E3DA6A7AD95F5F6015C68D6E /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; + E3DA6A7AD95F5F6015C68D6E /* Frameworks */ = { + isa = PBXGroup; + children = ( + 4C1C7A58E6736735DB3741AF /* Pods_Runner.framework */, + D1F0BAC141A9D52C59E53F78 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + DDE474FEC955071850376935 /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 9F7FF8772AB7D5EF1FE767B8 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + A0D2CE5D6D9177A98AEC934A /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 427D45CCC00DEF67533D6D75 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 427D45CCC00DEF67533D6D75 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; + A0D2CE5D6D9177A98AEC934A /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + DDE474FEC955071850376935 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 7F7JZ33L4R; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.phpeste.app; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 94AA1E5FA711D8D131FC681B /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.phpeste.app.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 8C504740496C66ED7232174B /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.phpeste.app.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5DEF7CE028004B43195CDFB9 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.phpeste.app.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 7F7JZ33L4R; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.phpeste.app; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 7F7JZ33L4R; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.phpeste.app; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..15cada4 --- /dev/null +++ b/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner.xcworkspace/contents.xcworkspacedata b/app/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/app/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/app/ios/Runner/AppDelegate.swift b/app/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/app/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/app/ios/Runner/Base.lproj/LaunchScreen.storyboard b/app/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/app/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner/Base.lproj/Main.storyboard b/app/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/app/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner/Info.plist b/app/ios/Runner/Info.plist new file mode 100644 index 0000000..5fc930f --- /dev/null +++ b/app/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + PHPeste + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + PHPeste + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/app/ios/Runner/Runner-Bridging-Header.h b/app/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/app/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/app/ios/RunnerTests/RunnerTests.swift b/app/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/app/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/app/lib/app_widget.dart b/app/lib/app_widget.dart new file mode 100644 index 0000000..e43358c --- /dev/null +++ b/app/lib/app_widget.dart @@ -0,0 +1,30 @@ +import 'package:phpeste_app/routes.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/bloc/auth_bloc.dart'; +import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; +import 'package:phpeste_app/src/core/config/app_config.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class AppWidget extends StatelessWidget { + const AppWidget({super.key}); + + @override + Widget build(BuildContext context) { + return MultiBlocProvider( + providers: [ + BlocProvider( + create: (context) => injector(), + ), + ], + child: MaterialApp.router( + title: 'PHPeste', + debugShowCheckedModeBanner: !AppConfig.isProduction, + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + routerConfig: router, + ), + ); + } +} diff --git a/app/lib/main.dart b/app/lib/main.dart new file mode 100644 index 0000000..99998ea --- /dev/null +++ b/app/lib/main.dart @@ -0,0 +1,38 @@ +import 'package:phpeste_app/app_widget.dart'; +import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; +import 'package:phpeste_app/src/core/config/app_config.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; +import 'package:flutter/foundation.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:intl/intl.dart'; +import 'package:logger/logger.dart'; +import 'package:marionette_flutter/marionette_flutter.dart'; +import 'package:marionette_logger/marionette_logger.dart'; + +Future main() async { + /// Coleta os logs emitidos via `Logger` para que o marionette_mcp + /// (agente de IA conectado ao app em runtime) consiga lê-los com `get_logs`. + final logCollector = LoggerLogCollector(); + + /// `MarionetteBinding` só roda em debug - em release o app usa o binding + /// padrão do Flutter normalmente. Veja https://github.com/leancodepl/marionette_mcp + if (kDebugMode) { + MarionetteBinding.ensureInitialized( + MarionetteConfiguration(logCollector: logCollector), + ); + } else { + WidgetsFlutterBinding.ensureInitialized(); + } + + Intl.defaultLocale = 'pt_BR'; + + final logger = Logger(output: MultiOutput([ConsoleOutput(), logCollector])); + + setupDependencyInjector( + loggerApi: AppConfig.logApi, + useMocks: AppConfig.useMocks, + logger: logger, + ); + await injector().restore(); + runApp(const AppWidget()); +} diff --git a/app/lib/routes.dart b/app/lib/routes.dart new file mode 100644 index 0000000..e713b74 --- /dev/null +++ b/app/lib/routes.dart @@ -0,0 +1,58 @@ +import 'package:go_router/go_router.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/pages/login_page.dart'; +import 'package:phpeste_app/src/app/features/base/presentation/pages/base_page.dart'; +import 'package:phpeste_app/src/app/features/home/presentation/pages/home_page.dart'; +import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; + +class AppRoutes { + static const String login = '/entrar'; + static const String home = '/inicio'; + static const String profile = '/perfil'; + + static const Set public = {login}; +} + +String? sessionRedirect({required bool signedIn, required Uri location}) { + final isPublic = AppRoutes.public.contains(location.path); + + if (!signedIn && !isPublic) { + final destination = location.toString(); + return Uri(path: AppRoutes.login, queryParameters: destination == '/' ? null : {'de': destination}).toString(); + } + + if (signedIn && location.path == AppRoutes.login) { + final destination = location.queryParameters['de']; + return destination != null && destination.startsWith('/') && !destination.startsWith('//') ? destination : AppRoutes.home; + } + + return null; +} + +GoRouter createRouter(SessionService session) => GoRouter( + initialLocation: AppRoutes.home, + refreshListenable: session.signedIn, + redirect: (context, state) => sessionRedirect(signedIn: session.signedIn.value, location: state.uri), + routes: [ + StatefulShellRoute.indexedStack( + builder: (context, state, shell) => BasePage(shell: shell), + branches: [ + StatefulShellBranch( + routes: [ + GoRoute(path: AppRoutes.home, name: 'home', builder: (context, state) => const HomePage()), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute(path: AppRoutes.profile, name: 'profile', builder: (context, state) => const Placeholder()), + ], + ), + ], + ), + GoRoute(path: '/', redirect: (context, state) => AppRoutes.home), + GoRoute(path: AppRoutes.login, name: 'login', builder: (context, state) => const LoginPage()), + ], + ); + +final GoRouter router = createRouter(injector()); diff --git a/app/lib/src/app/features/auth/data/datasources/auth_remote_datasource.dart b/app/lib/src/app/features/auth/data/datasources/auth_remote_datasource.dart new file mode 100644 index 0000000..f05c6a4 --- /dev/null +++ b/app/lib/src/app/features/auth/data/datasources/auth_remote_datasource.dart @@ -0,0 +1,17 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/utils/endpoints.dart'; + +class AuthRemoteDatasource { + final IRestClient _restClient; + + AuthRemoteDatasource({required IRestClient restClient}) : _restClient = restClient; + + Future login(LoginParams params) => // + _restClient.post( + RestClientRequest( + path: Endpoints.login, + data: params.toJson(), + ), + ); +} diff --git a/app/lib/src/app/features/auth/data/models/auth_response_model.dart b/app/lib/src/app/features/auth/data/models/auth_response_model.dart new file mode 100644 index 0000000..bd4a76f --- /dev/null +++ b/app/lib/src/app/features/auth/data/models/auth_response_model.dart @@ -0,0 +1,30 @@ +import 'dart:convert'; + +import 'package:phpeste_app/src/app/features/auth/data/models/user_model.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; + +class AuthResponseModel extends AuthResponseEntity { + const AuthResponseModel({required super.user, required super.token}); + + Map toMap() { + return { + 'user': (user as UserModel).toMap(), + 'token': token, + }; + } + + factory AuthResponseModel.fromMap(Map map) { + try { + return AuthResponseModel( + user: UserModel.fromMap(map['user'] as Map), + token: map['token'] as String, + ); + } catch (e, s) { + throw Exception('Error parsing AuthResponseModel: $e \nStack trace: $s'); + } + } + + String toJson() => json.encode(toMap()); + + factory AuthResponseModel.fromJson(String source) => AuthResponseModel.fromMap(json.decode(source) as Map); +} diff --git a/app/lib/src/app/features/auth/data/models/user_model.dart b/app/lib/src/app/features/auth/data/models/user_model.dart new file mode 100644 index 0000000..6b09da4 --- /dev/null +++ b/app/lib/src/app/features/auth/data/models/user_model.dart @@ -0,0 +1,31 @@ +import 'dart:convert'; + +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; + +class UserModel extends UserEntity { + const UserModel({required super.id, required super.email, required super.name}); + + Map toMap() { + return { + 'id': id, + 'email': email, + 'name': name, + }; + } + + factory UserModel.fromMap(Map map) { + try { + return UserModel( + id: map['id'] as String, + email: map['email'] as String, + name: map['name'] as String, + ); + } catch (e, stackTrace) { + throw Exception('Error parsing UserModel: $e\nStack trace: $stackTrace'); + } + } + + String toJson() => json.encode(toMap()); + + factory UserModel.fromJson(String source) => UserModel.fromMap(json.decode(source) as Map); +} diff --git a/app/lib/src/app/features/auth/data/repositories/auth_repository_impl.dart b/app/lib/src/app/features/auth/data/repositories/auth_repository_impl.dart new file mode 100644 index 0000000..fac4ddb --- /dev/null +++ b/app/lib/src/app/features/auth/data/repositories/auth_repository_impl.dart @@ -0,0 +1,31 @@ +import 'package:phpeste_app/src/app/features/auth/data/datasources/auth_remote_datasource.dart'; +import 'package:phpeste_app/src/app/features/auth/data/models/auth_response_model.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/repositories/auth_repository_interface.dart'; +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/errors/errors.dart'; +import 'package:phpeste_app/src/core/errors/unauthorized_exception.dart'; +import 'package:result_dart/result_dart.dart'; + +class AuthRepositoryImpl implements IAuthRepository { + final AuthRemoteDatasource _authRemoteDatasource; + + AuthRepositoryImpl({required AuthRemoteDatasource authRemoteDatasource}) : _authRemoteDatasource = authRemoteDatasource; + + @override + AsyncResult login(LoginParams params) async { + try { + final response = await _authRemoteDatasource.login(params); + final authResponse = AuthResponseModel.fromMap(response.data as Map); + return Success(authResponse); + } on RestClientException catch (e) { + if (e.statusCode == 401) { + return Failure(UnauthorizedException(message: e.message)); + } + return Failure(DefaultException(message: e.message)); + } catch (e) { + return Failure(DefaultException(message: 'Erro inesperado: ${e.toString()}')); + } + } +} diff --git a/app/lib/src/app/features/auth/data/repositories/auth_repository_mock.dart b/app/lib/src/app/features/auth/data/repositories/auth_repository_mock.dart new file mode 100644 index 0000000..90e598e --- /dev/null +++ b/app/lib/src/app/features/auth/data/repositories/auth_repository_mock.dart @@ -0,0 +1,38 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/repositories/auth_repository_interface.dart'; +import 'package:phpeste_app/src/core/errors/errors.dart'; +import 'package:result_dart/result_dart.dart'; + +/// Mock de [IAuthRepository] para uso em desenvolvimento e testes de UI. +/// +/// Credenciais válidas: +/// - Email: `teste@teste.com` +/// - Senha: `123456Aa!` +/// +/// Qualquer outra combinação retorna [DefaultException] com mensagem "Credenciais inválidas". +class AuthRepositoryMock implements IAuthRepository { + static const _validEmail = 'teste@teste.com'; + static const _validPassword = '123456Aa!'; + + @override + AsyncResult login(LoginParams params) async { + await Future.delayed(const Duration(milliseconds: 500)); // simula latência + + if (params.email == _validEmail && params.password == _validPassword) { + return const Success( + AuthResponseEntity( + token: 'mock-token-abc123', + user: UserEntity( + id: '1', + email: _validEmail, + name: 'Usuário Teste', + ), + ), + ); + } + + return const Failure(DefaultException(message: 'Credenciais inválidas')); + } +} diff --git a/app/lib/src/app/features/auth/domain/dtos/login_params.dart b/app/lib/src/app/features/auth/domain/dtos/login_params.dart new file mode 100644 index 0000000..c46ab0f --- /dev/null +++ b/app/lib/src/app/features/auth/domain/dtos/login_params.dart @@ -0,0 +1,46 @@ +class LoginParams { + String email; + String password; + + LoginParams({ + required this.email, + required this.password, + }); + + Map toJson() { + return { + 'email': email, + 'password': password, + }; + } + + void setEmail(String value) { + email = value; + } + + void setPassword(String value) { + password = value; + } + + static LoginParams empty() { + return LoginParams(email: '', password: ''); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is LoginParams && + other.email == email && + other.password == password; + } + + @override + int get hashCode { + return email.hashCode ^ password.hashCode; + } + + @override + String toString() { + return 'LoginParams(email: $email, password: $password)'; + } +} diff --git a/app/lib/src/app/features/auth/domain/entities/auth_response_entity.dart b/app/lib/src/app/features/auth/domain/entities/auth_response_entity.dart new file mode 100644 index 0000000..a6b94c1 --- /dev/null +++ b/app/lib/src/app/features/auth/domain/entities/auth_response_entity.dart @@ -0,0 +1,20 @@ +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; +import 'package:equatable/equatable.dart'; + +class AuthResponseEntity extends Equatable { + final UserEntity user; + final String token; + + const AuthResponseEntity({ + required this.user, + required this.token, + }); + + @override + String toString() { + return 'AuthResponseEntity(user: $user, token: $token)'; + } + + @override + List get props => [user, token]; +} diff --git a/app/lib/src/app/features/auth/domain/entities/user_entity.dart b/app/lib/src/app/features/auth/domain/entities/user_entity.dart new file mode 100644 index 0000000..c686e78 --- /dev/null +++ b/app/lib/src/app/features/auth/domain/entities/user_entity.dart @@ -0,0 +1,21 @@ +import 'package:equatable/equatable.dart'; + +class UserEntity extends Equatable { + final String id; + final String email; + final String name; + + const UserEntity({ + required this.id, + required this.email, + required this.name, + }); + + @override + String toString() { + return 'UserEntity(id: $id, email: $email, name: $name)'; + } + + @override + List get props => [id, email, name]; +} diff --git a/app/lib/src/app/features/auth/domain/repositories/auth_repository_interface.dart b/app/lib/src/app/features/auth/domain/repositories/auth_repository_interface.dart new file mode 100644 index 0000000..33f487a --- /dev/null +++ b/app/lib/src/app/features/auth/domain/repositories/auth_repository_interface.dart @@ -0,0 +1,7 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:result_dart/result_dart.dart'; + +abstract interface class IAuthRepository { + AsyncResult login(LoginParams login); +} diff --git a/app/lib/src/app/features/auth/domain/usecases/login_usecase.dart b/app/lib/src/app/features/auth/domain/usecases/login_usecase.dart new file mode 100644 index 0000000..1901b54 --- /dev/null +++ b/app/lib/src/app/features/auth/domain/usecases/login_usecase.dart @@ -0,0 +1,27 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/repositories/auth_repository_interface.dart'; +import 'package:phpeste_app/src/core/interfaces/usecase_interface.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; +import 'package:result_dart/result_dart.dart'; + +class LoginUsecase implements UseCase { + final IAuthRepository _authRepository; + final SessionService _sessionService; + + LoginUsecase({required IAuthRepository authRepository, required SessionService sessionService}) + : _authRepository = authRepository, + _sessionService = sessionService; + + @override + AsyncResult call(LoginParams params) async { + final result = await _authRepository.login(params); + + final response = result.getOrNull(); + if (response != null) { + await _sessionService.saveSession(response.token); + } + + return result; + } +} diff --git a/app/lib/src/app/features/auth/domain/validators/login_params_validators.dart b/app/lib/src/app/features/auth/domain/validators/login_params_validators.dart new file mode 100644 index 0000000..e29bc4a --- /dev/null +++ b/app/lib/src/app/features/auth/domain/validators/login_params_validators.dart @@ -0,0 +1,13 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/core/extensions/lucid_validator_extensions.dart'; +import 'package:lucid_validation/lucid_validation.dart'; + +class LoginParamsValidators extends LucidValidator { + LoginParamsValidators() { + ruleFor((params) => params.email, key: 'email') // + .notEmpty(message: 'Email não pode ser vazio') + .validEmail(message: 'Email inválido'); + ruleFor((params) => params.password, key: 'password') // + .customValidPassword(); + } +} diff --git a/app/lib/src/app/features/auth/infrastructure/auth_interceptor.dart b/app/lib/src/app/features/auth/infrastructure/auth_interceptor.dart new file mode 100644 index 0000000..06622f0 --- /dev/null +++ b/app/lib/src/app/features/auth/infrastructure/auth_interceptor.dart @@ -0,0 +1,37 @@ +import 'dart:async'; + +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; +import 'package:result_dart/result_dart.dart'; + +class AuthInterceptor implements IClientInterceptor { + final SessionService _sessionService; + + AuthInterceptor({ + required SessionService sessionService, + }) : _sessionService = sessionService; + + @override + FutureOr onError(RestClientException error) async { + return error; + } + + @override + FutureOr onRequest(RestClientRequest request) async { + final token = await _sessionService.getToken(); + + if (token != null && token.isNotEmpty) { + return Success(token) // + .map((token) => 'Bearer $token') + .map((str) => request..headers?.addAll({'Authorization': str})) + .getOrDefault(request); + } + + return request; + } + + @override + FutureOr onResponse(RestClientResponse response) { + return response; + } +} diff --git a/app/lib/src/app/features/auth/presentation/bloc/auth_bloc.dart b/app/lib/src/app/features/auth/presentation/bloc/auth_bloc.dart new file mode 100644 index 0000000..88f89a6 --- /dev/null +++ b/app/lib/src/app/features/auth/presentation/bloc/auth_bloc.dart @@ -0,0 +1,33 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/usecases/login_usecase.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/validators/login_params_validators.dart'; +import 'package:phpeste_app/src/core/errors/errors.dart'; +import 'package:phpeste_app/src/core/extensions/lucid_validator_extensions.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:result_dart/result_dart.dart'; + +part 'auth_event.dart'; +part 'auth_state.dart'; + +class AuthBloc extends Bloc { + final LoginUsecase _loginUsecase; + + AuthBloc({required LoginUsecase loginUsecase}) + : _loginUsecase = loginUsecase, + super(AuthInitial()) { + on((event, emit) async { + emit(AuthLoading()); + + final validator = LoginParamsValidators(); + + final newState = await validator + .validateResult(event.params) // + .flatMap(_loginUsecase.call) + .fold(AuthLoginSuccess.new, (exception) => AuthLoginFailure(exception: exception as BaseException)); + + emit(newState); + }); + } +} diff --git a/app/lib/src/app/features/auth/presentation/bloc/auth_event.dart b/app/lib/src/app/features/auth/presentation/bloc/auth_event.dart new file mode 100644 index 0000000..f3c1279 --- /dev/null +++ b/app/lib/src/app/features/auth/presentation/bloc/auth_event.dart @@ -0,0 +1,19 @@ +part of 'auth_bloc.dart'; + +abstract class AuthEvent extends Equatable { + const AuthEvent(); + + @override + List get props => []; +} + +class AuthLoginRequested extends AuthEvent { + final LoginParams params; + + const AuthLoginRequested({ + required this.params, + }); + + @override + List get props => [params]; +} diff --git a/app/lib/src/app/features/auth/presentation/bloc/auth_state.dart b/app/lib/src/app/features/auth/presentation/bloc/auth_state.dart new file mode 100644 index 0000000..d70becb --- /dev/null +++ b/app/lib/src/app/features/auth/presentation/bloc/auth_state.dart @@ -0,0 +1,30 @@ +part of 'auth_bloc.dart'; + +abstract class AuthState extends Equatable { + const AuthState(); + + @override + List get props => []; +} + +class AuthInitial extends AuthState {} + +class AuthLoading extends AuthState {} + +class AuthLoginSuccess extends AuthState { + final AuthResponseEntity authResponse; + + const AuthLoginSuccess(this.authResponse); + + @override + List get props => [authResponse]; +} + +class AuthLoginFailure extends AuthState { + final BaseException exception; + + const AuthLoginFailure({required this.exception}); + + @override + List get props => [exception]; +} diff --git a/app/lib/src/app/features/auth/presentation/pages/login_page.dart b/app/lib/src/app/features/auth/presentation/pages/login_page.dart new file mode 100644 index 0000000..bfc9439 --- /dev/null +++ b/app/lib/src/app/features/auth/presentation/pages/login_page.dart @@ -0,0 +1,139 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/validators/login_params_validators.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/bloc/auth_bloc.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/texts/auth_texts.dart'; +import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; +import 'package:phpeste_app/src/core/utils/show_snack_bar.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class LoginPage extends StatefulWidget { + const LoginPage({super.key}); + + @override + State createState() => _LoginPageState(); +} + +class _LoginPageState extends State { + final _formKey = GlobalKey(); + + bool _obscurePassword = true; + + LoginParams loginParams = LoginParams.empty(); + final LoginParamsValidators loginParamsValidator = LoginParamsValidators(); + + final authbloc = injector(); + + @override + void dispose() { + loginParams = LoginParams.empty(); + _formKey.currentState?.reset(); + _obscurePassword = true; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text(AuthTexts.title), + centerTitle: true, + ), + body: BlocListener( + listener: (context, state) { + if (state is AuthLoginSuccess) { + showMessageSnackBar(context, AuthTexts.success, icon: Icons.check_circle, iconColor: Colors.green, textColor: Colors.white); + } + if (state is AuthLoginFailure) { + showMessageSnackBar(context, state.exception.message, icon: Icons.error, iconColor: Colors.red, textColor: Colors.white); + } + }, + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Form( + key: _formKey, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Icon( + Icons.person_outline, + size: 80, + color: Theme.of(context).primaryColor, + ), + const SizedBox(height: 32), + TextFormField( + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration( + labelText: AuthTexts.email, + prefixIcon: Icon(Icons.email_outlined), + border: OutlineInputBorder(), + ), + validator: loginParamsValidator.byField(loginParams, 'email'), + onChanged: loginParams.setEmail, + autovalidateMode: AutovalidateMode.onUserInteraction, + ), + const SizedBox(height: 16), + TextFormField( + obscureText: _obscurePassword, + decoration: InputDecoration( + labelText: AuthTexts.password, + prefixIcon: const Icon(Icons.lock_outline), + suffixIcon: IconButton( + tooltip: _obscurePassword ? AuthTexts.showPassword : AuthTexts.hidePassword, + icon: Icon( + _obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined, + ), + onPressed: () { + setState(() { + _obscurePassword = !_obscurePassword; + }); + }, + ), + border: const OutlineInputBorder(), + ), + validator: loginParamsValidator.byField(loginParams, 'password'), + onChanged: loginParams.setPassword, + autovalidateMode: AutovalidateMode.onUserInteraction, + ), + const SizedBox(height: 24), + BlocBuilder( + builder: (context, state) { + return ElevatedButton( + onPressed: () { + authbloc.add(AuthLoginRequested(params: loginParams)); + }, + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + child: state is AuthLoading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : const Text( + AuthTexts.submit, + style: TextStyle(fontSize: 16), + ), + ); + }, + ), + const SizedBox(height: 16), + TextButton( + onPressed: () {}, + child: const Text(AuthTexts.register), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/src/app/features/auth/presentation/texts/auth_texts.dart b/app/lib/src/app/features/auth/presentation/texts/auth_texts.dart new file mode 100644 index 0000000..98b458e --- /dev/null +++ b/app/lib/src/app/features/auth/presentation/texts/auth_texts.dart @@ -0,0 +1,10 @@ +class AuthTexts { + static const String title = 'Entrar'; + static const String email = 'E-mail'; + static const String password = 'Senha'; + static const String submit = 'Entrar'; + static const String success = 'Você entrou.'; + static const String register = 'Primeira vez aqui? Criar conta'; + static const String showPassword = 'Mostrar senha'; + static const String hidePassword = 'Esconder senha'; +} diff --git a/app/lib/src/app/features/base/presentation/bloc/base_bloc.dart b/app/lib/src/app/features/base/presentation/bloc/base_bloc.dart new file mode 100644 index 0000000..a52b90f --- /dev/null +++ b/app/lib/src/app/features/base/presentation/bloc/base_bloc.dart @@ -0,0 +1,13 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:equatable/equatable.dart'; + +part 'base_event.dart'; +part 'base_state.dart'; + +class BaseBloc extends Bloc { + BaseBloc() : super(BaseInitial()) { + on((event, emit) { + // TODO: implement event handler + }); + } +} diff --git a/app/lib/src/app/features/base/presentation/bloc/base_event.dart b/app/lib/src/app/features/base/presentation/bloc/base_event.dart new file mode 100644 index 0000000..f60c357 --- /dev/null +++ b/app/lib/src/app/features/base/presentation/bloc/base_event.dart @@ -0,0 +1,8 @@ +part of 'base_bloc.dart'; + +abstract class BaseEvent extends Equatable { + const BaseEvent(); + + @override + List get props => []; +} diff --git a/app/lib/src/app/features/base/presentation/bloc/base_state.dart b/app/lib/src/app/features/base/presentation/bloc/base_state.dart new file mode 100644 index 0000000..6f36464 --- /dev/null +++ b/app/lib/src/app/features/base/presentation/bloc/base_state.dart @@ -0,0 +1,9 @@ +part of 'base_bloc.dart'; + +abstract class BaseState extends Equatable { + const BaseState(); + + @override + List get props => []; +} +class BaseInitial extends BaseState {} diff --git a/app/lib/src/app/features/base/presentation/pages/base_page.dart b/app/lib/src/app/features/base/presentation/pages/base_page.dart new file mode 100644 index 0000000..d83dbfa --- /dev/null +++ b/app/lib/src/app/features/base/presentation/pages/base_page.dart @@ -0,0 +1,33 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:go_router/go_router.dart'; +import 'package:phpeste_app/src/app/features/base/presentation/texts/base_texts.dart'; + +class BasePage extends StatelessWidget { + const BasePage({super.key, required this.shell}); + + final StatefulNavigationShell shell; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: shell, + bottomNavigationBar: BottomNavigationBar( + currentIndex: shell.currentIndex, + onTap: shell.goBranch, + showUnselectedLabels: true, + items: const [ + BottomNavigationBarItem( + backgroundColor: Colors.white, + icon: Icon(Icons.home_outlined), + label: BaseTexts.home, + ), + BottomNavigationBarItem( + icon: Icon(Icons.person), + backgroundColor: Colors.white, + label: BaseTexts.profile, + ), + ], + ), + ); + } +} diff --git a/app/lib/src/app/features/base/presentation/texts/base_texts.dart b/app/lib/src/app/features/base/presentation/texts/base_texts.dart new file mode 100644 index 0000000..9c7d414 --- /dev/null +++ b/app/lib/src/app/features/base/presentation/texts/base_texts.dart @@ -0,0 +1,4 @@ +class BaseTexts { + static const String home = 'Início'; + static const String profile = 'Perfil'; +} diff --git a/app/lib/src/app/features/home/presentation/bloc/home_bloc.dart b/app/lib/src/app/features/home/presentation/bloc/home_bloc.dart new file mode 100644 index 0000000..2e506fc --- /dev/null +++ b/app/lib/src/app/features/home/presentation/bloc/home_bloc.dart @@ -0,0 +1,13 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:equatable/equatable.dart'; + +part 'home_event.dart'; +part 'home_state.dart'; + +class HomeBloc extends Bloc { + HomeBloc() : super(HomeInitial()) { + on((event, emit) { + // TODO: implement event handler + }); + } +} diff --git a/app/lib/src/app/features/home/presentation/bloc/home_event.dart b/app/lib/src/app/features/home/presentation/bloc/home_event.dart new file mode 100644 index 0000000..9d94475 --- /dev/null +++ b/app/lib/src/app/features/home/presentation/bloc/home_event.dart @@ -0,0 +1,8 @@ +part of 'home_bloc.dart'; + +abstract class HomeEvent extends Equatable { + const HomeEvent(); + + @override + List get props => []; +} diff --git a/app/lib/src/app/features/home/presentation/bloc/home_state.dart b/app/lib/src/app/features/home/presentation/bloc/home_state.dart new file mode 100644 index 0000000..7b760dc --- /dev/null +++ b/app/lib/src/app/features/home/presentation/bloc/home_state.dart @@ -0,0 +1,9 @@ +part of 'home_bloc.dart'; + +abstract class HomeState extends Equatable { + const HomeState(); + + @override + List get props => []; +} +class HomeInitial extends HomeState {} diff --git a/app/lib/src/app/features/home/presentation/pages/home_page.dart b/app/lib/src/app/features/home/presentation/pages/home_page.dart new file mode 100644 index 0000000..f068d0e --- /dev/null +++ b/app/lib/src/app/features/home/presentation/pages/home_page.dart @@ -0,0 +1,31 @@ +import 'package:phpeste_app/src/app/features/home/presentation/texts/home_texts.dart'; +import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; +import 'package:material_ui/material_ui.dart'; + +class HomePage extends StatelessWidget { + const HomePage({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text(HomeTexts.title), + centerTitle: true, + actions: [ + IconButton( + onPressed: () async { + final sessionService = injector(); + await sessionService.removeToken(); + }, + tooltip: HomeTexts.logout, + icon: const Icon(Icons.logout_sharp), + ), + ], + ), + body: const Center( + child: Text(HomeTexts.body), + ), + ); + } +} diff --git a/app/lib/src/app/features/home/presentation/texts/home_texts.dart b/app/lib/src/app/features/home/presentation/texts/home_texts.dart new file mode 100644 index 0000000..c4bba72 --- /dev/null +++ b/app/lib/src/app/features/home/presentation/texts/home_texts.dart @@ -0,0 +1,5 @@ +class HomeTexts { + static const String title = 'Início'; + static const String body = 'PHPeste'; + static const String logout = 'Sair'; +} diff --git a/app/lib/src/core/DI/dependency_injector.dart b/app/lib/src/core/DI/dependency_injector.dart new file mode 100644 index 0000000..137f44d --- /dev/null +++ b/app/lib/src/core/DI/dependency_injector.dart @@ -0,0 +1,60 @@ +import 'package:phpeste_app/src/app/features/auth/data/datasources/auth_remote_datasource.dart'; +import 'package:phpeste_app/src/app/features/auth/data/repositories/auth_repository_impl.dart'; +import 'package:phpeste_app/src/app/features/auth/data/repositories/auth_repository_mock.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/repositories/auth_repository_interface.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/usecases/login_usecase.dart'; +import 'package:phpeste_app/src/app/features/auth/infrastructure/auth_interceptor.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/bloc/auth_bloc.dart'; +import 'package:phpeste_app/src/core/cache/shared_preferences/shared_preferences_impl.dart'; +import 'package:phpeste_app/src/core/client_http/dio/rest_client_dio_impl.dart'; +import 'package:phpeste_app/src/core/client_http/logger/client_interceptor_logger_impl.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; +import 'package:get_it/get_it.dart'; +import 'package:logger/logger.dart'; + +final injector = GetIt.instance; + +void setupDependencyInjector({bool loggerApi = false, bool useMocks = true, Logger? logger}) { + injector.registerLazySingleton(() => logger ?? Logger()); + + injector.registerFactory(() { + final instance = RestClientDioImpl( + dio: DioFactory.dio(), + ); + + instance.addInterceptors(AuthInterceptor( + sessionService: injector(), + )); + + if (loggerApi) { + instance.addInterceptors(ClientInterceptorLoggerImpl(logger: injector())); + } + + return instance; + }); + + injector.registerLazySingleton(() { + return SessionService( + cache: SharedPreferencesImpl(), + ); + }); + + injector.registerLazySingleton(() { + return AuthRemoteDatasource( + restClient: injector(), + ); + }); + + if (useMocks) { + injector.registerLazySingleton(() => AuthRepositoryMock()); + } else { + injector.registerLazySingleton(() => AuthRepositoryImpl(authRemoteDatasource: injector())); + } + + injector.registerLazySingleton(() => AuthBloc( + loginUsecase: LoginUsecase( + authRepository: injector(), + sessionService: injector(), + ), + )); +} diff --git a/app/lib/src/core/cache/cache.dart b/app/lib/src/core/cache/cache.dart new file mode 100644 index 0000000..5ce75f4 --- /dev/null +++ b/app/lib/src/core/cache/cache.dart @@ -0,0 +1,3 @@ +export 'cache_exception.dart'; +export 'cache_interface.dart'; +export 'cache_params.dart'; diff --git a/app/lib/src/core/cache/cache_exception.dart b/app/lib/src/core/cache/cache_exception.dart new file mode 100644 index 0000000..ee9864a --- /dev/null +++ b/app/lib/src/core/cache/cache_exception.dart @@ -0,0 +1,7 @@ +import 'package:phpeste_app/src/core/errors/errors.dart'; + +class CacheException extends BaseException { + const CacheException({ + required super.message, + }); +} diff --git a/app/lib/src/core/cache/cache_interface.dart b/app/lib/src/core/cache/cache_interface.dart new file mode 100644 index 0000000..cd174c5 --- /dev/null +++ b/app/lib/src/core/cache/cache_interface.dart @@ -0,0 +1,8 @@ +import 'package:phpeste_app/src/core/cache/cache_params.dart'; + +abstract class ICache { + Future setData({required CacheParams params}); + Future getData(String key); + Future removeData(String key); + Future clean(); +} diff --git a/app/lib/src/core/cache/cache_params.dart b/app/lib/src/core/cache/cache_params.dart new file mode 100644 index 0000000..178d462 --- /dev/null +++ b/app/lib/src/core/cache/cache_params.dart @@ -0,0 +1,9 @@ +class CacheParams { + final String key; + final dynamic value; + + CacheParams({ + required this.key, + required this.value, + }); +} diff --git a/app/lib/src/core/cache/shared_preferences/shared_preferences_impl.dart b/app/lib/src/core/cache/shared_preferences/shared_preferences_impl.dart new file mode 100644 index 0000000..53db1e3 --- /dev/null +++ b/app/lib/src/core/cache/shared_preferences/shared_preferences_impl.dart @@ -0,0 +1,49 @@ +import 'dart:convert'; + +import 'package:phpeste_app/src/core/cache/cache.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class SharedPreferencesImpl implements ICache { + @override + Future getData(String key) async { + final prefs = await SharedPreferences.getInstance(); + final result = prefs.get(key); + + try { + return jsonDecode(result as String); + } catch (e) { + return result; + } + } + + @override + Future setData({required CacheParams params}) async { + final prefs = await SharedPreferences.getInstance(); + switch (params.value.runtimeType.toString()) { + case 'String': + return await prefs.setString(params.key, params.value); + case 'int': + return await prefs.setInt(params.key, params.value); + case 'bool': + return await prefs.setBool(params.key, params.value); + case 'double': + return await prefs.setDouble(params.key, params.value); + case 'List': + return await prefs.setStringList(params.key, params.value); + default: + return await prefs.setString(params.key, jsonEncode(params.value)); + } + } + + @override + Future removeData(String key) async { + final prefs = await SharedPreferences.getInstance(); + return await prefs.remove(key); + } + + @override + Future clean() async { + final prefs = await SharedPreferences.getInstance(); + return await prefs.clear(); + } +} diff --git a/app/lib/src/core/client_http/app_response.dart b/app/lib/src/core/client_http/app_response.dart new file mode 100644 index 0000000..f2ad416 --- /dev/null +++ b/app/lib/src/core/client_http/app_response.dart @@ -0,0 +1,78 @@ +import 'package:equatable/equatable.dart'; + +class AppResponse extends Equatable { + final bool success; + + final String message; + + final T? data; + + final int statusCode; + + final String statusMessage; + + const AppResponse._({ + required this.success, + required this.message, + required this.statusCode, + required this.statusMessage, + this.data, + }); + + factory AppResponse({ + required bool success, + required String message, + int? statusCode, + String? statusMessage, + T? data, + }) => + AppResponse._( + success: success, + message: message, + statusCode: statusCode ?? 200, + statusMessage: + statusMessage ?? "A requisição foi concluída com sucesso", + data: data, + ); + factory AppResponse.fromJson( + Map json, T Function(Object? json) fromJsonT) { + return AppResponse( + success: json['success'] as bool, + message: json['message'] as String, + statusCode: json['statusCode'] ?? 200, + statusMessage: + json['statusMessage'] ?? "A requisição foi concluída com sucesso", + data: fromJsonT(json['data']), + ); + } + + Map toJson(Object? Function(T? value) toJsonT) { + return { + 'success': success, + 'message': message, + 'statusCode': statusCode, + 'statusMessage': statusMessage, + 'data': toJsonT(data as T), + }; + } + + Map fromJsonT(Object? json) { + return json as Map; + } + + Object toJsonT(Map value) { + return value; + } + + @override + List get props { + return [ + success, + message, + data ?? "", + ]; + } + + @override + bool get stringify => true; +} diff --git a/app/lib/src/core/client_http/client_http.dart b/app/lib/src/core/client_http/client_http.dart new file mode 100644 index 0000000..5bd2f59 --- /dev/null +++ b/app/lib/src/core/client_http/client_http.dart @@ -0,0 +1,6 @@ +export 'client_interceptor_interface.dart'; +export 'rest_client_exception.dart'; +export 'rest_client_http_message.dart'; +export 'rest_client_interface.dart'; +export 'rest_client_request.dart'; +export 'rest_client_response.dart'; diff --git a/app/lib/src/core/client_http/client_interceptor_interface.dart b/app/lib/src/core/client_http/client_interceptor_interface.dart new file mode 100644 index 0000000..0326543 --- /dev/null +++ b/app/lib/src/core/client_http/client_interceptor_interface.dart @@ -0,0 +1,9 @@ +import 'dart:async'; + +import 'package:phpeste_app/src/core/client_http/client_http.dart'; + +abstract interface class IClientInterceptor { + FutureOr onResponse(RestClientResponse response); + FutureOr onRequest(RestClientRequest request); + FutureOr onError(RestClientException error); +} diff --git a/app/lib/src/core/client_http/dio/client_interceptor_dio_impl.dart b/app/lib/src/core/client_http/dio/client_interceptor_dio_impl.dart new file mode 100644 index 0000000..de87f85 --- /dev/null +++ b/app/lib/src/core/client_http/dio/client_interceptor_dio_impl.dart @@ -0,0 +1,49 @@ +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/client_http/dio/dio_adapter.dart'; +import 'package:dio/dio.dart'; + +class ClientInterceptorDioImpl implements Interceptor { + final IClientInterceptor interceptor; + + ClientInterceptorDioImpl({required this.interceptor}); + + @override + void onError(DioException err, ErrorInterceptorHandler handler) async { + final restClientHttp = DioAdapter.toClientException(err); + final message = await interceptor.onError(restClientHttp); + + if (message is RestClientException) { + handler.next(DioAdapter.toDioException(message)); + } else if (message is RestClientResponse) { + handler.resolve(DioAdapter.toResponse(message)); + } + } + + @override + void onRequest(RequestOptions options, RequestInterceptorHandler handler) async { + final restRequest = DioAdapter.toClientRequest(options); + final message = await interceptor.onRequest(restRequest); + + //log('onRequest: $message'); + + if (message is RestClientException) { + handler.reject(DioAdapter.toDioException(message)); + } else if (message is RestClientRequest) { + handler.next(DioAdapter.toRequestOptions(message)); + } else if (message is RestClientResponse) { + handler.resolve(DioAdapter.toResponse(message)); + } + } + + @override + void onResponse(Response response, ResponseInterceptorHandler handler) async { + final restResponse = DioAdapter.toClientResponse(response); + final message = await interceptor.onResponse(restResponse); + + if (message is RestClientException) { + handler.reject(DioAdapter.toDioException(message)); + } else if (message is RestClientResponse) { + handler.next(DioAdapter.toResponse(message)); + } + } +} diff --git a/app/lib/src/core/client_http/dio/dio_adapter.dart b/app/lib/src/core/client_http/dio/dio_adapter.dart new file mode 100644 index 0000000..3676163 --- /dev/null +++ b/app/lib/src/core/client_http/dio/dio_adapter.dart @@ -0,0 +1,71 @@ +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:dio/dio.dart'; + +class DioAdapter { + static RestClientException toClientException(DioException dioException) { + return RestClientException( + error: dioException.error, + message: dioException.message ?? '', + data: dioException.response?.data ?? {}, + response: dioException.response == null ? null : toClientResponse(dioException.response!), + statusCode: dioException.response?.statusCode, + ); + } + + static DioException toDioException(RestClientException restClientException) { + return DioException( + requestOptions: RequestOptions(), + error: restClientException.error, + message: restClientException.message, + response: restClientException.response == null ? null : toResponse(restClientException.response!), + ); + } + + static RestClientRequest toClientRequest(RequestOptions request) { + return RestClientRequest( + path: request.path, + method: request.method, + headers: request.headers, + queryParameters: request.queryParameters, + data: request.data, + baseUrl: request.baseUrl, + ); + } + + static RequestOptions toRequestOptions(RestClientRequest restClientRequest) { + return RequestOptions( + path: restClientRequest.path, + data: restClientRequest.data, + method: restClientRequest.method, + queryParameters: restClientRequest.queryParameters, + headers: restClientRequest.headers, + baseUrl: restClientRequest.baseUrl, + ); + } + + static RestClientResponse toClientResponse(Response response) { + return RestClientResponse( + request: toClientRequest(response.requestOptions), + message: response.statusMessage, + data: response.data, + statusCode: response.statusCode, + ); + } + + static Response toResponse(RestClientResponse restClientResponse) { + final headers = restClientResponse.request.headers ?? {}; + final dioHeaders = >{}; + + for (var key in headers.keys) { + dioHeaders[key] = [headers[key]]; + } + + return Response( + requestOptions: toRequestOptions(restClientResponse.request), + data: restClientResponse.data, + headers: Headers.fromMap(dioHeaders), + statusCode: restClientResponse.statusCode, + statusMessage: restClientResponse.message, + ); + } +} diff --git a/app/lib/src/core/client_http/dio/rest_client_dio_impl.dart b/app/lib/src/core/client_http/dio/rest_client_dio_impl.dart new file mode 100644 index 0000000..6ac60e3 --- /dev/null +++ b/app/lib/src/core/client_http/dio/rest_client_dio_impl.dart @@ -0,0 +1,150 @@ +import 'dart:developer'; + +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/client_http/dio/client_interceptor_dio_impl.dart'; +import 'package:phpeste_app/src/core/client_http/dio/dio_adapter.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_multipart.dart'; +import 'package:dio/dio.dart'; + +class DioFactory { + static Dio dio() { + final baseOptions = BaseOptions( + connectTimeout: const Duration(milliseconds: 15000), + receiveTimeout: const Duration(milliseconds: 15000), + validateStatus: (status) { + return status != null && status < 500; + }, + ); + return Dio(baseOptions); + } +} + +class RestClientDioImpl implements IRestClient { + final Dio _dio; + + final Map _interceptors = {}; + + RestClientDioImpl({required Dio dio}) : _dio = dio; + + @override + void addInterceptors(IClientInterceptor interceptor) { + _interceptors[interceptor] = ClientInterceptorDioImpl(interceptor: interceptor); + _dio.interceptors.add(_interceptors[interceptor]!); + } + + @override + void removeInterceptors(IClientInterceptor interceptor) { + _dio.interceptors.remove(_interceptors[interceptor]); + } + + @override + Future upload(RestClientMultipart multipart) async { + final formData = FormData.fromMap({ + multipart.fileKey: MultipartFile.fromBytes( + multipart.fileBytes ?? [], + filename: multipart.fileName, + ), + }); + + final baseOptions = BaseOptions( + connectTimeout: const Duration(milliseconds: 15000), + receiveTimeout: const Duration(milliseconds: 15000), + validateStatus: (status) { + return status != null && status < 500; + }, + ); + + Dio dio = Dio(baseOptions); + final response = await dio.put( + multipart.path, + data: formData, + ); + + return DioAdapter.toClientResponse(response); + } + + @override + Future delete(RestClientRequest request) async { + try { + final response = await _dio.delete( + request.path, + data: request.data, + queryParameters: request.queryParameters, + options: Options( + headers: request.headers, + ), + ); + return DioAdapter.toClientResponse(response); + } on DioException catch (e) { + throw DioAdapter.toClientException(e); + } + } + + @override + Future get(RestClientRequest request) async { + try { + final response = await _dio.get( + request.path, + queryParameters: request.queryParameters, + options: Options( + headers: request.headers, + ), + ); + return DioAdapter.toClientResponse(response); + } on DioException catch (e) { + throw DioAdapter.toClientException(e); + } + } + + @override + Future patch(RestClientRequest request) async { + try { + final response = await _dio.patch( + request.path, + data: request.data, + queryParameters: request.queryParameters, + options: Options( + headers: request.headers, + ), + ); + return DioAdapter.toClientResponse(response); + } on DioException catch (e) { + throw DioAdapter.toClientException(e); + } + } + + @override + Future post(RestClientRequest request) async { + try { + final response = await _dio.post( + request.path, + data: request.data, + queryParameters: request.queryParameters, + options: Options( + headers: request.headers, + ), + ); + return DioAdapter.toClientResponse(response); + } on DioException catch (e) { + log(e.message ?? 'DioException', name: 'RestClientDioImpl', error: e); + throw DioAdapter.toClientException(e); + } + } + + @override + Future put(RestClientRequest request) async { + try { + final response = await _dio.put( + request.path, + data: request.data, + queryParameters: request.queryParameters, + options: Options( + headers: request.headers, + ), + ); + return DioAdapter.toClientResponse(response); + } on DioException catch (e) { + throw DioAdapter.toClientException(e); + } + } +} diff --git a/app/lib/src/core/client_http/logger/client_interceptor_logger_impl.dart b/app/lib/src/core/client_http/logger/client_interceptor_logger_impl.dart new file mode 100644 index 0000000..d47f7de --- /dev/null +++ b/app/lib/src/core/client_http/logger/client_interceptor_logger_impl.dart @@ -0,0 +1,92 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:logger/logger.dart'; + +import '../client_http.dart'; + +const JsonEncoder _encoder = JsonEncoder.withIndent(' '); + +/// Loga request/response/erro de toda chamada HTTP através do [Logger] +/// compartilhado da DI (em vez de `dart:developer`'s `log()`) para que esses +/// logs também cheguem ao `get_logs` do Marionette MCP quando um agente +/// estiver conectado — ver `lib/main.dart`. +class ClientInterceptorLoggerImpl implements IClientInterceptor { + ClientInterceptorLoggerImpl({required Logger logger}) : _logger = logger; + + final Logger _logger; + + @override + FutureOr onError(RestClientException err) { + final loggerString = [ + '\n🛑 [ERROR] ${err.statusCode}', + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', + if (err.response != null) + '🔹 Request: ${err.response?.request.method.toUpperCase()} ${_formatUrl(err.response!.request)}', + if (err.response != null && + err.response!.request.queryParameters!.isNotEmpty) + '🔹 Query: ${prettyJson(err.response!.request.queryParameters!)}', + if (err.response != null && err.response!.request.headers!.isNotEmpty) + '🔹 Headers: ${prettyJson(err.response!.request.headers!)}', + '🔹 Response Status Code: ${err.response?.statusCode}', + if (err.message.isNotEmpty) '🔹 Message Error: ${err.message}', + if (err.response != null && err.response!.message!.isNotEmpty) + '🔹 Response Message: ${err.response!.message}', + if (err.response?.data != null) + '🔹 Response Data: ${prettyJson(err.response?.data)}', + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', + ].join('\n'); + + _logger.e(loggerString); + return err; + } + + @override + FutureOr onRequest(RestClientRequest request) { + final loggerString = [ + '\n📤 [REQUEST]', + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', + '🔹 ${request.method.toUpperCase()} ${_formatUrl(request)}', + if (request.queryParameters!.isNotEmpty) + '🔹 Query: ${prettyJson(request.queryParameters!)}', + if (request.headers!.isNotEmpty) + '🔹 Headers: ${prettyJson(request.headers!)}', + if (request.data != null) '🔹 Body: ${prettyJson(request.data)}', + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', + ].join('\n'); + + _logger.i(loggerString); + return request; + } + + @override + FutureOr onResponse(RestClientResponse response) { + final loggerString = [ + '\n📥 [RESPONSE] Status ${response.statusCode}', + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', + '🔹 ${response.request.method.toUpperCase()} ${_formatUrl(response.request)}', + '🔹 Status Code: ${response.statusCode}', + if (response.data != null) '🔹 Body: ${prettyJson(response.data)}', + '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', + ].join('\n'); + + _logger.i(loggerString); + return response; + } + + Object? prettyJson(Object? data) { + try { + return _encoder.convert(data); + } catch (_) { + return data; + } + } + + String _formatUrl(RestClientRequest request) { + String baseUrl = request.baseUrl; + if (baseUrl.endsWith('/')) { + baseUrl = baseUrl.substring(0, baseUrl.length - 1); + } + return '$baseUrl${request.path}'; + } +} diff --git a/app/lib/src/core/client_http/rest_client_exception.dart b/app/lib/src/core/client_http/rest_client_exception.dart new file mode 100644 index 0000000..b6916f4 --- /dev/null +++ b/app/lib/src/core/client_http/rest_client_exception.dart @@ -0,0 +1,16 @@ +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/errors/errors.dart'; + +class RestClientException extends BaseException implements RestClientHttpMessage { + dynamic error; + RestClientResponse? response; + + RestClientException({ + required super.message, + super.statusCode, + super.data, + required this.error, + this.response, + super.stackTracing, + }); +} diff --git a/app/lib/src/core/client_http/rest_client_http_message.dart b/app/lib/src/core/client_http/rest_client_http_message.dart new file mode 100644 index 0000000..f858657 --- /dev/null +++ b/app/lib/src/core/client_http/rest_client_http_message.dart @@ -0,0 +1 @@ +abstract class RestClientHttpMessage {} diff --git a/app/lib/src/core/client_http/rest_client_interface.dart b/app/lib/src/core/client_http/rest_client_interface.dart new file mode 100644 index 0000000..87962ef --- /dev/null +++ b/app/lib/src/core/client_http/rest_client_interface.dart @@ -0,0 +1,20 @@ +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_multipart.dart'; + +abstract interface class IRestClient { + Future post(RestClientRequest request); + + Future get(RestClientRequest request); + + Future put(RestClientRequest request); + + Future delete(RestClientRequest request); + + Future patch(RestClientRequest request); + + Future upload(RestClientMultipart multipart); + + void addInterceptors(IClientInterceptor interceptor); + + void removeInterceptors(IClientInterceptor interceptor); +} diff --git a/app/lib/src/core/client_http/rest_client_multipart.dart b/app/lib/src/core/client_http/rest_client_multipart.dart new file mode 100644 index 0000000..1040dd7 --- /dev/null +++ b/app/lib/src/core/client_http/rest_client_multipart.dart @@ -0,0 +1,13 @@ +class RestClientMultipart { + final String fileKey; + final String fileName; + final String path; + final List? fileBytes; + + RestClientMultipart({ + required this.fileKey, + required this.fileName, + required this.path, + required this.fileBytes, + }); +} diff --git a/app/lib/src/core/client_http/rest_client_request.dart b/app/lib/src/core/client_http/rest_client_request.dart new file mode 100644 index 0000000..bad701e --- /dev/null +++ b/app/lib/src/core/client_http/rest_client_request.dart @@ -0,0 +1,35 @@ +import 'package:phpeste_app/src/core/client_http/client_http.dart'; + +class RestClientRequest implements RestClientHttpMessage { + final String path; + final dynamic data; + final String method; + final String baseUrl; + final Map? queryParameters; + final Map? headers; + + RestClientRequest({ + required this.path, + this.data, + this.queryParameters, + this.headers, + this.method = 'GET', + this.baseUrl = '', + }); + + RestClientRequest copyWith({ + String? path, + dynamic data, + String? method, + Map? queryParameters, + Map? headers, + }) { + return RestClientRequest( + path: path ?? this.path, + data: data ?? this.data, + method: method ?? this.method, + queryParameters: queryParameters ?? this.queryParameters, + headers: headers ?? this.headers, + ); + } +} diff --git a/app/lib/src/core/client_http/rest_client_response.dart b/app/lib/src/core/client_http/rest_client_response.dart new file mode 100644 index 0000000..d5699ae --- /dev/null +++ b/app/lib/src/core/client_http/rest_client_response.dart @@ -0,0 +1,15 @@ +import 'package:phpeste_app/src/core/client_http/client_http.dart'; + +class RestClientResponse implements RestClientHttpMessage { + dynamic data; + int? statusCode; + String? message; + RestClientRequest request; + + RestClientResponse({ + this.data, + this.statusCode, + this.message, + required this.request, + }); +} diff --git a/app/lib/src/core/config/app_config.dart b/app/lib/src/core/config/app_config.dart new file mode 100644 index 0000000..aeba0a0 --- /dev/null +++ b/app/lib/src/core/config/app_config.dart @@ -0,0 +1,8 @@ +class AppConfig { + static const String flavor = String.fromEnvironment('FLAVOR', defaultValue: 'dev'); + static const String apiUrl = String.fromEnvironment('API_URL', defaultValue: 'http://localhost:8000/api/v1'); + static const bool useMocks = bool.fromEnvironment('USE_MOCKS'); + static const bool logApi = bool.fromEnvironment('LOG_API'); + + static bool get isProduction => flavor == 'prod'; +} diff --git a/app/lib/src/core/errors/base_exception.dart b/app/lib/src/core/errors/base_exception.dart new file mode 100644 index 0000000..feb8f10 --- /dev/null +++ b/app/lib/src/core/errors/base_exception.dart @@ -0,0 +1,13 @@ +abstract class BaseException implements Exception { + const BaseException({ + required this.message, + this.data, + this.statusCode, + this.stackTracing, + }); + + final dynamic data; + final String message; + final int? statusCode; + final dynamic stackTracing; +} diff --git a/app/lib/src/core/errors/credentials_validation_exception.dart b/app/lib/src/core/errors/credentials_validation_exception.dart new file mode 100644 index 0000000..f0e2a3f --- /dev/null +++ b/app/lib/src/core/errors/credentials_validation_exception.dart @@ -0,0 +1,5 @@ +import 'base_exception.dart'; + +class CredentialsValidationException extends BaseException { + CredentialsValidationException({required super.message}); +} diff --git a/app/lib/src/core/errors/default_exception.dart b/app/lib/src/core/errors/default_exception.dart new file mode 100644 index 0000000..dfc50b0 --- /dev/null +++ b/app/lib/src/core/errors/default_exception.dart @@ -0,0 +1,10 @@ +import 'base_exception.dart'; + +class DefaultException extends BaseException { + const DefaultException({ + required super.message, + super.data, + super.statusCode, + super.stackTracing, + }); +} diff --git a/app/lib/src/core/errors/errors.dart b/app/lib/src/core/errors/errors.dart new file mode 100644 index 0000000..0fcf971 --- /dev/null +++ b/app/lib/src/core/errors/errors.dart @@ -0,0 +1,4 @@ +export 'base_exception.dart'; +export 'default_exception.dart'; +export 'not_found_exception.dart'; +export 'server_exception.dart'; diff --git a/app/lib/src/core/errors/not_found_exception.dart b/app/lib/src/core/errors/not_found_exception.dart new file mode 100644 index 0000000..fe47caa --- /dev/null +++ b/app/lib/src/core/errors/not_found_exception.dart @@ -0,0 +1,8 @@ +import 'package:phpeste_app/src/core/errors/errors.dart'; + +class NotFoundException extends BaseException { + NotFoundException({ + required super.message, + super.statusCode = 404, + }); +} diff --git a/app/lib/src/core/errors/server_exception.dart b/app/lib/src/core/errors/server_exception.dart new file mode 100644 index 0000000..e489f3a --- /dev/null +++ b/app/lib/src/core/errors/server_exception.dart @@ -0,0 +1,11 @@ +import 'package:phpeste_app/src/core/errors/errors.dart'; + +class ServerException extends BaseException { + final String error; + + ServerException({ + required super.message, + required this.error, + super.stackTracing, + }); +} diff --git a/app/lib/src/core/errors/unauthorized_exception.dart b/app/lib/src/core/errors/unauthorized_exception.dart new file mode 100644 index 0000000..009b927 --- /dev/null +++ b/app/lib/src/core/errors/unauthorized_exception.dart @@ -0,0 +1,7 @@ +import 'package:phpeste_app/src/core/errors/base_exception.dart'; + +class UnauthorizedException extends BaseException { + UnauthorizedException({ + required super.message, + }); +} diff --git a/app/lib/src/core/extensions/lucid_validator_extensions.dart b/app/lib/src/core/extensions/lucid_validator_extensions.dart new file mode 100644 index 0000000..cbf06e6 --- /dev/null +++ b/app/lib/src/core/extensions/lucid_validator_extensions.dart @@ -0,0 +1,27 @@ +import 'package:phpeste_app/src/core/errors/credentials_validation_exception.dart'; +import 'package:lucid_validation/lucid_validation.dart'; +import 'package:result_dart/result_dart.dart'; + +extension LucidValidatorExtensions on LucidValidator { + AsyncResult validateResult(T object) async { + final result = validate(object); + if (result.isValid) { + return Success(object); + } + + return Failure( + CredentialsValidationException(message: result.exceptions.first.message), + ); + } +} + +extension CustomValidPasswordValidator on SimpleValidationBuilder { + SimpleValidationBuilder customValidPassword() { + return notEmpty(message: 'O campo senha é obrigatório') + .minLength(8, message: 'A senha deve ter no mínimo 8 caracteres') + .mustHaveLowercase(message: 'A senha deve ter no mínimo uma letra minúscula') + .mustHaveUppercase(message: 'A senha deve ter no mínimo uma letra maiúscula') + .mustHaveNumber(message: 'A senha deve ter no mínimo um número') + .mustHaveSpecialCharacter(message: 'A senha deve ter no mínimo um caractere especial'); + } +} diff --git a/app/lib/src/core/interfaces/usecase_interface.dart b/app/lib/src/core/interfaces/usecase_interface.dart new file mode 100644 index 0000000..968ced0 --- /dev/null +++ b/app/lib/src/core/interfaces/usecase_interface.dart @@ -0,0 +1,18 @@ +import 'package:result_dart/result_dart.dart'; + +/// `UseCase` é uma classe abstrata que define uma interface para um caso de uso. +/// Ela é genérica, o que significa que pode trabalhar com qualquer tipo de objeto (`Output` e `Params`). +abstract interface class UseCase { + /// O método `call` é uma operação assíncrona que recebe um parâmetro do tipo `Params` + /// e retorna um objeto `Future>`. + /// + /// `Future` é uma maneira de Dart lidar com operações assíncronas. Ele representa um valor potencial + /// ou erro que estará disponível em algum momento no futuro. + /// + /// `Either` é um tipo que pode conter um valor de dois tipos possíveis. Neste caso, `Failure` ou `Output`. + /// É comumente usado em programação funcional para lidar com operações que podem falhar. + /// Aqui, `Failure` representa um erro, enquanto `Output` seria o tipo de resultado esperado se a operação for bem-sucedida. + AsyncResult call(Params params); +} + +class NoParams {} diff --git a/app/lib/src/core/services/session_service.dart b/app/lib/src/core/services/session_service.dart new file mode 100644 index 0000000..626fcec --- /dev/null +++ b/app/lib/src/core/services/session_service.dart @@ -0,0 +1,38 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/cache/cache.dart'; + +class SessionService { + static const String _tokenKey = 'token'; + + final ICache _cache; + + final ValueNotifier signedIn = ValueNotifier(false); + + SessionService({required ICache cache}) : _cache = cache; + + Future restore() async { + signedIn.value = await getToken() != null; + } + + Future saveSession(String value) async { + final saved = await _cache.setData(params: CacheParams(key: _tokenKey, value: value)); + signedIn.value = saved; + return saved; + } + + Future getToken() async { + final response = await _cache.getData(_tokenKey); + + if (response == null || response is! String || response.isEmpty) { + return null; + } + + return response; + } + + Future removeToken() async { + final removed = await _cache.removeData(_tokenKey); + signedIn.value = false; + return removed; + } +} diff --git a/app/lib/src/core/utils/endpoints.dart b/app/lib/src/core/utils/endpoints.dart new file mode 100644 index 0000000..537f354 --- /dev/null +++ b/app/lib/src/core/utils/endpoints.dart @@ -0,0 +1,7 @@ +import 'package:phpeste_app/src/core/config/app_config.dart'; + +class Endpoints { + static const String baseUrl = AppConfig.apiUrl; + static const String login = '$baseUrl/auth/login'; + static const String register = '$baseUrl/auth/register'; +} diff --git a/app/lib/src/core/utils/loading_start.dart b/app/lib/src/core/utils/loading_start.dart new file mode 100644 index 0000000..35fd6c5 --- /dev/null +++ b/app/lib/src/core/utils/loading_start.dart @@ -0,0 +1,57 @@ +import 'package:material_ui/material_ui.dart'; + +class LoadinStart extends StatefulWidget { + const LoadinStart({ + super.key, + required this.onInit, + required this.child, + this.onDispose, + this.delayInitDuration, + }); + + final Function onInit; + final Widget child; + final Function? onDispose; + + final int? delayInitDuration; + + @override + State createState() => _LoadinStartState(); +} + +class _LoadinStartState extends State { + bool _isInit = false; + late BuildContext buildContext; + + @override + void didChangeDependencies() { + _initialize(); + super.didChangeDependencies(); + } + + _initialize() async { + if (!_isInit) { + final duration = widget.delayInitDuration ?? 200; + if (duration > 0) { + await Future.delayed(Duration(milliseconds: duration)); + } + if (!mounted) return; + widget.onInit(); + buildContext = context; + _isInit = true; + } + } + + @override + void dispose() { + if (widget.onDispose != null) { + widget.onDispose!(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return widget.child; + } +} diff --git a/app/lib/src/core/utils/shimmer.dart b/app/lib/src/core/utils/shimmer.dart new file mode 100644 index 0000000..50ec447 --- /dev/null +++ b/app/lib/src/core/utils/shimmer.dart @@ -0,0 +1,113 @@ +import 'package:material_ui/material_ui.dart'; + +class BannerPlaceholder extends StatelessWidget { + const BannerPlaceholder({super.key}); + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + height: 200.0, + margin: const EdgeInsets.all(16.0), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12.0), + color: Colors.white, + ), + ); + } +} + +class TitlePlaceholder extends StatelessWidget { + final double width; + + const TitlePlaceholder({ + super.key, + required this.width, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: width, + height: 12.0, + color: Colors.white, + ), + const SizedBox(height: 8.0), + Container( + width: width, + height: 12.0, + color: Colors.white, + ), + ], + ), + ); + } +} + +enum ContentLineType { + twoLines, + threeLines, +} + +class ContentPlaceholder extends StatelessWidget { + final ContentLineType lineType; + + const ContentPlaceholder({ + super.key, + required this.lineType, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Row( + mainAxisSize: MainAxisSize.max, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + width: 96.0, + height: 72.0, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12.0), + color: Colors.white, + ), + ), + const SizedBox(width: 12.0), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: double.infinity, + height: 10.0, + color: Colors.white, + margin: const EdgeInsets.only(bottom: 8.0), + ), + if (lineType == ContentLineType.threeLines) + Container( + width: double.infinity, + height: 10.0, + color: Colors.white, + margin: const EdgeInsets.only(bottom: 8.0), + ), + Container( + width: 100.0, + height: 10.0, + color: Colors.white, + ) + ], + ), + ) + ], + ), + ); + } +} diff --git a/app/lib/src/core/utils/show_snack_bar.dart b/app/lib/src/core/utils/show_snack_bar.dart new file mode 100644 index 0000000..e9b41be --- /dev/null +++ b/app/lib/src/core/utils/show_snack_bar.dart @@ -0,0 +1,39 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:gap/gap.dart'; + +void showMessageSnackBar( + BuildContext context, + String message, { + Color? color = Colors.grey, + Color? textColor = Colors.white, + required IconData icon, + required Color iconColor, +}) { + final theme = Theme.of(context); + final snackbar = SnackBar( + backgroundColor: color, + content: Row( + children: [ + Icon( + icon, + color: iconColor, + ), + const Gap(8), + Expanded( + child: Text( + message, + style: theme.textTheme.bodySmall!.copyWith( + color: textColor, + ), + ), + ) + ], + ), + behavior: SnackBarBehavior.floating, + ); + + final scaffoldMsg = ScaffoldMessenger.of(context); + scaffoldMsg + ..hideCurrentSnackBar() + ..showSnackBar(snackbar); +} diff --git a/app/mason-lock.json b/app/mason-lock.json new file mode 100644 index 0000000..4c367c4 --- /dev/null +++ b/app/mason-lock.json @@ -0,0 +1 @@ +{"bricks":{"feature":{"path":"/Users/redrodrigo/Documents/code/RED/base_clean_arch_bloc/bricks/feature"}}} \ No newline at end of file diff --git a/app/mason.yaml b/app/mason.yaml new file mode 100644 index 0000000..19c7499 --- /dev/null +++ b/app/mason.yaml @@ -0,0 +1,3 @@ +bricks: + feature: + path: bricks/feature diff --git a/app/pubspec.lock b/app/pubspec.lock new file mode 100644 index 0000000..183e48e --- /dev/null +++ b/app/pubspec.lock @@ -0,0 +1,791 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "1c5591cc6f252d5f440d96ab87c03e43504be552a3fa49d7cb7563f04c51fb0a" + url: "https://pub.dev" + source: hosted + version: "111.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "6c39bd5486a310e56217bed7cb1691377959f31be4227e41750107db7e6dd55c" + url: "https://pub.dev" + source: hosted + version: "14.7.0" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + bloc: + dependency: transitive + description: + name: bloc + sha256: "52c10575f4445c61dd9e0cafcc6356fdd827c4c64dd7945ef3c4105f6b6ac189" + url: "https://pub.dev" + source: hosted + version: "9.0.0" + bloc_test: + dependency: "direct dev" + description: + name: bloc_test + sha256: "1dd549e58be35148bc22a9135962106aa29334bc1e3f285994946a1057b29d7b" + url: "https://pub.dev" + source: hosted + version: "10.0.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" + url: "https://pub.dev" + source: hosted + version: "1.15.0" + crypto: + dependency: transitive + description: + name: crypto + sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + url: "https://pub.dev" + source: hosted + version: "3.0.6" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + cupertino_ui: + dependency: transitive + description: + name: cupertino_ui + sha256: c3eaf7f5bdfee36deb0b14a4cbf7602f1b6b8d8b8576b81f38fc08c25881c94c + url: "https://pub.dev" + source: hosted + version: "1.1.7" + diff_match_patch: + dependency: transitive + description: + name: diff_match_patch + sha256: "2efc9e6e8f449d0abe15be240e2c2a3bcd977c8d126cfd70598aee60af35c0a4" + url: "https://pub.dev" + source: hosted + version: "0.4.1" + dio: + dependency: "direct main" + description: + name: dio + sha256: "253a18bbd4851fecba42f7343a1df3a9a4c1d31a2c1b37e221086b4fa8c8dbc9" + url: "https://pub.dev" + source: hosted + version: "5.8.0+1" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "7586e476d70caecaf1686d21eee7247ea43ef5c345eab9e0cc3583ff13378d78" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + equatable: + dependency: "direct main" + description: + name: equatable + sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + url: "https://pub.dev" + source: hosted + version: "2.0.7" + fake_async: + dependency: "direct dev" + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_bloc: + dependency: "direct main" + description: + name: flutter_bloc + sha256: cf51747952201a455a1c840f8171d273be009b932c75093020f9af64f2123e38 + url: "https://pub.dev" + source: hosted + version: "9.1.1" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + flutter_localizations: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + gap: + dependency: "direct main" + description: + name: gap + sha256: f19387d4e32f849394758b91377f9153a1b41d79513ef7668c088c77dbc6955d + url: "https://pub.dev" + source: hosted + version: "3.0.1" + get_it: + dependency: "direct main" + description: + name: get_it + sha256: f126a3e286b7f5b578bf436d5592968706c4c1de28a228b870ce375d9f743103 + url: "https://pub.dev" + source: hosted + version: "8.0.3" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: "0b1e06223bee260dee31a171fb1153e306907563a0b0225e8c1733211911429a" + url: "https://pub.dev" + source: hosted + version: "15.1.2" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + intl: + dependency: "direct main" + description: + name: intl + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" + url: "https://pub.dev" + source: hosted + version: "0.20.3" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + listen: + dependency: transitive + description: + name: listen + sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + logger: + dependency: "direct main" + description: + name: logger + sha256: "2621da01aabaf223f8f961e751f2c943dbb374dc3559b982f200ccedadaa6999" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + lucid_validation: + dependency: "direct main" + description: + name: lucid_validation + sha256: "45cb775d8c694483b63c7aeb939aaa53f052b257f0e857c91224b9404860ce14" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + marionette_flutter: + dependency: "direct main" + description: + name: marionette_flutter + sha256: "9bf6aa531157edeb3d94f7c4972367240a1d704bbe9f4ac558ef1a125c4d1a6d" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + marionette_logger: + dependency: "direct main" + description: + name: marionette_logger + sha256: "6220aaafa8de2bfb23070c2dff2ceafabfe8e43a46259b750db8c10090f702cb" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + material_ui: + dependency: "direct main" + description: + name: material_ui + sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab + url: "https://pub.dev" + source: hosted + version: "1.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.dev" + source: hosted + version: "1.19.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + mocktail: + dependency: "direct dev" + description: + name: mocktail + sha256: "890df3f9688106f25755f26b1c60589a92b3ab91a22b8b224947ad041bf172d8" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + provider: + dependency: transitive + description: + name: provider + sha256: "4abbd070a04e9ddc287673bf5a030c7ca8b685ff70218720abab8b092f53dd84" + url: "https://pub.dev" + source: hosted + version: "6.1.5" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + result_dart: + dependency: "direct main" + description: + name: result_dart + sha256: "0666b21fbdf697b3bdd9986348a380aa204b3ebe7c146d8e4cdaa7ce735e6054" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + url: "https://pub.dev" + source: hosted + version: "2.5.3" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "9f9f3d372d4304723e6136663bb291c0b93f5e4c8a4a6314347f481a33bda2b1" + url: "https://pub.dev" + source: hosted + version: "2.4.7" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + shimmer: + dependency: "direct main" + description: + name: shimmer + sha256: "5f88c883a22e9f9f299e5ba0e4f7e6054857224976a5d9f839d4ebdc94a14ac9" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812" + url: "https://pub.dev" + source: hosted + version: "0.10.13" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test: + dependency: transitive + description: + name: test + sha256: de5d145b0afff7921e5e788a880f52d7e5f3ae24068a202f6fd3b58e4ba26323 + url: "https://pub.dev" + source: hosted + version: "1.32.0" + test_api: + dependency: transitive + description: + name: test_api + sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" + url: "https://pub.dev" + source: hosted + version: "0.7.14" + test_core: + dependency: transitive + description: + name: test_core + sha256: "80f3fb49087454e07e7e07c67578cfdd156c8c3a5227d8b3f47c7b2d019c2e93" + url: "https://pub.dev" + source: hosted + version: "0.6.20" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc + url: "https://pub.dev" + source: hosted + version: "2.4.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d" + url: "https://pub.dev" + source: hosted + version: "14.2.5" + watcher: + dependency: transitive + description: + name: watcher + sha256: "0b7fd4a0bbc4b92641dbf20adfd7e3fd1398fe17102d94b674234563e110088a" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml new file mode 100644 index 0000000..14384d5 --- /dev/null +++ b/app/pubspec.yaml @@ -0,0 +1,110 @@ +name: phpeste_app +description: "App do PHPeste para participante, palestrante e equipe de check-in." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.10.0 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + get_it: ^8.0.3 + go_router: ^15.1.2 + flutter_bloc: ^9.1.1 + equatable: ^2.0.7 + dio: ^5.8.0+1 + shared_preferences: ^2.5.3 + gap: ^3.0.1 + intl: ^0.20.2 + shimmer: ^3.0.0 + logger: ^2.6.0 + result_dart: ^2.1.1 + lucid_validation: ^1.3.1 + marionette_flutter: ^0.6.0 + marionette_logger: ^0.6.0 + material_ui: 1.11.1 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^4.0.0 + + # Testing dependencies + bloc_test: ^10.0.0 + mocktail: ^1.0.4 + fake_async: ^1.3.1 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/app/test/unit/auth/data/datasources/auth_remote_datasource_test.dart b/app/test/unit/auth/data/datasources/auth_remote_datasource_test.dart new file mode 100644 index 0000000..307b0ef --- /dev/null +++ b/app/test/unit/auth/data/datasources/auth_remote_datasource_test.dart @@ -0,0 +1,221 @@ +import 'package:phpeste_app/src/app/features/auth/data/datasources/auth_remote_datasource.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_exception.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_interface.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_request.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_response.dart'; +import 'package:phpeste_app/src/core/utils/endpoints.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class MockRestClient extends Mock implements IRestClient {} + +void main() { + group('AuthRemoteDatasource', () { + late AuthRemoteDatasource datasource; + late MockRestClient mockRestClient; + + setUp(() { + mockRestClient = MockRestClient(); + datasource = AuthRemoteDatasource(restClient: mockRestClient); + }); + + setUpAll(() { + registerFallbackValue(RestClientRequest(path: '')); + }); + + group('login', () { + final loginParams = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + final expectedResponseData = { + 'user': { + 'id': '1', + 'email': 'test@example.com', + 'name': 'Test User', + }, + 'token': 'test_token_123', + }; + + final successResponse = RestClientResponse( + data: expectedResponseData, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/test'), + ); + + test('should call rest client with correct parameters', () async { + // Arrange + when(() => mockRestClient.post(any())).thenAnswer((_) async => successResponse); + + // Act + await datasource.login(loginParams); + + // Assert + final captured = verify(() => mockRestClient.post(captureAny())).captured; + final request = captured.first as RestClientRequest; + + expect(request.path, equals(Endpoints.login)); + expect(request.data, equals(loginParams.toJson())); + }); + + test('should return RestClientResponse when login succeeds', () async { + // Arrange + when(() => mockRestClient.post(any())).thenAnswer((_) async => successResponse); + + // Act + final result = await datasource.login(loginParams); + + // Assert + expect(result, isA()); + expect(result.data, equals(expectedResponseData)); + expect(result.statusCode, equals(200)); + }); + + test('should throw RestClientException when login fails', () async { + // Arrange + final exception = RestClientException( + message: 'Login failed', + statusCode: 401, + error: 'Unauthorized', + ); + + when(() => mockRestClient.post(any())).thenThrow(exception); + + // Act & Assert + expect( + () => datasource.login(loginParams), + throwsA(isA()), + ); + }); + + test('should handle different HTTP status codes', () async { + // Arrange + final responses = [ + RestClientResponse(data: {}, statusCode: 200, message: 'OK', request: RestClientRequest(path: '/test')), + RestClientResponse(data: {}, statusCode: 201, message: 'Created', request: RestClientRequest(path: '/test')), + ]; + + for (final response in responses) { + when(() => mockRestClient.post(any())).thenAnswer((_) async => response); + + // Act + final result = await datasource.login(loginParams); + + // Assert + expect(result.statusCode, equals(response.statusCode)); + } + }); + + test('should handle network errors', () async { + // Arrange + when(() => mockRestClient.post(any())).thenThrow(RestClientException( + message: 'Network error', + statusCode: 0, + error: 'Network error', + )); + + // Act & Assert + expect( + () => datasource.login(loginParams), + throwsA( + predicate((e) => e is RestClientException && e.message == 'Network error' && e.statusCode == 0), + ), + ); + }); + + test('should handle server errors', () async { + // Arrange + when(() => mockRestClient.post(any())).thenThrow(RestClientException( + message: 'Internal server error', + statusCode: 500, + error: 'Internal server error', + )); + + // Act & Assert + expect( + () => datasource.login(loginParams), + throwsA( + predicate((e) => e is RestClientException && e.statusCode == 500), + ), + ); + }); + + test('should serialize login params correctly', () async { + // Arrange + when(() => mockRestClient.post(any())).thenAnswer((_) async => successResponse); + + final params = LoginParams( + email: 'user@test.com', + password: 'secure_password', + ); + + // Act + await datasource.login(params); + + // Assert + final captured = verify(() => mockRestClient.post(captureAny())).captured; + final request = captured.first as RestClientRequest; + + expect( + request.data, + equals({ + 'email': 'user@test.com', + 'password': 'secure_password', + })); + }); + + test('should verify rest client is called exactly once', () async { + // Arrange + when(() => mockRestClient.post(any())).thenAnswer((_) async => successResponse); + + // Act + await datasource.login(loginParams); + + // Assert + verify(() => mockRestClient.post(any())).called(1); + verifyNoMoreInteractions(mockRestClient); + }); + + test('should handle empty response data', () async { + // Arrange + final emptyResponse = RestClientResponse( + data: {}, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/test'), + ); + + when(() => mockRestClient.post(any())).thenAnswer((_) async => emptyResponse); + + // Act + final result = await datasource.login(loginParams); + + // Assert + expect(result.data, equals({})); + expect(result.statusCode, equals(200)); + }); + + test('should handle null response data', () async { + // Arrange + final nullResponse = RestClientResponse( + data: null, + statusCode: 204, + message: 'No Content', + request: RestClientRequest(path: '/test'), + ); + + when(() => mockRestClient.post(any())).thenAnswer((_) async => nullResponse); + + // Act + final result = await datasource.login(loginParams); + + // Assert + expect(result.data, isNull); + expect(result.statusCode, equals(204)); + }); + }); + }); +} diff --git a/app/test/unit/auth/data/models/auth_response_model_test.dart b/app/test/unit/auth/data/models/auth_response_model_test.dart new file mode 100644 index 0000000..68da9bd --- /dev/null +++ b/app/test/unit/auth/data/models/auth_response_model_test.dart @@ -0,0 +1,176 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/src/app/features/auth/data/models/auth_response_model.dart'; +import 'package:phpeste_app/src/app/features/auth/data/models/user_model.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; + +void main() { + group('AuthResponseModel', () { + const userModel = UserModel( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + const authResponseModel = AuthResponseModel( + user: userModel, + token: 'test_token_123', + ); + + const authResponseMap = { + 'user': { + 'id': '1', + 'email': 'test@example.com', + 'name': 'Test User', + }, + 'token': 'test_token_123', + }; + + test('should be a subclass of AuthResponseEntity', () { + expect(authResponseModel, isA()); + }); + + test('should create AuthResponseModel with correct properties', () { + expect(authResponseModel.user, equals(userModel)); + expect(authResponseModel.token, equals('test_token_123')); + }); + + group('fromMap', () { + test('should return a valid AuthResponseModel from Map', () { + final result = AuthResponseModel.fromMap(authResponseMap); + + expect(result, isA()); + expect(result.user.id, equals('1')); + expect(result.user.email, equals('test@example.com')); + expect(result.user.name, equals('Test User')); + expect(result.token, equals('test_token_123')); + }); + + test('should throw exception when map is invalid', () { + const invalidMap = { + 'token': 'test_token_123', + // missing user + }; + + expect( + () => AuthResponseModel.fromMap(invalidMap), + throwsA(isA()), + ); + }); + + test('should throw exception when user data is invalid', () { + const invalidMap = { + 'user': { + 'id': '1', + // missing email and name + }, + 'token': 'test_token_123', + }; + + expect( + () => AuthResponseModel.fromMap(invalidMap), + throwsA(isA()), + ); + }); + + test('should throw exception when token is missing', () { + const invalidMap = { + 'user': { + 'id': '1', + 'email': 'test@example.com', + 'name': 'Test User', + }, + // missing token + }; + + expect( + () => AuthResponseModel.fromMap(invalidMap), + throwsA(isA()), + ); + }); + + test('should throw exception when field types are wrong', () { + const invalidMap = { + 'user': 'invalid_user_data', // should be Map + 'token': 'test_token_123', + }; + + expect( + () => AuthResponseModel.fromMap(invalidMap), + throwsA(isA()), + ); + }); + }); + + group('error handling', () { + test('should include stack trace in exception message', () { + const invalidMap = { + 'user': 'invalid_user_data', + 'token': 'test_token_123', + }; + + try { + AuthResponseModel.fromMap(invalidMap); + fail('Should have thrown an exception'); + } catch (e) { + expect(e.toString(), contains('Error parsing AuthResponseModel')); + expect(e.toString(), contains('Stack trace')); + } + }); + + test('should handle null values gracefully', () { + const invalidMap = { + 'user': null, + 'token': 'test_token_123', + }; + + expect( + () => AuthResponseModel.fromMap(invalidMap), + throwsA(isA()), + ); + }); + + test('should handle empty map', () { + const emptyMap = {}; + + expect( + () => AuthResponseModel.fromMap(emptyMap), + throwsA(isA()), + ); + }); + }); + + group('data integrity', () { + test('should preserve user data correctly', () { + final result = AuthResponseModel.fromMap(authResponseMap); + + expect(result.user, isA()); + expect(result.user.id, equals(userModel.id)); + expect(result.user.email, equals(userModel.email)); + expect(result.user.name, equals(userModel.name)); + }); + + test('should preserve token correctly', () { + final result = AuthResponseModel.fromMap(authResponseMap); + + expect(result.token, equals('test_token_123')); + expect(result.token, isA()); + }); + + test('should handle different token formats', () { + final mapWithLongToken = { + 'user': { + 'id': '1', + 'email': 'test@example.com', + 'name': 'Test User', + }, + 'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + }; + + final result = AuthResponseModel.fromMap(mapWithLongToken); + + expect(result.token, isA()); + expect(result.token.length, greaterThan(10)); + }); + }); + }); +} \ No newline at end of file diff --git a/app/test/unit/auth/data/models/user_model_test.dart b/app/test/unit/auth/data/models/user_model_test.dart new file mode 100644 index 0000000..9024f14 --- /dev/null +++ b/app/test/unit/auth/data/models/user_model_test.dart @@ -0,0 +1,158 @@ +import 'dart:convert'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/src/app/features/auth/data/models/user_model.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; + +void main() { + group('UserModel', () { + const userModel = UserModel( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + const userMap = { + 'id': '1', + 'email': 'test@example.com', + 'name': 'Test User', + }; + + const userJson = '{"id":"1","email":"test@example.com","name":"Test User"}'; + + test('should be a subclass of UserEntity', () { + expect(userModel, isA()); + }); + + test('should create UserModel with correct properties', () { + expect(userModel.id, equals('1')); + expect(userModel.email, equals('test@example.com')); + expect(userModel.name, equals('Test User')); + }); + + group('fromMap', () { + test('should return a valid UserModel from Map', () { + final result = UserModel.fromMap(userMap); + + expect(result, isA()); + expect(result.id, equals('1')); + expect(result.email, equals('test@example.com')); + expect(result.name, equals('Test User')); + }); + + test('should throw exception when map is invalid', () { + const invalidMap = { + 'id': '1', + // missing email and name + }; + + expect( + () => UserModel.fromMap(invalidMap), + throwsA(isA()), + ); + }); + + test('should throw exception when field types are wrong', () { + const invalidMap = { + 'id': 123, // should be String + 'email': 'test@example.com', + 'name': 'Test User', + }; + + expect( + () => UserModel.fromMap(invalidMap), + throwsA(isA()), + ); + }); + }); + + group('toMap', () { + test('should return a valid Map from UserModel', () { + final result = userModel.toMap(); + + expect(result, isA>()); + expect(result['id'], equals('1')); + expect(result['email'], equals('test@example.com')); + expect(result['name'], equals('Test User')); + }); + + test('should return Map with all required fields', () { + final result = userModel.toMap(); + + expect(result.containsKey('id'), isTrue); + expect(result.containsKey('email'), isTrue); + expect(result.containsKey('name'), isTrue); + }); + }); + + group('fromJson', () { + test('should return a valid UserModel from JSON string', () { + final result = UserModel.fromJson(userJson); + + expect(result, isA()); + expect(result.id, equals('1')); + expect(result.email, equals('test@example.com')); + expect(result.name, equals('Test User')); + }); + + test('should throw exception when JSON is invalid', () { + const invalidJson = '{"id":"1"}'; // missing required fields + + expect( + () => UserModel.fromJson(invalidJson), + throwsA(isA()), + ); + }); + + test('should throw exception when JSON format is wrong', () { + const invalidJson = 'invalid json string'; + + expect( + () => UserModel.fromJson(invalidJson), + throwsA(isA()), + ); + }); + }); + + group('toJson', () { + test('should return a valid JSON string from UserModel', () { + final result = userModel.toJson(); + + expect(result, isA()); + + final decoded = json.decode(result) as Map; + expect(decoded['id'], equals('1')); + expect(decoded['email'], equals('test@example.com')); + expect(decoded['name'], equals('Test User')); + }); + + test('should create JSON that can be parsed back to UserModel', () { + final jsonString = userModel.toJson(); + final parsedModel = UserModel.fromJson(jsonString); + + expect(parsedModel.id, equals(userModel.id)); + expect(parsedModel.email, equals(userModel.email)); + expect(parsedModel.name, equals(userModel.name)); + }); + }); + + group('serialization round trip', () { + test('should maintain data integrity through map serialization', () { + final map = userModel.toMap(); + final reconstructed = UserModel.fromMap(map); + + expect(reconstructed.id, equals(userModel.id)); + expect(reconstructed.email, equals(userModel.email)); + expect(reconstructed.name, equals(userModel.name)); + }); + + test('should maintain data integrity through JSON serialization', () { + final jsonString = userModel.toJson(); + final reconstructed = UserModel.fromJson(jsonString); + + expect(reconstructed.id, equals(userModel.id)); + expect(reconstructed.email, equals(userModel.email)); + expect(reconstructed.name, equals(userModel.name)); + }); + }); + }); +} \ No newline at end of file diff --git a/app/test/unit/auth/data/repositories/auth_repository_impl_test.dart b/app/test/unit/auth/data/repositories/auth_repository_impl_test.dart new file mode 100644 index 0000000..60fcd50 --- /dev/null +++ b/app/test/unit/auth/data/repositories/auth_repository_impl_test.dart @@ -0,0 +1,298 @@ +import 'package:phpeste_app/src/app/features/auth/data/datasources/auth_remote_datasource.dart'; +import 'package:phpeste_app/src/app/features/auth/data/repositories/auth_repository_impl.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_exception.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_request.dart'; +import 'package:phpeste_app/src/core/client_http/rest_client_response.dart'; +import 'package:phpeste_app/src/core/errors/default_exception.dart'; +import 'package:phpeste_app/src/core/errors/unauthorized_exception.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class MockAuthRemoteDatasource extends Mock implements AuthRemoteDatasource {} + +void main() { + group('AuthRepositoryImpl', () { + late AuthRepositoryImpl repository; + late MockAuthRemoteDatasource mockDatasource; + + setUpAll(() { + registerFallbackValue(LoginParams(email: '', password: '')); + }); + + setUp(() { + mockDatasource = MockAuthRemoteDatasource(); + repository = AuthRepositoryImpl(authRemoteDatasource: mockDatasource); + }); + + group('login', () { + final loginParams = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + final successResponseData = { + 'user': { + 'id': '1', + 'email': 'test@example.com', + 'name': 'Test User', + }, + 'token': 'test_token_123', + }; + + final successResponse = RestClientResponse( + data: successResponseData, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/test'), + ); + + test('should return Success with AuthResponseEntity when datasource succeeds', () async { + // Arrange + when(() => mockDatasource.login(loginParams)).thenAnswer((_) async => successResponse); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isSuccess(), isTrue); + + final authResponse = result.getOrNull()!; + expect(authResponse, isA()); + expect(authResponse.user.id, equals('1')); + expect(authResponse.user.email, equals('test@example.com')); + expect(authResponse.user.name, equals('Test User')); + expect(authResponse.token, equals('test_token_123')); + + verify(() => mockDatasource.login(loginParams)).called(1); + }); + + test('should return Failure with UnauthorizedException when status code is 401', () async { + // Arrange + final exception = RestClientException( + message: 'Invalid credentials', + statusCode: 401, + error: 'Unauthorized', + ); + + when(() => mockDatasource.login(loginParams)).thenThrow(exception); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + + final error = result.exceptionOrNull(); + expect(error, isA()); + final authError = error as UnauthorizedException; + expect(authError.message, equals('Invalid credentials')); + + verify(() => mockDatasource.login(loginParams)).called(1); + }); + + test('should return Failure with DefaultException for other HTTP errors', () async { + // Arrange + final exception = RestClientException( + message: 'Server error', + statusCode: 500, + error: 'Internal Server Error', + ); + + when(() => mockDatasource.login(loginParams)).thenThrow(exception); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + + final error = result.exceptionOrNull(); + expect(error, isA()); + final defaultError = error as DefaultException; + expect(defaultError.message, equals('Server error')); + + verify(() => mockDatasource.login(loginParams)).called(1); + }); + + test('should return Failure with DefaultException for generic exceptions', () async { + // Arrange + when(() => mockDatasource.login(loginParams)).thenThrow(Exception('Generic error')); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + + final error = result.exceptionOrNull(); + expect(error, isA()); + final defaultError = error as DefaultException; + expect(defaultError.message, contains('Erro inesperado')); + + verify(() => mockDatasource.login(loginParams)).called(1); + }); + + test('should handle different HTTP status codes correctly', () async { + final testCases = [ + { + 'statusCode': 400, + 'message': 'Bad request', + 'expectedType': DefaultException, + }, + { + 'statusCode': 404, + 'message': 'Not found', + 'expectedType': DefaultException, + }, + { + 'statusCode': 403, + 'message': 'Forbidden', + 'expectedType': DefaultException, + }, + ]; + + for (final testCase in testCases) { + // Arrange + final exception = RestClientException( + message: testCase['message'] as String, + statusCode: testCase['statusCode'] as int, + error: testCase['message'] as String, + ); + + when(() => mockDatasource.login(loginParams)).thenThrow(exception); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + final error = result.exceptionOrNull(); + expect(error, isA()); + final defaultError = error as DefaultException; + expect(defaultError.message, equals(testCase['message'])); + } + }); + + test('should handle malformed response data', () async { + // Arrange + final malformedResponse = RestClientResponse( + data: { + 'user': 'invalid_user_data', // should be Map + 'token': 'test_token_123', + }, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/test'), + ); + + when(() => mockDatasource.login(loginParams)).thenAnswer((_) async => malformedResponse); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + + final error = result.exceptionOrNull(); + expect(error, isA()); + final defaultError = error as DefaultException; + expect(defaultError.message, contains('Erro inesperado')); + }); + + test('should handle missing user data in response', () async { + // Arrange + final incompleteResponse = RestClientResponse( + data: { + 'token': 'test_token_123', + // missing user data + }, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/test'), + ); + + when(() => mockDatasource.login(loginParams)).thenAnswer((_) async => incompleteResponse); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + expect(result.exceptionOrNull(), isA()); + }); + + test('should handle missing token in response', () async { + // Arrange + final incompleteResponse = RestClientResponse( + data: { + 'user': { + 'id': '1', + 'email': 'test@example.com', + 'name': 'Test User', + }, + // missing token + }, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/test'), + ); + + when(() => mockDatasource.login(loginParams)).thenAnswer((_) async => incompleteResponse); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + expect(result.exceptionOrNull(), isA()); + }); + + test('should verify datasource is called with correct parameters', () async { + // Arrange + when(() => mockDatasource.login(any())).thenAnswer((_) async => successResponse); + + // Act + await repository.login(loginParams); + + // Assert + final captured = verify(() => mockDatasource.login(captureAny())).captured; + final capturedParams = captured.first as LoginParams; + expect(capturedParams.email, equals(loginParams.email)); + expect(capturedParams.password, equals(loginParams.password)); + }); + + test('should call datasource exactly once', () async { + // Arrange + when(() => mockDatasource.login(loginParams)).thenAnswer((_) async => successResponse); + + // Act + await repository.login(loginParams); + + // Assert + verify(() => mockDatasource.login(loginParams)).called(1); + verifyNoMoreInteractions(mockDatasource); + }); + + test('should handle null response data', () async { + // Arrange + final nullResponse = RestClientResponse( + data: null, + statusCode: 200, + message: 'OK', + request: RestClientRequest(path: '/test'), + ); + + when(() => mockDatasource.login(loginParams)).thenAnswer((_) async => nullResponse); + + // Act + final result = await repository.login(loginParams); + + // Assert + expect(result.isError(), isTrue); + expect(result.exceptionOrNull(), isA()); + }); + }); + }); +} diff --git a/app/test/unit/auth/domain/dtos/login_params_test.dart b/app/test/unit/auth/domain/dtos/login_params_test.dart new file mode 100644 index 0000000..c50613f --- /dev/null +++ b/app/test/unit/auth/domain/dtos/login_params_test.dart @@ -0,0 +1,94 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; + +void main() { + group('LoginParams', () { + test('should create LoginParams with correct properties', () { + final params = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + expect(params.email, equals('test@example.com')); + expect(params.password, equals('password123')); + }); + + test('should create empty LoginParams', () { + final params = LoginParams.empty(); + + expect(params.email, equals('')); + expect(params.password, equals('')); + }); + + test('should convert to JSON correctly', () { + final params = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + final json = params.toJson(); + + expect(json, isA>()); + expect(json['email'], equals('test@example.com')); + expect(json['password'], equals('password123')); + }); + + test('should set email correctly', () { + final params = LoginParams.empty(); + + params.setEmail('newemail@example.com'); + + expect(params.email, equals('newemail@example.com')); + }); + + test('should set password correctly', () { + final params = LoginParams.empty(); + + params.setPassword('newpassword'); + + expect(params.password, equals('newpassword')); + }); + + test('should be equal when properties are the same', () { + final params1 = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + final params2 = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + expect(params1.email, equals(params2.email)); + expect(params1.password, equals(params2.password)); + }); + + test('should not be equal when properties are different', () { + final params1 = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + final params2 = LoginParams( + email: 'different@example.com', + password: 'password123', + ); + + expect(params1.email, isNot(equals(params2.email))); + }); + + test('toString should return correct string representation', () { + final params = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + final result = params.toString(); + + expect(result, contains('LoginParams')); + expect(result, contains('email: test@example.com')); + expect(result, contains('password: password123')); + }); + }); +} \ No newline at end of file diff --git a/app/test/unit/auth/domain/entities/auth_response_entity_test.dart b/app/test/unit/auth/domain/entities/auth_response_entity_test.dart new file mode 100644 index 0000000..9cbd0d2 --- /dev/null +++ b/app/test/unit/auth/domain/entities/auth_response_entity_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; + +void main() { + group('AuthResponseEntity', () { + const user = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + test('should create AuthResponseEntity with correct properties', () { + const authResponse = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + expect(authResponse.user, equals(user)); + expect(authResponse.token, equals('test_token_123')); + }); + + test('should be equal when properties are the same', () { + const authResponse1 = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + const authResponse2 = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + expect(authResponse1, equals(authResponse2)); + expect(authResponse1.hashCode, equals(authResponse2.hashCode)); + }); + + test('should not be equal when properties are different', () { + const authResponse1 = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + const authResponse2 = AuthResponseEntity( + user: user, + token: 'different_token', + ); + + expect(authResponse1, isNot(equals(authResponse2))); + expect(authResponse1.hashCode, isNot(equals(authResponse2.hashCode))); + }); + + test('should not be equal when user is different', () { + const user2 = UserEntity( + id: '2', + email: 'test2@example.com', + name: 'Test User 2', + ); + + const authResponse1 = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + const authResponse2 = AuthResponseEntity( + user: user2, + token: 'test_token_123', + ); + + expect(authResponse1, isNot(equals(authResponse2))); + expect(authResponse1.hashCode, isNot(equals(authResponse2.hashCode))); + }); + + test('toString should return correct string representation', () { + const authResponse = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + final result = authResponse.toString(); + + expect(result, contains('AuthResponseEntity')); + expect(result, contains('user:')); + expect(result, contains('token: test_token_123')); + }); + }); +} \ No newline at end of file diff --git a/app/test/unit/auth/domain/entities/user_entity_test.dart b/app/test/unit/auth/domain/entities/user_entity_test.dart new file mode 100644 index 0000000..4ffba2f --- /dev/null +++ b/app/test/unit/auth/domain/entities/user_entity_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; + +void main() { + group('UserEntity', () { + test('should create UserEntity with correct properties', () { + const user = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + expect(user.id, equals('1')); + expect(user.email, equals('test@example.com')); + expect(user.name, equals('Test User')); + }); + + test('should be equal when properties are the same', () { + const user1 = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + const user2 = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + expect(user1, equals(user2)); + expect(user1.hashCode, equals(user2.hashCode)); + }); + + test('should not be equal when properties are different', () { + const user1 = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + const user2 = UserEntity( + id: '2', + email: 'test@example.com', + name: 'Test User', + ); + + expect(user1, isNot(equals(user2))); + expect(user1.hashCode, isNot(equals(user2.hashCode))); + }); + + test('toString should return correct string representation', () { + const user = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + final result = user.toString(); + + expect(result, contains('UserEntity')); + expect(result, contains('id: 1')); + expect(result, contains('email: test@example.com')); + expect(result, contains('name: Test User')); + }); + }); +} \ No newline at end of file diff --git a/app/test/unit/auth/domain/usecases/login_usecase_test.dart b/app/test/unit/auth/domain/usecases/login_usecase_test.dart new file mode 100644 index 0000000..614b7fa --- /dev/null +++ b/app/test/unit/auth/domain/usecases/login_usecase_test.dart @@ -0,0 +1,109 @@ +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/repositories/auth_repository_interface.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/usecases/login_usecase.dart'; +import 'package:phpeste_app/src/core/errors/default_exception.dart'; +import 'package:phpeste_app/src/core/errors/unauthorized_exception.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:result_dart/result_dart.dart'; + +class MockAuthRepository extends Mock implements IAuthRepository {} + +class MockSessionService extends Mock implements SessionService {} + +void main() { + group('LoginUsecase', () { + late LoginUsecase usecase; + late MockAuthRepository mockAuthRepository; + late MockSessionService mockSessionService; + + setUpAll(() { + registerFallbackValue(LoginParams.empty()); + }); + + setUp(() { + mockAuthRepository = MockAuthRepository(); + mockSessionService = MockSessionService(); + when(() => mockSessionService.saveSession(any())).thenAnswer((_) async => true); + usecase = LoginUsecase(authRepository: mockAuthRepository, sessionService: mockSessionService); + }); + + group('call', () { + final loginParams = LoginParams( + email: 'test@example.com', + password: 'password123', + ); + + const user = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + const authResponse = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + test('should return AuthResponseEntity when repository call succeeds', () async { + // Arrange + when(() => mockAuthRepository.login(loginParams)).thenAnswer((_) async => const Success(authResponse)); + + // Act + final result = await usecase.call(loginParams); + + // Assert + expect(result.isSuccess(), isTrue); + expect(result.getOrNull(), equals(authResponse)); + verify(() => mockAuthRepository.login(loginParams)).called(1); + }); + + test('should return Failure when repository call fails', () async { + // Arrange + const exception = DefaultException(message: 'Login failed'); + when(() => mockAuthRepository.login(loginParams)).thenAnswer((_) async => const Failure(exception)); + + // Act + final result = await usecase.call(loginParams); + + // Assert + expect(result.isError(), isTrue); + expect(result.exceptionOrNull(), equals(exception)); + verify(() => mockAuthRepository.login(loginParams)).called(1); + }); + + test('should return UnauthorizedException when credentials are invalid', () async { + // Arrange + final exception = UnauthorizedException(message: 'Invalid credentials'); + when(() => mockAuthRepository.login(loginParams)).thenAnswer((_) async => Failure(exception)); + + // Act + final result = await usecase.call(loginParams); + + // Assert + expect(result.isError(), isTrue); + expect(result.exceptionOrNull(), isA()); + //final exceptions = result.exceptionOrNull() as UnauthorizedException; + expect(exception.message, equals('Invalid credentials')); + verify(() => mockAuthRepository.login(loginParams)).called(1); + }); + + test('should call repository with correct parameters', () async { + // Arrange + when(() => mockAuthRepository.login(any())).thenAnswer((_) async => const Success(authResponse)); + + // Act + await usecase.call(loginParams); + + // Assert + final captured = verify(() => mockAuthRepository.login(captureAny())).captured; + final capturedParams = captured.first as LoginParams; + expect(capturedParams.email, equals(loginParams.email)); + expect(capturedParams.password, equals(loginParams.password)); + }); + }); + }); +} diff --git a/app/test/unit/auth/domain/validators/login_params_validators_test.dart b/app/test/unit/auth/domain/validators/login_params_validators_test.dart new file mode 100644 index 0000000..2ab24e6 --- /dev/null +++ b/app/test/unit/auth/domain/validators/login_params_validators_test.dart @@ -0,0 +1,228 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/validators/login_params_validators.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; + +void main() { + group('LoginParamsValidators', () { + late LoginParamsValidators validator; + + setUp(() { + validator = LoginParamsValidators(); + }); + + group('email validation', () { + test('should return valid when email is valid', () { + final params = LoginParams( + email: 'test@example.com', + password: 'Password123!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isTrue); + }); + + test('should return invalid when email is empty', () { + final params = LoginParams( + email: '', + password: 'Password123!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'email'), isTrue); + }); + + test('should return invalid when email format is invalid', () { + final params = LoginParams( + email: 'invalid-email', + password: 'Password123!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'email'), isTrue); + }); + + test('should validate email field individually', () { + final params = LoginParams( + email: 'test@example.com', + password: 'Password123!', + ); + + // byField returns a FormFieldValidator (the closure TextFormField calls + // with the current field value), not the validation result itself. + final result = validator.byField(params, 'email')(params.email); + + expect(result, isNull); // null means valid + }); + + test('should return error message for invalid email field', () { + final params = LoginParams( + email: 'invalid-email', + password: 'Password123!', + ); + + final result = validator.byField(params, 'email')(params.email); + + expect(result, isNotNull); + expect(result, contains('Email')); + }); + }); + + group('password validation', () { + test('should return valid when password meets all criteria', () { + final params = LoginParams( + email: 'test@example.com', + password: 'Password123!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isTrue); + }); + + test('should return invalid when password is empty', () { + final params = LoginParams( + email: 'test@example.com', + password: '', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'password'), isTrue); + }); + + test('should return invalid when password is too short', () { + final params = LoginParams( + email: 'test@example.com', + password: 'Pass1!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'password'), isTrue); + }); + + test('should return invalid when password lacks uppercase', () { + final params = LoginParams( + email: 'test@example.com', + password: 'password123!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'password'), isTrue); + }); + + test('should return invalid when password lacks lowercase', () { + final params = LoginParams( + email: 'test@example.com', + password: 'PASSWORD123!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'password'), isTrue); + }); + + test('should return invalid when password lacks number', () { + final params = LoginParams( + email: 'test@example.com', + password: 'Password!', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'password'), isTrue); + }); + + test('should return invalid when password lacks special character', () { + final params = LoginParams( + email: 'test@example.com', + password: 'Password123', + ); + + final result = validator.validate(params); + + expect(result.isValid, isFalse); + expect(result.exceptions.any((e) => e.key == 'password'), isTrue); + }); + + test('should validate password field individually', () { + final params = LoginParams( + email: 'test@example.com', + password: 'Password123!', + ); + + final result = validator.byField(params, 'password')(params.password); + + expect(result, isNull); // null means valid + }); + + test('should return error message for invalid password field', () { + final params = LoginParams( + email: 'test@example.com', + password: '123', + ); + + final result = validator.byField(params, 'password')(params.password); + + expect(result, isNotNull); + expect(result, contains('senha')); + }); + }); + + group('custom validation scenarios', () { + test('should accept various valid email formats', () { + // lucid_validation's validEmail() uses a simple RFC-lite regex + // (`^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$`) that does not allow "+" in + // the local part, so plus-tagged addresses are intentionally excluded here. + final validEmails = [ + 'test@example.com', + 'user.name@domain.co.uk', + 'user_tag@example.org', + 'test123@test-domain.com', + ]; + + for (final email in validEmails) { + final params = LoginParams( + email: email, + password: 'Password123!', + ); + + final result = validator.validate(params); + expect(result.isValid, isTrue, reason: 'Email $email should be valid'); + } + }); + + test('should reject various invalid email formats', () { + // Same regex limitation as above: it doesn't reject consecutive dots + // in the local part, so 'user..name@domain.com' is left out here. + final invalidEmails = [ + 'plainaddress', + '@domain.com', + 'user@', + 'user@domain', + ]; + + for (final email in invalidEmails) { + final params = LoginParams( + email: email, + password: 'Password123!', + ); + + final result = validator.validate(params); + expect(result.isValid, isFalse, reason: 'Email $email should be invalid'); + } + }); + }); + }); +} \ No newline at end of file diff --git a/app/test/unit/auth/presentation/bloc/auth_bloc_test.dart b/app/test/unit/auth/presentation/bloc/auth_bloc_test.dart new file mode 100644 index 0000000..38bd490 --- /dev/null +++ b/app/test/unit/auth/presentation/bloc/auth_bloc_test.dart @@ -0,0 +1,367 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:result_dart/result_dart.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/bloc/auth_bloc.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/usecases/login_usecase.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; +import 'package:phpeste_app/src/core/errors/default_exception.dart'; +import 'package:phpeste_app/src/core/errors/unauthorized_exception.dart'; +import 'package:phpeste_app/src/core/errors/credentials_validation_exception.dart'; + +class MockLoginUsecase extends Mock implements LoginUsecase {} + +void main() { + group('AuthBloc', () { + late AuthBloc authBloc; + late MockLoginUsecase mockLoginUsecase; + + setUpAll(() { + registerFallbackValue(LoginParams(email: '', password: '')); + }); + + setUp(() { + mockLoginUsecase = MockLoginUsecase(); + authBloc = AuthBloc(loginUsecase: mockLoginUsecase); + }); + + tearDown(() { + authBloc.close(); + }); + + test('initial state is AuthInitial', () { + expect(authBloc.state, equals(AuthInitial())); + }); + + group('AuthLoginRequested', () { + final loginParams = LoginParams( + email: 'test@example.com', + password: 'Password123!', + ); + + const user = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + + const authResponse = AuthResponseEntity( + user: user, + token: 'test_token_123', + ); + + blocTest( + 'emits [AuthLoading, AuthLoginSuccess] when login succeeds', + build: () { + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Success(authResponse)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + const AuthLoginSuccess(authResponse), + ], + verify: (_) { + verify(() => mockLoginUsecase.call(loginParams)).called(1); + }, + ); + + blocTest( + 'emits [AuthLoading, AuthLoginFailure] when login fails with DefaultException', + build: () { + const exception = DefaultException(message: 'Login failed'); + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Failure(exception)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + isA().having( + (state) => state.exception.message, + 'exception message', + equals('Login failed'), + ), + ], + verify: (_) { + verify(() => mockLoginUsecase.call(loginParams)).called(1); + }, + ); + + blocTest( + 'emits [AuthLoading, AuthLoginFailure] when login fails with UnauthorizedException', + build: () { + final exception = UnauthorizedException(message: 'Invalid credentials'); + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => Failure(exception)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + isA().having( + (state) => state.exception, + 'exception type', + isA(), + ), + ], + verify: (_) { + verify(() => mockLoginUsecase.call(loginParams)).called(1); + }, + ); + + blocTest( + 'emits [AuthLoading, AuthLoginFailure] when validation fails', + build: () { + final exception = CredentialsValidationException(message: 'Invalid email'); + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => Failure(exception)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + isA().having( + (state) => state.exception, + 'exception type', + isA(), + ), + ], + verify: (_) { + verify(() => mockLoginUsecase.call(loginParams)).called(1); + }, + ); + + blocTest( + 'calls usecase with correct parameters', + build: () { + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Success(authResponse)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + verify: (_) { + final captured = verify(() => mockLoginUsecase.call(captureAny())).captured; + final capturedParams = captured.first as LoginParams; + expect(capturedParams.email, equals(loginParams.email)); + expect(capturedParams.password, equals(loginParams.password)); + }, + ); + + blocTest( + 'handles multiple login requests correctly', + build: () { + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Success(authResponse)); + return authBloc; + }, + act: (bloc) async { + bloc.add(AuthLoginRequested(params: loginParams)); + await Future.delayed(const Duration(milliseconds: 100)); + bloc.add(AuthLoginRequested(params: loginParams)); + }, + expect: () => [ + AuthLoading(), + const AuthLoginSuccess(authResponse), + AuthLoading(), + const AuthLoginSuccess(authResponse), + ], + verify: (_) { + verify(() => mockLoginUsecase.call(loginParams)).called(2); + }, + ); + + group('validation integration', () { + blocTest( + 'emits failure when email is invalid', + build: () { + final exception = CredentialsValidationException(message: 'Email inválido'); + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => Failure(exception)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested( + params: LoginParams( + email: 'invalid-email', + password: 'Password123!', + ), + )), + expect: () => [ + AuthLoading(), + isA().having( + (state) => state.exception, + 'exception type', + isA(), + ), + ], + ); + + blocTest( + 'emits failure when password is invalid', + build: () { + final exception = CredentialsValidationException(message: 'Senha inválida'); + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => Failure(exception)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested( + params: LoginParams( + email: 'test@example.com', + password: '123', + ), + )), + expect: () => [ + AuthLoading(), + isA().having( + (state) => state.exception, + 'exception type', + isA(), + ), + ], + ); + }); + + group('state transitions', () { + blocTest( + 'transitions from AuthInitial to AuthLoading to AuthLoginSuccess', + build: () { + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Success(authResponse)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + const AuthLoginSuccess(authResponse), + ], + verify: (_) { + // Verify state transitions are correct + expect(authBloc.state, isA()); + }, + ); + + blocTest( + 'transitions from AuthLoginSuccess back to AuthLoading on new request', + build: () { + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Success(authResponse)); + return authBloc; + }, + seed: () => const AuthLoginSuccess(authResponse), + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + const AuthLoginSuccess(authResponse), + ], + ); + + blocTest( + 'transitions from AuthLoginFailure back to AuthLoading on new request', + build: () { + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Success(authResponse)); + return authBloc; + }, + seed: () => const AuthLoginFailure( + exception: DefaultException(message: 'Previous error'), + ), + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + const AuthLoginSuccess(authResponse), + ], + ); + }); + + group('edge cases', () { + blocTest( + 'handles empty email and password', + build: () { + final exception = CredentialsValidationException(message: 'Campos obrigatórios'); + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => Failure(exception)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested( + params: LoginParams(email: '', password: ''), + )), + expect: () => [ + AuthLoading(), + isA(), + ], + ); + + blocTest( + 'handles network timeout errors', + build: () { + const exception = DefaultException(message: 'Network timeout'); + when(() => mockLoginUsecase.call(any())) + .thenAnswer((_) async => const Failure(exception)); + return authBloc; + }, + act: (bloc) => bloc.add(AuthLoginRequested(params: loginParams)), + expect: () => [ + AuthLoading(), + isA().having( + (state) => state.exception.message, + 'exception message', + equals('Network timeout'), + ), + ], + ); + }); + }); + + group('AuthEvent props', () { + test('AuthLoginRequested should have correct props', () { + final params1 = LoginParams(email: 'test@example.com', password: 'password'); + final params2 = LoginParams(email: 'test@example.com', password: 'password'); + final params3 = LoginParams(email: 'different@example.com', password: 'password'); + + final event1 = AuthLoginRequested(params: params1); + final event2 = AuthLoginRequested(params: params2); + final event3 = AuthLoginRequested(params: params3); + + expect(event1.props, equals([params1])); + expect(event1.props, equals(event2.props)); + expect(event1.props, isNot(equals(event3.props))); + }); + }); + + group('AuthState props', () { + test('AuthLoginSuccess should have correct props', () { + const user = UserEntity(id: '1', email: 'test@example.com', name: 'Test'); + const authResponse1 = AuthResponseEntity(user: user, token: 'token1'); + const authResponse2 = AuthResponseEntity(user: user, token: 'token2'); + + const state1 = AuthLoginSuccess(authResponse1); + const state2 = AuthLoginSuccess(authResponse2); + + expect(state1.props, equals([authResponse1])); + expect(state1.props, isNot(equals(state2.props))); + }); + + test('AuthLoginFailure should have correct props', () { + const exception1 = DefaultException(message: 'Error 1'); + const exception2 = DefaultException(message: 'Error 2'); + + const state1 = AuthLoginFailure(exception: exception1); + const state2 = AuthLoginFailure(exception: exception2); + + expect(state1.props, equals([exception1])); + expect(state1.props, isNot(equals(state2.props))); + }); + + test('AuthInitial and AuthLoading should have empty props', () { + final initial = AuthInitial(); + final loading = AuthLoading(); + + expect(initial.props, equals([])); + expect(loading.props, equals([])); + }); + }); + }); +} \ No newline at end of file diff --git a/app/test/unit/core/routes_test.dart b/app/test/unit/core/routes_test.dart new file mode 100644 index 0000000..8e47417 --- /dev/null +++ b/app/test/unit/core/routes_test.dart @@ -0,0 +1,29 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/routes.dart'; + +void main() { + group('sessionRedirect', () { + test('sem sessão, rota privada vai para Entrar guardando o destino', () { + expect(sessionRedirect(signedIn: false, location: Uri.parse('/perfil')), '/entrar?de=%2Fperfil'); + expect(sessionRedirect(signedIn: false, location: Uri.parse('/inicio?aba=2')), '/entrar?de=%2Finicio%3Faba%3D2'); + }); + + test('sem sessão, Entrar não redireciona', () { + expect(sessionRedirect(signedIn: false, location: Uri.parse('/entrar')), isNull); + }); + + test('com sessão, Entrar volta para o destino guardado ou para o Início', () { + expect(sessionRedirect(signedIn: true, location: Uri.parse('/entrar?de=%2Fperfil')), '/perfil'); + expect(sessionRedirect(signedIn: true, location: Uri.parse('/entrar')), AppRoutes.home); + }); + + test('destino de fora do app é ignorado', () { + expect(sessionRedirect(signedIn: true, location: Uri.parse('/entrar?de=https://evil.dev')), AppRoutes.home); + expect(sessionRedirect(signedIn: true, location: Uri.parse('/entrar?de=//evil.dev')), AppRoutes.home); + }); + + test('com sessão, rota privada segue', () { + expect(sessionRedirect(signedIn: true, location: Uri.parse('/inicio')), isNull); + }); + }); +} diff --git a/app/test/unit/core/session_service_test.dart b/app/test/unit/core/session_service_test.dart new file mode 100644 index 0000000..e30a411 --- /dev/null +++ b/app/test/unit/core/session_service_test.dart @@ -0,0 +1,53 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/src/core/cache/cache.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; + +class MemoryCache implements ICache { + final Map data = {}; + + @override + Future clean() async { + data.clear(); + return true; + } + + @override + Future getData(String key) async => data[key]; + + @override + Future removeData(String key) async { + data.remove(key); + return true; + } + + @override + Future setData({required CacheParams params}) async { + data[params.key] = params.value; + return true; + } +} + +void main() { + group('SessionService', () { + test('restaura a sessão guardada e avisa quem observa', () async { + final cache = MemoryCache()..data['token'] = 'tok'; + final session = SessionService(cache: cache); + final changes = []; + session.signedIn.addListener(() => changes.add(session.signedIn.value)); + + await session.restore(); + await session.removeToken(); + await session.saveSession('novo'); + + expect(changes, [true, false, true]); + expect(await session.getToken(), 'novo'); + }); + + test('token vazio não conta como sessão', () async { + final session = SessionService(cache: MemoryCache()..data['token'] = ''); + await session.restore(); + expect(session.signedIn.value, isFalse); + expect(await session.getToken(), isNull); + }); + }); +} diff --git a/app/test/widget/app_widget_test.dart b/app/test/widget/app_widget_test.dart new file mode 100644 index 0000000..7b6db12 --- /dev/null +++ b/app/test/widget/app_widget_test.dart @@ -0,0 +1,25 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:phpeste_app/app_widget.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/texts/auth_texts.dart'; +import 'package:phpeste_app/src/app/features/home/presentation/texts/home_texts.dart'; +import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; +import 'package:phpeste_app/src/core/services/session_service.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + testWidgets('sem sessão abre em Entrar e, ao entrar, vai sozinho para o Início', (tester) async { + SharedPreferences.setMockInitialValues({}); + setupDependencyInjector(useMocks: true); + final session = injector(); + await session.restore(); + + await tester.pumpWidget(const AppWidget()); + await tester.pumpAndSettle(); + expect(find.text(AuthTexts.email), findsOneWidget); + + await tester.runAsync(() => session.saveSession('tok')); + await tester.pumpAndSettle(); + expect(find.text(HomeTexts.title), findsWidgets); + expect(find.text(AuthTexts.email), findsNothing); + }); +} diff --git a/app/test/widget/auth/login_page_test.dart b/app/test/widget/auth/login_page_test.dart new file mode 100644 index 0000000..0a80389 --- /dev/null +++ b/app/test/widget/auth/login_page_test.dart @@ -0,0 +1,534 @@ +import 'package:phpeste_app/src/app/features/auth/domain/entities/auth_response_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/entities/user_entity.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/dtos/login_params.dart'; +import 'package:phpeste_app/src/app/features/auth/domain/validators/login_params_validators.dart'; +import 'package:phpeste_app/src/app/features/auth/presentation/bloc/auth_bloc.dart'; +import 'package:phpeste_app/src/core/errors/default_exception.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:bloc_test/bloc_test.dart'; + +class MockAuthBloc extends MockBloc implements AuthBloc {} + +// Test-specific login page widget that doesn't use dependency injection +class TestLoginPage extends StatefulWidget { + final AuthBloc authBloc; + + const TestLoginPage({super.key, required this.authBloc}); + + @override + State createState() => _TestLoginPageState(); +} + +class _TestLoginPageState extends State { + final _formKey = GlobalKey(); + bool _obscurePassword = true; + LoginParams loginParams = LoginParams.empty(); + final LoginParamsValidators loginParamsValidator = LoginParamsValidators(); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Login'), + centerTitle: true, + ), + body: BlocListener( + listener: (context, state) { + if (state is AuthLoginSuccess) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Login realizado com sucesso!')), + ); + } + if (state is AuthLoginFailure) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(state.exception.message)), + ); + } + }, + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Form( + key: _formKey, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Icon( + Icons.person_outline, + size: 80, + color: Theme.of(context).primaryColor, + ), + const SizedBox(height: 32), + TextFormField( + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration( + labelText: 'Email', + prefixIcon: Icon(Icons.email_outlined), + border: OutlineInputBorder(), + ), + validator: loginParamsValidator.byField(loginParams, 'email'), + onChanged: loginParams.setEmail, + autovalidateMode: AutovalidateMode.onUserInteraction, + ), + const SizedBox(height: 16), + TextFormField( + obscureText: _obscurePassword, + decoration: InputDecoration( + labelText: 'Senha', + prefixIcon: const Icon(Icons.lock_outline), + suffixIcon: IconButton( + icon: Icon( + _obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined, + ), + onPressed: () { + setState(() { + _obscurePassword = !_obscurePassword; + }); + }, + ), + border: const OutlineInputBorder(), + ), + validator: loginParamsValidator.byField(loginParams, 'password'), + onChanged: loginParams.setPassword, + autovalidateMode: AutovalidateMode.onUserInteraction, + ), + const SizedBox(height: 24), + BlocBuilder( + builder: (context, state) { + return ElevatedButton( + onPressed: state is AuthLoading ? null : () { + widget.authBloc.add(AuthLoginRequested(params: loginParams)); + }, + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + child: state is AuthLoading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : const Text( + 'Entrar', + style: TextStyle(fontSize: 16), + ), + ); + }, + ), + const SizedBox(height: 16), + TextButton( + onPressed: () {}, + child: const Text('Não tem uma conta? Cadastre-se'), + ), + ], + ), + ), + ), + ), + ); + } +} + +void main() { + group('LoginPage Widget Tests', () { + late MockAuthBloc mockAuthBloc; + + setUp(() { + mockAuthBloc = MockAuthBloc(); + }); + + Widget createWidgetUnderTest() { + return MaterialApp( + home: BlocProvider.value( + value: mockAuthBloc, + child: TestLoginPage(authBloc: mockAuthBloc), + ), + ); + } + + group('UI Elements', () { + testWidgets('should display all required UI elements', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + expect(find.text('Login'), findsOneWidget); + expect(find.byIcon(Icons.person_outline), findsOneWidget); + expect(find.byType(TextFormField), findsNWidgets(2)); + expect(find.text('Email'), findsOneWidget); + expect(find.text('Senha'), findsOneWidget); + expect(find.text('Entrar'), findsOneWidget); + expect(find.text('Não tem uma conta? Cadastre-se'), findsOneWidget); + }); + + testWidgets('should display email field with correct label', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + final emailField = find.widgetWithText(TextFormField, 'Email'); + expect(emailField, findsOneWidget); + + // Verify email icon is present + expect(find.byIcon(Icons.email_outlined), findsOneWidget); + }); + + testWidgets('should display password field with visibility toggle', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + final passwordField = find.widgetWithText(TextFormField, 'Senha'); + expect(passwordField, findsOneWidget); + + // Verify lock icon and visibility toggle are present + expect(find.byIcon(Icons.lock_outline), findsOneWidget); + expect(find.byIcon(Icons.visibility_outlined), findsOneWidget); + }); + + testWidgets('should toggle password visibility when icon is tapped', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + await tester.pump(); // Let the widget settle + + // Find password field by hint text + final passwordField = find.widgetWithText(TextFormField, 'Senha'); + expect(passwordField, findsOneWidget); + + // Verify visibility toggle icon is present + expect(find.byIcon(Icons.visibility_outlined), findsOneWidget); + + // Tap visibility toggle icon + await tester.tap(find.byIcon(Icons.visibility_outlined)); + await tester.pump(); + + // Verify icon changed to visibility_off after tap + expect(find.byIcon(Icons.visibility_off_outlined), findsOneWidget); + expect(find.byIcon(Icons.visibility_outlined), findsNothing); + + // Tap again to hide + await tester.tap(find.byIcon(Icons.visibility_off_outlined)); + await tester.pump(); + + // Verify icon changed back to visibility + expect(find.byIcon(Icons.visibility_outlined), findsOneWidget); + expect(find.byIcon(Icons.visibility_off_outlined), findsNothing); + }); + }); + + group('Form Validation', () { + testWidgets('should show validation errors for empty fields', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Tap submit button without filling fields + await tester.tap(find.text('Entrar')); + await tester.pump(); + + // Assert + // Note: This test depends on the actual validation implementation + // The validation is handled by the validator, so errors should appear + }); + + testWidgets('should accept valid email format', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Enter valid email + await tester.enterText( + find.widgetWithText(TextFormField, 'Email'), + 'test@example.com', + ); + await tester.pump(); + + // No validation error should be visible + expect(find.text('Por favor, insira um email válido'), findsNothing); + }); + }); + + group('BLoC Integration', () { + testWidgets('should show loading indicator when state is AuthLoading', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthLoading()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(find.text('Entrar'), findsNothing); + }); + + testWidgets('should disable button when state is AuthLoading', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthLoading()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + final button = find.byType(ElevatedButton); + expect(button, findsOneWidget); + + final elevatedButton = tester.widget(button); + expect(elevatedButton.onPressed, isNull); + }); + + testWidgets('should show success snackbar when login succeeds', (tester) async { + // Arrange + const user = UserEntity( + id: '1', + email: 'test@example.com', + name: 'Test User', + ); + const authResponse = AuthResponseEntity(user: user, token: 'token'); + + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + await tester.pump(); + + // Simulate state change to success + when(() => mockAuthBloc.state).thenReturn(const AuthLoginSuccess(authResponse)); + await tester.pump(); + + // For widget testing, we verify the state handling exists rather than the actual snackbar + expect(find.byType(Scaffold), findsOneWidget); + }); + + testWidgets('should show error snackbar when login fails', (tester) async { + // Arrange + const exception = DefaultException(message: 'Login failed'); + + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + await tester.pump(); + + // Simulate state change to failure + when(() => mockAuthBloc.state).thenReturn(const AuthLoginFailure(exception: exception)); + await tester.pump(); + + // For widget testing, we verify the state handling exists rather than the actual snackbar + expect(find.byType(Scaffold), findsOneWidget); + }); + }); + + group('User Interactions', () { + testWidgets('should accept text input in email field', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + const testEmail = 'test@example.com'; + await tester.enterText( + find.widgetWithText(TextFormField, 'Email'), + testEmail, + ); + await tester.pump(); + + // Assert + expect(find.text(testEmail), findsOneWidget); + }); + + testWidgets('should accept text input in password field', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + const testPassword = 'password123'; + final passwordFields = find.byType(TextFormField); + await tester.enterText(passwordFields.at(1), testPassword); + await tester.pump(); + + // Since password is obscured, we can't see the text but the field should accept input + // We verify the field exists and input was processed + expect(find.byType(TextFormField).at(1), findsOneWidget); + }); + + testWidgets('should trigger login when submit button is pressed', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Fill form + await tester.enterText( + find.widgetWithText(TextFormField, 'Email'), + 'test@example.com', + ); + await tester.enterText( + find.byType(TextFormField).at(1), + 'Password123!', + ); + await tester.pump(); + + // Tap submit button + await tester.tap(find.text('Entrar')); + await tester.pump(); + + // Assert - verify button tap worked + expect(find.text('Entrar'), findsOneWidget); + }); + + testWidgets('should handle register button tap', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Tap register button + await tester.tap(find.text('Não tem uma conta? Cadastre-se')); + await tester.pump(); + + // Assert + // Since the onPressed is empty, nothing should happen + // This test ensures the button exists and is tappable + expect(find.text('Não tem uma conta? Cadastre-se'), findsOneWidget); + }); + }); + + group('Accessibility', () { + testWidgets('should have proper semantics for form fields', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + // Verify form fields exist for accessibility + expect(find.widgetWithText(TextFormField, 'Email'), findsOneWidget); + expect(find.widgetWithText(TextFormField, 'Senha'), findsOneWidget); + }); + + testWidgets('should be accessible with screen readers', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + final emailField = find.widgetWithText(TextFormField, 'Email'); + final passwordField = find.widgetWithText(TextFormField, 'Senha'); + final submitButton = find.text('Entrar'); + + expect(emailField, findsOneWidget); + expect(passwordField, findsOneWidget); + expect(submitButton, findsOneWidget); + }); + }); + + group('Layout and Design', () { + testWidgets('should have proper layout structure', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + expect(find.byType(Scaffold), findsOneWidget); + expect(find.byType(AppBar), findsOneWidget); + expect(find.byType(Form), findsOneWidget); + expect(find.byType(Column), findsWidgets); + expect(find.byType(Padding), findsWidgets); + }); + + testWidgets('should have correct spacing between elements', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + expect(find.byType(SizedBox), findsWidgets); + }); + + testWidgets('should display app bar with correct title', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Assert + expect(find.widgetWithText(AppBar, 'Login'), findsOneWidget); + }); + }); + + group('Edge Cases', () { + testWidgets('should handle rapid button taps gracefully', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + // Rapidly tap submit button + for (int i = 0; i < 5; i++) { + await tester.tap(find.text('Entrar')); + } + await tester.pump(); + + // Assert + // Should not crash and maintain single button + expect(find.text('Entrar'), findsOneWidget); + }); + + testWidgets('should handle very long text input', (tester) async { + // Arrange + when(() => mockAuthBloc.state).thenReturn(AuthInitial()); + + // Act + await tester.pumpWidget(createWidgetUnderTest()); + + const longEmail = 'very.long.email.address.that.might.overflow@example.com'; + await tester.enterText( + find.widgetWithText(TextFormField, 'Email'), + longEmail, + ); + await tester.pump(); + + // Assert + expect(find.text(longEmail), findsOneWidget); + }); + }); + }); +} diff --git a/docs/arquitetura/PHPeste_Arquitetura.pdf b/docs/arquitetura/PHPeste_Arquitetura.pdf index a537f14..5d98132 100644 Binary files a/docs/arquitetura/PHPeste_Arquitetura.pdf and b/docs/arquitetura/PHPeste_Arquitetura.pdf differ diff --git a/docs/arquitetura/README.md b/docs/arquitetura/README.md index fbe3946..37592dd 100644 --- a/docs/arquitetura/README.md +++ b/docs/arquitetura/README.md @@ -25,7 +25,7 @@ | 19 | Telas: organização (patrocinadores, fornecedores, finanças, tarefas, comunicação; cresce a cada tela do Marco 2) | | 20 | Onde estamos e o que falta | -Retrato de 27/11/2026, no fim do Marco 2 (a última entrega foi a P06, conta do participante). +Retrato de 28/11/2026, com a base do app Flutter (M01) e o Marco 5 no roadmap. ## Como atualizar diff --git a/docs/arquitetura/fonte/arquitetura.html b/docs/arquitetura/fonte/arquitetura.html index 917e481..b875710 100644 --- a/docs/arquitetura/fonte/arquitetura.html +++ b/docs/arquitetura/fonte/arquitetura.html @@ -108,7 +108,7 @@

Conteúdo

chamada ou dependência assíncrono (evento, fila, webhook) -
Fonte: código da main, backend/CLAUDE.md, docs/produto.md e ADRs 0001–0009.27/11/2026 · fim do Marco 2 · página 1
+
Fonte: código da main, backend/CLAUDE.md, docs/produto.md e ADRs 0001–0009.28/11/2026 · M01 (base do app) · página 1
@@ -134,7 +134,8 @@

Visão geral do sistema

API pública (CORS por edição) App Flutter -ainda não iniciado +participante, palestrante +e check-in · base pronta Gateways (webhooks) Asaas e Mercado Pago @@ -215,7 +216,7 @@

Visão geral do sistema

  • Painel e site são projetos separados (decisão: front-admin SPA, front-public SSR). O token é Bearer do Sanctum nos dois (ADR 0005).
  • Fila e agendador rodam a mesma imagem do backend (horizon e scheduler no infra/docker-compose.yml).
-
PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 2
+
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 2
@@ -290,7 +291,7 @@

Tenancy: comunidade, edição e o que é global

community_id
  • Por que não um banco por comunidade: a mesma pessoa palestra no PHPeste de um ano e compra ingresso no outro, e o perfil dela é um só.
  • Dado de edição que vai para a próxima ("criar edição a partir da anterior") é copiado por um EditionCloner de cada módulo, nunca dado de pessoa.
-
PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 3
+
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 3
@@ -358,7 +359,7 @@

Como uma requisição encontra a edição

O site chama /public/resolve com o host da requisição, recebe edition_id e o domínio principal e redireciona se for preciso (ADR 0008). O host é normalizado (minúsculas, sem porta, IDN em punycode) e nunca é usado para montar URL sem passar pela tabela edition_domains. -
PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 4
+
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 4
@@ -424,7 +425,7 @@

Ciclo de vida da edição

palestrantes, patrocínio, fornecedores), pendências com caminho e filtro (propostas sem revisor, divergência na conciliação, entregas e despesas vencidas) e marcos. O Community filtra cada pendência pela permissão de quem vê: o voluntário não vê pendência de finanças. -
PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 5
+
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 5
@@ -523,7 +524,7 @@

Os 15 módulos do backend

casca -
PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 6
+
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 6
@@ -590,7 +591,7 @@

Como os módulos conversam

EditionMailer::send(...): todo e-mail, com o tema; ::preview mostra sem enviar
  • Ponto de extensão é registrado com $app->tag([...], Contrato::TAG): o Community não conhece os módulos, só a tag. Módulo novo aparece na Visão geral e na clonagem sem mexer no Community. O mesmo vale para TaskLinkProvider (Tasks): Suppliers e Sponsors registram o que uma tarefa pode apontar, e o Program vai registrar a sessão.
-
PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 7
+
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 7
@@ -692,7 +693,7 @@

Banco de dados por domínio

cache · cache_locks sessions
  • Dinheiro sempre em centavos (inteiro). Dado sensível cifrado no banco: CPF de quem compra, credenciais do gateway, acessibilidade, corpo de webhook, linhas de importação. APP_PREVIOUS_KEYS + comandos *:reencrypt-* para trocar a chave.
  • Estoque e cupom nunca são lidos e depois gravados: UPDATE … WHERE allocated + q <= quantity. Testes com 12 processos simultâneos provam que não vende além do lote.
-
PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 8
+
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 8
@@ -713,7 +714,7 @@

Como funciona

  • Palestrante e participante não têm papel: entram pelas rotas de edição publicada.
  • -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 9
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 9
    @@ -788,7 +789,7 @@

    Ingresso: da compra ao QR

    ticketing:expire-orders (1/min) devolve estoque de reserva vencida · ticketing:rotate-batches abre o próximo lote payments:retry-webhooks (1, 5, 15, 60 min) · ticketing:reconcile (diário) grava divergência com o gateway
    • No site, /ingressos confere o cupom na hora e valida os dados de cada participante antes de reservar; a mesma tentativa repete a mesma Idempotency-Key. A reserva aparece em /checkout/pedido/{id} com contagem regressiva (o token do pedido fica só no navegador de quem comprou); ao expirar, volta para a escolha com a mensagem e a escolha anterior. O pagamento mostra quem recebe, gera o Pix (QR, copia e cola, validade) ou leva o cartão para a página do gateway; no Mercado Pago o cartão é digitado nos campos do próprio SDK e só o token chega à API. O status é consultado com espera crescente e, pago, a tela mostra os ingressos com QR (GET …/orders/{id}/tickets, com o token do pedido).
    • Depois da compra, a conta do participante (/conta/ingressos, o link dos e-mails de ingresso) lista os ingressos com QR pelas rotas /attendee/editions/{id}/tickets: salvar a imagem, imprimir, editar o crachá e transferir por e-mail. A transferência sobe a versão do QR e o anterior passa a ser recusado no check-in (replaced) na hora; a tela apaga o QR antigo também da cópia guardada no aparelho. Essa cópia, mais um service worker que guarda só /conta/ingressos e os arquivos dela, mantém o QR visível sem internet depois da primeira abertura. GET /attendee/editions/{id}/orders traz os pedidos e reembolsos de quem comprou.
    • Reembolso: PaymentLedger::refund reserva o valor antes de chamar o gateway (dois reembolsos ao mesmo tempo nunca passam do pago). Pedido importado de outra plataforma entra pago, sem cobrança, e não passa por reembolso nem conciliação. Pagamento recebido fora do gateway é marcado à mão pela organização (MarkOrderPaid), com justificativa na auditoria, emissão dos ingressos e cancelamento da cobrança aberta.
    -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 10
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 10
    @@ -864,7 +865,7 @@

    CFP: da proposta à grade

    Configurar CFP (A10) · Avaliar propostas com teclado (A11) · Palestrantes: lista, cobertura e detalhe (A12) · no site público: formulário de proposta e área do palestrante com entrar pelo GitHub (P03, P11). -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 11
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 11
    @@ -917,7 +918,7 @@

    Dinheiro: patrocínio, fornecedores e finanças

    ADR 0009: a plataforma não recebe nem repassa dinheiro Cada edição cadastra a conta do próprio gateway; a API valida as chaves e um webhook assinado antes de abrir vendas. Credenciais cifradas; a API só mostra os 4 últimos caracteres. -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 12
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 12
    @@ -947,7 +948,7 @@

    Auditoria

  • Segredo removido, dado pessoal mascarado; o model recusa update e delete.
  • -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 13
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 13
    @@ -957,7 +958,7 @@

    Segurança

    TemaComo está
    AutenticaçãoSanctum Bearer, um token por dispositivo com expiração (SANCTUM_EXPIRATION_MINUTES); revogar é imediato. Senha mínima de 10 e checagem de vazamento.
    IsolamentoEscopo global por edição; outra comunidade recebe 404; arch test impede módulo de depender de App\ e controller de usar $request->all().
    Rate limitLimiters nomeados: login, password-reset, checkout, webhooks, configuráveis por .env.
    Headers e CORSCSP, HSTS, nosniff, Referrer-Policy, Permissions-Policy. CORS por ambiente e, em /public/*, só a origem do site próprio da edição.
    Dados sensíveisCifrados no banco (CPF, credenciais, acessibilidade, webhooks). Logs JSON com password, token, secret e cartão redigidos automaticamente.
    ArquivosDisco privado; download só por URL assinada que expira (10 min), sempre como anexo, com nosniff e CSP sandbox. SVG sanitizado.
    PagamentoSem dado de cartão na API; webhook com assinatura do driver e reconsulta ao gateway; idempotência no banco (unique(edition_id, idempotency_key)).
    SegredosADR 0006: nada de segredo no repositório; APP_PREVIOUS_KEYS para trocar a chave sem perder o que já foi cifrado.
    LGPDEncarregado e política por edição, anonimização após o evento (B43 em aberto). Decisão em aberto: comunidade controladora, PHPeste operador.
    -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 14
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 14
    @@ -1032,7 +1033,7 @@

    Desenvolvimento, CI e deploy

    Em aberto para o evento teste de carga, backups, runbook do dia do evento (B45) · dados de demonstração e documentação publicada (B46) -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 15
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 15
    @@ -1045,7 +1046,7 @@

    Telas: o design do painel

    Tokens do tema Sertão
    Design: tokens do tema Sertão
    -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 16
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 16
    @@ -1059,7 +1060,7 @@

    Telas: o painel em uso

    Login
    Entrar com e-mail e senha ou GitHub
    -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 17
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 17
    @@ -1069,7 +1070,7 @@

    Telas: vendas

    Ingressos: tipos e lotes com o preço, o que a edição recebe depois da taxa do gateway, vendidos e situação. Cupons e regras da venda nas outras abas.
    Pedidos: números da edição no topo (pagos, aguardando, reembolsos, taxa do gateway), busca e filtro por situação, e o detalhe com itens, pagamento, reembolsos e histórico (auditoria). Reembolso com aviso de taxa e confirmação explícita; marcar como pago exige justificativa.
    Pagamentos (só a organização): gateway da comunidade com chave mascarada, etapas para abrir vendas e Testar conexão, prévia do recebedor no checkout, métodos aceitos, webhook com o último evento e os últimos eventos do gateway com reprocessar.
    Participantes (só a organização): uma linha por ingresso com crachá, acessibilidade (só a organização vê) e camiseta, filtros de dados faltando e transferidos, edição registrada na auditoria, cobrança de dados com prévia do e-mail e CSV dos crachás.
    -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 18
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 18
    @@ -1079,7 +1080,7 @@

    Telas: organização

    Patrocinadores (só a organização): meta, fechado, pago e em negociação, funil com o último contato de cada empresa, mover que desfaz se a API recusa e pede confirmação de cota sem vaga, e as cotas. O detalhe tem acordo, pagamentos, entregas, histórico e anexos por URL assinada.
    Fornecedores (só a organização): orçado e contratado da lista filtrada, que batem com o total no pé da tabela, filtros, contato restrito e trazer de outra edição da comunidade. O detalhe tem orçamentos, contratar e recusar, anexos e histórico.
    Finanças (organização e financeiro): receita, despesas pagas, saldo e previsão, orçamento por categoria com barra e texto equivalente, receita por origem e por conta com as taxas do gateway, despesas com comprovante por URL assinada e exportação em planilha.
    Tarefas (toda a equipe vê; o responsável move a própria): colunas com contagem, filtros, atrasada em destaque e mover com o mouse ou Alt + setas, anunciado e desfeito se a API recusa.
    Comunicação (só a organização): modelos de e-mail com gatilho e último envio, variável desconhecida bloqueia salvar, prévia gerada pelo backend com o tema e os dados de exemplo, teste para si mesmo e restaurar o padrão.
    -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 19
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 19
    @@ -1087,8 +1088,8 @@

    Telas: organização

    Onde estamos e o que falta

    Os milestones do GitHub e o board PHPeste Platform são a fonte da verdade do andamento; esta página é o retrato no dia da geração.

    -
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPConcluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosConcluídobackend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 e P05 (checkout com Pix e cartão) e P06 (conta do participante)
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37, A13), check-in com modo offline (B38–B39, A18), push (B40), API pública e checkout embutível (B41, P07), site da edição (P02, P08–P10), viagem do palestrante (P11)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    +
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPConcluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosConcluídobackend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 e P05 (checkout com Pix e cartão) e P06 (conta do participante)
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37, A13), check-in com modo offline (B38–B39, A18), push (B40), API pública e checkout embutível (B41, P07), site da edição (P02, P08–P10), viagem do palestrante (P11)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    Marco 5 · App mobileEm andamentobase do app Flutter (M01); telas do participante, palestrante e check-in (M02–M23); o backend que o app precisa está no Marco 3 (B50–B56)
    -
    PHPeste Platform · Arquitetura27/11/2026 · fim do Marco 2 · página 20
    +
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 20
    diff --git a/docs/arquitetura/fonte/gerar.py b/docs/arquitetura/fonte/gerar.py index 80641ed..13281b6 100644 --- a/docs/arquitetura/fonte/gerar.py +++ b/docs/arquitetura/fonte/gerar.py @@ -13,7 +13,7 @@ from pathlib import Path OUT = Path(__file__).with_name("arquitetura.html") -RETRATO = "27/11/2026 · fim do Marco 2" +RETRATO = "28/11/2026 · M01 (base do app)" # ---------------------------------------------------------------- estilo --- # Cores do tema Sertão (front-admin) para o que é da plataforma, e neutras @@ -171,7 +171,7 @@ def legend(): b.append(box(24, 62, 202, 92, "Painel da organização", ["front-admin · Nuxt 4 SPA", "organizador, financeiro,", "avaliador, check-in"], "client")) b.append(box(24, 168, 202, 104, "Site da edição", ["front-public · Nuxt 4 SSR", "site, CFP, checkout,", "área do palestrante e", "do participante"], "client")) b.append(box(24, 286, 202, 78, "Site próprio da comunidade", ["opcional: chama só a", "API pública (CORS por edição)"], "client", dashed=True)) -b.append(box(24, 378, 202, 64, "App Flutter", ["ainda não iniciado"], "todo", dashed=True)) +b.append(box(24, 378, 202, 64, "App Flutter", ["participante, palestrante", "e check-in · base pronta"], "todo", dashed=True)) b.append(box(24, 456, 202, 62, "Gateways (webhooks)", ["Asaas e Mercado Pago"], "external")) b.append(box(275, 200, 120, 150, "Caddy", ["proxy reverso", "TLS sob demanda", "para domínio de", "cada edição", "(tls-check)"], "infra", center=True)) @@ -590,6 +590,7 @@ def legend(): ("Marco 2 · Ingressos", "Concluído", "backend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 e P05 (checkout com Pix e cartão) e P06 (conta do participante)"), ("Marco 3 · Evento pronto", "A fazer", "grade e programação (B35–B37, A13), check-in com modo offline (B38–B39, A18), push (B40), API pública e checkout embutível (B41, P07), site da edição (P02, P08–P10), viagem do palestrante (P11)"), ("Marco 4 · Operação", "A fazer", "engajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)"), + ("Marco 5 · App mobile", "Em andamento", "base do app Flutter (M01); telas do participante, palestrante e check-in (M02–M23); o backend que o app precisa está no Marco 3 (B50–B56)"), ] pages.append(page(20, "Roadmap", "Onde estamos e o que falta", "Os milestones do GitHub e o board PHPeste Platform são a fonte da verdade do andamento; esta página é o retrato no dia da geração.", diff --git a/docs/produto.md b/docs/produto.md index fae73b6..8c63e4b 100644 --- a/docs/produto.md +++ b/docs/produto.md @@ -37,6 +37,7 @@ Os 15 módulos existem no backend (`internachi/modular`, namespace `PHPeste\