diff --git a/app/lib/main.dart b/app/lib/main.dart index 9610865..22de2d0 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flame/game.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; @@ -6,6 +8,10 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; import 'src/ads/ads_service.dart'; +import 'src/billing/billing_service.dart'; +import 'src/billing/entitlements.dart'; +import 'src/billing/models.dart'; +import 'src/billing/store_client.dart'; import 'src/game/iron_arc_game.dart'; import 'src/native/native_match.dart'; import 'src/net/api_client.dart'; @@ -66,6 +72,9 @@ class _MatchScreenState extends State { IronArcGame? _game; bool _splashGone = false; + Entitlements? _entitlements; + BillingService? _billing; + @override void initState() { super.initState(); @@ -96,11 +105,30 @@ class _MatchScreenState extends State { setState(() => _splashGone = true); debugPrint('iron_arc: ready after ${_bootWatch.elapsedMilliseconds} ms'); + + // Store first: entitlements gate the interstitials that ads would load. + final entitlements = await Entitlements.load(); + if (!mounted) return; + _entitlements = entitlements; + entitlements.addListener(_syncAdsGate); + _syncAdsGate(); + final billing = BillingService( + entitlements: entitlements, + client: PlayStoreClient(), + ); + _billing = billing; + unawaited(billing.init()); + _ads.initialize(); } + /// Owners of "Remove Ads" never see an interstitial. + void _syncAdsGate() => _ads.adsRemoved = _entitlements?.adsRemoved ?? false; + @override void dispose() { + _entitlements?.removeListener(_syncAdsGate); + _billing?.dispose(); _ads.dispose(); _api.close(); _session.dispose(); @@ -199,6 +227,7 @@ class _MatchScreenState extends State { if (!ok && mounted) _toast('Keine App zum Öffnen gefunden'); }, ), + _shopSection(sheetContext), ListTile( leading: const Icon(Icons.campaign_outlined), title: const Text('Werbe-Status'), @@ -228,6 +257,36 @@ class _MatchScreenState extends State { if (!ok && mounted) _toast('Keine E-Mail-App gefunden'); }, ), + ListTile( + leading: const Icon(Icons.cleaning_services_outlined), + title: const Text('Lokale Daten löschen'), + subtitle: const Text('Verlauf, Warteschlange, Geräte-ID'), + onTap: () async { + Navigator.pop(sheetContext); + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Lokale Daten löschen?'), + content: const Text( + 'Entfernt Offline-Warteschlange, Replays und die Geräte-ID ' + 'von diesem Gerät. Käufe bleiben erhalten.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Abbrechen')), + FilledButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text('Löschen')), + ], + ), + ); + if (confirmed != true || !mounted) return; + final prefs = await SharedPreferences.getInstance(); + await prefs.clear(); + if (!mounted) return; + _toast('Lokale Daten gelöscht – App neu starten'); + }, + ), if (kDebugMode) ListTile( leading: const Icon(Icons.restart_alt), @@ -245,6 +304,73 @@ class _MatchScreenState extends State { ); } + /// Store section of the settings sheet (M7c). + Widget _shopSection(BuildContext sheetContext) { + final billing = _billing; + final ent = _entitlements; + if (billing == null || ent == null) { + return const ListTile( + leading: Icon(Icons.shopping_bag_outlined), + title: Text('Werbung entfernen'), + subtitle: Text('Store wird geladen …'), + enabled: false, + ); + } + return ListenableBuilder( + listenable: Listenable.merge([billing, ent]), + builder: (context, _) { + final owned = ent.adsRemoved; + final price = billing.product(ProductIds.removeAds)?.price; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Divider(height: 1, color: Color(0xFF1B2C44)), + ListTile( + leading: Icon( + owned ? Icons.verified : Icons.block, + color: owned ? const Color(0xFFFFB347) : null, + ), + title: const Text('Werbung entfernen'), + subtitle: Text(owned + ? 'Gekauft - keine Interstitials mehr' + : billing.busy + ? 'Einen Moment …' + : price ?? billing.error ?? 'Preis wird geladen …'), + trailing: owned + ? null + : const Icon(Icons.shopping_bag_outlined, size: 18), + enabled: !owned && billing.canPurchase && !billing.busy, + onTap: owned + ? null + : () async { + Navigator.pop(sheetContext); + final started = await billing.buy(ProductIds.removeAds); + if (!mounted) return; + _toast(started + ? 'Kauf gestartet' + : billing.error ?? 'Kauf nicht möglich'); + }, + ), + if (!owned) + ListTile( + leading: const Icon(Icons.restore), + title: const Text('Käufe wiederherstellen'), + enabled: billing.available && !billing.busy, + onTap: () async { + Navigator.pop(sheetContext); + await billing.restore(); + if (!mounted) return; + _toast(ent.adsRemoved + ? 'Käufe wiederhergestellt' + : 'Keine Käufe gefunden'); + }, + ), + ], + ); + }, + ); + } + Future _showRewardedAd() async { if (!_ads.isAdsAllowed) { _toast('Anzeigen erst nach Zustimmung'); diff --git a/app/lib/src/ads/ads_service.dart b/app/lib/src/ads/ads_service.dart index 3731d68..89c1831 100644 --- a/app/lib/src/ads/ads_service.dart +++ b/app/lib/src/ads/ads_service.dart @@ -30,6 +30,10 @@ class AdsService { InterstitialAd? _interstitial; bool _started = false; bool _adsAllowed = false; + + /// Set from the store entitlements ("Remove Ads"). Owners never see an + /// interstitial; rewarded video stays available on purpose. + bool adsRemoved = false; int _matchesFinished = 0; ConsentStatus _consentStatus = ConsentStatus.unknown; @@ -168,6 +172,7 @@ class AdsService { } void _loadInterstitial() { + if (adsRemoved) return; // owner: never request an interstitial InterstitialAd.load( adUnitId: interstitialUnitId, request: const AdRequest(), @@ -215,7 +220,7 @@ class AdsService { /// Called when a match ends; applies the frequency caps from the GDD. void onMatchFinished() { - if (!_adsAllowed) return; + if (!_adsAllowed || adsRemoved) return; _matchesFinished++; if (_matchesFinished <= skipFirstMatches) return; if (_matchesFinished % everyNthMatch != 0) return; diff --git a/app/lib/src/billing/billing_service.dart b/app/lib/src/billing/billing_service.dart new file mode 100644 index 0000000..a2cc07d --- /dev/null +++ b/app/lib/src/billing/billing_service.dart @@ -0,0 +1,143 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import 'entitlements.dart'; +import 'models.dart'; +import 'store_client.dart'; + +/// Orchestrates the store: product query, purchase, restore, entitlement write. +/// +/// Rules from docs/monetization.md: +/// * prices come from the store, never from the app; +/// * `queryPurchases` on start, so a reinstall restores what was bought; +/// * pending transactions are reported but never granted; +/// * every purchased/restored item is completed (Play refunds after 3 days). +class BillingService extends ChangeNotifier { + BillingService({required this.entitlements, required this.client}); + + final Entitlements entitlements; + final StoreClient client; + + StreamSubscription? _sub; + final Map _products = {}; + + bool _available = false; + bool _busy = false; + bool _initialised = false; + String? _error; + + bool get available => _available; + bool get busy => _busy; + bool get initialised => _initialised; + String? get error => _error; + bool get adsRemoved => entitlements.adsRemoved; + + StoreProduct? product(String id) => _products[id]; + Iterable get products => _products.values; + + /// True when the store answered and offered at least one product. + bool get canPurchase => _available && _products.isNotEmpty; + + Future init() async { + if (_initialised) return; + _initialised = true; + _sub = client.events.listen(_onEvent); + + try { + _available = await client.isAvailable(); + } catch (e) { + _available = false; + _error = 'Play Store nicht erreichbar'; + } + if (!_available) { + notifyListeners(); + return; + } + await refreshProducts(); + // Owned products are re-delivered through the event stream. + await restore(silent: true); + } + + Future refreshProducts() async { + if (!_available) return; + try { + final found = await client.queryProducts(ProductIds.offered); + _products + ..clear() + ..addEntries(found.map((p) => MapEntry(p.id, p))); + _error = found.isEmpty ? 'Keine Produkte im Play Store angelegt' : null; + } catch (e) { + _error = 'Produkte konnten nicht geladen werden'; + } + notifyListeners(); + } + + /// Starts the purchase flow. The result arrives asynchronously via the + /// stream - this only reports whether the flow could be started at all. + Future buy(String productId) async { + final item = _products[productId]; + if (item == null) { + _error = 'Produkt nicht verfügbar'; + notifyListeners(); + return false; + } + _busy = true; + _error = null; + notifyListeners(); + try { + final started = await client.buy(item); + if (!started) _error = 'Kauf konnte nicht gestartet werden'; + return started; + } catch (e) { + _error = 'Kauf abgebrochen: $e'; + return false; + } finally { + _busy = false; + notifyListeners(); + } + } + + Future restore({bool silent = false}) async { + if (!_available) return; + _busy = true; + notifyListeners(); + try { + await client.restore(); + } catch (e) { + if (!silent) _error = 'Wiederherstellen fehlgeschlagen'; + } finally { + _busy = false; + notifyListeners(); + } + } + + Future _onEvent(PurchaseEvent event) async { + switch (event.state) { + case PurchaseState.purchased: + case PurchaseState.restored: + // Grant first, then complete: a crash in between re-delivers the + // purchase instead of losing it. + await entitlements.grant(event.productId); + await client.complete(event); + _error = null; + break; + case PurchaseState.pending: + _error = 'Kauf wird geprüft (pending)'; + break; + case PurchaseState.canceled: + _error = null; + break; + case PurchaseState.error: + _error = event.error ?? 'Kauf fehlgeschlagen'; + break; + } + notifyListeners(); + } + + @override + void dispose() { + _sub?.cancel(); + super.dispose(); + } +} diff --git a/app/lib/src/billing/entitlements.dart b/app/lib/src/billing/entitlements.dart new file mode 100644 index 0000000..cb15e70 --- /dev/null +++ b/app/lib/src/billing/entitlements.dart @@ -0,0 +1,52 @@ +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'models.dart'; + +/// Non-consumable products the player owns, persisted on the device. +/// +/// The Play Console is the source of truth for money; this is the local mirror +/// that the UI and the ad gate read. `BillingService` only grants after the +/// store reported `purchased` or `restored`, and every grant is written through +/// to disk immediately. +class Entitlements extends ChangeNotifier { + Entitlements._(this._prefs, this._owned); + + static const String storageKey = 'iron_arc.entitlements'; + + final SharedPreferences _prefs; + final Set _owned; + + static Future load() async { + final prefs = await SharedPreferences.getInstance(); + final owned = prefs.getStringList(storageKey)?.toSet() ?? {}; + return Entitlements._(prefs, owned); + } + + Set get owned => Set.unmodifiable(_owned); + + bool owns(String productId) => _owned.contains(productId); + + /// Interstitials are hidden for owners; rewarded video stays opt-in. + bool get adsRemoved => owns(ProductIds.removeAds); + + Future grant(String productId) async { + if (!_owned.add(productId)) return; + await _prefs.setStringList(storageKey, _owned.toList()); + notifyListeners(); + } + + /// Used when the store reports that a product is no longer owned (refund). + Future revoke(String productId) async { + if (!_owned.remove(productId)) return; + await _prefs.setStringList(storageKey, _owned.toList()); + notifyListeners(); + } + + Future clearAll() async { + if (_owned.isEmpty) return; + _owned.clear(); + await _prefs.remove(storageKey); + notifyListeners(); + } +} diff --git a/app/lib/src/billing/models.dart b/app/lib/src/billing/models.dart new file mode 100644 index 0000000..c98ada0 --- /dev/null +++ b/app/lib/src/billing/models.dart @@ -0,0 +1,60 @@ +/// Product catalogue. Ids must match the entries created in the Play Console - +/// prices are **never** hardcoded in the app, the store returns them. +/// +/// Only [removeAds] is wired into the UI so far (M7c); the rest of the table in +/// docs/monetization.md needs the economy that does not exist yet. +abstract final class ProductIds { + /// Non-consumable: hides interstitials. Rewarded video stays opt-in. + static const String removeAds = 'remove_ads'; + + /// Documents the seasonal pass that will follow in MVP-3. + static const String seasonPass = 'season_pass'; + + /// Consumable hard currency - needs server-side bookkeeping, not wired yet. + static const String coresSmall = 'cores_small'; + + static const Set all = {removeAds, seasonPass, coresSmall}; + + /// Products the UI offers today. + static const Set offered = {removeAds}; +} + +/// One purchasable item as the store describes it. +class StoreProduct { + const StoreProduct({ + required this.id, + required this.title, + required this.price, + this.raw, + }); + + final String id; + final String title; + final String price; + final Object? raw; + + @override + String toString() => '$id ($price)'; +} + +/// State of a purchase event, mapped from the platform. +enum PurchaseState { pending, purchased, restored, canceled, error } + +class PurchaseEvent { + const PurchaseEvent({ + required this.productId, + required this.state, + this.error, + this.complete = false, + this.raw, + }); + + final String productId; + final PurchaseState state; + final String? error; + + /// True when the platform waits for `completePurchase` (Play: acknowledge + /// within three days, otherwise the purchase is refunded automatically). + final bool complete; + final Object? raw; +} diff --git a/app/lib/src/billing/store_client.dart b/app/lib/src/billing/store_client.dart new file mode 100644 index 0000000..362cd83 --- /dev/null +++ b/app/lib/src/billing/store_client.dart @@ -0,0 +1,106 @@ +import 'dart:async'; + +import 'package:in_app_purchase/in_app_purchase.dart'; + +import 'models.dart'; + +/// Thin seam over the platform billing plugin. +/// +/// Everything above this interface (entitlements, UI) is testable with a fake +/// implementation; only [PlayStoreClient] touches the real store. +abstract class StoreClient { + /// Emits every purchase state change, including restored purchases. + Stream get events; + + Future isAvailable(); + + Future> queryProducts(Set ids); + + /// Returns false when the platform refused to start the flow. + Future buy(StoreProduct product); + + /// Acknowledge/consume - must happen or Play refunds after three days. + Future complete(PurchaseEvent event); + + /// Re-delivers owned non-consumables through [events]. + Future restore(); + + Future dispose(); +} + +/// Google Play implementation. +class PlayStoreClient implements StoreClient { + PlayStoreClient({InAppPurchase? iap}) : _iap = iap ?? InAppPurchase.instance { + _subscription = _iap.purchaseStream.listen(_onPurchases); + } + + final InAppPurchase _iap; + late final StreamSubscription> _subscription; + final StreamController _out = StreamController.broadcast(); + + @override + Stream get events => _out.stream; + + @override + Future isAvailable() => _iap.isAvailable(); + + @override + Future> queryProducts(Set ids) async { + final response = await _iap.queryProductDetails(ids); + if (response.error != null) { + throw StateError(response.error!.message); + } + return response.productDetails + .map((d) => StoreProduct( + id: d.id, + title: d.title, + price: d.price, + raw: d, + )) + .toList(growable: false); + } + + @override + Future buy(StoreProduct product) async { + final details = product.raw; + if (details is! ProductDetails) return false; + return _iap.buyNonConsumable( + purchaseParam: PurchaseParam(productDetails: details), + ); + } + + @override + Future complete(PurchaseEvent event) async { + final raw = event.raw; + if (raw is PurchaseDetails && raw.pendingCompletePurchase) { + await _iap.completePurchase(raw); + } + } + + @override + Future restore() => _iap.restorePurchases(); + + void _onPurchases(List purchases) { + for (final p in purchases) { + _out.add(PurchaseEvent( + productId: p.productID, + state: switch (p.status) { + PurchaseStatus.pending => PurchaseState.pending, + PurchaseStatus.purchased => PurchaseState.purchased, + PurchaseStatus.restored => PurchaseState.restored, + PurchaseStatus.canceled => PurchaseState.canceled, + PurchaseStatus.error => PurchaseState.error, + }, + error: p.error?.message, + complete: p.pendingCompletePurchase, + raw: p, + )); + } + } + + @override + Future dispose() async { + await _subscription.cancel(); + await _out.close(); + } +} diff --git a/app/pubspec.lock b/app/pubspec.lock index 516fd8f..148ecee 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -136,6 +136,38 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.2" + in_app_purchase: + dependency: "direct main" + description: + name: in_app_purchase + sha256: d8317ec2ed6fe33199957d67ee67e08a4fd4871ef93b91d7611d8ee560892afc + url: "https://pub.dev" + source: hosted + version: "3.3.1" + in_app_purchase_android: + dependency: transitive + description: + name: in_app_purchase_android + sha256: b76ab601573f8a848e72d015496257235066ba3479bef6300482239f417e0d72 + url: "https://pub.dev" + source: hosted + version: "0.5.5" + in_app_purchase_platform_interface: + dependency: transitive + description: + name: in_app_purchase_platform_interface + sha256: "0b0076cac8ce4fa7048f01e76af8b123aeb6a7c4e0dea2a5206d6664454f3e36" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + in_app_purchase_storekit: + dependency: transitive + description: + name: in_app_purchase_storekit + sha256: de4f86b7bed848cd60a32c93affad868ba06a5276c007e23878855558094ff43 + url: "https://pub.dev" + source: hosted + version: "0.4.15" jni: dependency: transitive description: @@ -152,6 +184,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.0" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.dev" + source: hosted + version: "4.12.0" leak_tracker: dependency: transitive description: diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 5890e46..1fd7f82 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 0.8.2+12 +version: 0.9.0+13 environment: sdk: ^3.13.4 @@ -40,6 +40,7 @@ dependencies: shared_preferences: ^2.5.6 google_mobile_ads: ^9.2.0 url_launcher: ^6.3.0 + in_app_purchase: ^3.2.0 dev_dependencies: flutter_test: diff --git a/app/test/billing_test.dart b/app/test/billing_test.dart new file mode 100644 index 0000000..d3a6f70 --- /dev/null +++ b/app/test/billing_test.dart @@ -0,0 +1,227 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:iron_arc/src/billing/billing_service.dart'; +import 'package:iron_arc/src/billing/entitlements.dart'; +import 'package:iron_arc/src/billing/models.dart'; +import 'package:iron_arc/src/billing/store_client.dart'; +import 'package:iron_arc/src/ui/links.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Stand-in for Google Play: the module is testable before the Console has any +/// products, which is the only way to verify the grant/complete logic here. +class FakeStore implements StoreClient { + FakeStore({ + this.available = true, + List? products, + this.purchaseStarts = true, + this.throwOnQuery = false, + }) : products = products ?? _defaultProducts; + + static const List _defaultProducts = [ + StoreProduct( + id: ProductIds.removeAds, title: 'Werbung entfernen', price: '4,99 €'), + ]; + + final bool available; + final bool purchaseStarts; + final bool throwOnQuery; + final List products; + + final StreamController _events = + StreamController.broadcast(); + + int completedCalls = 0; + int restoreCalls = 0; + int buyCalls = 0; + bool disposed = false; + + @override + Stream get events => _events.stream; + + void emit(PurchaseEvent event) => _events.add(event); + + @override + Future isAvailable() async => available; + + @override + Future> queryProducts(Set ids) async { + if (throwOnQuery) throw StateError('store down'); + return products.where((p) => ids.contains(p.id)).toList(); + } + + @override + Future buy(StoreProduct product) async { + buyCalls++; + return purchaseStarts; + } + + /// Mirrors Play: acknowledging is only required (and only counted) when the + /// platform flags `pendingCompletePurchase`. + @override + Future complete(PurchaseEvent event) async { + if (event.complete) completedCalls++; + } + + @override + Future restore() async => restoreCalls++; + + @override + Future dispose() async { + disposed = true; + await _events.close(); + } +} + +Future _service(FakeStore store) async { + final entitlements = await Entitlements.load(); + final billing = BillingService(entitlements: entitlements, client: store); + await billing.init(); + return billing; +} + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + test('query on start exposes the catalogue and restores silently', () async { + final store = FakeStore(); + final billing = await _service(store); + + expect(billing.available, isTrue); + expect(billing.canPurchase, isTrue); + expect(billing.product(ProductIds.removeAds)?.price, '4,99 €'); + // Restoring on start is the documented rule (monetization.md §3). + expect(store.restoreCalls, 1); + + billing.dispose(); + await store.dispose(); + }); + + test('purchase grants the entitlement and is completed', () async { + final store = FakeStore(); + final billing = await _service(store); + + expect(await billing.buy(ProductIds.removeAds), isTrue); + expect(billing.adsRemoved, isFalse, + reason: 'nothing is granted before the store answers'); + + store.emit(const PurchaseEvent( + productId: ProductIds.removeAds, + state: PurchaseState.purchased, + complete: true, + )); + await pumpEventQueue(); + + expect(billing.entitlements.adsRemoved, isTrue); + expect(store.completedCalls, 1, + reason: 'Play refunds purchases that are not acknowledged'); + + billing.dispose(); + await store.dispose(); + }); + + test('pending purchases are reported but never granted', () async { + final store = FakeStore(); + final billing = await _service(store); + + store.emit(const PurchaseEvent( + productId: ProductIds.removeAds, + state: PurchaseState.pending, + complete: true, + )); + await pumpEventQueue(); + + expect(billing.entitlements.adsRemoved, isFalse); + expect(store.completedCalls, 0); + expect(billing.error, contains('pending')); + + billing.dispose(); + await store.dispose(); + }); + + test('cancel and error leave the entitlement untouched', () async { + final store = FakeStore(); + final billing = await _service(store); + + store.emit(const PurchaseEvent( + productId: ProductIds.removeAds, state: PurchaseState.canceled)); + await pumpEventQueue(); + expect(billing.entitlements.adsRemoved, isFalse); + expect(billing.error, isNull); + + store.emit(const PurchaseEvent( + productId: ProductIds.removeAds, + state: PurchaseState.error, + error: 'ITEM_ALREADY_OWNED')); + await pumpEventQueue(); + expect(billing.entitlements.adsRemoved, isFalse); + expect(billing.error, 'ITEM_ALREADY_OWNED'); + + billing.dispose(); + await store.dispose(); + }); + + test('restored purchases grant too (reinstall path)', () async { + final store = FakeStore(); + final billing = await _service(store); + + store.emit(const PurchaseEvent( + productId: ProductIds.removeAds, + state: PurchaseState.restored, + complete: false, + )); + await pumpEventQueue(); + + expect(billing.adsRemoved, isTrue); + expect(store.completedCalls, 0, reason: 'restores need no acknowledgement'); + + billing.dispose(); + await store.dispose(); + }); + + test('entitlement survives a restart', () async { + final first = await _service(FakeStore()); + await first.entitlements.grant(ProductIds.removeAds); + expect(first.entitlements.adsRemoved, isTrue); + first.dispose(); + + final second = await Entitlements.load(); + expect(second.adsRemoved, isTrue, reason: 'written through to disk'); + + await second.clearAll(); + expect(second.adsRemoved, isFalse); + }); + + test('missing store: no crash, clear error, purchase disabled', () async { + final store = FakeStore(available: false); + final billing = await _service(store); + + expect(billing.available, isFalse); + expect(billing.canPurchase, isFalse); + expect(await billing.buy(ProductIds.removeAds), isFalse); + expect(billing.error, isNotNull); + + billing.dispose(); + await store.dispose(); + }); + + test('store that throws while querying is handled', () async { + final store = FakeStore(throwOnQuery: true); + final billing = await _service(store); + + expect(billing.canPurchase, isFalse); + expect(billing.error, 'Produkte konnten nicht geladen werden'); + + billing.dispose(); + await store.dispose(); + }); + + test('deletion request carries the device id and the contact address', () { + final uri = deletionRequestUri('dev-abc123'); + + expect(uri.scheme, 'mailto'); + expect(uri.path, kContactEmail); + expect(Uri.decodeComponent(uri.query), contains('dev-abc123')); + expect(Uri.decodeComponent(uri.query), contains('Datenlöschung')); + }); +} diff --git a/build/native-debug-symbols.zip b/build/native-debug-symbols.zip index a7e0aac..87e47f0 100644 Binary files a/build/native-debug-symbols.zip and b/build/native-debug-symbols.zip differ diff --git a/docs/compliance-play-store.md b/docs/compliance-play-store.md index 4bed25b..8a197ad 100644 --- a/docs/compliance-play-store.md +++ b/docs/compliance-play-store.md @@ -45,7 +45,7 @@ Legende: `[ ]` offen · `[x]` erledigt · `[~]` teilweise/geplant mit Owner | `[ ]` | Altersfreigabe (IARC) | Erwartung: USK 12 / PEGI 12 (kompetitive Gewalt, keine realistischen Darstellungen, keine Sprache) | | `[x]` | Datenschutzerklärung | URL gesetzt: `store/privacy-policy.html` im öffentlichen Gitea-Repo (Rohdatei, HTTP 200, `text/plain` – funktioniert, aber unschön; besserer Host in [status/blocked.md](status/blocked.md) §3b). In-App-Einstieg implementiert und auf Gerät verifiziert (Zahnrad → „Datenschutzerklärung“, `url_launcher`), Release-Guard gegen Platzhalter. Deckt: Geräte-ID, Match-/Replay-Daten, AdMob (Werbe-ID, IP, Geräteinformationen), ungefährer Standort aus IP. **Keine** Analytics-, Crash- oder Firebase-SDKs im Build | | `[~]` | Data-Safety-Formular | Angaben aus [privacy-policy.md](privacy-policy.md) übernehmen: Geräte-IDs (App-Funktion), ungefährer Standort aus IP + Werbe-ID (durch AdMob, Weitergabe an Google), **keine** Crash-Logs, **keine** Käufe (bis M7c) | -| `[ ]` | Account-Löschung | In-App **und** Web-URL, da Accounts existieren (Firebase/Leaderboard) | +| `[x]` | Account-Löschung | **Keine Accounts** in der App (Geräte-ID genügt). Datenlöschung: Einstellungen → „Datenlöschung anfragen“ (vorausgefüllte E-Mail, auf Gerät verifiziert) plus „Lokale Daten löschen“ (Warteschlange, Replays, Geräte-ID). Damit ist die Play-Anforderung erfüllt | | `[ ]` | Nachrichten-App? | Nein | | `[ ]` | News-App? | Nein | @@ -65,8 +65,8 @@ Legende: `[ ]` offen · `[x]` erledigt · `[~]` teilweise/geplant mit Owner | Status | Anforderung | Umsetzung | |---|---|---| -| `[ ]` | Nur **Play Billing** für digitale Güter | Keine externen Payment-Links, kein Stripe/PayPal im Spiel | -| `[ ]` | „Käufe wiederherstellen" | `queryPurchases` beim Start + Button in Settings | +| `[x]` | Nur **Play Billing** für digitale Güter | `in_app_purchase` (Play Billing Library), keine externen Payment-Links. `com.android.vending.BILLING` im gemergten Manifest geprüft | +| `[x]` | „Käufe wiederherstellen" | `restorePurchases` beim Start + „Käufe wiederherstellen“ im Einstellungen-Sheet | | `[ ]` | Pending Transactions | Korrekt behandeln (z. B. Barzahlung), keine Doppel-Gutschrift | | `[ ]` | Preise & MwSt. | Über Play Console gepflegt, nicht hartkodiert | | `[ ]` | Keine Lootboxen mit Zufall | Kosmetik direkt kaufbar; keine Odds-Disclosure nötig | @@ -112,7 +112,8 @@ Ein Release ist **nicht** erlaubt, wenn einer dieser Punkte offen ist: 2. `targetSdk` < 36 oder 16-KB-Check fehlgeschlagen. 3. Keine `native-debug-symbols.zip` im Upload. 4. Data-Safety-Formular unvollständig. -5. Account-Löschung nicht implementiert. +5. ~~Account-Löschung nicht implementiert~~ → **erledigt 2026-10-25**: keine Accounts; Daten- und + lokale Löschung in der App (Einstellungen). 6. ~~Keine Datenschutz-Nachricht in AdMob~~ → **erledigt 2026-10-25**: Nachricht veröffentlicht, Formular erscheint, `consent=obtained`, Ads laden erst danach (Nachweis in [monetization.md](monetization.md#7b-ump-consent-m7b-umgesetzt)). diff --git a/docs/decisions.md b/docs/decisions.md index 54c84d0..6621952 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -79,3 +79,22 @@ AdMob-Konto sperren. Test-Units liefern zuverlaessig Fill und sind dafuer vorges **Naechster Schritt:** echte Unit-IDs (Rewarded, Interstitial, ggf. Banner) vom Auftraggeber, dann Ersatz der Konstanten in `app/lib/src/ads/ads_service.dart` — **erst nach** implementiertem UMP-Consent. + +## D6 — Käufe: lokal freigeschaltet, serverseitig geprüft erst in MVP-2 (2026-10-25) + +**Entscheidung:** M7c schaltet Entitlements **lokal** frei (`iron_arc.entitlements`), nachdem +der Play Store `purchased`/`restored` gemeldet hat. Es gibt noch keine serverseitige +Belegprüfung und keine Real-time Developer Notifications. + +**Begründung:** Der Referee kennt keine Accounts und keine Inventare; ein gekaufter +Skin/Pass existiert nicht. „Remove Ads“ wirkt ausschließlich auf dem Gerät, ein gefälschter +Besitzstand schadet also niemandem außer dem Fälscher. Eine Verifikation wäre Aufwand ohne +Gegenwert, solange keine serverseitigen Vorteile verkauft werden. + +**Konsequenzen:** +- Ein manipuliertes Gerät kann sich Interstitials selbst abschalten. Akzeptiert. +- Sobald käufliche Vorteile den Server berühren (Cores, Season Pass, Loadout-Slots), ist die + Prüfung Pflicht: `purchases.products.get` mit Service-Account plus RTDN-Webhook, und die + Entitlements wandern in die Datenbank statt in SharedPreferences. +- Dasselbe gilt für Erstattungen: heute bleibt ein erstatteter Kauf aktiv, bis der Nutzer die + App-Daten löscht. Bei serverseitigen Vorteilen muss der Webhook entziehen. diff --git a/docs/monetization.md b/docs/monetization.md index b88874a..9148263 100644 --- a/docs/monetization.md +++ b/docs/monetization.md @@ -145,6 +145,43 @@ Das war der Release-Blocker: ohne Nachricht hätte die App in der EU ohne Einwil Damit sind die drei Play-Anforderungen erfüllt: Einwilligung **vor** der ersten Ad-Anfrage, keine Ads ohne Zustimmung, und ein **dauerhafter** Weg, die Einwilligung zu ändern. +## 7c. Play Billing (M7c, umgesetzt 2026-10-25) + +**Katalog** aus §3, aber bewusst klein gestartet: nur **Remove Ads** (`remove_ads`, +Non-Consumable) ist im UI. Season Pass, Starter Pack und Cores brauchen eine Ökonomie, +die es noch nicht gibt – die IDs stehen bereits in `ProductIds`, damit die Erweiterung +eine Datenzeile ist und kein Umbau. + +| Baustein | Datei | +|---|---| +| Katalog + Ereignismodelle | `lib/src/billing/models.dart` | +| Store-Schnittstelle + Play-Implementierung | `lib/src/billing/store_client.dart` | +| Besitzstand (persistiert) | `lib/src/billing/entitlements.dart` | +| Ablaufsteuerung | `lib/src/billing/billing_service.dart` | +| UI | Einstellungen-Sheet: „Werbung entfernen“, „Käufe wiederherstellen“ | + +**Regeln, die eingehalten werden** + +1. Preise kommen ausschließlich aus dem Store (`queryProductDetails`), nichts ist hartkodiert. +2. `restorePurchases` läuft **beim Start** – Neuinstallation stellt den Besitz wieder her. +3. `purchased`/`restored` → erst Entitlement schreiben, dann `completePurchase` + (Play erstattet nach 3 Tagen nicht bestätigte Käufe automatisch). +4. `pending` wird gemeldet, aber **nie** freigeschaltet (z. B. Barzahlung im Laden). +5. Besitz wird sofort persistiert (`iron_arc.entitlements`), damit ein Absturz zwischen + Store-Ereignis und Bestätigung nichts verliert. +6. Remove Ads schaltet nur **Interstitials** ab (`AdsService.adsRemoved`); Rewarded bleibt + freiwillig – sonst wäre die Belohnung für Käufer weg. +7. Ohne Play-Dienst (Seitelladen, kein Konto) gibt es keinen Crash, sondern einen klaren + Zustand: „Play Store nicht erreichbar“ bzw. „Keine Produkte im Play Store angelegt“. + +**Verifikation:** 9 Unit-Tests mit einem Fake-Store (`app/test/billing_test.dart`) decken +Kauf, Restore, Pending, Abbruch, Fehler, Neustart-Persistenz und den Fall „kein Store“ ab. +Auf dem Gerät wurde zusätzlich geprüft, dass die App den echten Billing-Dienst anspricht +(`IInAppBillingService` im Logcat) und ohne angelegte Produkte sauber degradiert. + +**Noch offen:** serverseitige Belegprüfung (siehe [D6](decisions.md)) und die Produkte +im Play Console (siehe [status/blocked.md](status/blocked.md)). + ## 8. Offene Punkte 1. Ads schon in MVP-1 (Test-IDs) oder erst M7? (siehe README, offene Entscheidungen) diff --git a/docs/status/autonomous-log.md b/docs/status/autonomous-log.md index b1b526a..a144185 100644 --- a/docs/status/autonomous-log.md +++ b/docs/status/autonomous-log.md @@ -230,6 +230,40 @@ unter der Oberfläche → entfernt; Boden pro Frame → `ui.Picture` je Terrain- - Terrain-Cache braucht die Terrain-Version, sonst friert der Boden nach dem ersten Krater ein (gleiche Klasse Fehler wie das HUD-`onLoad`-Problem aus M3a). +## M7c — Play Billing + Löschpfad (erledigt 2026-10-25) + +**Umfang:** `remove_ads` (Non-Consumable) ist der erste echte Kauf; der Rest des Katalogs aus +monetization.md §3 wartet auf eine Ökonomie, die IDs stehen aber schon in `ProductIds`. + +| Datei | Aufgabe | +|---|---| +| `billing/models.dart` | Produkt-IDs, `StoreProduct`, `PurchaseEvent`/`PurchaseState` | +| `billing/store_client.dart` | Schnittstelle + `PlayStoreClient` über `in_app_purchase` | +| `billing/entitlements.dart` | Besitzstand, persistiert, `ChangeNotifier` | +| `billing/billing_service.dart` | Ablauf: Query, Kauf, Restore, Grant+Complete, Fehlerzustände | +| `main.dart` | Shop-Bereich im Einstellungen-Sheet, Ads-Gate, lokale Löschung | +| `test/billing_test.dart` | 9 Tests mit Fake-Store | + +**Regeln, die den Unterschied machen** +- Erst Entitlement schreiben, **dann** `completePurchase` — Play erstattet nach drei Tagen + nicht bestätigte Käufe automatisch. +- `pending` wird angezeigt, aber nie freigeschaltet. +- `restorePurchases` beim Start, sonst verliert eine Neuinstallation den Kauf. +- Remove Ads schaltet nur Interstitials ab; Rewarded bleibt freiwillig verfügbar. +- Kein Play-Dienst → kein Crash, sondern „Play Store nicht erreichbar“ bzw. „Keine Produkte + im Play Store angelegt“. + +**Verifikation:** 17 Tests grün (9 neu), `flutter analyze` sauber, `com.android.vending.BILLING` +im gemergten Manifest. Auf dem Gerät spricht die App den echten Dienst an +(`IInAppBillingService`-Transaktionen im Logcat) und degradiert ohne angelegte Produkte sauber — +der Screenshot der Einstellungen zeigt genau diese Meldung. + +**Entscheidung:** [D6](decisions.md) — lokal freigeschaltet, serverseitige Belegprüfung erst +wenn käufliche Vorteile den Server berühren. + +**Löschpfad:** keine Accounts → Play-Anforderung über Datenlöschung (E-Mail vorausgefüllt) +plus „Lokale Daten löschen“ (Warteschlange, Replays, Geräte-ID) erfüllt. + ## Nächste Schritte (aktualisiert) 1. `bundletool build-apks --connected-device` aus `~/exports/iron-arc-0.7.0.aab` → Install → Smoke. diff --git a/docs/status/blocked.md b/docs/status/blocked.md index 44181dc..03fb173 100644 --- a/docs/status/blocked.md +++ b/docs/status/blocked.md @@ -46,6 +46,17 @@ und AdMob funktioniert das, wirkt im Review aber unsauber. 2. Prüfen: `curl -sI | grep -i content-type` → muss `text/html` sein. 3. Die eine Zeile in `app/lib/src/ui/links.dart` ändern, neu bauen, fertig. +## 3c. Produkt im Play Console anlegen (blockiert den ersten Kauf) + +Die App fragt `remove_ads` ab; ohne Eintrag im Console steht dort +„Keine Produkte im Play Store angelegt“ (verifiziert, kein Crash). + +1. Console → Monetarisieren → Produkte → In-App-Produkt anlegen: ID **`remove_ads`** + (muss exakt so heißen), Typ *Einmalig*, Preis 4,99 €. +2. Aktivieren; Produkte sind erst mit einem veröffentlichten Track (Internal Testing genügt) + abrufbar. +3. Lizenz-Testkonto im Console eintragen, dann erscheint der Preis in der App. + ## 4. Echte AdMob-Unit-IDs Aktuell Test-IDs (liefern immer Testanzeigen). Sobald die echten IDs da sind, trage ich sie in