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:
@@ -0,0 +1,180 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pluriwave/estado/estado_alarmas.dart';
|
||||
import 'package:pluriwave/modelos/alarma_musical.dart';
|
||||
import 'package:pluriwave/servicios/servicio_alarmas.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../helpers/fakes_alarmas.dart';
|
||||
|
||||
/// Freemium gating (freemium-gating spec, design ADR-3/ADR-5): the 5-alarm
|
||||
/// cap for free-tier users, grandfathering of pre-existing alarms, and the
|
||||
/// full premium gate on vacation-range creation. `EstadoAlarmas`'s existing
|
||||
/// suite constructs it with NO `esPremium` callback and expects unrestricted
|
||||
/// behavior — the default therefore stays `() => true` (ungated) so every
|
||||
/// one of those tests keeps passing unchanged; only tests here explicitly
|
||||
/// inject `esPremium: () => false` to exercise the free tier.
|
||||
AlarmaMusical _alarma(String id, {bool activa = true}) => AlarmaMusical(
|
||||
id: id,
|
||||
nombre: 'Alarma $id',
|
||||
hora: 7,
|
||||
minuto: 0,
|
||||
tipoProgramacion: TipoProgramacionAlarma.diaria,
|
||||
diasSemana: const [],
|
||||
activa: activa,
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
});
|
||||
|
||||
EstadoAlarmas construir({required bool premium}) {
|
||||
final android = FakePuertoAlarmasAndroid();
|
||||
final estado = EstadoAlarmas(
|
||||
servicio: ServicioAlarmas(reloj: () => DateTime(2026, 5, 25, 7)),
|
||||
android: android,
|
||||
iniciarAutomaticamente: false,
|
||||
esPremium: () => premium,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
addTearDown(android.dispose);
|
||||
return estado;
|
||||
}
|
||||
|
||||
group('puedeCrearAlarma / cap de 5 (free tier)', () {
|
||||
test('con 4 alarmas puede crear una mas', () async {
|
||||
final estado = construir(premium: false);
|
||||
for (var i = 1; i <= 4; i++) {
|
||||
await estado.guardarAlarma(_alarma('a$i'));
|
||||
}
|
||||
|
||||
expect(estado.puedeCrearAlarma(), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'con 5 alarmas (cualquier estado activa) no puede crear una 6a',
|
||||
() async {
|
||||
final estado = construir(premium: false);
|
||||
for (var i = 1; i <= 4; i++) {
|
||||
await estado.guardarAlarma(_alarma('a$i'));
|
||||
}
|
||||
await estado.guardarAlarma(_alarma('a5', activa: false));
|
||||
|
||||
expect(estado.puedeCrearAlarma(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('la 6a alarma es bloqueada ANTES de programar en Android', () async {
|
||||
final estado = construir(premium: false);
|
||||
for (var i = 1; i <= 5; i++) {
|
||||
await estado.guardarAlarma(_alarma('a$i'));
|
||||
}
|
||||
final android = estado.android as FakePuertoAlarmasAndroid;
|
||||
final programadasPrevias = android.programadas.length;
|
||||
|
||||
final resultado = await estado.guardarAlarma(_alarma('a6'));
|
||||
|
||||
expect(resultado, ResultadoGuardarAlarma.limiteAlcanzado);
|
||||
expect(estado.alarmas.length, 5);
|
||||
expect(android.programadas.length, programadasPrevias);
|
||||
});
|
||||
|
||||
test('editar una de las 5 alarmas existentes sigue funcionando', () async {
|
||||
final estado = construir(premium: false);
|
||||
for (var i = 1; i <= 5; i++) {
|
||||
await estado.guardarAlarma(_alarma('a$i'));
|
||||
}
|
||||
|
||||
final resultado = await estado.guardarAlarma(
|
||||
_alarma('a3').copyWith(hora: 8),
|
||||
);
|
||||
|
||||
expect(resultado, ResultadoGuardarAlarma.guardada);
|
||||
expect(estado.alarmas.firstWhere((a) => a.id == 'a3').hora, 8);
|
||||
});
|
||||
|
||||
test('usuario premium no tiene tope', () async {
|
||||
final estado = construir(premium: true);
|
||||
for (var i = 1; i <= 5; i++) {
|
||||
await estado.guardarAlarma(_alarma('a$i'));
|
||||
}
|
||||
|
||||
final resultado = await estado.guardarAlarma(_alarma('a6'));
|
||||
|
||||
expect(resultado, ResultadoGuardarAlarma.guardada);
|
||||
expect(estado.alarmas.length, 6);
|
||||
expect(estado.puedeCrearAlarma(), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'grandfathering: 8 alarmas preexistentes siguen funcionando, solo se bloquea la 9a',
|
||||
() async {
|
||||
// Simula alarmas ya persistidas antes de que el gate existiera:
|
||||
// se crean en modo premium (sin tope) y luego se re-evalua en free.
|
||||
final estadoPremium = construir(premium: true);
|
||||
for (var i = 1; i <= 8; i++) {
|
||||
await estadoPremium.guardarAlarma(_alarma('g$i'));
|
||||
}
|
||||
expect(estadoPremium.alarmas.length, 8);
|
||||
|
||||
// Editar una de las 8 preexistentes en free tier sigue funcionando.
|
||||
final estadoFree = EstadoAlarmas(
|
||||
servicio: estadoPremium.servicio,
|
||||
android: estadoPremium.android,
|
||||
iniciarAutomaticamente: false,
|
||||
esPremium: () => false,
|
||||
);
|
||||
addTearDown(estadoFree.dispose);
|
||||
await estadoFree.cargarPersistidasSinRecalcular();
|
||||
expect(estadoFree.alarmas.length, 8);
|
||||
|
||||
final edicion = await estadoFree.guardarAlarma(
|
||||
estadoFree.alarmas.first.copyWith(hora: 9),
|
||||
);
|
||||
expect(edicion, ResultadoGuardarAlarma.guardada);
|
||||
expect(estadoFree.alarmas.length, 8);
|
||||
|
||||
// Una 9a alarma NUEVA sigue bloqueada.
|
||||
final resultado = await estadoFree.guardarAlarma(_alarma('g9'));
|
||||
expect(resultado, ResultadoGuardarAlarma.limiteAlcanzado);
|
||||
expect(estadoFree.alarmas.length, 8);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('crearRangoVacaciones — gate completo (freemium-gating)', () {
|
||||
test('free tier: cualquier creacion de vacaciones es bloqueada', () async {
|
||||
final estado = construir(premium: false);
|
||||
|
||||
final creada = await estado.crearRangoVacaciones(
|
||||
RangoVacaciones(
|
||||
id: 'v1',
|
||||
nombre: 'Verano',
|
||||
inicio: DateTime(2026, 7, 1),
|
||||
fin: DateTime(2026, 7, 15),
|
||||
),
|
||||
);
|
||||
|
||||
expect(creada, isFalse);
|
||||
expect(estado.vacaciones, isEmpty);
|
||||
});
|
||||
|
||||
test('premium: crea vacaciones sin restriccion', () async {
|
||||
final estado = construir(premium: true);
|
||||
|
||||
final creada = await estado.crearRangoVacaciones(
|
||||
RangoVacaciones(
|
||||
id: 'v1',
|
||||
nombre: 'Verano',
|
||||
inicio: DateTime(2026, 7, 1),
|
||||
fin: DateTime(2026, 7, 15),
|
||||
),
|
||||
);
|
||||
|
||||
expect(creada, isTrue);
|
||||
expect(estado.vacaciones, hasLength(1));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pluriwave/estado/estado_entitlement.dart';
|
||||
import 'package:pluriwave/servicios/servicio_compras.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Fake [PuertoCompras] (Design ADR-2): never touches `in_app_purchase`,
|
||||
/// lets each test drive [emitir] to simulate the purchase stream.
|
||||
class _PuertoComprasFalso implements PuertoCompras {
|
||||
final _eventos = StreamController<EventoCompra>.broadcast();
|
||||
int comprasIntentadas = 0;
|
||||
int restaurosIntentados = 0;
|
||||
|
||||
@override
|
||||
Stream<EventoCompra> get eventos => _eventos.stream;
|
||||
|
||||
@override
|
||||
Future<void> comprar() async {
|
||||
comprasIntentadas++;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> restaurar() async {
|
||||
restaurosIntentados++;
|
||||
}
|
||||
|
||||
void emitir(EventoCompra evento) => _eventos.add(evento);
|
||||
|
||||
Future<void> dispose() => _eventos.close();
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
});
|
||||
|
||||
group('EstadoEntitlement', () {
|
||||
test('por defecto es free (sin flag persistida)', () async {
|
||||
final estado = EstadoEntitlement(
|
||||
prefs: await SharedPreferences.getInstance(),
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(estado.esPremium, isFalse);
|
||||
});
|
||||
|
||||
test('carga premium desde una flag persistida previamente', () async {
|
||||
SharedPreferences.setMockInitialValues({'compra_premium_v1': true});
|
||||
final estado = EstadoEntitlement(
|
||||
prefs: await SharedPreferences.getInstance(),
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(estado.esPremium, isTrue);
|
||||
});
|
||||
|
||||
test('comprar() con éxito desbloquea premium y persiste', () async {
|
||||
final compras = _PuertoComprasFalso();
|
||||
addTearDown(compras.dispose);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final estado = EstadoEntitlement(prefs: prefs, compras: compras);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
var notificaciones = 0;
|
||||
estado.addListener(() => notificaciones++);
|
||||
|
||||
unawaited(estado.comprar());
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
compras.emitir(const EventoCompra(TipoEventoCompra.comprada));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(estado.esPremium, isTrue);
|
||||
expect(estado.compraEnCurso, isFalse);
|
||||
expect(compras.comprasIntentadas, 1);
|
||||
expect(prefs.getBool('compra_premium_v1'), isTrue);
|
||||
expect(notificaciones, greaterThan(0));
|
||||
});
|
||||
|
||||
test('comprar() cancelada deja el tier free sin cargo', () async {
|
||||
final compras = _PuertoComprasFalso();
|
||||
addTearDown(compras.dispose);
|
||||
final estado = EstadoEntitlement(
|
||||
prefs: await SharedPreferences.getInstance(),
|
||||
compras: compras,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
unawaited(estado.comprar());
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
compras.emitir(const EventoCompra(TipoEventoCompra.cancelada));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(estado.esPremium, isFalse);
|
||||
expect(estado.compraEnCurso, isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'comprar() ya premium es idempotente: no reintenta la compra',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues({'compra_premium_v1': true});
|
||||
final compras = _PuertoComprasFalso();
|
||||
addTearDown(compras.dispose);
|
||||
final estado = EstadoEntitlement(
|
||||
prefs: await SharedPreferences.getInstance(),
|
||||
compras: compras,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
await estado.comprar();
|
||||
|
||||
expect(compras.comprasIntentadas, 0);
|
||||
expect(estado.esPremium, isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test('restaurar() encuentra una compra y desbloquea premium', () async {
|
||||
final compras = _PuertoComprasFalso();
|
||||
addTearDown(compras.dispose);
|
||||
final estado = EstadoEntitlement(
|
||||
prefs: await SharedPreferences.getInstance(),
|
||||
compras: compras,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
unawaited(estado.restaurar());
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
compras.emitir(const EventoCompra(TipoEventoCompra.restaurada));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(estado.esPremium, isTrue);
|
||||
expect(compras.restaurosIntentados, 1);
|
||||
});
|
||||
|
||||
test('restaurar() sin compra previa mantiene free sin error', () async {
|
||||
final compras = _PuertoComprasFalso();
|
||||
addTearDown(compras.dispose);
|
||||
final estado = EstadoEntitlement(
|
||||
prefs: await SharedPreferences.getInstance(),
|
||||
compras: compras,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
unawaited(estado.restaurar());
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
compras.emitir(const EventoCompra(TipoEventoCompra.noEncontrada));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(estado.esPremium, isFalse);
|
||||
expect(estado.compraEnCurso, isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'un error en el flujo de compra no bloquea al pagador (fail-open)',
|
||||
() async {
|
||||
final compras = _PuertoComprasFalso();
|
||||
addTearDown(compras.dispose);
|
||||
final estado = EstadoEntitlement(
|
||||
prefs: await SharedPreferences.getInstance(),
|
||||
compras: compras,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
unawaited(estado.comprar());
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
compras.emitir(const EventoCompra(TipoEventoCompra.error));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
// Fail-open: un error NUNCA escribe `false` sobre una flag ya premium,
|
||||
// y tampoco inventa un `true` para un usuario free.
|
||||
expect(estado.esPremium, isFalse);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('esPremiumPersistido (headless, sin BuildContext)', () {
|
||||
test('lee la flag persistida directamente desde prefs', () async {
|
||||
SharedPreferences.setMockInitialValues({'compra_premium_v1': true});
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
expect(await esPremiumPersistido(prefs: prefs), isTrue);
|
||||
});
|
||||
|
||||
test('por defecto (sin flag) resuelve a free', () async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
expect(await esPremiumPersistido(prefs: prefs), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'resuelve sin prefs inyectadas (SharedPreferences.getInstance)',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues({'compra_premium_v1': true});
|
||||
|
||||
expect(await esPremiumPersistido(), isTrue);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pluriwave/estado/estado_grabacion.dart';
|
||||
import 'package:pluriwave/modelos/emisora.dart';
|
||||
import 'package:pluriwave/servicios/servicio_grabacion_radio.dart';
|
||||
|
||||
import '../helpers/fakes.dart';
|
||||
|
||||
/// Freemium gating (freemium-gating spec "Recording Start Gated, Management
|
||||
/// Stays Free"): starting a NEW recording requires premium; management of
|
||||
/// already-existing recordings (listing/playing/deleting — untouched by
|
||||
/// this file) stays free regardless.
|
||||
void main() {
|
||||
test(
|
||||
'free tier: iniciar() no llama al servicio y reporta requierePremium',
|
||||
() async {
|
||||
final servicio = _ServicioGrabacionControlado();
|
||||
final emisora = emisoraDemo(uuid: 'rec-1', nombre: 'Grabable');
|
||||
final estado = EstadoGrabacion(
|
||||
servicio: servicio,
|
||||
emisoraActual: () => emisora,
|
||||
esPremium: () => false,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
|
||||
final resultado = await estado.iniciar();
|
||||
|
||||
expect(resultado, ResultadoIniciarGrabacion.requierePremium);
|
||||
expect(servicio.inicios, 0);
|
||||
},
|
||||
);
|
||||
|
||||
test('premium: iniciar() delega en el servicio normalmente', () async {
|
||||
final servicio = _ServicioGrabacionControlado();
|
||||
final emisora = emisoraDemo(uuid: 'rec-2', nombre: 'Grabable');
|
||||
final estado = EstadoGrabacion(
|
||||
servicio: servicio,
|
||||
emisoraActual: () => emisora,
|
||||
esPremium: () => true,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
|
||||
final resultado = await estado.iniciar(
|
||||
duracion: const Duration(minutes: 1),
|
||||
);
|
||||
|
||||
expect(resultado, ResultadoIniciarGrabacion.iniciada);
|
||||
expect(servicio.inicios, 1);
|
||||
});
|
||||
|
||||
test('sin callback de entitlement, el default no bloquea (compat)', () async {
|
||||
final servicio = _ServicioGrabacionControlado();
|
||||
final emisora = emisoraDemo(uuid: 'rec-3', nombre: 'Grabable');
|
||||
final estado = EstadoGrabacion(
|
||||
servicio: servicio,
|
||||
emisoraActual: () => emisora,
|
||||
);
|
||||
addTearDown(estado.dispose);
|
||||
|
||||
final resultado = await estado.iniciar();
|
||||
|
||||
expect(resultado, ResultadoIniciarGrabacion.iniciada);
|
||||
expect(servicio.inicios, 1);
|
||||
});
|
||||
}
|
||||
|
||||
class _ServicioGrabacionControlado extends ServicioGrabacionRadio {
|
||||
final _controller = StreamController<EstadoGrabacionRadio>.broadcast();
|
||||
final EstadoGrabacionRadio _estadoActual =
|
||||
const EstadoGrabacionRadio.inactiva();
|
||||
|
||||
int inicios = 0;
|
||||
|
||||
@override
|
||||
EstadoGrabacionRadio get estado => _estadoActual;
|
||||
|
||||
@override
|
||||
Stream<EstadoGrabacionRadio> get estadoStream => _controller.stream;
|
||||
|
||||
@override
|
||||
Future<void> inicializar() async {}
|
||||
|
||||
@override
|
||||
Future<void> iniciar(
|
||||
Emisora emisora, {
|
||||
Duration? duracion,
|
||||
String? directorio,
|
||||
}) async {
|
||||
inicios++;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> dispose() => _controller.close();
|
||||
}
|
||||
Reference in New Issue
Block a user