Files
pluriwave/lib/servicios/servicio_compras.dart
T
FreeTLab aa0b242374 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.
2026-08-10 20:37:07 +02:00

175 lines
6.0 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:in_app_purchase/in_app_purchase.dart';
/// Outcome kinds the purchase stream can report (Design ADR-2). Mirrors
/// `in_app_purchase`'s [PurchaseStatus] but stays a PluriWave-owned type so
/// [EstadoEntitlement] never imports the plugin package directly — the SAME
/// port-boundary discipline `PuertoAlarmasAndroid` already applies.
enum TipoEventoCompra {
/// A fresh purchase completed successfully.
comprada,
/// [PuertoCompras.restaurar] found a prior purchase.
restaurada,
/// The user cancelled the purchase flow before it completed.
cancelada,
/// The purchase/restore flow failed (network, billing error, etc).
error,
/// [PuertoCompras.restaurar] completed with nothing to restore — NOT an
/// error (Spec "Restore finds nothing").
noEncontrada,
/// A purchase is in-flight (billing dialog shown, awaiting the user).
pendiente,
}
/// A single purchase-stream event (Design ADR-2). [mensaje] is populated
/// only for [TipoEventoCompra.error], for diagnostics/logging — never shown
/// to the user verbatim.
class EventoCompra {
const EventoCompra(this.tipo, {this.mensaje});
final TipoEventoCompra tipo;
final String? mensaje;
}
/// Purchase I/O abstraction (Design ADR-2): [EstadoEntitlement] depends on
/// this port, never on `in_app_purchase` directly — matches
/// `EstadoAlarmas(android: PuertoAlarmasAndroid)`'s injection shape, and
/// keeps Strict TDD viable with zero plugin channels in unit tests.
abstract class PuertoCompras {
/// Broadcasts every purchase-flow outcome (Design ADR-2) — [comprar] and
/// [restaurar] do not return the outcome directly because
/// `in_app_purchase`'s own API is stream-based (a purchase can complete
/// asynchronously well after the call that started it, e.g. after leaving
/// and returning to the app).
Stream<EventoCompra> get eventos;
/// Starts the one-time non-consumable purchase flow.
Future<void> comprar();
/// Re-queries Play Billing for a prior purchase on this account.
Future<void> restaurar();
}
/// The SOLE `in_app_purchase` call site (Design ADR-2) — every other file
/// depends on [PuertoCompras] instead.
class ServicioComprasPlayBilling implements PuertoCompras {
ServicioComprasPlayBilling({InAppPurchase? inAppPurchase})
: _iap = inAppPurchase ?? InAppPurchase.instance {
_sub = _iap.purchaseStream.listen(
_alRecibirCompras,
onError: (Object error) {
debugPrint('[PluriWave][compras] purchaseStream ERROR $error');
_eventos.add(
EventoCompra(TipoEventoCompra.error, mensaje: error.toString()),
);
},
);
}
/// The single non-consumable product id (Design "Interfaces / Contracts").
static const idProducto = 'pluriwave_premium';
final InAppPurchase _iap;
final _eventos = StreamController<EventoCompra>.broadcast();
StreamSubscription<List<PurchaseDetails>>? _sub;
@override
Stream<EventoCompra> get eventos => _eventos.stream;
@override
Future<void> comprar() async {
try {
final disponible = await _iap.isAvailable();
if (!disponible) {
_eventos.add(
const EventoCompra(
TipoEventoCompra.error,
mensaje: 'Play Billing no disponible',
),
);
return;
}
final respuesta = await _iap.queryProductDetails({idProducto});
final detalle = respuesta.productDetails.firstOrNull;
if (detalle == null) {
_eventos.add(
const EventoCompra(
TipoEventoCompra.error,
mensaje: 'Producto no encontrado en Play Console',
),
);
return;
}
final parametros = PurchaseParam(productDetails: detalle);
await _iap.buyNonConsumable(purchaseParam: parametros);
} catch (e) {
debugPrint('[PluriWave][compras] comprar ERROR $e');
_eventos.add(EventoCompra(TipoEventoCompra.error, mensaje: e.toString()));
}
}
@override
Future<void> restaurar() async {
try {
await _iap.restorePurchases();
} catch (e) {
debugPrint('[PluriWave][compras] restaurar ERROR $e');
_eventos.add(EventoCompra(TipoEventoCompra.error, mensaje: e.toString()));
}
}
void _alRecibirCompras(List<PurchaseDetails> compras) {
if (compras.isEmpty) {
// `restorePurchases()` with nothing to restore completes without ever
// pushing a PurchaseDetails (Spec "Restore finds nothing") — there is
// no per-call correlation in this stream, so this fires on ANY empty
// batch. In practice `queryPastPurchases`/`restorePurchases` on an
// account with nothing to restore is the only source of an empty
// batch this stream would ever emit.
return;
}
for (final compra in compras) {
_eventos.add(
eventoDesdeEstadoCompra(compra.status, mensaje: compra.error?.message),
);
if (compra.pendingCompletePurchase) {
unawaited(_iap.completePurchase(compra));
}
}
}
Future<void> dispose() async {
await _sub?.cancel();
await _eventos.close();
}
}
/// Pure mapping from `in_app_purchase`'s [PurchaseStatus] to the
/// PluriWave-owned [EventoCompra] (Design ADR-2's port boundary): pulled out
/// of [ServicioComprasPlayBilling] so it is unit-testable with zero plugin
/// channels, mirroring how `servicio_audio.dart` extracts its pure mapping
/// helpers (e.g. `mapearEstadoProceso`) out of the un-instantiable handler.
EventoCompra eventoDesdeEstadoCompra(PurchaseStatus status, {String? mensaje}) {
return switch (status) {
PurchaseStatus.pending => const EventoCompra(TipoEventoCompra.pendiente),
PurchaseStatus.purchased => const EventoCompra(TipoEventoCompra.comprada),
PurchaseStatus.restored => const EventoCompra(TipoEventoCompra.restaurada),
PurchaseStatus.error => EventoCompra(
TipoEventoCompra.error,
mensaje: mensaje,
),
PurchaseStatus.canceled => const EventoCompra(TipoEventoCompra.cancelada),
};
}
extension<T> on List<T> {
T? get firstOrNull => isEmpty ? null : first;
}