Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1923,6 +1923,24 @@ Branch `feat/issue-136-cifra-local-paciente`. **Estado:** a Fase 1 (T1–T8) est
- **Dependência descontinuada:** `flutter_secure_storage` com `encryptedSharedPreferences` depende do `androidx.security:security-crypto`; migrar ACS e paciente juntos.
- **#125 ("Sobre")** deve reaproveitar `LocalProtectionNotice`; a C-10 acrescenta a frase da mitigação.

## Pedido de contato e saída "Ligar 192" (C-04, #127) — 2026-11-10

Branch `feat/issue-127-pedido-de-contato-192`. Pré-requisito do portão do piloto (M-01, P-09). Depende da Fase 1 da #136 (banco cifrado), já em `develop`.

- **Pedido de contato.** A aba "Urgência" virou **Contato**: "Ligar 192" no topo, antes do pedido; o botão "Pedir contato ao agente" não tem cor clínica nem rótulo de urgência, e o estado diz que o pedido foi enviado ou registrado, nunca que alguém foi atendido. Por dentro é o mesmo `alerts.createRedAlert` (idempotência, localização), por isso os testes de INV-03 seguem verdes sem mudança de lógica.
- **Saída "Ligar 192".** O vermelho da autoavaliação abre a orientação em tela cheia, que o voltar do sistema não fecha (só "Fechar esta orientação"), não chama o backend e grava um evento na trilha local cifrada.
- **Trilha local cifrada.** Tabela `local_events` no banco SQLCipher do paciente (schema v1 → v2, migração aditiva que preserva lembretes e consentimento): tipo, instante em UTC e versão do motor (`selfAssessmentEngineVersion = 'arvore-v1'`, que não existia), sem respostas. A gravação nunca segura a tela: com o banco indisponível a orientação aparece igual, sem evento.
- **Status.** Sem "Risco: …" e sem "Atendido": "Enviado — aguardando o agente confirmar", "Visto pelo agente participante", "Encerrado pelo agente participante", "Repassado à coordenação do piloto" (este sem escritor hoje; o rótulo antigo prometia o SAMU). Em "Meus dados", a origem `alert` aparece como "Pedido de contato".
- **Dependência.** `url_launcher` ^6.3.0 no paciente (a mesma do ACS) e `<queries>` de `ACTION_DIAL tel` no manifesto; registro em `spec/stack.md`.
- **Provas (VM).** `flutter analyze` sem avisos e 350 testes (eram 334). `test/call_192_test.dart`: orientação sem `createRedAlert`, com o evento e a versão do motor; voltar do sistema não fecha; discador chamado com 192; aviso quando o discador não abre; banco quebrado não impede a orientação; cabeçalho semântico e diretrizes de toque e contraste; pedido depois da orientação é ato separado; "Ligar 192" acima do pedido; nenhum rótulo de urgência na aba. `test/events/sqflite_local_event_log_test.dart`: colunas exatas, UTC, persistência, migração v1 → v2 com lembrete preservado, `deleteEverything()` leva a trilha.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pedido. O CONTRIBUTING.md (linha 250) pede para não gravar contagens de testes nos documentos, porque "elas envelhecem a cada PR". Sugiro trocar "flutter analyze sem avisos e 350 testes (eram 334)." por "flutter analyze sem avisos e suíte verde." e manter as contagens só no corpo da PR. Foi o mesmo pedido feito na #155.


