Files
halobestie-clone/client_app/lib/features/onboarding/usp_seen_provider.dart
ramadhan sjamsani a09f37135c Phase 4 checkpoint: chat-screen perf refactor + retryable blast-failure + repo-wide dispose-ref guardrail
Chat-screen performance (customer + mitra):
- Parent screens have zero `ref.watch` — only `ref.listen` for side effects
- Body extracted into its own `ConsumerStatefulWidget`; AppBar parts split
  into narrow `.select` consumers (mode, sensitivity, timer)
- Per-second timer ticks routed to dedicated providers
  (`chatRemainingSecondsProvider` + new `mitraChatRemainingSecondsProvider`)
  so WS `session_tick` frames don't invalidate the rest of the chat state

Dispose-in-ref bug fix:
- `home_screen.dart`, `payment_screen.dart`, `mitra_chat_screen.dart` —
  ref-using cleanup moved from `dispose()` to `deactivate()`. Modern
  Riverpod invalidates `ref` the moment `dispose()` runs; the resulting
  silent error corrupts the widget-tree finalize and the next screen
  appears frozen
- `halo_lints` package added at repo root with `no_ref_in_dispose` rule
  to catch this pattern in CI / IDE analysis
- `custom_lint` activated in both apps' `analysis_options.yaml`
  (was installed but never wired in — also brings `riverpod_lint`'s
  `avoid_ref_inside_state_dispose` online)
- CLAUDE.md Pitfalls section added to client_app + mitra_app

Phase 4 §3 retryable blast-failure (Option A):
- Backend `expirePairingRequest` + all-rejected use
  `recordIntermediateFailure` instead of `failPaymentSession` so the
  payment session stays `confirmed` for re-blast
- WS `pairing_failed` payload carries `is_terminal: false` on the
  retryable paths; client parses the flag and exposes `retryBlast()`
- "Coba cari lagi" CTA on S7 Timeout now re-blasts on the same payment
- Pairing service test updated to reflect the new semantics

Customer waiting-payment screen navigation patch:
- `_navigateTerminal` uses `Future.microtask` + `addPostFrameCallback`
  redundancy after a release-mode bug where polling stopped but
  `context.go` never fired, leaving the screen visually stuck on
  "menunggu pembayaran"

See requirement/resume-2026-05-15.md for next-day pickup checklist
(mitra release rebuild + S21 Ultra install + retest is the gating item).

Bundles unrelated in-flight Phase 4 §2.x work that was already on disk
(ESP screen removal, USP one-time gate scaffolding, bestie-availability
public route, OTP service edits, Maestro flow tweaks) — kept together
to avoid a partial-rebase mess.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 19:12:34 +08:00

82 lines
3.0 KiB
Dart

import 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/api/api_client_provider.dart';
import '../../core/auth/auth_notifier.dart';
part 'usp_seen_provider.g.dart';
const _kPrefsKey = 'usp_seen';
/// One-time gate for the S5b USP onboarding screen (Phase 4, 2026-05-12).
///
/// Local SharedPreferences flag is the runtime source of truth. When an
/// authenticated session is hydrated (bootstrap, OTP verify, social, name
/// patch), the server-side `customers.usp_seen` value is OR-merged into the
/// local flag — true wins. When the user dismisses the USP screen and an
/// account exists, the local true is best-effort propagated to the server via
/// `POST /api/client/auth/usp-seen`.
@Riverpod(keepAlive: true)
class UspSeen extends _$UspSeen {
@override
FutureOr<bool> build() async {
// Watch auth state; whenever an auth-bearing profile arrives, OR-merge the
// server flag into local. Disposed/recreated automatically with the
// notifier so no manual cleanup needed.
ref.listen<AsyncValue<AuthData>>(authProvider, (prev, next) {
final profile = _profileOf(next.valueOrNull);
if (profile != null) {
unawaited(_hydrateFromProfile(profile));
}
});
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(_kPrefsKey) ?? false;
}
Map<String, dynamic>? _profileOf(AuthData? data) => switch (data) {
AuthAuthenticatedData d => d.profile,
AuthAnonymousData d => d.profile,
AuthForceRegisterData d => d.profile,
AuthNeedsDisplayNameData d => d.profile,
_ => null,
};
Future<void> _hydrateFromProfile(Map<String, dynamic> profile) async {
final serverSeen = profile['usp_seen'] as bool? ?? false;
if (!serverSeen) return;
if ((state.valueOrNull ?? false) == true) return;
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_kPrefsKey, true);
state = const AsyncData(true);
}
/// Mark seen locally; if an account exists, also persist to DB best-effort.
/// Safe to call when already seen — no-ops out of the network hit if local
/// is already true AND no account exists yet.
Future<void> markSeen() async {
final alreadySeen = (state.valueOrNull ?? false) == true;
if (!alreadySeen) {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_kPrefsKey, true);
state = const AsyncData(true);
}
final authData = ref.read(authProvider).valueOrNull;
final hasAccount = authData is AuthAuthenticatedData ||
authData is AuthAnonymousData ||
authData is AuthForceRegisterData ||
authData is AuthNeedsDisplayNameData;
if (!hasAccount) return;
try {
await ref.read(apiClientProvider).post('/api/client/auth/usp-seen');
} catch (_) {
// Local stays true; next markSeen call (or a successful login on a
// different device) will re-attempt the DB write.
}
}
}