feat(iap): add freemium unlock via one-time in-app purchase

Adds a permanent, non-consumable premium unlock (EstadoEntitlement +
PuertoCompras/ServicioComprasPlayBilling) that removes ads and unlocks
alarm vacations, alarms past a 5-alarm free cap, recording start, and
full Android Auto browsing. The phone equalizer stays free for everyone.

- Entitlement is prefs-backed (compra_premium_v1), fail-open, and
  resolvable headlessly via esPremiumPersistido() for the Android Auto
  audio handler, which registers before runApp.
- Android Auto reduced mode keeps the real root folder labels for free
  users; browsing into any of them (and playFromMediaId/playFromSearch/
  skipToNext/skipToPrevious) is blocked at the getChildren/servicio_audio
  choke points, with a locked "Función Premium" item as the backstop.
  Current-station play/pause/stop stays untouched. A free -> premium
  transition actively invalidates the head unit's cached browse tree.
- Ads (top banner + capped interstitial before adding a station or an
  alarm) are gated behind entitlement via ServicioAnuncios, using
  official Google test ad unit IDs pending AdMob provisioning.
- Alarm cap UX shows an explanatory message with a secondary unlock
  action rather than a bare paywall jump; existing data is grandfathered.
- 4 new localization keys translated across all 13 supported locales.