**Abertos e limites.**
- **Não verificado no aparelho:** cifra do arquivo com a tabela nova (a mesma da #136, sem prova nova), `PopScope` com o gesto de voltar preditivo do Android 14+, discador real. `integration_test/full_journey_test.dart` foi ajustado aos textos novos, mas não foi rodado (exige a stack de e2e e o emulador).
- **Amarelo e verde** ainda mostram "Risco: …" e prometem uma "solicitação" que não é enviada ("O agente de saúde entrará em contato", "Acompanhar solicitação"). É a C-08 (#130).
- **Retenção de 30 dias e "Apagar meus dados"** da trilha: C-10 (#131). Hoje a trilha só some com "Apagar e recomeçar".
- **Lado do agente e backend:** o ACS e o backoffice continuam chamando o pedido de alerta vermelho ("Risco: Vermelho"). A issue não pediu mudança lá; fica para decisão do dono.
- **Captura de tela** `docs/screenshots/patient/01-emergencia.png` é anterior à C-04.

## Aviso educativo na primeira abertura e em "Sobre" (C-02, #125) — 2026-11-08

Branch `feat/c-02-aviso-educativo`. RF21 nos apps do paciente e do agente.
Expand Down
2 changes: 2 additions & 0 deletions apps/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ The onboarding QR (RF02) now exists on both sides: the ACS's "Mais › Convidar

**Full patient test against the test database (`scripts/qa/patient_full_e2e.sh`).** One command on `emulator-5554`: it brings up `docker-compose.e2e.yml` through `scripts/qa/e2e_stack.sh` (database `sinalacs_e2e` inside the ephemeral `postgres-test`, `ENABLE_DEV_LOGIN=false`, `SMS_GATEWAY=log`, Gorush), seeds **synthetic fixtures generated per run** (`bin/seed_e2e_fixtures.dart`: random UUIDs, CPFs with valid check digits, one ACS with a random password; manifest `.e2e/fixtures.json`, mode 600, git-ignored and deleted at the end) and runs `integration_test/full_journey_test.dart` (real OTP through the screen, terms, red triage, alert, status, "Meus dados", and ACS territory) plus `backend_connection_test.dart`; without `--sem-push` it ends with `push_e2e.sh --e2e-db --negativos` (real Gorush and FCM). The OTP code reaches the emulator through `scripts/qa/otp_relay.py` (`adb reverse tcp:8765`; the cut-off of "codes after my request" uses the relay's `/now`, the HOST clock, never the device's; the runners refuse to start if an old relay still holds the port), because the `log` SMS gateway only writes it to the server log. The integration helpers (`integration_test/support/e2e_login.dart`) use the manifest when `--dart-define=E2E_FIXTURES=...` is given and **fall back to `developmentLogin` otherwise**, which is what keeps the CI's `android-e2e` working; the host tools (`tool/live_check.dart`, `tool/push_consent.dart`) only use a manifest when `E2E_FIXTURES_FILE` is set. The server enforces 60 s between two OTP requests of the same patient, hence one fixture per consumer (`main`, `chronic`, `api`, `push`, plus `outsider` in another micro-area) and a wait in `push_e2e.sh`. The widget tests keep `FakePatientBackend` and their fixed names on purpose: they are hermetic.

**Paciente: pedido de contato e "Ligar 192" (C-04, #127, 2026-11-10).** A aba antes "Urgência" agora é **Contato** (`EmergencyScreen`): o cartão com `call_192_button` (`Call192Button`, `lib/app/call_192.dart`, `EmergencyDialer` em `core/services/emergency_dialer.dart`, `url_launcher` com `tel:192`, nunca liga sozinho, 64×60dp) vem **antes** do pedido; o pedido (`panic_button`, chave mantida pelos e2e; texto "Pedir contato ao agente", sem cor clínica e sem `Semantics` em volta) continua chamando `alerts.createRedAlert` com a mesma idempotência e localização, e é isso que mantém a INV-03. O vermelho do `triage.evaluate` **não** mostra cartão: `_TriageScreenState._showCall192` abre `Call192OrientationScreen` na rota raiz (cobre a barra de navegação), com `PopScope(canPop: false)` e só `call_192_close` fecha; não chama o backend, grava `LocalEventKind.call192OrientationShown` em `LocalEventLog` sem esperar (falha engolida, a tela aparece igual) e recomeça a autoavaliação. A trilha é a tabela `local_events` (schema v2 do `PatientLocalDatabase`, migração aditiva `_upgrade`; colunas `kind`, `occurred_at` em UTC e `engine_version` = `selfAssessmentEngineVersion` em `core/triage/self_assessment.dart`, nunca respostas), lida e gravada por `SqfliteLocalEventLog` (`PatientLocalStores.events`) e injetada por `Call192Scope` (`SinalAcsApp(emergencyDialer:, localEvents:)` nos testes). `deleteEverything()` a leva junto; a expiração em 30 dias é da C-10. O Status mostra "Pedido de contato" e estados descritivos, sem `riskLevel` e sem "Atendido". Testes: `test/call_192_test.dart`, `test/events/sqflite_local_event_log_test.dart`.

The UI depends on the interface, never on the generated `Client`, which is what keeps the widget tests hermetic; the live path is checked by `tool/live_check.dart` in each app and by `integration_test/`.

Risk classification now comes **only** from `triage.evaluate`: the patient app's client-side string-matching rule is gone, and its triage form asks the six symptoms the server's engine actually takes. The ACS dashboard is fed by `AlertQueue`, which receives alerts over MQTT and orders them deterministically by risk and then by age; it rejects alerts from another micro-area and de-duplicates re-deliveries (QoS 1 is at-least-once).
Expand Down
7 changes: 7 additions & 0 deletions apps/patient/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@

In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<!-- "Ligar 192" (C-04, #127): o discador precisa ser visível ao app no
Android 11+. Só ACTION_DIAL, nunca CALL_PHONE: a pessoa confirma a
ligação no discador. -->
<intent>
<action android:name="android.intent.action.DIAL"/>
<data android:scheme="tel"/>
</intent>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
Expand Down
22 changes: 13 additions & 9 deletions apps/patient/integration_test/full_journey_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ void main() {
/// Passa pelo convite de termos, se o paciente ainda não os aceitou.
Future<void> aceitarTermosSePedido(WidgetTester tester) async {
final termos = find.byKey(const Key('terms_gate_accept_button'));
final home = find.text('Urgência');
final home = find.text('Contato');
final limit = DateTime.now().add(const Duration(seconds: 30));
while (termos.evaluate().isEmpty && home.evaluate().isEmpty) {
if (DateTime.now().isAfter(limit)) throw TestFailure('nem termos nem home após o login');
Expand Down Expand Up @@ -115,12 +115,12 @@ void main() {
// O código verdadeiro é o do PRIMEIRO pedido: errar não gasta outro SMS.
await digitarCodigo(tester, await codeFromRelay(_relay, pedidoEm));
await aceitarTermosSePedido(tester);
expect(find.text('Urgência'), findsOneWidget);
expect(find.text('Contato'), findsOneWidget);
// E de fato foi UM pedido: errar o código não pode ter gasto outro SMS.
expect(await relayCount(_relay, pedidoEm), 1);
});

testWidgets('triagem vermelha, alerta, status e Meus dados do próprio paciente', (tester) async {
testWidgets('triagem vermelha, "Ligar 192", pedido de contato, status e Meus dados do próprio paciente', (tester) async {
final backend = await backendReal();
addTearDown(backend.close);
await tester.pumpWidget(SinalAcsApp(backend: backend, locationReader: _FixedLocation()));
Expand All @@ -138,18 +138,22 @@ void main() {
await tester.tap(find.byKey(const Key('submit_triage')));
await tester.pump(const Duration(milliseconds: 400));
}
await pumpUntil(tester, find.text('Risco: Vermelho'));
// Vermelho no motor do servidor: só a orientação "Ligar 192", sem
// pedido de contato (C-04); fecha pela escolha explícita.
await pumpUntil(tester, find.byKey(const Key('call_192_title')));
await tapKey(tester, 'call_192_close');
await tester.pump(const Duration(milliseconds: 400));

// Alerta de urgência: sai mesmo sem o GPS do sistema.
await tester.tap(find.text('Urgência'));
// Pedido de contato, ato separado: sai mesmo sem o GPS do sistema.
await tester.tap(find.text('Contato'));
await tester.pump(const Duration(milliseconds: 400));
await tapKey(tester, 'panic_button');
await tester.tap(find.text('Confirmar alerta'));
await pumpUntil(tester, find.textContaining('Alerta recebido pela equipe'));
await tester.tap(find.text('Enviar pedido'));
await pumpUntil(tester, find.textContaining(RegExp('^Pedido (enviado|registrado)')));

// Status real, não o vazio.
await tester.tap(find.text('Status'));
await pumpUntil(tester, find.text('Enviado — aguardando confirmação da equipe'));
await pumpUntil(tester, find.text('Enviado — aguardando o agente confirmar'));
expect(find.byKey(const Key('status_empty')), findsNothing);

// Meus dados: o cadastro da fixture, a condição crônica decifrada, e só.
Expand Down
Loading
Loading