From 8e2d37ae0c32134ae1e07ab5ce94ff42431efd6b Mon Sep 17 00:00:00 2001 From: ShiftHackZ Date: Wed, 2 Dec 2026 19:11:35 +0200 Subject: [PATCH] Add Google Play tips and unify donation options Add a Play-only consumable tip jar and unify donation options across platforms. Cover billing, donation UI, and catalog behavior with unit tests and discover variant coverage reports in CI. --- .github/workflows/project_tests.yml | 17 +- .../shifthackz/aisdv1/buildlogic/Jacoco.kt | 12 +- .../src/androidMain/res/values-de/strings.xml | 5 +- .../src/androidMain/res/values-ru/strings.xml | 5 +- .../src/androidMain/res/values-tr/strings.xml | 5 +- .../src/androidMain/res/values-uk/strings.xml | 5 +- .../src/androidMain/res/values-zh/strings.xml | 5 +- .../src/androidMain/res/values/strings.xml | 5 +- .../core/localization/LocalizationTest.kt | 33 ++ .../repository/DonationRepositoryImplTest.kt | 36 +++ ...etchOrGetDonationOptionsUseCaseImplTest.kt | 34 +- feature/iap/build.gradle.kts | 19 +- .../aisdv1/feature/iap/NoOpIapGateway.kt | 2 +- .../feature/iap/di/IapModule.android.kt | 6 +- .../aisdv1/feature/iap/di/AndroidIapModule.kt | 14 + .../aisdv1/feature/iap/di/AndroidIapModule.kt | 14 + .../feature/iap/PlayIapActivityCallbacks.kt | 33 ++ .../aisdv1/feature/iap/PlayIapGateway.kt | 291 ++++++++++++++++++ .../aisdv1/feature/iap/di/AndroidIapModule.kt | 15 + .../aisdv1/feature/iap/FossIapModuleTest.kt | 41 +++ .../aisdv1/feature/iap/NoOpIapGatewayTest.kt | 2 +- .../aisdv1/feature/iap/PlayIapCatalogTest.kt | 192 ++++++++++++ .../aisdv1/feature/iap/PlayIapFixture.kt | 139 +++++++++ .../aisdv1/feature/iap/PlayIapPurchaseTest.kt | 263 ++++++++++++++++ .../aisdv1/feature/iap/PlayIapRecoveryTest.kt | 194 ++++++++++++ gradle/libs.versions.toml | 2 + presentation/donate/build.gradle.kts | 1 + .../donate/di/DonateScreenTabs.android.kt | 12 - .../di/WaysToSupportSections.android.kt | 17 + .../donate/preview/DonatePreview.kt | 31 +- .../donate/preview/DonatePreviewCase.kt | 8 +- .../preview/DonatePreviewParameterProvider.kt | 26 +- .../preview/IapWaysToSupportPreviewCases.kt | 143 +++++++++ .../donate/preview/TipJarPreviewCase.kt | 15 - .../preview/TipJarPreviewParameterProvider.kt | 54 ---- .../donate/preview/TipJarPreviews.android.kt | 54 ---- .../donate/DonateContainerTest.kt | 28 -- .../donate/DonatePreviewCoverageTest.kt | 53 ++-- .../donate/DonateRouteIntegrationTest.kt | 177 ++++++++++- .../presentation/donate/di/DiModuleTest.kt | 42 ++- .../options/DonationOptionsContentTest.kt | 25 +- .../preview/DonatePreviewRenderingTest.kt | 14 +- .../donate/tipjar/TipJarContentTest.kt | 21 +- .../donate/tipjar/TipJarViewModelTest.kt | 36 +++ .../presentation/donate/DonateLoading.kt | 31 +- .../presentation/donate/DonateScreen.kt | 12 +- .../presentation/donate/DonateScreenTab.kt | 2 +- .../donate/di/DonateViewModelModule.kt | 18 +- .../donate/options/DonationGroupCard.kt | 10 +- .../options/DonationOptionsCatalogStatus.kt | 50 --- .../donate/options/DonationOptionsContent.kt | 94 ------ ...onsScreen.kt => DonationOptionsSection.kt} | 28 +- .../donate/options/DonationOptionsStrings.kt | 42 --- .../donate/supporters/SupportersContent.kt | 4 +- .../donate/tipjar/TipJarContent.kt | 76 ----- .../donate/tipjar/TipJarScreen.kt | 43 --- .../donate/tipjar/TipJarSection.kt | 27 ++ .../donate/tipjar/TipJarStrings.kt | 45 --- .../donate/ways/WaysToSupportContent.kt | 72 +++++ .../donate/ways/WaysToSupportFeedback.kt | 98 ++++++ .../donate/ways/WaysToSupportIntroduction.kt | 55 ++++ .../donate/ways/WaysToSupportScreen.kt | 62 ++++ .../donate/ways/WaysToSupportSection.kt | 8 + .../donate/di/DonateScreenTabs.ios.kt | 12 - .../donate/di/WaysToSupportSections.ios.kt | 12 + .../presentation/donate/di/IosDiModuleTest.kt | 9 +- 66 files changed, 2242 insertions(+), 714 deletions(-) create mode 100644 feature/iap/src/foss/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt create mode 100644 feature/iap/src/full/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt create mode 100644 feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapActivityCallbacks.kt create mode 100644 feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapGateway.kt create mode 100644 feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt create mode 100644 feature/iap/src/testFoss/java/com/shifthackz/aisdv1/feature/iap/FossIapModuleTest.kt rename feature/iap/src/{androidUnitTest/kotlin => testFull/java}/com/shifthackz/aisdv1/feature/iap/NoOpIapGatewayTest.kt (93%) create mode 100644 feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapCatalogTest.kt create mode 100644 feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapFixture.kt create mode 100644 feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapPurchaseTest.kt create mode 100644 feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapRecoveryTest.kt delete mode 100644 presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.android.kt create mode 100644 presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.android.kt create mode 100644 presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/IapWaysToSupportPreviewCases.kt delete mode 100644 presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewCase.kt delete mode 100644 presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewParameterProvider.kt delete mode 100644 presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviews.android.kt delete mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsCatalogStatus.kt delete mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContent.kt rename presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/{DonationOptionsScreen.kt => DonationOptionsSection.kt} (69%) delete mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsStrings.kt delete mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContent.kt delete mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarScreen.kt create mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarSection.kt delete mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarStrings.kt create mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportContent.kt create mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportFeedback.kt create mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportIntroduction.kt create mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportScreen.kt create mode 100644 presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportSection.kt delete mode 100644 presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.ios.kt create mode 100644 presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.ios.kt diff --git a/.github/workflows/project_tests.yml b/.github/workflows/project_tests.yml index d04429501c..7415b53170 100644 --- a/.github/workflows/project_tests.yml +++ b/.github/workflows/project_tests.yml @@ -561,12 +561,23 @@ jobs: name: android-jvm-test-coverage path: | build/reports/jacoco/ciCoverage/ + **/build/reports/jacoco/variants/ **/build/reports/tests/test*UnitTest/ **/build/test-results/test*UnitTest/*.xml if-no-files-found: warn - - name: Verify coverage report - run: test -s build/reports/jacoco/ciCoverage/ciCoverage.xml + - name: Verify coverage reports + id: coverage-reports + shell: bash + run: | + files=build/reports/jacoco/ciCoverage/ciCoverage.xml + test -s "$files" + variant_reports=$(find . -type f -path '*/build/reports/jacoco/variants/*/coverage.xml' | sort) + while IFS= read -r report && [[ -n "$report" ]]; do + test -s "$report" || { echo "Missing or empty coverage report: $report" >&2; exit 1; } + files+=",${report#./}" + done <<< "$variant_reports" + printf 'files=%s\n' "$files" >> "$GITHUB_OUTPUT" # Public fork and Dependabot PRs use Codecov's tokenless public-PR uploads. # Keep this on pull_request; untrusted PR code must never receive base-repo secrets. @@ -575,7 +586,7 @@ jobs: with: token: ${{ secrets.CODECOV_TOKEN }} override_branch: ${{ github.actor == 'dependabot[bot]' && github.event_name == 'pull_request' && format('pr{0}:{1}', github.event.pull_request.number, github.head_ref) || '' }} - files: build/reports/jacoco/ciCoverage/ciCoverage.xml + files: ${{ steps.coverage-reports.outputs.files }} disable_search: true fail_ci_if_error: true flags: android-unit diff --git a/build-logic/convention/src/main/kotlin/com/shifthackz/aisdv1/buildlogic/Jacoco.kt b/build-logic/convention/src/main/kotlin/com/shifthackz/aisdv1/buildlogic/Jacoco.kt index 85a5161a68..b0b79e7196 100644 --- a/build-logic/convention/src/main/kotlin/com/shifthackz/aisdv1/buildlogic/Jacoco.kt +++ b/build-logic/convention/src/main/kotlin/com/shifthackz/aisdv1/buildlogic/Jacoco.kt @@ -10,7 +10,8 @@ import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension /** * Registers coverage for enabled debug variants using their production class artifacts. - * CI selects debug for plain modules and fullDebug for modules with product flavors. + * CI aggregates debug for plain modules and fullDebug for flavored modules. Other variants + * write separate reports so their classes do not collide with the aggregate. * Shared Kotlin sources come from the Android compilation, including dependsOn source sets. * * @author Dmitriy Moroz @@ -21,6 +22,7 @@ internal fun Project.jacocoCodeCoverageReporting() { androidComponents.onVariants(androidComponents.selector().withBuildType("debug")) { variant -> if ((variant as? HasUnitTest)?.unitTest == null) return@onVariants + val isAggregateVariant = variant.name == "debug" || variant.name == "fullDebug" val capitalizedVariant = variant.name.replaceFirstChar(Char::titlecase) val testTaskName = "test${capitalizedVariant}UnitTest" val report = tasks.register("jacoco${capitalizedVariant}Report") { @@ -32,6 +34,12 @@ internal fun Project.jacocoCodeCoverageReporting() { xml.required.set(true) html.required.set(true) csv.required.set(false) + if (!isAggregateVariant) { + val variantReports = + layout.buildDirectory.dir("reports/jacoco/variants/${variant.name}") + xml.outputLocation.set(variantReports.map { it.file("coverage.xml") }) + html.outputLocation.set(variantReports.map { it.dir("html") }) + } } sourceDirectories.from(variant.sources.java?.all, variant.sources.kotlin?.all) @@ -57,7 +65,7 @@ internal fun Project.jacocoCodeCoverageReporting() { VariantCoverageReport::classFolders, ) - if (variant.name == "debug" || variant.name == "fullDebug") { + if (isAggregateVariant) { tasks.register("ciCoverage") { group = "verification" description = "Runs the selected Android/JVM unit tests and generates coverage." diff --git a/core/localization/src/androidMain/res/values-de/strings.xml b/core/localization/src/androidMain/res/values-de/strings.xml index 1b31887bcc..408e3c05df 100644 --- a/core/localization/src/androidMain/res/values-de/strings.xml +++ b/core/localization/src/androidMain/res/values-de/strings.xml @@ -556,7 +556,6 @@ Vielen Dank an diese großartigen Unterstützer ❤ SDAI ist eine Open-Source-Anwendung, die: • dir ermöglicht, mit KI Bilder zu erstellen;\n• dir die freie Wahl deines Generierungsanbieters lässt;\n• keine Werbung oder Telemetrie enthält und dich nicht ausspioniert;\n• quelloffen ist;\n• kostenlos genutzt werden kann. - Wenn du diese Software nützlich findest, vielen Dank für deine Unterstützung und dafür, dass du zum Fortbestand des Projekts beiträgst. Speicher Benachrichtigungen @@ -990,7 +989,7 @@ Weiter Skalierungsfaktor Unterstützungsmöglichkeiten - Wähle genau das unten angegebene Netzwerk. Dieselbe Adresse kann in mehreren Netzwerken verwendet werden. + Netzwerk: %1$s Adresse kopieren Adresse kopiert Spendenmöglichkeiten konnten nicht geladen werden. @@ -1000,7 +999,7 @@ Gespeicherte Spendenoptionen werden angezeigt. Die aktuellen Optionen sind nicht verfügbar. Musikpause Sieh dir das SDAI-Musikvideo von D10G3N auf YouTube an. - Unterstütze die Entwicklung mit einem freiwilligen Trinkgeld. Alle Funktionen bleiben ohne Trinkgeld verfügbar. + Spenden helfen dabei, SDAI weiterzuentwickeln. Alle Funktionen bleiben auch ohne Spende verfügbar. Unterstützungskäufe sind derzeit nicht verfügbar. Der Store konnte diese Anfrage nicht abschließen. Bitte versuche es erneut. Deine Unterstützungsanfrage wurde an Apple gesendet. diff --git a/core/localization/src/androidMain/res/values-ru/strings.xml b/core/localization/src/androidMain/res/values-ru/strings.xml index de6254c553..977f19a855 100644 --- a/core/localization/src/androidMain/res/values-ru/strings.xml +++ b/core/localization/src/androidMain/res/values-ru/strings.xml @@ -519,7 +519,6 @@ Спасибо этим замечательным людям за поддержку ❤ SDAI — это приложение с открытым исходным кодом, которое: • Предоставляет Вам возможность создавать изображения с помощью ИИ;\n• Предоставляет Вам свободу выбора провайдера генерации;\n• Нет рекламы, телеметрии, не шпионит за Вами;\n• ПО с открытым исходным кодом;\n• Вы можете использовать его бесплатно. - Если программа стала Вам полезной, спасибо за поддержку проекта и помощь в его развитии. Хранилище Push уведомления @@ -953,7 +952,7 @@ Продолжить Масштаб Способы поддержки - Выберите именно ту сеть, которая указана ниже. Разные сети могут иметь одинаковый адрес. + Сеть: %1$s Копировать адрес Адрес скопирован Не удалось загрузить способы поддержки. @@ -963,7 +962,7 @@ Показаны сохранённые способы поддержки. Не удалось загрузить актуальные. Музыкальная пауза Посмотрите клип SDAI от D10G3N на YouTube. - Поддержите разработку добровольными чаевыми. Все функции доступны без оплаты. + Пожертвования помогают развивать SDAI. Все функции доступны и без пожертвований. Покупки для поддержки сейчас недоступны. Магазин не смог выполнить запрос. Попробуйте ещё раз. Ваш запрос на поддержку отправлен в Apple. diff --git a/core/localization/src/androidMain/res/values-tr/strings.xml b/core/localization/src/androidMain/res/values-tr/strings.xml index 145cad5984..7a18f12aa7 100644 --- a/core/localization/src/androidMain/res/values-tr/strings.xml +++ b/core/localization/src/androidMain/res/values-tr/strings.xml @@ -519,7 +519,6 @@ Destekleri için bu harika insanlara teşekkürler ❤ SDAI, şu özelliklere sahip açık kaynaklı bir uygulamadır: • Yapay zekâ ile görüntü oluşturma olanağı sunar;\n• Üretim sağlayıcınızı seçme özgürlüğü verir;\n• AD, telemetri içermez ve sizi gözetlemez;\n• Açık kaynaklı bir yazılımdır;\n• Ücretsiz olarak kullanabilirsiniz. - Bu yazılımı değerli buluyorsanız, projeyi desteklediğiniz ve yaşamasına yardımcı olduğunuz için teşekkürler. Depolamak Bildirimler @@ -953,7 +952,7 @@ Devam et Ölçek katsayısı Destek yolları - Aşağıda belirtilen ağı seçin. Aynı adres farklı ağlarda kullanılabilir. + Ağ: %1$s Adresi kopyala Adres kopyalandı Bağış seçenekleri yüklenemedi. @@ -963,7 +962,7 @@ Kaydedilen bağış seçenekleri gösteriliyor. Güncel seçeneklere ulaşılamıyor. Müzik molası D10G3N’in SDAI müzik videosunu YouTube’da izleyin. - Geliştirmeyi isteğe bağlı bir bahşişle destekleyin. Tüm özellikler bahşiş vermeden kullanılabilir. + Bağışlar SDAI geliştirmesinin sürmesine yardımcı olur. Bağış yapmadan da tüm özellikleri kullanabilirsiniz. Destek satın alımları şu anda kullanılamıyor. Mağaza bu isteği tamamlayamadı. Lütfen tekrar deneyin. Destek isteğiniz Apple’a gönderildi. diff --git a/core/localization/src/androidMain/res/values-uk/strings.xml b/core/localization/src/androidMain/res/values-uk/strings.xml index 0e41155f18..7dae229217 100644 --- a/core/localization/src/androidMain/res/values-uk/strings.xml +++ b/core/localization/src/androidMain/res/values-uk/strings.xml @@ -519,7 +519,6 @@ Дякую цим чудовим людям за підтримку ❤ SDAI – це програма з відкритим кодом, яка: • Надає Вам можливість створювати зображення за допомогою ШІ;\n• Дає Вам свободу вибору постачальника генерації;\n• Не містить реклами, телеметрії та не шпигує за вами;\n• ПО з відкритим кодом;\n• Ви можете використовувати його безкоштовно. - Якщо програма була Вам корисна, дякую за підтримку проєкту та допомогу в його розвитку. Сховище Push повідомлення @@ -953,7 +952,7 @@ Продовжити Масштаб Способи підтримки - Виберіть саме ту мережу, що вказана нижче. Різні мережі можуть мати однакову адресу. + Мережа: %1$s Копіювати адресу Адресу скопійовано Не вдалося завантажити способи підтримки. @@ -963,7 +962,7 @@ Показано збережені способи підтримки. Не вдалося завантажити актуальні. Музична пауза Дивіться кліп SDAI від D10G3N на YouTube. - Підтримайте розробку добровільними чайовими. Усі функції доступні без оплати. + Пожертви допомагають розвивати SDAI. Усі функції доступні й без пожертв. Покупки для підтримки наразі недоступні. Магазин не зміг виконати запит. Спробуйте ще раз. Ваш запит на підтримку надіслано до Apple. diff --git a/core/localization/src/androidMain/res/values-zh/strings.xml b/core/localization/src/androidMain/res/values-zh/strings.xml index 2c41cf6ece..8d1f6085a8 100644 --- a/core/localization/src/androidMain/res/values-zh/strings.xml +++ b/core/localization/src/androidMain/res/values-zh/strings.xml @@ -571,7 +571,6 @@ 感谢这些了不起的人们提供的支持 ❤ SDAI 是一款开源应用程序,它: • 让您使用 AI 创建图像;\n• 让您自由选择生成供应商;\n• 无广告、无遥测,无监控;\n• 是一款开源软件;\n• 欢迎您免费使用。 - 如果您觉得这个软件有价值,感谢您支持这个项目并帮助它继续发展。 存储 通知 @@ -1005,7 +1004,7 @@ 继续 缩放倍数 支持方式 - 请选择下方标明的网络。不同网络可以使用相同的地址。 + 网络:%1$s 复制地址 地址已复制 无法加载捐赠方式。 @@ -1015,7 +1014,7 @@ 正在显示已保存的捐赠方式,暂时无法获取最新选项。 音乐小憩 在 YouTube 上观看 D10G3N 的 SDAI 音乐视频。 - 通过自愿打赏支持开发。无需打赏也能使用所有功能。 + 捐赠有助于 SDAI 持续开发。无需捐赠即可使用所有功能。 支持购买目前不可用。 商店无法完成此请求,请重试。 您的支持请求已提交给 Apple。 diff --git a/core/localization/src/androidMain/res/values/strings.xml b/core/localization/src/androidMain/res/values/strings.xml index 2fa4a3a969..8c97688dff 100755 --- a/core/localization/src/androidMain/res/values/strings.xml +++ b/core/localization/src/androidMain/res/values/strings.xml @@ -556,7 +556,6 @@ Thanks to this amazing people for the support ❤ SDAI is an open source application that: • Lets you create images with AI;\n• Gives you freedom to choose your generation provider;\n• Has no ADs, telemetry and does not spy on you;\n• Is an open source software;\n• You are welcome to use it for free. - If you find this software valuable, thank you for supporting the project and helping it stay alive. Storage Notifications @@ -990,7 +989,7 @@ Continue Scale factor Ways to support - Choose the exact network shown below. The same address can be used on different networks. + Network: %1$s Copy address Address copied Unable to load donation options. @@ -1000,7 +999,7 @@ Showing saved donation options. The latest options are unavailable. Music break Watch the SDAI music video by D10G3N on YouTube. - Support development with an optional tip. All features remain available without tipping. + Donations help keep SDAI in development. All features remain available without a donation. Support purchases are currently unavailable. The store could not complete this request. Please try again. Your support request was submitted to Apple. diff --git a/core/localization/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/localization/LocalizationTest.kt b/core/localization/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/localization/LocalizationTest.kt index 4fab8b7752..730418c668 100644 --- a/core/localization/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/localization/LocalizationTest.kt +++ b/core/localization/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/core/localization/LocalizationTest.kt @@ -3,6 +3,8 @@ package com.shifthackz.aisdv1.core.localization import java.util.Locale import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test /** @@ -65,4 +67,35 @@ class LocalizationTest { Locale.setDefault(originalLocale) } } + + @Test + fun `given localized donation cards, support copy and network labels are resolved, expected all bundled languages retain the network name`() { + // Given + val keys = setOf("donate_support_explanation", "donate_network_label") + val languages = listOf("en", "de", "ru", "tr", "uk", "zh") + val network = "Ethereum (ERC-20)" + + // When + val labels = languages.map { code -> + Localization.string( + "donate_network_label", + network, + languageCode = code + ) + } + + // Then + languages.forEach { code -> + val catalog = Localization.strings(code) + assertTrue(catalog.keys.containsAll(keys)) + assertTrue(catalog.getValue("donate_support_explanation").isNotBlank()) + assertFalse("donate_network_notice" in catalog) + } + assertEquals("Network: $network", labels.first()) + assertTrue(labels.all { + it.contains(network) && it.length > network.length && !it.contains( + '%' + ) + }) + } } diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/repository/DonationRepositoryImplTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/repository/DonationRepositoryImplTest.kt index 2180088a62..941968a66f 100644 --- a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/repository/DonationRepositoryImplTest.kt +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/repository/DonationRepositoryImplTest.kt @@ -1,12 +1,18 @@ package com.shifthackz.aisdv1.data.repository import com.shifthackz.aisdv1.data.donate.DonationFixtures +import com.shifthackz.aisdv1.data.local.DonationLocalDataSource +import com.shifthackz.aisdv1.data.remote.DonationRemoteDataSource +import com.shifthackz.aisdv1.network.api.sdai.SdaiAppApi +import com.shifthackz.aisdv1.storage.db.persistent.dao.DonationDao +import com.shifthackz.aisdv1.storage.db.persistent.entity.DonationCatalogSnapshot import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import kotlinx.coroutines.test.runTest import org.junit.Assert.assertSame import org.junit.Assert.assertNull +import org.junit.Assert.assertEquals import org.junit.Test import io.mockk.coVerifySequence import com.shifthackz.aisdv1.domain.datasource.DonationDataSource @@ -72,4 +78,34 @@ class DonationRepositoryImplTest { assertSame(failure, write.exceptionOrNull()) coVerify(exactly = 0) { remote.fetch() } } + + @Test + fun `given donation repository with published and saved revisions, an empty revision replaces payment choices, expected cache retains exact data then clears old destinations`() = + runTest { + // Given + val api = mockk() + val dao = mockk() + var saved: DonationCatalogSnapshot? = null + coEvery { dao.replace(any()) } coAnswers { saved = firstArg() } + coEvery { dao.read() } coAnswers { saved } + val empty = DonationFixtures.raw.copy(schemaVersion = 18, groups = emptyList()) + coEvery { api.fetchDonationOptions() } returnsMany listOf(DonationFixtures.raw, empty) + val donations = + DonationRepositoryImpl(DonationRemoteDataSource(api), DonationLocalDataSource(dao)) + + // When + donations.writeCache(donations.fetch().getOrThrow()).getOrThrow() + val original = donations.readCache().getOrThrow() + val replacement = donations.fetch().getOrThrow() + donations.writeCache(replacement).getOrThrow() + val updated = donations.readCache().getOrThrow() + + // Then + assertEquals(DonationFixtures.catalog, original) + assertEquals( + DonationFixtures.catalog.copy(schemaVersion = 18, groups = emptyList()), + updated + ) + coVerify(exactly = 2) { dao.replace(any()) } + } } diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchOrGetDonationOptionsUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchOrGetDonationOptionsUseCaseImplTest.kt index 4de23c0cdc..2a91890e9b 100644 --- a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchOrGetDonationOptionsUseCaseImplTest.kt +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/donate/FetchOrGetDonationOptionsUseCaseImplTest.kt @@ -1,11 +1,11 @@ package com.shifthackz.aisdv1.domain.usecase.donate -import com.shifthackz.aisdv1.domain.entity.DonationOptionKind - +import com.shifthackz.aisdv1.domain.entity.DonationAsset import com.shifthackz.aisdv1.domain.entity.DonationCatalog import com.shifthackz.aisdv1.domain.entity.DonationContent import com.shifthackz.aisdv1.domain.entity.DonationGroup import com.shifthackz.aisdv1.domain.entity.DonationOption +import com.shifthackz.aisdv1.domain.entity.DonationOptionKind import com.shifthackz.aisdv1.domain.repository.DonationRepository import io.mockk.coEvery import io.mockk.coVerify @@ -234,4 +234,34 @@ class FetchOrGetDonationOptionsUseCaseImplTest { assertSame(cancellation, error) } + @Test + fun `given donation options with a mixed published revision, network goes offline after saving it, expected same eligible destinations from cache`() = + runTest { + // Given + val group = catalog.groups.single().copy( + options = listOf(option.copy(assets = listOf(DonationAsset("BTC", "btc")))) + ) + val eligible = catalog.copy(groups = listOf(group)) + val published = eligible.copy( + groups = eligible.groups + group.copy( + id = "disabled", + isEnabled = false + ) + ) + coEvery { repository.fetch() } returnsMany listOf( + Result.success(published), + Result.failure(failure) + ) + coEvery { repository.writeCache(published) } returns Result.success(Unit) + coEvery { repository.readCache() } returns Result.success(published) + + // When + val online = useCase().getOrThrow() + val offline = useCase().getOrThrow() + + // Then + assertEquals(eligible, online.catalog) + assertEquals(online.copy(isCached = true), offline) + coVerify(exactly = 1) { repository.writeCache(published) } + } } diff --git a/feature/iap/build.gradle.kts b/feature/iap/build.gradle.kts index 9b8b371dc0..ad96054346 100644 --- a/feature/iap/build.gradle.kts +++ b/feature/iap/build.gradle.kts @@ -1,5 +1,8 @@ +import org.gradle.testing.jacoco.tasks.JacocoReport + plugins { alias(libs.plugins.generic.kmp.library) + alias(libs.plugins.generic.flavors) alias(libs.plugins.generic.di.tests) } @@ -9,6 +12,7 @@ kotlin { sourceSets { commonMain.dependencies { api(project(":domain")) + implementation(project(":core:common")) implementation(libs.koin.core) implementation(libs.kotlinx.coroutines.core) } @@ -16,11 +20,20 @@ kotlin { implementation(kotlin("test")) implementation(libs.test.coroutines) } - iosMain.dependencies { - implementation(project(":core:common")) - } androidUnitTest.dependencies { implementation(libs.test.junit) } } } + +dependencies { + "playstoreImplementation"(libs.google.play.billing) + "playstoreImplementation"(libs.koin.android) + "testPlaystoreImplementation"(libs.test.mockk) + "testPlaystoreImplementation"(libs.test.roboelectric) +} + +// Run coverage for every IAP variant. Only the primary variant enters the aggregate. +tasks.matching { it.name == "ciCoverage" }.configureEach { + dependsOn(tasks.withType()) +} diff --git a/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/NoOpIapGateway.kt b/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/NoOpIapGateway.kt index 2440d1a6cf..a8932e911a 100644 --- a/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/NoOpIapGateway.kt +++ b/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/NoOpIapGateway.kt @@ -8,7 +8,7 @@ import com.shifthackz.aisdv1.domain.gateway.IapGateway import kotlinx.coroutines.flow.emptyFlow /** - * Leaves native billing unavailable on Android while preserving the shared API. + * Preserves the shared billing API for Android distributions without a store catalog. * * @author Dmitriy Moroz */ diff --git a/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/di/IapModule.android.kt b/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/di/IapModule.android.kt index 06a4c5491d..8df61baf21 100644 --- a/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/di/IapModule.android.kt +++ b/feature/iap/src/androidMain/kotlin/com/shifthackz/aisdv1/feature/iap/di/IapModule.android.kt @@ -1,14 +1,12 @@ package com.shifthackz.aisdv1.feature.iap.di -import com.shifthackz.aisdv1.domain.gateway.IapGateway -import com.shifthackz.aisdv1.feature.iap.NoOpIapGateway import org.koin.dsl.module /** - * Binds unsupported billing without linking a billing SDK. + * Includes only the billing bindings compiled into the current Android distribution. * * @author Dmitriy Moroz */ internal actual fun platformIapModule() = module { - single { NoOpIapGateway() } + includes(androidIapModule()) } diff --git a/feature/iap/src/foss/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt b/feature/iap/src/foss/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt new file mode 100644 index 0000000000..bdf0389675 --- /dev/null +++ b/feature/iap/src/foss/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.feature.iap.di + +import com.shifthackz.aisdv1.domain.gateway.IapGateway +import com.shifthackz.aisdv1.feature.iap.NoOpIapGateway +import org.koin.dsl.module + +/** + * Keeps the FOSS distribution independent of the Google Play Billing SDK. + * + * @author Dmitriy Moroz + */ +internal fun androidIapModule() = module { + single { NoOpIapGateway() } +} diff --git a/feature/iap/src/full/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt b/feature/iap/src/full/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt new file mode 100644 index 0000000000..0078dbefef --- /dev/null +++ b/feature/iap/src/full/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.feature.iap.di + +import com.shifthackz.aisdv1.domain.gateway.IapGateway +import com.shifthackz.aisdv1.feature.iap.NoOpIapGateway +import org.koin.dsl.module + +/** + * Keeps billing unavailable for the sideloaded FULL distribution. + * + * @author Dmitriy Moroz + */ +internal fun androidIapModule() = module { + single { NoOpIapGateway() } +} diff --git a/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapActivityCallbacks.kt b/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapActivityCallbacks.kt new file mode 100644 index 0000000000..d5b956eeef --- /dev/null +++ b/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapActivityCallbacks.kt @@ -0,0 +1,33 @@ +package com.shifthackz.aisdv1.feature.iap + +import android.app.Activity +import android.app.Application +import android.os.Bundle + +/** + * Tracks the foreground host for Play's purchase sheet and triggers reconciliation on resume. + * + * @param onResume Starts a Play purchase query when an activity becomes active. + * @author Dmitriy Moroz + */ +internal class PlayIapActivityCallbacks(private val onResume: () -> Unit) : + Application.ActivityLifecycleCallbacks { + + var activity: Activity? = null + private set + + override fun onActivityResumed(activity: Activity) { + this.activity = activity + onResume() + } + + override fun onActivityPaused(activity: Activity) { + if (this.activity === activity) this.activity = null + } + + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit + override fun onActivityStarted(activity: Activity) = Unit + override fun onActivityStopped(activity: Activity) = Unit + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit + override fun onActivityDestroyed(activity: Activity) = Unit +} diff --git a/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapGateway.kt b/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapGateway.kt new file mode 100644 index 0000000000..443f23a95a --- /dev/null +++ b/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/PlayIapGateway.kt @@ -0,0 +1,291 @@ +package com.shifthackz.aisdv1.feature.iap + +import android.app.Application +import android.util.LruCache +import com.android.billingclient.api.BillingClient +import com.android.billingclient.api.BillingClient.BillingResponseCode +import com.android.billingclient.api.BillingClient.ProductType +import com.android.billingclient.api.BillingClientStateListener +import com.android.billingclient.api.BillingFlowParams +import com.android.billingclient.api.BillingResult +import com.android.billingclient.api.ConsumeParams +import com.android.billingclient.api.PendingPurchasesParams +import com.android.billingclient.api.ProductDetails +import com.android.billingclient.api.Purchase +import com.android.billingclient.api.QueryProductDetailsParams +import com.android.billingclient.api.QueryPurchasesParams +import com.android.billingclient.api.consumePurchase +import com.android.billingclient.api.queryProductDetails +import com.android.billingclient.api.queryPurchasesAsync +import com.shifthackz.aisdv1.core.common.log.errorLog +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.IapProduct +import com.shifthackz.aisdv1.domain.entity.IapPurchaseResult +import com.shifthackz.aisdv1.domain.entity.IapPurchaseStatus +import com.shifthackz.aisdv1.domain.entity.IapTransaction +import com.shifthackz.aisdv1.domain.entity.TipProducts +import com.shifthackz.aisdv1.domain.gateway.IapGateway +import java.security.MessageDigest +import kotlin.coroutines.resume +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** + * Settles voluntary one-time tips through Play for the lifetime of the application process. + * Only completed purchases for the app's tip products are consumed. The app grants no + * entitlement, and reports completion only after Play accepts consumption. + * + * @param application Owns the BillingClient and foreground activity callbacks. + * @param dispatchers Supplies the main dispatcher for billing and purchase state. + * @author Dmitriy Moroz + */ +internal class PlayIapGateway( + application: Application, + private val dispatchers: DispatchersProvider, +) : IapGateway { + private class PurchaseRequest(val productId: String) { + val result = CompletableDeferred>() + } + + private val packageName = application.packageName + private val scope = CoroutineScope(SupervisorJob() + dispatchers.immediate) + private val connection = Mutex() + private val purchaseLaunch = Mutex() + private val settlement = Mutex() + private val consumedTransactions = LruCache(64) + private val transactions = MutableSharedFlow(extraBufferCapacity = 16) + private val activities = PlayIapActivityCallbacks(::reconcileOnResume) + private var hasConnected = false + private var activePurchase: PurchaseRequest? = null + private var reconciliation: Job? = null + private val client = BillingClient.newBuilder(application) + .setListener(::onPurchasesUpdated) + .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()) + .enableAutoServiceReconnection() + .build() + + init { + application.registerActivityLifecycleCallbacks(activities) + } + + override suspend fun loadProducts(productIds: List): Result> = + withContext(dispatchers.immediate) { + billingResult { + queryProducts(productIds).mapNotNull { product -> + product.tipOffer()?.let { offer -> + IapProduct( + product.productId, + product.title, + product.description, + offer.formattedPrice + ) + } + } + } + } + + override suspend fun purchase(productId: String): Result = + withContext(dispatchers.immediate) { + billingResult { + require(productId in TipProducts.ids) { "Unknown tip product" } + val request = purchaseLaunch.withLock { + check(activePurchase == null) { "Another tip is in progress" } + launchPurchase(productId) + } + // The purchase belongs to Play once launched, even if the screen stops waiting. + request.result.await().getOrThrow() + } + } + + override fun observeTransactions() = transactions.asSharedFlow() + + private suspend fun launchPurchase(productId: String): PurchaseRequest { + val product = checkNotNull(queryProducts(listOf(productId)).firstOrNull()) { + "Tip product is unavailable" + } + val offer = checkNotNull(product.tipOffer()) { "Tip purchase option is unavailable" } + val activity = checkNotNull(activities.activity) { "No foreground activity for billing" } + val params = BillingFlowParams.ProductDetailsParams.newBuilder() + .setProductDetails(product) + .apply { offer.offerToken?.let(::setOfferToken) } + .build() + val request = PurchaseRequest(productId) + activePurchase = request + try { + client.launchBillingFlow( + activity, + BillingFlowParams.newBuilder().setProductDetailsParamsList(listOf(params)).build(), + ).requireOk("launch") + } catch (error: Exception) { + if (activePurchase === request) activePurchase = null + throw error + } + return request + } + + private suspend fun queryProducts(productIds: List): List { + if (productIds.isEmpty()) return emptyList() + connect() + val products = productIds.distinct().map { id -> + QueryProductDetailsParams.Product.newBuilder() + .setProductId(id) + .setProductType(ProductType.INAPP) + .build() + } + val result = client.queryProductDetails( + QueryProductDetailsParams.newBuilder().setProductList(products).build(), + ) + result.billingResult.requireOk("load products") + return result.productDetailsList.orEmpty().filter { it.productId in productIds } + } + + private fun ProductDetails.tipOffer(): ProductDetails.OneTimePurchaseOfferDetails? { + val offers = oneTimePurchaseOfferDetailsList ?: listOfNotNull(oneTimePurchaseOfferDetails) + return offers.singleOrNull { it.rentalDetails == null && it.preorderDetails == null } + } + + private suspend fun connect() = connection.withLock { + if (hasConnected) return@withLock + // After the first successful setup, the SDK reconnects automatically for subsequent calls. + val result = suspendCancellableCoroutine { continuation -> + client.startConnection(object : BillingClientStateListener { + override fun onBillingSetupFinished(result: BillingResult) { + if (continuation.isActive) continuation.resume(result) + } + + override fun onBillingServiceDisconnected() = Unit + }) + } + result.requireOk("connect") + hasConnected = true + } + + private fun reconcileOnResume() { + if (reconciliation?.isActive == true) return + reconciliation = scope.launch { + val request = activePurchase + billingResult { + connect() + val result = client.queryPurchasesAsync( + QueryPurchasesParams.newBuilder().setProductType(ProductType.INAPP).build(), + ) + result.billingResult.requireOk("recover purchases") + processPurchases(result.purchasesList, request) + }.onFailure { errorLog(message = "Could not recover Play tip purchases") } + } + } + + private fun onPurchasesUpdated(result: BillingResult, purchases: List?) { + scope.launch { + val request = activePurchase + when (result.responseCode) { + BillingResponseCode.OK -> + if (purchases.isNullOrEmpty()) { + request?.finish(Result.failure(IllegalStateException("Missing Play purchase response"))) + } else { + processPurchases(purchases, request) + } + + BillingResponseCode.USER_CANCELED -> + request?.finish( + Result.success( + IapPurchaseResult( + IapPurchaseStatus.CANCELLED, + request.productId + ) + ) + ) + + else -> request?.finish(Result.failure(result.failure("purchase"))) + } + } + } + + private suspend fun processPurchases(purchases: List, request: PurchaseRequest?) { + for (purchase in purchases) { + val productId = + purchase.products.singleOrNull()?.takeIf { it in TipProducts.ids } ?: continue + if (purchase.packageName != packageName || purchase.purchaseToken.isBlank()) continue + val matchingRequest = request?.takeIf { it.productId == productId } + when (purchase.purchaseState) { + Purchase.PurchaseState.PENDING -> + matchingRequest?.finish( + Result.success( + IapPurchaseResult( + IapPurchaseStatus.PENDING, + productId + ) + ) + ) + + Purchase.PurchaseState.PURCHASED -> { + val result = billingResult { settle(purchase, productId) } + result.onSuccess { transaction -> + if (transaction != null) { + matchingRequest?.finish( + Result.success( + IapPurchaseResult( + IapPurchaseStatus.COMPLETED, + productId, + transaction.transactionId + ) + ) + ) + } + }.onFailure { error -> + if (matchingRequest == null) errorLog(message = "Could not settle a Play tip purchase") + else matchingRequest.finish(Result.failure(error)) + } + } + } + } + } + + private suspend fun settle(purchase: Purchase, productId: String): IapTransaction? = + settlement.withLock { + val digest = + MessageDigest.getInstance("SHA-256").digest(purchase.purchaseToken.toByteArray()) + val transactionId = digest.toHexString() + // Play's update and resume query can both surface the same purchase. + if (consumedTransactions.get(transactionId) != null) return@withLock null + + val params = ConsumeParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build() + client.consumePurchase(params).billingResult.requireOk("consume tip") + val transaction = IapTransaction(productId, transactionId) + consumedTransactions.put(transactionId, Unit) + transactions.emit(transaction) + transaction + } + + private fun PurchaseRequest.finish(outcome: Result) { + if (activePurchase === this) { + activePurchase = null + result.complete(outcome) + } + } + + private fun BillingResult.requireOk(operation: String) { + if (responseCode != BillingResponseCode.OK) throw failure(operation) + } + + private fun BillingResult.failure(operation: String) = + IllegalStateException("Play Billing could not $operation ($responseCode)") + + private inline fun billingResult(block: () -> T): Result = try { + Result.success(block()) + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + Result.failure(error) + } +} diff --git a/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt b/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt new file mode 100644 index 0000000000..5a5d5d5370 --- /dev/null +++ b/feature/iap/src/playstore/java/com/shifthackz/aisdv1/feature/iap/di/AndroidIapModule.kt @@ -0,0 +1,15 @@ +package com.shifthackz.aisdv1.feature.iap.di + +import com.shifthackz.aisdv1.domain.gateway.IapGateway +import com.shifthackz.aisdv1.feature.iap.PlayIapGateway +import org.koin.android.ext.koin.androidApplication +import org.koin.dsl.module + +/** + * Starts the Play purchase observer with the application so settlement does not depend on opening Donate. + * + * @author Dmitriy Moroz + */ +internal fun androidIapModule() = module { + single(createdAtStart = true) { PlayIapGateway(androidApplication(), get()) } +} diff --git a/feature/iap/src/testFoss/java/com/shifthackz/aisdv1/feature/iap/FossIapModuleTest.kt b/feature/iap/src/testFoss/java/com/shifthackz/aisdv1/feature/iap/FossIapModuleTest.kt new file mode 100644 index 0000000000..d59940af84 --- /dev/null +++ b/feature/iap/src/testFoss/java/com/shifthackz/aisdv1/feature/iap/FossIapModuleTest.kt @@ -0,0 +1,41 @@ +package com.shifthackz.aisdv1.feature.iap + +import com.shifthackz.aisdv1.domain.entity.IapPurchaseStatus +import com.shifthackz.aisdv1.domain.entity.TipProducts +import com.shifthackz.aisdv1.domain.gateway.IapGateway +import com.shifthackz.aisdv1.feature.iap.di.iapModule +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.koin.dsl.koinApplication + +/** + * Checks the FOSS distribution uses the common unsupported store contract without a BillingClient. + * + * @author Dmitriy Moroz + */ +class FossIapModuleTest { + @Test + fun `given the FOSS IAP graph, discovery and purchase are requested, expected unsupported without emitting a transaction`() = + runTest { + // Given + val graph = koinApplication { modules(iapModule) } + val gateway = graph.koin.get() + + try { + // When + val products = gateway.loadProducts(TipProducts.ids) + val purchase = gateway.purchase(TipProducts.ids.first()).getOrThrow() + + // Then + assertTrue(gateway is NoOpIapGateway) + assertTrue(products.exceptionOrNull() is UnsupportedOperationException) + assertEquals(IapPurchaseStatus.UNSUPPORTED, purchase.status) + assertTrue(gateway.observeTransactions().toList().isEmpty()) + } finally { + graph.close() + } + } +} diff --git a/feature/iap/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/iap/NoOpIapGatewayTest.kt b/feature/iap/src/testFull/java/com/shifthackz/aisdv1/feature/iap/NoOpIapGatewayTest.kt similarity index 93% rename from feature/iap/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/iap/NoOpIapGatewayTest.kt rename to feature/iap/src/testFull/java/com/shifthackz/aisdv1/feature/iap/NoOpIapGatewayTest.kt index a0631eba87..b867bab248 100644 --- a/feature/iap/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/feature/iap/NoOpIapGatewayTest.kt +++ b/feature/iap/src/testFull/java/com/shifthackz/aisdv1/feature/iap/NoOpIapGatewayTest.kt @@ -31,7 +31,7 @@ class NoOpIapGatewayTest { } @Test - fun `given Android IAP graph, store operations are requested, expected unsupported without simulated success`() = + fun `given FULL IAP graph, store operations are requested, expected unsupported without simulated success`() = runTest { // Given val application = koinApplication { modules(iapModule) } diff --git a/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapCatalogTest.kt b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapCatalogTest.kt new file mode 100644 index 0000000000..2ee3b59cd8 --- /dev/null +++ b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapCatalogTest.kt @@ -0,0 +1,192 @@ +package com.shifthackz.aisdv1.feature.iap + +import com.android.billingclient.api.BillingClient +import com.android.billingclient.api.BillingClient.BillingResponseCode +import com.android.billingclient.api.BillingClientStateListener +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.IapProduct +import com.shifthackz.aisdv1.domain.gateway.IapGateway +import com.shifthackz.aisdv1.feature.iap.di.iapModule +import io.mockk.every +import io.mockk.slot +import io.mockk.unmockkStatic +import io.mockk.verify +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.koin.android.ext.koin.androidContext +import org.koin.dsl.koinApplication +import org.koin.dsl.module +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Checks Play product selection, retry and SDK initialization through the production gateway. + * + * @author Dmitriy Moroz + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +@OptIn(ExperimentalCoroutinesApi::class) +class PlayIapCatalogTest { + @After + fun unmockBillingFactory() = unmockkStatic(BillingClient::class) + + @Test + fun `given Play tip discovery, compatible and foreign offers arrive, expected only requested buy offers with store prices`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val rental = + store.offer("rental").put("rentalDetails", JSONObject().put("rentalPeriod", "P1D")) + val preorder = store.offer("preorder").put( + "preorderDetails", + JSONObject() + .put("preorderReleaseTimeMillis", 1_800_000_000_000L) + .put("preorderPresaleEndTimeMillis", 1_799_900_000_000L), + ) + store.products = listOf( + store.product( + store.small, + listOf(rental, store.offer(price = "54,99 UAH"), preorder) + ), + store.product( + store.medium, + listOf(store.offer(price = "269,99 UAH")), + isLegacy = true + ), + store.product(store.large, listOf(store.offer(), store.offer("second-buy"))), + store.product("unrelated"), + ) + val gateway = PlayIapGateway(store.application, store.dispatchers) + + // When + val products = + gateway.loadProducts(listOf(store.large, store.small, store.medium, store.small)) + .getOrThrow() + + // Then + assertEquals( + listOf( + IapProduct(store.small, "Tip ${store.small}", "Optional support", "54,99 UAH"), + IapProduct( + store.medium, + "Tip ${store.medium}", + "Optional support", + "269,99 UAH" + ), + ), + products, + ) + verify(exactly = 1) { store.client.queryProductDetailsAsync(any(), any()) } + } + + @Test + fun `given Play tip discovery with an empty selection, products are requested, expected no SDK connection or query`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + + // When + val products = gateway.loadProducts(emptyList()).getOrThrow() + + // Then + assertTrue(products.isEmpty()) + verify(exactly = 0) { store.client.startConnection(any()) } + verify(exactly = 0) { store.client.queryProductDetailsAsync(any(), any()) } + } + + @Test + fun `given Play tip discovery after connection and query failures, a later query succeeds, expected retry without a redundant setup`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val ids = listOf(store.small) + store.setupCode = BillingResponseCode.BILLING_UNAVAILABLE + val connection = gateway.loadProducts(ids) + + // When + store.setupCode = BillingResponseCode.OK + store.productCode = BillingResponseCode.NETWORK_ERROR + val query = gateway.loadProducts(ids) + store.productCode = BillingResponseCode.OK + val recovered = gateway.loadProducts(ids).getOrThrow() + + // Then + assertEquals( + "Play Billing could not connect (3)", + connection.exceptionOrNull()?.message + ) + assertEquals( + "Play Billing could not load products (12)", + query.exceptionOrNull()?.message + ) + assertEquals(store.small, recovered.single().productId) + verify(exactly = 2) { store.client.startConnection(any()) } + verify(exactly = 2) { store.client.queryProductDetailsAsync(any(), any()) } + } + + @Test + fun `given cancelled Play discovery, the SDK replies late, expected a new request can connect and load`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val listener = slot() + every { store.client.startConnection(capture(listener)) } returns Unit + val gateway = PlayIapGateway(store.application, store.dispatchers) + val first = async { gateway.loadProducts(listOf(store.small)) } + runCurrent() + val cancelledListener = listener.captured + cancelledListener.onBillingServiceDisconnected() + assertFalse(first.isCompleted) + + // When + first.cancelAndJoin() + cancelledListener.onBillingSetupFinished(store.result(BillingResponseCode.OK)) + val next = async { gateway.loadProducts(listOf(store.small)) } + runCurrent() + listener.captured.onBillingSetupFinished(store.result(BillingResponseCode.OK)) + + // Then + assertTrue(first.isCancelled) + assertEquals(store.small, next.await().getOrThrow().single().productId) + verify(exactly = 2) { store.client.startConnection(any()) } + verify(exactly = 1) { store.client.queryProductDetailsAsync(any(), any()) } + } + + @Test + fun `given the Play IAP graph, Koin starts, expected a single gateway begins observing activities before Donate is opened`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + + // When + val graph = koinApplication { + androidContext(store.application) + modules(iapModule, module { single { store.dispatchers } }) + } + + // Then + try { + verify(exactly = 1) { store.application.registerActivityLifecycleCallbacks(any()) } + val gateway = graph.koin.get() + assertTrue(gateway is PlayIapGateway) + assertSame(gateway, graph.koin.get()) + } finally { + graph.close() + } + } +} diff --git a/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapFixture.kt b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapFixture.kt new file mode 100644 index 0000000000..e7fbbbf2fd --- /dev/null +++ b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapFixture.kt @@ -0,0 +1,139 @@ +package com.shifthackz.aisdv1.feature.iap + +import android.app.Activity +import android.app.Application +import com.android.billingclient.api.BillingClient +import com.android.billingclient.api.BillingClient.BillingResponseCode +import com.android.billingclient.api.BillingClientStateListener +import com.android.billingclient.api.BillingResult +import com.android.billingclient.api.ConsumeParams +import com.android.billingclient.api.ConsumeResponseListener +import com.android.billingclient.api.ProductDetails +import com.android.billingclient.api.ProductDetailsResponseListener +import com.android.billingclient.api.Purchase +import com.android.billingclient.api.PurchasesResponseListener +import com.android.billingclient.api.PurchasesUpdatedListener +import com.android.billingclient.api.QueryProductDetailsResult +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.TipProducts +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkStatic +import io.mockk.slot +import kotlinx.coroutines.CoroutineDispatcher +import org.json.JSONArray +import org.json.JSONObject + +/** + * Drives the gateway at the SDK callback boundary with real Play models and request builders. + * + * @param dispatcher Runs the gateway and its callbacks on the test scheduler. + * @author Dmitriy Moroz + */ +internal class PlayIapFixture(dispatcher: CoroutineDispatcher) { + private val packageName = "com.shifthackz.aisdv1.app" + val small = TipProducts.ids[0] + val medium = TipProducts.ids[1] + val large = TipProducts.ids[2] + val client = mockk() + val application = mockk() + val activity = mockk() + val dispatchers = object : DispatchersProvider { + override val io = dispatcher + override val ui = dispatcher + override val immediate = dispatcher + } + + var setupCode = BillingResponseCode.OK + var productCode = BillingResponseCode.OK + var launchCode = BillingResponseCode.OK + var recoveryCode = BillingResponseCode.OK + var consumeCode = BillingResponseCode.OK + var products = listOf(product(small)) + var recoverablePurchases = emptyList() + private val updates = slot() + private val lifecycle = slot() + + init { + mockkStatic(BillingClient::class) + val builder = mockk() + every { application.packageName } returns packageName + every { application.registerActivityLifecycleCallbacks(capture(lifecycle)) } returns Unit + every { BillingClient.newBuilder(application) } returns builder + every { builder.setListener(capture(updates)) } returns builder + every { builder.enablePendingPurchases(any()) } returns builder + every { builder.enableAutoServiceReconnection() } returns builder + every { builder.build() } returns client + every { client.startConnection(any()) } answers { + firstArg().onBillingSetupFinished(result(setupCode)) + } + every { client.queryProductDetailsAsync(any(), any()) } answers { + secondArg().onProductDetailsResponse( + result(productCode), QueryProductDetailsResult.create(products, emptyList()), + ) + } + every { client.launchBillingFlow(any(), any()) } answers { result(launchCode) } + every { client.queryPurchasesAsync(any(), any()) } answers { + secondArg().onQueryPurchasesResponse( + result(recoveryCode), + recoverablePurchases + ) + } + every { client.consumeAsync(any(), any()) } answers { + secondArg().onConsumeResponse( + result(consumeCode), + firstArg().purchaseToken + ) + } + } + + fun resume(host: Activity = activity) = lifecycle.captured.onActivityResumed(host) + + fun pause(host: Activity = activity) = lifecycle.captured.onActivityPaused(host) + + fun update(code: Int = BillingResponseCode.OK, purchases: List? = null) { + updates.captured.onPurchasesUpdated(result(code), purchases) + } + + fun result(code: Int): BillingResult = BillingResult.newBuilder().setResponseCode(code).build() + + fun purchase( + token: String, + productIds: List = listOf(small), + buyerPackage: String = packageName, + isPending: Boolean = false, + ): Purchase = Purchase( + JSONObject() + .put("productIds", JSONArray(productIds)) + .put("packageName", buyerPackage) + .put("purchaseToken", token) + .put("purchaseState", if (isPending) 4 else 0) + .toString(), + "unused-test-signature", + ) + + fun product( + id: String, + offers: List = listOf(offer()), + isLegacy: Boolean = false + ): ProductDetails { + val json = JSONObject() + .put("productId", id) + .put("type", BillingClient.ProductType.INAPP) + .put("title", "Tip $id") + .put("description", "Optional support") + if (isLegacy) json.put("oneTimePurchaseOfferDetails", offers.single()) + else if (offers.isNotEmpty()) json.put("oneTimePurchaseOfferDetailsList", JSONArray(offers)) + // BillingClient normally constructs this SDK model when it decodes a Play response. + return ProductDetails::class.java.getDeclaredConstructor(String::class.java) + .apply { isAccessible = true } + .newInstance(json.toString()) + } + + fun offer(option: String = "buy", price: String = "€0.99"): JSONObject = JSONObject() + .put("purchaseOptionId", option) + .put("offerIdToken", "$option-token") + .put("formattedPrice", price) + .put("priceAmountMicros", 990_000) + .put("priceCurrencyCode", "EUR") +} diff --git a/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapPurchaseTest.kt b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapPurchaseTest.kt new file mode 100644 index 0000000000..2b5b9d50b9 --- /dev/null +++ b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapPurchaseTest.kt @@ -0,0 +1,263 @@ +package com.shifthackz.aisdv1.feature.iap + +import android.app.Activity +import android.os.Bundle +import com.android.billingclient.api.BillingClient +import com.android.billingclient.api.BillingClient.BillingResponseCode +import com.android.billingclient.api.Purchase +import com.shifthackz.aisdv1.domain.entity.IapPurchaseResult +import com.shifthackz.aisdv1.domain.entity.IapPurchaseStatus +import com.shifthackz.aisdv1.domain.entity.IapTransaction +import io.mockk.mockk +import io.mockk.unmockkStatic +import io.mockk.verify +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +/** + * Verifies how the Play gateway starts a tip and translates SDK updates into payment outcomes. + * + * @author Dmitriy Moroz + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +@OptIn(ExperimentalCoroutinesApi::class) +class PlayIapPurchaseTest { + @After + fun unmockBillingFactory() = unmockkStatic(BillingClient::class) + + @Test + fun `given Play tip purchase, invalid selections and missing offers are requested, expected no native checkout`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + + // When + val unknown = gateway.purchase("unrelated") + val unavailable = gateway.purchase(store.medium) + store.products = listOf(store.product(store.small, offers = emptyList())) + val noOffer = gateway.purchase(store.small) + + // Then + assertEquals("Unknown tip product", unknown.exceptionOrNull()?.message) + assertEquals("Tip product is unavailable", unavailable.exceptionOrNull()?.message) + assertEquals("Tip purchase option is unavailable", noOffer.exceptionOrNull()?.message) + verify(exactly = 0) { store.client.launchBillingFlow(any(), any()) } + } + + @Test + fun `given overlapping Android activity transitions, the previous host pauses, expected checkout uses only the current resumed activity`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val nextHost = mockk() + store.resume() + store.resume(nextHost) + store.pause() + runCurrent() + + // When + val purchase = async { gateway.purchase(store.small) } + runCurrent() + store.update(BillingResponseCode.USER_CANCELED) + assertEquals(IapPurchaseStatus.CANCELLED, purchase.await().getOrThrow().status) + store.pause(nextHost) + val afterPause = gateway.purchase(store.small) + + // Then + assertEquals( + "No foreground activity for billing", + afterPause.exceptionOrNull()?.message + ) + verify(exactly = 1) { store.client.launchBillingFlow(nextHost, any()) } + verify(exactly = 0) { store.client.launchBillingFlow(store.activity, any()) } + verify(exactly = 1) { store.client.queryPurchasesAsync(any(), any()) } + } + + @Test + fun `given Play checkout launch failure, user retries and cancels, expected request released without consuming anything`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + store.resume() + store.launchCode = BillingResponseCode.DEVELOPER_ERROR + val failure = gateway.purchase(store.small) + + // When + store.launchCode = BillingResponseCode.OK + val request = async { gateway.purchase(store.small) } + runCurrent() + val overlapping = gateway.purchase(store.small) + store.update(BillingResponseCode.USER_CANCELED) + + // Then + assertEquals("Play Billing could not launch (5)", failure.exceptionOrNull()?.message) + assertEquals("Another tip is in progress", overlapping.exceptionOrNull()?.message) + assertEquals( + IapPurchaseResult(IapPurchaseStatus.CANCELLED, store.small), + request.await().getOrThrow() + ) + verify(exactly = 2) { store.client.launchBillingFlow(store.activity, any()) } + verify(exactly = 0) { store.client.consumeAsync(any(), any()) } + } + + @Test + fun `given launched Play checkout, null and empty updates and store errors arrive, expected each request finishes as a failure`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + store.resume() + + // When + val outcomes = listOf?>(null, emptyList()).map { updates -> + val request = async { gateway.purchase(store.small) } + runCurrent() + store.update(purchases = updates) + request.await().exceptionOrNull()?.message + } + val request = async { gateway.purchase(store.small) } + runCurrent() + store.update(BillingResponseCode.NETWORK_ERROR) + val failure = request.await().exceptionOrNull() + store.update() + store.update(BillingResponseCode.USER_CANCELED) + store.update(BillingResponseCode.NETWORK_ERROR) + runCurrent() + + // Then + assertEquals(List(2) { "Missing Play purchase response" }, outcomes) + assertEquals( + "Play Billing could not purchase (12)", + failure?.message + ) + verify(exactly = 0) { store.client.consumeAsync(any(), any()) } + } + + @Test + fun `given Play checkout with unrelated or invalid purchase updates, matching pending purchase arrives, expected pending result without consumption`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val events = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + gateway.observeTransactions().collect(events::add) + } + store.resume() + val request = async { gateway.purchase(store.small) } + runCurrent() + + // When + store.update( + purchases = listOf( + store.purchase("foreign-app", buyerPackage = "other.app"), + store.purchase(" "), + store.purchase("foreign-product", listOf("unrelated")), + store.purchase("multiple-products", listOf(store.small, store.medium)), + store.purchase("other-pending", listOf(store.medium), isPending = true), + ) + ) + runCurrent() + assertFalse(request.isCompleted) + store.update(purchases = listOf(store.purchase("pending", isPending = true))) + + // Then + assertEquals( + IapPurchaseResult(IapPurchaseStatus.PENDING, store.small), + request.await().getOrThrow() + ) + assertTrue(events.isEmpty()) + verify(exactly = 0) { store.client.consumeAsync(any(), any()) } + } + + @Test + fun `given Play tips use repeatable purchases, the same tier completes twice, expected consumption before each distinct acknowledgement`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val events = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + gateway.observeTransactions().collect(events::add) + } + store.resume() + val tokens = listOf("first-tip", "second-tip") + + // When + val confirmations = tokens.mapIndexed { index, token -> + if (index == 1) { + val legacyBuy = store.offer().apply { remove("offerIdToken") } + store.products = + listOf(store.product(store.small, listOf(legacyBuy), isLegacy = true)) + } + val request = async { gateway.purchase(store.small) } + runCurrent() + store.update(purchases = listOf(store.purchase(token))) + request.await().getOrThrow() + } + + // Then + assertEquals(List(2) { IapPurchaseStatus.COMPLETED }, confirmations.map { it.status }) + assertEquals( + confirmations.map { IapTransaction(it.productId, it.transactionId) }, + events + ) + assertNotEquals(events[0].transactionId, events[1].transactionId) + assertTrue(events.all { it.transactionId.matches(Regex("[0-9a-f]{64}")) }) + tokens.forEach { token -> + verify(exactly = 1) { + store.client.consumeAsync( + match { it.purchaseToken == token }, + any() + ) + } + } + } + + @Test + fun `given an Android activity lifecycle, host is created resumed paused and destroyed, expected only resume starts reconciliation and pause clears checkout host`() { + // Given + val app = RuntimeEnvironment.getApplication() + var resumes = 0 + val callbacks = PlayIapActivityCallbacks { resumes++ } + app.registerActivityLifecycleCallbacks(callbacks) + try { + val controller = Robolectric.buildActivity(Activity::class.java).create().start() + assertEquals(0, resumes) + assertNull(callbacks.activity) + + // When + controller.resume() + assertSame(controller.get(), callbacks.activity) + controller.pause().saveInstanceState(Bundle()).stop().destroy() + + // Then + assertEquals(1, resumes) + assertNull(callbacks.activity) + } finally { + app.unregisterActivityLifecycleCallbacks(callbacks) + } + } +} diff --git a/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapRecoveryTest.kt b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapRecoveryTest.kt new file mode 100644 index 0000000000..c0f1256c6b --- /dev/null +++ b/feature/iap/src/testPlaystore/java/com/shifthackz/aisdv1/feature/iap/PlayIapRecoveryTest.kt @@ -0,0 +1,194 @@ +package com.shifthackz.aisdv1.feature.iap + +import com.android.billingclient.api.BillingClient +import com.android.billingclient.api.BillingClient.BillingResponseCode +import com.android.billingclient.api.ConsumeResponseListener +import com.shifthackz.aisdv1.domain.entity.IapPurchaseStatus +import com.shifthackz.aisdv1.domain.entity.IapTransaction +import io.mockk.every +import io.mockk.slot +import io.mockk.unmockkStatic +import io.mockk.verify +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Verifies settlement and idempotency when Play reports the same purchase through different callbacks. + * + * @author Dmitriy Moroz + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +@OptIn(ExperimentalCoroutinesApi::class) +class PlayIapRecoveryTest { + @After + fun unmockBillingFactory() = unmockkStatic(BillingClient::class) + + @Test + fun `given old Play settlement is still running after checkout closes, a new checkout starts, expected the old completion leaves the new request active`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val events = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + gateway.observeTransactions().collect(events::add) + } + val response = slot() + every { store.client.consumeAsync(any(), capture(response)) } returns Unit + store.resume() + val first = async { gateway.purchase(store.small) } + runCurrent() + val purchase = store.purchase("late-settlement") + store.update(purchases = listOf(purchase)) + runCurrent() + store.update(BillingResponseCode.USER_CANCELED) + assertEquals(IapPurchaseStatus.CANCELLED, first.await().getOrThrow().status) + + // When + val next = async { gateway.purchase(store.small) } + runCurrent() + response.captured.onConsumeResponse( + store.result(BillingResponseCode.OK), + purchase.purchaseToken + ) + runCurrent() + assertFalse(next.isCompleted) + store.update(purchases = listOf(store.purchase("next-pending", isPending = true))) + + // Then + assertEquals(IapPurchaseStatus.PENDING, next.await().getOrThrow().status) + assertEquals(store.small, events.single().productId) + } + + @Test + fun `given a Play purchase update with consumption still pending, a resume query reports the same token, expected one consume and one completion`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val events = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + gateway.observeTransactions().collect(events::add) + } + val response = slot() + every { store.client.consumeAsync(any(), capture(response)) } returns Unit + store.resume() + val request = async { gateway.purchase(store.small) } + runCurrent() + val purchase = store.purchase("matching-tip") + + // When + store.update(purchases = listOf(purchase)) + store.recoverablePurchases = listOf(purchase) + store.resume() + runCurrent() + assertFalse(request.isCompleted) + assertTrue(events.isEmpty()) + response.captured.onConsumeResponse( + store.result(BillingResponseCode.OK), + purchase.purchaseToken + ) + + // Then + val completed = request.await().getOrThrow() + assertEquals(IapPurchaseStatus.COMPLETED, completed.status) + assertEquals(listOf(IapTransaction(store.small, completed.transactionId)), events) + verify(exactly = 1) { store.client.consumeAsync(any(), any()) } + verify(exactly = 2) { store.client.queryPurchasesAsync(any(), any()) } + } + + @Test + fun `given failed Play consumption, the app resumes with a recoverable tip, expected no premature acknowledgement and one eventual completion`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val events = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + gateway.observeTransactions().collect(events::add) + } + store.resume() + val request = async { gateway.purchase(store.small) } + runCurrent() + val purchase = store.purchase("unconsumed-tip") + store.consumeCode = BillingResponseCode.NETWORK_ERROR + store.update(purchases = listOf(purchase)) + val failure = request.await().exceptionOrNull() + assertTrue(events.isEmpty()) + + // When + store.recoverablePurchases = listOf(purchase) + store.recoveryCode = BillingResponseCode.SERVICE_UNAVAILABLE + store.resume() + runCurrent() + assertTrue(events.isEmpty()) + store.recoveryCode = BillingResponseCode.OK + store.resume() + runCurrent() + assertTrue(events.isEmpty()) + store.consumeCode = BillingResponseCode.OK + store.resume() + runCurrent() + + // Then + assertEquals("Play Billing could not consume tip (12)", failure?.message) + assertEquals(store.small, events.single().productId) + verify(exactly = 3) { + store.client.consumeAsync( + match { it.purchaseToken == purchase.purchaseToken }, + any() + ) + } + } + + @Test + fun `given Play checkout outlives its caller, a different tip settles and the original tip is recovered, expected both events and no blocked next checkout`() = + runTest { + // Given + val store = PlayIapFixture(StandardTestDispatcher(testScheduler)) + val gateway = PlayIapGateway(store.application, store.dispatchers) + val events = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + gateway.observeTransactions().collect(events::add) + } + store.resume() + val waiter = async { gateway.purchase(store.small) } + runCurrent() + + // When + waiter.cancelAndJoin() + store.update(purchases = listOf(store.purchase("older-medium", listOf(store.medium)))) + runCurrent() + val blocked = gateway.purchase(store.small) + store.recoverablePurchases = listOf(store.purchase("cancelled-waiter")) + store.resume() + runCurrent() + val next = async { gateway.purchase(store.small) } + runCurrent() + store.update(purchases = store.recoverablePurchases) + runCurrent() + assertFalse(next.isCompleted) + store.update(BillingResponseCode.USER_CANCELED) + + // Then + assertEquals("Another tip is in progress", blocked.exceptionOrNull()?.message) + assertEquals(listOf(store.medium, store.small), events.map { it.productId }) + assertEquals(IapPurchaseStatus.CANCELLED, next.await().getOrThrow().status) + verify(exactly = 2) { store.client.consumeAsync(any(), any()) } + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5e213a2dfe..53e25b73f6 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -36,6 +36,7 @@ crypto = "1.1.0" onnx = "1.32.0" workManager = "2.11.2" playAppUpdate = "2.1.0" +playBilling = "9.1.0" room = "2.8.4" sqlite = "2.6.2" timber = "5.0.1" @@ -57,6 +58,7 @@ coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" coil-network-ktor = { module = "io.coil-kt.coil3:coil-network-ktor3", version.ref = "coil" } markdown-material3 = { module = "com.mikepenz:multiplatform-markdown-renderer-m3", version.ref = "markdownRenderer" } google-play-app-update = { group = "com.google.android.play", name = "app-update", version.ref = "playAppUpdate" } +google-play-billing = { module = "com.android.billingclient:billing-ktx", version.ref = "playBilling" } appauth = { group = "net.openid", name = "appauth", version = "0.11.1" } compose-runtime = { module = "org.jetbrains.compose.runtime:runtime", version.ref = "composeMultiplatform" } compose-ui = { module = "org.jetbrains.compose.ui:ui", version.ref = "composeMultiplatform" } diff --git a/presentation/donate/build.gradle.kts b/presentation/donate/build.gradle.kts index 1f5bf7dd72..c74edcff53 100644 --- a/presentation/donate/build.gradle.kts +++ b/presentation/donate/build.gradle.kts @@ -38,6 +38,7 @@ kotlin { implementation(libs.compose.animation) implementation(libs.kotlinx.coroutines.core) implementation(libs.koin.core) + implementation(libs.koin.compose) } androidMain.dependencies { diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.android.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.android.kt deleted file mode 100644 index 54f6ae3f21..0000000000 --- a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.android.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.di - -import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab - -/** - * Tabs available in this distribution, without resolving unconfigured tab factories. - * - * @author Dmitriy Moroz - */ -internal actual val platformDonateScreenTabs: Set = setOf( - DonateScreenTab.DONATION_OPTIONS, DonateScreenTab.SUPPORTERS, -) diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.android.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.android.kt new file mode 100644 index 0000000000..52971fda25 --- /dev/null +++ b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.android.kt @@ -0,0 +1,17 @@ +package com.shifthackz.aisdv1.presentation.donate.di + +import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider +import com.shifthackz.aisdv1.core.common.appbuild.BuildType +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection +import org.koin.core.scope.Scope + +/** + * Adds native tips only for the distribution with a Google Play product catalog. + * + * @author Dmitriy Moroz + */ +internal actual fun Scope.platformWaysToSupportSections(): Set = + when (get().type) { + BuildType.PLAY -> setOf(WaysToSupportSection.TIP_JAR, WaysToSupportSection.BACKEND_OPTIONS) + BuildType.FULL, BuildType.FOSS -> setOf(WaysToSupportSection.BACKEND_OPTIONS) + } diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreview.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreview.kt index f87171ff2b..f0b3f3c453 100644 --- a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreview.kt +++ b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreview.kt @@ -7,16 +7,13 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import com.shifthackz.aisdv1.presentation.components.theme.global.AiSdAppTheme import com.shifthackz.aisdv1.presentation.components.theme.global.AiSdAppThemeState -import com.shifthackz.aisdv1.presentation.donate.DonateBrandIcon import com.shifthackz.aisdv1.presentation.donate.DonateScreenContent import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab import com.shifthackz.aisdv1.presentation.donate.donateScreenStrings -import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsContent -import com.shifthackz.aisdv1.presentation.donate.options.donationOptionsStrings import com.shifthackz.aisdv1.presentation.donate.supporters.SupportersContent import com.shifthackz.aisdv1.presentation.donate.supporters.supportersStrings -import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarContent -import com.shifthackz.aisdv1.presentation.donate.tipjar.tipJarStrings +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportContent +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection /** * Renders independent tab snapshots without constructing any ViewModel or graph. @@ -35,7 +32,7 @@ internal fun DonatePreview(scenario: DonatePreviewCase) { applySystemBars = false, ) { DonateScreenContent( - tabs = scenario.tabs, + tabs = DonateScreenTab.entries.toSet(), selectedTab = scenario.tab, strings = donateScreenStrings(), onSelectTab = {}, @@ -48,13 +45,14 @@ internal fun DonatePreview(scenario: DonatePreviewCase) { ) } when (tab) { - DonateScreenTab.DONATION_OPTIONS -> DonationOptionsContent( - scenario.options, - donationOptionsStrings(), - listState, - canReportScroll, - {}, - brandIcon = { DonateBrandIcon() }) + DonateScreenTab.DONATION_OPTIONS -> WaysToSupportContent( + tips = scenario.tips.takeIf { WaysToSupportSection.TIP_JAR in scenario.sections }, + options = scenario.options.takeIf { WaysToSupportSection.BACKEND_OPTIONS in scenario.sections }, + listState = listState, + canReportToolbarScroll = canReportScroll, + onTipIntent = {}, + onOptionsIntent = {}, + ) DonateScreenTab.SUPPORTERS -> SupportersContent( scenario.supporters, @@ -63,13 +61,6 @@ internal fun DonatePreview(scenario: DonatePreviewCase) { canReportScroll ) - DonateScreenTab.TIP_JAR -> TipJarContent( - scenario.tips, - tipJarStrings(), - listState, - canReportScroll, - {}, - ) } } } diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewCase.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewCase.kt index 36115811b6..7f3b87ee25 100644 --- a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewCase.kt +++ b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewCase.kt @@ -4,6 +4,7 @@ import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsState import com.shifthackz.aisdv1.presentation.donate.supporters.SupportersState import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection /** * Preview-only independent tab snapshots and container selection, without application state ownership. @@ -13,7 +14,7 @@ import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState * @param options External catalog snapshot supplied only to its content. * @param supporters Acknowledgement snapshot supplied only to its content. * @param firstVisibleItem Initial selected-page lazy-list position. - * @param tabs Available pages matching a platform's container configuration. + * @param sections Support mechanisms rendered in the first page. * @param tips Store snapshot supplied only to the tip content. * @author Dmitriy Moroz */ @@ -23,9 +24,6 @@ internal data class DonatePreviewCase( val options: DonationOptionsState = DonationOptionsState(isLoadingOptions = false), val supporters: SupportersState = SupportersState(isLoadingSupporters = false), val firstVisibleItem: Int = 0, - val tabs: Set = setOf( - DonateScreenTab.DONATION_OPTIONS, - DonateScreenTab.SUPPORTERS - ), + val sections: Set = setOf(WaysToSupportSection.BACKEND_OPTIONS), val tips: TipJarState = TipJarState(), ) diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewParameterProvider.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewParameterProvider.kt index eeaf20ad49..9764ec289d 100644 --- a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewParameterProvider.kt +++ b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewParameterProvider.kt @@ -8,10 +8,9 @@ import com.shifthackz.aisdv1.domain.entity.DonationOptionKind import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsState import com.shifthackz.aisdv1.presentation.donate.supporters.SupportersState -import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState /** - * Supplies independent content snapshots for external-support and store-support tab configurations. + * Supplies independent content snapshots for backend, store and combined support configurations. * * @author Dmitriy Moroz */ @@ -24,25 +23,7 @@ internal class DonatePreviewParameterProvider : PreviewParameterProvider = cases.asSequence() /** diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/IapWaysToSupportPreviewCases.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/IapWaysToSupportPreviewCases.kt new file mode 100644 index 0000000000..fdac243775 --- /dev/null +++ b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/IapWaysToSupportPreviewCases.kt @@ -0,0 +1,143 @@ +package com.shifthackz.aisdv1.presentation.donate.preview + +import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsState +import com.shifthackz.aisdv1.presentation.donate.supporters.SupportersState +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection + +/** + * Supplies full-page previews for StoreKit and the Play Store, including both Play catalog load orders. + * + * @param backendReady Sample populated backend catalog shared with backend-only previews. + * @author Dmitriy Moroz + */ +internal fun iapWaysToSupportPreviewCases(backendReady: DonationOptionsState): List { + val tipsLoading = TipJarState() + val tipsEmpty = TipJarState(isLoading = false) + val tipsReady = tipsEmpty.copy(products = DonatePreviewFixtures.tipProducts) + val tipsFailed = tipsEmpty.copy(hasError = true) + val backendLoading = DonationOptionsState() + val backendEmpty = DonationOptionsState(isLoadingOptions = false) + val backendFailed = backendEmpty.copy(hasOptionsError = true) + val backendCached = backendReady.copy(isUsingCachedOptions = true) + val storeOnly = setOf(WaysToSupportSection.TIP_JAR) + val playSections = WaysToSupportSection.entries.toSet() + val payments = listOf( + "Purchase in progress" to tipsReady.copy(isPurchasing = true), + "Purchase error with prices" to tipsReady.copy(hasError = true), + "Pending payment" to tipsReady.copy(hasPendingNotice = true), + "Thank you" to tipsReady.copy(hasCompletedTip = true), + "Thank you and pending notice" to tipsReady.copy( + hasCompletedTip = true, + hasPendingNotice = true + ), + ) + val ios = ( + listOf( + "Loading" to tipsLoading, + "Tips available" to tipsReady, + "Empty store catalog" to tipsEmpty, + "Store error" to tipsFailed, + "Retrying store error" to tipsFailed.copy(isLoading = true), + ) + payments + tipsReady.products.map { product -> + "${product.title} only" to tipsReady.copy(products = listOf(product)) + } + ( + "Long store metadata" to tipsReady.copy( + products = listOf( + tipsReady.products.first().copy( + title = "A longer localized product title for supporting continued development", + description = "Optional support for the app and its continued development. ".repeat( + 3 + ), + formattedPrice = "1.234,99 €", + ) + ) + ) + ) + ).map { (name, tips) -> + DonatePreviewCase( + "iOS · $name", + sections = storeOnly, + tips = tips + ) + } + val playResults = listOf( + "Tips available" to tipsReady, + "Tips empty" to tipsEmpty, + "Store error" to tipsFailed + ) + .flatMap { (tipName, tips) -> + listOf( + "backend ready" to backendReady, + "backend empty" to backendEmpty, + "backend error" to backendFailed, + "backend cached" to backendCached, + ).map { (backendName, options) -> + DonatePreviewCase( + "Play Store · $tipName, $backendName", + sections = playSections, + tips = tips, + options = options + ) + } + } + val playTransitions = listOf( + Triple("Both catalogs loading", tipsLoading, backendLoading), + Triple("Waiting for backend", tipsReady, backendLoading), + Triple("Waiting for store", tipsLoading, backendReady), + Triple("Waiting for backend after store error", tipsFailed, backendLoading), + Triple("Waiting for store after backend error", tipsLoading, backendFailed), + Triple( + "Retrying both errors", + tipsFailed.copy(isLoading = true), + backendFailed.copy(isLoadingOptions = true) + ), + Triple( + "Retrying store with backend choices", + tipsFailed.copy(isLoading = true), + backendReady + ), + Triple( + "Retrying backend with tips", + tipsReady, + backendFailed.copy(isLoadingOptions = true) + ), + Triple("Refreshing saved choices", tipsReady, backendCached.copy(isLoadingOptions = true)), + Triple( + "Thank you with backend error", + tipsReady.copy(hasCompletedTip = true), + backendFailed + ), + ).map { (name, tips, options) -> + DonatePreviewCase( + "Play Store · $name", + sections = playSections, + tips = tips, + options = options + ) + } + val playPayments = payments.map { (name, tips) -> + DonatePreviewCase( + "Play Store · $name", + sections = playSections, + tips = tips, + options = backendReady + ) + } + return ios + playResults + playTransitions + playPayments + listOf( + DonatePreviewCase( + "iOS · Supporters", + tab = DonateScreenTab.SUPPORTERS, + sections = storeOnly, + supporters = SupportersState(false, DonatePreviewFixtures.mixed), + ), + DonatePreviewCase( + "Play Store · Scrolled to tips and backend choices", + sections = playSections, + tips = tipsReady, + options = backendReady, + firstVisibleItem = tipsReady.products.size, + ), + ) +} diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewCase.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewCase.kt deleted file mode 100644 index d1b529de0e..0000000000 --- a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewCase.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.preview - -import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState - -/** - * Names a fixed store snapshot for the preview picker without initiating purchases. - * - * @param name Descriptive picker label. - * @param state Product availability and payment feedback to render. - * @author Dmitriy Moroz - */ -internal data class TipJarPreviewCase( - val name: String, - val state: TipJarState, -) diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewParameterProvider.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewParameterProvider.kt deleted file mode 100644 index de314cb0f2..0000000000 --- a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviewParameterProvider.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.preview - -import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState - -/** - * Supplies store loading, recovery and payment-feedback snapshots without a graph or store connection. - * - * @author Dmitriy Moroz - */ -internal class TipJarPreviewParameterProvider : PreviewParameterProvider { - private val ready = TipJarState(isLoading = false, products = DonatePreviewFixtures.tipProducts) - private val cases = listOf( - TipJarPreviewCase("Initial loading", TipJarState()), - TipJarPreviewCase("Products unavailable", TipJarState(isLoading = false)), - TipJarPreviewCase("Store error", TipJarState(isLoading = false, hasError = true)), - TipJarPreviewCase("Store error retrying", TipJarState(hasError = true)), - TipJarPreviewCase("Support choices", ready), - TipJarPreviewCase("Purchasing", ready.copy(isPurchasing = true)), - TipJarPreviewCase("Purchase error with choices", ready.copy(hasError = true)), - TipJarPreviewCase("Request submitted", ready.copy(hasPendingNotice = true)), - TipJarPreviewCase("Verified thanks", ready.copy(hasCompletedTip = true)), - TipJarPreviewCase( - "Thanks and submission notice", - ready.copy(hasCompletedTip = true, hasPendingNotice = true) - ), - TipJarPreviewCase("Small tip only", ready.copy(products = listOf(ready.products[0]))), - TipJarPreviewCase("Medium tip only", ready.copy(products = listOf(ready.products[1]))), - TipJarPreviewCase("Large tip only", ready.copy(products = listOf(ready.products[2]))), - TipJarPreviewCase( - "Long store metadata", - ready.copy( - products = listOf( - ready.products.first().copy( - title = "A longer localized product title for supporting continued development", - description = "Optional support for the app and its continued development. ".repeat( - 3 - ), - formattedPrice = "1.234,99 €", - ) - ) - ), - ), - ) - override val values: Sequence = cases.asSequence() - - /** - * Names the product or payment state in the preview picker. - * - * @param index Ordered snapshot position. - * @author Dmitriy Moroz - */ - override fun getDisplayName(index: Int): String = cases[index].name -} diff --git a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviews.android.kt b/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviews.android.kt deleted file mode 100644 index a9fbf782e0..0000000000 --- a/presentation/donate/src/androidMain/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/TipJarPreviews.android.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.preview - -import android.content.res.Configuration -import androidx.compose.foundation.isSystemInDarkTheme -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.runtime.Composable -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.tooling.preview.PreviewParameter -import com.shifthackz.aisdv1.presentation.components.theme.global.AiSdAppTheme -import com.shifthackz.aisdv1.presentation.components.theme.global.AiSdAppThemeState -import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarContent -import com.shifthackz.aisdv1.presentation.donate.tipjar.tipJarStrings - -/** - * Renders tip loading, store failure, payment progress and acknowledgement in the application theme. - * - * @param scenario Named store snapshot without native payment actions. - * @author Dmitriy Moroz - */ -@Preview(name = "Tip jar light", group = "Donate tips", widthDp = 360, heightDp = 800) -@Preview( - name = "Tip jar dark", - group = "Donate tips", - widthDp = 360, - heightDp = 800, - uiMode = Configuration.UI_MODE_NIGHT_YES -) -@Preview(name = "Tip jar compact", group = "Donate tips", widthDp = 320, heightDp = 640) -@Preview(name = "Tip jar tablet", group = "Donate tips", widthDp = 756, heightDp = 1024) -@Preview(name = "Tip jar landscape", group = "Donate tips", widthDp = 800, heightDp = 360) -@Preview( - name = "Tip jar large text", - group = "Donate tips", - widthDp = 360, - heightDp = 800, - fontScale = 1.5f -) -@Composable -private fun TipJarPreview(@PreviewParameter(TipJarPreviewParameterProvider::class) scenario: TipJarPreviewCase) { - AiSdAppTheme( - state = AiSdAppThemeState( - shouldUseSystemDarkTheme = false, - isDarkTheme = isSystemInDarkTheme(), - shouldUseSystemColorPalette = false, - ), - applySystemBars = false, - ) { - Surface(color = MaterialTheme.colorScheme.background) { - TipJarContent(scenario.state, tipJarStrings(), rememberLazyListState(), false, {}) - } - } -} diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateContainerTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateContainerTest.kt index ad0409c62b..8712bb35bb 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateContainerTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateContainerTest.kt @@ -23,7 +23,6 @@ import com.shifthackz.aisdv1.core.localization.Localization import org.junit.After import org.junit.Before import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -111,33 +110,6 @@ class DonateContainerTest { assertEquals(1, backCount) } - @Test - fun `given tip jar and supporters tab set, container composes pages, expected external tab is never composed`() { - // Given - val composed = mutableSetOf() - val iosTabs = setOf(DonateScreenTab.TIP_JAR, DonateScreenTab.SUPPORTERS) - - // When - compose.setContent { - MaterialTheme { - DonateScreenContent( - iosTabs, - DonateScreenTab.TIP_JAR, - donateScreenStrings(), - {}, - {}) { tab, _, _ -> - composed += tab - Text(tab.name) - } - } - } - compose.waitForIdle() - - // Then - assertEquals(iosTabs, composed) - assertFalse(DonateScreenTab.DONATION_OPTIONS in composed) - } - private fun render() { compose.setContent { var selected by remember { mutableStateOf(DonateScreenTab.DONATION_OPTIONS) } diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonatePreviewCoverageTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonatePreviewCoverageTest.kt index 97cb635aa0..419ada975b 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonatePreviewCoverageTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonatePreviewCoverageTest.kt @@ -3,50 +3,43 @@ package com.shifthackz.aisdv1.presentation.donate import com.shifthackz.aisdv1.domain.entity.DonationOptionKind import com.shifthackz.aisdv1.presentation.donate.preview.DonatePreviewParameterProvider -import com.shifthackz.aisdv1.presentation.donate.preview.TipJarPreviewParameterProvider +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test /** - * Keeps the preview picker representative of platform tab sets and loading, recovery and payment states. + * Keeps the preview picker representative of distribution catalogs and payment feedback. * * @author Dmitriy Moroz */ class DonatePreviewCoverageTest { @Test - fun `given donation container previews, available tabs are inspected, expected platform configurations with valid selected content`() { + fun `given donation container previews, available support sections are inspected, expected all distribution configurations`() { // Given val cases = DonatePreviewParameterProvider().values.toList() // When - val store = cases.filter { DonateScreenTab.TIP_JAR in it.tabs } - val external = cases.filter { DonateScreenTab.DONATION_OPTIONS in it.tabs } + val store = cases.filter { it.sections == setOf(WaysToSupportSection.TIP_JAR) } + val external = cases.filter { it.sections == setOf(WaysToSupportSection.BACKEND_OPTIONS) } // Then - assertTrue(cases.all { it.tab in it.tabs }) assertTrue(store.isNotEmpty()) assertTrue(external.isNotEmpty()) - assertTrue(store.all { DonateScreenTab.DONATION_OPTIONS !in it.tabs }) + assertTrue(cases.any { it.sections == WaysToSupportSection.entries.toSet() }) assertTrue(store.any { it.tab == DonateScreenTab.SUPPORTERS }) - assertTrue(store.any { it.tab == DonateScreenTab.TIP_JAR && it.tips.hasError }) - assertTrue(store.any { it.tab == DonateScreenTab.TIP_JAR && it.tips.isLoading }) - assertTrue(store.any { it.tab == DonateScreenTab.TIP_JAR && it.tips.products.isNotEmpty() }) + assertTrue(store.any { it.tab == DonateScreenTab.DONATION_OPTIONS && it.tips.hasError }) + assertTrue(store.any { it.tab == DonateScreenTab.DONATION_OPTIONS && it.tips.isLoading }) + assertTrue(store.any { it.tab == DonateScreenTab.DONATION_OPTIONS && it.tips.products.isNotEmpty() }) } @Test - fun `given tip jar previews, named states are inspected, expected loading recovery and distinct payment feedback coverage`() { + fun `given iOS support previews, named states are inspected, expected loading recovery and distinct payment feedback coverage`() { // Given - val provider = TipJarPreviewParameterProvider() - val cases = provider.values.toList() + val cases = DonatePreviewParameterProvider().values.filter { + it.sections == setOf(WaysToSupportSection.TIP_JAR) && it.tab == DonateScreenTab.DONATION_OPTIONS + } // When - val states = cases.map { it.state } + val states = cases.map { it.tips }.toList() // Then - assertEquals(cases.size, cases.map { it.name }.distinct().size) - cases.forEachIndexed { index, scenario -> - assertEquals( - scenario.name, - provider.getDisplayName(index) - ) - } assertTrue(states.any { it.isLoading && !it.hasError }) assertTrue(states.any { it.isLoading && it.hasError }) assertTrue(states.any { !it.isLoading && !it.hasError && it.products.isEmpty() }) @@ -58,6 +51,24 @@ class DonatePreviewCoverageTest { assertTrue(states.any { it.products.size == 1 }) } + @Test + fun `given Play support previews, catalog combinations are inspected, expected both load orders and all failure combinations`() { + // Given + val provider = DonatePreviewParameterProvider() + // When + val play = + provider.values.filter { it.sections == WaysToSupportSection.entries.toSet() }.toList() + // Then + assertTrue(play.any { it.tips.isLoading && it.options.isLoadingOptions }) + assertTrue(play.any { it.tips.isLoading && it.options.donationGroups.isNotEmpty() }) + assertTrue(play.any { it.tips.products.isNotEmpty() && it.options.isLoadingOptions }) + assertTrue(play.any { it.tips.hasError && it.options.hasOptionsError }) + assertTrue(play.any { it.tips.hasError && it.options.donationGroups.isNotEmpty() }) + assertTrue(play.any { it.tips.products.isNotEmpty() && it.options.hasOptionsError }) + assertTrue(play.any { it.tips.hasCompletedTip && it.options.isUsingCachedOptions.not() }) + assertTrue(play.any { it.tips.hasPendingNotice && it.options.donationGroups.isNotEmpty() }) + } + @Test fun `given donation preview catalog, scenarios are enumerated, expected unique descriptive picker names`() { // Given diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateRouteIntegrationTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateRouteIntegrationTest.kt index ea17078e53..e4e9399227 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateRouteIntegrationTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateRouteIntegrationTest.kt @@ -7,14 +7,23 @@ import android.content.Intent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasAnyDescendant import androidx.compose.ui.test.hasClickAction import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performScrollToNode +import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider +import com.shifthackz.aisdv1.core.common.appbuild.BuildType import com.shifthackz.aisdv1.core.common.links.LinksProvider import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider import com.shifthackz.aisdv1.core.localization.Localization @@ -27,6 +36,7 @@ import com.shifthackz.aisdv1.domain.entity.DonationOption import com.shifthackz.aisdv1.domain.usecase.donate.FetchOrGetDonationOptionsUseCase import com.shifthackz.aisdv1.domain.usecase.donate.FetchSupportersUseCase import com.shifthackz.aisdv1.presentation.donate.di.donateViewModelModule +import com.shifthackz.aisdv1.presentation.donate.di.waysToSupportSectionsQualifier import io.mockk.coVerify import io.mockk.coEvery import io.mockk.every @@ -40,11 +50,14 @@ import com.shifthackz.aisdv1.domain.usecase.donate.GetTipProductsUseCase import com.shifthackz.aisdv1.domain.usecase.donate.PurchaseTipUseCase import com.shifthackz.aisdv1.domain.usecase.donate.ObserveTipTransactionsUseCase import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsViewModel +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection import org.koin.mp.KoinPlatform.getKoin +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.Dispatchers import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test @@ -74,6 +87,7 @@ class DonateRouteIntegrationTest { private val observeTips = mockk() private val supporters = mockk() private val router = mockk(relaxed = true) + private var buildType = BuildType.FULL private lateinit var previousLanguage: String private val group = DonationGroup( "network", "Bitcoin", "Bitcoin network", true, listOf( @@ -126,6 +140,11 @@ class DonateRouteIntegrationTest { every { observeTips() } returns emptyFlow() startKoin { modules(donateViewModelModule, module { + single { + object : BuildInfoProvider by BuildInfoProvider.stub { + override val type = buildType + } + } single { mockk(relaxed = true) } single { object : DispatchersProvider { @@ -240,14 +259,37 @@ class DonateRouteIntegrationTest { coVerify(exactly = 0) { getProducts() } } + @OptIn(ExperimentalTestApi::class) + @Test + fun `given a saved donation tab no longer available, the route restores, expected the first supported tab opens`() { + // Given + var configuredTabs = androidTabs + val restoration = StateRestorationTester(compose) + restoration.setContent { MaterialTheme { DonateScreen(configuredTabs, router) } } + compose.onNode(hasText(Localization.string("donate_supporters_tab")) and hasClickAction()) + .performClick() + compose.waitForIdle() + + // When + configuredTabs = setOf(DonateScreenTab.DONATION_OPTIONS) + restoration.emulateSavedInstanceStateRestore() + + // Then + compose.onNodeWithText(Localization.string("donate_supporters_tab")).assertDoesNotExist() + compose.onNodeWithText(Localization.string("donate_support_explanation")) + .assertIsDisplayed() + } + @Test - fun `given tip jar and supporters tabs, submitted notice survives tab switches, expected retained tip state and no external ViewModel resolution`() { + fun `given tips only in Ways to support, a pending payment is followed by tab switches, expected retained tip state without loading backend options`() { // Given getKoin().loadModules(listOf(module { + single>(waysToSupportSectionsQualifier) { + setOf(WaysToSupportSection.TIP_JAR) + } factory { error("External options must not be resolved") } })) - val iosTabs = setOf(DonateScreenTab.TIP_JAR, DonateScreenTab.SUPPORTERS) - compose.setContent { MaterialTheme { DonateScreen(iosTabs, router) } } + compose.setContent { MaterialTheme { DonateScreen(androidTabs, router) } } compose.onNodeWithText("€1.19").performScrollTo().performClick() compose.onNodeWithText(Localization.string("donate_tip_pending")).assertIsDisplayed() @@ -267,4 +309,133 @@ class DonateRouteIntegrationTest { coVerify(exactly = 0) { options() } } + @Test + fun `given Play Ways to support, user scrolls from native tips to the backend catalog, expected both options in the same tab`() { + // Given + buildType = BuildType.PLAY + compose.setContent { MaterialTheme { DonateScreen(androidTabs, router) } } + compose.onNodeWithText("€1.19").assertIsDisplayed() + + // When + val supportList = + SemanticsMatcher.keyIsDefined(SemanticsProperties.VerticalScrollAxisRange) and + hasAnyDescendant(hasText("€1.19")) + compose.onNode(supportList).performScrollToNode(hasText("ExactCaseAddress")) + + // Then + compose.onNodeWithText("ExactCaseAddress").assertIsDisplayed() + coVerify(exactly = 1) { getProducts() } + coVerify(exactly = 1) { options() } + } + + @Test + fun `given Play Ways to support with tips loaded first, backend catalog resolves, expected one shimmer replaced by both catalogs`() { + // Given + buildType = BuildType.PLAY + val backend = CompletableDeferred>() + coEvery { options() } coAnswers { backend.await() } + compose.setContent { MaterialTheme { DonateScreen(androidTabs, router) } } + val progress = SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo) + compose.onAllNodes(progress).assertCountEquals(1) + compose.onNodeWithText(Localization.string("donate_support_explanation")) + .assertIsDisplayed() + compose.onNodeWithText("€1.19").assertDoesNotExist() + + // When + backend.complete(Result.success(DonationContent(DonationCatalog(1, listOf(group)), false))) + compose.waitForIdle() + + // Then + compose.onAllNodes(progress).assertCountEquals(0) + val tipBounds = compose.onNodeWithText("€1.19").fetchSemanticsNode().boundsInRoot + val networkBounds = + compose.onNodeWithText(Localization.string("donate_network_label", group.network)) + .fetchSemanticsNode().boundsInRoot + assertTrue(tipBounds.bottom < networkBounds.top) + } + + @Test + fun `given Play Ways to support with both catalogs failed, Retry is clicked, expected one banner retries both sources`() { + // Given + buildType = BuildType.PLAY + coEvery { getProducts() } returns Result.failure(IllegalStateException("Store unavailable")) + coEvery { options() } returns Result.failure(IllegalStateException("Backend unavailable")) + compose.setContent { MaterialTheme { DonateScreen(androidTabs, router) } } + + // When + val retry = hasText(Localization.string("retry")) and hasClickAction() + compose.onAllNodes(retry).assertCountEquals(1) + compose.onNode(retry).performClick() + + // Then + compose.onNodeWithText(Localization.string("donate_options_error")).assertIsDisplayed() + compose.onNodeWithText(Localization.string("donate_tip_error")).assertDoesNotExist() + coVerify(exactly = 2) { getProducts() } + coVerify(exactly = 2) { options() } + } + + @Test + fun `given Play Ways to support with backend loaded first, store discovery fails, expected shimmer stops and retry targets only the store`() { + // Given + buildType = BuildType.PLAY + val store = CompletableDeferred>>() + coEvery { getProducts() } coAnswers { store.await() } + compose.setContent { MaterialTheme { DonateScreen(androidTabs, router) } } + val progress = SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo) + compose.onAllNodes(progress).assertCountEquals(1) + compose.onNodeWithText("ExactCaseAddress").assertDoesNotExist() + + // When + store.complete(Result.failure(IllegalStateException("Store unavailable"))) + compose.onNodeWithText(Localization.string("retry")).performClick() + + // Then + compose.onAllNodes(progress).assertCountEquals(0) + compose.onNodeWithText(Localization.string("donate_tip_error")).assertIsDisplayed() + compose.onNodeWithText("ExactCaseAddress").performScrollTo().assertIsDisplayed() + coVerify(exactly = 2) { getProducts() } + coVerify(exactly = 1) { options() } + } + + @Test + fun `given Play Ways to support with a backend failure, a store tip completes, expected acknowledgement and only the backend retries`() { + // Given + buildType = BuildType.PLAY + val tipId = TipProducts.ids.first() + coEvery { purchaseTip(tipId) } returns Result.success( + IapPurchaseResult( + IapPurchaseStatus.COMPLETED, + tipId, + "settled" + ) + ) + coEvery { options() } returns Result.failure(IllegalStateException("Backend unavailable")) + compose.setContent { MaterialTheme { DonateScreen(androidTabs, router) } } + compose.onNodeWithText("€1.19").performScrollTo().performClick() + compose.onNodeWithText(Localization.string("donate_tip_thanks"), substring = true) + .assertIsDisplayed() + + // When + coEvery { options() } returns Result.success( + DonationContent( + DonationCatalog( + 1, + listOf(group) + ), false + ) + ) + compose.onNodeWithText(Localization.string("retry")).performClick() + + // Then + compose.onNodeWithText(Localization.string("donate_options_error"), substring = true) + .assertDoesNotExist() + compose.onNodeWithText(Localization.string("donate_tip_thanks")).assertIsDisplayed() + val list = SemanticsMatcher.keyIsDefined(SemanticsProperties.VerticalScrollAxisRange) and + hasAnyDescendant(hasText(Localization.string("donate_support_explanation"))) + compose.onNode(list).performScrollToNode(hasText("ExactCaseAddress")) + compose.onNodeWithText("ExactCaseAddress").assertIsDisplayed() + coVerify(exactly = 2) { options() } + coVerify(exactly = 1) { getProducts() } + coVerify(exactly = 1) { purchaseTip(tipId) } + } } diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DiModuleTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DiModuleTest.kt index 7921bd4426..da73a49844 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DiModuleTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DiModuleTest.kt @@ -1,15 +1,19 @@ package com.shifthackz.aisdv1.presentation.donate.di +import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider +import com.shifthackz.aisdv1.core.common.appbuild.BuildType import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsViewModel import com.shifthackz.aisdv1.presentation.donate.supporters.SupportersViewModel import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarViewModel +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection import com.shifthackz.aisdv1.test.di.bindingTypes import com.shifthackz.aisdv1.test.di.concreteServiceKeys import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.koin.dsl.koinApplication +import org.koin.dsl.module class DiModuleTest { @Test @@ -29,15 +33,11 @@ class DiModuleTest { // Then assertEquals(expectedTypes, types) - assertEquals( - setOf(DonateScreenTab.DONATION_OPTIONS, DonateScreenTab.SUPPORTERS), - platformDonateScreenTabs - ) assertTrue("Unexpected implementation keys: $concreteKeys", concreteKeys.isEmpty()) } @Test - fun `given Android donation graph without tab collaborators, configured tabs are resolved, expected external options and supporters without creating ViewModels`() { + fun `given Android donation graph without tab collaborators, configured tabs are resolved, expected Ways to support and supporters without creating ViewModels`() { // Given val application = koinApplication { modules(donateViewModelModule) } @@ -49,4 +49,36 @@ class DiModuleTest { application.close() } + @Test + fun `given Android support sections, each build flavor is resolved, expected native tips only for Play and backend options for all`() { + // Given + val expected = mapOf( + BuildType.PLAY to setOf( + WaysToSupportSection.TIP_JAR, + WaysToSupportSection.BACKEND_OPTIONS + ), + BuildType.FULL to setOf(WaysToSupportSection.BACKEND_OPTIONS), + BuildType.FOSS to setOf(WaysToSupportSection.BACKEND_OPTIONS), + ) + + for ((buildType, sections) in expected) { + val application = koinApplication { + modules(donateViewModelModule, module { + single { + object : BuildInfoProvider by BuildInfoProvider.stub { + override val type = buildType + } + } + }) + } + + // When + val actual = + application.koin.get>(waysToSupportSectionsQualifier) + + // Then + assertEquals(buildType.name, sections, actual) + application.close() + } + } } diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContentTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContentTest.kt index 2e54458a24..9cc4e8b2f6 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContentTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContentTest.kt @@ -2,11 +2,8 @@ package com.shifthackz.aisdv1.presentation.donate.options import com.shifthackz.aisdv1.domain.entity.DonationOptionKind -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme -import androidx.compose.ui.Modifier import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.assertWidthIsAtLeast @@ -23,6 +20,7 @@ import com.shifthackz.aisdv1.core.localization.Localization import com.shifthackz.aisdv1.domain.entity.DonationAsset import com.shifthackz.aisdv1.domain.entity.DonationGroup import com.shifthackz.aisdv1.domain.entity.DonationOption +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportContent import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before @@ -152,7 +150,8 @@ class DonationOptionsContentTest { // Then assertEquals(listOf(DonationOptionsIntent.SelectOption("wallet")), intents) compose.onNodeWithText("BTC").assertIsDisplayed() - compose.onNodeWithText("Bitcoin network").assertIsDisplayed() + compose.onNodeWithText(Localization.string("donate_network_label", group.network)) + .assertIsDisplayed() } @Test @@ -170,7 +169,7 @@ class DonationOptionsContentTest { group.copy( network = "", options = listOf(link) - ), donationOptionsStrings(), { intents += it }) + ), { intents += it }) } } // When @@ -225,14 +224,14 @@ class DonationOptionsContentTest { private fun render(state: DonationOptionsState) { compose.setContent { MaterialTheme { - Box(Modifier.fillMaxSize()) { - DonationOptionsContent( - state, - donationOptionsStrings(), - rememberLazyListState(), - true, - { intents += it }) - } + WaysToSupportContent( + tips = null, + options = state, + listState = rememberLazyListState(), + canReportToolbarScroll = true, + onTipIntent = {}, + onOptionsIntent = { intents += it }, + ) } } } diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewRenderingTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewRenderingTest.kt index d727acffd8..39f8ae22be 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewRenderingTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/preview/DonatePreviewRenderingTest.kt @@ -4,8 +4,6 @@ import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.hasText -import androidx.compose.ui.test.hasClickAction import com.shifthackz.aisdv1.core.localization.Localization import org.junit.After import org.junit.Before @@ -16,7 +14,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** - * Runs the graph-free preview renderer through its real independent tab content. + * Verifies the preview renderer uses the same support list and tab content as the route. * * @author Dmitriy Moroz */ @@ -42,7 +40,7 @@ class DonatePreviewRenderingTest { fun `given store preview, catalog is rendered, expected Apple metadata and inert payment action`() { // Given val scenario = - DonatePreviewParameterProvider().values.single { it.name == "Store container choices" } + DonatePreviewParameterProvider().values.single { it.name == "iOS · Tips available" } val product = scenario.tips.products.first() // When @@ -50,6 +48,8 @@ class DonatePreviewRenderingTest { compose.onNodeWithText(product.formattedPrice).performClick() // Then + compose.onNodeWithText(Localization.string("donate_support_explanation")) + .assertIsDisplayed() compose.onNodeWithText(product.title).assertIsDisplayed() compose.onNodeWithText(product.formattedPrice).assertIsDisplayed() } @@ -57,14 +57,16 @@ class DonatePreviewRenderingTest { @Test fun `given external preview, empty options render, expected support invitation without application graph`() { // Given - val scenario = DonatePreviewParameterProvider().values.single { it.name == "Payment empty" } + val scenario = + DonatePreviewParameterProvider().values.single { it.name == "Full / FOSS · Payment empty" } // When compose.setContent { DonatePreview(scenario) } // Then - compose.onNode(hasText(Localization.string("donate_options_title")) and hasClickAction()) + compose.onNodeWithText(Localization.string("donate_support_explanation")) .assertIsDisplayed() + compose.onNodeWithText(Localization.string("donate_options_empty")).assertIsDisplayed() } @Test diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContentTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContentTest.kt index e891b8b2aa..a862359197 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContentTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContentTest.kt @@ -20,6 +20,7 @@ import androidx.compose.ui.unit.dp import com.shifthackz.aisdv1.core.localization.Localization import com.shifthackz.aisdv1.domain.entity.IapProduct import com.shifthackz.aisdv1.domain.entity.TipProducts +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportContent import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before @@ -165,7 +166,8 @@ class TipJarContentTest { // Then assertEquals(listOf(TipJarIntent.DismissNotice), intents) compose.onNodeWithText(Localization.string("action_close")).assertWidthIsAtLeast(144.dp) - compose.onNodeWithText(Localization.string("donate_options_title")).assertIsDisplayed() + compose.onNodeWithText(Localization.string("donate_support_explanation")) + .assertIsDisplayed() compose.onNodeWithText(Localization.string("donate_tip_pending")).assertIsDisplayed() compose.onNodeWithText(product.formattedPrice).assertIsDisplayed() } @@ -194,7 +196,8 @@ class TipJarContentTest { // Then assertEquals(listOf(TipJarIntent.Retry), intents) compose.onNodeWithText(Localization.string("retry")).assertWidthIsAtLeast(144.dp) - compose.onNodeWithText(Localization.string("donate_options_title")).assertIsDisplayed() + compose.onNodeWithText(Localization.string("donate_support_explanation")) + .assertIsDisplayed() compose.onNodeWithText(Localization.string("donate_tip_error")).assertIsDisplayed() compose.onNodeWithText(Localization.string("donate_tip_unavailable")).assertDoesNotExist() } @@ -249,12 +252,14 @@ class TipJarContentTest { private fun render(state: TipJarState) { compose.setContent { MaterialTheme { - TipJarContent( - state, - tipJarStrings(), - rememberLazyListState(), - false, - { intents += it }) + WaysToSupportContent( + tips = state, + options = null, + listState = rememberLazyListState(), + canReportToolbarScroll = false, + onTipIntent = { intents += it }, + onOptionsIntent = {}, + ) } } } diff --git a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarViewModelTest.kt b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarViewModelTest.kt index dc9127982a..c37906cda2 100644 --- a/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarViewModelTest.kt +++ b/presentation/donate/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarViewModelTest.kt @@ -26,6 +26,11 @@ import org.junit.Assert.assertTrue import org.junit.Test import androidx.lifecycle.ViewModelStore +/** + * Checks catalog and purchase state transitions using the shared donation contracts. + * + * @author Dmitriy Moroz + */ @OptIn(ExperimentalCoroutinesApi::class) class TipJarViewModelTest { private val dispatcher = StandardTestDispatcher() @@ -433,6 +438,37 @@ class TipJarViewModelTest { assertFalse(model.state.value.isPurchasing) } + @Test + fun `given a loaded tip catalog, a retry fails and the next refresh returns partial prices, expected old choices retained only until successful refresh`() = + runTest(dispatcher) { + // Given + val model = model() + advanceUntilIdle() + val failure = CompletableDeferred>>() + coEvery { products() } coAnswers { failure.await() } + model.processIntent(TipJarIntent.Retry) + runCurrent() + assertTrue(model.state.value.isLoading) + assertEquals(listOf(product), model.state.value.products) + + // When + failure.complete(Result.failure(IllegalStateException("Offline"))) + advanceUntilIdle() + assertTrue(model.state.value.hasError) + assertEquals(listOf(product), model.state.value.products) + val medium = product.copy(productId = TipProducts.ids[1], formattedPrice = "269,99 UAH") + coEvery { products() } returns Result.success(listOf(medium)) + model.processIntent(TipJarIntent.Retry) + advanceUntilIdle() + model.processIntent(TipJarIntent.Purchase(product.productId)) + + // Then + assertEquals(listOf(medium), model.state.value.products) + assertFalse(model.state.value.isLoading) + assertFalse(model.state.value.hasError) + coVerify(exactly = 0) { purchase(any()) } + } + private fun model() = TipJarViewModel( diagnostics = mockk(relaxed = true), dispatchers = object : DispatchersProvider { diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateLoading.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateLoading.kt index 9718e7f540..0b0c608374 100644 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateLoading.kt +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateLoading.kt @@ -23,20 +23,27 @@ import com.shifthackz.aisdv1.core.extensions.shimmer import com.shifthackz.aisdv1.presentation.components.widget.surface.PlatformSurface /** - * Reserves themed card space with the shared shimmer animation while a tab loads its first content. + * Selects the placeholder geometry for each independently loaded donation content group. * - * @param tab Tab whose content geometry the placeholder collection reserves. + * @author Dmitriy Moroz + */ +internal enum class DonateLoadingStyle { DONATION_OPTIONS, TIP_JAR, SUPPORTERS } + +/** + * Reserves themed card space with the shared shimmer animation while a section loads its first content. + * + * @param style Content geometry that the placeholder collection reserves. * @param loadingDescription Localized loading announcement for the placeholder collection. * @param modifier Bounds of the loading collection. * @author Dmitriy Moroz */ @Composable internal fun DonateLoading( - tab: DonateScreenTab, + style: DonateLoadingStyle, loadingDescription: String, modifier: Modifier = Modifier, ) { - val isSupporters = tab == DonateScreenTab.SUPPORTERS + val isSupporters = style == DonateLoadingStyle.SUPPORTERS Column( modifier = modifier.fillMaxWidth().semantics { contentDescription = loadingDescription @@ -48,10 +55,10 @@ internal fun DonateLoading( PlatformSurface( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape( - when (tab) { - DonateScreenTab.SUPPORTERS -> 16.dp - DonateScreenTab.DONATION_OPTIONS -> 20.dp - DonateScreenTab.TIP_JAR -> 24.dp + when (style) { + DonateLoadingStyle.SUPPORTERS -> 16.dp + DonateLoadingStyle.DONATION_OPTIONS -> 20.dp + DonateLoadingStyle.TIP_JAR -> 24.dp } ), color = MaterialTheme.colorScheme.surfaceVariant, @@ -60,7 +67,7 @@ internal fun DonateLoading( Modifier.padding(if (isSupporters) 12.dp else 20.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - if (tab == DonateScreenTab.TIP_JAR) { + if (style == DonateLoadingStyle.TIP_JAR) { Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { Box(Modifier.size(80.dp).clip(RoundedCornerShape(16.dp)).shimmer()) Column( @@ -88,18 +95,18 @@ internal fun DonateLoading( .shimmer() ) } - if (tab == DonateScreenTab.DONATION_OPTIONS) { + if (style == DonateLoadingStyle.DONATION_OPTIONS) { Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { repeat(3) { Box(Modifier.size(28.dp).clip(CircleShape).shimmer()) } } } - if (tab != DonateScreenTab.TIP_JAR) { + if (style != DonateLoadingStyle.TIP_JAR) { Box( Modifier.fillMaxWidth().height(18.dp).clip(RoundedCornerShape(8.dp)) .shimmer() ) } - if (tab == DonateScreenTab.DONATION_OPTIONS) { + if (style == DonateLoadingStyle.DONATION_OPTIONS) { Box( Modifier.fillMaxWidth(0.8f).height(18.dp).clip(RoundedCornerShape(8.dp)) .shimmer() diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreen.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreen.kt index cf30a96aaf..7b9983bac1 100644 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreen.kt +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreen.kt @@ -2,19 +2,18 @@ package com.shifthackz.aisdv1.presentation.donate import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.runtime.setValue -import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import com.shifthackz.aisdv1.core.navigation.router.DonateRouter -import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsScreen import com.shifthackz.aisdv1.presentation.donate.supporters.SupportersScreen -import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarScreen +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportScreen /** * Contains only route navigation and the configured independent support tabs. * - * @param tabs Tabs declared by the distribution composition root. + * @param tabs Pages declared by the caller. The support page selects its own sections. * @param router Caller-owned back navigation. * @param modifier Bounds applied to the donation container. * @author Dmitriy Moroz @@ -38,8 +37,7 @@ fun DonateScreen( modifier = modifier, ) { tab, listState, canReportScroll -> when (tab) { - DonateScreenTab.DONATION_OPTIONS -> DonationOptionsScreen(listState, canReportScroll) - DonateScreenTab.TIP_JAR -> TipJarScreen(listState, canReportScroll) + DonateScreenTab.DONATION_OPTIONS -> WaysToSupportScreen(listState, canReportScroll) DonateScreenTab.SUPPORTERS -> SupportersScreen(listState, canReportScroll) } } diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreenTab.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreenTab.kt index 8f1daaa5b0..0174eb2fb4 100644 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreenTab.kt +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/DonateScreenTab.kt @@ -6,4 +6,4 @@ package com.shifthackz.aisdv1.presentation.donate * * @author Dmitriy Moroz */ -enum class DonateScreenTab { DONATION_OPTIONS, TIP_JAR, SUPPORTERS } +enum class DonateScreenTab { DONATION_OPTIONS, SUPPORTERS } diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateViewModelModule.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateViewModelModule.kt index 285e6ba862..5d2776bcf1 100644 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateViewModelModule.kt +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateViewModelModule.kt @@ -4,7 +4,9 @@ import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsViewModel import com.shifthackz.aisdv1.presentation.donate.supporters.SupportersViewModel import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarViewModel +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection import org.koin.core.qualifier.named +import org.koin.core.scope.Scope import org.koin.dsl.module /** @@ -15,20 +17,28 @@ import org.koin.dsl.module val donateTabsQualifier = named("DonateScreenTabs") /** - * Declares independent tab factories and the distribution-selected tabs. + * Identifies the support mechanisms shown together in the Ways to support tab. + * + * @author Dmitriy Moroz + */ +internal val waysToSupportSectionsQualifier = named("WaysToSupportSections") + +/** + * Keeps pager navigation and independently loaded support sections separately configurable. * * @author Dmitriy Moroz */ val donateViewModelModule = module { - single>(donateTabsQualifier) { platformDonateScreenTabs } + single>(donateTabsQualifier) { DonateScreenTab.entries.toSet() } + single>(waysToSupportSectionsQualifier) { platformWaysToSupportSections() } factory { DonationOptionsViewModel(get(), get(), get(), get()) } factory { SupportersViewModel(get(), get(), get()) } factory { TipJarViewModel(get(), get(), get(), get(), get()) } } /** - * Supplies fixed platform tab declarations without a payment-mode flag. + * Selects the sections supported by the current platform and distribution. * * @author Dmitriy Moroz */ -internal expect val platformDonateScreenTabs: Set +internal expect fun Scope.platformWaysToSupportSections(): Set diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationGroupCard.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationGroupCard.kt index f06bac2bf2..5b0566f07d 100644 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationGroupCard.kt +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationGroupCard.kt @@ -18,6 +18,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization import com.shifthackz.aisdv1.domain.entity.DonationGroup import com.shifthackz.aisdv1.domain.entity.DonationOptionKind import com.shifthackz.aisdv1.presentation.components.widget.action.PrimaryButton @@ -27,7 +28,6 @@ import com.shifthackz.aisdv1.presentation.components.widget.surface.PlatformSurf * Keeps the receiving network, accepted assets and exact destination together in one readable card. * * @param group Published network group with available payment choices. - * @param strings Localized action labels. * @param processIntent Selects a catalog choice by its stable identifier. * @param modifier Layout modifiers for the outer card. * @author Dmitriy Moroz @@ -35,7 +35,6 @@ import com.shifthackz.aisdv1.presentation.components.widget.surface.PlatformSurf @Composable internal fun DonationGroupCard( group: DonationGroup, - strings: DonationOptionsStrings, processIntent: (DonationOptionsIntent) -> Unit, modifier: Modifier = Modifier, ) { @@ -48,7 +47,7 @@ internal fun DonationGroupCard( Text(group.title, style = MaterialTheme.typography.titleLarge) if (group.network.isNotBlank()) { Text( - group.network, + Localization.string("donate_network_label", group.network), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary ) @@ -80,7 +79,10 @@ internal fun DonationGroupCard( ) Spacer(Modifier.width(8.dp)) } - Text(if (option.kind == DonationOptionKind.CRYPTO) strings.copyAddress else option.label) + Text( + if (option.kind == DonationOptionKind.CRYPTO) Localization.string("donate_copy_address") + else option.label + ) } } } diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsCatalogStatus.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsCatalogStatus.kt deleted file mode 100644 index 7dd03aa023..0000000000 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsCatalogStatus.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.options - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.semantics.LiveRegionMode -import androidx.compose.ui.semantics.liveRegion -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.unit.dp -import com.shifthackz.aisdv1.presentation.components.widget.catalog.CatalogStatusCard -import com.shifthackz.aisdv1.presentation.components.widget.action.PrimaryButton - -/** - * Keeps catalog feedback visible during retry using the model-download screen's outlined action and sizing. - * - * @param state Catalog resolution state, including a retry that retains saved destinations. - * @param strings Localized feedback and action labels. - * @param processIntent Requests catalog retry or opens the website after an uncached failure. - * @param modifier Bounds of the feedback row. - * @author Dmitriy Moroz - */ -@Composable -internal fun DonationOptionsCatalogStatus( - state: DonationOptionsState, - strings: DonationOptionsStrings, - processIntent: (DonationOptionsIntent) -> Unit, - modifier: Modifier = Modifier, -) { - Column( - modifier = modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }, - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - CatalogStatusCard( - title = strings.optionsTitle, - message = if (state.hasOptionsError) strings.optionsError else strings.cachedNotice, - hasFailed = true, - isRefreshing = state.isLoadingOptions, - onRetry = { processIntent(DonationOptionsIntent.RetryOptions) }, - ) - if (state.hasOptionsError) { - PrimaryButton( - onClick = { processIntent(DonationOptionsIntent.LaunchDonate) }, - modifier = Modifier.fillMaxWidth(), - ) { Text(strings.title) } - } - } -} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContent.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContent.kt deleted file mode 100644 index 30cbf48f7a..0000000000 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsContent.kt +++ /dev/null @@ -1,94 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.options - -import com.shifthackz.aisdv1.presentation.donate.DonateLoading -import com.shifthackz.aisdv1.presentation.donate.DonatePage -import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import com.shifthackz.aisdv1.presentation.components.widget.surface.PlatformSurface - -/** - * Shows the current payment catalog with network instructions and independent retry feedback. - * - * @param state Loading and data snapshot owned by this tab. - * @param strings Localized page headings and feedback. - * @param listState Retained position of this tab. - * @param canReportToolbarScroll Whether this tab drives toolbar appearance. - * @param processIntent Requests payment selection or catalog retry. - * @param modifier Bounds of this pager page. - * @param brandIcon Platform illustration accompanying the introduction. - * @author Dmitriy Moroz - */ -@Composable -internal fun DonationOptionsContent( - state: DonationOptionsState, - strings: DonationOptionsStrings, - listState: LazyListState, - canReportToolbarScroll: Boolean, - processIntent: (DonationOptionsIntent) -> Unit, - modifier: Modifier = Modifier, - brandIcon: @Composable () -> Unit = {}, -) { - DonatePage(listState, canReportToolbarScroll, modifier) { - item(key = "introduction") { - PlatformSurface( - shape = RoundedCornerShape(24.dp), - color = MaterialTheme.colorScheme.surfaceVariant - ) { - Column( - Modifier.padding(20.dp), - verticalArrangement = Arrangement.spacedBy(12.dp) - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp) - ) { - brandIcon() - Text( - strings.optionsTitle, - style = MaterialTheme.typography.headlineSmall - ) - } - Text(strings.bottomEnding, style = MaterialTheme.typography.bodyLarge) - } - } - } - item(key = "network-notice") { - Text( - strings.networkNotice, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - val shouldShowStatus = state.hasOptionsError || state.isUsingCachedOptions - if (shouldShowStatus) { - item(key = "options-status") { - DonationOptionsCatalogStatus(state, strings, processIntent) - } - } - if (state.isLoadingOptions && !shouldShowStatus) { - item(key = "options-loading") { - DonateLoading( - tab = DonateScreenTab.DONATION_OPTIONS, - loadingDescription = strings.loading - ) - } - } else if (!state.isLoadingOptions && !state.hasOptionsError && state.donationGroups.isEmpty()) { - item(key = "options-empty") { Text(strings.optionsEmpty) } - } - items(state.donationGroups, key = { "payment-" + it.id }) { group -> - DonationGroupCard(group, strings, processIntent) - } - } -} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsScreen.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsSection.kt similarity index 69% rename from presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsScreen.kt rename to presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsSection.kt index 948954332d..90c0baa83c 100644 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsScreen.kt +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsSection.kt @@ -3,7 +3,6 @@ package com.shifthackz.aisdv1.presentation.donate.options import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.windowInsetsPadding -import androidx.compose.foundation.lazy.LazyListState import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable @@ -19,25 +18,22 @@ import com.shifthackz.aisdv1.core.localization.Localization import com.shifthackz.aisdv1.core.mvi.MviComponent import com.shifthackz.aisdv1.presentation.components.platform.rememberExternalUrlLauncher import com.shifthackz.aisdv1.presentation.components.theme.global.persistentBottomBarWindowInsets -import com.shifthackz.aisdv1.presentation.donate.DonateBrandIcon import kotlinx.coroutines.launch -import org.koin.mp.KoinPlatform.getKoin +import org.koin.compose.koinInject /** - * Owns external catalog state, clipboard/URL effects and subscription cleanup for this tab. + * Owns the backend catalog and its clipboard and URL effects until the containing page is disposed. * - * @param listState Scroll position retained by the container. - * @param canReportToolbarScroll Whether this tab currently controls toolbar appearance. - * @param modifier Bounds applied to this tab and its feedback overlay. + * @param modifier Bounds applied to the page and its clipboard feedback overlay. + * @param content Receives the current catalog snapshot and dispatcher for catalog actions. * @author Dmitriy Moroz */ @Composable -internal fun DonationOptionsScreen( - listState: LazyListState, - canReportToolbarScroll: Boolean, +internal fun DonationOptionsSection( modifier: Modifier = Modifier, + content: @Composable (DonationOptionsState, (DonationOptionsIntent) -> Unit) -> Unit, ) { - val viewModel = remember { getKoin().get() } + val viewModel = koinInject() DisposableEffect(viewModel) { val store = ViewModelStore() store.put("DonationOptions", viewModel) @@ -58,15 +54,7 @@ internal fun DonationOptionsScreen( is DonationOptionsEffect.OpenUrl -> launcher.openUrl(effect.url) } - }) { state, processIntent -> - DonationOptionsContent( - state, donationOptionsStrings(), - listState = listState, - canReportToolbarScroll = canReportToolbarScroll, - processIntent = processIntent, - brandIcon = { DonateBrandIcon() }, - ) - } + }, content = content) SnackbarHost( hostState = snackbar, modifier = Modifier diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsStrings.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsStrings.kt deleted file mode 100644 index 463fc297f6..0000000000 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/options/DonationOptionsStrings.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.options - -import androidx.compose.runtime.Composable -import com.shifthackz.aisdv1.core.localization.Localization - -/** - * External support catalog text, independent of purchase and acknowledgement state. - * - * @param title Website action label. - * @param bottomEnding Optional support explanation. - * @param optionsTitle Support catalog heading. - * @param networkNotice Receiving-network instruction. - * @param copyAddress Clipboard action label. - * @param optionsError Fetch failure message. - * @param optionsEmpty Empty catalog message. - * @param cachedNotice Saved-catalog explanation. - * @param loading Accessible loading announcement. - * @author Dmitriy Moroz - */ -data class DonationOptionsStrings( - val title: String, val bottomEnding: String, val optionsTitle: String, - val networkNotice: String, val copyAddress: String, val optionsError: String, - val optionsEmpty: String, val cachedNotice: String, val loading: String, -) - -/** - * Reads catalog strings from the active shared localization catalog. - * - * @author Dmitriy Moroz - */ -@Composable -internal fun donationOptionsStrings() = DonationOptionsStrings( - title = Localization.string("settings_item_donate"), - bottomEnding = Localization.string("donate_bs_ending"), - optionsTitle = Localization.string("donate_options_title"), - networkNotice = Localization.string("donate_network_notice"), - copyAddress = Localization.string("donate_copy_address"), - optionsError = Localization.string("donate_options_error"), - optionsEmpty = Localization.string("donate_options_empty"), - cachedNotice = Localization.string("donate_cached"), - loading = Localization.string("loading"), -) diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/supporters/SupportersContent.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/supporters/SupportersContent.kt index 7135c623be..9252462d10 100644 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/supporters/SupportersContent.kt +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/supporters/SupportersContent.kt @@ -2,7 +2,7 @@ package com.shifthackz.aisdv1.presentation.donate.supporters import com.shifthackz.aisdv1.presentation.donate.DonateLoading import com.shifthackz.aisdv1.presentation.donate.DonatePage -import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab +import com.shifthackz.aisdv1.presentation.donate.DonateLoadingStyle import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyListState @@ -38,7 +38,7 @@ internal fun SupportersContent( if (state.isLoadingSupporters) { item(key = "supporters-loading") { DonateLoading( - tab = DonateScreenTab.SUPPORTERS, + style = DonateLoadingStyle.SUPPORTERS, loadingDescription = strings.loading ) } diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContent.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContent.kt deleted file mode 100644 index 9c519a5f98..0000000000 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarContent.kt +++ /dev/null @@ -1,76 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.tipjar - -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.outlined.Schedule -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import com.shifthackz.aisdv1.presentation.components.widget.catalog.CatalogStatusCard -import com.shifthackz.aisdv1.presentation.components.widget.feedback.FeedbackCard -import com.shifthackz.aisdv1.presentation.donate.DonateLoading -import com.shifthackz.aisdv1.presentation.donate.DonatePage -import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab - -/** - * Displays voluntary store support choices with no external payment fallback. - * - * @param state Loaded products and payment feedback. - * @param strings Localized support explanation and actions. - * @param listState First-tab scroll position owned by the donation pager. - * @param canReportToolbarScroll Whether this page controls the toolbar scroll appearance. - * @param processIntent Receives explicit product selections and retry requests. - * @param modifier Layout applied to the full scrolling page. - * @author Dmitriy Moroz - */ -@Composable -internal fun TipJarContent( - state: TipJarState, - strings: TipJarStrings, - listState: LazyListState, - canReportToolbarScroll: Boolean, - processIntent: (TipJarIntent) -> Unit, - modifier: Modifier = Modifier, -) { - DonatePage(listState, canReportToolbarScroll, modifier) { - item("explanation") { Text(strings.explanation) } - val shouldShowStatus = state.hasError || (!state.isLoading && state.products.isEmpty()) - if (shouldShowStatus) { - item("status") { - CatalogStatusCard( - title = strings.title, - message = if (state.hasError) strings.error else strings.unavailable, - hasFailed = state.hasError, - isRefreshing = state.isLoading, - onRetry = { processIntent(TipJarIntent.Retry) }, - ) - } - } - if (state.isLoading && state.products.isEmpty() && !state.hasError) { - item("loading") { - DonateLoading( - tab = DonateScreenTab.TIP_JAR, - loadingDescription = strings.loading, - ) - } - } - if (state.hasPendingNotice) item("pending") { - FeedbackCard( - title = strings.title, - message = strings.pending, - icon = Icons.Outlined.Schedule, - actionLabel = strings.dismiss, - onAction = { processIntent(TipJarIntent.DismissNotice) }, - ) - } - if (state.hasCompletedTip) item("thanks") { TipJarThanksCard(strings.thanks) } - items(state.products, key = { it.productId }) { product -> - TipJarProductCard( - product = product, - isEnabled = !state.isPurchasing && !state.isLoading, - onPurchase = { processIntent(TipJarIntent.Purchase(product.productId)) }, - ) - } - } -} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarScreen.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarScreen.kt deleted file mode 100644 index 13333e6119..0000000000 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarScreen.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.tipjar - -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.remember -import androidx.compose.ui.Modifier -import androidx.lifecycle.ViewModelStore -import com.shifthackz.aisdv1.core.mvi.MviComponent -import org.koin.mp.KoinPlatform.getKoin - -/** - * Retains tip UI state and its transaction subscription until the configured tab leaves the route. - * Native store settlement remains application-owned after this screen is disposed. - * - * @param listState Scroll position retained by the container. - * @param canReportToolbarScroll Whether this tab currently controls toolbar appearance. - * @param modifier Bounds forwarded to the tip content. - * @author Dmitriy Moroz - */ -@Composable -internal fun TipJarScreen( - listState: LazyListState, - canReportToolbarScroll: Boolean, - modifier: Modifier = Modifier, -) { - val viewModel = remember { getKoin().get() } - DisposableEffect(viewModel) { - val store = ViewModelStore() - store.put("TipJar", viewModel) - onDispose { store.clear() } - } - MviComponent(viewModel = viewModel) { state, processIntent -> - TipJarContent( - state = state, - strings = tipJarStrings(), - listState = listState, - canReportToolbarScroll = canReportToolbarScroll, - processIntent = processIntent, - modifier = modifier - ) - } -} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarSection.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarSection.kt new file mode 100644 index 0000000000..936368bea2 --- /dev/null +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarSection.kt @@ -0,0 +1,27 @@ +package com.shifthackz.aisdv1.presentation.donate.tipjar + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.lifecycle.ViewModelStore +import com.shifthackz.aisdv1.core.mvi.MviComponent +import org.koin.compose.koinInject + +/** + * Retains tip UI state and its transaction subscription until the containing page leaves the route. + * Native store settlement remains application-owned after this screen is disposed. + * + * @param content Receives the current store snapshot and dispatcher for purchase actions. + * @author Dmitriy Moroz + */ +@Composable +internal fun TipJarSection( + content: @Composable (TipJarState, (TipJarIntent) -> Unit) -> Unit, +) { + val viewModel = koinInject() + DisposableEffect(viewModel) { + val store = ViewModelStore() + store.put("TipJar", viewModel) + onDispose { store.clear() } + } + MviComponent(viewModel = viewModel, content = content) +} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarStrings.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarStrings.kt deleted file mode 100644 index 6ffd2edf83..0000000000 --- a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/tipjar/TipJarStrings.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.tipjar - -import androidx.compose.runtime.Composable -import com.shifthackz.aisdv1.core.localization.Localization - -/** - * Localized payment feedback, separate from store-localized product metadata. - * - * @param title Shared support heading for error and empty-state cards. - * @param explanation Explains optional support without feature unlocks. - * @param unavailable Empty-catalog explanation. - * @param error Discovery or purchase failure explanation. - * @param pending One-time request-submission feedback. - * @param dismiss Closes the submitted-request notice. - * @param thanks Verified completion acknowledgement. - * @param loading Accessible product-loading description. - * @author Dmitriy Moroz - */ -internal data class TipJarStrings( - val title: String, - val explanation: String, - val unavailable: String, - val error: String, - val pending: String, - val dismiss: String, - val thanks: String, - val loading: String, -) - -/** - * Reads payment feedback from the active generated localization catalog. - * - * @author Dmitriy Moroz - */ -@Composable -internal fun tipJarStrings() = TipJarStrings( - title = Localization.string("donate_options_title"), - explanation = Localization.string("donate_tip_explanation"), - unavailable = Localization.string("donate_tip_unavailable"), - error = Localization.string("donate_tip_error"), - pending = Localization.string("donate_tip_pending"), - dismiss = Localization.string("action_close"), - thanks = Localization.string("donate_tip_thanks"), - loading = Localization.string("loading"), -) diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportContent.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportContent.kt new file mode 100644 index 0000000000..f566ae6f65 --- /dev/null +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportContent.kt @@ -0,0 +1,72 @@ +package com.shifthackz.aisdv1.presentation.donate.ways + +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.presentation.donate.DonateLoading +import com.shifthackz.aisdv1.presentation.donate.DonateLoadingStyle +import com.shifthackz.aisdv1.presentation.donate.DonatePage +import com.shifthackz.aisdv1.presentation.donate.options.DonationGroupCard +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsIntent +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsState +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarIntent +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarProductCard +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState + +/** + * Renders a single list with the introduction, shared feedback, store tips, then external options. + * The loading placeholder is replaced when all applicable sources finish their initial request. + * + * @param tips Store catalog and payment state, or null when store tips are unsupported. + * @param options External catalog state, or null when external options are unsupported. + * @param listState Scroll position retained by the donation pager. + * @param canReportToolbarScroll Whether this page drives the toolbar appearance. + * @param onTipIntent Dispatches purchases, store retries and pending-notice dismissal. + * @param onOptionsIntent Dispatches external choices, catalog retries and the website fallback. + * @param modifier Bounds of the shared scrollable page. + * @author Dmitriy Moroz + */ +@Composable +internal fun WaysToSupportContent( + tips: TipJarState?, + options: DonationOptionsState?, + listState: LazyListState, + canReportToolbarScroll: Boolean, + onTipIntent: (TipJarIntent) -> Unit, + onOptionsIntent: (DonationOptionsIntent) -> Unit, + modifier: Modifier = Modifier, +) { + val isWaitingForTips = + tips != null && tips.isLoading && !tips.hasError && tips.products.isEmpty() + val isWaitingForOptions = options != null && options.isLoadingOptions && + !options.hasOptionsError && !options.isUsingCachedOptions && options.donationGroups.isEmpty() + DonatePage(listState, canReportToolbarScroll, modifier) { + item("support-introduction") { WaysToSupportIntroduction() } + if (isWaitingForTips || isWaitingForOptions) { + item("support-loading") { + DonateLoading( + style = if (tips != null) DonateLoadingStyle.TIP_JAR else DonateLoadingStyle.DONATION_OPTIONS, + loadingDescription = Localization.string("loading"), + ) + } + } else { + waysToSupportFeedback(tips, options, onTipIntent, onOptionsIntent) + if (tips != null) { + items(tips.products, key = { "tip-${it.productId}" }) { product -> + TipJarProductCard( + product = product, + isEnabled = !tips.isPurchasing && !tips.isLoading, + onPurchase = { onTipIntent(TipJarIntent.Purchase(product.productId)) }, + ) + } + } + if (options != null) { + items(options.donationGroups, key = { "payment-${it.id}" }) { group -> + DonationGroupCard(group, onOptionsIntent) + } + } + } + } +} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportFeedback.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportFeedback.kt new file mode 100644 index 0000000000..5ba52d4280 --- /dev/null +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportFeedback.kt @@ -0,0 +1,98 @@ +package com.shifthackz.aisdv1.presentation.donate.ways + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Schedule +import androidx.compose.material3.Text +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.presentation.components.widget.action.PrimaryButton +import com.shifthackz.aisdv1.presentation.components.widget.catalog.CatalogStatusCard +import com.shifthackz.aisdv1.presentation.components.widget.feedback.FeedbackCard +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsIntent +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsState +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarIntent +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarThanksCard + +/** + * Combines catalog and payment problems into one retry row ahead of the available choices. + * + * @param tips Store snapshot when the distribution offers tips. + * @param options Backend snapshot when the distribution offers external options. + * @param onTipIntent Retries an unavailable store catalog or dismisses a pending payment notice. + * @param onOptionsIntent Refreshes external choices or opens the fallback donation website. + * @author Dmitriy Moroz + */ +internal fun LazyListScope.waysToSupportFeedback( + tips: TipJarState?, + options: DonationOptionsState?, + onTipIntent: (TipJarIntent) -> Unit, + onOptionsIntent: (DonationOptionsIntent) -> Unit, +) { + val hasTipError = tips?.hasError == true + val hasNoTips = tips != null && !tips.isLoading && tips.products.isEmpty() + val shouldRetryTips = hasTipError || hasNoTips + val hasOptionsError = options?.hasOptionsError == true + val isUsingCachedOptions = options?.isUsingCachedOptions == true + val shouldRetryOptions = hasOptionsError || isUsingCachedOptions + + if (shouldRetryTips || shouldRetryOptions) { + item("support-status") { + val message = listOfNotNull( + when { + hasOptionsError -> Localization.string("donate_options_error") + hasTipError -> Localization.string("donate_tip_error") + hasNoTips -> Localization.string("donate_tip_unavailable") + else -> null + }, + Localization.string("donate_cached").takeIf { isUsingCachedOptions }, + Localization.string("donate_tip_thanks").takeIf { tips?.hasCompletedTip == true }, + ).joinToString("\n") + Column( + modifier = Modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + CatalogStatusCard( + title = Localization.string("donate_options_title"), + message = message, + hasFailed = hasTipError || shouldRetryOptions, + isRefreshing = tips?.isLoading == true || options?.isLoadingOptions == true, + onRetry = { + if (shouldRetryTips) onTipIntent(TipJarIntent.Retry) + if (shouldRetryOptions) onOptionsIntent(DonationOptionsIntent.RetryOptions) + }, + ) + if (hasOptionsError) { + PrimaryButton( + onClick = { onOptionsIntent(DonationOptionsIntent.LaunchDonate) }, + modifier = Modifier.fillMaxWidth(), + ) { Text(Localization.string("settings_item_donate")) } + } + } + } + } else if (tips?.hasCompletedTip == true) { + item("support-thanks") { TipJarThanksCard(Localization.string("donate_tip_thanks")) } + } + if (tips?.hasPendingNotice == true) { + item("support-pending") { + FeedbackCard( + title = Localization.string("donate_options_title"), + message = Localization.string("donate_tip_pending"), + icon = Icons.Outlined.Schedule, + actionLabel = Localization.string("action_close"), + onAction = { onTipIntent(TipJarIntent.DismissNotice) }, + ) + } + } + if (!shouldRetryTips && !shouldRetryOptions && tips?.products.isNullOrEmpty() && options?.donationGroups.isNullOrEmpty()) { + item("support-empty") { Text(Localization.string("donate_options_empty")) } + } +} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportIntroduction.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportIntroduction.kt new file mode 100644 index 0000000000..032293c476 --- /dev/null +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportIntroduction.kt @@ -0,0 +1,55 @@ +package com.shifthackz.aisdv1.presentation.donate.ways + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.presentation.components.widget.surface.PlatformSurface +import com.shifthackz.aisdv1.presentation.donate.DonateBrandIcon + +/** + * Introduces optional support before any payment mechanisms or catalog status. + * + * @param modifier Bounds of the opening card. + * @author Dmitriy Moroz + */ +@Composable +internal fun WaysToSupportIntroduction(modifier: Modifier = Modifier) { + PlatformSurface( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surfaceVariant, + ) { + Column( + modifier = Modifier.padding(20.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + DonateBrandIcon() + Text( + text = Localization.string("donate_options_title"), + modifier = Modifier.semantics { heading() }, + style = MaterialTheme.typography.headlineSmall, + ) + } + Text( + text = Localization.string("donate_support_explanation"), + style = MaterialTheme.typography.bodyLarge, + ) + } + } +} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportScreen.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportScreen.kt new file mode 100644 index 0000000000..b91001b156 --- /dev/null +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportScreen.kt @@ -0,0 +1,62 @@ +package com.shifthackz.aisdv1.presentation.donate.ways + +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import com.shifthackz.aisdv1.presentation.donate.di.waysToSupportSectionsQualifier +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsIntent +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsSection +import com.shifthackz.aisdv1.presentation.donate.options.DonationOptionsState +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarIntent +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarSection +import com.shifthackz.aisdv1.presentation.donate.tipjar.TipJarState +import org.koin.compose.koinInject + +/** + * Resolves only the supported catalogs and supplies their snapshots to the shared scrollable page. + * + * @param listState Scroll position retained by the donation pager. + * @param canReportToolbarScroll Whether this page drives the toolbar appearance. + * @param modifier Layout applied to this page, including its feedback overlay when present. + * @author Dmitriy Moroz + */ +@Composable +internal fun WaysToSupportScreen( + listState: LazyListState, + canReportToolbarScroll: Boolean, + modifier: Modifier = Modifier, +) { + val sections = koinInject>(waysToSupportSectionsQualifier) + val page: @Composable (TipJarState?, (TipJarIntent) -> Unit, DonationOptionsState?, (DonationOptionsIntent) -> Unit) -> Unit = + { tips, onTipIntent, options, onOptionsIntent -> + WaysToSupportContent( + tips = tips, + options = options, + listState = listState, + canReportToolbarScroll = canReportToolbarScroll, + onTipIntent = onTipIntent, + onOptionsIntent = onOptionsIntent, + modifier = if (options == null) modifier else Modifier, + ) + } + val withTips: @Composable (DonationOptionsState?, (DonationOptionsIntent) -> Unit) -> Unit = + { options, onOptionsIntent -> + if (WaysToSupportSection.TIP_JAR in sections) { + TipJarSection { tips, onTipIntent -> + page( + tips, + onTipIntent, + options, + onOptionsIntent + ) + } + } else { + page(null, {}, options, onOptionsIntent) + } + } + if (WaysToSupportSection.BACKEND_OPTIONS in sections) { + DonationOptionsSection(modifier, content = withTips) + } else { + withTips(null, {}) + } +} diff --git a/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportSection.kt b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportSection.kt new file mode 100644 index 0000000000..cd914fd66a --- /dev/null +++ b/presentation/donate/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/donate/ways/WaysToSupportSection.kt @@ -0,0 +1,8 @@ +package com.shifthackz.aisdv1.presentation.donate.ways + +/** + * Independently loaded payment mechanisms that can share the Ways to support page. + * + * @author Dmitriy Moroz + */ +internal enum class WaysToSupportSection { TIP_JAR, BACKEND_OPTIONS } diff --git a/presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.ios.kt b/presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.ios.kt deleted file mode 100644 index bb44583b6a..0000000000 --- a/presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/DonateScreenTabs.ios.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.shifthackz.aisdv1.presentation.donate.di - -import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab - -/** - * Tabs available in this distribution, without resolving unconfigured tab factories. - * - * @author Dmitriy Moroz - */ -internal actual val platformDonateScreenTabs: Set = setOf( - DonateScreenTab.TIP_JAR, DonateScreenTab.SUPPORTERS, -) diff --git a/presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.ios.kt b/presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.ios.kt new file mode 100644 index 0000000000..f094aeec71 --- /dev/null +++ b/presentation/donate/src/iosMain/kotlin/com/shifthackz/aisdv1/presentation/donate/di/WaysToSupportSections.ios.kt @@ -0,0 +1,12 @@ +package com.shifthackz.aisdv1.presentation.donate.di + +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection +import org.koin.core.scope.Scope + +/** + * Uses StoreKit tips as the sole payment mechanism on iOS. + * + * @author Dmitriy Moroz + */ +internal actual fun Scope.platformWaysToSupportSections(): Set = + setOf(WaysToSupportSection.TIP_JAR) diff --git a/presentation/donate/src/iosTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/IosDiModuleTest.kt b/presentation/donate/src/iosTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/IosDiModuleTest.kt index 1e6190d483..92f40babe5 100644 --- a/presentation/donate/src/iosTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/IosDiModuleTest.kt +++ b/presentation/donate/src/iosTest/kotlin/com/shifthackz/aisdv1/presentation/donate/di/IosDiModuleTest.kt @@ -1,6 +1,7 @@ package com.shifthackz.aisdv1.presentation.donate.di import com.shifthackz.aisdv1.presentation.donate.DonateScreenTab +import com.shifthackz.aisdv1.presentation.donate.ways.WaysToSupportSection import org.koin.dsl.koinApplication import kotlin.test.Test import kotlin.test.assertEquals @@ -8,16 +9,18 @@ import kotlin.test.assertEquals @Suppress("INVALID_CHARACTERS_NATIVE_ERROR") class IosDiModuleTest { @Test - fun `given iOS donation distribution, tab declarations are read, expected only native tips and supporters`() { + fun `given iOS donation distribution, tabs and sections are resolved, expected native tips only in Ways to support`() { // Given - val expected = setOf(DonateScreenTab.TIP_JAR, DonateScreenTab.SUPPORTERS) val application = koinApplication { modules(donateViewModelModule) } // When val tabs = application.koin.get>(donateTabsQualifier) + val sections = + application.koin.get>(waysToSupportSectionsQualifier) // Then - assertEquals(expected, tabs) + assertEquals(setOf(DonateScreenTab.DONATION_OPTIONS, DonateScreenTab.SUPPORTERS), tabs) + assertEquals(setOf(WaysToSupportSection.TIP_JAR), sections) application.close() } }