Co-located tests use strict TDD (RED test before implementation) for
every new pure-logic unit; full existing suite passes unchanged.
This commit is contained in:
2026-08-10 20:37:07 +02:00
parent f4a1fac45a
commit aa0b242374
77 changed files with 3757 additions and 72 deletions
+54 -3
View File
@@ -9,15 +9,31 @@ import '../servicios/servicio_alarmas.dart';
import '../servicios/servicio_alarmas_android.dart';
import '../servicios/servicio_programacion_alarmas.dart';
/// Distinct "limit reached" signal (Design ADR-5, freemium-gating spec
/// "Alarm Count Cap At 5"): kept SEPARATE from [EstadoAlarmas.error], which
/// stays reserved for native scheduling failures — overloading it would
/// surface a free-tier limit as a scheduling failure in `app.dart`'s global
/// snackbar path.
enum ResultadoGuardarAlarma { guardada, limiteAlcanzado }
class EstadoAlarmas extends ChangeNotifier {
EstadoAlarmas({
ServicioAlarmas? servicio,
PuertoAlarmasAndroid? android,
SharedPreferences? prefs,
bool iniciarAutomaticamente = true,
// iap-freemium-unlock (Design ADR-3): entitlement query, mirroring
// `EstadoGrabacion`'s `emisoraActual` callback-injection shape rather
// than a direct `EstadoEntitlement` dependency (this notifier must stay
// constructible with zero widget-tree/Provider context). Defaults to
// "premium" (ungated) so every pre-existing test/call site that never
// wires entitlement keeps its exact previous behavior — production
// wiring in `app.dart` always passes the real callback.
bool Function()? esPremium,
}) : servicio = servicio ?? ServicioAlarmas(prefs: prefs),
android = android ?? ServicioAlarmasAndroid(),
_prefs = prefs {
_prefs = prefs,
_esPremium = esPremium ?? (() => true) {
// Decision 2.1 (snooze sync): the native layer reports its own snoozes
// back through alarmFired/snoozed; record them here so the Flutter
// config stays the single source of truth.
@@ -32,8 +48,12 @@ class EstadoAlarmas extends ChangeNotifier {
final ServicioAlarmas servicio;
final PuertoAlarmasAndroid android;
final SharedPreferences? _prefs;
final bool Function() _esPremium;
static const _keyExencionBateriaSolicitada = 'bateria_exencion_solicitada';
/// Free-tier alarm cap (freemium-gating spec "Alarm Count Cap At 5").
static const maxAlarmasFree = 5;
List<AlarmaMusical> _alarmas = [];
List<RangoVacaciones> _vacaciones = [];
List<ExcepcionAlarma> _excepciones = [];
@@ -101,7 +121,26 @@ class EstadoAlarmas extends ChangeNotifier {
}
}
Future<void> guardarAlarma(AlarmaMusical alarma) async {
/// Pure query (freemium-gating spec "Alarm Count Cap At 5"): whether a NEW
/// alarm may be created right now. Counts ALL alarms regardless of
/// `activa` (Spec "6th alarm creation is blocked" — "any enabled state").
/// Always `true` for premium (no cap). Editing an existing id is never
/// subject to this — see [guardarAlarma]'s own new-vs-edit check.
bool puedeCrearAlarma() => _esPremium() || _alarmas.length < maxAlarmasFree;
Future<ResultadoGuardarAlarma> guardarAlarma(AlarmaMusical alarma) async {
// Gate BEFORE any native scheduling attempt (freemium-gating spec "6th
// alarm creation is blocked": "no native scheduling is attempted").
// Editing an alarm that already exists (by id) is NEVER capped — only
// genuinely NEW creation counts against the limit (Spec "Editing an
// existing alarm is unaffected", grandfathering).
final esAlarmaNueva = !_alarmas.any((a) => a.id == alarma.id);
if (esAlarmaNueva && !puedeCrearAlarma()) {
debugPrint(
'[PluriWave][alarmas] guardar bloqueado por limite free id=${alarma.id}',
);
return ResultadoGuardarAlarma.limiteAlcanzado;
}
debugPrint(
'[PluriWave][alarmas] guardar id=${alarma.id} activa=${alarma.activa} hora=${alarma.hora}:${alarma.minuto} tipo=${alarma.tipoProgramacion.name}',
);
@@ -125,6 +164,7 @@ class EstadoAlarmas extends ChangeNotifier {
await _registrarFalloProgramacion(alarma.id);
}
notifyListeners();
return ResultadoGuardarAlarma.guardada;
}
Future<void> refrescarProgramacion() async {
@@ -507,9 +547,20 @@ class EstadoAlarmas extends ChangeNotifier {
notifyListeners();
}
Future<void> crearRangoVacaciones(RangoVacaciones rango) async {
/// Full premium gate (freemium-gating spec "Gated Feature Set (Exactly
/// 4)" — alarm vacations, unlike the alarm cap above, are gated entirely,
/// not counted): returns `false` without persisting anything when the
/// caller is free tier.
Future<bool> crearRangoVacaciones(RangoVacaciones rango) async {
if (!_esPremium()) {
debugPrint(
'[PluriWave][alarmas] crear vacaciones bloqueado (free) id=${rango.id}',
);
return false;
}
final nuevos = [..._vacaciones, rango];
await guardarVacaciones(nuevos);
return true;
}
Future<void> eliminarRangoVacaciones(String id) async {
+140
View File
@@ -0,0 +1,140 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../servicios/servicio_audio.dart' show notificarDesbloqueoAuto;
import '../servicios/servicio_compras.dart';
/// Versioned persistence key (Design ADR-1) for the permanent, non-consumable
/// premium unlock. Older builds that predate this key simply never read it —
/// no migration needed (Rollout "Versioned key ... is ignored by older
/// builds").
const _keyPremium = 'compra_premium_v1';
/// Headless-safe entitlement read (Design ADR-1, Spec "Headless-Safe
/// Entitlement Read"): resolves the persisted premium flag directly from
/// prefs, with NO `BuildContext`/`Provider` dependency. Mirrors
/// `FuenteMusicaLocalAutoImpl._resolverPrefs()`'s
/// inject-or-`getInstance()` convention (`musica_local_auto.dart:163`) —
/// this is what `PluriWaveAudioHandler` calls, since it registers before
/// `runApp` and no widget tree (therefore no `Provider`) exists yet.
///
/// Absent key = free tier (Rollout "Additive and prefs-backed; absent key =
/// free"). Never throws — a `SharedPreferences.getInstance()` failure would
/// propagate here exactly like the persisted read failing, which the caller
/// (Design ADR-2 "fail-open") must treat as "trust the last known state",
/// not this function's job to catch.
Future<bool> esPremiumPersistido({SharedPreferences? prefs}) async {
final resueltas = prefs ?? await SharedPreferences.getInstance();
return resueltas.getBool(_keyPremium) ?? false;
}
/// Cross-cutting entitlement notifier (Design ADR-1), idiomatic
/// `EstadoIdioma`-shaped `ChangeNotifier`: UI layers `context.watch`/`read`
/// this; headless callers (Android Auto) use [esPremiumPersistido] instead,
/// since no `Provider` exists on that path.
class EstadoEntitlement extends ChangeNotifier {
EstadoEntitlement({SharedPreferences? prefs, PuertoCompras? compras})
: _prefs = prefs,
_compras = compras {
final flujo = _compras;
if (flujo != null) {
_comprasSub = flujo.eventos.listen(_alRecibirEvento);
}
_cargar();
}
/// The single non-consumable product id (Design "Interfaces / Contracts"),
/// re-exported here so UI/paywall code depends on ONE canonical constant
/// rather than reaching into `servicio_compras.dart` for it.
static const idProducto = ServicioComprasPlayBilling.idProducto;
final SharedPreferences? _prefs;
final PuertoCompras? _compras;
StreamSubscription<EventoCompra>? _comprasSub;
bool _esPremium = false;
bool _compraEnCurso = false;
bool get esPremium => _esPremium;
bool get compraEnCurso => _compraEnCurso;
Future<void> _cargar() async {
final prefs = await _resolverPrefs();
final premium = prefs.getBool(_keyPremium) ?? false;
if (premium != _esPremium) {
_esPremium = premium;
}
notifyListeners();
}
Future<SharedPreferences> _resolverPrefs() async =>
_prefs ?? SharedPreferences.getInstance();
/// Starts the purchase flow (Spec "Successful purchase"). A no-op when
/// already premium (Spec "Already-purchased attempt is idempotent") — no
/// duplicate charge is even attempted.
Future<void> comprar() async {
if (_esPremium) return;
final compras = _compras;
if (compras == null) return;
_compraEnCurso = true;
notifyListeners();
await compras.comprar();
}
/// Re-queries Play Billing for a prior purchase (Spec "Restore Purchases").
Future<void> restaurar() async {
final compras = _compras;
if (compras == null) return;
_compraEnCurso = true;
notifyListeners();
await compras.restaurar();
}
Future<void> _alRecibirEvento(EventoCompra evento) async {
switch (evento.tipo) {
case TipoEventoCompra.comprada:
case TipoEventoCompra.restaurada:
await _desbloquear();
case TipoEventoCompra.cancelada:
case TipoEventoCompra.noEncontrada:
// Spec "Purchase cancelled or failed" / "Restore finds nothing":
// stays free tier, no error surfaced — just stop the in-flight
// spinner.
_compraEnCurso = false;
notifyListeners();
case TipoEventoCompra.error:
// Fail-open (Design ADR-2): an error NEVER writes `false` over an
// already-premium flag, and never invents a `true` for a free user
// either — the persisted flag from `_cargar()` is left untouched.
_compraEnCurso = false;
notifyListeners();
case TipoEventoCompra.pendiente:
_compraEnCurso = true;
notifyListeners();
}
}
Future<void> _desbloquear() async {
final yaEraPremium = _esPremium;
_esPremium = true;
_compraEnCurso = false;
final prefs = await _resolverPrefs();
await prefs.setBool(_keyPremium, true);
notifyListeners();
if (!yaEraPremium) {
// Orchestrator-resolved open question (design.md): actively
// invalidate the Android Auto browse cache on the free -> premium
// transition, rather than waiting for the head unit's own re-bind.
notificarDesbloqueoAuto();
}
}
@override
void dispose() {
_comprasSub?.cancel();
super.dispose();
}
}
+26 -3
View File
@@ -35,14 +35,26 @@ bool esEmisoraGrabable(Emisora emisora) {
return esquema == 'http' || esquema == 'https';
}
/// Distinct outcome signal for [EstadoGrabacion.iniciar] (freemium-gating
/// spec "Recording Start Gated"): [requierePremium] is NOT surfaced through
/// [EstadoGrabacion.iniciar]'s existing `alError` sink — the caller must
/// react by opening the paywall, a different UI than a plain error snackbar.
enum ResultadoIniciarGrabacion { iniciada, requierePremium, error }
class EstadoGrabacion extends ChangeNotifier {
EstadoGrabacion({
ServicioGrabacionRadio? servicio,
Emisora? Function()? emisoraActual,
void Function(String mensaje)? alError,
// iap-freemium-unlock (Design ADR-3): entitlement query, mirroring
// [_emisoraActual]'s callback-injection shape. Defaults to "premium"
// (ungated) so every pre-existing test/call site keeps its exact
// previous behavior — `app.dart` always wires the real callback.
bool Function()? esPremium,
}) : servicio = servicio ?? ServicioGrabacionRadio(),
_emisoraActual = emisoraActual ?? (() => null),
_alError = alError {
_alError = alError,
_esPremium = esPremium ?? (() => true) {
_suscripcion = this.servicio.estadoStream.listen((estado) {
if (estado.tipo == EstadoGrabacionRadioTipo.error &&
estado.error != null) {
@@ -65,6 +77,8 @@ class EstadoGrabacion extends ChangeNotifier {
/// User-visible error sink (EstadoRadio routes it to its snackbar stream).
final void Function(String mensaje)? _alError;
final bool Function() _esPremium;
StreamSubscription<EstadoGrabacionRadio>? _suscripcion;
AppLocalizations? _l10n;
@@ -87,7 +101,14 @@ class EstadoGrabacion extends ChangeNotifier {
int get maxBytes => servicio.maxBytes;
File? get ultimoArchivo => servicio.ultimoArchivo;
Future<void> iniciar({Duration? duracion}) async {
Future<ResultadoIniciarGrabacion> iniciar({Duration? duracion}) async {
// Freemium gate (freemium-gating spec "Free user starts a new
// recording"): the AUTHORITATIVE check, before touching the service at
// all. Management of already-existing recordings is untouched — this
// method only governs STARTING a new one.
if (!_esPremium()) {
return ResultadoIniciarGrabacion.requierePremium;
}
final actual = _emisoraActual();
// `emisoraActual` is set by `_cambiarFuente` for EVERY source, local
// tracks included -- a local file becomes an `Emisora` whose `url` is the
@@ -97,12 +118,14 @@ class EstadoGrabacion extends ChangeNotifier {
// that, whatever was playing was always a real station.
if (actual == null || !esEmisoraGrabable(actual)) {
_alError?.call(_textos.recordingSelectStationFirst);
return;
return ResultadoIniciarGrabacion.error;
}
try {
await servicio.iniciar(actual, duracion: duracion);
return ResultadoIniciarGrabacion.iniciada;
} catch (e) {
_alError?.call(_textos.recordingStartError(e.toString()));
return ResultadoIniciarGrabacion.error;
}
}
+5
View File
@@ -47,6 +47,10 @@ class EstadoRadio extends ChangeNotifier {
Future<File> Function()? resolverArchivoCustom,
FuenteEmisorasAuto? fuenteAuto,
bool iniciarAutomaticamente = true,
// iap-freemium-unlock (Design ADR-3): threaded straight through to the
// internal `EstadoGrabacion` below — `EstadoRadio` itself has no gated
// behavior of its own.
bool Function()? esPremium,
}) : audio = audio ?? ServicioAudio(),
favoritos = favoritos ?? ServicioFavoritos(),
radio = radio ?? ServicioRadio(),
@@ -66,6 +70,7 @@ class EstadoRadio extends ChangeNotifier {
servicio: servicioGrabacion ?? ServicioGrabacionRadio(prefs: prefs),
emisoraActual: () => emisoraActual,
alError: _errorController.add,
esPremium: esPremium,
);
busqueda = EstadoBusqueda(
radio: this.radio,