diff --git a/app/build.gradle b/app/build.gradle index 266f2c73be..93e5b91825 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -9,7 +9,7 @@ buildscript { dependencies { classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.9' - classpath 'com.apollographql.apollo:apollo-gradle-plugin:2.5.14' + classpath 'com.apollographql.apollo3:apollo-gradle-plugin:3.8.5' classpath 'com.karumi:shot:5.13.0' } } @@ -23,10 +23,11 @@ apply plugin: 'com.google.firebase.crashlytics' apply plugin: 'com.google.firebase.firebase-perf' apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-parcelize' -apply plugin: 'com.apollographql.apollo' +apply plugin: 'com.apollographql.apollo3' apply plugin: 'jacoco' apply from: 'quality.gradle' apply from: "$project.rootDir/jacoco.gradle" +def apolloVersion = '3.8.5' def externalPrivateVersion = new File(project.rootDir.path + "/app/external_version_code.txt").text.trim().toInteger() def externalPublicVersion = new File(project.rootDir.path + "/app/external_version_name.txt").text.trim() @@ -182,12 +183,12 @@ android { } apollo { - customTypeMapping = [ - "Date" : "java.util.Date", - "Email": "java.lang.String", - "ISO8601DateTime" : "org.joda.time.DateTime", - "DateTime" : "org.joda.time.DateTime" - ] + service("service") { + packageName.set("com.kickstarter") // -> Every generated files/classes by apollo will now live under the directory "com.kickstarter.*" + mapScalar("Date", "java.util.Date") + mapScalar("ISO8601DateTime", "org.joda.time.DateTime") + mapScalar("DateTime", "org.joda.time.DateTime") + } } repositories { @@ -219,7 +220,12 @@ dependencies { implementation 'com.android.support.constraint:constraint-layout:2.0.4' implementation("androidx.core:core-splashscreen:1.0.1") - implementation 'com.apollographql.apollo:apollo-runtime:2.5.14' + + implementation "com.apollographql.apollo3:apollo-adapters:$apolloVersion" + implementation "com.apollographql.apollo3:apollo-runtime:$apolloVersion" + // RxJava2 support + implementation "com.apollographql.apollo3:apollo-rx2-support:$apolloVersion" + implementation 'com.facebook.android:facebook-android-sdk:16.0.0' implementation("com.google.android.play:review-ktx:2.0.1") implementation 'androidx.constraintlayout:constraintlayout:2.1.4' diff --git a/app/internal_version_code.txt b/app/internal_version_code.txt index 98eead86a0..eb943ee4b9 100644 --- a/app/internal_version_code.txt +++ b/app/internal_version_code.txt @@ -1 +1 @@ -2014150921 +2014150925 diff --git a/app/internal_version_name.txt b/app/internal_version_name.txt index cc6b5127bc..0f414fd3e1 100644 --- a/app/internal_version_name.txt +++ b/app/internal_version_name.txt @@ -1 +1 @@ -3.26.2 \ No newline at end of file +3.28.0 \ No newline at end of file diff --git a/app/src/androidTest/java/com/kickstarter/screenshoot/testing/di/AndroidTestApplicationModule.kt b/app/src/androidTest/java/com/kickstarter/screenshoot/testing/di/AndroidTestApplicationModule.kt index 03b31df2c2..0b9cf3a417 100644 --- a/app/src/androidTest/java/com/kickstarter/screenshoot/testing/di/AndroidTestApplicationModule.kt +++ b/app/src/androidTest/java/com/kickstarter/screenshoot/testing/di/AndroidTestApplicationModule.kt @@ -2,7 +2,7 @@ package com.kickstarter.screenshoot.testing.di import android.app.Application import androidx.annotation.NonNull -import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo3.ApolloClient import com.google.gson.Gson import com.kickstarter.ApplicationModule import com.kickstarter.libs.ApiEndpoint diff --git a/app/src/external/java/com/kickstarter/ExternalApplicationModule.java b/app/src/external/java/com/kickstarter/ExternalApplicationModule.java index 32d510055f..355d103e24 100644 --- a/app/src/external/java/com/kickstarter/ExternalApplicationModule.java +++ b/app/src/external/java/com/kickstarter/ExternalApplicationModule.java @@ -1,6 +1,6 @@ package com.kickstarter; -import com.apollographql.apollo.ApolloClient; +import com.apollographql.apollo3.ApolloClient; import com.google.gson.Gson; import com.kickstarter.libs.ApiEndpoint; import com.kickstarter.libs.InternalToolsType; diff --git a/app/src/internal/java/com/kickstarter/InternalApplicationModule.java b/app/src/internal/java/com/kickstarter/InternalApplicationModule.java index f4d8a7bd69..96513aa59f 100644 --- a/app/src/internal/java/com/kickstarter/InternalApplicationModule.java +++ b/app/src/internal/java/com/kickstarter/InternalApplicationModule.java @@ -2,7 +2,7 @@ import android.content.SharedPreferences; -import com.apollographql.apollo.ApolloClient; +import com.apollographql.apollo3.ApolloClient; import com.google.gson.Gson; import com.kickstarter.libs.ApiEndpoint; import com.kickstarter.libs.InternalTools; diff --git a/app/src/main/graphql/checkout.graphql b/app/src/main/graphql/checkout.graphql index 214a46faa9..63177f90b5 100644 --- a/app/src/main/graphql/checkout.graphql +++ b/app/src/main/graphql/checkout.graphql @@ -78,8 +78,8 @@ mutation CompleteOnSessionCheckout($checkoutId: ID!, $paymentIntentClientSecret: } } -mutation completeOrder($projectId: ID!, $stripePaymentMethodId: String, $paymentSourceId: String, $paymentSourceReusable: Boolean, $paymentMethodTypes: [String!]) { - completeOrder(input:{stripePaymentMethodId: $stripePaymentMethodId, paymentSourceId: $paymentSourceId, paymentSourceReusable: $paymentSourceReusable, paymentMethodTypes: $paymentMethodTypes }) { +mutation completeOrder($orderId: ID!, $stripePaymentMethodId: String, $paymentSourceId: String, $paymentSourceReusable: Boolean, $paymentMethodTypes: [String!]) { + completeOrder(input:{orderId: $orderId, stripePaymentMethodId: $stripePaymentMethodId, paymentSourceId: $paymentSourceId, paymentSourceReusable: $paymentSourceReusable, paymentMethodTypes: $paymentMethodTypes }) { status clientSecret } diff --git a/app/src/main/graphql/thirdPartyEvents.graphql b/app/src/main/graphql/thirdPartyEvents.graphql index 7c06f155e3..5116d04911 100644 --- a/app/src/main/graphql/thirdPartyEvents.graphql +++ b/app/src/main/graphql/thirdPartyEvents.graphql @@ -1,6 +1,6 @@ -mutation triggerThirdPartyEvent ($triggerThirdPartyEventInput: TriggerThirdPartyEventInput!) { - triggerThirdPartyEvent(input: $triggerThirdPartyEventInput) { - message - success - } -} \ No newline at end of file +#mutation triggerThirdPartyEvent ($triggerThirdPartyEventInput: TriggerThirdPartyEventInput!) { +# triggerThirdPartyEvent(input: $triggerThirdPartyEventInput) { +# message +# success +# } +#} \ No newline at end of file diff --git a/app/src/main/java/com/kickstarter/ApplicationModule.java b/app/src/main/java/com/kickstarter/ApplicationModule.java index 266ed4d0c3..db3f45e357 100644 --- a/app/src/main/java/com/kickstarter/ApplicationModule.java +++ b/app/src/main/java/com/kickstarter/ApplicationModule.java @@ -8,7 +8,8 @@ import android.content.res.AssetManager; import android.content.res.Resources; -import com.apollographql.apollo.ApolloClient; +import com.apollographql.apollo3.ApolloClient; +import com.apollographql.apollo3.network.http.DefaultHttpEngine; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; @@ -42,7 +43,6 @@ import com.kickstarter.libs.graphql.DateAdapter; import com.kickstarter.libs.graphql.DateTimeAdapter; import com.kickstarter.libs.graphql.Iso8601DateTimeAdapter; -import com.kickstarter.libs.graphql.EmailAdapter; import com.kickstarter.libs.keystore.EncryptionEngine; import com.kickstarter.libs.preferences.BooleanPreference; import com.kickstarter.libs.preferences.BooleanPreferenceType; @@ -72,6 +72,7 @@ import com.kickstarter.services.interceptors.GraphQLInterceptor; import com.kickstarter.services.interceptors.KSRequestInterceptor; import com.kickstarter.services.interceptors.WebRequestInterceptor; +import com.kickstarter.type.Date; import com.kickstarter.ui.SharedPreferenceKey; import com.stripe.android.PaymentConfiguration; import com.stripe.android.Stripe; @@ -97,7 +98,6 @@ import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; -import type.CustomType; @Module public class ApplicationModule { @@ -200,13 +200,12 @@ static ApolloClient provideApolloClient(final @NonNull Build build, final @NonNu final OkHttpClient okHttpClient = builder.build(); - return ApolloClient.builder() - .addCustomTypeAdapter(CustomType.DATE, new DateAdapter()) - .addCustomTypeAdapter(CustomType.EMAIL, new EmailAdapter()) - .addCustomTypeAdapter(CustomType.ISO8601DATETIME, new Iso8601DateTimeAdapter()) - .addCustomTypeAdapter(CustomType.DATETIME, new DateTimeAdapter()) + return new ApolloClient.Builder() .serverUrl(webEndpoint + "/graph") - .okHttpClient(okHttpClient) + .addCustomScalarAdapter(Date.Companion.getType(), new DateAdapter()) + .addCustomScalarAdapter(com.kickstarter.type.DateTime.Companion.getType(), new DateTimeAdapter()) + .addCustomScalarAdapter(com.kickstarter.type.ISO8601DateTime.Companion.getType(), new Iso8601DateTimeAdapter()) + .httpEngine(new DefaultHttpEngine(okHttpClient)) .build(); } diff --git a/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCard.kt b/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCard.kt index 8d17d7bfa7..261a8a43bc 100644 --- a/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCard.kt +++ b/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCard.kt @@ -2,8 +2,8 @@ package com.kickstarter.features.pledgedprojectsoverview.data import android.os.Parcelable import com.kickstarter.features.pledgedprojectsoverview.ui.PPOCardViewType +import com.kickstarter.type.CurrencyCode import kotlinx.parcelize.Parcelize -import type.CurrencyCode @Parcelize class PPOCard private constructor( diff --git a/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCardFactory.kt b/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCardFactory.kt index 10938e7bac..a7171a1d6c 100644 --- a/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCardFactory.kt +++ b/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/data/PPOCardFactory.kt @@ -1,7 +1,7 @@ package com.kickstarter.features.pledgedprojectsoverview.data import com.kickstarter.features.pledgedprojectsoverview.ui.PPOCardViewType -import type.CurrencyCode +import com.kickstarter.type.CurrencyCode class PPOCardFactory private constructor() { companion object { diff --git a/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/ui/PledgedProjectsOverviewScreen.kt b/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/ui/PledgedProjectsOverviewScreen.kt index 38bc34cf8b..0ad7f72e87 100644 --- a/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/ui/PledgedProjectsOverviewScreen.kt +++ b/app/src/main/java/com/kickstarter/features/pledgedprojectsoverview/ui/PledgedProjectsOverviewScreen.kt @@ -252,7 +252,7 @@ fun PledgedProjectsOverviewScreen( onProjectPledgeSummaryClick = { onProjectPledgeSummaryClick(it.backingDetailsUrl() ?: "") }, projectName = it.projectName(), pledgeAmount = it.amount?.toDoubleOrNull()?.let { amount -> - RewardViewUtils.formatCurrency(amount, it.currencyCode?.rawValue(), it.currencySymbol) + RewardViewUtils.formatCurrency(amount, it.currencyCode?.rawValue, it.currencySymbol) }, imageUrl = it.imageUrl(), flags = it.flags, diff --git a/app/src/main/java/com/kickstarter/libs/graphql/DateAdapter.kt b/app/src/main/java/com/kickstarter/libs/graphql/DateAdapter.kt index 00815c5bde..52f7a846a0 100644 --- a/app/src/main/java/com/kickstarter/libs/graphql/DateAdapter.kt +++ b/app/src/main/java/com/kickstarter/libs/graphql/DateAdapter.kt @@ -1,25 +1,27 @@ package com.kickstarter.libs.graphql -import com.apollographql.apollo.api.CustomTypeAdapter -import com.apollographql.apollo.api.CustomTypeValue +import com.apollographql.apollo3.api.Adapter +import com.apollographql.apollo3.api.CustomScalarAdapters +import com.apollographql.apollo3.api.json.JsonReader +import com.apollographql.apollo3.api.json.JsonWriter import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale -class DateAdapter : CustomTypeAdapter { +class DateAdapter : Adapter { private val DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) - override fun encode(value: Date): CustomTypeValue<*> { - return CustomTypeValue.GraphQLString(DATE_FORMAT.format(value)) - } - - override fun decode(value: CustomTypeValue<*>): Date { - try { - return DATE_FORMAT.parse(value.value.toString()) + override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): Date { + return try { + reader.nextString()?.let { DATE_FORMAT.parse(it) } ?: Date() } catch (exception: ParseException) { throw RuntimeException(exception) } } + + override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: Date) { + writer.value(DATE_FORMAT.format(value)) + } } diff --git a/app/src/main/java/com/kickstarter/libs/graphql/DateTimeAdapter.kt b/app/src/main/java/com/kickstarter/libs/graphql/DateTimeAdapter.kt index 7f6681e7e3..fd4febbc3b 100644 --- a/app/src/main/java/com/kickstarter/libs/graphql/DateTimeAdapter.kt +++ b/app/src/main/java/com/kickstarter/libs/graphql/DateTimeAdapter.kt @@ -1,22 +1,30 @@ package com.kickstarter.libs.graphql - -import com.apollographql.apollo.api.CustomTypeAdapter -import com.apollographql.apollo.api.CustomTypeValue +import com.apollographql.apollo3.api.Adapter +import com.apollographql.apollo3.api.CustomScalarAdapters +import com.apollographql.apollo3.api.json.JsonReader +import com.apollographql.apollo3.api.json.JsonWriter import org.joda.time.DateTime import org.joda.time.DateTimeZone import java.text.ParseException -class DateTimeAdapter : CustomTypeAdapter { - - override fun encode(value: DateTime): CustomTypeValue<*> { - return CustomTypeValue.GraphQLNumber(value.toString().toLong() / 1000L) - } +class DateTimeAdapter : Adapter { - override fun decode(value: CustomTypeValue<*>): DateTime { + override fun fromJson( + reader: JsonReader, + customScalarAdapters: CustomScalarAdapters + ): DateTime { try { - return DateTime(java.lang.Long.valueOf(value.value.toString().toLong() * 1000L), DateTimeZone.UTC) + return DateTime(java.lang.Long.valueOf(reader.nextString()!!.toLong() * 1000L), DateTimeZone.UTC) } catch (exception: ParseException) { throw RuntimeException(exception) } } + + override fun toJson( + writer: JsonWriter, + customScalarAdapters: CustomScalarAdapters, + value: DateTime + ) { + writer.value(value.toString().toLong() / 1000L) + } } diff --git a/app/src/main/java/com/kickstarter/libs/graphql/EmailAdapter.kt b/app/src/main/java/com/kickstarter/libs/graphql/EmailAdapter.kt deleted file mode 100644 index 52a9f65cd7..0000000000 --- a/app/src/main/java/com/kickstarter/libs/graphql/EmailAdapter.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.kickstarter.libs.graphql - -import com.apollographql.apollo.api.CustomTypeAdapter -import com.apollographql.apollo.api.CustomTypeValue - -class EmailAdapter : CustomTypeAdapter { - override fun encode(value: String): CustomTypeValue<*> { - return CustomTypeValue.GraphQLString(value) - } - - override fun decode(value: CustomTypeValue<*>): String { - return value.toString() - } -} diff --git a/app/src/main/java/com/kickstarter/libs/graphql/Iso8601DateTimeAdapter.kt b/app/src/main/java/com/kickstarter/libs/graphql/Iso8601DateTimeAdapter.kt index e3cccfdad5..ffda9b1d96 100644 --- a/app/src/main/java/com/kickstarter/libs/graphql/Iso8601DateTimeAdapter.kt +++ b/app/src/main/java/com/kickstarter/libs/graphql/Iso8601DateTimeAdapter.kt @@ -1,21 +1,30 @@ package com.kickstarter.libs.graphql -import com.apollographql.apollo.api.CustomTypeAdapter -import com.apollographql.apollo.api.CustomTypeValue +import com.apollographql.apollo3.api.Adapter +import com.apollographql.apollo3.api.CustomScalarAdapters +import com.apollographql.apollo3.api.json.JsonReader +import com.apollographql.apollo3.api.json.JsonWriter import org.joda.time.DateTime import java.text.ParseException -class Iso8601DateTimeAdapter : CustomTypeAdapter { +class Iso8601DateTimeAdapter : Adapter { - override fun encode(value: DateTime): CustomTypeValue<*> { - return CustomTypeValue.GraphQLString(value.toString()) - } - - override fun decode(value: CustomTypeValue<*>): DateTime { + override fun fromJson( + reader: JsonReader, + customScalarAdapters: CustomScalarAdapters + ): DateTime { try { - return DateTime.parse(value.value.toString()) + return DateTime.parse(reader.nextString()) } catch (exception: ParseException) { throw RuntimeException(exception) } } + + override fun toJson( + writer: JsonWriter, + customScalarAdapters: CustomScalarAdapters, + value: DateTime + ) { + writer.value(value.toString()) + } } diff --git a/app/src/main/java/com/kickstarter/libs/utils/AnalyticEventsUtils.kt b/app/src/main/java/com/kickstarter/libs/utils/AnalyticEventsUtils.kt index 561198ae2c..4793b55b88 100644 --- a/app/src/main/java/com/kickstarter/libs/utils/AnalyticEventsUtils.kt +++ b/app/src/main/java/com/kickstarter/libs/utils/AnalyticEventsUtils.kt @@ -51,7 +51,7 @@ object AnalyticEventsUtils { checkoutData.id()?.let { put("id", it.toString()) } put( "payment_type", - checkoutData.paymentType().rawValue().lowercase(Locale.getDefault()) + checkoutData.paymentType().rawValue.lowercase(Locale.getDefault()) ) put("amount_total_usd", checkoutData.totalAmount(project.staticUsdRate()).round()) put("shipping_amount", checkoutData.shippingAmount()) @@ -73,7 +73,7 @@ object AnalyticEventsUtils { checkoutData.id()?.let { put("id", it.toString()) } put( "payment_type", - checkoutData.paymentType().rawValue().lowercase(Locale.getDefault()) + checkoutData.paymentType().rawValue.lowercase(Locale.getDefault()) ) put("amount_total_usd", checkoutData.totalAmount(project.staticUsdRate()).round()) put("shipping_amount", checkoutData.shippingAmount()) diff --git a/app/src/main/java/com/kickstarter/libs/utils/SharedFunctions.kt b/app/src/main/java/com/kickstarter/libs/utils/SharedFunctions.kt index 653a9d910b..567e0ed765 100644 --- a/app/src/main/java/com/kickstarter/libs/utils/SharedFunctions.kt +++ b/app/src/main/java/com/kickstarter/libs/utils/SharedFunctions.kt @@ -1,8 +1,8 @@ package com.kickstarter.libs.utils import com.kickstarter.models.Reward +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.data.CheckoutData -import type.CreditCardPaymentType /** * Total count of selected add-ons (including multiple quantities of a single add-on) diff --git a/app/src/main/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExt.kt b/app/src/main/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExt.kt index 9a5add8c3a..1a15227510 100644 --- a/app/src/main/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExt.kt +++ b/app/src/main/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExt.kt @@ -6,8 +6,8 @@ import com.kickstarter.libs.utils.ListUtils import com.kickstarter.models.Category import com.kickstarter.models.User import com.kickstarter.services.DiscoveryParams +import com.kickstarter.type.ProjectSort import com.kickstarter.ui.adapters.data.NavigationDrawerData -import type.ProjectSort import java.util.TreeMap /** diff --git a/app/src/main/java/com/kickstarter/libs/utils/extensions/ProjectExt.kt b/app/src/main/java/com/kickstarter/libs/utils/extensions/ProjectExt.kt index a3ec4e0559..c4c1549103 100644 --- a/app/src/main/java/com/kickstarter/libs/utils/extensions/ProjectExt.kt +++ b/app/src/main/java/com/kickstarter/libs/utils/extensions/ProjectExt.kt @@ -15,10 +15,10 @@ import com.kickstarter.models.Urls import com.kickstarter.models.User import com.kickstarter.models.Web import com.kickstarter.services.DiscoveryParams +import com.kickstarter.type.CreditCardTypes import io.reactivex.Observable import org.joda.time.DateTime import org.joda.time.Duration -import type.CreditCardTypes import kotlin.math.floor /** @@ -61,7 +61,7 @@ fun Project.showLatePledgeFlow() = this.isInPostCampaignPledgingPhase() ?: false * * @return boolean that represents if the card type is available */ -fun Project.acceptedCardType(cardType: CreditCardTypes?) = this.availableCardTypes()?.contains(cardType?.rawValue()) ?: false +fun Project.acceptedCardType(cardType: CreditCardTypes?) = this.availableCardTypes()?.contains(cardType?.rawValue) ?: false /** * Combines each project in the list with the discovery param diff --git a/app/src/main/java/com/kickstarter/mock/factories/CheckoutDataFactory.kt b/app/src/main/java/com/kickstarter/mock/factories/CheckoutDataFactory.kt index 1e1a83edce..7745559565 100644 --- a/app/src/main/java/com/kickstarter/mock/factories/CheckoutDataFactory.kt +++ b/app/src/main/java/com/kickstarter/mock/factories/CheckoutDataFactory.kt @@ -1,7 +1,7 @@ package com.kickstarter.mock.factories +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.data.CheckoutData -import type.CreditCardPaymentType object CheckoutDataFactory { @JvmStatic diff --git a/app/src/main/java/com/kickstarter/mock/factories/PaymentSourceFactory.kt b/app/src/main/java/com/kickstarter/mock/factories/PaymentSourceFactory.kt index 87328d5183..9e2015a0a0 100644 --- a/app/src/main/java/com/kickstarter/mock/factories/PaymentSourceFactory.kt +++ b/app/src/main/java/com/kickstarter/mock/factories/PaymentSourceFactory.kt @@ -1,7 +1,7 @@ package com.kickstarter.mock.factories import com.kickstarter.models.PaymentSource -import type.CreditCardPaymentType +import com.kickstarter.type.CreditCardPaymentType import java.util.Date class PaymentSourceFactory private constructor() { @@ -11,7 +11,7 @@ class PaymentSourceFactory private constructor() { .id(IdFactory.id().toString()) .expirationDate(Date()) .lastFour("4321") - .paymentType(CreditCardPaymentType.CREDIT_CARD.rawValue()) + .paymentType(CreditCardPaymentType.CREDIT_CARD.rawValue) .state("ACTIVE") .type("VISA") .build() @@ -20,7 +20,7 @@ class PaymentSourceFactory private constructor() { fun googlePay(): PaymentSource { return PaymentSource.builder() .id(IdFactory.id().toString()) - .paymentType(CreditCardPaymentType.ANDROID_PAY.rawValue()) + .paymentType(CreditCardPaymentType.ANDROID_PAY.rawValue) .state("ACTIVE") .build() } @@ -28,7 +28,7 @@ class PaymentSourceFactory private constructor() { fun applePay(): PaymentSource { return PaymentSource.builder() .id(IdFactory.id().toString()) - .paymentType(CreditCardPaymentType.APPLE_PAY.rawValue()) + .paymentType(CreditCardPaymentType.APPLE_PAY.rawValue) .state("ACTIVE") .build() } @@ -36,7 +36,7 @@ class PaymentSourceFactory private constructor() { fun bankAccount(): PaymentSource { return PaymentSource.builder() .id(IdFactory.id().toString()) - .paymentType(CreditCardPaymentType.BANK_ACCOUNT.rawValue()) + .paymentType(CreditCardPaymentType.BANK_ACCOUNT.rawValue) .state("ACTIVE") .build() } diff --git a/app/src/main/java/com/kickstarter/mock/factories/ProjectEnvironmentalCommitmentFactory.kt b/app/src/main/java/com/kickstarter/mock/factories/ProjectEnvironmentalCommitmentFactory.kt index 2e962e6d93..91500896bf 100644 --- a/app/src/main/java/com/kickstarter/mock/factories/ProjectEnvironmentalCommitmentFactory.kt +++ b/app/src/main/java/com/kickstarter/mock/factories/ProjectEnvironmentalCommitmentFactory.kt @@ -1,7 +1,7 @@ package com.kickstarter.mock.factories +import com.kickstarter.libs.EnvironmentalCommitmentCategories import com.kickstarter.models.EnvironmentalCommitment -import type.EnvironmentalCommitmentCategory class ProjectEnvironmentalCommitmentFactory private constructor() { companion object { @@ -18,7 +18,7 @@ class ProjectEnvironmentalCommitmentFactory private constructor() { "No, there is no extra VAT or taxes for backers.\r\n\r\nWe will export the " + "tables to local countries first and forward to respective shipping addresses through local couriers. We will clear the customs for all the desks. \r\n\r\nVAT and taxes are already included in the reward price and no extra payment will be required from backers." ) - .category(EnvironmentalCommitmentCategory.LONG_LASTING_DESIGN.name) + .category(EnvironmentalCommitmentCategories.LONG_LASTING_DESIGN.name.lowercase()) .build() private fun getSustainableMaterialsCategory() = EnvironmentalCommitment.builder() @@ -27,7 +27,7 @@ class ProjectEnvironmentalCommitmentFactory private constructor() { "No, there is no extra VAT or taxes for backers.\r\n\r\nWe will export the " + "tables to local countries first and forward to respective shipping addresses through local couriers. We will clear the customs for all the desks. \r\n\r\nVAT and taxes are already included in the reward price and no extra payment will be required from backers." ) - .category(EnvironmentalCommitmentCategory.SUSTAINABLE_MATERIALS.name) + .category(EnvironmentalCommitmentCategories.SUSTAINABLE_MATERIALS.name.lowercase()) .build() } } diff --git a/app/src/main/java/com/kickstarter/mock/factories/ProjectFactory.kt b/app/src/main/java/com/kickstarter/mock/factories/ProjectFactory.kt index 7ed3aca7ce..979280cb41 100644 --- a/app/src/main/java/com/kickstarter/mock/factories/ProjectFactory.kt +++ b/app/src/main/java/com/kickstarter/mock/factories/ProjectFactory.kt @@ -1,16 +1,14 @@ package com.kickstarter.mock.factories -import com.apollographql.apollo.api.CustomTypeValue -import com.kickstarter.libs.graphql.DateTimeAdapter import com.kickstarter.models.Backing import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.models.Urls import com.kickstarter.models.Web +import com.kickstarter.type.CreditCardPaymentType +import com.kickstarter.type.CreditCardTypes import org.joda.time.DateTime import org.joda.time.DateTimeZone -import type.CreditCardPaymentType -import type.CreditCardTypes object ProjectFactory { @JvmStatic @@ -26,13 +24,13 @@ object ProjectFactory { return Project.builder() .availableCardTypes( listOf( - CreditCardTypes.AMEX.rawValue(), - CreditCardTypes.DINERS.rawValue(), - CreditCardTypes.DISCOVER.rawValue(), - CreditCardTypes.JCB.rawValue(), - CreditCardTypes.MASTERCARD.rawValue(), - CreditCardTypes.UNIONPAY.rawValue(), - CreditCardTypes.VISA.rawValue() + CreditCardTypes.AMEX.rawValue, + CreditCardTypes.DINERS.rawValue, + CreditCardTypes.DISCOVER.rawValue, + CreditCardTypes.JCB.rawValue, + CreditCardTypes.MASTERCARD.rawValue, + CreditCardTypes.UNIONPAY.rawValue, + CreditCardTypes.VISA.rawValue ) ) .backersCount(100) @@ -128,7 +126,7 @@ object ProjectFactory { .build() return project .toBuilder() - .availableCardTypes(listOf(PaymentSourceFactory.visa().type() ?: CreditCardPaymentType.CREDIT_CARD.rawValue())) + .availableCardTypes(listOf(PaymentSourceFactory.visa().type() ?: CreditCardPaymentType.CREDIT_CARD.rawValue)) .canComment(true) .backing(backing) .isBacking(true) @@ -376,9 +374,9 @@ object ProjectFactory { .toBuilder() .availableCardTypes( listOf( - CreditCardTypes.AMEX.rawValue(), - CreditCardTypes.MASTERCARD.rawValue(), - CreditCardTypes.VISA.rawValue() + CreditCardTypes.AMEX.rawValue, + CreditCardTypes.MASTERCARD.rawValue, + CreditCardTypes.VISA.rawValue ) ) .name("caProject") @@ -398,9 +396,9 @@ object ProjectFactory { .toBuilder() .availableCardTypes( listOf( - CreditCardTypes.AMEX.rawValue(), - CreditCardTypes.MASTERCARD.rawValue(), - CreditCardTypes.VISA.rawValue() + CreditCardTypes.AMEX.rawValue, + CreditCardTypes.MASTERCARD.rawValue, + CreditCardTypes.VISA.rawValue ) ) .name("mxCurrencyCAProject") @@ -419,9 +417,9 @@ object ProjectFactory { .toBuilder() .availableCardTypes( listOf( - CreditCardTypes.AMEX.rawValue(), - CreditCardTypes.MASTERCARD.rawValue(), - CreditCardTypes.VISA.rawValue() + CreditCardTypes.AMEX.rawValue, + CreditCardTypes.MASTERCARD.rawValue, + CreditCardTypes.VISA.rawValue ) ) .name("mxProject") @@ -442,9 +440,9 @@ object ProjectFactory { .toBuilder() .availableCardTypes( listOf( - CreditCardTypes.AMEX.rawValue(), - CreditCardTypes.MASTERCARD.rawValue(), - CreditCardTypes.VISA.rawValue() + CreditCardTypes.AMEX.rawValue, + CreditCardTypes.MASTERCARD.rawValue, + CreditCardTypes.VISA.rawValue ) ) .name("ukProject") @@ -512,7 +510,7 @@ object ProjectFactory { return project() .toBuilder() - .launchedAt(DateTimeAdapter().decode(CustomTypeValue.fromRawValue(0))) + .launchedAt(DateTime(0)) .displayPrelaunch(true) .urls(Urls.builder().web(web).build()) .build() diff --git a/app/src/main/java/com/kickstarter/mock/factories/StoredCardFactory.kt b/app/src/main/java/com/kickstarter/mock/factories/StoredCardFactory.kt index e0bb5c4086..a834bc23b7 100644 --- a/app/src/main/java/com/kickstarter/mock/factories/StoredCardFactory.kt +++ b/app/src/main/java/com/kickstarter/mock/factories/StoredCardFactory.kt @@ -1,7 +1,7 @@ package com.kickstarter.mock.factories import com.kickstarter.models.StoredCard -import type.CreditCardTypes +import com.kickstarter.type.CreditCardTypes import java.util.Date object StoredCardFactory { diff --git a/app/src/main/java/com/kickstarter/mock/services/MockApolloClientV2.kt b/app/src/main/java/com/kickstarter/mock/services/MockApolloClientV2.kt index abf3efb5e8..78fe8bbc56 100644 --- a/app/src/main/java/com/kickstarter/mock/services/MockApolloClientV2.kt +++ b/app/src/main/java/com/kickstarter/mock/services/MockApolloClientV2.kt @@ -1,12 +1,12 @@ package com.kickstarter.mock.services -import CreatePasswordMutation -import DeletePaymentSourceMutation -import SendEmailVerificationMutation -import UpdateUserCurrencyMutation -import UpdateUserEmailMutation -import UpdateUserPasswordMutation import android.util.Pair +import com.kickstarter.CreatePasswordMutation +import com.kickstarter.DeletePaymentSourceMutation +import com.kickstarter.SendEmailVerificationMutation +import com.kickstarter.UpdateUserCurrencyMutation +import com.kickstarter.UpdateUserEmailMutation +import com.kickstarter.UpdateUserPasswordMutation import com.kickstarter.features.pledgedprojectsoverview.data.PledgedProjectsOverviewEnvelope import com.kickstarter.features.pledgedprojectsoverview.data.PledgedProjectsOverviewQueryData import com.kickstarter.mock.factories.BackingFactory @@ -47,8 +47,8 @@ import com.kickstarter.services.mutations.CreateOrUpdateBackingAddressData import com.kickstarter.services.mutations.PostCommentData import com.kickstarter.services.mutations.SavePaymentMethodData import com.kickstarter.services.mutations.UpdateBackingData +import com.kickstarter.type.CurrencyCode import com.kickstarter.viewmodels.usecases.TPEventInputData -import type.CurrencyCode import java.util.Collections open class MockApolloClientV2 : ApolloClientTypeV2 { @@ -73,8 +73,7 @@ open class MockApolloClientV2 : ApolloClientTypeV2 { return io.reactivex.Observable.just( UpdateUserPasswordMutation.Data( UpdateUserPasswordMutation.UpdateUserAccount( - "", - UpdateUserPasswordMutation.User("", "some@email.com", true, true) + UpdateUserPasswordMutation.User("some@email.com", true, true) ) ) ) @@ -86,8 +85,7 @@ open class MockApolloClientV2 : ApolloClientTypeV2 { return io.reactivex.Observable.just( UpdateUserEmailMutation.Data( UpdateUserEmailMutation.UpdateUserAccount( - "", - UpdateUserEmailMutation.User("", "Some Name", "some@email.com") + UpdateUserEmailMutation.User("Some Name", "some@email.com") ) ) ) @@ -97,7 +95,6 @@ open class MockApolloClientV2 : ApolloClientTypeV2 { return io.reactivex.Observable.just( SendEmailVerificationMutation.Data( SendEmailVerificationMutation.UserSendEmailVerification( - "", "12345" ) ) @@ -153,7 +150,7 @@ open class MockApolloClientV2 : ApolloClientTypeV2 { } override fun deletePaymentSource(paymentSourceId: String): io.reactivex.Observable { - return io.reactivex.Observable.just(DeletePaymentSourceMutation.Data(DeletePaymentSourceMutation.PaymentSourceDelete("", ""))) + return io.reactivex.Observable.just(DeletePaymentSourceMutation.Data(DeletePaymentSourceMutation.PaymentSourceDelete(""))) } override fun savePaymentMethod(savePaymentMethodData: SavePaymentMethodData): io.reactivex.Observable { @@ -343,4 +340,8 @@ open class MockApolloClientV2 : ApolloClientTypeV2 { override fun getPledgedProjectsOverviewPledges(inputData: PledgedProjectsOverviewQueryData): io.reactivex.Observable { return io.reactivex.Observable.empty() } + + override fun cleanDisposables() { + TODO("Not yet implemented") + } } diff --git a/app/src/main/java/com/kickstarter/models/StoredCard.kt b/app/src/main/java/com/kickstarter/models/StoredCard.kt index 2f82dac147..99df1a41ea 100644 --- a/app/src/main/java/com/kickstarter/models/StoredCard.kt +++ b/app/src/main/java/com/kickstarter/models/StoredCard.kt @@ -1,9 +1,9 @@ package com.kickstarter.models import android.os.Parcelable +import com.kickstarter.type.CreditCardTypes import com.stripe.android.model.CardBrand import kotlinx.parcelize.Parcelize -import type.CreditCardTypes import java.util.Date @Parcelize @@ -29,7 +29,7 @@ class StoredCard private constructor( private var id: String? = "0L", private var lastFourDigits: String? = "", private var expiration: Date? = null, - private var type: CreditCardTypes? = CreditCardTypes.`$UNKNOWN`, + private var type: CreditCardTypes? = CreditCardTypes.UNKNOWN__, private var resourceId: Int? = null, private var clientSetupId: String? = null, private var stripeCardId: String? = null diff --git a/app/src/main/java/com/kickstarter/models/extensions/CommentExt.kt b/app/src/main/java/com/kickstarter/models/extensions/CommentExt.kt index 178aa9f788..7be51a1d09 100644 --- a/app/src/main/java/com/kickstarter/models/extensions/CommentExt.kt +++ b/app/src/main/java/com/kickstarter/models/extensions/CommentExt.kt @@ -5,7 +5,6 @@ import com.kickstarter.models.User import com.kickstarter.ui.data.CommentCardData import com.kickstarter.ui.views.CommentCardBadge import com.kickstarter.ui.views.CommentCardStatus -import type.CommentBadge /** * Update the internal persisted list of comments with the successful response @@ -50,10 +49,10 @@ fun Comment.updateCommentFailedToPost( } fun Comment.assignAuthorBadge(user: User? = null): CommentCardBadge { - if (this.authorBadges()?.contains(CommentBadge.CREATOR.rawValue()) == true) return CommentCardBadge.CREATOR - if (this.authorBadges()?.contains(CommentBadge.COLLABORATOR.rawValue()) == true) return CommentCardBadge.COLLABORATOR - if (this.authorBadges()?.contains(CommentBadge.SUPERBACKER.rawValue()) == true) return CommentCardBadge.SUPERBACKER - if (this.author()?.id() == user?.id()) return CommentCardBadge.YOU + if (this.authorBadges()?.contains(CommentCardBadge.CREATOR.name.lowercase()) == true) return CommentCardBadge.CREATOR + if (this.authorBadges()?.contains(CommentCardBadge.COLLABORATOR.name.lowercase()) == true) return CommentCardBadge.COLLABORATOR + if (this.authorBadges()?.contains(CommentCardBadge.SUPERBACKER.name.lowercase()) == true) return CommentCardBadge.SUPERBACKER + if (this.author().id() == user?.id()) return CommentCardBadge.YOU return CommentCardBadge.NO_BADGE } diff --git a/app/src/main/java/com/kickstarter/models/extensions/StoredCardExt.kt b/app/src/main/java/com/kickstarter/models/extensions/StoredCardExt.kt index 258daa6bde..178b5b1b23 100644 --- a/app/src/main/java/com/kickstarter/models/extensions/StoredCardExt.kt +++ b/app/src/main/java/com/kickstarter/models/extensions/StoredCardExt.kt @@ -8,10 +8,10 @@ import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.models.StoredCard import com.kickstarter.services.mutations.CreateBackingData -import type.CreditCardTypes +import com.kickstarter.type.CreditCardTypes fun StoredCard.getCardTypeDrawable(): Int { - val cardType = this.type() ?: CreditCardTypes.`$UNKNOWN` + val cardType = this.type() ?: CreditCardTypes.UNKNOWN__ val resourceId = this.expiration()?.let { getCardTypeDrawable(cardType) } ?: this.resourceId() ?: R.drawable.generic_bank_md @@ -20,7 +20,7 @@ fun StoredCard.getCardTypeDrawable(): Int { } fun StoredCard.isFromPaymentSheet(): Boolean { - return this.type() == CreditCardTypes.`$UNKNOWN` && + return this.type() == CreditCardTypes.UNKNOWN__ && this.lastFourDigits()?.isNotEmpty() ?: false && this.clientSetupId()?.isNotEmpty() ?: false } @@ -56,7 +56,7 @@ fun StoredCard.getBackingData( } fun PaymentSource.getCardTypeDrawable(): Int { - val type = CreditCardTypes.safeValueOf(this.type()) + val type = CreditCardTypes.safeValueOf(this.type() ?: "") return getCardTypeDrawable(type) } diff --git a/app/src/main/java/com/kickstarter/services/KSApolloClientV2.kt b/app/src/main/java/com/kickstarter/services/KSApolloClientV2.kt index 1f14cfe756..347f90a2c7 100644 --- a/app/src/main/java/com/kickstarter/services/KSApolloClientV2.kt +++ b/app/src/main/java/com/kickstarter/services/KSApolloClientV2.kt @@ -1,56 +1,58 @@ package com.kickstarter.services -import CancelBackingMutation -import ClearUserUnseenActivityMutation -import CompleteOnSessionCheckoutMutation -import CreateAttributionEventMutation -import CreateBackingMutation -import CreateCheckoutMutation -import CreateCommentMutation -import CreateFlaggingMutation -import CreatePasswordMutation -import CreatePaymentIntentMutation -import CreateSetupIntentMutation -import DeletePaymentSourceMutation -import ErroredBackingsQuery -import FetchCategoryQuery -import FetchProjectQuery -import FetchProjectRewardsQuery -import FetchProjectsQuery -import GetBackingQuery -import GetCommentQuery -import GetProjectAddOnsQuery -import GetProjectBackingQuery -import GetProjectCommentsQuery -import GetProjectUpdateCommentsQuery -import GetProjectUpdatesQuery -import GetRepliesForCommentQuery -import GetRootCategoriesQuery -import GetShippingRulesForRewardIdQuery -import ProjectCreatorDetailsQuery -import SavePaymentMethodMutation -import SendEmailVerificationMutation -import SendMessageMutation -import TriggerThirdPartyEventMutation -import UnwatchProjectMutation -import UpdateBackingMutation -import UpdateUserCurrencyMutation -import UpdateUserEmailMutation -import UpdateUserPasswordMutation -import UserPaymentsQuery -import UserPrivacyQuery -import ValidateCheckoutQuery -import WatchProjectMutation import android.util.Pair -import com.apollographql.apollo.ApolloCall -import com.apollographql.apollo.ApolloClient -import com.apollographql.apollo.api.Response -import com.apollographql.apollo.exception.ApolloException +import com.apollographql.apollo3.ApolloClient +import com.apollographql.apollo3.api.ApolloResponse +import com.apollographql.apollo3.api.Optional +import com.apollographql.apollo3.rx2.rxFlowable +import com.apollographql.apollo3.rx2.rxSingle import com.google.android.gms.common.util.Base64Utils import com.google.gson.Gson +import com.kickstarter.CancelBackingMutation +import com.kickstarter.ClearUserUnseenActivityMutation +import com.kickstarter.CompleteOnSessionCheckoutMutation +import com.kickstarter.CompleteOrderMutation +import com.kickstarter.CreateBackingMutation +import com.kickstarter.CreateCheckoutMutation +import com.kickstarter.CreateCommentMutation +import com.kickstarter.CreateFlaggingMutation +import com.kickstarter.CreatePasswordMutation +import com.kickstarter.CreatePaymentIntentMutation +import com.kickstarter.CreateSetupIntentMutation +import com.kickstarter.DeletePaymentSourceMutation +import com.kickstarter.ErroredBackingsQuery +import com.kickstarter.FetchCategoryQuery +import com.kickstarter.FetchProjectQuery +import com.kickstarter.FetchProjectRewardsQuery +import com.kickstarter.FetchProjectsQuery +import com.kickstarter.GetBackingQuery +import com.kickstarter.GetCommentQuery +import com.kickstarter.GetProjectAddOnsQuery +import com.kickstarter.GetProjectBackingQuery +import com.kickstarter.GetProjectCommentsQuery +import com.kickstarter.GetProjectUpdateCommentsQuery +import com.kickstarter.GetProjectUpdatesQuery +import com.kickstarter.GetRepliesForCommentQuery +import com.kickstarter.GetRootCategoriesQuery +import com.kickstarter.GetShippingRulesForRewardIdQuery +import com.kickstarter.ProjectCreatorDetailsQuery +import com.kickstarter.SavePaymentMethodMutation +import com.kickstarter.SendEmailVerificationMutation +import com.kickstarter.SendMessageMutation +import com.kickstarter.UnwatchProjectMutation +import com.kickstarter.UpdateBackingMutation +import com.kickstarter.UpdateUserCurrencyMutation +import com.kickstarter.UpdateUserEmailMutation +import com.kickstarter.UpdateUserPasswordMutation +import com.kickstarter.UserPaymentsQuery +import com.kickstarter.UserPrivacyQuery +import com.kickstarter.ValidateCheckoutQuery +import com.kickstarter.WatchProjectMutation import com.kickstarter.features.pledgedprojectsoverview.data.PledgedProjectsOverviewEnvelope import com.kickstarter.features.pledgedprojectsoverview.data.PledgedProjectsOverviewQueryData +import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.libs.utils.extensions.isNotNull +import com.kickstarter.libs.utils.extensions.isPresent import com.kickstarter.libs.utils.extensions.toBoolean import com.kickstarter.libs.utils.extensions.toProjectSort import com.kickstarter.mock.factories.RewardFactory @@ -92,22 +94,22 @@ import com.kickstarter.services.transformers.encodeRelayId import com.kickstarter.services.transformers.getCreateAttributionEventMutation import com.kickstarter.services.transformers.getCreateOrUpdateBackingAddressMutation import com.kickstarter.services.transformers.getPledgedProjectsOverviewQuery -import com.kickstarter.services.transformers.getTriggerThirdPartyEventMutation import com.kickstarter.services.transformers.pledgedProjectsOverviewEnvelopeTransformer import com.kickstarter.services.transformers.projectTransformer import com.kickstarter.services.transformers.rewardTransformer import com.kickstarter.services.transformers.shippingRulesListTransformer import com.kickstarter.services.transformers.updateTransformer import com.kickstarter.services.transformers.userPrivacyTransformer +import com.kickstarter.type.BackingState +import com.kickstarter.type.CurrencyCode +import com.kickstarter.type.NonDeprecatedFlaggingKind +import com.kickstarter.type.PaymentTypes +import com.kickstarter.type.StripeIntentContextTypes import com.kickstarter.viewmodels.usecases.TPEventInputData import io.reactivex.Observable +import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject -import type.BackingState -import type.CurrencyCode -import type.NonDeprecatedFlaggingKind -import type.PaymentTypes -import type.StripeIntentContextTypes import java.nio.charset.Charset interface ApolloClientTypeV2 { @@ -211,12 +213,19 @@ interface ApolloClientTypeV2 { fun completeOrder(orderInput: CompleteOrderInput): Observable fun getPledgedProjectsOverviewPledges(inputData: PledgedProjectsOverviewQueryData): Observable fun getRewardsFromProject(slug: String): Observable> + fun cleanDisposables() } private const val PAGE_SIZE = 25 private const val REPLIES_PAGE_SIZE = 7 class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClientTypeV2 { + private val disposables = CompositeDisposable() + + override fun cleanDisposables() { + disposables.clear() + } + override fun getProject(project: Project): Observable { return getProject(project.slug() ?: "") } @@ -224,53 +233,53 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun getProject(slug: String): Observable { return Observable.defer { val ps = PublishSubject.create() + val query = FetchProjectQuery(slug) this.service.query( - FetchProjectQuery.builder() - .slug(slug) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + query + ).rxSingle() + .subscribeOn(Schedulers.io()) + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { - if (response.hasErrors()) ps.onError(java.lang.Exception(response.errors?.first()?.message)) - else { + .subscribe { response -> + if (response.hasErrors()) { + if (response.hasErrors()) ps.onError(java.lang.Exception(response.errors?.first()?.message)) + } else { response.data?.let { responseData -> ps.onNext( projectTransformer( - responseData.project()?.fragments()?.fullProject() + responseData.project?.fullProject ) ) } - ps.onComplete() } - } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } override fun getProjects( discoveryParams: DiscoveryParams, - slug: String? + cursor: String? ): Observable { - return Observable.defer { - val ps = PublishSubject.create() - this.service.query( - buildFetchProjectsQuery(discoveryParams, slug) - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } - - override fun onResponse(response: Response) { + val ps = PublishSubject.create() + this.service.query(query = buildFetchProjectsQuery(discoveryParams, cursor)) + .rxFlowable() + .subscribeOn(Schedulers.io()) + .doOnError { + ps.onError(it) + } + .subscribe { response -> + if (response.hasErrors()) { + if (response.hasErrors()) ps.onError(java.lang.Exception(response.errors?.first()?.message)) + } else { response.data?.let { responseData -> - val projects = responseData.projects()?.edges()?.map { - projectTransformer(it.node()?.fragments()?.projectCard()) + val projects = responseData.projects?.edges?.map { + projectTransformer(it?.node?.projectCard) } val pageInfoEnvelope = - responseData.projects()?.pageInfo()?.fragments()?.pageInfo()?.let { + responseData.projects?.pageInfo?.pageInfo?.let { createPageInfoObject(it) } val discoverEnvelope = DiscoverEnvelope.builder() @@ -279,100 +288,88 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient .build() ps.onNext(discoverEnvelope) } - ps.onComplete() } - }) - return@defer ps - }.subscribeOn(Schedulers.io()) + ps.onComplete() + }.addToDisposable(disposables) + return ps } private fun buildFetchProjectsQuery( discoveryParams: DiscoveryParams, - slug: String? + cursor: String? ): FetchProjectsQuery { - val query = FetchProjectsQuery.builder() - .sort(discoveryParams.sort()?.toProjectSort()) - .apply { - slug?.let { cursor -> if (cursor.isNotEmpty()) this.cursor(cursor) } - discoveryParams.category()?.id()?.let { id -> this.categoryId(id.toString()) } - discoveryParams.recommended() - ?.let { isRecommended -> this.recommended(isRecommended) } - discoveryParams.starred()?.let { isStarred -> this.starred(isStarred.toBoolean()) } - discoveryParams.backed()?.let { isBacked -> this.backed(isBacked.toBoolean()) } - discoveryParams.staffPicks()?.let { isPicked -> this.staffPicks(isPicked) } - } - .build() - - return query + return FetchProjectsQuery( + sort = Optional.present(discoveryParams.sort()?.toProjectSort()), + cursor = cursor?.let { if (it.isNotEmpty()) Optional.present(it) else Optional.absent() } ?: Optional.absent(), + categoryId = if (discoveryParams.category()?.id() == null) Optional.absent() else Optional.present(discoveryParams.category()?.id().toString()), + recommended = if (discoveryParams.recommended() == null) Optional.absent() else Optional.present(discoveryParams.recommended()), + starred = if (discoveryParams.starred() == null) Optional.absent() else Optional.present(discoveryParams.starred().toBoolean()), + backed = if (discoveryParams.staffPicks() == null) Optional.absent() else Optional.present(discoveryParams.backed().toBoolean()) + ) } override fun createSetupIntent(project: Project?): Observable { return Observable.defer { - val createSetupIntentMut = CreateSetupIntentMutation.builder() - .apply { - project?.let { - this.projectId(encodeRelayId(it)) - this.setupIntentContext(StripeIntentContextTypes.CROWDFUNDING_CHECKOUT) - } ?: run { - this.setupIntentContext(StripeIntentContextTypes.PROFILE_SETTINGS) - } - } - .build() - val ps = PublishSubject.create() - this.service.mutate(createSetupIntentMut) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) ps.onError(java.lang.Exception(response.errors?.first()?.message)) - else { - ps.onNext(response.data?.createSetupIntent()?.clientSecret() ?: "") - } - ps.onComplete() + val mutation = project?.let { + CreateSetupIntentMutation( + projectId = Optional.present(encodeRelayId(it)), + setupIntentContext = Optional.present(StripeIntentContextTypes.CROWDFUNDING_CHECKOUT) + ) + } ?: CreateSetupIntentMutation(Optional.absent(), Optional.present(StripeIntentContextTypes.PROFILE_SETTINGS)) + + this.service.mutation(mutation) + .rxSingle() + .subscribeOn(Schedulers.io()) + .doOnError { + ps.onError(it) + } + .subscribe { response -> + if (response.hasErrors()) + ps.onError(java.lang.Exception(response.errors?.first()?.message)) + else { + ps.onNext(response.data?.createSetupIntent?.clientSecret ?: "") } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps - } + }.subscribeOn(Schedulers.io()) } override fun savePaymentMethod(savePaymentMethodData: SavePaymentMethodData): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - SavePaymentMethodMutation.builder() - .paymentType(savePaymentMethodData.paymentType) - .stripeToken(savePaymentMethodData.stripeToken) - .stripeCardId(savePaymentMethodData.stripeCardId) - .reusable(savePaymentMethodData.reusable) - .intentClientSecret(savePaymentMethodData.intentClientSecret) - .build() + val mutation = SavePaymentMethodMutation( + paymentType = if (savePaymentMethodData.paymentType.isNotNull()) Optional.present(savePaymentMethodData.paymentType) else Optional.absent(), + stripeToken = if (savePaymentMethodData.stripeToken.isNotNull()) Optional.present(savePaymentMethodData.stripeToken) else Optional.absent(), + stripeCardId = if (savePaymentMethodData.stripeCardId.isNotNull()) Optional.present(savePaymentMethodData.stripeCardId) else Optional.absent(), + reusable = if (savePaymentMethodData.reusable.isNotNull()) Optional.present(savePaymentMethodData.reusable) else Optional.absent(), + intentClientSecret = if (savePaymentMethodData.intentClientSecret.isNotNull()) Optional.present(savePaymentMethodData.intentClientSecret) else Optional.absent() ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.mutation( + mutation + ) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - - val paymentSource = response.data?.createPaymentSource()?.paymentSource() - paymentSource?.let { - val storedCard = StoredCard.builder() - .expiration(it.expirationDate()) - .id(it.id()) - .lastFourDigits(it.lastFour()) - .type(it.type()) - .build() - ps.onNext(storedCard) - } - ps.onComplete() + val paymentSource = response.data?.createPaymentSource?.paymentSource + paymentSource?.let { + val storedCard = StoredCard.builder() + .expiration(it.expirationDate) + .id(it.id) + .lastFourDigits(it.lastFour) + .type(it.type) + .build() + ps.onNext(storedCard) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -380,34 +377,35 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun getStoredCards(): Observable> { return Observable.defer { val ps = PublishSubject.create>() - this.service.query(UserPaymentsQuery.builder().build()) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } else { - val cardsList = mutableListOf() - response.data?.me()?.storedCards()?.nodes()?.map { - it?.let { cardData -> - val card = StoredCard.builder() - .expiration(cardData.expirationDate()) - .id(cardData.id()) - .lastFourDigits(cardData.lastFour()) - .type(it.type()) - .stripeCardId(it.stripeCardId()) - .build() - cardsList.add(card) - } + val query = UserPaymentsQuery() + this.service + .query(query) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } else { + val cardsList = mutableListOf() + response.data?.me?.storedCards?.nodes?.map { + it?.let { cardData -> + val card = StoredCard.builder() + .expiration(cardData.expirationDate) + .id(cardData.id) + .lastFourDigits(cardData.lastFour) + .type(it.type) + .stripeCardId(it.stripeCardId) + .build() + cardsList.add(card) } - ps.onNext(cardsList) } - ps.onComplete() + ps.onNext(cardsList) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -415,25 +413,25 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun deletePaymentSource(paymentSourceId: String): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - DeletePaymentSourceMutation.builder() - .paymentSourceId(paymentSourceId) - .build() + val mutation = DeletePaymentSourceMutation( + paymentSourceId = paymentSourceId, ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { ps.onNext(it) } - ps.onComplete() + service.mutation( + mutation + ) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - }) + + response.data?.let { ps.onNext(it) } + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -447,31 +445,29 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient project?.let { val ps = PublishSubject.create() val flagging = NonDeprecatedFlaggingKind.safeValueOf(flaggingKind) - val mutation = CreateFlaggingMutation.builder() - .contentId(encodeRelayId(it)) - .details(details) - .kind(flagging) - .build() + val mutation = CreateFlaggingMutation( + contentId = encodeRelayId(it), + details = Optional.present(details), + kind = flagging + ) - service.mutate( + service.mutation( mutation - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } response.data?.let { data -> - data.createFlagging()?.flagging()?.kind()?.name?.let { kindString -> + data.createFlagging?.flagging?.kind?.name?.let { kindString -> ps.onNext(kindString) } } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps } } @@ -480,19 +476,20 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun userPrivacy(): Observable { return Observable.defer { val ps = PublishSubject.create() - service.query(UserPrivacyQuery.builder().build()) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } + val query = UserPrivacyQuery() - override fun onResponse(response: Response) { - response.data?.me()?.let { - ps.onNext(userPrivacyTransformer(it)) - } - ps.onComplete() + service.query( + query = query + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + response.data?.me?.let { + ps.onNext(userPrivacyTransformer(it)) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -500,30 +497,31 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun watchProject(project: Project): Observable { return Observable.defer { val ps = PublishSubject.create() - this.service.mutate( - WatchProjectMutation.builder().id(encodeRelayId(project)).build() + val mutation = WatchProjectMutation( + id = encodeRelayId(project) ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + this.service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(java.lang.Exception(response.errors?.first()?.message)) } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(java.lang.Exception(response.errors?.first()?.message)) - } - /* make a copy of what you posted. just in case - * we want to update the list without doing - * a full refresh. - */ - ps.onNext( - projectTransformer( - response.data?.watchProject()?.project()?.fragments()?.fullProject() - ) + /* make a copy of what you posted. just in case + * we want to update the list without doing + * a full refresh. + */ + ps.onNext( + projectTransformer( + response.data?.watchProject?.project?.fullProject ) - ps.onComplete() - } - }) + ) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -531,30 +529,30 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun unWatchProject(project: Project): Observable { return Observable.defer { val ps = PublishSubject.create() - this.service.mutate( - UnwatchProjectMutation.builder().id(encodeRelayId(project)).build() + val mutation = UnwatchProjectMutation( + id = encodeRelayId(project) ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(java.lang.Exception(response.errors?.first()?.message)) - } - /* make a copy of what you posted. just in case - * we want to update the list without doing - * a full refresh. - */ - ps.onNext( - projectTransformer( - response.data?.watchProject()?.project()?.fragments()?.fullProject() - ) + this.service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(java.lang.Exception(response.errors?.first()?.message)) + } + /* make a copy of what you posted. just in case + * we want to update the list without doing + * a full refresh. + */ + ps.onNext( + projectTransformer( + response.data?.watchProject?.project?.fullProject ) - ps.onComplete() - } - }) + ) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -566,29 +564,26 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient ): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - UpdateUserPasswordMutation.builder() - .currentPassword(currentPassword) - .password(newPassword) - .passwordConfirmation(confirmPassword) - .build() + val mutation = UpdateUserPasswordMutation( + currentPassword = currentPassword, + password = newPassword, + passwordConfirmation = confirmPassword + ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.mutation(mutation) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { - ps.onNext(it) - } - - ps.onComplete() + response.data?.let { + ps.onNext(it) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -599,27 +594,25 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient ): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - UpdateUserEmailMutation.builder() - .email(email) - .currentPassword(currentPassword) - .build() + val mutation = UpdateUserEmailMutation( + email = email, + currentPassword = currentPassword ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { data -> - ps.onNext(data) - } - ps.onComplete() + response.data?.let { data -> + ps.onNext(data) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -627,25 +620,22 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun sendVerificationEmail(): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - SendEmailVerificationMutation.builder() - .build() - ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + val mutation = SendEmailVerificationMutation() + service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { data -> - ps.onNext(data) - } - ps.onComplete() + response.data?.let { data -> + ps.onNext(data) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -653,26 +643,24 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun updateUserCurrencyPreference(currency: CurrencyCode): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - UpdateUserCurrencyMutation.builder() - .chosenCurrency(currency) - .build() + val mutation = UpdateUserCurrencyMutation( + chosenCurrency = currency ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { - ps.onNext(it) - } - ps.onComplete() + response.data?.let { + ps.onNext(it) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -680,39 +668,29 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun getShippingRules(reward: Reward): Observable { return Observable.defer { val ps = PublishSubject.create() - val query = GetShippingRulesForRewardIdQuery.builder() - .rewardId(encodeRelayId(reward)) - .build() - this.service.query(query) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + val query = GetShippingRulesForRewardIdQuery( + rewardId = encodeRelayId(reward) + ) + this.service + .query(query) + .rxFlowable() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - - response.data?.let { data -> - Observable.just(data?.node() as? GetShippingRulesForRewardIdQuery.AsReward) - .filter { !it?.shippingRulesExpanded()?.nodes().isNullOrEmpty() } - .map { - it?.shippingRulesExpanded()?.nodes()?.mapNotNull { node -> - node.fragments().shippingRule() - } - } - .filter { it.isNotNull() } - .subscribe { shippingList -> - val shippingEnvelope = - shippingRulesListTransformer(shippingList ?: emptyList()) - ps.onNext(shippingEnvelope) - }.dispose() - } - ps.onComplete() + response.data?.let { data -> + val shippingEnvelope = data.node?.onReward?.shippingRulesExpanded?.nodes?.mapNotNull { node -> + node?.shippingRule + } ?: emptyList() + ps.onNext(shippingRulesListTransformer(shippingEnvelope)) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } @@ -720,51 +698,50 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun getRewardsFromProject(slug: String): Observable> { return Observable.defer { val ps = PublishSubject.create>() - val query = FetchProjectRewardsQuery.builder() - .slug(slug) - .build() + val query = FetchProjectRewardsQuery(slug) this.service.query(query) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + .rxFlowable() + .subscribeOn(Schedulers.io()) + .doOnError { + ps.onError(it) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { data -> - val rwList = data.project()?.rewards()?.nodes()?.map { + response.data?.let { data -> + val rwList: List = data.project?.rewards?.nodes?.map { + it?.reward?.let { rwGr -> rewardTransformer( - rewardGr = it.fragments().reward(), - allowedAddons = it.allowedAddons().pageInfo().startCursor()?.isNotEmpty() ?: false, - rewardItems = complexRewardItemsTransformer(it.items()?.fragments()?.rewardItems()), - simpleShippingRules = it.simpleShippingRulesExpanded() + rewardGr = rwGr, + allowedAddons = it.allowedAddons.pageInfo.startCursor?.isNotEmpty() ?: false, + rewardItems = complexRewardItemsTransformer(it.items?.rewardItems), + simpleShippingRules = it.simpleShippingRulesExpanded.filterNotNull() ) - } ?: emptyList() - // - API does not provide the Reward no reward, we need to add it first - val minPledge = data.project()?.minPledge()?.toDouble() ?: 1.0 - val modifiedRewards = rwList.toMutableList() - modifiedRewards.add(0, RewardFactory.noReward().toBuilder().minimum(minPledge).build()) - ps.onNext(modifiedRewards.toList()) - } - ps.onComplete() + } + } ?: emptyList() + // - API does not provide the Reward no reward, we need to add it first + val minPledge = data.project?.minPledge?.toDouble() ?: 1.0 + val modifiedRewards = rwList.filterNotNull().toMutableList() + modifiedRewards.add(0, RewardFactory.noReward().toBuilder().minimum(minPledge).build()) + ps.onNext(modifiedRewards.toList()) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } private fun getAddOnsFromProject(addOnsGr: GetProjectAddOnsQuery.AddOns): List { - return addOnsGr.nodes()?.map { node -> + return addOnsGr.nodes?.map { node -> val shippingRulesGr = - node.shippingRulesExpanded()?.nodes()?.map { it.fragments().shippingRule() } + node?.shippingRulesExpanded?.nodes?.map { requireNotNull(it?.shippingRule) } ?: emptyList() rewardTransformer( - node.fragments().reward(), - shippingRulesGr, - addOnItems = complexRewardItemsTransformer(node.items()?.fragments()?.rewardItems()) + requireNotNull(node?.reward), + shippingRulesExpanded = shippingRulesGr, + addOnItems = complexRewardItemsTransformer(node?.items?.rewardItems) ) }?.toList() ?: emptyList() } @@ -772,140 +749,126 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun getProjectAddOns(slug: String, locationId: Location): Observable> { return Observable.defer { val ps = PublishSubject.create>() - val query = GetProjectAddOnsQuery.builder() - .slug(slug) - .locationId(encodeRelayId(locationId)) - .build() - this.service.query(query) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } + val query = GetProjectAddOnsQuery( + slug = slug, + locationId = encodeRelayId(locationId) + ) - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { data -> - Observable.just(data.project()?.addOns()) - .filter { it?.nodes() != null } - .map> { addOnsList -> - addOnsList?.let { - getAddOnsFromProject( - it - ) - } ?: emptyList() - } - .subscribe { - ps.onNext(it) - }.dispose() - } - ps.onComplete() + this.service + .query(query) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } + response.data?.let { data -> + val addOns = getAddOnsFromProject(requireNotNull(data.project?.addOns)) + ps.onNext(addOns) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } override fun updateBacking(updateBackingData: UpdateBackingData): Observable { return Observable.defer { - val updateBackingMutation = UpdateBackingMutation.builder() - .backingId(encodeRelayId(updateBackingData.backing)) - .amount(updateBackingData.amount) - .locationId(updateBackingData.locationId) - .rewardIds(updateBackingData.rewardsIds?.let { list -> list.map { encodeRelayId(it) } }) - .apply { - updateBackingData.paymentSourceId?.let { this.paymentSourceId(it) } - updateBackingData.intentClientSecret?.let { this.intentClientSecret(it) } - } - .build() - + val mutation = UpdateBackingMutation( + backingId = encodeRelayId(updateBackingData.backing), + amount = if (updateBackingData.amount.isNotNull()) Optional.present(updateBackingData.amount) else Optional.absent(), + locationId = if (updateBackingData.locationId.isNotNull()) Optional.present(updateBackingData.locationId) else Optional.absent(), + rewardIds = + if (updateBackingData.rewardsIds.isNotNull()) Optional.present(updateBackingData.rewardsIds?.let { list -> list.map { encodeRelayId(it) } }) + else Optional.absent(), + paymentSourceId = if (updateBackingData.paymentSourceId.isNotNull()) Optional.present(updateBackingData.paymentSourceId) else Optional.absent(), + intentClientSecret = if (updateBackingData.intentClientSecret.isNotNull()) Optional.present(updateBackingData.intentClientSecret) else Optional.absent() + ) val ps = PublishSubject.create() - service.mutate(updateBackingMutation) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(java.lang.Exception(response.errors?.first()?.message)) - } else { - val checkoutPayload = response.data?.updateBacking()?.checkout() - val backing = Checkout.Backing.builder() - .clientSecret( - checkoutPayload?.backing()?.fragments()?.checkoutBacking() - ?.clientSecret() - ) - .requiresAction( - checkoutPayload?.backing()?.fragments()?.checkoutBacking() - ?.requiresAction() ?: false - ) - .build() + service + .mutation(mutation) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(java.lang.Exception(response.errors?.first()?.message)) + } else { + val checkoutPayload = response.data?.updateBacking?.checkout + val backing = Checkout.Backing.builder() + .clientSecret( + checkoutPayload?.backing?.checkoutBacking?.clientSecret + ) + .requiresAction( + checkoutPayload?.backing?.checkoutBacking?.requiresAction ?: false + ) + .build() - val checkout = Checkout.builder() - .id(decodeRelayId(checkoutPayload?.id())) - .backing(backing) - .build() - ps.onNext(checkout) - } - ps.onComplete() + val checkout = Checkout.builder() + .id(decodeRelayId(checkoutPayload?.id)) + .backing(backing) + .build() + ps.onNext(checkout) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } override fun createBacking(createBackingData: CreateBackingData): Observable { return Observable.defer { - val createBackingMutation = CreateBackingMutation.builder() - .projectId(encodeRelayId(createBackingData.project)) - .amount(createBackingData.amount) - .paymentType(PaymentTypes.CREDIT_CARD.rawValue()) - .paymentSourceId(createBackingData.paymentSourceId) - .setupIntentClientSecret(createBackingData.setupIntentClientSecret) - .locationId(createBackingData.locationId?.let { it }) - .rewardIds(createBackingData.rewardsIds?.let { list -> list.map { encodeRelayId(it) } }) - .refParam(createBackingData.refTag?.tag()) - .build() - val ps = PublishSubject.create() + val mutation = CreateBackingMutation( + projectId = encodeRelayId(createBackingData.project), + amount = createBackingData.amount, + paymentType = PaymentTypes.CREDIT_CARD.rawValue, + paymentSourceId = if (createBackingData.paymentSourceId.isNotNull()) Optional.present(createBackingData.paymentSourceId) else Optional.absent(), + setupIntentClientSecret = + if (createBackingData.setupIntentClientSecret.isNotNull()) Optional.present(createBackingData.setupIntentClientSecret) + else Optional.absent(), + locationId = if (createBackingData.locationId.isNotNull()) Optional.present(createBackingData.locationId) else Optional.absent(), + rewardIds = + if (createBackingData.rewardsIds.isNotNull()) Optional.present(createBackingData.rewardsIds?.let { list -> list.map { encodeRelayId(it) } }) + else Optional.absent(), + refParam = if (createBackingData.refTag?.tag().isNotNull()) Optional.present(createBackingData.refTag?.tag()) else Optional.absent() + ) - this.service.mutate(createBackingMutation) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(java.lang.Exception(response.errors?.first()?.message)) - } else { + this.service.mutation(mutation) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(java.lang.Exception(response.errors?.first()?.message)) + } else { - val checkoutPayload = response.data?.createBacking()?.checkout() + val checkoutPayload = response.data?.createBacking?.checkout - // TODO: Add new status field to backing model - val backing = Checkout.Backing.builder() - .clientSecret( - checkoutPayload?.backing()?.fragments()?.checkoutBacking() - ?.clientSecret() - ) - .requiresAction( - checkoutPayload?.backing()?.fragments()?.checkoutBacking() - ?.requiresAction() ?: false - ) - .build() + // TODO: Add new status field to backing model + val backing = Checkout.Backing.builder() + .clientSecret( + checkoutPayload?.backing?.checkoutBacking?.clientSecret + ) + .requiresAction( + checkoutPayload?.backing?.checkoutBacking + ?.requiresAction ?: false + ) + .build() - val checkout = Checkout.builder() - .id(decodeRelayId(checkoutPayload?.id())) - .backing(backing) - .build() - ps.onNext(checkout) - } - ps.onComplete() + val checkout = Checkout.builder() + .id(decodeRelayId(checkoutPayload?.id)) + .backing(backing) + .build() + ps.onNext(checkout) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -913,28 +876,28 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun triggerThirdPartyEvent(eventInput: TPEventInputData): Observable> { return Observable.defer { val ps = PublishSubject.create>() - - val mutation = getTriggerThirdPartyEventMutation(eventInput) - - service.mutate(mutation) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message ?: "")) - } - - response.data?.let { - val message = it.triggerThirdPartyEvent()?.message() ?: "" - val isSuccess = it.triggerThirdPartyEvent()?.success() ?: false - ps.onNext(Pair(isSuccess, message)) - } - ps.onComplete() - } - }) +// TODO: rewrite this query on the thirdPartyEvents.graphQL file, something is off here +// val mutation = getTriggerThirdPartyEventMutation(eventInput) +// +// service.mutate(mutation) +// .enqueue(object : ApolloCall.Callback() { +// override fun onFailure(exception: ApolloException) { +// ps.onError(exception) +// } +// +// override fun onResponse(response: Response) { +// if (response.hasErrors()) { +// ps.onError(Exception(response.errors?.first()?.message ?: "")) +// } +// +// response.data?.let { +// val message = it.triggerThirdPartyEvent()?.message() ?: "" +// val isSuccess = it.triggerThirdPartyEvent()?.success() ?: false +// ps.onNext(Pair(isSuccess, message)) +// } +// ps.onComplete() +// } +// }) return@defer ps } } @@ -945,27 +908,25 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient ): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - CreatePasswordMutation.builder() - .password(password) - .passwordConfirmation(confirmPassword) - .build() + val mutation = CreatePasswordMutation( + password = password, + passwordConfirmation = confirmPassword ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(java.lang.Exception(response.errors?.first()?.message)) } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(java.lang.Exception(response.errors?.first()?.message)) - } - response.data?.let { - ps.onNext(it) - } - ps.onComplete() + response.data?.let { + ps.onNext(it) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -973,32 +934,31 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun creatorDetails(slug: String): Observable { return Observable.defer { val ps = PublishSubject.create() - service.query( - ProjectCreatorDetailsQuery.builder() - .slug(slug) - .build() + + val query = ProjectCreatorDetailsQuery( + slug = slug ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.query( + query + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - - response.data?.project()?.creator()?.let { - ps.onNext( - CreatorDetails.builder() - .backingsCount(it.backingsCount()) - .launchedProjectsCount(it.launchedProjects()?.totalCount() ?: 1) - .build() - ) - ps.onComplete() - } + response.data?.project?.creator?.let { + ps.onNext( + CreatorDetails.builder() + .backingsCount(it.backingsCount) + .launchedProjectsCount(it.launchedProjects?.totalCount ?: 1) + .build() + ) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1006,34 +966,33 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun sendMessage(project: Project, recipient: User, body: String): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - SendMessageMutation.builder() - .projectId(encodeRelayId(project)) - .recipientId(encodeRelayId(recipient)) - .body(body) - .build() + val mutation = SendMessageMutation( + projectId = encodeRelayId(project), + recipientId = encodeRelayId(recipient), + body = body ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } - response.data?.let { - decodeRelayId( - response.data?.sendMessage()?.conversation()?.id() - )?.let { - ps.onNext(it) - } ?: ps.onError(Exception()) - } + service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } - ps.onComplete() + response.data?.let { + decodeRelayId( + response.data?.sendMessage?.conversation?.id + )?.let { + ps.onNext(it) + } ?: ps.onError(Exception()) } - }) + + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1041,28 +1000,26 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun cancelBacking(backing: Backing, note: String): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - CancelBackingMutation.builder() - .backingId(encodeRelayId(backing)) - .note(note) - .build() + val mutation = CancelBackingMutation( + backingId = encodeRelayId(backing), + note = Optional.present(note) ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onNext(Exception(response.errors?.first()?.message ?: "")) - } else { - val state = response.data?.cancelBacking()?.backing()?.status() - val success = state == BackingState.CANCELED - ps.onNext(success) - } - ps.onComplete() + service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onNext(Exception(response.errors?.first()?.message ?: "")) + } else { + val state = response.data?.cancelBacking?.backing?.status + val success = state == BackingState.canceled + ps.onNext(success) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1070,26 +1027,25 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun fetchCategory(categoryParam: String): Observable { return Observable.defer { val ps = PublishSubject.create() + val query = FetchCategoryQuery( + categoryParam = categoryParam + ) this.service.query( - FetchCategoryQuery.builder() - .categoryParam(categoryParam) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + query + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { val category = - categoryTransformer(response.data?.category()?.fragments()?.category()) + categoryTransformer(response.data?.category?.category) ps.onNext(category) } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } @@ -1097,70 +1053,68 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun getBacking(backingId: String): Observable { return Observable.defer { val ps = PublishSubject.create() - - this.service.query( - GetBackingQuery.builder() - .backingId(backingId).build() + val query = GetBackingQuery( + backingId = backingId ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } else { - response.data?.let { - it.backing()?.fragments()?.let { backingFragments -> - backingTransformer( - backingFragments.backing() - )?.let { backingObject -> - ps.onNext(backingObject) - } + this.service.query( + query + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } else { + response.data?.let { + it.backing?.let { backingFragments -> + backingTransformer( + backingFragments.backing + )?.let { backingObject -> + ps.onNext(backingObject) } } - ps.onComplete() } } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } override fun fetchCategories(): Observable> { return Observable.defer { + val query = GetRootCategoriesQuery() val ps = PublishSubject.create>() - this.service.query( - GetRootCategoriesQuery.builder() - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } - override fun onResponse(response: Response) { + service.query( + query + ).rxFlowable() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response: ApolloResponse -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { response.data?.let { responseData -> - val subCategories = responseData.rootCategories() - .flatMap { it.subcategories()?.nodes().orEmpty() } + val subCategories = responseData.rootCategories + .flatMap { it.subcategories?.nodes.orEmpty() } .map { - categoryTransformer(it.fragments().category()) + categoryTransformer(it?.category) } - val rootCategories = responseData.rootCategories() - .map { categoryTransformer(it.fragments().category()) } + val rootCategories = responseData.rootCategories + .map { categoryTransformer(it.category) } .toMutableList() .apply { addAll(subCategories) } ps.onNext(rootCategories) } - ps.onComplete() } + ps.onComplete() } - }) + .addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } @@ -1173,76 +1127,66 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient return Observable.defer { val ps = PublishSubject.create() - this.service.query( - GetProjectUpdatesQuery.builder() - .cursor(cursor) - .slug(slug) - .limit(limit) - .build() + val query = GetProjectUpdatesQuery( + cursor = Optional.present(cursor), + slug = slug, + limit = limit ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } - - override fun onResponse(response: Response) { + this.service.query( + query + ).rxFlowable() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } else { response.data?.let { data -> - Observable.just(data.project()) - .filter { it?.posts() != null } - .map { project -> - - val updates = project?.posts()?.edges()?.map { edge -> - updateTransformer( - edge?.node()?.fragments()?.post() - ).toBuilder() - .build() - } + val updates = data.project?.posts?.edges?.map { + updateTransformer(it?.node?.post) + } + val envelope = UpdatesGraphQlEnvelope.builder() + .updates(updates) + .totalCount(data.project?.posts?.totalCount ?: 0) + .pageInfoEnvelope( + createPageInfoObject( + data.project?.posts?.pageInfo?.pageInfo + ) + ) + .build() - UpdatesGraphQlEnvelope.builder() - .updates(updates) - .totalCount(project?.posts()?.totalCount() ?: 0) - .pageInfoEnvelope( - createPageInfoObject( - project?.posts()?.pageInfo()?.fragments() - ?.pageInfo() - ) - ) - .build() - } - .filter { it.isNotNull() } - .subscribe { - ps.onNext(it) - ps.onComplete() - } + ps.onNext(envelope) } } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } - private fun createPageInfoObject(pageFr: fragment.PageInfo?): PageInfoEnvelope { + private fun createPageInfoObject(pageFr: com.kickstarter.fragment.PageInfo?): PageInfoEnvelope { return PageInfoEnvelope.builder() - .endCursor(pageFr?.endCursor() ?: "") - .hasNextPage(pageFr?.hasNextPage() ?: false) - .hasPreviousPage(pageFr?.hasPreviousPage() ?: false) - .startCursor(pageFr?.startCursor() ?: "") + .endCursor(pageFr?.endCursor ?: "") + .hasNextPage(pageFr?.hasNextPage ?: false) + .hasPreviousPage(pageFr?.hasPreviousPage ?: false) + .startCursor(pageFr?.startCursor ?: "") .build() } override fun getComment(commentableId: String): Observable { return Observable.defer { val ps = PublishSubject.create() + val query = GetCommentQuery( + commentableId = commentableId + ) this.service.query( - GetCommentQuery.builder() - .commentableId(commentableId) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + query + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { @@ -1252,15 +1196,13 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient } } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } private fun mapGetCommentQueryResponseToComment(responseData: GetCommentQuery.Data): Comment { - val commentFragment = - (responseData.commentable() as? GetCommentQuery.AsComment)?.fragments()?.comment() + val commentFragment = responseData.commentable?.onComment?.comment return commentTransformer(commentFragment) } @@ -1272,54 +1214,49 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient return Observable.defer { val ps = PublishSubject.create() - this.service.query( - GetProjectUpdateCommentsQuery.builder() - .cursor(cursor.ifEmpty { null }) - .id(updateId) - .limit(limit) - .build() + val query = GetProjectUpdateCommentsQuery( + cursor = if (cursor.isPresent()) Optional.present(cursor) else Optional.absent(), + id = updateId, + limit = limit ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } else { - response.data?.let { data -> - data.post()?.fragments()?.freeformPost()?.comments() - ?.let { graphComments -> - val comments = graphComments.edges()?.map { edge -> - commentTransformer(edge?.node()?.fragments()?.comment()) - .toBuilder() - .cursor(edge?.cursor()) - .build() - } - - val envelope = CommentEnvelope.builder() - .comments(comments) - .commentableId(data.post()?.id() ?: "") - .totalCount( - data.post()?.fragments()?.freeformPost()?.comments() - ?.totalCount() ?: 0 - ) - .pageInfoEnvelope( - createPageInfoObject( - data.post()?.fragments()?.freeformPost() - ?.comments() - ?.pageInfo()?.fragments()?.pageInfo() - ) - ) + this.service.query( + query + ).rxFlowable() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } else { + response.data?.let { data -> + data.post?.freeformPost?.comments + ?.let { graphComments -> + val comments = graphComments.edges?.map { edge -> + commentTransformer(edge?.node?.comment) + .toBuilder() + .cursor(edge?.cursor) .build() - ps.onNext(envelope) } - } + + val envelope = CommentEnvelope.builder() + .comments(comments) + .commentableId(data.post?.id ?: "") + .totalCount( + data.post?.freeformPost?.comments?.totalCount ?: 0 + ) + .pageInfoEnvelope( + createPageInfoObject( + data.post?.freeformPost?.comments?.pageInfo?.pageInfo + ) + ) + .build() + ps.onNext(envelope) + } } - ps.onComplete() } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } @@ -1331,50 +1268,47 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient ): Observable { return Observable.defer { val ps = PublishSubject.create() - this.service.query( - GetProjectCommentsQuery.builder() - .cursor(cursor.ifEmpty { null }) - .slug(slug) - .limit(limit) - .build() + val query = GetProjectCommentsQuery( + cursor = if (cursor.isPresent()) Optional.present(cursor) else Optional.absent(), + slug = slug, + limit = limit ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } else { - response.data?.let { data -> - data.project()?.comments()?.let { graphComments -> - val comments = graphComments.edges()?.map { edge -> - commentTransformer( - edge?.node()?.fragments()?.comment() - ).toBuilder() - .cursor(edge?.cursor()) - .build() - } - - val envelope = CommentEnvelope.builder() - .commentableId(data.project()?.id()) - .comments(comments) - .totalCount(data.project()?.comments()?.totalCount() ?: 0) - .pageInfoEnvelope( - createPageInfoObject( - data.project()?.comments()?.pageInfo()?.fragments() - ?.pageInfo() - ) - ) + this.service.query( + query + ).rxFlowable() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } else { + response.data?.let { data -> + data.project?.comments?.let { graphComments -> + val comments = graphComments.edges?.map { edge -> + commentTransformer( + edge?.node?.comment + ).toBuilder() + .cursor(edge?.cursor) .build() - ps.onNext(envelope) } + + val envelope = CommentEnvelope.builder() + .commentableId(data.project?.id) + .comments(comments) + .totalCount(data.project?.comments?.totalCount ?: 0) + .pageInfoEnvelope( + createPageInfoObject( + data.project?.comments?.pageInfo?.pageInfo + ) + ) + .build() + ps.onNext(envelope) } } - ps.onComplete() } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } @@ -1386,44 +1320,38 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient ): Observable { return Observable.defer { val ps = PublishSubject.create() + val query = GetRepliesForCommentQuery( + commentableId = encodeRelayId(comment), + cursor = if (cursor.isNullOrBlank()) Optional.absent() else Optional.present(cursor), + pageSize = Optional.present(pageSize), + ) this.service.query( - GetRepliesForCommentQuery.builder() - .commentableId(encodeRelayId(comment)) - .cursor(cursor) - .pageSize(pageSize) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + query + ).rxFlowable() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { response.data?.let { responseData -> - Observable.just(createCommentEnvelop(responseData)) - .subscribe { - ps.onNext(it) - ps.onComplete() - } + ps.onNext(createCommentEnvelop(responseData)) } } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } private fun createCommentEnvelop(responseData: GetRepliesForCommentQuery.Data): CommentEnvelope { - val replies = - (responseData.commentable() as? GetRepliesForCommentQuery.AsComment)?.replies() - val listOfComments = replies?.nodes()?.map { commentFragment -> - commentTransformer(commentFragment.fragments().comment()) + val replies = responseData.commentable?.onComment?.replies + val listOfComments = replies?.nodes?.map { commentFragment -> + commentTransformer(commentFragment?.comment) } ?: emptyList() - val totalCount = replies?.totalCount() ?: 0 - val pageInfo = createPageInfoObject(replies?.pageInfo()?.fragments()?.pageInfo()) + val totalCount = replies?.totalCount ?: 0 + val pageInfo = createPageInfoObject(replies?.pageInfo?.pageInfo) return CommentEnvelope.builder() .comments(listOfComments) @@ -1435,37 +1363,34 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun createComment(comment: PostCommentData): Observable { return Observable.defer { val ps = PublishSubject.create() - this.service.mutate( - CreateCommentMutation.builder() - .parentId(comment.parent?.let { encodeRelayId(it) }) - .commentableId(comment.commentableId) - .clientMutationId(comment.clientMutationId) - .body(comment.body) - .build() + val mutation = CreateCommentMutation( + parentId = if (comment.parent?.id().isNotNull()) Optional.present(comment.parent?.let { encodeRelayId(it) }) else Optional.absent(), + commentableId = comment.commentableId, + clientMutationId = Optional.present(comment.clientMutationId), + body = comment.body ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(java.lang.Exception(response.errors?.first()?.message)) - } else { - /* make a copy of what you posted. just in case - * we want to update the list without doing - * a full refresh. - */ - ps.onNext( - commentTransformer( - response.data?.createComment()?.comment()?.fragments() - ?.comment() - ) + this.service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(java.lang.Exception(response.errors?.first()?.message)) + } else { + /* make a copy of what you posted. just in case + * we want to update the list without doing + * a full refresh. + */ + ps.onNext( + commentTransformer( + response.data?.createComment?.comment?.comment ) - } - ps.onComplete() + ) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1473,31 +1398,31 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun erroredBackings(): Observable> { return Observable.defer { val ps = PublishSubject.create>() - this.service.query(ErroredBackingsQuery.builder().build()) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } else { - val erroredBackings = response.data?.me()?.backings()?.nodes()?.map { - val project = ErroredBacking.Project.builder() - .finalCollectionDate(it.project()?.finalCollectionDate()) - .name(it.project()?.name()) - .slug(it.project()?.slug()) - .build() - return@map ErroredBacking.builder() - .project(project) - .build() - } ?: listOf() - ps.onNext(erroredBackings) - } - ps.onComplete() + val query = ErroredBackingsQuery() + this.service + .query(query) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } else { + val erroredBackings = response.data?.me?.backings?.nodes?.map { + val project = ErroredBacking.Project.builder() + .finalCollectionDate(it?.project?.finalCollectionDate) + .name(it?.project?.name) + .slug(it?.project?.slug) + .build() + return@map ErroredBacking.builder() + .project(project) + .build() + } ?: listOf() + ps.onNext(erroredBackings) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1505,26 +1430,23 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient override fun clearUnseenActivity(): Observable { return Observable.defer { val ps = PublishSubject.create() - service.mutate( - ClearUserUnseenActivityMutation.builder() - .build() - ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + val mutation = ClearUserUnseenActivityMutation() + service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(java.lang.Exception(response.errors?.first()?.message)) } + response.data?.clearUserUnseenActivity?.activityIndicatorCount?.let { + ps.onNext(it) + } ?: ps.onError(Exception()) - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(java.lang.Exception(response.errors?.first()?.message)) - } - response.data?.clearUserUnseenActivity()?.activityIndicatorCount()?.let { - ps.onNext(it) - } ?: ps.onError(Exception()) - - ps.onComplete() - } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1533,33 +1455,31 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient return Observable.defer { val ps = PublishSubject.create() - this.service.query( - GetProjectBackingQuery.builder() - .slug(slug) - .build() + val query = GetProjectBackingQuery( + slug = slug ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) - } - - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message)) - } else { - response.data?.let { data -> - data.project()?.backing()?.fragments()?.backing()?.let { backingObj -> - val backing = backingTransformer( - backingObj - ) - - ps.onNext(backing) - ps.onComplete() + this.service.query( + query + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message)) + } else { + response.data?.let { data -> + data.project?.backing?.backing?.let { backingObj -> + backingTransformer( + backingObj + )?.let { + ps.onNext(it) } } } } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } @@ -1568,35 +1488,35 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient return Observable.defer { val ps = PublishSubject.create() - this.service.mutate( - CreateCheckoutMutation.builder() - .projectId(encodeRelayId(createCheckoutData.project)) - .amount(createCheckoutData.amount) - .rewardIds( - createCheckoutData.rewardsIds?.let { list -> - list.map { encodeRelayId(it) } - } - ) - .locationId(createCheckoutData.locationId) - .refParam(createCheckoutData.refTag?.tag()) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + val mutation = CreateCheckoutMutation( + projectId = encodeRelayId(createCheckoutData.project), + amount = createCheckoutData.amount, + rewardIds = Optional.present( + createCheckoutData.rewardsIds?.let { list -> + list.map { encodeRelayId(it) } + } + ), + locationId = if (createCheckoutData.locationId.isNotNull()) Optional.present(createCheckoutData.locationId) else Optional.absent(), + refParam = if (createCheckoutData.refTag?.tag().isNotNull()) Optional.present(createCheckoutData.refTag?.tag()) else Optional.absent() + ) + this.service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { response.data?.let { data -> - data.createCheckout()?.checkout()?.let { checkoutObj -> - val backingId = decodeRelayId(checkoutObj.id()) ?: 0L + data.createCheckout?.checkout?.let { checkoutObj -> + val backingId = decodeRelayId(checkoutObj.id) ?: 0L val backing = Backing.builder().id(backingId).build() - decodeRelayId(checkoutObj.id())?.let { id -> + decodeRelayId(checkoutObj.id)?.let { id -> val checkout = CheckoutPayment( id, - checkoutObj.paymentUrl(), + checkoutObj.paymentUrl, backing = backing ) ps.onNext(checkout) @@ -1605,8 +1525,7 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient } } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } @@ -1617,30 +1536,29 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient val checkoutId = createPaymentIntentInput.checkoutId val backingId = encodeRelayId(createPaymentIntentInput.backing) - this.service.mutate( - CreatePaymentIntentMutation.builder() - .projectId(encodeRelayId(createPaymentIntentInput.project)) - .amount(createPaymentIntentInput.amount) - .paymentIntentContext(StripeIntentContextTypes.POST_CAMPAIGN_CHECKOUT) - .checkoutId(Base64Utils.encodeUrlSafe(("Checkout-$checkoutId").toByteArray(Charset.defaultCharset()))) - .backingId(backingId) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + val mutation = CreatePaymentIntentMutation( + projectId = encodeRelayId(createPaymentIntentInput.project), + amount = createPaymentIntentInput.amount, + paymentIntentContext = Optional.present(StripeIntentContextTypes.POST_CAMPAIGN_CHECKOUT), + checkoutId = (Base64Utils.encodeUrlSafe(("Checkout-$checkoutId").toByteArray(Charset.defaultCharset()))), + backingId = Optional.present(backingId) + ) + this.service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { - response.data?.createPaymentIntent()?.clientSecret()?.let { + response.data?.createPaymentIntent?.clientSecret?.let { ps.onNext(it) } ?: ps.onError(Exception("Client Secret was Null")) } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps } } @@ -1652,33 +1570,31 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient ): Observable { return Observable.defer { val ps = PublishSubject.create() - + val query = ValidateCheckoutQuery( + checkoutId = checkoutId, + paymentIntentClientSecret = paymentIntentClientSecret, + paymentSourceId = paymentSourceId + ) this.service.query( - ValidateCheckoutQuery.builder() - .checkoutId(checkoutId) - .paymentIntentClientSecret(paymentIntentClientSecret) - .paymentSourceId(paymentSourceId) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + query + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { response.data?.let { data -> val validation = PaymentValidationResponse( - data.checkout()?.isValidForOnSessionCheckout?.valid() ?: false, - data.checkout()?.isValidForOnSessionCheckout?.messages() ?: listOf() + data.checkout?.isValidForOnSessionCheckout?.valid ?: false, + data.checkout?.isValidForOnSessionCheckout?.messages ?: listOf() ) ps.onNext(validation) } - ps.onComplete() } - } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1692,31 +1608,30 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient return Observable.defer { val ps = PublishSubject.create>() - this.service.mutate( - CompleteOnSessionCheckoutMutation.builder() - .checkoutId(Base64Utils.encodeUrlSafe(("Checkout-$checkoutId").toByteArray(Charset.defaultCharset()))) - .paymentIntentClientSecret(paymentIntentClientSecret) - .paymentSourceId(paymentSourceId) - .paymentSourceReusable(paymentSourceReusable) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + val mutation = CompleteOnSessionCheckoutMutation( + checkoutId = Base64Utils.encodeUrlSafe(("Checkout-$checkoutId").toByteArray(Charset.defaultCharset())), + paymentIntentClientSecret = paymentIntentClientSecret, + paymentSourceId = if (paymentSourceId.isNotNull()) Optional.present(paymentSourceId) else Optional.absent(), + paymentSourceReusable = Optional.present(paymentSourceReusable) + ) + this.service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message)) } else { - response.data?.completeOnSessionCheckout()?.checkout()?.id()?.let { checkoutId -> - response.data?.completeOnSessionCheckout()?.checkout()?.backing()?.requiresAction()?.let { requiresAction -> + response.data?.completeOnSessionCheckout?.checkout?.id?.let { checkoutId -> + response.data?.completeOnSessionCheckout?.checkout?.backing?.requiresAction?.let { requiresAction -> ps.onNext(Pair(checkoutId, requiresAction)) } } ?: ps.onError(Exception("Checkout ID was null")) } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps } } @@ -1726,25 +1641,22 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient val ps = PublishSubject.create() val mutation = getCreateAttributionEventMutation(eventInput, gson) - - service.mutate(mutation) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.mutation(mutation) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message ?: "")) } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message ?: "")) - } - - response.data?.let { - val isSuccess = it.createAttributionEvent()?.successful() ?: false - ps.onNext(isSuccess) - } - ps.onComplete() + response.data?.let { + val isSuccess = it.createAttributionEvent?.successful ?: false + ps.onNext(isSuccess) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } @@ -1755,59 +1667,56 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient val mutation = getCreateOrUpdateBackingAddressMutation(eventInput) - service.mutate(mutation) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + service.mutation(mutation) + .rxSingle() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message ?: "")) } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message ?: "")) - } - - response.data?.let { - val isSuccess = it.createOrUpdateBackingAddress()?.success() ?: false - ps.onNext(isSuccess) - } - ps.onComplete() + response.data?.let { + val isSuccess = it.createOrUpdateBackingAddress?.success ?: false + ps.onNext(isSuccess) } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps } } + // TODO: was part of initial discovery for PledgeRedemption ML2 on mobile, not is use currently, as is happens on a webview override fun completeOrder(orderInput: CompleteOrderInput): Observable { return Observable.defer { val ps = PublishSubject.create() - this.service.mutate( - CompleteOrderMutation.builder() - .projectId(orderInput.projectId) - .stripePaymentMethodId(orderInput.stripePaymentMethodId) - .paymentSourceId(orderInput.paymentSourceId) - .paymentSourceReusable(orderInput.paymentSourceReusable) - .build() - ).enqueue(object : ApolloCall.Callback() { - override fun onFailure(exception: ApolloException) { - ps.onError(exception) + val mutation = CompleteOrderMutation( + orderId = "", + stripePaymentMethodId = Optional.present(orderInput.stripePaymentMethodId), + paymentSourceReusable = Optional.present(orderInput.paymentSourceReusable) + ) + this.service.mutation( + mutation + ).rxSingle() + .doOnError { throwable -> + ps.onError(throwable) } - - override fun onResponse(response: Response) { + .subscribe { response -> if (response.hasErrors()) { ps.onError(Exception(response.errors?.first()?.message ?: "")) } - response.data?.completeOrder()?.let { + response.data?.completeOrder?.let { val payload = CompleteOrderPayload( - status = it.status(), - clientSecret = it?.clientSecret() ?: "" + status = it.status, + clientSecret = it.clientSecret ?: "" ) ps.onNext(payload) } ps.onComplete() - } - }) + }.addToDisposable(disposables) return@defer ps } @@ -1819,31 +1728,24 @@ class KSApolloClientV2(val service: ApolloClient, val gson: Gson) : ApolloClient this.service.query( getPledgedProjectsOverviewQuery(inputData) - ) - .enqueue(object : ApolloCall.Callback() { - override fun onFailure(e: ApolloException) { - ps.onError(e) + ).rxFlowable() + .doOnError { throwable -> + ps.onError(throwable) + } + .subscribe { response -> + if (response.hasErrors()) { + ps.onError(Exception(response.errors?.first()?.message ?: "")) } - override fun onResponse(response: Response) { - if (response.hasErrors()) { - ps.onError(Exception(response.errors?.first()?.message ?: "")) - } - - response.data?.let { data -> - Observable.just(data.pledgeProjectsOverview()) - .filter { it.pledges() != null } - .map { pledgeProjectsOverview -> - pledgedProjectsOverviewEnvelopeTransformer(pledgeProjectsOverview) - } - .filter { it.isNotNull() } - .subscribe { - ps.onNext(it) - ps.onComplete() - } + response.data?.let { data -> + data.pledgeProjectsOverview?.let { + pledgedProjectsOverviewEnvelopeTransformer(it) + }?.let { + ps.onNext(it) } } - }) + ps.onComplete() + }.addToDisposable(disposables) return@defer ps }.subscribeOn(Schedulers.io()) } diff --git a/app/src/main/java/com/kickstarter/services/mutations/SavePaymentMethodData.kt b/app/src/main/java/com/kickstarter/services/mutations/SavePaymentMethodData.kt index f6cf110ce6..afa38325d0 100644 --- a/app/src/main/java/com/kickstarter/services/mutations/SavePaymentMethodData.kt +++ b/app/src/main/java/com/kickstarter/services/mutations/SavePaymentMethodData.kt @@ -1,5 +1,5 @@ package com.kickstarter.services.mutations -import type.PaymentTypes +import com.kickstarter.type.PaymentTypes data class SavePaymentMethodData(val paymentType: PaymentTypes = PaymentTypes.CREDIT_CARD, val stripeToken: String? = null, val stripeCardId: String? = null, val reusable: Boolean, val intentClientSecret: String? = null) diff --git a/app/src/main/java/com/kickstarter/services/transformers/GraphQLTransformers.kt b/app/src/main/java/com/kickstarter/services/transformers/GraphQLTransformers.kt index 130a65dd9a..c96b784908 100644 --- a/app/src/main/java/com/kickstarter/services/transformers/GraphQLTransformers.kt +++ b/app/src/main/java/com/kickstarter/services/transformers/GraphQLTransformers.kt @@ -1,20 +1,25 @@ package com.kickstarter.services.transformers -import CreateAttributionEventMutation -import CreateOrUpdateBackingAddressMutation -import PledgedProjectsOverviewQuery -import TriggerThirdPartyEventMutation -import UserPrivacyQuery +import com.apollographql.apollo3.api.Optional import com.google.android.gms.common.util.Base64Utils import com.google.gson.Gson +import com.kickstarter.CreateAttributionEventMutation +import com.kickstarter.CreateOrUpdateBackingAddressMutation +import com.kickstarter.FetchProjectRewardsQuery +import com.kickstarter.PledgedProjectsOverviewQuery +import com.kickstarter.UserPrivacyQuery import com.kickstarter.features.pledgedprojectsoverview.data.Flag import com.kickstarter.features.pledgedprojectsoverview.data.PPOCard import com.kickstarter.features.pledgedprojectsoverview.data.PledgeTierType import com.kickstarter.features.pledgedprojectsoverview.data.PledgedProjectsOverviewEnvelope import com.kickstarter.features.pledgedprojectsoverview.data.PledgedProjectsOverviewQueryData import com.kickstarter.features.pledgedprojectsoverview.ui.PPOCardViewType +import com.kickstarter.fragment.FullProject +import com.kickstarter.fragment.PpoCard.DeliveryAddress +import com.kickstarter.fragment.ProjectCard import com.kickstarter.libs.Permission import com.kickstarter.libs.utils.extensions.isNotNull +import com.kickstarter.libs.utils.extensions.isPresent import com.kickstarter.libs.utils.extensions.negate import com.kickstarter.mock.factories.RewardFactory import com.kickstarter.models.AiDisclosure @@ -43,22 +48,16 @@ import com.kickstarter.services.apiresponses.ShippingRulesEnvelope import com.kickstarter.services.apiresponses.commentresponse.PageInfoEnvelope import com.kickstarter.services.mutations.CreateAttributionEventData import com.kickstarter.services.mutations.CreateOrUpdateBackingAddressData -import com.kickstarter.viewmodels.usecases.TPEventInputData -import fragment.FullProject -import fragment.PpoCard.DeliveryAddress -import fragment.ProjectCard +import com.kickstarter.type.CollaboratorPermission +import com.kickstarter.type.CreateAttributionEventInput +import com.kickstarter.type.CreateOrUpdateBackingAddressInput +import com.kickstarter.type.CreditCardPaymentType +import com.kickstarter.type.CurrencyCode +import com.kickstarter.type.Feature +import com.kickstarter.type.RewardType +import com.kickstarter.type.ShippingPreference import org.jetbrains.annotations.Nullable import org.joda.time.DateTime -import type.AppDataInput -import type.CollaboratorPermission -import type.CreateAttributionEventInput -import type.CreateOrUpdateBackingAddressInput -import type.CreditCardPaymentType -import type.CurrencyCode -import type.RewardType -import type.ShippingPreference -import type.ThirdPartyEventItemInput -import type.TriggerThirdPartyEventInput import java.nio.charset.Charset import kotlin.math.absoluteValue @@ -91,11 +90,11 @@ fun encodeRelayId(relay: T): String { * @param fragment.Faq faq * @return ProjectFaq */ -fun projectFaqTransformer(faq: fragment.Faq): ProjectFaq { - val id = decodeRelayId(faq.id()) ?: -1 - val answer = faq.answer() - val createdAt = faq.createdAt() - val question = faq.question() +fun projectFaqTransformer(faq: com.kickstarter.fragment.Faq): ProjectFaq { + val id = decodeRelayId(faq.id) ?: -1 + val answer = faq.answer + val createdAt = faq.createdAt + val question = faq.question return ProjectFaq.builder() .id(id) @@ -110,10 +109,10 @@ fun projectFaqTransformer(faq: fragment.Faq): ProjectFaq { * @param fragment.EnvironmentalCommitment * @return EnvironmentalCommitment */ -fun environmentalCommitmentTransformer(envCommit: fragment.EnvironmentalCommitment): EnvironmentalCommitment { - val id = decodeRelayId(envCommit.id()) ?: -1 - val category = envCommit.commitmentCategory().name - val description = envCommit.description() +fun environmentalCommitmentTransformer(envCommit: com.kickstarter.fragment.EnvironmentalCommitment): EnvironmentalCommitment { + val id = decodeRelayId(envCommit.id) ?: -1 + val category = envCommit.commitmentCategory.name + val description = envCommit.description return EnvironmentalCommitment.builder() .id(id = id) @@ -128,48 +127,47 @@ fun environmentalCommitmentTransformer(envCommit: fragment.EnvironmentalCommitme * @return Reward */ fun rewardTransformer( - rewardGr: fragment.Reward, - shippingRulesExpanded: List = emptyList(), + rewardGr: com.kickstarter.fragment.Reward, + shippingRulesExpanded: List = emptyList(), simpleShippingRules: List = emptyList(), allowedAddons: Boolean = false, rewardItems: List = emptyList(), addOnItems: List = emptyList() ): Reward { - val amount = rewardGr.amount().fragments().amount().amount()?.toDouble() ?: 0.0 - val latePledgeAmount = rewardGr.latePledgeAmount().fragments().amount().amount()?.toDouble() ?: 0.0 - val pledgeAmount = rewardGr.pledgeAmount().fragments().amount().amount()?.toDouble() ?: 0.0 + val amount = rewardGr.amount.amount.amount?.toDouble() ?: 0.0 + val latePledgeAmount = rewardGr.latePledgeAmount.amount.amount?.toDouble() ?: 0.0 + val pledgeAmount = rewardGr.pledgeAmount.amount.amount?.toDouble() ?: 0.0 val convertedAmount = - rewardGr.convertedAmount().fragments().amount().amount()?.toDouble() ?: 0.0 - val desc = rewardGr.description() - val title = rewardGr.name() - val estimatedDelivery = rewardGr.estimatedDeliveryOn()?.let { DateTime(it) } - val remaining = rewardGr.remainingQuantity() - val endsAt = rewardGr.endsAt()?.let { DateTime(it) } - val startsAt = rewardGr.startsAt()?.let { DateTime(it) } - val rewardId = decodeRelayId(rewardGr.id()) ?: -1 - val available = rewardGr.available() - val isAddOn = rewardGr.rewardType() == RewardType.ADDON - val isReward = rewardGr.rewardType() == RewardType.BASE - val backersCount = rewardGr.backersCount() - val shippingPreference = when (rewardGr.shippingPreference()) { - ShippingPreference.NONE -> Reward.ShippingPreference.NONE - ShippingPreference.RESTRICTED -> Reward.ShippingPreference.RESTRICTED - ShippingPreference.UNRESTRICTED -> Reward.ShippingPreference.UNRESTRICTED - ShippingPreference.LOCAL -> Reward.ShippingPreference.LOCAL + rewardGr.convertedAmount.amount.amount?.toDouble() ?: 0.0 + val desc = rewardGr.description + val title = rewardGr.name + val estimatedDelivery = rewardGr.estimatedDeliveryOn?.let { DateTime(it) } + val remaining = rewardGr.remainingQuantity + val endsAt = rewardGr.endsAt?.let { DateTime(it) } + val startsAt = rewardGr.startsAt?.let { DateTime(it) } + val rewardId = decodeRelayId(rewardGr.id) ?: -1 + val available = rewardGr.available + val isAddOn = rewardGr.rewardType == RewardType.addon + val isReward = rewardGr.rewardType == RewardType.base + val backersCount = rewardGr.backersCount + val shippingPreference = when (rewardGr.shippingPreference) { + ShippingPreference.none -> Reward.ShippingPreference.NONE + ShippingPreference.restricted -> Reward.ShippingPreference.RESTRICTED + ShippingPreference.unrestricted -> Reward.ShippingPreference.UNRESTRICTED + ShippingPreference.local -> Reward.ShippingPreference.LOCAL else -> Reward.ShippingPreference.UNKNOWN } - val limit = if (isAddOn) chooseLimit(rewardGr.limit(), rewardGr.limitPerBacker()) - else rewardGr.limit() + val limit = if (isAddOn) chooseLimit(rewardGr.limit, rewardGr.limitPerBacker) + else rewardGr.limit val shippingRules = shippingRulesExpanded.takeIf { it.isNotEmpty() }?.map { shippingRuleTransformer(it) } ?: simpleShippingRules.takeIf { it.isNotEmpty() }?.map { return@map simpleShippingRuleTransformer(it) - } - ?: emptyList() + } ?: emptyList() - val localReceiptLocation = locationTransformer(rewardGr.localReceiptLocation()?.fragments()?.location()) + val localReceiptLocation = locationTransformer(rewardGr.localReceiptLocation?.location) return Reward.builder() .title(title) @@ -199,9 +197,9 @@ fun rewardTransformer( } fun simpleShippingRuleTransformer(simpleShippingRules: FetchProjectRewardsQuery.SimpleShippingRulesExpanded): ShippingRule { - val id = decodeRelayId(simpleShippingRules.locationId()) ?: -1 - val country = simpleShippingRules.country() ?: "" - val displayName = simpleShippingRules.locationName() + val id = decodeRelayId(simpleShippingRules.locationId) ?: -1 + val country = simpleShippingRules.country ?: "" + val displayName = simpleShippingRules.locationName val location = Location.builder() .id(id) @@ -209,9 +207,9 @@ fun simpleShippingRuleTransformer(simpleShippingRules: FetchProjectRewardsQuery. .displayableName(displayName) .name(displayName) .build() - val cost = simpleShippingRules.cost()?.toDoubleOrNull() ?: 0.0 - val estimatedMin = simpleShippingRules.estimatedMin()?.toDoubleOrNull() ?: 0.0 - val estimatedMax = simpleShippingRules.estimatedMax()?.toDoubleOrNull() ?: 0.0 + val cost = simpleShippingRules.cost?.toDoubleOrNull() ?: 0.0 + val estimatedMin = simpleShippingRules.estimatedMin?.toDoubleOrNull() ?: 0.0 + val estimatedMax = simpleShippingRules.estimatedMax?.toDoubleOrNull() ?: 0.0 return ShippingRule.builder() .id(id) @@ -245,12 +243,12 @@ private fun chooseLimit(limitReward: Int?, limitPerBacker: Int?): Int { * @param fragment.Reward.items * @return List */ -fun complexRewardItemsTransformer(items: fragment.RewardItems?): List { - val rewardItems = items?.edges()?.map { edge -> - val quantity = edge.quantity() - val description = edge.node()?.name() - val id = decodeRelayId(edge.node()?.id()) ?: -1 - val name = edge.node()?.name() ?: "" +fun complexRewardItemsTransformer(items: com.kickstarter.fragment.RewardItems?): List { + val rewardItems = items?.edges?.map { edge -> + val quantity = edge?.quantity + val description = edge?.node?.name + val id = decodeRelayId(edge?.node?.id) ?: -1 + val name = edge?.node?.name ?: "" val item = Item.builder() .name(name) @@ -275,61 +273,63 @@ fun complexRewardItemsTransformer(items: fragment.RewardItems?): List() - val fxRate = projectFragment?.fxRate()?.toFloat() - val deadline = projectFragment?.deadlineAt() - val goal = projectFragment?.goal()?.fragments()?.amount()?.amount()?.toDouble() ?: 0.0 - val id = decodeRelayId(projectFragment?.id()) ?: -1 - val isBacking = projectFragment?.backing()?.fragments()?.backing()?.let { true } ?: false + val fxRate = projectFragment?.fxRate?.toFloat() + val deadline = projectFragment?.deadlineAt + val goal = projectFragment?.goal?.amount?.amount?.toDouble() ?: 0.0 + val id = decodeRelayId(projectFragment?.id) ?: -1 + val isBacking = projectFragment?.backing?.backing?.let { true } ?: false val isStarred = projectFragment?.isWatched ?: false - val launchedAt = projectFragment?.launchedAt() - val location = locationTransformer(projectFragment?.location()?.fragments()?.location()) - val name = projectFragment?.name() - val permission = projectFragment?.collaboratorPermissions()?.map { + val launchedAt = projectFragment?.launchedAt + val location = locationTransformer(projectFragment?.location?.location) + val name = projectFragment?.name + val permission = projectFragment?.collaboratorPermissions?.map { when (it) { - CollaboratorPermission.COMMENT -> Permission.COMMENT - CollaboratorPermission.EDIT_FAQ -> Permission.EDIT_FAQ - CollaboratorPermission.EDIT_PROJECT -> Permission.EDIT_PROJECT - CollaboratorPermission.FULFILLMENT -> Permission.FULFILLMENT - CollaboratorPermission.POST -> Permission.POST - CollaboratorPermission.VIEW_PLEDGES -> Permission.VIEW_PLEDGES + CollaboratorPermission.comment -> Permission.COMMENT + CollaboratorPermission.edit_faq -> Permission.EDIT_FAQ + CollaboratorPermission.edit_project -> Permission.EDIT_PROJECT + CollaboratorPermission.fulfillment -> Permission.FULFILLMENT + CollaboratorPermission.post -> Permission.POST + CollaboratorPermission.view_pledges -> Permission.VIEW_PLEDGES else -> Permission.UNKNOWN } } - val pledged = projectFragment?.pledged()?.fragments()?.amount()?.amount()?.toDouble() ?: 0.0 - val photoUrl = projectFragment?.fragments()?.full()?.image()?.url() + val pledged = projectFragment?.pledged?.amount?.amount?.toDouble() ?: 0.0 + val photoUrl = projectFragment?.full?.image?.url val photo = getPhoto(photoUrl) val tags = mutableListOf() - projectFragment?.fragments()?.tagsCreative()?.tags()?.map { tags.add(it.id()) } - projectFragment?.fragments()?.tagsDiscovery()?.tags()?.map { tags.add(it.id()) } + projectFragment?.tagsCreative?.tags?.map { tags.add(it?.id ?: "") } + projectFragment?.tagsDiscovery?.tags?.map { tags.add(it?.id ?: "") } - val minPledge = projectFragment?.minPledge()?.toDouble() ?: 1.0 + val minPledge = projectFragment?.minPledge?.toDouble() ?: 1.0 val rewards = - projectFragment?.rewards()?.nodes()?.map { - rewardTransformer( - it.fragments().reward() - ) + projectFragment?.rewards?.nodes?.map { + it?.reward?.let { rw -> + rewardTransformer( + rewardGr = rw + ) + } } // - GraphQL does not provide the Reward no reward, we need to add it first @@ -337,43 +337,43 @@ fun projectTransformer(projectFragment: FullProject?): Project { modifiedRewards?.add(0, RewardFactory.noReward().toBuilder().minimum(minPledge).build()) modifiedRewards?.toList() - val slug = projectFragment?.slug() + val slug = projectFragment?.slug val staffPicked = projectFragment?.isProjectWeLove ?: false - val state = projectFragment?.state()?.name?.lowercase() - val stateChangedAt = projectFragment?.stateChangedAt() - val staticUSDRate = projectFragment?.usdExchangeRate()?.toFloat() ?: 1f - val usdExchangeRate = projectFragment?.usdExchangeRate()?.toFloat() ?: 1f - val updatedAt = projectFragment?.posts()?.fragments()?.updates()?.nodes()?.let { - if (it.isNotEmpty()) return@let it.first()?.updatedAt() + val state = projectFragment?.state?.name?.lowercase() + val stateChangedAt = projectFragment?.stateChangedAt + val staticUSDRate = projectFragment?.usdExchangeRate?.toFloat() ?: 1f + val usdExchangeRate = projectFragment?.usdExchangeRate?.toFloat() ?: 1f + val updatedAt = projectFragment?.posts?.updates?.nodes?.let { + if (it.isNotEmpty()) return@let it.first()?.updatedAt else null } - val updatesCount = projectFragment?.posts()?.fragments()?.updates()?.totalCount() - val url = projectFragment?.url() + val updatesCount = projectFragment?.posts?.updates?.totalCount + val url = projectFragment?.url val urlsWeb = Web.builder() .project(url) .rewards("$url/rewards") .build() val urls = Urls.builder().web(urlsWeb).build() - val video = if (projectFragment?.video()?.fragments()?.video() != null) { - videoTransformer(projectFragment.video()?.fragments()?.video()) + val video = if (projectFragment?.video?.video != null) { + videoTransformer(projectFragment.video?.video) } else null val displayPrelaunch = (projectFragment?.isLaunched ?: false).negate() - val faqs = projectFragment?.faqs()?.nodes()?.map { node -> - projectFaqTransformer(node.fragments().faq()) + val faqs = projectFragment?.faqs?.nodes?.map { node -> + node?.let { projectFaqTransformer(it.faq) } } ?: emptyList() - val eCommitment = projectFragment?.environmentalCommitments()?.map { - environmentalCommitmentTransformer(it.fragments().environmentalCommitment()) + val eCommitment = projectFragment?.environmentalCommitments?.map { + it?.let { it1 -> environmentalCommitmentTransformer(it1.environmentalCommitment) } } ?: emptyList() - val aiDisclosure = projectFragment?.aiDisclosure()?.fragments()?.aiDisclosure()?.let { + val aiDisclosure = projectFragment?.aiDisclosure?.aiDisclosure?.let { aiDisclosureTransformer(it) - } ?: null - val risks = projectFragment?.risks() - val story = projectFragment?.story()?.toString() ?: "" - val userCanComment = projectFragment?.canComment() ?: false - val isFlagged = projectFragment?.flagging()?.kind()?.let { true } ?: false - val watchesCount = projectFragment?.watchesCount() ?: 0 + } + val risks = projectFragment?.risks + val story = projectFragment?.story?.toString() ?: "" + val userCanComment = projectFragment?.canComment ?: false + val isFlagged = projectFragment?.flagging?.kind?.let { true } ?: false + val watchesCount = projectFragment?.watchesCount ?: 0 val isInPostCampaignPledgingPhase = projectFragment?.isInPostCampaignPledgingPhase ?: false - val postCampaignPledgingEnabled = projectFragment?.postCampaignPledgingEnabled() ?: false + val postCampaignPledgingEnabled = projectFragment?.postCampaignPledgingEnabled ?: false return Project.builder() .availableCardTypes(availableCards.map { it.name }) @@ -410,7 +410,7 @@ fun projectTransformer(projectFragment: FullProject?): Project { .sendMetaCapiEvents(sendMetaCapiEvents) .sendThirdPartyEvents(sendThirdPartyEvents) .tags(tags) - .rewards(modifiedRewards) + .rewards(modifiedRewards?.filterNotNull()?.toList()) .slug(slug) .staffPick(staffPicked) .state(state) @@ -423,8 +423,8 @@ fun projectTransformer(projectFragment: FullProject?): Project { .updatesCount(updatesCount) .urls(urls) .video(video) - .projectFaqs(faqs) - .envCommitments(eCommitment) + .projectFaqs(faqs.filterNotNull()) + .envCommitments(eCommitment.filterNotNull()) .aiDisclosure(aiDisclosure) .risks(risks) .story(story) @@ -440,15 +440,15 @@ fun projectTransformer(projectFragment: FullProject?): Project { * @param FullProject.AiDisclosure aiDisclosureGraph * @return AiDisclosure */ -fun aiDisclosureTransformer(aiDisclosureGraph: fragment.AiDisclosure): AiDisclosure { +fun aiDisclosureTransformer(aiDisclosureGraph: com.kickstarter.fragment.AiDisclosure): AiDisclosure { return AiDisclosure.builder() - .id(decodeRelayId(aiDisclosureGraph.id()) ?: -1) - .fundingForAiAttribution(aiDisclosureGraph.fundingForAiAttribution()) - .fundingForAiConsent(aiDisclosureGraph.fundingForAiConsent()) - .fundingForAiOption(aiDisclosureGraph.fundingForAiOption()) - .generatedByAiConsent(aiDisclosureGraph.generatedByAiConsent()) - .generatedByAiDetails(aiDisclosureGraph.generatedByAiDetails()) - .otherAiDetails(aiDisclosureGraph.otherAiDetails()) + .id(decodeRelayId(aiDisclosureGraph.id) ?: -1) + .fundingForAiAttribution(aiDisclosureGraph.fundingForAiAttribution) + .fundingForAiConsent(aiDisclosureGraph.fundingForAiConsent) + .fundingForAiOption(aiDisclosureGraph.fundingForAiOption) + .generatedByAiConsent(aiDisclosureGraph.generatedByAiConsent) + .generatedByAiDetails(aiDisclosureGraph.generatedByAiDetails) + .otherAiDetails(aiDisclosureGraph.otherAiDetails) .build() } @@ -457,15 +457,15 @@ fun aiDisclosureTransformer(aiDisclosureGraph: fragment.AiDisclosure): AiDisclos * @param fragment.Category category * @return Project */ -fun categoryTransformer(categoryFragment: fragment.Category?): Category { - val analyticsName = categoryFragment?.analyticsName() ?: "" - val name = categoryFragment?.name() ?: "" - val id = decodeRelayId(categoryFragment?.id()) ?: -1 - val slug = categoryFragment?.slug() - val parentId = decodeRelayId(categoryFragment?.parentCategory()?.id()) ?: 0 - val parentName = categoryFragment?.parentCategory()?.name() - val parentSlug = categoryFragment?.parentCategory()?.slug() - val parentAnalyticName = categoryFragment?.parentCategory()?.analyticsName() ?: "" +fun categoryTransformer(categoryFragment: com.kickstarter.fragment.Category?): Category { + val analyticsName = categoryFragment?.analyticsName ?: "" + val name = categoryFragment?.name ?: "" + val id = decodeRelayId(categoryFragment?.id) ?: -1 + val slug = categoryFragment?.slug + val parentId = decodeRelayId(categoryFragment?.parentCategory?.id) ?: 0 + val parentName = categoryFragment?.parentCategory?.name + val parentSlug = categoryFragment?.parentCategory?.slug + val parentAnalyticName = categoryFragment?.parentCategory?.analyticsName ?: "" val parentCategory = if (parentId > 0) { Category.builder() @@ -492,13 +492,13 @@ fun categoryTransformer(categoryFragment: fragment.Category?): Category { * @param fragment.User user * @return User */ -fun userTransformer(user: fragment.User?): User { - val id = decodeRelayId(user?.id()) ?: -1 - val name = user?.name() +fun userTransformer(user: com.kickstarter.fragment.User?): User { + val id = decodeRelayId(user?.id) ?: -1 + val name = user?.name val avatar = Avatar.builder() - .medium(user?.imageUrl()) + .medium(user?.imageUrl) .build() - val chosenCurrency = user?.chosenCurrency() ?: CurrencyCode.USD.rawValue() + val chosenCurrency = user?.chosenCurrency ?: CurrencyCode.USD.rawValue return User.builder() .id(id) @@ -514,17 +514,17 @@ fun userTransformer(user: fragment.User?): User { * @return UserPrivacy */ fun userPrivacyTransformer(userPrivacy: UserPrivacyQuery.Me): UserPrivacy { - val defaultCurrency = CurrencyCode.USD.rawValue() + val defaultCurrency = CurrencyCode.USD.rawValue return UserPrivacy( - name = userPrivacy.name(), - email = userPrivacy.email() ?: "", - hasPassword = userPrivacy.hasPassword() ?: false, + name = userPrivacy.name, + email = userPrivacy.email ?: "", + hasPassword = userPrivacy.hasPassword ?: false, isCreator = userPrivacy.isCreator ?: false, isDeliverable = userPrivacy.isDeliverable ?: false, isEmailVerified = userPrivacy.isEmailVerified ?: false, - chosenCurrency = userPrivacy.chosenCurrency() ?: defaultCurrency, - enabledFeatures = userPrivacy.enabledFeatures().map { - it.rawValue() + chosenCurrency = userPrivacy.chosenCurrency ?: defaultCurrency, + enabledFeatures = userPrivacy.enabledFeatures.map { feature: Feature -> + feature.rawValue } ) } @@ -535,37 +535,37 @@ fun userPrivacyTransformer(userPrivacy: UserPrivacyQuery.Me): UserPrivacy { * @return Project */ fun projectTransformer(projectFragment: ProjectCard?): Project { - val backersCount = projectFragment?.backersCount() ?: 0 - val blurb = projectFragment?.description() ?: "" - val category = if (projectFragment?.category()?.fragments()?.category() != null) { - categoryTransformer(projectFragment.category()?.fragments()?.category()) + val backersCount = projectFragment?.backersCount ?: 0 + val blurb = projectFragment?.description ?: "" + val category = if (projectFragment?.category?.category != null) { + categoryTransformer(projectFragment.category.category) } else null - val country = projectFragment?.country()?.fragments()?.country()?.name() ?: "" - val createdAt = projectFragment?.createdAt() - val creator = userTransformer(projectFragment?.creator()?.fragments()?.user()) - val currencySymbol = projectFragment?.goal()?.fragments()?.amount()?.symbol() - val prelaunchActivated = projectFragment?.prelaunchActivated() - val featuredAt = projectFragment?.projectOfTheDayAt() + val country = projectFragment?.country?.country?.name ?: "" + val createdAt = projectFragment?.createdAt + val creator = userTransformer(projectFragment?.creator?.user) + val currencySymbol = projectFragment?.goal?.amount?.symbol + val prelaunchActivated = projectFragment?.prelaunchActivated + val featuredAt = projectFragment?.projectOfTheDayAt val friends = - projectFragment?.friends()?.nodes()?.map { userTransformer(it.fragments().user()) } + projectFragment?.friends?.nodes?.map { userTransformer(it?.user) } ?: emptyList() - val pledged = projectFragment?.pledged()?.fragments()?.amount()?.amount()?.toDouble() ?: 0.0 - val fxRate = projectFragment?.fxRate()?.toFloat() - val deadline = projectFragment?.deadlineAt() - val goal = projectFragment?.goal()?.fragments()?.amount()?.amount()?.toDouble() ?: 0.0 - val id = decodeRelayId(projectFragment?.id()) ?: -1 - val isBacking = projectFragment?.backing()?.id()?.let { true } ?: false + val pledged = projectFragment?.pledged?.amount?.amount?.toDouble() ?: 0.0 + val fxRate = projectFragment?.fxRate?.toFloat() + val deadline = projectFragment?.deadlineAt + val goal = projectFragment?.goal?.amount?.amount?.toDouble() ?: 0.0 + val id = decodeRelayId(projectFragment?.id) ?: -1 + val isBacking = projectFragment?.backing?.id?.let { true } ?: false val isStarred = projectFragment?.isWatched ?: false - val launchedAt = projectFragment?.launchedAt() - val location = locationTransformer(projectFragment?.location()?.fragments()?.location()) - val name = projectFragment?.name() - val photoUrl = projectFragment?.fragments()?.full()?.image()?.url() + val launchedAt = projectFragment?.launchedAt + val location = locationTransformer(projectFragment?.location?.location) + val name = projectFragment?.name + val photoUrl = projectFragment?.full?.image?.url val photo = getPhoto(photoUrl) - val slug = projectFragment?.slug() + val slug = projectFragment?.slug val staffPicked = projectFragment?.isProjectWeLove ?: false - val state = projectFragment?.state()?.name?.lowercase() - val stateChangedAt = projectFragment?.stateChangedAt() - val url = projectFragment?.url() + val state = projectFragment?.state?.name?.lowercase() + val stateChangedAt = projectFragment?.stateChangedAt + val url = projectFragment?.url val urlsWeb = Web.builder() .project(url) .rewards("$url/rewards") @@ -620,35 +620,35 @@ private fun getPhoto(photoUrl: @Nullable String?): Photo? { return photo } -fun updateTransformer(post: fragment.Post?): Update { - val id = decodeRelayId(post?.id()) ?: -1 +fun updateTransformer(post: com.kickstarter.fragment.Post?): Update { + val id = decodeRelayId(post?.id) ?: -1 val author = User.builder() - .id(decodeRelayId(post?.author()?.fragments()?.user()?.id()) ?: -1) - .name(post?.author()?.fragments()?.user()?.name() ?: "") + .id(decodeRelayId(post?.author?.user?.id) ?: -1) + .name(post?.author?.user?.name ?: "") .avatar( Avatar.builder() - .medium(post?.author()?.fragments()?.user()?.imageUrl()) + .medium(post?.author?.user?.imageUrl) .build() ) .build() - val projectId = decodeRelayId(post?.project()?.id()) ?: -1 + val projectId = decodeRelayId(post?.project?.id) ?: -1 - val title = post?.title() ?: "" + val title = post?.title ?: "" - val publishedAt = post?.publishedAt() - val updatedAt = post?.updatedAt() - val sequence = post?.number() ?: 0 + val publishedAt = post?.publishedAt + val updatedAt = post?.updatedAt + val sequence = post?.number ?: 0 - val url = post?.project()?.url() + val url = post?.project?.url val urlsWeb = Update.Urls.Web.builder() .update("$url/posts/$id") .build() val updateUrl = Update.Urls.builder().web(urlsWeb).build() - val updateFreeformPost = post?.fragments()?.updateFreeformPost() - val commentsCount = updateFreeformPost?.commentsCount() - val body = updateFreeformPost?.body() as? String + val updateFreeformPost = post?.updateFreeformPost + val commentsCount = updateFreeformPost?.commentsCount + val body = updateFreeformPost?.body as? String return Update.builder() .body(body) @@ -656,7 +656,7 @@ fun updateTransformer(post: fragment.Post?): Update { .hasLiked(post?.isLiked) .id(id) .isPublic(post?.isPublic) - .likesCount(post?.likesCount()) + .likesCount(post?.likesCount) .projectId(projectId) .publishedAt(publishedAt) .sequence(sequence) @@ -668,29 +668,29 @@ fun updateTransformer(post: fragment.Post?): Update { .build() } -fun commentTransformer(commentFr: fragment.Comment?): Comment { - val badges: List = commentFr?.authorBadges()?.map { badge -> - badge?.rawValue() ?: "" +fun commentTransformer(commentFr: com.kickstarter.fragment.Comment?): Comment { + val badges: List = commentFr?.authorBadges?.map { badge -> + badge?.rawValue ?: "" } ?: emptyList() val author = User.builder() - .id(decodeRelayId(commentFr?.author()?.fragments()?.user()?.id()) ?: -1) - .name(commentFr?.author()?.fragments()?.user()?.name() ?: "") + .id(decodeRelayId(commentFr?.author?.user?.id) ?: -1) + .name(commentFr?.author?.user?.name ?: "") .avatar( Avatar.builder() - .medium(commentFr?.author()?.fragments()?.user()?.imageUrl()) + .medium(commentFr?.author?.user?.imageUrl) .build() ) .build() - val id = decodeRelayId(commentFr?.id()) ?: -1 - val repliesCount = commentFr?.replies()?.totalCount() ?: 0 - val body = commentFr?.body() ?: "" - val createdAt = commentFr?.createdAt() - val deleted = commentFr?.deleted() ?: false - val hasFlaggings = commentFr?.hasFlaggings() ?: false - val sustained = commentFr?.sustained() ?: false - val authorCanceled = commentFr?.authorCanceledPledge() ?: false - val parentId = decodeRelayId(commentFr?.parentId()) + val id = decodeRelayId(commentFr?.id) ?: -1 + val repliesCount = commentFr?.replies?.totalCount ?: 0 + val body = commentFr?.body ?: "" + val createdAt = commentFr?.createdAt + val deleted = commentFr?.deleted ?: false + val hasFlaggings = commentFr?.hasFlaggings ?: false + val sustained = commentFr?.sustained ?: false + val authorCanceled = commentFr?.authorCanceledPledge ?: false + val parentId = decodeRelayId(commentFr?.parentId) return Comment.builder() .id(id) @@ -713,60 +713,60 @@ fun commentTransformer(commentFr: fragment.Comment?): Comment { * @param fragment.Baking projectFragment * @return Backing */ -fun backingTransformer(backingGr: fragment.Backing?): Backing { - val payment = backingGr?.paymentSource()?.fragments()?.payment()?.let { payment -> +fun backingTransformer(backingGr: com.kickstarter.fragment.Backing?): Backing { + val payment = backingGr?.paymentSource?.payment?.let { payment -> PaymentSource.builder() - .state(payment.state().toString()) - .type(payment.type().rawValue()) - .paymentType(CreditCardPaymentType.CREDIT_CARD.rawValue()) - .id(payment.id()) - .expirationDate(payment.expirationDate()) - .lastFour(payment.lastFour()) + .state(payment.state.toString()) + .type(payment.type.rawValue) + .paymentType(CreditCardPaymentType.CREDIT_CARD.rawValue) + .id(payment.id) + .expirationDate(payment.expirationDate) + .lastFour(payment.lastFour) .build() } - val addOns = backingGr?.addOns()?.let { + val addOns = backingGr?.addOns?.let { return@let getAddOnsList(it) } - val id = decodeRelayId(backingGr?.id())?.let { it } ?: 0 + val id = decodeRelayId(backingGr?.id)?.let { it } ?: 0 - val location = backingGr?.location()?.fragments()?.location() - val locationId = decodeRelayId(location?.id()) - val projectId = decodeRelayId(backingGr?.project()?.fragments()?.project()?.id()) ?: -1 - val shippingAmount = backingGr?.shippingAmount()?.fragments() - val items = backingGr?.reward()?.items() - val reward = backingGr?.reward()?.fragments()?.reward()?.let { reward -> + val location = backingGr?.location?.location + val locationId = decodeRelayId(location?.id) + val projectId = decodeRelayId(backingGr?.project?.project?.id) ?: -1 + val shippingAmount = backingGr?.shippingAmount + val items = backingGr?.reward?.items + val reward = backingGr?.reward?.reward?.let { reward -> return@let rewardTransformer( reward, - allowedAddons = reward.allowedAddons().isNotNull(), - rewardItems = complexRewardItemsTransformer(items?.fragments()?.rewardItems()) + allowedAddons = reward.allowedAddons.isNotNull(), + rewardItems = complexRewardItemsTransformer(items?.rewardItems) ) } - val backerData = backingGr?.backer()?.fragments()?.user() - val nameBacker = backerData?.let { it.name() } ?: "" - val backerId = decodeRelayId(backerData?.id()) ?: -1 + val backerData = backingGr?.backer?.user + val nameBacker = backerData?.let { it.name } ?: "" + val backerId = decodeRelayId(backerData?.id) ?: -1 val avatar = Avatar.builder() - .medium(backerData?.imageUrl()) + .medium(backerData?.imageUrl) .build() - val completedByBacker = backingGr?.backerCompleted() ?: false + val completedByBacker = backingGr?.backerCompleted ?: false val backer = User.builder() .id(backerId) .name(nameBacker) .avatar(avatar) .build() - val status = backingGr?.status()?.rawValue() ?: "" + val status = backingGr?.status?.rawValue ?: "" val isPostCampaign = backingGr?.isPostCampaign ?: false return Backing.builder() - .amount(backingGr?.amount()?.fragments()?.amount()?.amount()?.toDouble() ?: 0.0) - .bonusAmount(backingGr?.bonusAmount()?.fragments()?.amount()?.amount()?.toDouble() ?: 0.0) + .amount(backingGr?.amount?.amount?.amount?.toDouble() ?: 0.0) + .bonusAmount(backingGr?.bonusAmount?.amount?.amount?.toDouble() ?: 0.0) .paymentSource(payment) .backerId(backerId) - .backerUrl(backerData?.imageUrl()) + .backerUrl(backerData?.imageUrl) .backerName(nameBacker) .backer(backer) .id(id) @@ -774,13 +774,13 @@ fun backingTransformer(backingGr: fragment.Backing?): Backing { .addOns(addOns) .rewardId(reward?.id()) .locationId(locationId) - .locationName(location?.displayableName()) - .pledgedAt(backingGr?.pledgedOn()) + .locationName(location?.displayableName) + .pledgedAt(backingGr?.pledgedOn) .projectId(projectId) - .sequence(backingGr?.sequence()?.toLong() ?: 0) - .shippingAmount(shippingAmount?.amount()?.amount()?.toFloat() ?: 0f) + .sequence(backingGr?.sequence?.toLong() ?: 0) + .shippingAmount(shippingAmount?.amount?.amount?.toFloat() ?: 0f) .status(status) - .cancelable(backingGr?.cancelable() ?: false) + .cancelable(backingGr?.cancelable ?: false) .completedByBacker(completedByBacker) .isPostCampaign(isPostCampaign) .build() @@ -790,16 +790,17 @@ fun backingTransformer(backingGr: fragment.Backing?): Backing { * For addOns we receive this kind of data structure :[D, D, D, D, D, C, E, E] * and we need to transform it in : D(5),C(1),E(2) */ -fun getAddOnsList(addOns: fragment.Backing.AddOns): List { - val rewardsList = addOns.nodes()?.map { node -> - rewardTransformer(node.fragments().reward()) +fun getAddOnsList(addOns: com.kickstarter.fragment.Backing.AddOns): List { + val rewardsList = addOns.nodes?.mapNotNull { node -> + node?.let { rewardTransformer(it.reward) } } val mapHolder = mutableMapOf() rewardsList?.forEach { - val q = mapHolder[it.id()]?.quantity() ?: 0 - mapHolder[it.id()] = it.toBuilder().quantity(q + 1).build() + val rwId = it.id() + val q = mapHolder[rwId]?.quantity() ?: 0 + mapHolder[rwId] = it.toBuilder().quantity(q + 1).build() } return mapHolder.values.toList() @@ -810,11 +811,11 @@ fun getAddOnsList(addOns: fragment.Backing.AddOns): List { * @param fragment.Video video * @return Project */ -fun videoTransformer(video: fragment.Video?): Video { - val frame = video?.previewImageUrl() - val base = video?.videoSources()?.base()?.src() - val high = video?.videoSources()?.high()?.src() - val hls = video?.videoSources()?.hls()?.src() +fun videoTransformer(video: com.kickstarter.fragment.Video?): Video { + val frame = video?.previewImageUrl + val base = video?.videoSources?.base?.src + val high = video?.videoSources?.high?.src + val hls = video?.videoSources?.hls?.src return Video.builder() .base(base) @@ -829,13 +830,13 @@ fun videoTransformer(video: fragment.Video?): Video { * @param fragment.ShippingRule * @return ShippingRule */ -fun shippingRuleTransformer(rule: fragment.ShippingRule): ShippingRule { - val cost = rule.cost()?.fragments()?.amount()?.amount()?.toDoubleOrNull() ?: 0.0 - val location = rule.location()?.let { - locationTransformer(it.fragments().location()) +fun shippingRuleTransformer(rule: com.kickstarter.fragment.ShippingRule): ShippingRule { + val cost = rule.cost?.amount?.amount?.toDoubleOrNull() ?: 0.0 + val location = rule.location?.let { + locationTransformer(it.location) } - val estimatedMin = rule.estimatedMin()?.amount()?.toDoubleOrNull() ?: 0.0 - val estimatedMax = rule.estimatedMax()?.amount()?.toDoubleOrNull() ?: 0.0 + val estimatedMin = rule.estimatedMin?.amount?.toDoubleOrNull() ?: 0.0 + val estimatedMax = rule.estimatedMax?.amount?.toDoubleOrNull() ?: 0.0 return ShippingRule.builder() .cost(cost) @@ -850,11 +851,11 @@ fun shippingRuleTransformer(rule: fragment.ShippingRule): ShippingRule { * @param fragment.Location * @return Location */ -fun locationTransformer(locationGR: fragment.Location?): Location { - val id = decodeRelayId(locationGR?.id()) ?: -1 - val country = locationGR?.country() ?: "" - val displayName = locationGR?.displayableName() - val name = locationGR?.name() +fun locationTransformer(locationGR: com.kickstarter.fragment.Location?): Location { + val id = decodeRelayId(locationGR?.id) ?: -1 + val country = locationGR?.country ?: "" + val displayName = locationGR?.displayableName + val name = locationGR?.name return Location.builder() .id(id) @@ -864,10 +865,10 @@ fun locationTransformer(locationGR: fragment.Location?): Location { .build() } -fun shippingRulesListTransformer(shippingRulesExpanded: List): ShippingRulesEnvelope { - val shippingRulesList: List = shippingRulesExpanded?.mapNotNull { shippingRule -> +fun shippingRulesListTransformer(shippingRulesExpanded: List): ShippingRulesEnvelope { + val shippingRulesList: List = shippingRulesExpanded.map { shippingRule -> shippingRuleTransformer(shippingRule) - } ?: emptyList() + } return ShippingRulesEnvelope .builder() @@ -879,40 +880,40 @@ fun shippingRulesListTransformer(shippingRulesExpanded: List = eventInput.items - .map { - ThirdPartyEventItemInput.builder() - .itemId(it.itemId) - .itemName(it.itemName) - .price(it.price) - .build() - } - - val graphInput = - TriggerThirdPartyEventInput.builder() - .userId(eventInput.userId) - .eventName(eventInput.eventName) - .deviceId(eventInput.deviceId) - .firebaseScreen(eventInput.firebaseScreen) - .firebasePreviousScreen(eventInput.firebasePreviousScreen) - .projectId(eventInput.projectId) - .pledgeAmount(eventInput.pledgeAmount) - .shipping(eventInput.shipping) - .appData(graphAppData) - .items(items) - .transactionId(eventInput.transactionId) - .build() - - return TriggerThirdPartyEventMutation.builder().triggerThirdPartyEventInput(graphInput) - .build() -} +// fun getTriggerThirdPartyEventMutation(eventInput: TPEventInputData): TriggerThirdPartyEventMutation { +// val graphAppData = AppDataInput.builder() +// .advertiserTrackingEnabled(eventInput.appData.iOSConsent) +// .applicationTrackingEnabled(eventInput.appData.androidConsent) +// .extinfo(eventInput.appData.extInfo) +// .build() +// +// val items: List = eventInput.items +// .map { +// ThirdPartyEventItemInput.builder() +// .itemId(it.itemId) +// .itemName(it.itemName) +// .price(it.price) +// .build() +// } +// +// val graphInput = +// TriggerThirdPartyEventInput.builder() +// .userId(eventInput.userId) +// .eventName(eventInput.eventName) +// .deviceId(eventInput.deviceId) +// .firebaseScreen(eventInput.firebaseScreen) +// .firebasePreviousScreen(eventInput.firebasePreviousScreen) +// .projectId(eventInput.projectId) +// .pledgeAmount(eventInput.pledgeAmount) +// .shipping(eventInput.shipping) +// .appData(graphAppData) +// .items(items) +// .transactionId(eventInput.transactionId) +// .build() +// +// return TriggerThirdPartyEventMutation.builder().triggerThirdPartyEventInput(graphInput) +// .build() +// } /** * From KS dataModel CreateAttributionEventData, transform it into @@ -923,74 +924,70 @@ fun getCreateAttributionEventMutation(eventInput: CreateAttributionEventData, gs // Use gson to convert map -> JSON type to match mutation val eventPropertiesJson = gson.toJson(eventInput.eventProperties) - val graphInput = - CreateAttributionEventInput.builder() - .eventName(eventInput.eventName) - .eventProperties(eventPropertiesJson) - .projectId(eventInput.projectId) - .build() - - return CreateAttributionEventMutation.builder().input(graphInput) - .build() + val input = CreateAttributionEventInput( + eventName = eventInput.eventName, + eventProperties = if (eventPropertiesJson.isPresent()) Optional.present(eventPropertiesJson) else Optional.absent(), + projectId = if (eventInput.projectId.isNullOrBlank()) Optional.absent() else Optional.present(eventInput.projectId) + ) + return CreateAttributionEventMutation(input = input) } fun getCreateOrUpdateBackingAddressMutation(eventInput: CreateOrUpdateBackingAddressData): CreateOrUpdateBackingAddressMutation { - val graphInput = - CreateOrUpdateBackingAddressInput.builder() - .addressId(eventInput.addressID) - .backingId(eventInput.backingID) - .build() - return CreateOrUpdateBackingAddressMutation.builder().input(graphInput).build() + val graphInput = CreateOrUpdateBackingAddressInput( + addressId = eventInput.addressID, + backingId = eventInput.backingID + ) + return CreateOrUpdateBackingAddressMutation(input = graphInput) } fun getPledgedProjectsOverviewQuery(queryInput: PledgedProjectsOverviewQueryData): PledgedProjectsOverviewQuery { - return PledgedProjectsOverviewQuery.builder() - .after(queryInput.after) - .before(queryInput.before) - .first(queryInput.first) - .last(queryInput.last) - .build() + return PledgedProjectsOverviewQuery( + after = Optional.present(queryInput.after), + before = Optional.present(queryInput.before), + first = Optional.present(queryInput.first), + last = Optional.present(queryInput.last) + ) } fun pledgedProjectsOverviewEnvelopeTransformer(ppoResponse: PledgedProjectsOverviewQuery.PledgeProjectsOverview): PledgedProjectsOverviewEnvelope { val ppoCards = - ppoResponse.pledges()?.edges()?.map { - val ppoBackingData = it.node()?.backing()?.fragments()?.ppoCard() - val flags = it.node()?.flags()?.map { flag -> - Flag.builder().message(flag.message()).icon(flag.icon()).type(flag.type()).build() + ppoResponse.pledges?.edges?.mapNotNull { + val ppoBackingData = it?.node?.backing?.ppoCard + val flags = it?.node?.flags?.map { flag -> + Flag.builder().message(flag.message).icon(flag.icon).type(flag.type).build() } PPOCard.builder() - .backingId(ppoBackingData?.id()) - .backingDetailsUrl(ppoBackingData?.backingDetailsPageRoute()) - .clientSecret(ppoBackingData?.clientSecret()) - .amount(ppoBackingData?.amount()?.fragments()?.amount()?.amount()) - .currencyCode(ppoBackingData?.amount()?.fragments()?.amount()?.currency()) - .currencySymbol(ppoBackingData?.amount()?.fragments()?.amount()?.symbol()) - .projectName(ppoBackingData?.project()?.name()) - .projectId(ppoBackingData?.project()?.id()) - .projectSlug(ppoBackingData?.project()?.slug()) - .imageUrl(ppoBackingData?.project()?.fragments()?.full()?.image()?.url()) - .creatorName(ppoBackingData?.project()?.creator()?.name()) - .creatorID(ppoBackingData?.project()?.creator()?.id()) - .viewType(getTierType(it.node()?.tierType())) - .surveyID(ppoBackingData?.project()?.backerSurvey()?.id()) + .backingId(ppoBackingData?.id) + .backingDetailsUrl(ppoBackingData?.backingDetailsPageRoute) + .clientSecret(ppoBackingData?.clientSecret) + .amount(ppoBackingData?.amount?.amount?.amount) + .currencyCode(ppoBackingData?.amount?.amount?.currency) + .currencySymbol(ppoBackingData?.amount?.amount?.symbol) + .projectName(ppoBackingData?.project?.name) + .projectId(ppoBackingData?.project?.id) + .projectSlug(ppoBackingData?.project?.slug) + .imageUrl(ppoBackingData?.project?.full?.image?.url) + .creatorName(ppoBackingData?.project?.creator?.name) + .creatorID(ppoBackingData?.project?.creator?.id) + .viewType(getTierType(it?.node?.tierType)) + .surveyID(ppoBackingData?.project?.backerSurvey?.id) .flags(flags) - .deliveryAddress(getDeliveryAddress(ppoBackingData?.deliveryAddress())) + .deliveryAddress(getDeliveryAddress(ppoBackingData?.deliveryAddress)) .build() } - val pageInfoEnvelope = ppoResponse.pledges()?.pageInfo().let { + val pageInfoEnvelope = ppoResponse.pledges?.pageInfo.let { PageInfoEnvelope.builder() - .hasNextPage(it?.hasNextPage() ?: false) - .endCursor(it?.endCursor() ?: "") - .hasPreviousPage(it?.hasPreviousPage() ?: false) - .startCursor(it?.startCursor() ?: "") + .hasNextPage(it?.hasNextPage ?: false) + .endCursor(it?.endCursor ?: "") + .hasPreviousPage(it?.hasPreviousPage ?: false) + .startCursor(it?.startCursor ?: "") .build() } return PledgedProjectsOverviewEnvelope.builder() - .totalCount(ppoResponse.pledges()?.totalCount()) + .totalCount(ppoResponse.pledges?.totalCount) .pledges(ppoCards) .pageInfoEnvelope(pageInfoEnvelope) .build() @@ -999,14 +996,14 @@ fun pledgedProjectsOverviewEnvelopeTransformer(ppoResponse: PledgedProjectsOverv fun getDeliveryAddress(deliveryAddress: DeliveryAddress?): com.kickstarter.features.pledgedprojectsoverview.data.DeliveryAddress? { deliveryAddress?.let { address -> return com.kickstarter.features.pledgedprojectsoverview.data.DeliveryAddress.builder() - .addressId(address.id()) - .addressLine1(address.addressLine1()) - .addressLine2(address.addressLine2()) - .city(address.city()) - .region(address.region()) - .postalCode(address.postalCode()) - .phoneNumber(address.phoneNumber()) - .recipientName(address.recipientName()) + .addressId(address.id) + .addressLine1(address.addressLine1) + .addressLine2(address.addressLine2) + .city(address.city) + .region(address.region) + .postalCode(address.postalCode) + .phoneNumber(address.phoneNumber) + .recipientName(address.recipientName) .build() } ?: return null } diff --git a/app/src/main/java/com/kickstarter/ui/activities/AccountActivity.kt b/app/src/main/java/com/kickstarter/ui/activities/AccountActivity.kt index 3c7666e553..4032bcd61c 100644 --- a/app/src/main/java/com/kickstarter/ui/activities/AccountActivity.kt +++ b/app/src/main/java/com/kickstarter/ui/activities/AccountActivity.kt @@ -15,13 +15,13 @@ import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.libs.utils.extensions.getEnvironment import com.kickstarter.libs.utils.extensions.getPaymentMethodsIntent +import com.kickstarter.type.CurrencyCode import com.kickstarter.ui.extensions.setUpConnectivityStatusCheck import com.kickstarter.ui.extensions.showSnackbar import com.kickstarter.utils.WindowInsetsUtil import com.kickstarter.viewmodels.AccountViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable -import type.CurrencyCode class AccountActivity : AppCompatActivity() { @@ -199,7 +199,7 @@ class AccountActivity : AppCompatActivity() { CurrencyCode.SEK -> getString(R.string.Currency_SEK) CurrencyCode.SGD -> getString(R.string.Currency_SGD) CurrencyCode.USD -> getString(R.string.Currency_USD) - else -> currency.rawValue() + else -> currency.rawValue } } @@ -210,11 +210,11 @@ class AccountActivity : AppCompatActivity() { .setTitle(getString(R.string.Change_currency)) .setMessage(getString(R.string.Project_goal_and_pledge)) .setNegativeButton(R.string.Cancel) { _, _ -> - setSpinnerSelection(currentCurrencySelection!!.rawValue()) + setSpinnerSelection(currentCurrencySelection!!.rawValue) } .setPositiveButton(R.string.Yes_change_currency) { _, _ -> this.viewModel.inputs.onSelectedCurrency(newCurrencySelection!!) - setSpinnerSelection(newCurrencySelection!!.rawValue()) + setSpinnerSelection(newCurrencySelection!!.rawValue) } .create() } diff --git a/app/src/main/java/com/kickstarter/ui/activities/ThanksActivity.kt b/app/src/main/java/com/kickstarter/ui/activities/ThanksActivity.kt index bc685ab069..ee7d45edd1 100644 --- a/app/src/main/java/com/kickstarter/ui/activities/ThanksActivity.kt +++ b/app/src/main/java/com/kickstarter/ui/activities/ThanksActivity.kt @@ -165,7 +165,6 @@ class ThanksActivity : AppCompatActivity() { private fun startDiscoveryActivity(params: DiscoveryParams) { val intent = Intent(this, DiscoveryActivity::class.java) - .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) .putExtra(IntentKey.DISCOVERY_PARAMS, params) startActivity(intent) } diff --git a/app/src/main/java/com/kickstarter/ui/activities/compose/ReportProjectScreen.kt b/app/src/main/java/com/kickstarter/ui/activities/compose/ReportProjectScreen.kt index fedb533e47..7de49dc4d1 100644 --- a/app/src/main/java/com/kickstarter/ui/activities/compose/ReportProjectScreen.kt +++ b/app/src/main/java/com/kickstarter/ui/activities/compose/ReportProjectScreen.kt @@ -38,11 +38,11 @@ import com.kickstarter.R import com.kickstarter.libs.utils.extensions.hrefUrlFromTranslation import com.kickstarter.libs.utils.extensions.parseHtmlTag import com.kickstarter.libs.utils.extensions.stringsFromHtmlTranslation +import com.kickstarter.type.FlaggingKind import com.kickstarter.ui.compose.designsystem.KSTheme import com.kickstarter.ui.compose.designsystem.KSTheme.colors import com.kickstarter.ui.compose.designsystem.KSTheme.typography import com.kickstarter.viewmodels.ReportProjectViewModel -import type.FlaggingKind @Composable @Preview( @@ -135,27 +135,27 @@ fun rulesMap(): Map, List, List, List(this.chosenCurrency)) - .filter { it.first.rawValue() != it.second } + .filter { it.first.rawValue != it.second } .map { it.first } .switchMap { updateUserCurrency(it).materialize() } .share() updateCurrencyNotification .compose(valuesV2()) - .map { it.updateUserProfile()?.user()?.chosenCurrency() ?: "" } + .map { it.updateUserProfile?.user?.chosenCurrency ?: "" } .filter { it.isNotNull() } .subscribe { this.chosenCurrency.onNext(it) @@ -153,6 +153,7 @@ interface AccountViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/ActivityFeedViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/ActivityFeedViewModel.kt index b8afbf2f1a..c8a3f6d116 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/ActivityFeedViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/ActivityFeedViewModel.kt @@ -245,6 +245,7 @@ interface ActivityFeedViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/BackingFragmentViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/BackingFragmentViewModel.kt index bed173ba55..be8090259f 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/BackingFragmentViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/BackingFragmentViewModel.kt @@ -29,6 +29,8 @@ import com.kickstarter.models.Reward import com.kickstarter.models.StoredCard import com.kickstarter.models.User import com.kickstarter.models.extensions.getCardTypeDrawable +import com.kickstarter.type.CreditCardPaymentType +import com.kickstarter.type.CreditCardTypes import com.kickstarter.ui.data.PledgeStatusData import com.kickstarter.ui.data.ProjectData import com.kickstarter.ui.fragments.BackingFragment @@ -39,8 +41,6 @@ import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject import org.joda.time.DateTime -import type.CreditCardPaymentType -import type.CreditCardTypes import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit @@ -327,7 +327,7 @@ interface BackingFragmentViewModel { .addToDisposable(disposables) backing - .map { CreditCardPaymentType.safeValueOf(it.paymentSource()?.paymentType()) } + .map { CreditCardPaymentType.safeValueOf(it.paymentSource()?.paymentType() ?: "") } .map { it == CreditCardPaymentType.ANDROID_PAY || it == CreditCardPaymentType.APPLE_PAY || it == CreditCardPaymentType.CREDIT_CARD } .map { it.negate() } .distinctUntilChanged() @@ -507,7 +507,7 @@ interface BackingFragmentViewModel { return when (CreditCardPaymentType.safeValueOf(paymentSource.paymentType())) { CreditCardPaymentType.ANDROID_PAY -> Either.Right(R.string.googlepay_button_content_description) CreditCardPaymentType.APPLE_PAY -> Either.Right(R.string.apple_pay_content_description) - CreditCardPaymentType.CREDIT_CARD -> Either.Left(StoredCard.issuer(CreditCardTypes.safeValueOf(paymentSource.type()))) + CreditCardPaymentType.CREDIT_CARD -> Either.Left(StoredCard.issuer(CreditCardTypes.safeValueOf(paymentSource.type() ?: ""))) else -> Either.Left(CardBrand.Unknown.code) } } @@ -650,6 +650,7 @@ interface BackingFragmentViewModel { override fun deliveryDisclaimerSectionIsGone(): Observable = this.deliveryDisclaimerSectionIsGone override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/BackingViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/BackingViewModel.kt index ff6a20b8ed..79f8062ee4 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/BackingViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/BackingViewModel.kt @@ -108,6 +108,7 @@ interface BackingViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/CancelPledgeViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/CancelPledgeViewModel.kt index 5c8db8eb16..f39943192a 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/CancelPledgeViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/CancelPledgeViewModel.kt @@ -146,6 +146,7 @@ interface CancelPledgeViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/ChangeEmailViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/ChangeEmailViewModel.kt index d9a6cf02e5..8759dbca09 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/ChangeEmailViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/ChangeEmailViewModel.kt @@ -1,10 +1,10 @@ package com.kickstarter.viewmodels -import SendEmailVerificationMutation -import UpdateUserEmailMutation import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.kickstarter.R +import com.kickstarter.SendEmailVerificationMutation +import com.kickstarter.UpdateUserEmailMutation import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair import com.kickstarter.libs.rx.transformers.Transformers.errorsV2 @@ -179,7 +179,7 @@ interface ChangeEmailViewModel { updateEmailNotification .compose(valuesV2()) .subscribe { - it.updateUserAccount()?.user()?.email()?.let { email -> + it.updateUserAccount?.user?.email?.let { email -> this.currentEmail.onNext(email) } this.success.onNext(Unit) @@ -293,6 +293,7 @@ interface ChangeEmailViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/ChangePasswordViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/ChangePasswordViewModel.kt index 077fc86bda..5b0db8288d 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/ChangePasswordViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/ChangePasswordViewModel.kt @@ -45,7 +45,7 @@ class ChangePasswordViewModel(val environment: Environment) : ViewModel() { } .map { analytics.reset() - mutableUIState.emit(UpdatePasswordUIState(isLoading = false, email = it.updateUserAccount()?.user()?.email() ?: "")) + mutableUIState.emit(UpdatePasswordUIState(isLoading = false, email = it.updateUserAccount?.user?.email ?: "")) } .catch { mutableUIState.emit(UpdatePasswordUIState(errorMessage = it.message ?: "", isLoading = false)) diff --git a/app/src/main/java/com/kickstarter/viewmodels/CommentsViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/CommentsViewModel.kt index 7921ad2fc2..02e9b08f64 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/CommentsViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/CommentsViewModel.kt @@ -593,6 +593,7 @@ interface CommentsViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/CreatePasswordViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/CreatePasswordViewModel.kt index 3f2584b107..d139e31c7d 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/CreatePasswordViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/CreatePasswordViewModel.kt @@ -1,8 +1,8 @@ package com.kickstarter.viewmodels -import CreatePasswordMutation import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider +import com.kickstarter.CreatePasswordMutation import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers.errorsV2 import com.kickstarter.libs.rx.transformers.Transformers.takeWhenV2 @@ -74,7 +74,7 @@ interface CreatePasswordViewModel { createNewPasswordNotification .compose(valuesV2()) - .map { it.updateUserAccount()?.user()?.email() } + .map { it.updateUserAccount?.user?.email } .filter { it.isNotNull() } .map { it } .subscribe { @@ -92,6 +92,7 @@ interface CreatePasswordViewModel { } override fun onCleared() { + apolloClientV2.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/DiscoveryFragmentViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/DiscoveryFragmentViewModel.kt index 3239007329..ecd88130f4 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/DiscoveryFragmentViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/DiscoveryFragmentViewModel.kt @@ -490,6 +490,12 @@ interface DiscoveryFragmentViewModel { .addToDisposable(disposables) } + override fun onCleared() { + apolloClient.cleanDisposables() + disposables.clear() + super.onCleared() + } + /** * Calls to GraphQL client to fetch projects filtering by DiscoveryParams * @param discoveryParamsStringPair .first discovery params. diff --git a/app/src/main/java/com/kickstarter/viewmodels/DiscoveryViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/DiscoveryViewModel.kt index 5e2ac01de2..6c61d64ef0 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/DiscoveryViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/DiscoveryViewModel.kt @@ -298,7 +298,7 @@ interface DiscoveryViewModel { val sortToTabOpen = Observable.merge( pagerSelectedPage.map { DiscoveryUtils.sortFromPosition(it) }, - params.map { it.sort() } + params.filter { it.sort().isNotNull() }.map { it.sort() } ).filter { it.isNotNull() } .map { it } @@ -484,6 +484,7 @@ interface DiscoveryViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/EnvironmentalCommitmentsViewHolderViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/EnvironmentalCommitmentsViewHolderViewModel.kt index 0b1c91ba1e..054bfbf784 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/EnvironmentalCommitmentsViewHolderViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/EnvironmentalCommitmentsViewHolderViewModel.kt @@ -45,7 +45,7 @@ interface EnvironmentalCommitmentsViewHolderViewModel { this.projectEnvironmentalCommitmentInput .map { EnvironmentalCommitmentCategories.values().firstOrNull { environmentalCommitmentCategory -> - environmentalCommitmentCategory.name == it.category + environmentalCommitmentCategory.name.lowercase() == it.category }?.title } .filter { it.isNotNull() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/LoggedInViewHolderViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/LoggedInViewHolderViewModel.kt index 989edc3777..15e8f7b947 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/LoggedInViewHolderViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/LoggedInViewHolderViewModel.kt @@ -131,6 +131,7 @@ interface LoggedInViewHolderViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/MessageCreatorViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/MessageCreatorViewModel.kt index 9833aa8cd4..2e97e5c2b7 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/MessageCreatorViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/MessageCreatorViewModel.kt @@ -147,6 +147,7 @@ interface MessageCreatorViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/PaymentMethodsViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/PaymentMethodsViewModel.kt index 5cdebd342f..6f0bc329ac 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/PaymentMethodsViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/PaymentMethodsViewModel.kt @@ -1,9 +1,9 @@ package com.kickstarter.viewmodels -import DeletePaymentSourceMutation import android.util.Pair import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider +import com.kickstarter.DeletePaymentSourceMutation import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair import com.kickstarter.libs.rx.transformers.Transformers.errorsV2 @@ -123,7 +123,7 @@ class PaymentMethodsViewModel(environment: Environment) : ViewModel(), PaymentMe deleteCardNotification .compose(valuesV2()) .map { - it.paymentSourceDelete()?.clientMutationId() ?: "" + it.paymentSourceDelete?.clientMutationId ?: "" } .subscribe { this.refreshCards.onNext(Unit) @@ -208,6 +208,7 @@ class PaymentMethodsViewModel(environment: Environment) : ViewModel(), PaymentMe } override fun onCleared() { + apolloClient.cleanDisposables() compositeDisposable.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/PledgeFragmentViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/PledgeFragmentViewModel.kt index 655f4620e3..c284de18e9 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/PledgeFragmentViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/PledgeFragmentViewModel.kt @@ -42,6 +42,7 @@ import com.kickstarter.models.extensions.getBackingData import com.kickstarter.models.extensions.isFromPaymentSheet import com.kickstarter.services.mutations.CreateBackingData import com.kickstarter.services.mutations.UpdateBackingData +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.ArgumentsKey import com.kickstarter.ui.data.CardState import com.kickstarter.ui.data.CheckoutData @@ -58,7 +59,6 @@ import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject -import type.CreditCardPaymentType import java.math.RoundingMode import java.text.NumberFormat import kotlin.math.max diff --git a/app/src/main/java/com/kickstarter/viewmodels/ProjectUpdatesViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/ProjectUpdatesViewModel.kt index b8218c2b55..6263c99b66 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/ProjectUpdatesViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/ProjectUpdatesViewModel.kt @@ -139,6 +139,7 @@ interface ProjectUpdatesViewModel { } override fun onCleared() { + client.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/ReportProjectViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/ReportProjectViewModel.kt index ae0eb9fc34..e428421107 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/ReportProjectViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/ReportProjectViewModel.kt @@ -136,6 +136,7 @@ interface ReportProjectViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/SearchViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/SearchViewModel.kt index 55be3fed45..02ef65a808 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/SearchViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/SearchViewModel.kt @@ -5,12 +5,10 @@ import android.content.SharedPreferences import android.util.Pair import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider -import com.apollographql.apollo.api.CustomTypeValue import com.kickstarter.libs.ApiPaginatorV2 import com.kickstarter.libs.Environment import com.kickstarter.libs.RefTag import com.kickstarter.libs.featureflag.FlagKey -import com.kickstarter.libs.graphql.DateTimeAdapter import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.utils.ListUtils import com.kickstarter.libs.utils.RefTagUtils @@ -27,6 +25,7 @@ import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject +import org.joda.time.DateTime import java.net.CookieManager import java.util.concurrent.TimeUnit @@ -268,7 +267,8 @@ interface SearchViewModel { } selectedProject.subscribe { - if (it.first.launchedAt() == DateTimeAdapter().decode(CustomTypeValue.fromRawValue(0)) && + val epochDateTime = DateTime(0) + if (it.first.launchedAt() == epochDateTime && ffClient.getBoolean(FlagKey.ANDROID_PRE_LAUNCH_SCREEN) ) { startPreLaunchProjectActivity.onNext(it) diff --git a/app/src/main/java/com/kickstarter/viewmodels/SetPasswordViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/SetPasswordViewModel.kt index 76098ad35f..d69e6c8e72 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/SetPasswordViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/SetPasswordViewModel.kt @@ -3,6 +3,7 @@ package com.kickstarter.viewmodels import android.content.Intent import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider +import com.kickstarter.UpdateUserPasswordMutation import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.rx.transformers.Transformers.takeWhenV2 @@ -116,7 +117,7 @@ interface SetPasswordViewModel { val userHasPassword = setNewPasswordNotification .compose(Transformers.valuesV2()) - .filter { it.updateUserAccount()?.user()?.hasPassword() ?: false } + .filter { it.updateUserAccount?.user?.hasPassword ?: false } this.currentUserV2.loggedInUser() .compose(Transformers.takePairWhenV2(userHasPassword)) @@ -128,11 +129,12 @@ interface SetPasswordViewModel { it.first.toBuilder().needsPassword(false).build() ) } - this.success.onNext(it.second.updateUserAccount()?.user()?.email() ?: "") + this.success.onNext(it.second.updateUserAccount?.user?.email ?: "") }.addToDisposable(disposables) } override fun onCleared() { + apolloClientV2.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/ThanksViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/ThanksViewModel.kt index 449549324d..7d42069a83 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/ThanksViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/ThanksViewModel.kt @@ -442,6 +442,7 @@ interface ThanksViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/ThreadViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/ThreadViewModel.kt index 13dd221860..5c20194d81 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/ThreadViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/ThreadViewModel.kt @@ -535,6 +535,7 @@ interface ThreadViewModel { override fun closeThreadActivity(): Observable = this.closeThreadActivity override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/projectpage/CrowdfundCheckoutViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/projectpage/CrowdfundCheckoutViewModel.kt index e1dab951e5..626cc98487 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/projectpage/CrowdfundCheckoutViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/projectpage/CrowdfundCheckoutViewModel.kt @@ -25,6 +25,7 @@ import com.kickstarter.models.User import com.kickstarter.models.extensions.getBackingData import com.kickstarter.models.extensions.isFromPaymentSheet import com.kickstarter.services.mutations.getUpdateBackingData +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.ArgumentsKey import com.kickstarter.ui.data.CheckoutData import com.kickstarter.ui.data.PledgeData @@ -46,7 +47,6 @@ import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.rx2.asFlow -import type.CreditCardPaymentType data class CheckoutUIState( val storeCards: List = listOf(), diff --git a/app/src/main/java/com/kickstarter/viewmodels/projectpage/LatePledgeCheckoutViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/projectpage/LatePledgeCheckoutViewModel.kt index 0409c72986..42e17eb9e7 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/projectpage/LatePledgeCheckoutViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/projectpage/LatePledgeCheckoutViewModel.kt @@ -20,6 +20,7 @@ import com.kickstarter.models.Reward import com.kickstarter.models.StoredCard import com.kickstarter.services.mutations.CreateCheckoutData import com.kickstarter.services.mutations.SavePaymentMethodData +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.data.CheckoutData import com.kickstarter.ui.data.PledgeData import com.stripe.android.Stripe @@ -41,7 +42,6 @@ import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.rx2.asFlow -import type.CreditCardPaymentType data class LatePledgeCheckoutUIState( val storeCards: List = listOf(), diff --git a/app/src/main/java/com/kickstarter/viewmodels/projectpage/PrelaunchProjectViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/projectpage/PrelaunchProjectViewModel.kt index f28210f119..9ad1e503d8 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/projectpage/PrelaunchProjectViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/projectpage/PrelaunchProjectViewModel.kt @@ -347,7 +347,9 @@ interface PrelaunchProjectViewModel { return@withLatestFrom project.updateProjectWith(config, null) } } + override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectOverviewViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectOverviewViewModel.kt index 8c29e84a49..d65f103b26 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectOverviewViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectOverviewViewModel.kt @@ -709,6 +709,7 @@ interface ProjectOverviewViewModel { .addToDisposable(disposables) } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectPageViewModel.kt b/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectPageViewModel.kt index 951d068616..2ec6fdac45 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectPageViewModel.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectPageViewModel.kt @@ -1040,6 +1040,7 @@ interface ProjectPageViewModel { } override fun onCleared() { + apolloClient.cleanDisposables() disposables.clear() super.onCleared() } diff --git a/app/src/main/java/com/kickstarter/viewmodels/usecases/TPDataClasses.kt b/app/src/main/java/com/kickstarter/viewmodels/usecases/TPDataClasses.kt index bafbf25ca3..8a40c676b1 100644 --- a/app/src/main/java/com/kickstarter/viewmodels/usecases/TPDataClasses.kt +++ b/app/src/main/java/com/kickstarter/viewmodels/usecases/TPDataClasses.kt @@ -8,7 +8,7 @@ import com.kickstarter.models.User import com.kickstarter.services.transformers.encodeRelayId import com.kickstarter.ui.data.CheckoutData import com.kickstarter.ui.data.PledgeData -import type.TriggerThirdPartyEventInput +// import com.kickstarter.type.TriggerThirdPartyEventInput /*** * ThirdPartyEventInputData data model to sent items values to third party analytics systems diff --git a/app/src/test/java/com/kickstarter/KSCurrencyTest.kt b/app/src/test/java/com/kickstarter/KSCurrencyTest.kt index 9ad3ee9b1d..a566916797 100644 --- a/app/src/test/java/com/kickstarter/KSCurrencyTest.kt +++ b/app/src/test/java/com/kickstarter/KSCurrencyTest.kt @@ -8,9 +8,9 @@ import com.kickstarter.mock.factories.ConfigFactory.config import com.kickstarter.mock.factories.ProjectFactory.caProject import com.kickstarter.mock.factories.ProjectFactory.project import com.kickstarter.mock.factories.ProjectFactory.ukProject +import com.kickstarter.type.CurrencyCode import junit.framework.TestCase import org.junit.Test -import type.CurrencyCode import java.math.RoundingMode class KSCurrencyTest : TestCase() { @@ -39,7 +39,7 @@ class KSCurrencyTest : TestCase() { val currency = createKSCurrency("CA") val preferUSD_USProject = project() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals( "US$ 100", @@ -55,7 +55,7 @@ class KSCurrencyTest : TestCase() { ) val preferUSD_CAProject = caProject() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals( "US$ 100", @@ -71,7 +71,7 @@ class KSCurrencyTest : TestCase() { ) val preferUSD_UKProject = ukProject() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals( "US$ 100", @@ -92,7 +92,7 @@ class KSCurrencyTest : TestCase() { val currency = createKSCurrency("US") val preferUSD_USProject = project() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals( "$100", @@ -108,7 +108,7 @@ class KSCurrencyTest : TestCase() { ) val preferUSD_CAProject = caProject() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals( "$100", @@ -124,7 +124,7 @@ class KSCurrencyTest : TestCase() { ) val preferUSD_UKProject = ukProject() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals( "$100", @@ -185,7 +185,7 @@ class KSCurrencyTest : TestCase() { val currency = createKSCurrency("US") val preferUSD_USProject = project() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("$100", currency.formatWithUserPreference(100.1, preferUSD_USProject)) assertEquals("$100", currency.formatWithUserPreference(100.9, preferUSD_USProject)) @@ -207,7 +207,7 @@ class KSCurrencyTest : TestCase() { ) val preferUSD_CAProject = caProject() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("$75", currency.formatWithUserPreference(100.1, preferUSD_CAProject)) assertEquals("$75", currency.formatWithUserPreference(100.9, preferUSD_CAProject)) @@ -229,7 +229,7 @@ class KSCurrencyTest : TestCase() { ) val preferUSD_UKProject = ukProject() .toBuilder() - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("$150", currency.formatWithUserPreference(100.1, preferUSD_UKProject)) assertEquals("$150", currency.formatWithUserPreference(100.9, preferUSD_UKProject)) @@ -271,7 +271,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_USProject = project() .toBuilder() .fxRate(1f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 100", currency.formatWithUserPreference(100.1, preferUSD_USProject)) assertEquals("US$ 100", currency.formatWithUserPreference(100.9, preferUSD_USProject)) @@ -294,7 +294,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_CAProject = caProject() .toBuilder() .fxRate(.75f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 75", currency.formatWithUserPreference(100.1, preferUSD_CAProject)) assertEquals("US$ 75", currency.formatWithUserPreference(100.9, preferUSD_CAProject)) @@ -317,7 +317,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_UKProject = ukProject() .toBuilder() .fxRate(1.5f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 150", currency.formatWithUserPreference(100.1, preferUSD_UKProject)) assertEquals("US$ 150", currency.formatWithUserPreference(100.9, preferUSD_UKProject)) @@ -345,7 +345,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_USProject = project() .toBuilder() .fxRate(1f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 100", currency.formatWithUserPreference(100.1, preferUSD_USProject)) assertEquals("US$ 100", currency.formatWithUserPreference(100.9, preferUSD_USProject)) @@ -368,7 +368,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_CAProject = caProject() .toBuilder() .fxRate(.75f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 75", currency.formatWithUserPreference(100.1, preferUSD_CAProject)) assertEquals("US$ 75", currency.formatWithUserPreference(100.9, preferUSD_CAProject)) @@ -391,7 +391,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_UKProject = ukProject() .toBuilder() .fxRate(1.5f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 150", currency.formatWithUserPreference(100.1, preferUSD_UKProject)) assertEquals("US$ 150", currency.formatWithUserPreference(100.9, preferUSD_UKProject)) @@ -419,7 +419,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_USProject = project() .toBuilder() .fxRate(1f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 100", currency.formatWithUserPreference(100.1, preferUSD_USProject)) assertEquals("US$ 100", currency.formatWithUserPreference(100.9, preferUSD_USProject)) @@ -442,7 +442,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_CAProject = caProject() .toBuilder() .fxRate(.75f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 75", currency.formatWithUserPreference(100.1, preferUSD_CAProject)) assertEquals("US$ 75", currency.formatWithUserPreference(100.9, preferUSD_CAProject)) @@ -465,7 +465,7 @@ class KSCurrencyTest : TestCase() { val preferUSD_UKProject = ukProject() .toBuilder() .fxRate(1.5f) - .currentCurrency(CurrencyCode.USD.rawValue()) + .currentCurrency(CurrencyCode.USD.rawValue) .build() assertEquals("US$ 150", currency.formatWithUserPreference(100.1, preferUSD_UKProject)) assertEquals("US$ 150", currency.formatWithUserPreference(100.9, preferUSD_UKProject)) @@ -493,7 +493,7 @@ class KSCurrencyTest : TestCase() { val preferCAD_USProject = project() .toBuilder() .fxRate(1.5f) - .currentCurrency(CurrencyCode.CAD.rawValue()) + .currentCurrency(CurrencyCode.CAD.rawValue) .build() assertEquals("CA$ 150", currency.formatWithUserPreference(100.1, preferCAD_USProject)) assertEquals("CA$ 150", currency.formatWithUserPreference(100.9, preferCAD_USProject)) @@ -516,7 +516,7 @@ class KSCurrencyTest : TestCase() { val preferCAD_CAProject = caProject() .toBuilder() .fxRate(1f) - .currentCurrency(CurrencyCode.CAD.rawValue()) + .currentCurrency(CurrencyCode.CAD.rawValue) .build() assertEquals("CA$ 100", currency.formatWithUserPreference(100.1, preferCAD_CAProject)) assertEquals("CA$ 100", currency.formatWithUserPreference(100.9, preferCAD_CAProject)) @@ -539,7 +539,7 @@ class KSCurrencyTest : TestCase() { val preferCAD_UKProject = ukProject() .toBuilder() .fxRate(.75f) - .currentCurrency(CurrencyCode.CAD.rawValue()) + .currentCurrency(CurrencyCode.CAD.rawValue) .build() assertEquals("CA$ 75", currency.formatWithUserPreference(100.1, preferCAD_UKProject)) assertEquals("CA$ 75", currency.formatWithUserPreference(100.9, preferCAD_UKProject)) @@ -567,7 +567,7 @@ class KSCurrencyTest : TestCase() { val preferGBP_USProject = project() .toBuilder() .fxRate(.75f) - .currentCurrency(CurrencyCode.GBP.rawValue()) + .currentCurrency(CurrencyCode.GBP.rawValue) .build() assertEquals("£75", currency.formatWithUserPreference(100.1, preferGBP_USProject)) assertEquals("£75", currency.formatWithUserPreference(100.9, preferGBP_USProject)) @@ -590,7 +590,7 @@ class KSCurrencyTest : TestCase() { val preferGBP_CAProject = caProject() .toBuilder() .fxRate(1.5f) - .currentCurrency(CurrencyCode.GBP.rawValue()) + .currentCurrency(CurrencyCode.GBP.rawValue) .build() assertEquals("£150", currency.formatWithUserPreference(100.1, preferGBP_CAProject)) assertEquals("£150", currency.formatWithUserPreference(100.9, preferGBP_CAProject)) @@ -613,7 +613,7 @@ class KSCurrencyTest : TestCase() { val preferGBP_UKProject = ukProject() .toBuilder() .fxRate(1f) - .currentCurrency(CurrencyCode.GBP.rawValue()) + .currentCurrency(CurrencyCode.GBP.rawValue) .build() assertEquals("£100", currency.formatWithUserPreference(100.1, preferGBP_UKProject)) assertEquals("£100", currency.formatWithUserPreference(100.9, preferGBP_UKProject)) diff --git a/app/src/test/java/com/kickstarter/libs/utils/TransformersTest.kt b/app/src/test/java/com/kickstarter/libs/utils/TransformersTest.kt index bca1ad569b..cac55b11f4 100644 --- a/app/src/test/java/com/kickstarter/libs/utils/TransformersTest.kt +++ b/app/src/test/java/com/kickstarter/libs/utils/TransformersTest.kt @@ -4,15 +4,15 @@ import com.kickstarter.KSRobolectricTestCase import com.kickstarter.services.transformers.decodeRelayId import com.kickstarter.services.transformers.environmentalCommitmentTransformer import com.kickstarter.services.transformers.projectFaqTransformer +import com.kickstarter.type.EnvironmentalCommitmentCategory import org.junit.Test -import type.EnvironmentalCommitmentCategory class TransformersTest : KSRobolectricTestCase() { @Test fun projectFaqTransformerTest() { // - fragment.Faq is a generated DataStructure by Apollo - val fragmentFaq = fragment.Faq("", "UHJvamVjdEZhcS0zNTgwNTE=", "answer", null, "question") + val fragmentFaq = com.kickstarter.fragment.Faq("UHJvamVjdEZhcS0zNTgwNTE=", "answer", null, "question") val faq = projectFaqTransformer(fragmentFaq) assertTrue(faq.id == decodeRelayId("UHJvamVjdEZhcS0zNTgwNTE=")) @@ -24,9 +24,8 @@ class TransformersTest : KSRobolectricTestCase() { @Test fun environmentCommitmentsTransformerTest() { - val fragmentEnvCom = fragment.EnvironmentalCommitment( - "", - EnvironmentalCommitmentCategory.ENVIRONMENTALLY_FRIENDLY_FACTORIES, + val fragmentEnvCom = com.kickstarter.fragment.EnvironmentalCommitment( + EnvironmentalCommitmentCategory.environmentally_friendly_factories, "Description", "RW52aXJvbm1lbnRhbENvbW1pdG1lbnQtMTA5Njk0", ) @@ -35,6 +34,6 @@ class TransformersTest : KSRobolectricTestCase() { assertTrue(envCommitment.id == decodeRelayId("RW52aXJvbm1lbnRhbENvbW1pdG1lbnQtMTA5Njk0")) assertTrue(envCommitment.description == "Description") - assertTrue(envCommitment.category == EnvironmentalCommitmentCategory.ENVIRONMENTALLY_FRIENDLY_FACTORIES.name) + assertTrue(envCommitment.category == EnvironmentalCommitmentCategory.environmentally_friendly_factories.name) } } diff --git a/app/src/test/java/com/kickstarter/libs/utils/extensions/CheckoutDataExtTest.kt b/app/src/test/java/com/kickstarter/libs/utils/extensions/CheckoutDataExtTest.kt index e628328d02..66888926e4 100644 --- a/app/src/test/java/com/kickstarter/libs/utils/extensions/CheckoutDataExtTest.kt +++ b/app/src/test/java/com/kickstarter/libs/utils/extensions/CheckoutDataExtTest.kt @@ -1,9 +1,9 @@ package com.kickstarter.libs.utils.extensions import com.kickstarter.mock.factories.ProjectFactory +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.data.CheckoutData import junit.framework.TestCase -import type.CreditCardPaymentType class CheckoutDataExtTest : TestCase() { diff --git a/app/src/test/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExtKtTest.kt b/app/src/test/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExtKtTest.kt index 585f34b419..bf233e1cd5 100644 --- a/app/src/test/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExtKtTest.kt +++ b/app/src/test/java/com/kickstarter/libs/utils/extensions/DiscoveryParamsExtKtTest.kt @@ -7,9 +7,9 @@ import com.kickstarter.mock.factories.LocationFactory import com.kickstarter.mock.factories.UserFactory import com.kickstarter.models.User import com.kickstarter.services.DiscoveryParams +import com.kickstarter.type.ProjectSort import com.kickstarter.ui.adapters.data.NavigationDrawerData import org.junit.Test -import type.ProjectSort class DiscoveryParamsExtKtTest : KSRobolectricTestCase() { diff --git a/app/src/test/java/com/kickstarter/libs/utils/extensions/ProjectExtTest.kt b/app/src/test/java/com/kickstarter/libs/utils/extensions/ProjectExtTest.kt index 47c0f95448..487271ffae 100644 --- a/app/src/test/java/com/kickstarter/libs/utils/extensions/ProjectExtTest.kt +++ b/app/src/test/java/com/kickstarter/libs/utils/extensions/ProjectExtTest.kt @@ -12,12 +12,12 @@ import com.kickstarter.models.ProjectFaq import com.kickstarter.models.Reward import com.kickstarter.models.User import com.kickstarter.services.DiscoveryParams +import com.kickstarter.type.CreditCardTypes import org.joda.time.DateTime import org.joda.time.DateTimeZone import org.junit.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` -import type.CreditCardTypes import java.util.Locale class ProjectExtTest : KSRobolectricTestCase() { diff --git a/app/src/test/java/com/kickstarter/models/CheckoutDataTest.kt b/app/src/test/java/com/kickstarter/models/CheckoutDataTest.kt index b717b20fd2..83e5c8a6fa 100644 --- a/app/src/test/java/com/kickstarter/models/CheckoutDataTest.kt +++ b/app/src/test/java/com/kickstarter/models/CheckoutDataTest.kt @@ -2,9 +2,9 @@ package com.kickstarter.models import com.kickstarter.KSRobolectricTestCase import com.kickstarter.mock.factories.CheckoutDataFactory +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.data.CheckoutData import org.junit.Test -import type.CreditCardPaymentType class CheckoutDataTest : KSRobolectricTestCase() { diff --git a/app/src/test/java/com/kickstarter/models/StoredCardTest.kt b/app/src/test/java/com/kickstarter/models/StoredCardTest.kt index 1102bbbc97..3e3a260335 100644 --- a/app/src/test/java/com/kickstarter/models/StoredCardTest.kt +++ b/app/src/test/java/com/kickstarter/models/StoredCardTest.kt @@ -8,10 +8,10 @@ import com.kickstarter.mock.factories.RewardFactory import com.kickstarter.mock.factories.StoredCardFactory import com.kickstarter.models.extensions.getBackingData import com.kickstarter.models.extensions.getCardTypeDrawable +import com.kickstarter.type.CreditCardTypes import com.stripe.android.model.CardBrand import junit.framework.TestCase import org.junit.Test -import type.CreditCardTypes import java.util.Date class StoredCardTest : TestCase() { @@ -47,7 +47,7 @@ class StoredCardTest : TestCase() { val resourceID = storedCard.getCardTypeDrawable() assertEquals(storedCard.lastFourDigits(), "1234") - assertEquals(storedCard.type(), CreditCardTypes.`$UNKNOWN`) + assertEquals(storedCard.type(), CreditCardTypes.UNKNOWN__) assertEquals(resourceID, 1234) } @@ -94,7 +94,7 @@ class StoredCardTest : TestCase() { assertEquals(StoredCard.issuer(CreditCardTypes.MASTERCARD), CardBrand.MasterCard.code) assertEquals(StoredCard.issuer(CreditCardTypes.UNIONPAY), CardBrand.UnionPay.code) assertEquals(StoredCard.issuer(CreditCardTypes.VISA), CardBrand.Visa.code) - assertEquals(StoredCard.issuer(CreditCardTypes.`$UNKNOWN`), CardBrand.Unknown.code) + assertEquals(StoredCard.issuer(CreditCardTypes.UNKNOWN__), CardBrand.Unknown.code) } @Test @@ -106,7 +106,7 @@ class StoredCardTest : TestCase() { assertEquals(getCardTypeDrawable(CreditCardTypes.MASTERCARD), R.drawable.mastercard_md) assertEquals(getCardTypeDrawable(CreditCardTypes.UNIONPAY), R.drawable.union_pay_md) assertEquals(getCardTypeDrawable(CreditCardTypes.VISA), R.drawable.visa_md) - assertEquals(getCardTypeDrawable(CreditCardTypes.`$UNKNOWN`), R.drawable.generic_bank_md) + assertEquals(getCardTypeDrawable(CreditCardTypes.UNKNOWN__), R.drawable.generic_bank_md) } @Test diff --git a/app/src/test/java/com/kickstarter/services/GraphQLTransformersTest.kt b/app/src/test/java/com/kickstarter/services/GraphQLTransformersTest.kt index e8e4fc23ff..4e6906cd79 100644 --- a/app/src/test/java/com/kickstarter/services/GraphQLTransformersTest.kt +++ b/app/src/test/java/com/kickstarter/services/GraphQLTransformersTest.kt @@ -1,7 +1,15 @@ package com.kickstarter.services -import UserPrivacyQuery +import com.kickstarter.FetchProjectRewardsQuery import com.kickstarter.KSRobolectricTestCase +import com.kickstarter.UserPrivacyQuery +import com.kickstarter.fragment.AiDisclosure +import com.kickstarter.fragment.Amount +import com.kickstarter.fragment.EnvironmentalCommitment +import com.kickstarter.fragment.Faq +import com.kickstarter.fragment.Reward +import com.kickstarter.fragment.Reward.AllowedAddons +import com.kickstarter.fragment.User import com.kickstarter.services.transformers.aiDisclosureTransformer import com.kickstarter.services.transformers.decodeRelayId import com.kickstarter.services.transformers.environmentalCommitmentTransformer @@ -11,42 +19,35 @@ import com.kickstarter.services.transformers.simpleShippingRuleTransformer import com.kickstarter.services.transformers.updateTransformer import com.kickstarter.services.transformers.userPrivacyTransformer import com.kickstarter.services.transformers.userTransformer -import fragment.AiDisclosure -import fragment.Amount -import fragment.EnvironmentalCommitment -import fragment.Faq -import fragment.Reward -import fragment.Reward.AllowedAddons -import fragment.User +import com.kickstarter.type.EnvironmentalCommitmentCategory +import com.kickstarter.type.RewardType +import com.kickstarter.type.ShippingPreference import org.joda.time.DateTime import org.junit.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` -import type.EnvironmentalCommitmentCategory -import type.RewardType -import type.ShippingPreference class GraphQLTransformersTest : KSRobolectricTestCase() { @Test fun testProjectFaqTransformer() { val faq: Faq = mock(Faq::class.java) - `when`(faq.id()).thenReturn("UHJvamVjdEZhcS0zODE3Mzk=") - `when`(faq.answer()).thenReturn("answer") - `when`(faq.question()).thenReturn("question") + `when`(faq.id).thenReturn("UHJvamVjdEZhcS0zODE3Mzk=") + `when`(faq.answer).thenReturn("answer") + `when`(faq.question).thenReturn("question") val projectFaq = projectFaqTransformer(faq) - assertTrue(projectFaq.id == decodeRelayId(faq.id())) + assertTrue(projectFaq.id == decodeRelayId(faq.id)) assertTrue(projectFaq.answer == "answer") assertTrue(projectFaq.question == "question") assertTrue(projectFaq.createdAt == null) val faq2: Faq = mock(Faq::class.java) - `when`(faq2.id()).thenReturn("") - `when`(faq2.answer()).thenReturn("") - `when`(faq2.question()).thenReturn("") - `when`(faq2.createdAt()).thenReturn(null) + `when`(faq2.id).thenReturn("") + `when`(faq2.answer).thenReturn("") + `when`(faq2.question).thenReturn("") + `when`(faq2.createdAt).thenReturn(null) val projectFaq2 = projectFaqTransformer(faq2) assertTrue(projectFaq2.id == -1L) @@ -54,10 +55,10 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { val date = DateTime.now().plusMillis(300) val faq3: Faq = mock(Faq::class.java) - `when`(faq3.id()).thenReturn("") - `when`(faq3.answer()).thenReturn("") - `when`(faq3.question()).thenReturn("") - `when`(faq3.createdAt()).thenReturn(date) + `when`(faq3.id).thenReturn("") + `when`(faq3.answer).thenReturn("") + `when`(faq3.question).thenReturn("") + `when`(faq3.createdAt).thenReturn(date) val projectFaq3 = projectFaqTransformer(faq3) assertTrue(projectFaq3.createdAt == date) @@ -66,36 +67,36 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { @Test fun testEnvironmentalCommitmentTransformer() { val envCom: EnvironmentalCommitment = mock(EnvironmentalCommitment::class.java) - `when`(envCom.id()).thenReturn("RW52aXJvbm1lbnRhbENvbW1pdG1lbnQtMTMzNTMy") - `when`(envCom.description()).thenReturn("desc") - `when`(envCom.commitmentCategory()).thenReturn(EnvironmentalCommitmentCategory.ENVIRONMENTALLY_FRIENDLY_FACTORIES) + `when`(envCom.id).thenReturn("RW52aXJvbm1lbnRhbENvbW1pdG1lbnQtMTMzNTMy") + `when`(envCom.description).thenReturn("desc") + `when`(envCom.commitmentCategory).thenReturn(EnvironmentalCommitmentCategory.environmentally_friendly_factories) val projEnvConv = environmentalCommitmentTransformer(envCom) assertTrue(projEnvConv.id == 133532L) assertTrue(projEnvConv.description == "desc") - assertTrue(projEnvConv.category == EnvironmentalCommitmentCategory.ENVIRONMENTALLY_FRIENDLY_FACTORIES.name) + assertTrue(projEnvConv.category == EnvironmentalCommitmentCategory.environmentally_friendly_factories.name) val envCom2: EnvironmentalCommitment = mock(EnvironmentalCommitment::class.java) - `when`(envCom2.id()).thenReturn("") - `when`(envCom2.description()).thenReturn("") - `when`(envCom2.commitmentCategory()).thenReturn(EnvironmentalCommitmentCategory.LONG_LASTING_DESIGN) + `when`(envCom2.id).thenReturn("") + `when`(envCom2.description).thenReturn("") + `when`(envCom2.commitmentCategory).thenReturn(EnvironmentalCommitmentCategory.long_lasting_design) val projEnvConv2 = environmentalCommitmentTransformer(envCom2) assertTrue(projEnvConv2.id == -1L) assertTrue(projEnvConv2.description == "") - assertTrue(projEnvConv2.category == EnvironmentalCommitmentCategory.LONG_LASTING_DESIGN.name) + assertTrue(projEnvConv2.category == EnvironmentalCommitmentCategory.long_lasting_design.name) } @Test fun testAiDisclosureTransformer() { val aiDisclosureMockComplete: AiDisclosure = mock(AiDisclosure::class.java) - `when`(aiDisclosureMockComplete.id()).thenReturn("QWlEaXNjbG9zdXJlLTE=") - `when`(aiDisclosureMockComplete.fundingForAiAttribution()).thenReturn(true) - `when`(aiDisclosureMockComplete.fundingForAiConsent()).thenReturn(true) - `when`(aiDisclosureMockComplete.fundingForAiOption()).thenReturn(true) - `when`(aiDisclosureMockComplete.generatedByAiConsent()).thenReturn("Some text here") - `when`(aiDisclosureMockComplete.generatedByAiDetails()).thenReturn("Some other details text here") - `when`(aiDisclosureMockComplete.otherAiDetails()).thenReturn("some other details here") + `when`(aiDisclosureMockComplete.id).thenReturn("QWlEaXNjbG9zdXJlLTE=") + `when`(aiDisclosureMockComplete.fundingForAiAttribution).thenReturn(true) + `when`(aiDisclosureMockComplete.fundingForAiConsent).thenReturn(true) + `when`(aiDisclosureMockComplete.fundingForAiOption).thenReturn(true) + `when`(aiDisclosureMockComplete.generatedByAiConsent).thenReturn("Some text here") + `when`(aiDisclosureMockComplete.generatedByAiDetails).thenReturn("Some other details text here") + `when`(aiDisclosureMockComplete.otherAiDetails).thenReturn("some other details here") val aiDisclosure = aiDisclosureTransformer(aiDisclosureGraph = aiDisclosureMockComplete) assertTrue(aiDisclosure.id == 1L) @@ -108,9 +109,9 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { assertEquals(aiDisclosure.otherAiDetails, "some other details here") val aiDisclosureMockPartial: AiDisclosure = mock(AiDisclosure::class.java) - `when`(aiDisclosureMockPartial.id()).thenReturn("") - `when`(aiDisclosureMockPartial.fundingForAiAttribution()).thenReturn(false) - `when`(aiDisclosureMockPartial.generatedByAiConsent()).thenReturn("Some more text here") + `when`(aiDisclosureMockPartial.id).thenReturn("") + `when`(aiDisclosureMockPartial.fundingForAiAttribution).thenReturn(false) + `when`(aiDisclosureMockPartial.generatedByAiConsent).thenReturn("Some more text here") val aiDisclosure1 = aiDisclosureTransformer(aiDisclosureGraph = aiDisclosureMockPartial) assertTrue(aiDisclosure1.id == -1L) @@ -126,11 +127,11 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { @Test fun testUserTransformer() { val userFragment = mock(User::class.java) - `when`(userFragment.id()).thenReturn("VXNlci0yMzc5NjEyNDM=") - `when`(userFragment.name()).thenReturn("Brotherwise Games") - `when`(userFragment.imageUrl()).thenReturn("https://ksr-qa-ugc.imgix.net/assets/005/791/327/f120c4cfe49495849b526b2cc6da44f9_original.png") + `when`(userFragment.id).thenReturn("VXNlci0yMzc5NjEyNDM=") + `when`(userFragment.name).thenReturn("Brotherwise Games") + `when`(userFragment.imageUrl).thenReturn("https://ksr-qa-ugc.imgix.net/assets/005/791/327/f120c4cfe49495849b526b2cc6da44f9_original.png") `when`(userFragment.isCreator).thenReturn(true) - `when`(userFragment.chosenCurrency()).thenReturn(null) + `when`(userFragment.chosenCurrency).thenReturn(null) val user = userTransformer(userFragment) assertTrue(user.id() == 237961243L) @@ -141,13 +142,13 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { @Test fun testUserPrivacyTransformer() { val userPrivacyQuery = mock(UserPrivacyQuery.Me::class.java) - `when`(userPrivacyQuery.name()).thenReturn("Brotherwise Games") - `when`(userPrivacyQuery.email()).thenReturn("hello@kickstarter.com") - `when`(userPrivacyQuery.hasPassword()).thenReturn(true) + `when`(userPrivacyQuery.name).thenReturn("Brotherwise Games") + `when`(userPrivacyQuery.email).thenReturn("hello@kickstarter.com") + `when`(userPrivacyQuery.hasPassword).thenReturn(true) `when`(userPrivacyQuery.isCreator).thenReturn(true) `when`(userPrivacyQuery.isDeliverable).thenReturn(true) `when`(userPrivacyQuery.isEmailVerified).thenReturn(true) - `when`(userPrivacyQuery.chosenCurrency()).thenReturn(null) + `when`(userPrivacyQuery.chosenCurrency).thenReturn(null) val userPrivacy = userPrivacyTransformer(userPrivacyQuery) assertTrue(userPrivacy.name == "Brotherwise Games") @@ -160,17 +161,17 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { @Test fun testUpdateTransformer() { - val post = mock(fragment.Post::class.java) - `when`(post.id()).thenReturn("VXNlci0yMzc5NjEyNDM=") - `when`(post.title()).thenReturn("Updated Add-on list") + val post = mock(com.kickstarter.fragment.Post::class.java) + `when`(post.id).thenReturn("VXNlci0yMzc5NjEyNDM=") + `when`(post.title).thenReturn("Updated Add-on list") `when`(post.isPublic).thenReturn(true) `when`(post.isVisible).thenReturn(true) `when`(post.isLiked).thenReturn(true) - `when`(post.number()).thenReturn(5) + `when`(post.number).thenReturn(5) val date = DateTime.now().plusMillis(300) - `when`(post.publishedAt()).thenReturn(date) - `when`(post.updatedAt()).thenReturn(date) + `when`(post.publishedAt).thenReturn(date) + `when`(post.updatedAt).thenReturn(date) val user = updateTransformer(post) assertTrue(user.id() == 237961243L) @@ -180,14 +181,13 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { assertTrue(user.visible() == true) assertTrue(user.hasLiked() == true) assertTrue(user.sequence() == 5) - assertTrue(post.publishedAt() == date) - assertTrue(post.updatedAt() == date) + assertTrue(post.publishedAt == date) + assertTrue(post.updatedAt == date) } @Test fun `test simpleShippingRuleTransformer provides appropriate shippingRule`() { val canadaSimpleSR = FetchProjectRewardsQuery.SimpleShippingRulesExpanded( - "SimpleShippingRule", "17.34562379823645234875620384756203847234", "CA", null, @@ -197,7 +197,6 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { ) val australiaSR = FetchProjectRewardsQuery.SimpleShippingRulesExpanded( - "SimpleShippingRule", "0", "AU", "20", // - Shipping Rule disable at shipping, cost = 0, estimated range max/min values not null @@ -207,7 +206,6 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { ) val forbiddenValues = FetchProjectRewardsQuery.SimpleShippingRulesExpanded( - "SimpleShippingRule", "Pikachusito", "AU", "AyOma", // - Shipping Rule disable at shipping, cost = 0, estimated range max/min values not null @@ -222,29 +220,29 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { // - Expected output model in case of forbidden values (non-numeric) on Cost/Monetary related fields val nonDoubleValues = simpleShippingRuleTransformer(forbiddenValues) - assert(cadShipping.location()?.id() == decodeRelayId(canadaSimpleSR.locationId())) + assert(cadShipping.location()?.id() == decodeRelayId(canadaSimpleSR.locationId)) assert(cadShipping.cost() == 17.345623798236453) // - Rounds up after 15th digit assert(cadShipping.estimatedMax() == 0.0) assert(cadShipping.estimatedMin() == 0.0) - assert(cadShipping.location()?.name() == canadaSimpleSR.locationName()) - assert(cadShipping.location()?.displayableName() == canadaSimpleSR.locationName()) - assert(cadShipping.location()?.country() == canadaSimpleSR.country()) + assert(cadShipping.location()?.name() == canadaSimpleSR.locationName) + assert(cadShipping.location()?.displayableName() == canadaSimpleSR.locationName) + assert(cadShipping.location()?.country() == canadaSimpleSR.country) - assert(ausShipping.location()?.id() == decodeRelayId(australiaSR.locationId())) + assert(ausShipping.location()?.id() == decodeRelayId(australiaSR.locationId)) assert(ausShipping.cost() == 0.0) assert(ausShipping.estimatedMax() == 20.0) assert(ausShipping.estimatedMin() == 2.0) - assert(ausShipping.location()?.name() == australiaSR.locationName()) - assert(ausShipping.location()?.displayableName() == australiaSR.locationName()) - assert(ausShipping.location()?.country() == australiaSR.country()) + assert(ausShipping.location()?.name() == australiaSR.locationName) + assert(ausShipping.location()?.displayableName() == australiaSR.locationName) + assert(ausShipping.location()?.country() == australiaSR.country) - assert(nonDoubleValues.location()?.id() == decodeRelayId(forbiddenValues.locationId())) + assert(nonDoubleValues.location()?.id() == decodeRelayId(forbiddenValues.locationId)) assert(nonDoubleValues.cost() == 0.0) assert(nonDoubleValues.estimatedMax() == 0.0) assert(nonDoubleValues.estimatedMin() == 0.0) - assert(nonDoubleValues.location()?.name() == forbiddenValues.locationName()) - assert(nonDoubleValues.location()?.displayableName() == forbiddenValues.locationName()) - assert(nonDoubleValues.location()?.country() == forbiddenValues.country()) + assert(nonDoubleValues.location()?.name() == forbiddenValues.locationName) + assert(nonDoubleValues.location()?.displayableName() == forbiddenValues.locationName) + assert(nonDoubleValues.location()?.country() == forbiddenValues.country) } /** @@ -252,34 +250,30 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { * Mock of a rewardFragment received from GraphQL data types */ val fragmentReward = Reward( - "Reward", "UmV3YXJkLTk2NTM3NzY", "Stormgate Supporter", 452, "Some reward description here", DateTime.now().toDate(), true, - Reward.Amount("Amount", Reward.Amount.Fragments(Amount("Money", "20.0", null, null))), + Reward.Amount("Amount", Amount("20.0", null, null)), Reward.PledgeAmount( - "PledgeAmount", - Reward.PledgeAmount.Fragments(Amount("Money", "10.0", null, null)) + "PledgeAmount", Amount("10.0", null, null) ), Reward.LatePledgeAmount( - "LatePledgeAmount", - Reward.LatePledgeAmount.Fragments(Amount("Money", "30.0", null, null)) + "LatePledgeAmount", Amount("30.0", null, null) ), Reward.ConvertedAmount( - "ConvertedAmount", - Reward.ConvertedAmount.Fragments(Amount("Money", "30.0", null, null)) + "ConvertedAmount", Amount("30.0", null, null) ), - ShippingPreference.UNRESTRICTED, + ShippingPreference.unrestricted, 3, 3, 3, DateTime.now().minusDays(50), DateTime.now().plusDays(50), - RewardType.BASE, - AllowedAddons("RewardConnection", listOf(Reward.Node("Reward", "UmV3YXJkLTk3MDA2NjA"))), + RewardType.base, + AllowedAddons(listOf(Reward.Node("UmV3YXJkLTk3MDA2NjA"))), null, ) @@ -287,7 +281,6 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { fun `test rewardTransformer returns appropriate shippingRules field when querying for simpleShippingRulesExpanded`() { val canadaSimpleSR = FetchProjectRewardsQuery.SimpleShippingRulesExpanded( - "SimpleShippingRule", "17.34562379823645234875620384756203847234", "CA", null, @@ -297,7 +290,6 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { ) val australiaSR = FetchProjectRewardsQuery.SimpleShippingRulesExpanded( - "SimpleShippingRule", "0", "AU", "20", // - Shipping Rule disable at shipping, cost = 0, estimated range max/min values not null @@ -312,7 +304,7 @@ class GraphQLTransformersTest : KSRobolectricTestCase() { ) assertTrue(reward.shippingRules()?.size == 2) - assertTrue(reward.shippingRules()?.first()?.id() == decodeRelayId(canadaSimpleSR.locationId())) - assertTrue(reward.shippingRules()?.last()?.id() == decodeRelayId(australiaSR.locationId())) + assertTrue(reward.shippingRules()?.first()?.id() == decodeRelayId(canadaSimpleSR.locationId)) + assertTrue(reward.shippingRules()?.last()?.id() == decodeRelayId(australiaSR.locationId)) } } diff --git a/app/src/test/java/com/kickstarter/ui/activities/compose/PreLaunchProjectPageScreenTest.kt b/app/src/test/java/com/kickstarter/ui/activities/compose/PreLaunchProjectPageScreenTest.kt index e051f478e3..9f9ec22e03 100644 --- a/app/src/test/java/com/kickstarter/ui/activities/compose/PreLaunchProjectPageScreenTest.kt +++ b/app/src/test/java/com/kickstarter/ui/activities/compose/PreLaunchProjectPageScreenTest.kt @@ -7,10 +7,8 @@ import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick -import com.apollographql.apollo.api.CustomTypeValue import com.kickstarter.KSRobolectricTestCase import com.kickstarter.R -import com.kickstarter.libs.graphql.DateTimeAdapter import com.kickstarter.mock.factories.ProjectFactory import com.kickstarter.models.Urls import com.kickstarter.ui.activities.compose.PreLaunchProjectPageScreenTestTag.COMING_SOON_BADGE @@ -22,6 +20,7 @@ import com.kickstarter.ui.activities.compose.PreLaunchProjectPageScreenTestTag.P import com.kickstarter.ui.activities.compose.PreLaunchProjectPageScreenTestTag.PROJECT_LOCATION_NAME import com.kickstarter.ui.activities.compose.PreLaunchProjectPageScreenTestTag.PROJECT_NAME import com.kickstarter.ui.activities.compose.PreLaunchProjectPageScreenTestTag.PROJECT_SAVE_BUTTON +import org.joda.time.DateTime import org.junit.Test class PreLaunchProjectPageScreenTest : KSRobolectricTestCase() { @@ -59,9 +58,7 @@ class PreLaunchProjectPageScreenTest : KSRobolectricTestCase() { @Test fun verifyOnSaveButtonClicked() { val project = ProjectFactory.project().toBuilder() - .launchedAt( - DateTimeAdapter().decode(CustomTypeValue.fromRawValue(0)) - ) + .launchedAt(DateTime(0)) .displayPrelaunch(true) .watchesCount(1) .urls(Urls.builder().build()).build() diff --git a/app/src/test/java/com/kickstarter/viewmodels/AccountViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/AccountViewModelTest.kt index 3d40e279e4..40139142b7 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/AccountViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/AccountViewModelTest.kt @@ -1,18 +1,18 @@ package com.kickstarter.viewmodels -import UpdateUserCurrencyMutation import com.kickstarter.KSRobolectricTestCase +import com.kickstarter.UpdateUserCurrencyMutation import com.kickstarter.libs.Environment import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.mock.services.MockApolloClientV2 import com.kickstarter.models.UserPrivacy +import com.kickstarter.type.CurrencyCode import com.kickstarter.viewmodels.AccountViewModel.AccountViewModel import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subscribers.TestSubscriber import org.junit.After import org.junit.Test -import type.CurrencyCode class AccountViewModelTest : KSRobolectricTestCase() { @@ -88,7 +88,7 @@ class AccountViewModelTest : KSRobolectricTestCase() { return Observable.just( UpdateUserCurrencyMutation.Data( UpdateUserCurrencyMutation - .UpdateUserProfile("", UpdateUserCurrencyMutation.User("", currency.rawValue())) + .UpdateUserProfile(UpdateUserCurrencyMutation.User(currency.rawValue)) ) ) } @@ -97,10 +97,10 @@ class AccountViewModelTest : KSRobolectricTestCase() { this.chosenCurrency.assertValue("USD") this.vm.inputs.onSelectedCurrency(CurrencyCode.AUD) - this.chosenCurrency.assertValues("USD", CurrencyCode.AUD.rawValue()) - this.success.assertValue(CurrencyCode.AUD.rawValue()) + this.chosenCurrency.assertValues("USD", CurrencyCode.AUD.rawValue) + this.success.assertValue(CurrencyCode.AUD.rawValue) this.vm.inputs.onSelectedCurrency(CurrencyCode.AUD) - this.chosenCurrency.assertValues("USD", CurrencyCode.AUD.rawValue()) + this.chosenCurrency.assertValues("USD", CurrencyCode.AUD.rawValue) } @Test diff --git a/app/src/test/java/com/kickstarter/viewmodels/ChangeEmailViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/ChangeEmailViewModelTest.kt index 40c827bca7..07f054b9e4 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/ChangeEmailViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/ChangeEmailViewModelTest.kt @@ -1,9 +1,9 @@ package com.kickstarter.viewmodels -import SendEmailVerificationMutation -import UpdateUserEmailMutation import com.kickstarter.KSRobolectricTestCase import com.kickstarter.R +import com.kickstarter.SendEmailVerificationMutation +import com.kickstarter.UpdateUserEmailMutation import com.kickstarter.libs.Environment import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.mock.services.MockApolloClientV2 @@ -224,7 +224,7 @@ class ChangeEmailViewModelTest : KSRobolectricTestCase() { return Observable.just( SendEmailVerificationMutation.Data( SendEmailVerificationMutation - .UserSendEmailVerification("", "1234") + .UserSendEmailVerification("1234") ) ) } @@ -268,8 +268,7 @@ class ChangeEmailViewModelTest : KSRobolectricTestCase() { UpdateUserEmailMutation.Data( UpdateUserEmailMutation .UpdateUserAccount( - "", - UpdateUserEmailMutation.User("", "", email) + UpdateUserEmailMutation.User("", email) ) ) ) diff --git a/app/src/test/java/com/kickstarter/viewmodels/ChangePasswordViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/ChangePasswordViewModelTest.kt index 0994c45588..9755c8ca67 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/ChangePasswordViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/ChangePasswordViewModelTest.kt @@ -1,7 +1,7 @@ package com.kickstarter.viewmodels -import UpdateUserPasswordMutation import com.kickstarter.KSRobolectricTestCase +import com.kickstarter.UpdateUserPasswordMutation import com.kickstarter.libs.AnalyticEvents import com.kickstarter.libs.Environment import com.kickstarter.libs.MockCurrentUserV2 @@ -93,8 +93,7 @@ class ChangePasswordViewModelTest : KSRobolectricTestCase() { return Observable.just( UpdateUserPasswordMutation.Data( UpdateUserPasswordMutation.UpdateUserAccount( - "", - UpdateUserPasswordMutation.User("", "test@email.com", false, false) + UpdateUserPasswordMutation.User("test@email.com", false, false) ) ) ) @@ -167,8 +166,7 @@ class ChangePasswordViewModelTest : KSRobolectricTestCase() { return Observable.just( UpdateUserPasswordMutation.Data( UpdateUserPasswordMutation.UpdateUserAccount( - "", - UpdateUserPasswordMutation.User("", "new22test@email.com", false, false) + UpdateUserPasswordMutation.User("new22test@email.com", false, false) ) ) ) diff --git a/app/src/test/java/com/kickstarter/viewmodels/CommentsViewHolderViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/CommentsViewHolderViewModelTest.kt index 589f79b30e..4b65f6eb10 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/CommentsViewHolderViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/CommentsViewHolderViewModelTest.kt @@ -11,6 +11,7 @@ import com.kickstarter.mock.factories.UserFactory import com.kickstarter.mock.services.MockApolloClientV2 import com.kickstarter.models.Comment import com.kickstarter.services.mutations.PostCommentData +import com.kickstarter.type.CommentBadge import com.kickstarter.ui.data.CommentCardData import com.kickstarter.ui.views.CommentCardBadge import com.kickstarter.ui.views.CommentCardStatus @@ -22,7 +23,6 @@ import io.reactivex.subscribers.TestSubscriber import org.joda.time.DateTime import org.junit.After import org.junit.Test -import type.CommentBadge import java.util.concurrent.TimeUnit class CommentsViewHolderViewModelTest : KSRobolectricTestCase() { @@ -664,7 +664,7 @@ class CommentsViewHolderViewModelTest : KSRobolectricTestCase() { @Test fun commentBadge_whenYouAndSuperbacker_shouldEmitSuperbacker() { - val authorBadges = listOf(CommentBadge.SUPERBACKER.rawValue()) + val authorBadges = listOf(CommentBadge.superbacker.rawValue) val author = UserFactory.user().toBuilder().id(1).build() val currentUser = UserFactory.user().toBuilder().id(1).build() val environment = environment().toBuilder() @@ -692,7 +692,7 @@ class CommentsViewHolderViewModelTest : KSRobolectricTestCase() { .build() setUpEnvironment(environment) - val authorBadges = listOf(CommentBadge.SUPERBACKER.rawValue(), CommentBadge.CREATOR.rawValue()) + val authorBadges = listOf(CommentBadge.superbacker.rawValue, CommentBadge.creator.rawValue) val author = UserFactory.user().toBuilder().id(2).build() val comment = CommentFactory.commentFromCurrentUser(author, authorBadges) val commentCardData = CommentCardData.builder() @@ -714,7 +714,7 @@ class CommentsViewHolderViewModelTest : KSRobolectricTestCase() { .build() setUpEnvironment(environment) - val authorBadges = listOf(CommentBadge.SUPERBACKER.rawValue()) + val authorBadges = listOf(CommentBadge.superbacker.rawValue) val author = UserFactory.user().toBuilder().id(2).build() val comment = CommentFactory.commentFromCurrentUser(author, authorBadges) val commentCardData = CommentCardData.builder() @@ -754,7 +754,7 @@ class CommentsViewHolderViewModelTest : KSRobolectricTestCase() { fun commentBadge_whenNotLoggedInAndCommentIsFromCreator_shouldEmitCreator() { setUpEnvironment(environment()) - val authorBadges = listOf(CommentBadge.SUPERBACKER.rawValue(), CommentBadge.CREATOR.rawValue()) + val authorBadges = listOf(CommentBadge.superbacker.rawValue, CommentBadge.creator.rawValue) val author = UserFactory.user().toBuilder().id(2).build() val comment = CommentFactory.commentFromCurrentUser(author, authorBadges) val commentCardData = CommentCardData.builder() diff --git a/app/src/test/java/com/kickstarter/viewmodels/CreatePasswordViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/CreatePasswordViewModelTest.kt index b1603690d5..752de790ca 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/CreatePasswordViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/CreatePasswordViewModelTest.kt @@ -1,6 +1,6 @@ package com.kickstarter.viewmodels -import CreatePasswordMutation +import com.kickstarter.CreatePasswordMutation import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.AnalyticEvents import com.kickstarter.libs.Environment @@ -69,8 +69,7 @@ class CreatePasswordViewModelTest : KSRobolectricTestCase() { return Observable.just( CreatePasswordMutation.Data( CreatePasswordMutation.UpdateUserAccount( - "", - CreatePasswordMutation.User("", "test@emai", true) + CreatePasswordMutation.User("test@emai", true) ) ) ) @@ -123,8 +122,7 @@ class CreatePasswordViewModelTest : KSRobolectricTestCase() { return Observable.just( CreatePasswordMutation.Data( CreatePasswordMutation.UpdateUserAccount( - "", - CreatePasswordMutation.User("", "test@emai", true) + CreatePasswordMutation.User("test@emai", true) ) ) ) diff --git a/app/src/test/java/com/kickstarter/viewmodels/CrowdfundCheckoutViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/CrowdfundCheckoutViewModelTest.kt index 3127f46be6..db69634de9 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/CrowdfundCheckoutViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/CrowdfundCheckoutViewModelTest.kt @@ -30,6 +30,7 @@ import com.kickstarter.models.StoredCard import com.kickstarter.models.UserPrivacy import com.kickstarter.services.mutations.CreateBackingData import com.kickstarter.services.mutations.UpdateBackingData +import com.kickstarter.type.CreditCardPaymentType import com.kickstarter.ui.ArgumentsKey import com.kickstarter.ui.SharedPreferenceKey import com.kickstarter.ui.data.CheckoutData @@ -50,7 +51,6 @@ import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import org.junit.Test import org.mockito.Mockito -import type.CreditCardPaymentType @OptIn(ExperimentalCoroutinesApi::class) class CrowdfundCheckoutViewModelTest : KSRobolectricTestCase() { diff --git a/app/src/test/java/com/kickstarter/viewmodels/PaymentMethodsViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/PaymentMethodsViewModelTest.kt index 7b1902e2bf..2b0134ce76 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/PaymentMethodsViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/PaymentMethodsViewModelTest.kt @@ -1,7 +1,7 @@ package com.kickstarter.viewmodels -import DeletePaymentSourceMutation import android.util.Pair +import com.kickstarter.DeletePaymentSourceMutation import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.Environment import com.kickstarter.mock.factories.StoredCardFactory diff --git a/app/src/test/java/com/kickstarter/viewmodels/PledgeFragmentViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/PledgeFragmentViewModelTest.kt index dfdb8ffeb6..541de5daa1 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/PledgeFragmentViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/PledgeFragmentViewModelTest.kt @@ -40,6 +40,7 @@ import com.kickstarter.models.StoredCard import com.kickstarter.services.apiresponses.ShippingRulesEnvelope import com.kickstarter.services.mutations.CreateBackingData import com.kickstarter.services.mutations.UpdateBackingData +import com.kickstarter.type.CreditCardTypes import com.kickstarter.ui.ArgumentsKey import com.kickstarter.ui.SharedPreferenceKey import com.kickstarter.ui.data.CardState @@ -60,7 +61,6 @@ import org.joda.time.DateTime import org.junit.After import org.junit.Test import org.mockito.Mockito -import type.CreditCardTypes import java.math.RoundingMode import java.net.CookieManager import java.util.Collections @@ -2538,7 +2538,7 @@ class PledgeFragmentViewModelTest : KSRobolectricTestCase() { .build() val backedProject = ProjectFactory.backedProject() .toBuilder() - .availableCardTypes(listOf(CreditCardTypes.VISA.rawValue())) + .availableCardTypes(listOf(CreditCardTypes.VISA.rawValue)) .backing(backing) .build() diff --git a/app/src/test/java/com/kickstarter/viewmodels/ProjectOverviewViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/ProjectOverviewViewModelTest.kt index 81ab96a007..1e96cc8df8 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/ProjectOverviewViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/ProjectOverviewViewModelTest.kt @@ -21,6 +21,7 @@ import com.kickstarter.mock.services.MockApolloClientV2 import com.kickstarter.models.CreatorDetails import com.kickstarter.models.Project import com.kickstarter.models.User +import com.kickstarter.type.FlaggingKind import com.kickstarter.ui.data.ProjectData import com.kickstarter.viewmodels.ReportProjectViewModel.Companion.COMMUNITY_GUIDELINES import com.kickstarter.viewmodels.ReportProjectViewModel.Companion.COMMUNITY_GUIDELINES_TAG @@ -34,7 +35,6 @@ import org.joda.time.DateTime import org.joda.time.DateTimeUtils import org.junit.After import org.junit.Test -import type.FlaggingKind import java.util.Arrays class ProjectOverviewViewModelTest : KSRobolectricTestCase() { @@ -625,7 +625,7 @@ class ProjectOverviewViewModelTest : KSRobolectricTestCase() { .build() setUpEnvironment(env, project(project)) - vm.inputs.refreshFlaggedState(FlaggingKind.NOT_PROJECT.rawValue()) + vm.inputs.refreshFlaggedState(FlaggingKind.NOT_PROJECT.rawValue) this.shouldShowProjectFlagged.assertValues(true, true) this.shouldShowReportProject.assertValues(false, false) } diff --git a/app/src/test/java/com/kickstarter/viewmodels/ReportProjectViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/ReportProjectViewModelTest.kt index 227cc05bdd..8753e81a3d 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/ReportProjectViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/ReportProjectViewModelTest.kt @@ -8,6 +8,7 @@ import com.kickstarter.mock.factories.ProjectFactory import com.kickstarter.mock.services.MockApolloClientV2 import com.kickstarter.models.Project import com.kickstarter.models.UserPrivacy +import com.kickstarter.type.FlaggingKind import com.kickstarter.ui.IntentKey import com.kickstarter.viewmodels.ReportProjectViewModel.Companion.COMMUNITY_GUIDELINES import com.kickstarter.viewmodels.ReportProjectViewModel.Companion.COMMUNITY_GUIDELINES_TAG @@ -18,7 +19,6 @@ import io.reactivex.disposables.CompositeDisposable import io.reactivex.subscribers.TestSubscriber import org.junit.After import org.junit.Test -import type.FlaggingKind class ReportProjectViewModelTest : KSRobolectricTestCase() { @@ -43,7 +43,7 @@ class ReportProjectViewModelTest : KSRobolectricTestCase() { details: String, flaggingKind: String ): Observable { - return Observable.just(FlaggingKind.SPAM.rawValue()) + return Observable.just(FlaggingKind.SPAM.rawValue) } }).build() @@ -90,10 +90,10 @@ class ReportProjectViewModelTest : KSRobolectricTestCase() { val project = ProjectFactory.project() setUpEnvironment(getEnvironment(), getBundle(project)) - vm.inputs.inputDetails(FlaggingKind.SPAM.rawValue()) - vm.inputs.kind(FlaggingKind.SPAM.rawValue()) + vm.inputs.inputDetails(FlaggingKind.SPAM.rawValue) + vm.inputs.kind(FlaggingKind.SPAM.rawValue) vm.inputs.createFlagging() - finish.assertValue(ReportProjectViewModel.ReportProjectViewModel.NavigationResult(true, FlaggingKind.SPAM.rawValue())) + finish.assertValue(ReportProjectViewModel.ReportProjectViewModel.NavigationResult(true, FlaggingKind.SPAM.rawValue)) } @Test diff --git a/app/src/test/java/com/kickstarter/viewmodels/RootCommentViewHolderViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/RootCommentViewHolderViewModelTest.kt index bb5bcb5eb2..81d254c166 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/RootCommentViewHolderViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/RootCommentViewHolderViewModelTest.kt @@ -6,6 +6,7 @@ import com.kickstarter.libs.MockCurrentUserV2 import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.mock.factories.CommentFactory import com.kickstarter.mock.factories.UserFactory +import com.kickstarter.type.CommentBadge import com.kickstarter.ui.data.CommentCardData import com.kickstarter.ui.views.CommentCardBadge import com.kickstarter.ui.views.CommentCardStatus @@ -13,7 +14,6 @@ import io.reactivex.disposables.CompositeDisposable import io.reactivex.subscribers.TestSubscriber import org.junit.After import org.junit.Test -import type.CommentBadge class RootCommentViewHolderViewModelTest : KSRobolectricTestCase() { private lateinit var vm: RootCommentViewHolderViewModel.ViewModel @@ -81,7 +81,7 @@ class RootCommentViewHolderViewModelTest : KSRobolectricTestCase() { @Test fun commentBadge_whenYouAndSuperbacker_shouldEmitSuperbacker() { - val authorBadges = listOf(CommentBadge.SUPERBACKER.rawValue()) + val authorBadges = listOf(CommentBadge.superbacker.rawValue) val author = UserFactory.user().toBuilder().id(1).build() val currentUser = UserFactory.user().toBuilder().id(1).build() val environment = environment().toBuilder() @@ -108,7 +108,7 @@ class RootCommentViewHolderViewModelTest : KSRobolectricTestCase() { .build() setupEnvironment(environment) - val authorBadges = listOf(CommentBadge.SUPERBACKER.rawValue()) + val authorBadges = listOf(CommentBadge.superbacker.rawValue) val author = UserFactory.user().toBuilder().id(2).build() val comment = CommentFactory.commentFromCurrentUser(author, authorBadges) val commentCardData = CommentCardData.builder() @@ -130,8 +130,8 @@ class RootCommentViewHolderViewModelTest : KSRobolectricTestCase() { setupEnvironment(environment) val authorBadges = listOf( - CommentBadge.SUPERBACKER.rawValue(), - CommentBadge.COLLABORATOR.rawValue() + CommentBadge.superbacker.rawValue, + CommentBadge.collaborator.rawValue ) val author = UserFactory.user().toBuilder().id(2).build() val comment = CommentFactory.commentFromCurrentUser(author, authorBadges) @@ -170,7 +170,7 @@ class RootCommentViewHolderViewModelTest : KSRobolectricTestCase() { fun commentBadge_whenNotLoggedInAndCommentIsFromCreator_shouldEmitCreator() { setupEnvironment(environment()) val authorBadges = - listOf(CommentBadge.SUPERBACKER.rawValue(), CommentBadge.CREATOR.rawValue()) + listOf(CommentBadge.superbacker.rawValue, CommentBadge.creator.rawValue) val author = UserFactory.user().toBuilder().id(2).build() val comment = CommentFactory.commentFromCurrentUser(author, authorBadges) val commentCardData = CommentCardData.builder() diff --git a/app/src/test/java/com/kickstarter/viewmodels/SetPasswordViewModelTest.kt b/app/src/test/java/com/kickstarter/viewmodels/SetPasswordViewModelTest.kt index 7c19f1b63c..01838f7b53 100644 --- a/app/src/test/java/com/kickstarter/viewmodels/SetPasswordViewModelTest.kt +++ b/app/src/test/java/com/kickstarter/viewmodels/SetPasswordViewModelTest.kt @@ -1,8 +1,8 @@ package com.kickstarter.viewmodels -import UpdateUserPasswordMutation import android.content.Intent import com.kickstarter.KSRobolectricTestCase +import com.kickstarter.UpdateUserPasswordMutation import com.kickstarter.libs.Environment import com.kickstarter.libs.MockCurrentUserV2 import com.kickstarter.libs.utils.extensions.addToDisposable @@ -105,8 +105,7 @@ class SetPasswordViewModelTest : KSRobolectricTestCase() { return Observable.just( UpdateUserPasswordMutation.Data( UpdateUserPasswordMutation.UpdateUserAccount( - "", - UpdateUserPasswordMutation.User("", "test@email.com", false, true) + UpdateUserPasswordMutation.User("test@email.com", false, true) ) ) )