diff --git a/.github/workflows/feature_branch_ci.yml b/.github/workflows/feature_branch_ci.yml new file mode 100644 index 0000000000..7dcf639542 --- /dev/null +++ b/.github/workflows/feature_branch_ci.yml @@ -0,0 +1,34 @@ +name: Workflow for feature branches + +on: + push: + branches: + - '*' + - '!development' + - '!master' + +jobs: + build: + name: Build APK + runs-on: ubuntu-latest + steps: + - name: Checking out repository + uses: actions/checkout@v2 + + # Set up JDK + - name: Set Up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + + # Install NDK + - name: Install NDK + run: echo "y" | sudo ${ANDROID_HOME}/tools/bin/sdkmanager --install "ndk;20.0.5594570" --sdk_root=${ANDROID_SDK_ROOT} + + # Update Gradle Permission + - name: Change gradlew Permission + run: chmod +x gradlew + + # Build App + - name: Build with Gradle + run: ./gradlew assemble \ No newline at end of file diff --git a/.github/workflows/master_dev_ci.yml b/.github/workflows/master_dev_ci.yml new file mode 100644 index 0000000000..4351df81c3 --- /dev/null +++ b/.github/workflows/master_dev_ci.yml @@ -0,0 +1,75 @@ +name: Workflow for master/development branches + +on: + pull_request: + push: + branches: + - 'development' + - 'master' + +jobs: + build: + name: Build APK + runs-on: ubuntu-latest + steps: + - name: Checking out repository + uses: actions/checkout@v2 + + # Set up JDK + - name: Set Up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + + # Install NDK + - name: Install NDK + run: echo "y" | sudo ${ANDROID_HOME}/tools/bin/sdkmanager --install "ndk;20.0.5594570" --sdk_root=${ANDROID_SDK_ROOT} + + # Update Gradle Permission + - name: Change gradlew Permission + run: chmod +x gradlew + + # Build App + - name: Build with Gradle + run: ./gradlew assemble + + # Upload Built APK + - name: Upload Build Artifacts + uses: actions/upload-artifact@v2.2.0 + with: + name: mifos-mobile + path: app/build/outputs/apk/debug/ + + lintCheck: + name: Static Analysis + runs-on: ubuntu-latest + steps: + - name: Checking out repository + uses: actions/checkout@v2 + + - name: Static Analysis + run: ./gradlew lint + + - name: Upload Static Analysis Report For Mifos-Mobile Module + uses: actions/upload-artifact@v2.2.0 + if: failure() + with: + name: Static Analysis Report + path: app/build/reports/ + + pmd: + name: PMD + runs-on: ubuntu-latest + steps: + - name: Checking out repository + uses: actions/checkout@v2 + + - name: PMD Check + run: ./gradlew pmd + + - name: Upload PMD Report + uses: actions/upload-artifact@v2.2.0 + if: failure() + with: + name: PMD Report + path: app/build/reports/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 8bc1e32d59..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,31 +0,0 @@ -language: android -jdk: oraclejdk8 -sudo: required -android: - components: - - tools - - extra-android-support - - extra-google-google_play_services - - extra-android-m2repository - - extra-google-m2repository - - build-tools-28.0.3 - - android-28 - - android-22 - - sys-img-armeabi-v7a-android-22 - -before_script: - - echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a - - emulator -avd test -no-skin -no-audio -no-window & - - android-wait-for-emulator - - adb shell input keyevent 82 & - -script: "./gradlew build connectedAndroidTest --stacktrace" - -# gitter integration -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/6c1aa14ed3a3ccb5bc92 - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: never # options: [always|never|change] default: always \ No newline at end of file diff --git a/README.md b/README.md index 011a5d27cd..6568587f9f 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ # Mifos-Mobile Android Application for MifosX -An Android Application built on top of the MifosX Self-Service platform for end-user customers to view/transact on the accounts and loans they hold. Data visible to customers will be a sub-set of what staff can see. This is a native Android Application written in Java with POJO classes in Kotlin. +An Android Application built on top of the MifosX Self-Service platform for end-user customers to view/transact on the accounts and loans they hold. Data visible to customers will be a sub-set of what staff can see. This is a native Android Application written in Kotlin. ### Status -[![Join the chat at https://gitter.im/openMF/self-service-app](https://badges.gitter.im/openMF/self-service-app.svg)](https://gitter.im/openMF/self-service-app?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Build Status](https://travis-ci.org/openMF/mifos-mobile.svg?branch=development)](https://travis-ci.org/openMF/mifos-mobile) - +| Master | Development | Chat | +|------------|-----------------|-----------------| +| ![Mifos-Mobile CI[Master/Dev]](https://github.com/openMF/mifos-mobile/workflows/Mifos-Mobile%20CI%5BMaster/Dev%5D/badge.svg?branch=master) | ![Mifos-Mobile CI[Master/Dev]](https://github.com/openMF/mifos-mobile/workflows/Mifos-Mobile%20CI%5BMaster/Dev%5D/badge.svg?branch=development) |[![Join the chat at https://gitter.im/openMF/self-service-app](https://badges.gitter.im/openMF/self-service-app.svg)](https://gitter.im/openMF/self-service-app?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)| ## Screenshots @@ -29,7 +29,7 @@ We have the following branches : * **development** All the contributions should be pushed to this branch. If you're making a contribution, you are supposed to make a pull request to _development_. - Please make sure it passes a build check on Travis. + Please make sure it passes a build check on Github Workflows CI. It is advisable to clone only the development branch using the following command: @@ -42,6 +42,12 @@ We have the following branches : * **master** The master branch contains all the stable and bug-free working code. The development branch once complete will be merged with this branch. +To get the latest apk of master/development branch from Github Artifacts, follow these steps: +1. Go to to the [Actions](https://github.com/openMF/mifos-mobile/actions) tab of this repository. +2. Select the latest workflow for master/development branch. +3. Click on hyperlink 'mifos-mobile' in Artifacts section. +4. Extract the downloaded file and get the apk. + ## Development Setup Before you begin, you should have already downloaded the Android Studio SDK and set it up correctly. You can find a guide on how to do this here: [Setting up Android Studio](http://developer.android.com/sdk/installing/index.html?pkg=studio). @@ -68,3 +74,6 @@ View the [wiki](https://github.com/openMF/self-service-app/wiki) to see pages th See the [requirements](https://github.com/openMF/self-service-app/wiki/Design-&-Requirements) for an initial design mockup and documentation on the Fineract API. +## Note + +The UI design is currently being revamped. New design can be found [here](https://docs.google.com/presentation/d/1yFR19vGlKW-amxzGms8TgPzd1jWkrALPFcaC85EyYpw/edit#slide=id.g6c6ccd991d_0_42) diff --git a/app/build.gradle b/app/build.gradle index a1184bde95..a2e9aa177c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -3,12 +3,14 @@ apply plugin: 'io.fabric' apply plugin: 'com.google.gms.oss.licenses.plugin' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' +apply plugin: 'kotlin-kapt' apply from: '../config/quality/quality.gradle' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion + ndkVersion rootProject.ext.ndkVersion defaultConfig { applicationId "org.mifos.mobile" @@ -76,7 +78,7 @@ dependencies { implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0' - annotationProcessor "com.github.Raizlabs.DBFlow:dbflow-processor:$rootProject.dbflowVersion" + kapt "com.github.Raizlabs.DBFlow:dbflow-processor:$rootProject.dbflowVersion" implementation "com.github.Raizlabs.DBFlow:dbflow-core:$rootProject.dbflowVersion" implementation "com.github.Raizlabs.DBFlow:dbflow:$rootProject.dbflowVersion" @@ -95,7 +97,7 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" //Square dependencies - implementation('com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion') { + implementation("com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion") { // exclude Retrofit’s OkHttp peer-dependency module and define your own module import exclude module: 'okhttp' } @@ -109,17 +111,20 @@ dependencies { implementation "io.reactivex.rxjava2:rxjava:$rootProject.rxjavaVersion" //Dagger dependencies - annotationProcessor "com.google.dagger:dagger-compiler:$rootProject.daggerVersion" + kapt "com.google.dagger:dagger-compiler:$rootProject.daggerVersion" implementation "com.google.dagger:dagger:$rootProject.daggerVersion" compileOnly 'javax.annotation:jsr250-api:1.0' //Required by Dagger2 //Butter Knife - implementation "com.jakewharton:butterknife:$rootProject.butterKnifeVersion" - annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.butterKnifeVersion" + implementation "com.jakewharton:butterknife:$butterKnifeVersion" + kapt "com.jakewharton:butterknife-compiler:$butterKnifeVersion" implementation('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') { transitive = true } + //Annotation library + implementation "androidx.annotation:annotation:$rootProject.annotationLibraryVersion" + //qr code implementation "com.google.zxing:core:$rootProject.zxingcoreVersion" implementation "me.dm7.barcodescanner:zxing:$rootProject.zxingbarcodescannerVersion" @@ -132,7 +137,7 @@ dependencies { //multidex implementation "androidx.multidex:multidex:$rootProject.multiDexVersion" - + //TableView implementation "com.evrencoskun.library:tableview:$rootProject.tableViewVersion" @@ -155,4 +160,4 @@ dependencies { androidTestImplementation "androidx.test:runner:$rootProject.runnerVersion" androidTestImplementation "androidx.test:rules:$rootProject.rulesVersion" } -apply plugin: 'com.google.gms.google-services' +apply plugin: 'com.google.gms.google-services' \ No newline at end of file diff --git a/app/src/androidTest/java/org/mifos/mobile/ApplicationTest.java b/app/src/androidTest/java/org/mifos/mobile/ApplicationTest.java deleted file mode 100644 index adb323d113..0000000000 --- a/app/src/androidTest/java/org/mifos/mobile/ApplicationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import androidx.test.InstrumentationRegistry; -import androidx.test.runner.AndroidJUnit4; - -import static org.junit.Assert.assertEquals; - -/** - * Testing Fundamentals - */ -@RunWith(AndroidJUnit4.class) -public class ApplicationTest { - - @Test - public void useAppContext() { - // Context of the app under test. - Context appContext = InstrumentationRegistry.getTargetContext(); - assertEquals("org.mifos.mobile", appContext.getPackageName()); - } -} diff --git a/app/src/androidTest/java/org/mifos/mobile/ApplicationTest.kt b/app/src/androidTest/java/org/mifos/mobile/ApplicationTest.kt new file mode 100644 index 0000000000..03b73753c4 --- /dev/null +++ b/app/src/androidTest/java/org/mifos/mobile/ApplicationTest.kt @@ -0,0 +1,21 @@ +package org.mifos.mobile + +import androidx.test.InstrumentationRegistry +import androidx.test.runner.AndroidJUnit4 + +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith + +/** + * [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html) + */ +@RunWith(AndroidJUnit4::class) +class ApplicationTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getTargetContext() + Assert.assertEquals("org.mifos.mobile", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/commonTest/java/org/mifos/mobile/FakeJsonName.java b/app/src/commonTest/java/org/mifos/mobile/FakeJsonName.java deleted file mode 100644 index 80a9dc1439..0000000000 --- a/app/src/commonTest/java/org/mifos/mobile/FakeJsonName.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.mifos.mobile; - -/** - * Created by dilpreet on 26/6/17. - */ - -public class FakeJsonName { - - public static final String ACCOUNT_OPTION_TEMPLATE = "accountOptionTemplate.json"; - - public static final String CLIENT_ACCOUNTS_JSON = "clientAccounts.json"; - - public static final String CLIENT_SAVINGS_ACCOUNT_JSON = "clientSavingsAccounts.json"; - - public static final String CLIENT_LOAN_ACCOUNT_JSON = "clientLoanAccounts.json"; - - public static final String CLIENT_SHARE_ACCOUNT_JSON = "clientShareAccounts.json"; - - public static final String BENEFICIARIES_JSON = "beneficiaries.json"; - - public static final String BENEFICIARY_TEMPLATE_JSON = "beneficiaryTemplate.json"; - - public static final String BENEFICIARY_PAYLOAD_JSON = "beneficiaryPayload.json"; - - public static final String BENEFICIARY_UPDATE_PAYLOAD_JSON = "beneficiaryUpdatePayload.json"; - - public static final String LOAN_ACCOUNT_JSON = "loanAccount.json"; - - public static final String LOAN_PAYLOAD_JSON = "loanPayload.json"; - - public static final String LOAN_TEMPLATE_JSON = "loanTemplate.json"; - - public static final String LOAN_TEMPLATE_BY_PRODUCT_JSON = "loanTemplateByProduct.json"; - - public static final String LOAN_ACCOUNT_WITH_TRANSACTIONS_JSON = - "loanAccountWithTransactions.json"; - - public static final String LOAN_ACCOUNT_WITH_EMPTY_TRANSACTIONS_JSON = - "loanAccountWithEmptyTransactions.json"; - - public static final String LOAN_ACCOUNT_WITH_REPAYMENT_SCHEDULE_JSON = - "loanAccountWithRepaymentSchedule.json"; - - public static final String LOAN_ACCOUNT_WITH_EMPTY_REPAYMENT_SCHEDULE_JSON = - "loanAccountWithEmptyRepaymentSchedule.json"; - - public static final String CLIENTS_JSON = "clients.json"; - - public static final String CLIENTS_NOT_FOUND_JSON = "clientsNotFound.json"; - - public static final String USER_JSON = "user.json"; - - public static final String TRANSACTIONS_JSON = "transactions.json"; - - public static final String TRANFER_PAYLOAD_JSON = "transferPayload.json"; - - public static final String SAVINGS_WITH_ASSOCIATIONS = "SavingsAccountWithAssociations.json"; - - public static final String REGISTER = "register.json"; - - public static final String CHARGE = "charge.json"; - - public static final String SAVING_CHARGE = "savingCharge.json"; - - public static final String LOAN_CHARGE = "loanCharge.json"; - - public static final String USER_VERIFY_JSON = "userVerify.json"; - - public static final String GUARANTOR_TEMPLATE = "guarantorTemplate.json"; - - public static final String GUARANTOR_LIST = "guarantorList.json"; - - public static final String SAVINGS_ACCOUNT_TEMPLATE = "savingsAccountTemplate.json"; - - public static final String CLIENT_JSON = "client.json"; - - public static final String UPDATE_PASSWORD_PAYLOAD_JSON = "updatePasswordPayload.json"; -} diff --git a/app/src/commonTest/java/org/mifos/mobile/FakeJsonName.kt b/app/src/commonTest/java/org/mifos/mobile/FakeJsonName.kt new file mode 100644 index 0000000000..28b85bc9ac --- /dev/null +++ b/app/src/commonTest/java/org/mifos/mobile/FakeJsonName.kt @@ -0,0 +1,41 @@ +package org.mifos.mobile + +/** + * Created by dilpreet on 26/6/17. + */ +object FakeJsonName { + const val ACCOUNT_OPTION_TEMPLATE = "accountOptionTemplate.json" + const val CLIENT_ACCOUNTS_JSON = "clientAccounts.json" + const val CLIENT_SAVINGS_ACCOUNT_JSON = "clientSavingsAccounts.json" + const val CLIENT_LOAN_ACCOUNT_JSON = "clientLoanAccounts.json" + const val CLIENT_SHARE_ACCOUNT_JSON = "clientShareAccounts.json" + const val BENEFICIARIES_JSON = "beneficiaries.json" + const val BENEFICIARY_TEMPLATE_JSON = "beneficiaryTemplate.json" + const val BENEFICIARY_PAYLOAD_JSON = "beneficiaryPayload.json" + const val BENEFICIARY_UPDATE_PAYLOAD_JSON = "beneficiaryUpdatePayload.json" + const val LOGIN = "login.json" + const val LOAN_ACCOUNT_JSON = "loanAccount.json" + const val LOAN_PAYLOAD_JSON = "loanPayload.json" + const val LOAN_TEMPLATE_JSON = "loanTemplate.json" + const val LOAN_TEMPLATE_BY_PRODUCT_JSON = "loanTemplateByProduct.json" + const val LOAN_ACCOUNT_WITH_TRANSACTIONS_JSON = "loanAccountWithTransactions.json" + const val LOAN_ACCOUNT_WITH_EMPTY_TRANSACTIONS_JSON = "loanAccountWithEmptyTransactions.json" + const val LOAN_ACCOUNT_WITH_REPAYMENT_SCHEDULE_JSON = "loanAccountWithRepaymentSchedule.json" + const val LOAN_ACCOUNT_WITH_EMPTY_REPAYMENT_SCHEDULE_JSON = "loanAccountWithEmptyRepaymentSchedule.json" + const val CLIENTS_JSON = "clients.json" + const val CLIENTS_NOT_FOUND_JSON = "clientsNotFound.json" + const val USER_JSON = "user.json" + const val TRANSACTIONS_JSON = "transactions.json" + const val TRANFER_PAYLOAD_JSON = "transferPayload.json" + const val SAVINGS_WITH_ASSOCIATIONS = "SavingsAccountWithAssociations.json" + const val REGISTER = "register.json" + const val CHARGE = "charge.json" + const val SAVING_CHARGE = "savingCharge.json" + const val LOAN_CHARGE = "loanCharge.json" + const val USER_VERIFY_JSON = "userVerify.json" + const val GUARANTOR_TEMPLATE = "guarantorTemplate.json" + const val GUARANTOR_LIST = "guarantorList.json" + const val SAVINGS_ACCOUNT_TEMPLATE = "savingsAccountTemplate.json" + const val CLIENT_JSON = "client.json" + const val UPDATE_PASSWORD_PAYLOAD_JSON = "updatePasswordPayload.json" +} \ No newline at end of file diff --git a/app/src/commonTest/java/org/mifos/mobile/FakeRemoteDataSource.java b/app/src/commonTest/java/org/mifos/mobile/FakeRemoteDataSource.java deleted file mode 100644 index da159ce34d..0000000000 --- a/app/src/commonTest/java/org/mifos/mobile/FakeRemoteDataSource.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.mifos.mobile; - -import com.google.gson.reflect.TypeToken; - -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.Transaction; -import org.mifos.mobile.models.UpdatePasswordPayload; -import org.mifos.mobile.models.User; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.beneficiary.BeneficiaryPayload; -import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.client.ClientAccounts; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload; -import org.mifos.mobile.models.payload.LoansPayload; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.models.register.RegisterPayload; -import org.mifos.mobile.models.register.UserVerify; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; -import org.mifos.mobile.models.templates.loans.LoanTemplate; -import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate; - -import java.util.List; - -/** - * Created by dilpreet on 26/6/17. - */ - -public class FakeRemoteDataSource { - - private static TestDataFactory mTestDataFactory = new TestDataFactory(); - - public static ClientAccounts getClientAccounts() { - return mTestDataFactory.getListTypePojo(new TypeToken() { - }, FakeJsonName.CLIENT_ACCOUNTS_JSON); - } - - public static Client getCurrentClient() { - return mTestDataFactory.getObjectTypePojo(Client.class, - FakeJsonName.CLIENT_JSON); - } - - - public static ClientAccounts getClientSavingsAccount() { - return mTestDataFactory.getObjectTypePojo(ClientAccounts.class, - FakeJsonName.CLIENT_SAVINGS_ACCOUNT_JSON); - } - - public static ClientAccounts getClientLoanAccount() { - return mTestDataFactory.getObjectTypePojo(ClientAccounts.class, - FakeJsonName.CLIENT_LOAN_ACCOUNT_JSON); - } - - public static ClientAccounts getClientShareAccount() { - return mTestDataFactory.getObjectTypePojo(ClientAccounts.class, - FakeJsonName.CLIENT_SHARE_ACCOUNT_JSON); - } - - public static List getBeneficiaries() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.BENEFICIARIES_JSON); - } - - public static BeneficiaryTemplate getBeneficiaryTemplate() { - return mTestDataFactory.getObjectTypePojo(BeneficiaryTemplate.class, - FakeJsonName.BENEFICIARY_TEMPLATE_JSON); - } - - public static BeneficiaryPayload beneficiaryPayload() { - return mTestDataFactory.getObjectTypePojo(BeneficiaryPayload.class, - FakeJsonName.BENEFICIARY_PAYLOAD_JSON); - } - - public static BeneficiaryUpdatePayload beneficiaryUpdatePayload() { - return mTestDataFactory.getObjectTypePojo(BeneficiaryUpdatePayload.class, - FakeJsonName.BENEFICIARY_UPDATE_PAYLOAD_JSON); - } - - public static LoanAccount getLoanAccount() { - return mTestDataFactory.getObjectTypePojo(LoanAccount.class, - FakeJsonName.LOAN_ACCOUNT_JSON); - } - - public static LoanTemplate getLoanTemplate() { - return mTestDataFactory.getObjectTypePojo(LoanTemplate.class, - FakeJsonName.LOAN_TEMPLATE_JSON); - } - - public static LoansPayload getLoansPayload() { - return mTestDataFactory.getObjectTypePojo(LoansPayload.class, - FakeJsonName.LOAN_PAYLOAD_JSON); - } - - public static LoanTemplate getLoanTemplateByTemplate() { - return mTestDataFactory.getObjectTypePojo(LoanTemplate.class, - FakeJsonName.LOAN_TEMPLATE_BY_PRODUCT_JSON); - } - - public static LoanWithAssociations getLoanAccountWithTransaction() { - return mTestDataFactory.getObjectTypePojo(LoanWithAssociations.class, - FakeJsonName.LOAN_ACCOUNT_WITH_TRANSACTIONS_JSON); - } - - public static LoanWithAssociations getLoanAccountWithEmptyTransaction() { - return mTestDataFactory.getObjectTypePojo(LoanWithAssociations.class, - FakeJsonName.LOAN_ACCOUNT_WITH_EMPTY_TRANSACTIONS_JSON); - } - - public static LoanWithAssociations getLoanAccountRepaymentSchedule() { - return mTestDataFactory.getObjectTypePojo(LoanWithAssociations.class, - FakeJsonName.LOAN_ACCOUNT_WITH_REPAYMENT_SCHEDULE_JSON); - } - - public static LoanWithAssociations getLoanAccountEmptyRepaymentSchedule() { - return mTestDataFactory.getObjectTypePojo(LoanWithAssociations.class, - FakeJsonName.LOAN_ACCOUNT_WITH_EMPTY_REPAYMENT_SCHEDULE_JSON); - } - - public static User getUser() { - return mTestDataFactory.getObjectTypePojo(User.class, - FakeJsonName.USER_JSON); - } - - public static Page getClients() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.CLIENTS_JSON); - } - - public static Page getNoClients() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.CLIENTS_NOT_FOUND_JSON); - } - - public static Page getTransactions() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.TRANSACTIONS_JSON); - } - - public static SavingsWithAssociations getSavingsWithAssociations() { - return mTestDataFactory.getObjectTypePojo(SavingsWithAssociations.class, - FakeJsonName.SAVINGS_WITH_ASSOCIATIONS); - } - - public static AccountOptionsTemplate getAccountOptionsTemplate() { - return mTestDataFactory.getObjectTypePojo(AccountOptionsTemplate.class, - FakeJsonName.ACCOUNT_OPTION_TEMPLATE); - } - - public static TransferPayload getTransferPayload() { - return mTestDataFactory.getObjectTypePojo(TransferPayload.class, - FakeJsonName.TRANFER_PAYLOAD_JSON); - } - - - public static RegisterPayload getRegisterPayload() { - return mTestDataFactory.getObjectTypePojo(RegisterPayload.class, - FakeJsonName.REGISTER); - } - - public static Page getCharge() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.CHARGE); - } - - public static List getSavingsCharge() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.SAVING_CHARGE); - } - - public static List getLoanCharge() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.LOAN_CHARGE); - } - - public static UserVerify getUserVerify() { - return mTestDataFactory.getObjectTypePojo(UserVerify.class, - FakeJsonName.USER_VERIFY_JSON); - } - - public static GuarantorTemplatePayload getGuarantorTemplatePayload() { - return mTestDataFactory.getObjectTypePojo(GuarantorTemplatePayload.class, - FakeJsonName.GUARANTOR_TEMPLATE); - } - - public static List getGuarantorsList() { - return mTestDataFactory.getListTypePojo(new TypeToken>() { - }, FakeJsonName.GUARANTOR_LIST); - } - - public static SavingsAccountTemplate getSavingAccountApplicationTemplate() { - return mTestDataFactory.getObjectTypePojo(SavingsAccountTemplate.class, - FakeJsonName.SAVINGS_ACCOUNT_TEMPLATE); - - } - public static UpdatePasswordPayload getUpdatePasswordPayload() { - return mTestDataFactory.getObjectTypePojo(UpdatePasswordPayload.class, - FakeJsonName.UPDATE_PASSWORD_PAYLOAD_JSON); - - } -} diff --git a/app/src/commonTest/java/org/mifos/mobile/FakeRemoteDataSource.kt b/app/src/commonTest/java/org/mifos/mobile/FakeRemoteDataSource.kt new file mode 100644 index 0000000000..a837276de9 --- /dev/null +++ b/app/src/commonTest/java/org/mifos/mobile/FakeRemoteDataSource.kt @@ -0,0 +1,129 @@ +package org.mifos.mobile + +import com.google.gson.reflect.TypeToken + +import org.mifos.mobile.models.* +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.beneficiary.BeneficiaryPayload +import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload +import org.mifos.mobile.models.payload.LoansPayload +import org.mifos.mobile.models.payload.LoginPayload +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.models.register.RegisterPayload +import org.mifos.mobile.models.register.UserVerify +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate +import org.mifos.mobile.models.templates.loans.LoanTemplate +import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate + +/** + * Created by dilpreet on 26/6/17. + */ +object FakeRemoteDataSource { + private val mTestDataFactory = TestDataFactory() + val clientAccounts: ClientAccounts + get() = mTestDataFactory.getListTypePojo(object : TypeToken() {}, FakeJsonName.CLIENT_ACCOUNTS_JSON) + val currentClient: Client + get() = mTestDataFactory.getObjectTypePojo(Client::class.java, + FakeJsonName.CLIENT_JSON) + val clientSavingsAccount: ClientAccounts + get() = mTestDataFactory.getObjectTypePojo(ClientAccounts::class.java, + FakeJsonName.CLIENT_SAVINGS_ACCOUNT_JSON) + val clientLoanAccount: ClientAccounts + get() = mTestDataFactory.getObjectTypePojo(ClientAccounts::class.java, + FakeJsonName.CLIENT_LOAN_ACCOUNT_JSON) + val clientShareAccount: ClientAccounts + get() = mTestDataFactory.getObjectTypePojo(ClientAccounts::class.java, + FakeJsonName.CLIENT_SHARE_ACCOUNT_JSON) + val beneficiaries: List + get() = mTestDataFactory.getListTypePojo>(object : TypeToken?>() {}, FakeJsonName.BENEFICIARIES_JSON) + val beneficiaryTemplate: BeneficiaryTemplate + get() = mTestDataFactory.getObjectTypePojo(BeneficiaryTemplate::class.java, + FakeJsonName.BENEFICIARY_TEMPLATE_JSON) + + fun beneficiaryPayload(): BeneficiaryPayload { + return mTestDataFactory.getObjectTypePojo(BeneficiaryPayload::class.java, + FakeJsonName.BENEFICIARY_PAYLOAD_JSON) + } + + fun beneficiaryUpdatePayload(): BeneficiaryUpdatePayload { + return mTestDataFactory.getObjectTypePojo(BeneficiaryUpdatePayload::class.java, + FakeJsonName.BENEFICIARY_UPDATE_PAYLOAD_JSON) + } + + val loanAccount: LoanAccount + get() = mTestDataFactory.getObjectTypePojo(LoanAccount::class.java, + FakeJsonName.LOAN_ACCOUNT_JSON) + val loanTemplate: LoanTemplate + get() = mTestDataFactory.getObjectTypePojo(LoanTemplate::class.java, + FakeJsonName.LOAN_TEMPLATE_JSON) + val loansPayload: LoansPayload + get() = mTestDataFactory.getObjectTypePojo(LoansPayload::class.java, + FakeJsonName.LOAN_PAYLOAD_JSON) + val loanTemplateByTemplate: LoanTemplate + get() = mTestDataFactory.getObjectTypePojo(LoanTemplate::class.java, + FakeJsonName.LOAN_TEMPLATE_BY_PRODUCT_JSON) + val loanAccountWithTransaction: LoanWithAssociations + get() = mTestDataFactory.getObjectTypePojo(LoanWithAssociations::class.java, + FakeJsonName.LOAN_ACCOUNT_WITH_TRANSACTIONS_JSON) + val loanAccountWithEmptyTransaction: LoanWithAssociations + get() = mTestDataFactory.getObjectTypePojo(LoanWithAssociations::class.java, + FakeJsonName.LOAN_ACCOUNT_WITH_EMPTY_TRANSACTIONS_JSON) + val loanAccountRepaymentSchedule: LoanWithAssociations + get() = mTestDataFactory.getObjectTypePojo(LoanWithAssociations::class.java, + FakeJsonName.LOAN_ACCOUNT_WITH_REPAYMENT_SCHEDULE_JSON) + val loanAccountEmptyRepaymentSchedule: LoanWithAssociations + get() = mTestDataFactory.getObjectTypePojo(LoanWithAssociations::class.java, + FakeJsonName.LOAN_ACCOUNT_WITH_EMPTY_REPAYMENT_SCHEDULE_JSON) + val user: User + get() = mTestDataFactory.getObjectTypePojo(User::class.java, + FakeJsonName.USER_JSON) + val clients: Page? + get() = mTestDataFactory.getListTypePojo?>(object : TypeToken?>() {}, FakeJsonName.CLIENTS_JSON) + val noClients: Page? + get() = mTestDataFactory.getListTypePojo?>(object : TypeToken?>() {}, FakeJsonName.CLIENTS_NOT_FOUND_JSON) + val transactions: Page? + get() = mTestDataFactory.getListTypePojo?>(object : TypeToken?>() {}, FakeJsonName.TRANSACTIONS_JSON) + val savingsWithAssociations: SavingsWithAssociations + get() = mTestDataFactory.getObjectTypePojo(SavingsWithAssociations::class.java, + FakeJsonName.SAVINGS_WITH_ASSOCIATIONS) + val accountOptionsTemplate: AccountOptionsTemplate + get() = mTestDataFactory.getObjectTypePojo(AccountOptionsTemplate::class.java, + FakeJsonName.ACCOUNT_OPTION_TEMPLATE) + val transferPayload: TransferPayload + get() = mTestDataFactory.getObjectTypePojo(TransferPayload::class.java, + FakeJsonName.TRANFER_PAYLOAD_JSON) + val registerPayload: RegisterPayload + get() = mTestDataFactory.getObjectTypePojo(RegisterPayload::class.java, + FakeJsonName.REGISTER) + val loginPayload: LoginPayload + get() = mTestDataFactory.getObjectTypePojo(LoginPayload::class.java, + FakeJsonName.LOGIN) + val charge: Page? + get() = mTestDataFactory.getListTypePojo?>(object : TypeToken?>() {}, FakeJsonName.CHARGE) + val savingsCharge: List + get() = mTestDataFactory.getListTypePojo>(object : TypeToken?>() {}, FakeJsonName.SAVING_CHARGE) + val loanCharge: List + get() = mTestDataFactory.getListTypePojo>(object : TypeToken?>() {}, FakeJsonName.LOAN_CHARGE) + val userVerify: UserVerify + get() = mTestDataFactory.getObjectTypePojo(UserVerify::class.java, + FakeJsonName.USER_VERIFY_JSON) + val guarantorTemplatePayload: GuarantorTemplatePayload + get() = mTestDataFactory.getObjectTypePojo(GuarantorTemplatePayload::class.java, + FakeJsonName.GUARANTOR_TEMPLATE) + val guarantorsList: List + get() = mTestDataFactory.getListTypePojo>(object : TypeToken?>() {}, FakeJsonName.GUARANTOR_LIST) + val savingAccountApplicationTemplate: SavingsAccountTemplate + get() = mTestDataFactory.getObjectTypePojo(SavingsAccountTemplate::class.java, + FakeJsonName.SAVINGS_ACCOUNT_TEMPLATE) + val updatePasswordPayload: UpdatePasswordPayload + get() = mTestDataFactory.getObjectTypePojo(UpdatePasswordPayload::class.java, + FakeJsonName.UPDATE_PASSWORD_PAYLOAD_JSON) +} \ No newline at end of file diff --git a/app/src/commonTest/java/org/mifos/mobile/RetrofitUtils.java b/app/src/commonTest/java/org/mifos/mobile/RetrofitUtils.java deleted file mode 100644 index d4c816c7e0..0000000000 --- a/app/src/commonTest/java/org/mifos/mobile/RetrofitUtils.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifos.mobile; - -import okhttp3.MediaType; -import okhttp3.ResponseBody; -import retrofit2.HttpException; -import retrofit2.Response; - -/** - * Created by dilpreet on 29/7/17. - */ - -public class RetrofitUtils { - - public static Exception get404Exception() { - return new HttpException(Response.error(404, ResponseBody.create(MediaType. - parse("application/json"), "Not Found"))); - } - - public static Exception get401Exception() { - return new HttpException(Response.error(401, ResponseBody.create(MediaType. - parse("application/json"), "UnAuthorized"))); - } - -} diff --git a/app/src/commonTest/java/org/mifos/mobile/RetrofitUtils.kt b/app/src/commonTest/java/org/mifos/mobile/RetrofitUtils.kt new file mode 100644 index 0000000000..5358ca218f --- /dev/null +++ b/app/src/commonTest/java/org/mifos/mobile/RetrofitUtils.kt @@ -0,0 +1,19 @@ +package org.mifos.mobile + +import okhttp3.MediaType +import okhttp3.ResponseBody +import retrofit2.HttpException +import retrofit2.Response + +/** + * Created by dilpreet on 29/7/17. + */ +object RetrofitUtils { + fun get404Exception(): Exception { + return HttpException(Response.error(404, ResponseBody.create(MediaType.parse("application/json"), "Not Found"))) + } + + fun get401Exception(): Exception { + return HttpException(Response.error(401, ResponseBody.create(MediaType.parse("application/json"), "UnAuthorized"))) + } +} \ No newline at end of file diff --git a/app/src/commonTest/java/org/mifos/mobile/TestDataFactory.java b/app/src/commonTest/java/org/mifos/mobile/TestDataFactory.kt similarity index 57% rename from app/src/commonTest/java/org/mifos/mobile/TestDataFactory.java rename to app/src/commonTest/java/org/mifos/mobile/TestDataFactory.kt index a91cc8d88c..e045f80a3b 100644 --- a/app/src/commonTest/java/org/mifos/mobile/TestDataFactory.java +++ b/app/src/commonTest/java/org/mifos/mobile/TestDataFactory.kt @@ -1,22 +1,19 @@ -package org.mifos.mobile; +package org.mifos.mobile -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import com.google.gson.stream.JsonReader -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.InputStreamReader /** * Created by dilpreet on 26/6/17. */ - -public class TestDataFactory { - - +class TestDataFactory { /** * Note : This Generic Method DeSerialize Only Json Object in POJO - *

+ * + * * Note : Do Not use Array [] in POJO classes for of any element initialization, * Use Instead ArrayList. * @@ -25,23 +22,21 @@ public class TestDataFactory { * @param Return type * @return Return the Object Type model by Deserializing the Json of resources * @Example Of Deserializing Object Type Json - *

+ * + * * Object object = mTestDataFactory.getListTypePojo( * new TypeToken(){}, "Object.json") - */ - public T getObjectTypePojo(Class model, String jsonName) { - - InputStream in = getClass().getClassLoader().getResourceAsStream(jsonName); - JsonReader reader = new JsonReader(new InputStreamReader(in)); - T jsonModel = new Gson().fromJson(reader, model); - return jsonModel; - + */ + fun getObjectTypePojo(model: Class?, jsonName: String?): T { + val `in` = javaClass.classLoader?.getResourceAsStream(jsonName) + val reader = JsonReader(InputStreamReader(`in`)) + return Gson().fromJson(reader, model) } - /** * Note : This Generic Method DeSerialize Both Object and List Type Json in POJO - *

+ * + * * Note : Do Not use Array [] in POJO classes for of any element initialization, * Use Instead ArrayList. * @@ -50,22 +45,22 @@ public T getObjectTypePojo(Class model, String jsonName) { * @param return type * @return Return the List of the listModel by Deserializing the Json of resources * @Example of Deserializing List Type Json - *

+ * + * * TestDataFactory mTestDataFactory = new TestDataFactory(); - *

+ * + * * List listObject = mTestDataFactory.getListTypePojo( - * new TypeToken>(){}, "ListObject.json") + * new TypeToken>(){}, "ListObject.json") * @Example Of Deserializing Object Type Json - *

+ * + * * Object object = mTestDataFactory.getListTypePojo( * new TypeToken(){}, "Object.json") - */ - public T getListTypePojo(TypeToken listModel, String jsonName) { - - InputStream in = getClass().getClassLoader().getResourceAsStream(jsonName); - JsonReader reader = new JsonReader(new InputStreamReader(in)); - T listJsonModel = new Gson().fromJson(reader, listModel.getType()); - return listJsonModel; - +

*/ + fun getListTypePojo(listModel: TypeToken?, jsonName: String?): T { + val `in` = javaClass.classLoader?.getResourceAsStream(jsonName) + val reader = JsonReader(InputStreamReader(`in`)) + return Gson().fromJson(reader, listModel?.type) } -} +} \ No newline at end of file diff --git a/app/src/debug/java/org/mifos/mobile/api/BaseURL.java b/app/src/debug/java/org/mifos/mobile/api/BaseURL.java deleted file mode 100644 index 6e5c686498..0000000000 --- a/app/src/debug/java/org/mifos/mobile/api/BaseURL.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.mifos.mobile.api; - -/** - * @author Vishwajeet - * @since 09/06/16 - */ - -public class BaseURL { - - public static final String API_ENDPOINT = "mobile.openmf.org"; - public static final String API_PATH = "/fineract-provider/api/v1/self/"; - public static final String PROTOCOL_HTTPS = "https://"; - - private String url; - - public String getUrl() { - if (url == null) { - return PROTOCOL_HTTPS + API_ENDPOINT + API_PATH; - } - return url; - } - - public String getDefaultBaseUrl() { - return PROTOCOL_HTTPS + API_ENDPOINT; - } - - public String getUrl(String endpoint) { - return endpoint + API_PATH; - } -} diff --git a/app/src/debug/java/org/mifos/mobile/api/BaseURL.kt b/app/src/debug/java/org/mifos/mobile/api/BaseURL.kt new file mode 100644 index 0000000000..c582f3b5e7 --- /dev/null +++ b/app/src/debug/java/org/mifos/mobile/api/BaseURL.kt @@ -0,0 +1,23 @@ +package org.mifos.mobile.api + +/** + * @author Vishwajeet + * @since 09/06/16 + */ +class BaseURL { + val url: String? = null + get() = field + ?: PROTOCOL_HTTPS + API_ENDPOINT + API_PATH + val defaultBaseUrl: String + get() = PROTOCOL_HTTPS + API_ENDPOINT + + fun getUrl(endpoint: String): String { + return endpoint + API_PATH + } + + companion object { + const val API_ENDPOINT = "mobile.mifos.io" + const val API_PATH = "/fineract-provider/api/v1/self/" + const val PROTOCOL_HTTPS = "https://" + } +} \ No newline at end of file diff --git a/app/src/debug/java/org/mifos/mobile/api/SelfServiceInterceptor.java b/app/src/debug/java/org/mifos/mobile/api/SelfServiceInterceptor.java deleted file mode 100644 index 24943d66d9..0000000000 --- a/app/src/debug/java/org/mifos/mobile/api/SelfServiceInterceptor.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This project is licensed under the open source MPL V2. - * See https://github.com/openMF/android-client/blob/master/LICENSE.md - */ - -package org.mifos.mobile.api; - - -import android.text.TextUtils; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Request.Builder; -import okhttp3.Response; - -/** - * @author Vishwajeet - * @since 21/06/16 - */ -public class SelfServiceInterceptor implements Interceptor { - - public static final String HEADER_TENANT = "Fineract-Platform-TenantId"; - public static final String HEADER_AUTH = "Authorization"; - public static final String DEFAULT_TENANT = "mobile"; - private String authToken; - private String tenant; - - public SelfServiceInterceptor(String tenant, String authToken) { - this.authToken = authToken; - this.tenant = tenant; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request chainRequest = chain.request(); - Builder builder = chainRequest.newBuilder() - .header(HEADER_TENANT, tenant); - - if (!TextUtils.isEmpty(authToken)) { - builder.header(HEADER_AUTH, authToken); - } - - Request request = builder.build(); - return chain.proceed(request); - } -} diff --git a/app/src/debug/java/org/mifos/mobile/api/SelfServiceInterceptor.kt b/app/src/debug/java/org/mifos/mobile/api/SelfServiceInterceptor.kt new file mode 100644 index 0000000000..3cd1928b78 --- /dev/null +++ b/app/src/debug/java/org/mifos/mobile/api/SelfServiceInterceptor.kt @@ -0,0 +1,37 @@ +/* + * This project is licensed under the open source MPL V2. + * See https://github.com/openMF/android-client/blob/master/LICENSE.md + */ +package org.mifos.mobile.api + +import android.text.TextUtils + +import okhttp3.Interceptor +import okhttp3.Response + +import java.io.IOException + +/** + * @author Vishwajeet + * @since 21/06/16 + */ +class SelfServiceInterceptor(private val tenant: String?, private val authToken: String?) : + Interceptor { + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + val chainRequest = chain.request() + val builder = chainRequest.newBuilder() + .header(HEADER_TENANT, tenant) + if (!TextUtils.isEmpty(authToken)) { + builder.header(HEADER_AUTH, authToken) + } + val request = builder.build() + return chain.proceed(request) + } + + companion object { + const val HEADER_TENANT = "Fineract-Platform-TenantId" + const val HEADER_AUTH = "Authorization" + const val DEFAULT_TENANT = "mobile" + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3f796adfa7..2b0935a296 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -56,7 +56,8 @@ + android:screenOrientation="portrait" + android:windowSoftInputMode="adjustResize"/> T createApi(Class clazz) { - return retrofit.create(clazz); - } - - public static void createService(String endpoint, String tenant, String authToken) { - retrofit = new Retrofit.Builder() - .baseUrl(new BaseURL().getUrl(endpoint)) - .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) - .client(new SelfServiceOkHttpClient(tenant, authToken).getMifosOkHttpClient()) - .build(); - init(); - } - - public AuthenticationService getAuthenticationApi() { - return authenticationApi; - } - - public ClientService getClientsApi() { - return clientsApi; - } - - public SavingAccountsListService getSavingAccountsListApi() { - return savingAccountsListApi; - } - - public LoanAccountsListService getLoanAccountsListApi() { - return loanAccountsListApi; - } - - public RecentTransactionsService getRecentTransactionsApi() { - return recentTransactionsApi; - } - - public ClientChargeService getClientChargeApi() { - return clientChargeApi; - } - - public BeneficiaryService getBeneficiaryApi() { - return beneficiaryApi; - } - - public ThirdPartyTransferService getThirdPartyTransferApi() { - return thirdPartyTransferApi; - } - - public RegistrationService getRegistrationApi() { - return registrationApi; - } - - public NotificationService getNotificationApi() { - return notificationApi; - } - - public GuarantorService getGuarantorApi() { - return guarantorService; - } - - public UserDetailsService getUserDetailsService() { - return userDetailsService; - } -} diff --git a/app/src/main/java/org/mifos/mobile/api/BaseApiManager.kt b/app/src/main/java/org/mifos/mobile/api/BaseApiManager.kt new file mode 100644 index 0000000000..39092b656f --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/BaseApiManager.kt @@ -0,0 +1,92 @@ +package org.mifos.mobile.api + +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.api.services.* + +import retrofit2.Retrofit +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory +import retrofit2.converter.gson.GsonConverterFactory + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 13/6/16 + */ +class BaseApiManager @Inject constructor(preferencesHelper: PreferencesHelper) { + val authenticationApi: AuthenticationService? + get() = Companion.authenticationApi + val clientsApi: ClientService? + get() = Companion.clientsApi + val savingAccountsListApi: SavingAccountsListService? + get() = Companion.savingAccountsListApi + val loanAccountsListApi: LoanAccountsListService? + get() = Companion.loanAccountsListApi + val recentTransactionsApi: RecentTransactionsService? + get() = Companion.recentTransactionsApi + val clientChargeApi: ClientChargeService? + get() = Companion.clientChargeApi + val beneficiaryApi: BeneficiaryService? + get() = Companion.beneficiaryApi + val thirdPartyTransferApi: ThirdPartyTransferService? + get() = Companion.thirdPartyTransferApi + val registrationApi: RegistrationService? + get() = Companion.registrationApi + val notificationApi: NotificationService? + get() = Companion.notificationApi + val userDetailsService: UserDetailsService? + get() = Companion.userDetailsService + val guarantorApi: GuarantorService? + get() = Companion.field + + companion object { + private val field: GuarantorService? = null + private var retrofit: Retrofit? = null + private var authenticationApi: AuthenticationService? = null + private var clientsApi: ClientService? = null + private var savingAccountsListApi: SavingAccountsListService? = null + private var loanAccountsListApi: LoanAccountsListService? = null + private var recentTransactionsApi: RecentTransactionsService? = null + private var clientChargeApi: ClientChargeService? = null + private var beneficiaryApi: BeneficiaryService? = null + private var thirdPartyTransferApi: ThirdPartyTransferService? = null + private var registrationApi: RegistrationService? = null + private var notificationApi: NotificationService? = null + private var userDetailsService: UserDetailsService? = null + private var guarantorApi: GuarantorService? = null + private fun init() { + authenticationApi = createApi(AuthenticationService::class.java) + clientsApi = createApi(ClientService::class.java) + savingAccountsListApi = createApi(SavingAccountsListService::class.java) + loanAccountsListApi = createApi(LoanAccountsListService::class.java) + recentTransactionsApi = createApi(RecentTransactionsService::class.java) + clientChargeApi = createApi(ClientChargeService::class.java) + beneficiaryApi = createApi(BeneficiaryService::class.java) + thirdPartyTransferApi = createApi(ThirdPartyTransferService::class.java) + registrationApi = createApi(RegistrationService::class.java) + notificationApi = createApi(NotificationService::class.java) + guarantorApi = createApi(GuarantorService::class.java) + userDetailsService = createApi(UserDetailsService::class.java) + } + + private fun createApi(clazz: Class): T? { + return retrofit?.create(clazz) + } + + @JvmStatic + fun createService(endpoint: String?, tenant: String?, authToken: String?) { + retrofit = Retrofit.Builder() + .baseUrl(BaseURL().getUrl(endpoint!!)) + .addConverterFactory(GsonConverterFactory.create()) + .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) + .client(SelfServiceOkHttpClient(tenant, authToken).mifosOkHttpClient) + .build() + init() + } + } + + init { + createService(preferencesHelper.baseUrl, preferencesHelper.tenant, + preferencesHelper.token) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/DataManager.java b/app/src/main/java/org/mifos/mobile/api/DataManager.java deleted file mode 100644 index bd1946f2c7..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/DataManager.java +++ /dev/null @@ -1,339 +0,0 @@ -package org.mifos.mobile.api; - -import org.mifos.mobile.FakeRemoteDataSource; -import org.mifos.mobile.api.local.DatabaseHelper; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload; -import org.mifos.mobile.models.UpdatePasswordPayload; -import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload; -import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload; -import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload; -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.models.notification.NotificationRegisterPayload; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.Transaction; -import org.mifos.mobile.models.User; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.models.accounts.loan.LoanWithdraw; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.beneficiary.BeneficiaryPayload; -import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload; -import org.mifos.mobile.models.client.ClientAccounts; -import org.mifos.mobile.models.notification.NotificationUserDetail; -import org.mifos.mobile.models.payload.LoansPayload; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.models.register.RegisterPayload; -import org.mifos.mobile.models.register.UserVerify; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; -import org.mifos.mobile.models.templates.loans.LoanTemplate; -import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate; - -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.reactivex.Observable; -import io.reactivex.ObservableSource; -import io.reactivex.functions.Function; -import okhttp3.MediaType; -import okhttp3.ResponseBody; - - -/** - * @author Vishwajeet - * @since 13/6/16. - */ -@Singleton -public class DataManager { - - private final PreferencesHelper preferencesHelper; - private final BaseApiManager baseApiManager; - private final DatabaseHelper databaseHelper; - private long clientId; - - @Inject - public DataManager(PreferencesHelper preferencesHelper, BaseApiManager baseApiManager, - DatabaseHelper databaseHelper) { - this.preferencesHelper = preferencesHelper; - this.baseApiManager = baseApiManager; - this.databaseHelper = databaseHelper; - clientId = this.preferencesHelper.getClientId(); - } - - public Observable login(String username, String password) { - return baseApiManager.getAuthenticationApi().authenticate(username, password); - } - - public Observable> getClients() { - return baseApiManager.getClientsApi().getClients(); - } - - public Observable getCurrentClient() { - return baseApiManager.getClientsApi().getClientForId(clientId); - } - - public Observable getClientImage() { - return baseApiManager.getClientsApi().getClientImage(clientId); - } - - public Observable getClientAccounts() { - return baseApiManager.getClientsApi().getClientAccounts(clientId); - } - - public Observable getAccounts(String accountType) { - return baseApiManager.getClientsApi().getAccounts(clientId, accountType); - } - - public Observable> getRecentTransactions(int offset, int limit) { - return baseApiManager.getRecentTransactionsApi() - .getRecentTransactionsList(clientId, offset, limit); - } - - public Observable> getClientCharges(long clientId) { - return baseApiManager.getClientChargeApi().getClientChargeList(clientId) - .concatMap(new Function, ObservableSource>>() { - @Override - public Observable> apply(Page chargePage) { - return databaseHelper.syncCharges(chargePage); - } - }); - } - - public Observable> getLoanCharges(long loanId) { - return baseApiManager.getClientChargeApi().getLoanAccountChargeList(loanId); - } - - public Observable> getSavingsCharges(long savingsId) { - return baseApiManager.getClientChargeApi().getSavingsAccountChargeList(savingsId); - } - - public Observable getSavingsWithAssociations(long accountId, - String associationType) { - return baseApiManager - .getSavingAccountsListApi().getSavingsWithAssociations(accountId, associationType); - } - - public Observable getAccountTransferTemplate() { - return baseApiManager.getSavingAccountsListApi().getAccountTransferTemplate(); - } - - public Observable makeTransfer(TransferPayload transferPayload) { - return baseApiManager.getSavingAccountsListApi().makeTransfer(transferPayload); - } - - public Observable getSavingAccountApplicationTemplate(long client) { - return baseApiManager.getSavingAccountsListApi() - .getSavingsAccountApplicationTemplate(client); - } - - public Observable submitSavingAccountApplication( - SavingsAccountApplicationPayload payload) { - return baseApiManager.getSavingAccountsListApi().submitSavingAccountApplication(payload); - } - - public Observable updateSavingsAccount( - String accountId, SavingsAccountUpdatePayload payload) { - return baseApiManager.getSavingAccountsListApi() - .updateSavingsAccountUpdate(accountId, payload); - } - - public Observable submitWithdrawSavingsAccount( - String accountId, SavingsAccountWithdrawPayload payload) { - return baseApiManager.getSavingAccountsListApi() - .submitWithdrawSavingsAccount(accountId, payload) - .onErrorResumeNext(new Function>() { - @Override - public ObservableSource apply(Throwable throwable) throws Exception { - return Observable.just(ResponseBody.create(MediaType.parse("text/parse"), - "Saving Account Withdrawn Successfully")); - } - }); - } - - public Observable getLoanAccountDetails(long loanId) { - return baseApiManager.getLoanAccountsListApi().getLoanAccountsDetail(loanId); - } - - public Observable getLoanWithAssociations(String associationType, - long loanId) { - return baseApiManager.getLoanAccountsListApi() - .getLoanWithAssociations(loanId, associationType); - } - - public Observable getLoanTemplate() { - return baseApiManager.getLoanAccountsListApi().getLoanTemplate(clientId); - } - - public Observable getLoanTemplateByProduct(Integer productId) { - return baseApiManager.getLoanAccountsListApi() - .getLoanTemplateByProduct(clientId, productId); - } - - public Observable createLoansAccount(LoansPayload loansPayload) { - return baseApiManager.getLoanAccountsListApi().createLoansAccount(loansPayload); - } - - public Observable updateLoanAccount(long loanId, LoansPayload loansPayload) { - return baseApiManager.getLoanAccountsListApi().updateLoanAccount(loanId, loansPayload); - } - - public Observable withdrawLoanAccount(long loanId, LoanWithdraw loanWithdraw) { - return baseApiManager.getLoanAccountsListApi().withdrawLoanAccount(loanId, loanWithdraw); - } - - public Observable> getBeneficiaryList() { - return baseApiManager.getBeneficiaryApi().getBeneficiaryList(); - } - - public Observable getBeneficiaryTemplate() { - return baseApiManager.getBeneficiaryApi().getBeneficiaryTemplate(); - } - - public Observable createBeneficiary(BeneficiaryPayload beneficiaryPayload) { - return baseApiManager.getBeneficiaryApi().createBeneficiary(beneficiaryPayload); - } - - public Observable updateBeneficiary(long beneficiaryId, - BeneficiaryUpdatePayload payload) { - return baseApiManager.getBeneficiaryApi().updateBeneficiary(beneficiaryId, payload); - } - - public Observable deleteBeneficiary(long beneficiaryId) { - return baseApiManager.getBeneficiaryApi().deleteBeneficiary(beneficiaryId); - } - - public Observable getThirdPartyTransferTemplate() { - return baseApiManager.getThirdPartyTransferApi().getAccountTransferTemplate(); - } - - public Observable makeThirdPartyTransfer(TransferPayload transferPayload) { - return baseApiManager.getThirdPartyTransferApi().makeTransfer(transferPayload); - } - - public Observable registerUser(RegisterPayload registerPayload) { - return baseApiManager.getRegistrationApi().registerUser(registerPayload); - } - - public Observable verifyUser(UserVerify userVerify) { - return baseApiManager.getRegistrationApi().verifyUser(userVerify); - } - - public PreferencesHelper getPreferencesHelper() { - return preferencesHelper; - } - - public Observable> getClientLocalCharges() { - return databaseHelper.getClientCharges(); - } - - public Observable> getNotifications() { - return databaseHelper.getNotifications(); - } - - public Observable getUnreadNotificationsCount() { - return databaseHelper.getUnreadNotificationsCount(); - } - - public Observable registerNotification(NotificationRegisterPayload payload) { - return baseApiManager.getNotificationApi().registerNotification(payload); - } - - public Observable updateRegisterNotification(long id, NotificationRegisterPayload - payload) { - return baseApiManager.getNotificationApi().updateRegisterNotification(id, payload); - } - - public Observable getUserNotificationId(long id) { - return baseApiManager.getNotificationApi().getUserNotificationId(id); - } - - public Observable updateAccountPassword(UpdatePasswordPayload payload) { - return baseApiManager.getUserDetailsService().updateAccountPassword(payload); - } - - public long getClientId() { - return clientId; - } - - public void setClientId(long clientId) { - this.clientId = clientId; - } - - public Observable getGuarantorTemplate(long loanId) { - return baseApiManager.getGuarantorApi().getGuarantorTemplate(loanId) - .onErrorResumeNext(new Function>() { - @Override - public ObservableSource apply(Throwable throwable) throws Exception { - return Observable.just(FakeRemoteDataSource.getGuarantorTemplatePayload()); - } - }); - } - - public Observable> getGuarantorList(long loanId) { - return baseApiManager.getGuarantorApi().getGuarantorList(loanId) - .onErrorResumeNext(new Function>>() { - @Override - public ObservableSource> apply(Throwable throwable) throws - Exception { - return Observable.just(FakeRemoteDataSource.getGuarantorsList()); - } - }); - } - - public Observable createGuarantor(long loanId, - GuarantorApplicationPayload payload) { - return baseApiManager.getGuarantorApi().createGuarantor(loanId, payload) - .onErrorResumeNext(new Function>() { - @Override - public ObservableSource apply(Throwable throwable) - throws Exception { - ResponseBody responseBody = ResponseBody.create(MediaType - .parse("text/plain"), "Guarantor Added Successfully"); - return Observable.just(responseBody); - } - }); - } - - public Observable updateGuarantor(GuarantorApplicationPayload payload, - long loanId, long guarantorId) { - return baseApiManager.getGuarantorApi().updateGuarantor(payload, loanId, guarantorId) - .onErrorResumeNext(new Function>() { - @Override - public ObservableSource apply(Throwable throwable) - throws Exception { - return Observable.just(ResponseBody.create(MediaType - .parse("plain/text"), "Guarantor Updated Successfully")); - } - }); - } - - public Observable deleteGuarantor(long loanId, long guarantorId) { - return baseApiManager.getGuarantorApi().deleteGuarantor(loanId, guarantorId) - .onErrorResumeNext(new Function>() { - @Override - public ObservableSource apply(Throwable throwable) - throws Exception { - return Observable.just(ResponseBody.create(MediaType - .parse("plain/text"), "Guarantor Deleted Successfully")); - } - }); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/api/DataManager.kt b/app/src/main/java/org/mifos/mobile/api/DataManager.kt new file mode 100644 index 0000000000..0ebd57bd7a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/DataManager.kt @@ -0,0 +1,265 @@ +package org.mifos.mobile.api + +import io.reactivex.Observable +import io.reactivex.ObservableSource +import io.reactivex.functions.Function + +import okhttp3.MediaType +import okhttp3.ResponseBody + +import org.mifos.mobile.FakeRemoteDataSource +import org.mifos.mobile.api.local.DatabaseHelper +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.* +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.models.accounts.loan.LoanWithdraw +import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload +import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload +import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.beneficiary.BeneficiaryPayload +import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.models.notification.NotificationRegisterPayload +import org.mifos.mobile.models.notification.NotificationUserDetail +import org.mifos.mobile.models.payload.LoansPayload +import org.mifos.mobile.models.payload.LoginPayload +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.models.register.RegisterPayload +import org.mifos.mobile.models.register.UserVerify +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate +import org.mifos.mobile.models.templates.loans.LoanTemplate +import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate + +import javax.inject.Inject +import javax.inject.Singleton + +/** + * @author Vishwajeet + * @since 13/6/16. + */ +@Singleton +class DataManager @Inject constructor( + val preferencesHelper: PreferencesHelper, private val baseApiManager: BaseApiManager, + private val databaseHelper: DatabaseHelper +) { + var clientId: Long? = preferencesHelper.clientId + fun login(loginPayload: LoginPayload?): Observable? { + return baseApiManager.authenticationApi?.authenticate(loginPayload) + } + + val clients: Observable?>? + get() = baseApiManager.clientsApi?.clients + val currentClient: Observable? + get() = baseApiManager.clientsApi?.getClientForId(clientId) + val clientImage: Observable? + get() = baseApiManager.clientsApi?.getClientImage(clientId) + val clientAccounts: Observable? + get() = baseApiManager.clientsApi?.getClientAccounts(clientId) + + fun getAccounts(accountType: String?): Observable? { + return baseApiManager.clientsApi?.getAccounts(clientId, accountType) + } + + fun getRecentTransactions(offset: Int, limit: Int): Observable?>? { + return baseApiManager.recentTransactionsApi + ?.getRecentTransactionsList(clientId, offset, limit) + } + + fun getClientCharges(clientId: Long): Observable?>? { + return baseApiManager.clientChargeApi?.getClientChargeList(clientId) + ?.concatMap { chargePage -> databaseHelper.syncCharges(chargePage) } + } + + fun getLoanCharges(loanId: Long): Observable?>? { + return baseApiManager.clientChargeApi?.getLoanAccountChargeList(loanId) + } + + fun getSavingsCharges(savingsId: Long): Observable?>? { + return baseApiManager.clientChargeApi?.getSavingsAccountChargeList(savingsId) + } + + fun getSavingsWithAssociations( + accountId: Long?, + associationType: String? + ): Observable? { + return baseApiManager + .savingAccountsListApi?.getSavingsWithAssociations(accountId, associationType) + } + + val accountTransferTemplate: Observable? + get() = baseApiManager.savingAccountsListApi?.accountTransferTemplate + + fun makeTransfer(transferPayload: TransferPayload?): Observable? { + return baseApiManager.savingAccountsListApi?.makeTransfer(transferPayload) + } + + fun getSavingAccountApplicationTemplate(client: Long?): Observable? { + return baseApiManager.savingAccountsListApi + ?.getSavingsAccountApplicationTemplate(client) + } + + fun submitSavingAccountApplication( + payload: SavingsAccountApplicationPayload? + ): Observable? { + return baseApiManager.savingAccountsListApi?.submitSavingAccountApplication(payload) + } + + fun updateSavingsAccount( + accountId: String?, payload: SavingsAccountUpdatePayload? + ): Observable? { + return baseApiManager.savingAccountsListApi + ?.updateSavingsAccountUpdate(accountId, payload) + } + + fun submitWithdrawSavingsAccount( + accountId: String?, payload: SavingsAccountWithdrawPayload? + ): Observable? { + return baseApiManager.savingAccountsListApi + ?.submitWithdrawSavingsAccount(accountId, payload) + ?.onErrorResumeNext(Function> { + Observable.just(ResponseBody.create(MediaType.parse("text/parse"), + "Saving Account Withdrawn Successfully")) + }) + } + + fun getLoanAccountDetails(loanId: Long): Observable? { + return baseApiManager.loanAccountsListApi?.getLoanAccountsDetail(loanId) + } + + fun getLoanWithAssociations( + associationType: String?, + loanId: Long? + ): Observable? { + return baseApiManager.loanAccountsListApi + ?.getLoanWithAssociations(loanId, associationType) + } + + val loanTemplate: Observable? + get() = baseApiManager.loanAccountsListApi?.getLoanTemplate(clientId) + + fun getLoanTemplateByProduct(productId: Int?): Observable? { + return baseApiManager.loanAccountsListApi + ?.getLoanTemplateByProduct(clientId, productId) + } + + fun createLoansAccount(loansPayload: LoansPayload?): Observable? { + return baseApiManager.loanAccountsListApi?.createLoansAccount(loansPayload) + } + + fun updateLoanAccount(loanId: Long, loansPayload: LoansPayload?): Observable? { + return baseApiManager.loanAccountsListApi?.updateLoanAccount(loanId, loansPayload) + } + + fun withdrawLoanAccount(loanId: Long?, loanWithdraw: LoanWithdraw?): Observable? { + return baseApiManager.loanAccountsListApi?.withdrawLoanAccount(loanId, loanWithdraw) + } + + val beneficiaryList: Observable?>? + get() = baseApiManager.beneficiaryApi?.beneficiaryList + val beneficiaryTemplate: Observable? + get() = baseApiManager.beneficiaryApi?.beneficiaryTemplate + + fun createBeneficiary(beneficiaryPayload: BeneficiaryPayload?): Observable? { + return baseApiManager.beneficiaryApi?.createBeneficiary(beneficiaryPayload) + } + + fun updateBeneficiary( + beneficiaryId: Long?, + payload: BeneficiaryUpdatePayload? + ): Observable? { + return baseApiManager.beneficiaryApi?.updateBeneficiary(beneficiaryId, payload) + } + + fun deleteBeneficiary(beneficiaryId: Long?): Observable? { + return baseApiManager.beneficiaryApi?.deleteBeneficiary(beneficiaryId) + } + + val thirdPartyTransferTemplate: Observable? + get() = baseApiManager.thirdPartyTransferApi?.accountTransferTemplate + + fun makeThirdPartyTransfer(transferPayload: TransferPayload?): Observable? { + return baseApiManager.thirdPartyTransferApi?.makeTransfer(transferPayload) + } + + fun registerUser(registerPayload: RegisterPayload?): Observable? { + return baseApiManager.registrationApi?.registerUser(registerPayload) + } + + fun verifyUser(userVerify: UserVerify?): Observable? { + return baseApiManager.registrationApi?.verifyUser(userVerify) + } + + val clientLocalCharges: Observable?>? + get() = databaseHelper.clientCharges + val notifications: Observable?>? + get() = databaseHelper.notifications + val unreadNotificationsCount: Observable + get() = databaseHelper.unreadNotificationsCount + + fun registerNotification(payload: NotificationRegisterPayload?): Observable? { + return baseApiManager.notificationApi?.registerNotification(payload) + } + + fun updateRegisterNotification(id: Long, payload: NotificationRegisterPayload?): Observable? { + return baseApiManager.notificationApi?.updateRegisterNotification(id, payload) + } + + fun getUserNotificationId(id: Long): Observable? { + return baseApiManager.notificationApi?.getUserNotificationId(id) + } + + fun updateAccountPassword(payload: UpdatePasswordPayload?): Observable? { + return baseApiManager.userDetailsService?.updateAccountPassword(payload) + } + + fun getGuarantorTemplate(loanId: Long?): Observable? { + return baseApiManager.guarantorApi?.getGuarantorTemplate(loanId) + ?.onErrorResumeNext(Function> { Observable.just(FakeRemoteDataSource.guarantorTemplatePayload) }) + } + + fun getGuarantorList(loanId: Long): Observable?>? { + return baseApiManager.guarantorApi?.getGuarantorList(loanId) + ?.onErrorResumeNext(Function>> { Observable.just(FakeRemoteDataSource.guarantorsList) }) + } + + fun createGuarantor( + loanId: Long?, + payload: GuarantorApplicationPayload? + ): Observable? { + return baseApiManager.guarantorApi?.createGuarantor(loanId, payload) + ?.onErrorResumeNext(Function> { + val responseBody = ResponseBody.create(MediaType + .parse("text/plain"), "Guarantor Added Successfully") + Observable.just(responseBody) + }) + } + + fun updateGuarantor( + payload: GuarantorApplicationPayload?, + loanId: Long?, guarantorId: Long? + ): Observable? { + return baseApiManager.guarantorApi?.updateGuarantor(payload, loanId, guarantorId) + ?.onErrorResumeNext(Function> { + Observable.just(ResponseBody.create(MediaType + .parse("plain/text"), "Guarantor Updated Successfully")) + }) + } + + fun deleteGuarantor(loanId: Long?, guarantorId: Long?): Observable? { + return baseApiManager.guarantorApi?.deleteGuarantor(loanId, guarantorId) + ?.onErrorResumeNext(Function> { + Observable.just(ResponseBody.create(MediaType + .parse("plain/text"), "Guarantor Deleted Successfully")) + }) + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.java b/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.java deleted file mode 100644 index ac71f37b37..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.mifos.mobile.api; - -import java.security.KeyStore; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import okhttp3.OkHttpClient; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; - - -public class SelfServiceOkHttpClient { - private String authToken; - private String tenant; - - public SelfServiceOkHttpClient(String tenant, String authToken) { - this.authToken = authToken; - this.tenant = tenant; - } - - public OkHttpClient getMifosOkHttpClient() { - - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - - try { - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = { - new X509TrustManager() { - @Override - public void checkClientTrusted( - X509Certificate[] chain, - String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted( - X509Certificate[] chain, - String authType) throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - } - }; - - // Install the all-trusting trust manager - SSLContext sslContext = SSLContext.getInstance("SSL"); - sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); - // Create an ssl socket factory with our all-trusting manager - SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - - //Enable Full Body Logging - HttpLoggingInterceptor logger = new HttpLoggingInterceptor(); - logger.setLevel(Level.BODY); - - TrustManagerFactory trustManagerFactory = TrustManagerFactory. - getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init((KeyStore) null); - TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); - if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { - throw new IllegalStateException("Unexpected default trust managers:" + Arrays. - toString(trustManagers)); - } - X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; - - //Set SSL certificate to OkHttpClient Builder - - builder.sslSocketFactory(sslSocketFactory, trustManager); - - builder.hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); - } catch (Exception e) { - throw new RuntimeException(e); - } - - //Enable Full Body Logging - HttpLoggingInterceptor logger = new HttpLoggingInterceptor(); - logger.setLevel(Level.BODY); - - //Setting Timeout 30 Seconds - builder.connectTimeout(60, TimeUnit.SECONDS); - builder.readTimeout(60, TimeUnit.SECONDS); - - //Interceptor :> Full Body Logger and ApiRequest Header - builder.addInterceptor(logger); - builder.addInterceptor(new SelfServiceInterceptor(tenant, authToken)); - - return builder.build(); - - } -} diff --git a/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.kt b/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.kt new file mode 100644 index 0000000000..66de4399bd --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/SelfServiceOkHttpClient.kt @@ -0,0 +1,82 @@ +package org.mifos.mobile.api + +import okhttp3.OkHttpClient +import okhttp3.logging.HttpLoggingInterceptor + +import java.security.KeyStore +import java.security.SecureRandom +import java.security.cert.CertificateException +import java.security.cert.X509Certificate +import java.util.* +import java.util.concurrent.TimeUnit + +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManager +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager + +class SelfServiceOkHttpClient(private val tenant: String?, private val authToken: String?) { + // Create a trust manager that does not validate certificate chains + val mifosOkHttpClient: OkHttpClient + get() { + val builder = OkHttpClient.Builder() + try { + // Create a trust manager that does not validate certificate chains + val trustAllCerts = arrayOf( + object : X509TrustManager { + @Throws(CertificateException::class) + override fun checkClientTrusted( + chain: Array, + authType: String + ) { + } + + @Throws(CertificateException::class) + override fun checkServerTrusted( + chain: Array, + authType: String + ) { + } + + override fun getAcceptedIssuers(): Array { + return arrayOfNulls(0) + } + } + ) + + // Install the all-trusting trust manager + val sslContext = SSLContext.getInstance("SSL") + sslContext.init(null, trustAllCerts, SecureRandom()) + // Create an ssl socket factory with our all-trusting manager + val sslSocketFactory = sslContext.socketFactory + + //Enable Full Body Logging + val logger = HttpLoggingInterceptor() + logger.level = HttpLoggingInterceptor.Level.BODY + val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + trustManagerFactory.init(null as KeyStore?) + val trustManagers = trustManagerFactory.trustManagers + check(!(trustManagers.size != 1 || trustManagers[0] !is X509TrustManager)) { "Unexpected default trust managers:" + Arrays.toString(trustManagers) } + val trustManager = trustManagers[0] as X509TrustManager + + //Set SSL certificate to OkHttpClient Builder + builder.sslSocketFactory(sslSocketFactory, trustManager) + builder.hostnameVerifier { _, _ -> true } + } catch (e: Exception) { + throw RuntimeException(e) + } + + //Enable Full Body Logging + val logger = HttpLoggingInterceptor() + logger.level = HttpLoggingInterceptor.Level.BODY + + //Setting Timeout 30 Seconds + builder.connectTimeout(60, TimeUnit.SECONDS) + builder.readTimeout(60, TimeUnit.SECONDS) + + //Interceptor :> Full Body Logger and ApiRequest Header + builder.addInterceptor(logger) + builder.addInterceptor(SelfServiceInterceptor(tenant, authToken)) + return builder.build() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/local/DatabaseHelper.java b/app/src/main/java/org/mifos/mobile/api/local/DatabaseHelper.java deleted file mode 100644 index 7a51b88e51..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/local/DatabaseHelper.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.mifos.mobile.api.local; - -import com.raizlabs.android.dbflow.sql.language.SQLite; - -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.models.notification.MifosNotification_Table; -import org.mifos.mobile.utils.NotificationComparator; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Callable; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.reactivex.Observable; -import io.reactivex.ObservableSource; - - -/** - * Created by Rajan Maurya on 02/03/17. - */ -@Singleton -public class DatabaseHelper { - - @Inject - public DatabaseHelper() { - } - - public Observable> syncCharges(final Page charges) { - return Observable.defer(new Callable>>() { - @Override - public Observable> call() { - for (Charge charge : charges.getPageItems()) { - charge.save(); - } - return Observable.just(charges); - } - }); - } - - public Observable> getClientCharges() { - return Observable.defer(new Callable>>() { - @Override - public Observable> call() { - List charges = SQLite.select() - .from(Charge.class) - .queryList(); - Page chargePage = new Page<>(); - chargePage.setPageItems(charges); - return Observable.just(chargePage); - } - }); - } - - public Observable> getNotifications() { - return Observable.defer(new Callable>>() { - @Override - public Observable> call() { - deleteOldNotifications(); - List notifications = SQLite.select() - .from(MifosNotification.class) - .queryList(); - Collections.sort(notifications, new NotificationComparator()); - return Observable.just(notifications); - } - }); - } - - public Observable getUnreadNotificationsCount() { - return Observable.defer(new Callable>() { - @Override - public Observable call() { - deleteOldNotifications(); - int count = SQLite.select() - .from(MifosNotification.class) - .where(MifosNotification_Table.read.eq(false)) - .queryList().size(); - return Observable.just(count); - } - }); - } - - private void deleteOldNotifications() { - Observable.defer(new Callable>() { - @Override - public Observable call() { - long thirtyDaysInSeconds = 2592000; - long thirtyDaysFromCurrentTimeInSeconds = (System.currentTimeMillis() / 1000) - - thirtyDaysInSeconds; - SQLite.delete(MifosNotification.class) - .where(MifosNotification_Table.timeStamp. - lessThan(thirtyDaysFromCurrentTimeInSeconds * 1000)) - .execute(); - return null; - } - }); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/api/local/DatabaseHelper.kt b/app/src/main/java/org/mifos/mobile/api/local/DatabaseHelper.kt new file mode 100644 index 0000000000..8be20fc9c0 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/local/DatabaseHelper.kt @@ -0,0 +1,70 @@ +package org.mifos.mobile.api.local + +import com.raizlabs.android.dbflow.sql.language.SQLite + +import io.reactivex.Observable + +import org.mifos.mobile.models.Charge +import org.mifos.mobile.models.Page +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.models.notification.MifosNotification_Table +import org.mifos.mobile.utils.NotificationComparator + +import java.util.* +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by Rajan Maurya on 02/03/17. + */ +@Singleton +class DatabaseHelper @Inject constructor() { + fun syncCharges(charges: Page?): Observable?>? { + return Observable.defer { + if (charges != null) + for (charge in charges.pageItems) + charge?.save() + Observable.just(charges) + } + } + + val clientCharges: Observable?>? + get() = Observable.defer { + val charges = SQLite.select() + .from(Charge::class.java) + .queryList() + val chargePage = Page() + chargePage.pageItems = charges + Observable.just(chargePage) + } + val notifications: Observable?>? + get() = Observable.defer { + deleteOldNotifications() + val notifications = SQLite.select() + .from(MifosNotification::class.java) + .queryList() + Collections.sort(notifications, NotificationComparator()) + Observable.just(notifications) + } + val unreadNotificationsCount: Observable + get() = Observable.defer { + deleteOldNotifications() + val count = SQLite.select() + .from(MifosNotification::class.java) + .where(MifosNotification_Table.read.eq(false)) + .queryList().size + Observable.just(count) + } + + private fun deleteOldNotifications() { + Observable.defer { + val thirtyDaysInSeconds: Long = 2592000 + val thirtyDaysFromCurrentTimeInSeconds = System.currentTimeMillis() / 1000 - + thirtyDaysInSeconds + SQLite.delete(MifosNotification::class.java) + .where(MifosNotification_Table.timeStamp.lessThan(thirtyDaysFromCurrentTimeInSeconds * 1000)) + .execute() + null + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/local/PreferencesHelper.java b/app/src/main/java/org/mifos/mobile/api/local/PreferencesHelper.java deleted file mode 100644 index 6086138a02..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/local/PreferencesHelper.java +++ /dev/null @@ -1,198 +0,0 @@ -package org.mifos.mobile.api.local; - -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.text.TextUtils; - -import org.mifos.mobile.api.BaseURL; -import org.mifos.mobile.api.SelfServiceInterceptor; -import org.mifos.mobile.injection.ApplicationContext; - -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Singleton; - -/** - * @author Vishwajeet - * @since 07/06/16 - */ - -@Singleton -public class PreferencesHelper { - private static final String USER_ID = "preferences_user_id"; - private static final String TOKEN = "preferences_token"; - private static final String CLIENT_ID = "preferences_client"; - private static final String OFFICE_NAME = "preferences_office_name"; - private static final String USER_NAME = "preferences_user_name"; - private static final String PASSCODE = "preferences_passcode"; - private static final String OVERVIEW_STATE = "preferences_overview_state"; - private static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; - private static final String GCM_TOKEN = "gcm_token"; - private static final String TENANT = "preferences_base_tenant"; - private static final String BASE_URL = "preferences_base_url_key"; - private static final String PROFILE_IMAGE = "preferences_profile_image"; - public static final String CLIENT_NAME = "client_name"; - - private SharedPreferences sharedPreferences; - - @Inject - public PreferencesHelper(@ApplicationContext Context context) { - this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); - } - - public void clear() { - SharedPreferences.Editor editor = sharedPreferences.edit(); - //prevent deletion of url and tenant - for (Map.Entry entry: sharedPreferences.getAll().entrySet()) { - if (!(entry.getKey().equals(BASE_URL) || entry.getKey().equals(TENANT))) { - editor.remove(entry.getKey()); - } - } - editor.apply(); - } - - public int getInt(String preferenceKey, int preferenceDefaultValue) { - return sharedPreferences.getInt(preferenceKey, preferenceDefaultValue); - } - - public void putInt(String preferenceKey, int preferenceValue) { - sharedPreferences.edit().putInt(preferenceKey, preferenceValue).apply(); - } - - public long getLong(String preferenceKey, long preferenceDefaultValue) { - return sharedPreferences.getLong(preferenceKey, preferenceDefaultValue); - } - - public void putLong(String preferenceKey, long preferenceValue) { - sharedPreferences.edit().putLong(preferenceKey, preferenceValue).apply(); - } - - public String getString(String preferenceKey, String preferenceDefaultValue) { - return sharedPreferences.getString(preferenceKey, preferenceDefaultValue); - } - - public void putString(String preferenceKey, String preferenceValue) { - sharedPreferences.edit().putString(preferenceKey, preferenceValue).apply(); - } - - public void putBoolean(String preferenceKey, boolean preferenceValue) { - sharedPreferences.edit().putBoolean(preferenceKey, preferenceValue).apply(); - } - - public boolean getBoolean(String preferenceKey, boolean preferenceDefaultValue) { - return sharedPreferences.getBoolean(preferenceKey, preferenceDefaultValue); - } - - public void saveToken(String token) { - putString(TOKEN, token); - } - - public void clearToken() { - putString(TOKEN, ""); - } - - public String getToken() { - return getString(TOKEN, ""); - } - - public boolean isAuthenticated() { - return !TextUtils.isEmpty(getToken()); - } - - public long getUserId() { - return getLong(USER_ID, -1); - } - - public void setUserId(long id) { - putLong(USER_ID, id); - } - - public String getTenant() { - return getString(TENANT, SelfServiceInterceptor.DEFAULT_TENANT); - } - - public void setPasscode(String passcode) { - putString(PASSCODE, passcode); - } - - public String getPasscode() { - return getString(PASSCODE, ""); - } - - public void setClientId(long clientId) { - putLong(CLIENT_ID, clientId); - } - - public long getClientId() { - return getLong(CLIENT_ID, -1); - } - - public void setOfficeName(String officeName) { - putString(OFFICE_NAME, officeName); - } - - public String getUserName() { - return getString(USER_NAME, ""); - } - - public void setUserName(String userName) { - putString(USER_NAME, userName); - } - - public String getClientName() { - return getString(CLIENT_NAME, ""); - } - - public void setClientName(String clientName) { - putString(CLIENT_NAME, clientName); - } - - public String getOfficeName() { - return getString(OFFICE_NAME, ""); - } - - public void setOverviewState(boolean state) { - putBoolean(OVERVIEW_STATE, state); - } - - public boolean overviewState() { - return getBoolean(OVERVIEW_STATE, true); - } - - public void saveGcmToken(String token) { - putString(GCM_TOKEN, token); - } - - public String getUserProfileImage() { - return getString(PROFILE_IMAGE, null); - } - - public void setUserProfileImage(String image) { - putString(PROFILE_IMAGE, image); - } - - public String getGcmToken() { - return getString(GCM_TOKEN, ""); - } - - public void setSentTokenToServer(boolean sentTokenToServer) { - putBoolean(SENT_TOKEN_TO_SERVER, sentTokenToServer); - } - - public boolean sentTokenToServerState() { - return getBoolean(SENT_TOKEN_TO_SERVER, false); - } - - public void updateConfiguration(String baseUrl, String tenant) { - sharedPreferences.edit() - .putString(BASE_URL, baseUrl) - .putString(TENANT, tenant) - .apply(); - } - - public String getBaseUrl() { - return getString(BASE_URL, new BaseURL().getDefaultBaseUrl()); - } -} diff --git a/app/src/main/java/org/mifos/mobile/api/local/PreferencesHelper.kt b/app/src/main/java/org/mifos/mobile/api/local/PreferencesHelper.kt new file mode 100644 index 0000000000..6b892b89d2 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/local/PreferencesHelper.kt @@ -0,0 +1,167 @@ +package org.mifos.mobile.api.local + +import android.content.Context +import android.content.SharedPreferences +import android.preference.PreferenceManager +import android.text.TextUtils + +import org.mifos.mobile.api.BaseURL +import org.mifos.mobile.api.SelfServiceInterceptor +import org.mifos.mobile.injection.ApplicationContext + +import javax.inject.Inject +import javax.inject.Singleton + +/** + * @author Vishwajeet + * @since 07/06/16 + */ +@Singleton +class PreferencesHelper @Inject constructor(@ApplicationContext context: Context?) { + private val sharedPreferences: SharedPreferences? = PreferenceManager.getDefaultSharedPreferences(context) + fun clear() { + val editor = sharedPreferences?.edit() + //prevent deletion of url and tenant + if (sharedPreferences != null) + for ((key) in sharedPreferences.all) { + if (!(key == BASE_URL || key == TENANT)) { + editor?.remove(key) + } + } + editor?.apply() + } + + fun getInt(preferenceKey: String?, preferenceDefaultValue: Int): Int? { + return sharedPreferences?.getInt(preferenceKey, preferenceDefaultValue) + } + + fun putInt(preferenceKey: String?, preferenceValue: Int) { + sharedPreferences?.edit()?.putInt(preferenceKey, preferenceValue)?.apply() + } + + fun getLong(preferenceKey: String?, preferenceDefaultValue: Long): Long? { + return sharedPreferences?.getLong(preferenceKey, preferenceDefaultValue) + } + + fun putLong(preferenceKey: String?, preferenceValue: Long) { + sharedPreferences?.edit()?.putLong(preferenceKey, preferenceValue)?.apply() + } + + fun getString(preferenceKey: String?, preferenceDefaultValue: String?): String? { + return sharedPreferences?.getString(preferenceKey, preferenceDefaultValue) + } + + private fun putString(preferenceKey: String?, preferenceValue: String?) { + sharedPreferences?.edit()?.putString(preferenceKey, preferenceValue)?.apply() + } + + fun putBoolean(preferenceKey: String?, preferenceValue: Boolean) { + sharedPreferences?.edit()?.putBoolean(preferenceKey, preferenceValue)?.apply() + } + + fun getBoolean(preferenceKey: String?, preferenceDefaultValue: Boolean): Boolean? { + return sharedPreferences?.getBoolean(preferenceKey, preferenceDefaultValue) + } + + fun saveToken(token: String?) { + putString(TOKEN, token) + } + + fun clearToken() { + putString(TOKEN, "") + } + + val token: String? + get() = getString(TOKEN, "") + val isAuthenticated: Boolean? + get() = !TextUtils.isEmpty(token) + var userId: Long? + get() = getLong(USER_ID, -1) + set(id) { + if (id != null) + putLong(USER_ID, id) + } + val tenant: String? + get() = getString(TENANT, SelfServiceInterceptor.DEFAULT_TENANT) + var passcode: String? + get() = getString(PASSCODE, "") + set(passcode) { + putString(PASSCODE, passcode) + } + var clientId: Long? + get() = getLong(CLIENT_ID, -1) + set(clientId) { + if (clientId != null) + putLong(CLIENT_ID, clientId) + } + var userName: String? + get() = getString(USER_NAME, "") + set(userName) { + putString(USER_NAME, userName) + } + var clientName: String? + get() = getString(CLIENT_NAME, "") + set(clientName) { + putString(CLIENT_NAME, clientName) + } + var officeName: String? + get() = getString(OFFICE_NAME, "") + set(officeName) { + putString(OFFICE_NAME, officeName) + } + + fun setOverviewState(state: Boolean) { + putBoolean(OVERVIEW_STATE, state) + } + + fun overviewState(): Boolean? { + return getBoolean(OVERVIEW_STATE, true) + } + + fun saveGcmToken(token: String?) { + putString(GCM_TOKEN, token) + } + + var userProfileImage: String? + get() = getString(PROFILE_IMAGE, null) + set(image) { + putString(PROFILE_IMAGE, image) + } + val gcmToken: String? + get() = getString(GCM_TOKEN, "") + + fun setSentTokenToServer(sentTokenToServer: Boolean) { + putBoolean(SENT_TOKEN_TO_SERVER, sentTokenToServer) + } + + fun sentTokenToServerState(): Boolean? { + return getBoolean(SENT_TOKEN_TO_SERVER, false) + } + + fun updateConfiguration(baseUrl: String?, tenant: String?) { + sharedPreferences?.edit() + ?.putString(BASE_URL, baseUrl) + ?.putString(TENANT, tenant) + ?.apply() + } + + val baseUrl: String? + get() = getString(BASE_URL, BaseURL().defaultBaseUrl) + + companion object { + private const val USER_ID = "preferences_user_id" + private const val TOKEN = "preferences_token" + private const val CLIENT_ID = "preferences_client" + private const val OFFICE_NAME = "preferences_office_name" + private const val USER_NAME = "preferences_user_name" + private const val PASSCODE = "preferences_passcode" + private const val OVERVIEW_STATE = "preferences_overview_state" + private const val SENT_TOKEN_TO_SERVER = "sentTokenToServer" + private const val GCM_TOKEN = "gcm_token" + private const val TENANT = "preferences_base_tenant" + private const val BASE_URL = "preferences_base_url_key" + private const val PROFILE_IMAGE = "preferences_profile_image" + const val CLIENT_NAME = "client_name" + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/local/SelfServiceDatabase.java b/app/src/main/java/org/mifos/mobile/api/local/SelfServiceDatabase.java deleted file mode 100644 index 973a325e25..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/local/SelfServiceDatabase.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.mifos.mobile.api.local; - -import com.raizlabs.android.dbflow.annotation.Database; - -@Database(name = SelfServiceDatabase.NAME, version = SelfServiceDatabase.VERSION) -public class SelfServiceDatabase { - - public static final String NAME = "SelfService"; // we will add the .db extension - - public static final int VERSION = 1; -} diff --git a/app/src/main/java/org/mifos/mobile/api/local/SelfServiceDatabase.kt b/app/src/main/java/org/mifos/mobile/api/local/SelfServiceDatabase.kt new file mode 100644 index 0000000000..e16c092842 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/local/SelfServiceDatabase.kt @@ -0,0 +1,9 @@ +package org.mifos.mobile.api.local + +import com.raizlabs.android.dbflow.annotation.Database + +@Database(name = SelfServiceDatabase.NAME, version = SelfServiceDatabase.VERSION) +object SelfServiceDatabase { + const val NAME: String = "SelfService" // we will add the .db extension + const val VERSION: Int = 1 +} diff --git a/app/src/main/java/org/mifos/mobile/api/services/AuthenticationService.java b/app/src/main/java/org/mifos/mobile/api/services/AuthenticationService.java deleted file mode 100644 index b9ecb3b7de..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/AuthenticationService.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.User; - -import io.reactivex.Observable; -import retrofit2.http.POST; -import retrofit2.http.Query; - -/** - * @author Vishwajeet - * @since 09/06/16 - */ - -public interface AuthenticationService { - - @POST(ApiEndPoints.AUTHENTICATION) - Observable authenticate(@Query("username") String username, - @Query("password") String password); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/AuthenticationService.kt b/app/src/main/java/org/mifos/mobile/api/services/AuthenticationService.kt new file mode 100644 index 0000000000..33e2e4f799 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/AuthenticationService.kt @@ -0,0 +1,20 @@ +package org.mifos.mobile.api.services + +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.User +import org.mifos.mobile.models.payload.LoginPayload + +import io.reactivex.Observable +import retrofit2.http.Body +import retrofit2.http.POST + +/** + * @author Vishwajeet + * @since 09/06/16 + */ + +interface AuthenticationService { + + @POST(ApiEndPoints.AUTHENTICATION) + fun authenticate(@Body loginPayload: LoginPayload?): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/BeneficiaryService.java b/app/src/main/java/org/mifos/mobile/api/services/BeneficiaryService.java deleted file mode 100644 index 211f73f200..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/BeneficiaryService.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.beneficiary.BeneficiaryPayload; -import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload; -import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; - -import java.util.List; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.DELETE; -import retrofit2.http.GET; -import retrofit2.http.POST; -import retrofit2.http.PUT; -import retrofit2.http.Path; - -/** - * Created by dilpreet on 14/6/17. - */ - -public interface BeneficiaryService { - - @GET(ApiEndPoints.BENEFICIARIES + "/tpt") - Observable> getBeneficiaryList(); - - @GET(ApiEndPoints.BENEFICIARIES + "/tpt/template") - Observable getBeneficiaryTemplate(); - - @POST(ApiEndPoints.BENEFICIARIES + "/tpt") - Observable createBeneficiary(@Body BeneficiaryPayload beneficiaryPayload); - - @PUT(ApiEndPoints.BENEFICIARIES + "/tpt/{beneficiaryId}") - Observable updateBeneficiary(@Path("beneficiaryId") long beneficiaryId, - @Body BeneficiaryUpdatePayload payload); - - @DELETE(ApiEndPoints.BENEFICIARIES + "/tpt/{beneficiaryId}") - Observable deleteBeneficiary(@Path("beneficiaryId") long beneficiaryId); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/BeneficiaryService.kt b/app/src/main/java/org/mifos/mobile/api/services/BeneficiaryService.kt new file mode 100644 index 0000000000..dd21f3facc --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/BeneficiaryService.kt @@ -0,0 +1,33 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import okhttp3.ResponseBody +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.beneficiary.BeneficiaryPayload +import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload +import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate +import retrofit2.http.* + +/** + * Created by dilpreet on 14/6/17. + */ +interface BeneficiaryService { + @get:GET(ApiEndPoints.BENEFICIARIES + "/tpt") + val beneficiaryList: Observable?>? + + @get:GET(ApiEndPoints.BENEFICIARIES + "/tpt/template") + val beneficiaryTemplate: Observable? + + @POST(ApiEndPoints.BENEFICIARIES + "/tpt") + fun createBeneficiary(@Body beneficiaryPayload: BeneficiaryPayload?): Observable? + + @PUT(ApiEndPoints.BENEFICIARIES + "/tpt/{beneficiaryId}") + fun updateBeneficiary( + @Path("beneficiaryId") beneficiaryId: Long?, + @Body payload: BeneficiaryUpdatePayload? + ): Observable? + + @DELETE(ApiEndPoints.BENEFICIARIES + "/tpt/{beneficiaryId}") + fun deleteBeneficiary(@Path("beneficiaryId") beneficiaryId: Long?): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/ClientChargeService.java b/app/src/main/java/org/mifos/mobile/api/services/ClientChargeService.java deleted file mode 100644 index c03f1e9ca9..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/ClientChargeService.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.models.Page; - -import java.util.List; - -import io.reactivex.Observable; -import retrofit2.http.GET; -import retrofit2.http.Path; - -/** - * @author Vishwajeet - * @since 17/8/16. - */ -public interface ClientChargeService { - @GET(ApiEndPoints.CLIENTS + "/{clientId}/charges") - Observable> getClientChargeList(@Path("clientId") long clientId); - - @GET(ApiEndPoints.LOANS + "/{loanId}/charges") - Observable> getLoanAccountChargeList(@Path("loanId") long loanId); - - @GET(ApiEndPoints.SAVINGS_ACCOUNTS + "/{savingsId}/charges") - Observable> getSavingsAccountChargeList(@Path("savingsId") long savingsId); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/ClientChargeService.kt b/app/src/main/java/org/mifos/mobile/api/services/ClientChargeService.kt new file mode 100644 index 0000000000..ec58914253 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/ClientChargeService.kt @@ -0,0 +1,27 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable + +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.Charge +import org.mifos.mobile.models.Page + +import retrofit2.http.GET +import retrofit2.http.Path + +/** + * @author Vishwajeet + * @since 17/8/16. + */ +interface ClientChargeService { + + @GET(ApiEndPoints.CLIENTS + "/{clientId}/charges") + fun getClientChargeList(@Path("clientId") clientId: Long?): Observable?>? + + @GET(ApiEndPoints.LOANS + "/{loanId}/charges") + fun getLoanAccountChargeList(@Path("loanId") loanId: Long?): Observable?>? + + @GET(ApiEndPoints.SAVINGS_ACCOUNTS + "/{savingsId}/charges") + fun getSavingsAccountChargeList(@Path("savingsId") savingsId: Long?): Observable?>? + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/ClientService.java b/app/src/main/java/org/mifos/mobile/api/services/ClientService.java deleted file mode 100644 index cbd56d9a05..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/ClientService.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.client.ClientAccounts; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.GET; -import retrofit2.http.Path; -import retrofit2.http.Query; - -/** - * @author Vishwajeet - * @since 20/6/16. - */ -public interface ClientService { - - String CLIENT_ID = "clientId"; - - //This is a default call and Loads client from 0 to 200 - @GET(ApiEndPoints.CLIENTS) - Observable> getClients(); - - @GET(ApiEndPoints.CLIENTS + "/{clientId}") - Observable getClientForId(@Path(CLIENT_ID) long clientId); - - @GET(ApiEndPoints.CLIENTS + "/{clientId}/images") - Observable getClientImage(@Path(CLIENT_ID) long clientId); - - @GET(ApiEndPoints.CLIENTS + "/{clientId}/accounts") - Observable getClientAccounts(@Path(CLIENT_ID) long clientId); - - @GET(ApiEndPoints.CLIENTS + "/{clientId}/accounts") - Observable getAccounts(@Path(CLIENT_ID) long clientId, - @Query("fields") String accountType); - -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/ClientService.kt b/app/src/main/java/org/mifos/mobile/api/services/ClientService.kt new file mode 100644 index 0000000000..7145d69d8e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/ClientService.kt @@ -0,0 +1,40 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import okhttp3.ResponseBody +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.Page +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.client.ClientAccounts +import retrofit2.http.GET +import retrofit2.http.Path +import retrofit2.http.Query + +/** + * @author Vishwajeet + * @since 20/6/16. + */ +interface ClientService { + //This is a default call and Loads client from 0 to 200 + @get:GET(ApiEndPoints.CLIENTS) + val clients: Observable?>? + + @GET(ApiEndPoints.CLIENTS + "/{clientId}") + fun getClientForId(@Path(CLIENT_ID) clientId: Long?): Observable? + + @GET(ApiEndPoints.CLIENTS + "/{clientId}/images") + fun getClientImage(@Path(CLIENT_ID) clientId: Long?): Observable? + + @GET(ApiEndPoints.CLIENTS + "/{clientId}/accounts") + fun getClientAccounts(@Path(CLIENT_ID) clientId: Long?): Observable? + + @GET(ApiEndPoints.CLIENTS + "/{clientId}/accounts") + fun getAccounts( + @Path(CLIENT_ID) clientId: Long?, + @Query("fields") accountType: String? + ): Observable? + + companion object { + const val CLIENT_ID = "clientId" + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/GuarantorService.java b/app/src/main/java/org/mifos/mobile/api/services/GuarantorService.java deleted file mode 100644 index 976b1ed180..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/GuarantorService.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.mifos.mobile.api.services; - -/* - * Created by saksham on 23/July/2018 - */ - -import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload; - -import java.util.List; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.DELETE; -import retrofit2.http.GET; -import retrofit2.http.POST; -import retrofit2.http.PUT; -import retrofit2.http.Path; - -@SuppressWarnings("PMD.AvoidDuplicateLiterals") -public interface GuarantorService { - - @GET("/loans/{loanId}/guarantors/template") - Observable getGuarantorTemplate(@Path("loanId") long loanId); - - @GET("/loans/{loanId}/guarantors") - Observable> getGuarantorList(@Path("loanId") long loanId); - - @POST("/loans/{loanId}/guarantors") - Observable createGuarantor(@Path("loanId") long loanId, - @Body GuarantorApplicationPayload payload); - - @PUT("loans/{loanId}/guarantors/{guarantorId}") - Observable updateGuarantor(@Body GuarantorApplicationPayload payload, - @Path("loanId") long loanId, - @Path("guarantorId") long guarantorId); - - @DELETE("/loans/{loanId}/guarantors/{guarantorId}") - Observable deleteGuarantor(@Path("loanId") long loanId, - @Path("guarantorId") long guarantorId); - -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/GuarantorService.kt b/app/src/main/java/org/mifos/mobile/api/services/GuarantorService.kt new file mode 100644 index 0000000000..e6caa5e45c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/GuarantorService.kt @@ -0,0 +1,40 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload + +import retrofit2.http.* + +/* +* Created by saksham on 23/July/2018 +*/ interface GuarantorService { + @GET("/loans/{loanId}/guarantors/template") + fun getGuarantorTemplate(@Path("loanId") loanId: Long?): Observable? + + @GET("/loans/{loanId}/guarantors") + fun getGuarantorList(@Path("loanId") loanId: Long?): Observable?>? + + @POST("/loans/{loanId}/guarantors") + fun createGuarantor( + @Path("loanId") loanId: Long?, + @Body payload: GuarantorApplicationPayload? + ): Observable? + + @PUT("loans/{loanId}/guarantors/{guarantorId}") + fun updateGuarantor( + @Body payload: GuarantorApplicationPayload?, + @Path("loanId") loanId: Long?, + @Path("guarantorId") guarantorId: Long? + ): Observable? + + @DELETE("/loans/{loanId}/guarantors/{guarantorId}") + fun deleteGuarantor( + @Path("loanId") loanId: Long?, + @Path("guarantorId") guarantorId: Long? + ): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/LoanAccountsListService.java b/app/src/main/java/org/mifos/mobile/api/services/LoanAccountsListService.java deleted file mode 100644 index 92cdeecb6f..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/LoanAccountsListService.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.models.accounts.loan.LoanWithdraw; -import org.mifos.mobile.models.payload.LoansPayload; -import org.mifos.mobile.models.templates.loans.LoanTemplate; -import org.mifos.mobile.utils.Constants; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.GET; -import retrofit2.http.POST; -import retrofit2.http.PUT; -import retrofit2.http.Path; -import retrofit2.http.Query; - -/** - * @author Vishwajeet - * @since 23/6/16. - */ -public interface LoanAccountsListService { - - @GET(ApiEndPoints.LOANS + "/{loanId}/") - Observable getLoanAccountsDetail(@Path("loanId") long loanId); - - @GET(ApiEndPoints.LOANS + "/{loanId}") - Observable getLoanWithAssociations( - @Path("loanId") long loanId, - @Query("associations") String associationType); - - @GET(ApiEndPoints.LOANS + "/template?templateType=individual") - Observable getLoanTemplate(@Query("clientId") long clientId); - - @GET(ApiEndPoints.LOANS + "/template?templateType=individual") - Observable getLoanTemplateByProduct( - @Query("clientId") long clientId, - @Query("productId") Integer productId); - - @POST(ApiEndPoints.LOANS) - Observable createLoansAccount(@Body LoansPayload loansPayload); - - @PUT(ApiEndPoints.LOANS + "/{loanId}/") - Observable updateLoanAccount(@Path("loanId") long loanId, - @Body LoansPayload loansPayload); - - @POST(ApiEndPoints.LOANS + "/{loanId}?command=withdrawnByApplicant") - Observable withdrawLoanAccount(@Path(Constants.LOAN_ID) long loanId, - @Body LoanWithdraw loanWithdraw); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/LoanAccountsListService.kt b/app/src/main/java/org/mifos/mobile/api/services/LoanAccountsListService.kt new file mode 100644 index 0000000000..a6d697152f --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/LoanAccountsListService.kt @@ -0,0 +1,51 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import okhttp3.ResponseBody +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.models.accounts.loan.LoanWithdraw +import org.mifos.mobile.models.payload.LoansPayload +import org.mifos.mobile.models.templates.loans.LoanTemplate +import org.mifos.mobile.utils.Constants +import retrofit2.http.* + +/** + * @author Vishwajeet + * @since 23/6/16. + */ +interface LoanAccountsListService { + @GET(ApiEndPoints.LOANS + "/{loanId}/") + fun getLoanAccountsDetail(@Path("loanId") loanId: Long): Observable? + + @GET(ApiEndPoints.LOANS + "/{loanId}") + fun getLoanWithAssociations( + @Path("loanId") loanId: Long?, + @Query("associations") associationType: String? + ): Observable? + + @GET(ApiEndPoints.LOANS + "/template?templateType=individual") + fun getLoanTemplate(@Query("clientId") clientId: Long?): Observable? + + @GET(ApiEndPoints.LOANS + "/template?templateType=individual") + fun getLoanTemplateByProduct( + @Query("clientId") clientId: Long?, + @Query("productId") productId: Int? + ): Observable? + + @POST(ApiEndPoints.LOANS) + fun createLoansAccount(@Body loansPayload: LoansPayload?): Observable? + + @PUT(ApiEndPoints.LOANS + "/{loanId}/") + fun updateLoanAccount( + @Path("loanId") loanId: Long, + @Body loansPayload: LoansPayload? + ): Observable? + + @POST(ApiEndPoints.LOANS + "/{loanId}?command=withdrawnByApplicant") + fun withdrawLoanAccount( + @Path(Constants.LOAN_ID) loanId: Long?, + @Body loanWithdraw: LoanWithdraw? + ): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/NotificationService.java b/app/src/main/java/org/mifos/mobile/api/services/NotificationService.java deleted file mode 100644 index af6e52d54d..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/NotificationService.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.notification.NotificationRegisterPayload; -import org.mifos.mobile.models.notification.NotificationUserDetail; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.GET; -import retrofit2.http.POST; -import retrofit2.http.PUT; -import retrofit2.http.Path; - -/** - * Created by dilpreet on 26/09/17. - */ - -public interface NotificationService { - - @GET(ApiEndPoints.DEVICE + "/registration/client/{clientId}") - Observable getUserNotificationId(@Path("clientId")long clientId); - - @POST(ApiEndPoints.DEVICE + "/registration") - Observable registerNotification(@Body NotificationRegisterPayload payload); - - @PUT(ApiEndPoints.DEVICE + "/registration/{id}") - Observable updateRegisterNotification(@Path("id")long id, - @Body NotificationRegisterPayload payload); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/NotificationService.kt b/app/src/main/java/org/mifos/mobile/api/services/NotificationService.kt new file mode 100644 index 0000000000..fa8979783e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/NotificationService.kt @@ -0,0 +1,25 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import okhttp3.ResponseBody +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.notification.NotificationRegisterPayload +import org.mifos.mobile.models.notification.NotificationUserDetail +import retrofit2.http.* + +/** + * Created by dilpreet on 26/09/17. + */ +interface NotificationService { + @GET(ApiEndPoints.DEVICE + "/registration/client/{clientId}") + fun getUserNotificationId(@Path("clientId") clientId: Long): Observable? + + @POST(ApiEndPoints.DEVICE + "/registration") + fun registerNotification(@Body payload: NotificationRegisterPayload?): Observable? + + @PUT(ApiEndPoints.DEVICE + "/registration/{id}") + fun updateRegisterNotification( + @Path("id") id: Long, + @Body payload: NotificationRegisterPayload? + ): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/RecentTransactionsService.java b/app/src/main/java/org/mifos/mobile/api/services/RecentTransactionsService.java deleted file mode 100644 index ed5236e8b4..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/RecentTransactionsService.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.Transaction; - -import io.reactivex.Observable; -import retrofit2.http.GET; -import retrofit2.http.Path; -import retrofit2.http.Query; - -/** - * @author Vishwajeet - * @since 10/08/2016 - */ -public interface RecentTransactionsService { - @GET(ApiEndPoints.CLIENTS + "/{clientId}/transactions") - Observable> getRecentTransactionsList( - @Path("clientId") long clientId, - @Query("offset") int offset, - @Query("limit") int limit); -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/RecentTransactionsService.kt b/app/src/main/java/org/mifos/mobile/api/services/RecentTransactionsService.kt new file mode 100644 index 0000000000..1047322b7b --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/RecentTransactionsService.kt @@ -0,0 +1,22 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.Page +import org.mifos.mobile.models.Transaction +import retrofit2.http.GET +import retrofit2.http.Path +import retrofit2.http.Query + +/** + * @author Vishwajeet + * @since 10/08/2016 + */ +interface RecentTransactionsService { + @GET(ApiEndPoints.CLIENTS + "/{clientId}/transactions") + fun getRecentTransactionsList( + @Path("clientId") clientId: Long?, + @Query("offset") offset: Int?, + @Query("limit") limit: Int? + ): Observable?>? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/RegistrationService.java b/app/src/main/java/org/mifos/mobile/api/services/RegistrationService.java deleted file mode 100644 index c866a277e6..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/RegistrationService.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.register.RegisterPayload; -import org.mifos.mobile.models.register.UserVerify; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.POST; - -/** - * Created by dilpreet on 31/7/17. - */ - -public interface RegistrationService { - - @POST(ApiEndPoints.REGISTRATION) - Observable registerUser(@Body RegisterPayload registerPayload); - - @POST(ApiEndPoints.REGISTRATION + "/user") - Observable verifyUser(@Body UserVerify userVerify); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/RegistrationService.kt b/app/src/main/java/org/mifos/mobile/api/services/RegistrationService.kt new file mode 100644 index 0000000000..2661d97b71 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/RegistrationService.kt @@ -0,0 +1,20 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import okhttp3.ResponseBody +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.register.RegisterPayload +import org.mifos.mobile.models.register.UserVerify +import retrofit2.http.Body +import retrofit2.http.POST + +/** + * Created by dilpreet on 31/7/17. + */ +interface RegistrationService { + @POST(ApiEndPoints.REGISTRATION) + fun registerUser(@Body registerPayload: RegisterPayload?): Observable? + + @POST(ApiEndPoints.REGISTRATION + "/user") + fun verifyUser(@Body userVerify: UserVerify?): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/SavingAccountsListService.java b/app/src/main/java/org/mifos/mobile/api/services/SavingAccountsListService.java deleted file mode 100644 index 3ee0efe351..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/SavingAccountsListService.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload; -import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload; -import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.GET; -import retrofit2.http.POST; -import retrofit2.http.PUT; -import retrofit2.http.Path; -import retrofit2.http.Query; - -/** - * @author Vishwajeet - * @since 21/6/16. - */ -public interface SavingAccountsListService { - - @GET(ApiEndPoints.SAVINGS_ACCOUNTS + "/{accountId}") - Observable getSavingsWithAssociations( - @Path("accountId") long accountId, - @Query("associations") String associationType); - - @GET(ApiEndPoints.ACCOUNT_TRANSFER + "/template") - Observable getAccountTransferTemplate(); - - @POST(ApiEndPoints.ACCOUNT_TRANSFER) - Observable makeTransfer(@Body TransferPayload transferPayload); - - @GET(ApiEndPoints.SAVINGS_ACCOUNTS + "/template") - Observable getSavingsAccountApplicationTemplate( - @Query("clientId") long clientId); - - @POST(ApiEndPoints.SAVINGS_ACCOUNTS) - Observable submitSavingAccountApplication( - @Body SavingsAccountApplicationPayload payload); - - @PUT(ApiEndPoints.SAVINGS_ACCOUNTS + "/{accountsId}") - Observable updateSavingsAccountUpdate( - @Path("accountsId") String accountsId, @Body SavingsAccountUpdatePayload payload); - - @POST(ApiEndPoints.SAVINGS_ACCOUNTS + "/{savingsId}?command=withdrawnByApplicant") - Observable submitWithdrawSavingsAccount( - @Path("savingsId") String savingsId, @Body SavingsAccountWithdrawPayload payload); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/SavingAccountsListService.kt b/app/src/main/java/org/mifos/mobile/api/services/SavingAccountsListService.kt new file mode 100644 index 0000000000..a79592307a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/SavingAccountsListService.kt @@ -0,0 +1,54 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload +import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload +import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate + +import retrofit2.http.* + +/** + * @author Vishwajeet + * @since 21/6/16. + */ +interface SavingAccountsListService { + @GET(ApiEndPoints.SAVINGS_ACCOUNTS + "/{accountId}") + fun getSavingsWithAssociations( + @Path("accountId") accountId: Long?, + @Query("associations") associationType: String? + ): Observable? + + @get:GET(ApiEndPoints.ACCOUNT_TRANSFER + "/template") + val accountTransferTemplate: Observable? + + @POST(ApiEndPoints.ACCOUNT_TRANSFER) + fun makeTransfer(@Body transferPayload: TransferPayload?): Observable? + + @GET(ApiEndPoints.SAVINGS_ACCOUNTS + "/template") + fun getSavingsAccountApplicationTemplate( + @Query("clientId") clientId: Long? + ): Observable? + + @POST(ApiEndPoints.SAVINGS_ACCOUNTS) + fun submitSavingAccountApplication( + @Body payload: SavingsAccountApplicationPayload? + ): Observable? + + @PUT(ApiEndPoints.SAVINGS_ACCOUNTS + "/{accountsId}") + fun updateSavingsAccountUpdate( + @Path("accountsId") accountsId: String?, @Body payload: SavingsAccountUpdatePayload? + ): Observable? + + @POST(ApiEndPoints.SAVINGS_ACCOUNTS + "/{savingsId}?command=withdrawnByApplicant") + fun submitWithdrawSavingsAccount( + @Path("savingsId") savingsId: String?, @Body payload: SavingsAccountWithdrawPayload? + ): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/ThirdPartyTransferService.java b/app/src/main/java/org/mifos/mobile/api/services/ThirdPartyTransferService.java deleted file mode 100644 index 16b7f388bc..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/ThirdPartyTransferService.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifos.mobile.api.services; - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.GET; -import retrofit2.http.POST; - -/** - * Created by dilpreet on 21/6/17. - */ - -public interface ThirdPartyTransferService { - - @GET(ApiEndPoints.ACCOUNT_TRANSFER + "/template?type=tpt") - Observable getAccountTransferTemplate(); - - @POST(ApiEndPoints.ACCOUNT_TRANSFER + "?type=\"tpt\"") - Observable makeTransfer(@Body TransferPayload transferPayload); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/ThirdPartyTransferService.kt b/app/src/main/java/org/mifos/mobile/api/services/ThirdPartyTransferService.kt new file mode 100644 index 0000000000..bafeaf3496 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/ThirdPartyTransferService.kt @@ -0,0 +1,21 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import okhttp3.ResponseBody +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import retrofit2.http.Body +import retrofit2.http.GET +import retrofit2.http.POST + +/** + * Created by dilpreet on 21/6/17. + */ +interface ThirdPartyTransferService { + @get:GET(ApiEndPoints.ACCOUNT_TRANSFER + "/template?type=tpt") + val accountTransferTemplate: Observable? + + @POST(ApiEndPoints.ACCOUNT_TRANSFER + "?type=\"tpt\"") + fun makeTransfer(@Body transferPayload: TransferPayload?): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/api/services/UserDetailsService.java b/app/src/main/java/org/mifos/mobile/api/services/UserDetailsService.java deleted file mode 100644 index 02f120cadb..0000000000 --- a/app/src/main/java/org/mifos/mobile/api/services/UserDetailsService.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.api.services; - -/* - * Created by saksham on 13/July/2018 - */ - -import org.mifos.mobile.api.ApiEndPoints; -import org.mifos.mobile.models.UpdatePasswordPayload; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; -import retrofit2.http.Body; -import retrofit2.http.PUT; - -public interface UserDetailsService { - - @PUT(ApiEndPoints.USER) - Observable updateAccountPassword(@Body UpdatePasswordPayload payload); -} diff --git a/app/src/main/java/org/mifos/mobile/api/services/UserDetailsService.kt b/app/src/main/java/org/mifos/mobile/api/services/UserDetailsService.kt new file mode 100644 index 0000000000..4b14de99c7 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/api/services/UserDetailsService.kt @@ -0,0 +1,15 @@ +package org.mifos.mobile.api.services + +import io.reactivex.Observable +import okhttp3.ResponseBody +import org.mifos.mobile.api.ApiEndPoints +import org.mifos.mobile.models.UpdatePasswordPayload +import retrofit2.http.Body +import retrofit2.http.PUT + +/* +* Created by saksham on 13/July/2018 +*/ interface UserDetailsService { + @PUT(ApiEndPoints.USER) + fun updateAccountPassword(@Body payload: UpdatePasswordPayload?): Observable? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/injection/ActivityContext.java b/app/src/main/java/org/mifos/mobile/injection/ActivityContext.java deleted file mode 100644 index 92ee92206b..0000000000 --- a/app/src/main/java/org/mifos/mobile/injection/ActivityContext.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.mifos.mobile.injection; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import javax.inject.Qualifier; - -/** - * @author ishan - * @since 08/07/16 - */ -@Qualifier -@Retention(RetentionPolicy.RUNTIME) -public @interface ActivityContext { -} diff --git a/app/src/main/java/org/mifos/mobile/injection/ActivityContext.kt b/app/src/main/java/org/mifos/mobile/injection/ActivityContext.kt new file mode 100644 index 0000000000..a3b4113564 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/injection/ActivityContext.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.injection + +import javax.inject.Qualifier + +/** + * @author ishan + * @since 08/07/16 + */ +@Qualifier +@kotlin.annotation.Retention(AnnotationRetention.RUNTIME) +annotation class ActivityContext \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/injection/ApplicationContext.java b/app/src/main/java/org/mifos/mobile/injection/ApplicationContext.java deleted file mode 100644 index 0342198b97..0000000000 --- a/app/src/main/java/org/mifos/mobile/injection/ApplicationContext.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.mifos.mobile.injection; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import javax.inject.Qualifier; - -/** - * @author ishan - * @since 08/07/16 - */ -@Qualifier -@Retention(RetentionPolicy.RUNTIME) -public @interface ApplicationContext { -} diff --git a/app/src/main/java/org/mifos/mobile/injection/ApplicationContext.kt b/app/src/main/java/org/mifos/mobile/injection/ApplicationContext.kt new file mode 100644 index 0000000000..14ed9a361c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/injection/ApplicationContext.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.injection + +import javax.inject.Qualifier + +/** + * @author ishan + * @since 08/07/16 + */ +@Qualifier +@kotlin.annotation.Retention(AnnotationRetention.RUNTIME) +annotation class ApplicationContext \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/injection/PerActivity.java b/app/src/main/java/org/mifos/mobile/injection/PerActivity.java deleted file mode 100644 index 9a8e8a8c29..0000000000 --- a/app/src/main/java/org/mifos/mobile/injection/PerActivity.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.injection; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import javax.inject.Scope; - -/** - * A scoping annotation to permit objects whose lifetime should - * conform to the life of the Activity to be memorised in the - * correct component. - * - * @author ishan - * @since 08/07/16 - */ -@Scope -@Retention(RetentionPolicy.RUNTIME) -public @interface PerActivity { -} diff --git a/app/src/main/java/org/mifos/mobile/injection/PerActivity.kt b/app/src/main/java/org/mifos/mobile/injection/PerActivity.kt new file mode 100644 index 0000000000..303a76cf3a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/injection/PerActivity.kt @@ -0,0 +1,15 @@ +package org.mifos.mobile.injection + +import javax.inject.Scope + +/** + * A scoping annotation to permit objects whose lifetime should + * conform to the life of the Activity to be memorised in the + * correct component. + * + * @author ishan + * @since 08/07/16 + */ +@Scope +@kotlin.annotation.Retention(AnnotationRetention.RUNTIME) +annotation class PerActivity \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/injection/component/ActivityComponent.java b/app/src/main/java/org/mifos/mobile/injection/component/ActivityComponent.java deleted file mode 100644 index c66ad96bc4..0000000000 --- a/app/src/main/java/org/mifos/mobile/injection/component/ActivityComponent.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.mifos.mobile.injection.component; - -import org.mifos.mobile.injection.PerActivity; -import org.mifos.mobile.injection.module.ActivityModule; -import org.mifos.mobile.ui.activities.HomeActivity; -import org.mifos.mobile.ui.activities.SplashActivity; -import org.mifos.mobile.ui.fragments.AccountOverviewFragment; -import org.mifos.mobile.ui.fragments.AddGuarantorFragment; -import org.mifos.mobile.ui.fragments.BeneficiaryAddOptionsFragment; -import org.mifos.mobile.ui.activities.PassCodeActivity; -import org.mifos.mobile.ui.fragments.BeneficiaryApplicationFragment; -import org.mifos.mobile.ui.fragments.BeneficiaryDetailFragment; -import org.mifos.mobile.ui.fragments.BeneficiaryListFragment; -import org.mifos.mobile.ui.fragments.GuarantorDetailFragment; -import org.mifos.mobile.ui.fragments.GuarantorListFragment; -import org.mifos.mobile.ui.fragments.HelpFragment; -import org.mifos.mobile.ui.fragments.HomeOldFragment; -import org.mifos.mobile.ui.fragments.LoanAccountTransactionFragment; -import org.mifos.mobile.ui.fragments.LoanAccountWithdrawFragment; -import org.mifos.mobile.ui.fragments.LoanAccountsDetailFragment; -import org.mifos.mobile.ui.activities.LoginActivity; -import org.mifos.mobile.ui.fragments.LoanApplicationFragment; -import org.mifos.mobile.ui.fragments.NotificationFragment; -import org.mifos.mobile.ui.fragments.QrCodeImportFragment; -import org.mifos.mobile.ui.fragments.RegistrationFragment; -import org.mifos.mobile.ui.fragments.RegistrationVerificationFragment; -import org.mifos.mobile.ui.fragments.ReviewLoanApplicationFragment; -import org.mifos.mobile.ui.fragments.SavingAccountsDetailFragment; -import org.mifos.mobile.ui.fragments.AccountsFragment; -import org.mifos.mobile.ui.fragments.HomeFragment; -import org.mifos.mobile.ui.fragments.ClientAccountsFragment; -import org.mifos.mobile.ui.fragments.ClientChargeFragment; -import org.mifos.mobile.ui.fragments.LoanAccountSummaryFragment; -import org.mifos.mobile.ui.fragments.LoanRepaymentScheduleFragment; -import org.mifos.mobile.ui.fragments.RecentTransactionsFragment; -import org.mifos.mobile.ui.fragments.SavingAccountsTransactionFragment; -import org.mifos.mobile.ui.fragments.SavingsAccountApplicationFragment; -import org.mifos.mobile.ui.fragments.SavingsAccountWithdrawFragment; -import org.mifos.mobile.ui.fragments.SavingsMakeTransferFragment; -import org.mifos.mobile.ui.fragments.ThirdPartyTransferFragment; -import org.mifos.mobile.ui.fragments.TransferProcessFragment; -import org.mifos.mobile.ui.fragments.UpdatePasswordFragment; -import org.mifos.mobile.ui.fragments.UserProfileFragment; - -import dagger.Component; - -/** - * @author ishan - * @since 08/07/16 - */ -@PerActivity -@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) -public interface ActivityComponent { - - void inject(LoginActivity loginActivity); - - void inject(HomeActivity homeActivity); - - void inject(PassCodeActivity passCodeActivity); - - void inject(HomeFragment homeFragment); - - void inject(ClientAccountsFragment clientAccountsFragment); - - void inject(RecentTransactionsFragment recentTransactionsFragment); - - void inject(ClientChargeFragment clientChargeFragment); - - void inject(SavingAccountsDetailFragment savingAccountsDetailActivity); - - void inject(LoanAccountsDetailFragment loanAccountsDetailActivity); - - void inject(AccountsFragment accountsFragment); - - void inject(LoanAccountSummaryFragment loanAccountSummaryFragment); - - void inject(LoanAccountTransactionFragment loanAccountTransactionFragment); - - void inject(LoanRepaymentScheduleFragment loanRepaymentScheduleFragment); - - void inject(LoanApplicationFragment loanApplicationFragment); - - void inject(LoanAccountWithdrawFragment loanAccountWithdrawFragment); - - void inject(SavingAccountsTransactionFragment savingAccountsTransactionFragment); - - void inject(SavingsMakeTransferFragment savingsMakeTransferFragment); - - void inject(BeneficiaryAddOptionsFragment beneficiaryAddOptionsFragment); - - void inject(BeneficiaryListFragment beneficiaryListFragment); - - void inject(BeneficiaryApplicationFragment beneficiaryApplicationFragment); - - void inject(BeneficiaryDetailFragment beneficiaryDetailFragment); - - void inject(ThirdPartyTransferFragment thirdPartyTransferFragment); - - void inject(TransferProcessFragment transferProcessFragment); - - void inject(UserProfileFragment userProfileFragment); - - void inject(HelpFragment helpFragment); - - void inject(RegistrationFragment registrationFragment); - - void inject(RegistrationVerificationFragment registrationVerificationFragment); - - void inject(AccountOverviewFragment accountOverviewFragment); - - void inject(HomeOldFragment homeOldFragment); - - void inject(NotificationFragment notificationFragment); - - void inject(QrCodeImportFragment qrCodeImportFragment); - - void inject(SplashActivity splashActivity); - - void inject(AddGuarantorFragment addGuarantorFragment); - - void inject(GuarantorListFragment guarantorListFragment); - - void inject(GuarantorDetailFragment guarantorDetailFragment); - - void inject(UpdatePasswordFragment updatePasswordFragment); - - void inject(SavingsAccountApplicationFragment savingsAccountApplicationFragment); - - void inject(SavingsAccountWithdrawFragment savingsAccountWithdrawFragment); - - void inject(ReviewLoanApplicationFragment reviewLoanApplicationFragment); -} diff --git a/app/src/main/java/org/mifos/mobile/injection/component/ActivityComponent.kt b/app/src/main/java/org/mifos/mobile/injection/component/ActivityComponent.kt new file mode 100644 index 0000000000..c440e16d74 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/injection/component/ActivityComponent.kt @@ -0,0 +1,59 @@ +package org.mifos.mobile.injection.component + +import dagger.Component + +import org.mifos.mobile.injection.PerActivity +import org.mifos.mobile.injection.module.ActivityModule +import org.mifos.mobile.ui.activities.HomeActivity +import org.mifos.mobile.ui.activities.LoginActivity +import org.mifos.mobile.ui.activities.PassCodeActivity +import org.mifos.mobile.ui.activities.SplashActivity +import org.mifos.mobile.ui.fragments.* + +/** + * @author ishan + * @since 08/07/16 + */ +@PerActivity +@Component(dependencies = [ApplicationComponent::class], modules = [ActivityModule::class]) +interface ActivityComponent { + fun inject(loginActivity: LoginActivity?) + fun inject(homeActivity: HomeActivity?) + fun inject(passCodeActivity: PassCodeActivity?) + fun inject(homeFragment: HomeFragment?) + fun inject(clientAccountsFragment: ClientAccountsFragment?) + fun inject(recentTransactionsFragment: RecentTransactionsFragment?) + fun inject(clientChargeFragment: ClientChargeFragment?) + fun inject(savingAccountsDetailActivity: SavingAccountsDetailFragment?) + fun inject(loanAccountsDetailActivity: LoanAccountsDetailFragment?) + fun inject(accountsFragment: AccountsFragment?) + fun inject(loanAccountSummaryFragment: LoanAccountSummaryFragment?) + fun inject(loanAccountTransactionFragment: LoanAccountTransactionFragment?) + fun inject(loanRepaymentScheduleFragment: LoanRepaymentScheduleFragment?) + fun inject(loanApplicationFragment: LoanApplicationFragment?) + fun inject(loanAccountWithdrawFragment: LoanAccountWithdrawFragment?) + fun inject(savingAccountsTransactionFragment: SavingAccountsTransactionFragment?) + fun inject(savingsMakeTransferFragment: SavingsMakeTransferFragment?) + fun inject(beneficiaryAddOptionsFragment: BeneficiaryAddOptionsFragment?) + fun inject(beneficiaryListFragment: BeneficiaryListFragment?) + fun inject(beneficiaryApplicationFragment: BeneficiaryApplicationFragment?) + fun inject(beneficiaryDetailFragment: BeneficiaryDetailFragment?) + fun inject(thirdPartyTransferFragment: ThirdPartyTransferFragment?) + fun inject(transferProcessFragment: TransferProcessFragment?) + fun inject(userProfileFragment: UserProfileFragment?) + fun inject(helpFragment: HelpFragment?) + fun inject(registrationFragment: RegistrationFragment?) + fun inject(registrationVerificationFragment: RegistrationVerificationFragment?) + fun inject(accountOverviewFragment: AccountOverviewFragment?) + fun inject(homeOldFragment: HomeOldFragment?) + fun inject(notificationFragment: NotificationFragment?) + fun inject(qrCodeImportFragment: QrCodeImportFragment?) + fun inject(splashActivity: SplashActivity?) + fun inject(addGuarantorFragment: AddGuarantorFragment?) + fun inject(guarantorListFragment: GuarantorListFragment?) + fun inject(guarantorDetailFragment: GuarantorDetailFragment?) + fun inject(updatePasswordFragment: UpdatePasswordFragment?) + fun inject(savingsAccountApplicationFragment: SavingsAccountApplicationFragment?) + fun inject(savingsAccountWithdrawFragment: SavingsAccountWithdrawFragment?) + fun inject(reviewLoanApplicationFragment: ReviewLoanApplicationFragment?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/injection/component/ApplicationComponent.java b/app/src/main/java/org/mifos/mobile/injection/component/ApplicationComponent.java deleted file mode 100644 index c22dab9693..0000000000 --- a/app/src/main/java/org/mifos/mobile/injection/component/ApplicationComponent.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.mifos.mobile.injection.component; - -import android.app.Application; -import android.content.Context; - -import org.mifos.mobile.api.BaseApiManager; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.DatabaseHelper; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.injection.module.ApplicationModule; - -import javax.inject.Singleton; - -import dagger.Component; - -/** - * @author ishan - * @since 08/07/16 - */ -@Singleton -@Component(modules = ApplicationModule.class) -public interface ApplicationComponent { - - @ApplicationContext - Context context(); - - Application application(); - DataManager dataManager(); - PreferencesHelper prefManager(); - BaseApiManager baseApiManager(); - DatabaseHelper databaseHelper(); - -} diff --git a/app/src/main/java/org/mifos/mobile/injection/component/ApplicationComponent.kt b/app/src/main/java/org/mifos/mobile/injection/component/ApplicationComponent.kt new file mode 100644 index 0000000000..ee164328ea --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/injection/component/ApplicationComponent.kt @@ -0,0 +1,31 @@ +package org.mifos.mobile.injection.component + +import android.app.Application +import android.content.Context + +import dagger.Component + +import org.mifos.mobile.api.BaseApiManager +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.DatabaseHelper +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.injection.module.ApplicationModule + +import javax.inject.Singleton + +/** + * @author ishan + * @since 08/07/16 + */ +@Singleton +@Component(modules = [ApplicationModule::class]) +interface ApplicationComponent { + @ApplicationContext + fun context(): Context? + fun application(): Application? + fun dataManager(): DataManager? + fun prefManager(): PreferencesHelper? + fun baseApiManager(): BaseApiManager? + fun databaseHelper(): DatabaseHelper? +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/injection/module/ActivityModule.java b/app/src/main/java/org/mifos/mobile/injection/module/ActivityModule.java deleted file mode 100644 index e84dfc133f..0000000000 --- a/app/src/main/java/org/mifos/mobile/injection/module/ActivityModule.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.mifos.mobile.injection.module; - -import android.app.Activity; -import android.content.Context; - -import org.mifos.mobile.injection.ActivityContext; - -import dagger.Module; -import dagger.Provides; - -/** - * @author ishan - * @since 08/07/16 - */ -@Module -public class ActivityModule { - - private Activity activity; - - public ActivityModule(Activity activity) { - this.activity = activity; - } - - @Provides - Activity providesActivity() { - return activity; - } - - @Provides - @ActivityContext - Context providesContext() { - return activity; - } - -} diff --git a/app/src/main/java/org/mifos/mobile/injection/module/ActivityModule.kt b/app/src/main/java/org/mifos/mobile/injection/module/ActivityModule.kt new file mode 100644 index 0000000000..3d00e5f24b --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/injection/module/ActivityModule.kt @@ -0,0 +1,27 @@ +package org.mifos.mobile.injection.module + +import android.app.Activity +import android.content.Context + +import dagger.Module +import dagger.Provides + +import org.mifos.mobile.injection.ActivityContext + +/** + * @author ishan + * @since 08/07/16 + */ +@Module +class ActivityModule(private val activity: Activity) { + @Provides + fun providesActivity(): Activity { + return activity + } + + @Provides + @ActivityContext + fun providesContext(): Context { + return activity + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/injection/module/ApplicationModule.java b/app/src/main/java/org/mifos/mobile/injection/module/ApplicationModule.java deleted file mode 100644 index 0e50d66097..0000000000 --- a/app/src/main/java/org/mifos/mobile/injection/module/ApplicationModule.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.mifos.mobile.injection.module; - -import android.app.Application; -import android.content.Context; - -import org.mifos.mobile.api.BaseApiManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.api.local.PreferencesHelper; - -import javax.inject.Singleton; - -import dagger.Module; -import dagger.Provides; - -/** - * @author ishan - * @since 08/07/16 - */ -@Module -public class ApplicationModule { - - private Application application; - - public ApplicationModule(Application application) { - this.application = application; - } - - @Provides - Application provideApplication() { - return application; - } - - @Provides - @ApplicationContext - Context provideContext() { - return application; - } - - @Provides - @Singleton - PreferencesHelper providePrefManager(@ApplicationContext Context context) { - return new PreferencesHelper(context); - } - - @Provides - @Singleton - BaseApiManager provideBaseApiManager(PreferencesHelper preferencesHelper) { - return new BaseApiManager(preferencesHelper); - } -} diff --git a/app/src/main/java/org/mifos/mobile/injection/module/ApplicationModule.kt b/app/src/main/java/org/mifos/mobile/injection/module/ApplicationModule.kt new file mode 100644 index 0000000000..323f167330 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/injection/module/ApplicationModule.kt @@ -0,0 +1,43 @@ +package org.mifos.mobile.injection.module + +import android.app.Application +import android.content.Context + +import dagger.Module +import dagger.Provides + +import org.mifos.mobile.api.BaseApiManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ApplicationContext + +import javax.inject.Singleton + +/** + * @author ishan + * @since 08/07/16 + */ +@Module +class ApplicationModule(private val application: Application) { + @Provides + fun provideApplication(): Application { + return application + } + + @Provides + @ApplicationContext + fun provideContext(): Context { + return application + } + + @Provides + @Singleton + fun providePrefManager(@ApplicationContext context: Context?): PreferencesHelper { + return PreferencesHelper(context) + } + + @Provides + @Singleton + fun provideBaseApiManager(preferencesHelper: PreferencesHelper?): BaseApiManager { + return BaseApiManager(preferencesHelper!!) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/AccountOptionAndBeneficiary.kt b/app/src/main/java/org/mifos/mobile/models/AccountOptionAndBeneficiary.kt index fe0ffdbeae..7dd7ab44d5 100644 --- a/app/src/main/java/org/mifos/mobile/models/AccountOptionAndBeneficiary.kt +++ b/app/src/main/java/org/mifos/mobile/models/AccountOptionAndBeneficiary.kt @@ -9,4 +9,5 @@ import org.mifos.mobile.models.templates.account.AccountOptionsTemplate data class AccountOptionAndBeneficiary( val accountOptionsTemplate: AccountOptionsTemplate, - val beneficiaryList: List) + val beneficiaryList: List +) diff --git a/app/src/main/java/org/mifos/mobile/models/Charge.java b/app/src/main/java/org/mifos/mobile/models/Charge.java deleted file mode 100644 index cc2e299c0b..0000000000 --- a/app/src/main/java/org/mifos/mobile/models/Charge.java +++ /dev/null @@ -1,281 +0,0 @@ -package org.mifos.mobile.models; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.raizlabs.android.dbflow.annotation.Column; -import com.raizlabs.android.dbflow.annotation.PrimaryKey; -import com.raizlabs.android.dbflow.annotation.Table; -import com.raizlabs.android.dbflow.structure.BaseModel; - -import org.mifos.mobile.api.local.SelfServiceDatabase; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vishwajeet - * @since 16/8/16. - */ -@Table(database = SelfServiceDatabase.class) -public class Charge extends BaseModel implements Parcelable { - - @PrimaryKey - Integer id; - - Integer clientId; - Integer chargeId; - - @Column - String name; - - List dueDate = new ArrayList<>(); - ChargeTimeType chargeTimeType; - ChargeCalculationType chargeCalculationType; - Currency currency; - - @Column - Double amount = 0.0; - - @Column - Double amountPaid = 0.0; - - @Column - Double amountWaived = 0.0; - - @Column - Double amountWrittenOff = 0.0; - - @Column - Double amountOutstanding = 0.0; - - Boolean penalty = false; - - @Column - Boolean isActive = false; - - Boolean isPaid = false; - Boolean isWaived = false; - - Boolean paid = false; - Boolean waived = false; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getChargeId() { - return chargeId; - } - - public void setChargeId(int chargeId) { - this.chargeId = chargeId; - } - - public int getClientId() { - return chargeId; - } - - public void setClientId(int clientId) { - this.clientId = clientId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public double getAmount() { - return amount; - } - - public void setAmount(double amount) { - this.amount = amount; - } - - public double getAmountPaid() { - return amountPaid; - } - - public void setAmountPaid(double amountPaid) { - this.amountPaid = amountPaid; - } - - public double getAmountWaived() { - return amountWaived; - } - - public void setAmountWaived(double amountWaived) { - this.amountWaived = amountWaived; - } - - public double getAmountWrittenOff() { - return amountWrittenOff; - } - - public void setAmountWrittenOff(double amountWrittenOff) { - this.amountWrittenOff = amountWrittenOff; - } - - public double getAmountOutstanding() { - return amountOutstanding; - } - - public void setAmountOutstanding(double amountOutstanding) { - this.amountOutstanding = amountOutstanding; - } - - public List getDueDate() { - return dueDate; - } - - public void setDueDate(List dueDate) { - this.dueDate = dueDate; - } - - public Currency getCurrency() { - return currency; - } - - public void setCurrency(Currency currency) { - this.currency = currency; - } - - public ChargeTimeType getChargeTimeType() { - return chargeTimeType; - } - - public void setChargeTimeType(ChargeTimeType chargeTimeType) { - this.chargeTimeType = chargeTimeType; - } - - public ChargeCalculationType getChargeCalculationType() { - return chargeCalculationType; - } - - public void setChargeCalculationType(ChargeCalculationType chargeCalculationType) { - this.chargeCalculationType = chargeCalculationType; - } - - public boolean isPenalty() { - return penalty; - } - - public void setPenalty(boolean penalty) { - this.penalty = penalty; - } - - public boolean isIsActive() { - return isActive; - } - - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - public boolean isIsPaid() { - return isPaid; - } - - public void setPaid(boolean isPaid) { - this.isPaid = isPaid; - } - - public boolean isIsWaived() { - return isWaived; - } - - public void setWaived(boolean isWaived) { - this.isWaived = isWaived; - } - - public Boolean getPaid() { - return paid; - } - - public void setPaid(Boolean paid) { - this.paid = paid; - } - - public Boolean getWaived() { - return waived; - } - - public void setWaived(Boolean waived) { - this.waived = waived; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeValue(this.id); - dest.writeValue(this.clientId); - dest.writeValue(this.chargeId); - dest.writeString(this.name); - dest.writeList(this.dueDate); - dest.writeParcelable(this.chargeTimeType, flags); - dest.writeParcelable(this.chargeCalculationType, flags); - dest.writeParcelable(this.currency, flags); - dest.writeValue(this.amount); - dest.writeValue(this.amountPaid); - dest.writeValue(this.amountWaived); - dest.writeValue(this.amountWrittenOff); - dest.writeValue(this.amountOutstanding); - dest.writeValue(this.penalty); - dest.writeValue(this.isActive); - dest.writeValue(this.isPaid); - dest.writeValue(this.isWaived); - dest.writeValue(this.paid); - dest.writeValue(this.waived); - } - - public Charge() { - } - - protected Charge(Parcel in) { - this.id = (Integer) in.readValue(Integer.class.getClassLoader()); - this.clientId = (Integer) in.readValue(Integer.class.getClassLoader()); - this.chargeId = (Integer) in.readValue(Integer.class.getClassLoader()); - this.name = in.readString(); - this.dueDate = new ArrayList<>(); - in.readList(this.dueDate, Integer.class.getClassLoader()); - this.chargeTimeType = in.readParcelable(ChargeTimeType.class.getClassLoader()); - this.chargeCalculationType = in.readParcelable(ChargeCalculationType.class. - getClassLoader()); - this.currency = in.readParcelable(Currency.class.getClassLoader()); - this.amount = (Double) in.readValue(Double.class.getClassLoader()); - this.amountPaid = (Double) in.readValue(Double.class.getClassLoader()); - this.amountWaived = (Double) in.readValue(Double.class.getClassLoader()); - this.amountWrittenOff = (Double) in.readValue(Double.class.getClassLoader()); - this.amountOutstanding = (Double) in.readValue(Double.class.getClassLoader()); - this.penalty = (Boolean) in.readValue(Boolean.class.getClassLoader()); - this.isActive = (Boolean) in.readValue(Boolean.class.getClassLoader()); - this.isPaid = (Boolean) in.readValue(Boolean.class.getClassLoader()); - this.isWaived = (Boolean) in.readValue(Boolean.class.getClassLoader()); - this.paid = (Boolean) in.readValue(Boolean.class.getClassLoader()); - this.waived = (Boolean) in.readValue(Boolean.class.getClassLoader()); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public Charge createFromParcel(Parcel source) { - return new Charge(source); - } - - @Override - public Charge[] newArray(int size) { - return new Charge[size]; - } - }; -} diff --git a/app/src/main/java/org/mifos/mobile/models/Charge.kt b/app/src/main/java/org/mifos/mobile/models/Charge.kt new file mode 100644 index 0000000000..c36eb032a6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/models/Charge.kt @@ -0,0 +1,123 @@ +package org.mifos.mobile.models + +import android.os.Parcel +import android.os.Parcelable + +import com.raizlabs.android.dbflow.annotation.Column +import com.raizlabs.android.dbflow.annotation.PrimaryKey +import com.raizlabs.android.dbflow.annotation.Table +import com.raizlabs.android.dbflow.structure.BaseModel + +import org.mifos.mobile.api.local.SelfServiceDatabase + +import java.util.* + +/** + * @author Vishwajeet + * @since 16/8/16. + */ +@Table(database = SelfServiceDatabase::class) +class Charge : BaseModel, Parcelable { + @JvmField + @PrimaryKey + var id: Int? = null + + var clientId: Int? = null + private var chargeId: Int? = null + + @Column + var name: String? = null + + var dueDate: List = ArrayList() + private var chargeTimeType: ChargeTimeType? = null + private var chargeCalculationType: ChargeCalculationType? = null + var currency: Currency? = null + + @Column + var amount = 0.0 + + @Column + var amountPaid = 0.0 + + @Column + var amountWaived = 0.0 + + @Column + var amountWrittenOff = 0.0 + + @Column + var amountOutstanding = 0.0 + + var penalty = false + + @Column + var isActive = false + + var isPaid: Boolean? = false + var isWaived: Boolean? = false + + var paid = false + var waived = false + + override fun describeContents(): Int { + return 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeValue(id) + dest.writeValue(clientId) + dest.writeValue(chargeId) + dest.writeString(name) + dest.writeList(dueDate) + dest.writeParcelable(chargeTimeType, flags) + dest.writeParcelable(chargeCalculationType, flags) + dest.writeParcelable(currency, flags) + dest.writeValue(amount) + dest.writeValue(amountPaid) + dest.writeValue(amountWaived) + dest.writeValue(amountWrittenOff) + dest.writeValue(amountOutstanding) + dest.writeValue(penalty) + dest.writeValue(isActive) + dest.writeValue(isPaid) + dest.writeValue(isWaived) + dest.writeValue(paid) + dest.writeValue(waived) + } + + constructor() + private constructor(`in`: Parcel) { + id = `in`.readValue(Int::class.java.classLoader) as Int + clientId = `in`.readValue(Int::class.java.classLoader) as Int + chargeId = `in`.readValue(Int::class.java.classLoader) as Int + name = `in`.readString() + dueDate = ArrayList() + `in`.readList(dueDate, Int::class.java.classLoader) + chargeTimeType = `in`.readParcelable(ChargeTimeType::class.java.classLoader) + chargeCalculationType = `in`.readParcelable(ChargeCalculationType::class.java.classLoader) + currency = `in`.readParcelable(Currency::class.java.classLoader) + amount = `in`.readValue(Double::class.java.classLoader) as Double + amountPaid = `in`.readValue(Double::class.java.classLoader) as Double + amountWaived = `in`.readValue(Double::class.java.classLoader) as Double + amountWrittenOff = `in`.readValue(Double::class.java.classLoader) as Double + amountOutstanding = `in`.readValue(Double::class.java.classLoader) as Double + penalty = `in`.readValue(Boolean::class.java.classLoader) as Boolean + isActive = `in`.readValue(Boolean::class.java.classLoader) as Boolean + isPaid = `in`.readValue(Boolean::class.java.classLoader) as Boolean + isWaived = `in`.readValue(Boolean::class.java.classLoader) as Boolean + paid = `in`.readValue(Boolean::class.java.classLoader) as Boolean + waived = `in`.readValue(Boolean::class.java.classLoader) as Boolean + } + + companion object { + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(source: Parcel): Charge? { + return Charge(source) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/ChargeListResponse.kt b/app/src/main/java/org/mifos/mobile/models/ChargeListResponse.kt index 1867004577..772e56aeb7 100644 --- a/app/src/main/java/org/mifos/mobile/models/ChargeListResponse.kt +++ b/app/src/main/java/org/mifos/mobile/models/ChargeListResponse.kt @@ -1,6 +1,6 @@ package org.mifos.mobile.models -import java.util.ArrayList +import java.util.* /** * @author Vishwajeet diff --git a/app/src/main/java/org/mifos/mobile/models/Page.kt b/app/src/main/java/org/mifos/mobile/models/Page.kt index 015b2fd2a8..27d3e272f9 100644 --- a/app/src/main/java/org/mifos/mobile/models/Page.kt +++ b/app/src/main/java/org/mifos/mobile/models/Page.kt @@ -1,6 +1,6 @@ package org.mifos.mobile.models -import java.util.ArrayList +import java.util.* /** * @author Rajan Maurya diff --git a/app/src/main/java/org/mifos/mobile/models/Timeline.kt b/app/src/main/java/org/mifos/mobile/models/Timeline.kt index 4a89ca0d51..29191386ef 100644 --- a/app/src/main/java/org/mifos/mobile/models/Timeline.kt +++ b/app/src/main/java/org/mifos/mobile/models/Timeline.kt @@ -2,8 +2,7 @@ package org.mifos.mobile.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize - -import java.util.ArrayList +import java.util.* /** * Created by ishankhanna for mifos android-client on 09/02/14. diff --git a/app/src/main/java/org/mifos/mobile/models/Transaction.kt b/app/src/main/java/org/mifos/mobile/models/Transaction.kt index d2bdbe6843..646e807086 100644 --- a/app/src/main/java/org/mifos/mobile/models/Transaction.kt +++ b/app/src/main/java/org/mifos/mobile/models/Transaction.kt @@ -1,14 +1,10 @@ package org.mifos.mobile.models import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.client.Currency import org.mifos.mobile.models.client.Type - -import java.util.ArrayList +import java.util.* /** * @author Vishwajeet @@ -17,31 +13,23 @@ import java.util.ArrayList @Parcelize data class Transaction( - @SerializedName("id") + var id: Long? = null, - @SerializedName("officeId") var officeId: Long? = null, - @SerializedName("officeName") - var officeName: String, + var officeName: String? = null, - @SerializedName("type") var type: Type, - @SerializedName("date") var date: List = ArrayList(), - @SerializedName("currency") - var currency: Currency, + var currency: Currency? = null, - @SerializedName("amount") var amount: Double? = null, - @SerializedName("submittedOnDate") var submittedOnDate: List = ArrayList(), - @SerializedName("reversed") var reversed: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/UpdatePasswordPayload.java b/app/src/main/java/org/mifos/mobile/models/UpdatePasswordPayload.java deleted file mode 100644 index 28eb5ed143..0000000000 --- a/app/src/main/java/org/mifos/mobile/models/UpdatePasswordPayload.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.mifos.mobile.models; - -/* - * Created by saksham on 13/July/2018 - */ - -import com.google.gson.annotations.SerializedName; - -public class UpdatePasswordPayload { - - @SerializedName("password") - String password; - - @SerializedName("repeatPassword") - String repeatPassword; - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getRepeatPassword() { - return repeatPassword; - } - - public void setRepeatPassword(String repeatPassword) { - this.repeatPassword = repeatPassword; - } -} diff --git a/app/src/main/java/org/mifos/mobile/models/UpdatePasswordPayload.kt b/app/src/main/java/org/mifos/mobile/models/UpdatePasswordPayload.kt new file mode 100644 index 0000000000..6f902d9c9c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/models/UpdatePasswordPayload.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.models + +/* +* Created by saksham on 13/July/2018 +*/ +class UpdatePasswordPayload { + + var password: String? = null + + var repeatPassword: String? = null +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/User.kt b/app/src/main/java/org/mifos/mobile/models/User.kt index 523a7012f1..440b19830c 100644 --- a/app/src/main/java/org/mifos/mobile/models/User.kt +++ b/app/src/main/java/org/mifos/mobile/models/User.kt @@ -1,6 +1,6 @@ package org.mifos.mobile.models -import java.util.ArrayList +import java.util.* /** * @author Vishwajeet diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/Account.java b/app/src/main/java/org/mifos/mobile/models/accounts/Account.java deleted file mode 100644 index b8344d13ec..0000000000 --- a/app/src/main/java/org/mifos/mobile/models/accounts/Account.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.mifos.mobile.models.accounts; - -import com.google.gson.annotations.SerializedName; - -/** - * This class contains variables which are used for implementing Comparator and are common to loan, - * savings and share account. - * Created by dilpreet on 14/6/17. - */ - -public abstract class Account { - @SerializedName("id") - protected long id; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } -} diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/Account.kt b/app/src/main/java/org/mifos/mobile/models/accounts/Account.kt new file mode 100644 index 0000000000..5687581f32 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/models/accounts/Account.kt @@ -0,0 +1,10 @@ +package org.mifos.mobile.models.accounts + +/** + * This class contains variables which are used for implementing Comparator and are common to loan, + * savings and share account. + * Created by dilpreet on 14/6/17. + */ +abstract class Account { + var id: Long = 0 +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/LoanAccountsListResponse.kt b/app/src/main/java/org/mifos/mobile/models/accounts/LoanAccountsListResponse.kt index 05f46cc4b6..b834db7165 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/LoanAccountsListResponse.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/LoanAccountsListResponse.kt @@ -1,8 +1,7 @@ package org.mifos.mobile.models.accounts import org.mifos.mobile.models.accounts.loan.LoanAccount - -import java.util.ArrayList +import java.util.* /** * @author Vishwajeet diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/SavingAccountsListResponse.kt b/app/src/main/java/org/mifos/mobile/models/accounts/SavingAccountsListResponse.kt index 0ef5e448b7..901f47f9d5 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/SavingAccountsListResponse.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/SavingAccountsListResponse.kt @@ -1,8 +1,7 @@ package org.mifos.mobile.models.accounts import org.mifos.mobile.models.accounts.savings.SavingAccount - -import java.util.ArrayList +import java.util.* /** * @author Vishwajeet diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/AmortizationType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/AmortizationType.kt index 4b9306207a..89c84d6a7e 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/AmortizationType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/AmortizationType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class AmortizationType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Currency.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Currency.kt index 96ed282c36..d4a3eb8781 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Currency.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Currency.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,25 +9,17 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Currency( - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("name") - var name: String, + var name: String? = null, - @SerializedName("decimalPlaces") var decimalPlaces: Double? = null, - @SerializedName("inMultiplesOf") var inMultiplesOf: Double? = null, - @SerializedName("displaySymbol") - var displaySymbol: String, - - @SerializedName("nameCode") - var nameCode: String, + var displaySymbol: String? = null, - @SerializedName("displayLabel") - var displayLabel: String + var nameCode: String? = null, + var displayLabel: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInMonthType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInMonthType.kt index 358dda1ba3..4227cc75a7 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInMonthType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInMonthType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class DaysInMonthType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInYearType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInYearType.kt index 4f23c7f380..187ea1da16 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInYearType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/DaysInYearType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class DaysInYearType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestCalculationPeriodType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestCalculationPeriodType.kt index 14df4f3760..7e1c6fcec8 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestCalculationPeriodType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestCalculationPeriodType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class InterestCalculationPeriodType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRateFrequencyType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRateFrequencyType.kt index 57badf6265..abc86c210a 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRateFrequencyType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRateFrequencyType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class InterestRateFrequencyType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationCompoundingType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationCompoundingType.kt index d1f332f6c6..a821d828ed 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationCompoundingType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationCompoundingType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class InterestRecalculationCompoundingType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationData.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationData.kt index 8375f6ce86..4b5e69537a 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationData.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationData.kt @@ -13,34 +13,25 @@ import org.mifos.mobile.models.accounts.loan.calendardata.CalendarData @Parcelize data class InterestRecalculationData( - @SerializedName("id") var id: Int? = null, - @SerializedName("loanId") var loanId: Int? = null, - @SerializedName("interestRecalculationCompoundingType") - var interestRecalculationCompoundingType: InterestRecalculationCompoundingType, + var interestRecalculationCompoundingType: InterestRecalculationCompoundingType? = null, - @SerializedName("rescheduleStrategyType") - var rescheduleStrategyType: RescheduleStrategyType, + var rescheduleStrategyType: RescheduleStrategyType? = null, - @SerializedName("calendarData") var calendarData: CalendarData, - @SerializedName("recalculationRestFrequencyType") - var recalculationRestFrequencyType: RecalculationRestFrequencyType, + var recalculationRestFrequencyType: RecalculationRestFrequencyType? = null, - @SerializedName("recalculationRestFrequencyInterval") var recalculationRestFrequencyInterval: Double? = null, - @SerializedName("recalculationCompoundingFrequencyType") - var recalculationCompoundingFrequencyType: RecalculationCompoundingFrequencyType, + var recalculationCompoundingFrequencyType: RecalculationCompoundingFrequencyType? = null, @SerializedName("isCompoundingToBePostedAsTransaction") var compoundingToBePostedAsTransaction: Boolean? = null, - @SerializedName("allowCompoundingOnEod") var allowCompoundingOnEod: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestType.kt index 60a1e499d5..c9d582fbe1 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class InterestType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanAccount.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanAccount.kt index 4425ba6f22..81b180f704 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanAccount.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanAccount.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcel import android.os.Parcelable -import com.google.gson.annotations.SerializedName import org.mifos.mobile.models.accounts.Account /** @@ -10,68 +9,47 @@ import org.mifos.mobile.models.accounts.Account * @since 22/06/16. */ data class LoanAccount( - @SerializedName("loanProductId") var loanProductId: Long = 0, - @SerializedName("externalId") var externalId: String? = null, - @SerializedName("numberOfRepayments") var numberOfRepayments: Long = 0, - @SerializedName("accountNo") var accountNo: String? = null, - @SerializedName("productName") var productName: String? = null, - @SerializedName("productId") var productId: Int? = null, - @SerializedName("loanProductName") var loanProductName: String? = null, - @SerializedName("clientName") var clientName: String? = null, - @SerializedName("loanProductDescription") var loanProductDescription: String? = null, - @SerializedName("principal") var principal: Double = 0.toDouble(), - @SerializedName("annualInterestRate") var annualInterestRate: Double = 0.toDouble(), - @SerializedName("status") var status: Status? = null, - @SerializedName("loanType") var loanType: LoanType? = null, - @SerializedName("loanCycle") var loanCycle: Int? = null, - @SerializedName("loanBalance") var loanBalance: Double = 0.toDouble(), - @SerializedName("amountPaid") var amountPaid: Double = 0.toDouble(), - @SerializedName("currency") - var currency: Currency, + var currency: Currency?, - @SerializedName("inArrears") var inArrears: Boolean? = null, - @SerializedName("summary") var summary: Summary? = null, - @SerializedName("loanPurposeName") var loanPurposeName: String? = null, - @SerializedName("timeline") - var timeline: Timeline + var timeline: Timeline? ) : Account(), Parcelable { constructor(parcel: Parcel) : this( @@ -95,8 +73,7 @@ data class LoanAccount( parcel.readValue(Boolean::class.java.classLoader) as? Boolean, parcel.readParcelable(Summary::class.java.classLoader), parcel.readString(), - parcel.readParcelable(Timeline::class.java.classLoader)) { - } + parcel.readParcelable(Timeline::class.java.classLoader)) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeLong(loanProductId) @@ -129,7 +106,7 @@ data class LoanAccount( companion object { @JvmField - final val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): LoanAccount { return LoanAccount(parcel) diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanType.kt index 4342dadee0..365d699a9c 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanType.kt @@ -2,18 +2,14 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class LoanType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithAssociations.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithAssociations.kt index 60f00e347e..99f19bc869 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithAssociations.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithAssociations.kt @@ -3,10 +3,8 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.Transaction - -import java.util.ArrayList +import java.util.* /** * Created by Rajan Maurya on 04/03/17. @@ -14,165 +12,117 @@ import java.util.ArrayList @Parcelize data class LoanWithAssociations( - @SerializedName("id") var id: Int? = null, - @SerializedName("accountNo") var accountNo: String? = null, - @SerializedName("externalId") var externalId: String? = null, - @SerializedName("status") var status: Status? =null, - @SerializedName("clientId") var clientId: Int? = null, - @SerializedName("clientAccountNo") var clientAccountNo: String? = null, - @SerializedName("clientName") var clientName: String? = null, - @SerializedName("clientOfficeId") var clientOfficeId: Int? = null, - @SerializedName("loanProductId") var loanProductId: Int? = null, - @SerializedName("loanProductName") var loanProductName: String? = null, @SerializedName("isLoanProductLinkedToFloatingRate") var loanProductLinkedToFloatingRate: Boolean? = null, - @SerializedName("loanType") var loanType: LoanType? = null, - @SerializedName("currency") var currency: Currency? = null, - @SerializedName("principal") var principal: Double? = null, - @SerializedName("approvedPrincipal") var approvedPrincipal: Double? = null, - @SerializedName("proposedPrincipal") var proposedPrincipal: Double? = null, - @SerializedName("termFrequency") var termFrequency: Int? = null, - @SerializedName("termPeriodFrequencyType") var termPeriodFrequencyType: TermPeriodFrequencyType? = null, - @SerializedName("numberOfRepayments") var numberOfRepayments: Int? = null, - @SerializedName("repaymentEvery") var repaymentEvery: Int? = null, - @SerializedName("repaymentFrequencyType") var repaymentFrequencyType: RepaymentFrequencyType? = null, - @SerializedName("interestRatePerPeriod") var interestRatePerPeriod: Int? = null, - @SerializedName("interestRateFrequencyType") var interestRateFrequencyType: InterestRateFrequencyType? = null, @SerializedName("isFloatingInterestRate") var floatingInterestRate: Boolean? = null, - @SerializedName("amortizationType") var amortizationType: AmortizationType? = null, - @SerializedName("interestType") var interestType: InterestType? = null, - @SerializedName("interestCalculationPeriodType") var interestCalculationPeriodType: InterestCalculationPeriodType? = null, - @SerializedName("allowPartialPeriodInterestCalcualtion") var allowPartialPeriodInterestCalcualtion: Boolean? = null, - @SerializedName("transactionProcessingStrategyId") var transactionProcessingStrategyId: Int? = null, - @SerializedName("transactionProcessingStrategyName") var transactionProcessingStrategyName: String? = null, - @SerializedName("syncDisbursementWithMeeting") var syncDisbursementWithMeeting: Boolean? = null, - @SerializedName("timeline") var timeline: Timeline? = null, - @SerializedName("summary") var summary: Summary? = null, - @SerializedName("repaymentSchedule") var repaymentSchedule: RepaymentSchedule? = null, - @SerializedName("feeChargesAtDisbursementCharged") var feeChargesAtDisbursementCharged: Double? = null, - @SerializedName("loanProductCounter") var loanProductCounter: Int? = null, - @SerializedName("multiDisburseLoan") var multiDisburseLoan: Boolean? = null, - @SerializedName("canDefineInstallmentAmount") var canDefineInstallmentAmount: Boolean? = null, - @SerializedName("canDisburse") var canDisburse: Boolean? = null, - @SerializedName("canUseForTopup") var canUseForTopup: Boolean? = null, @SerializedName("isTopup") var topup: Boolean? = null, - @SerializedName("closureLoanId") var closureLoanId: Int? = null, - @SerializedName("inArrears") var inArrears: Boolean? = null, @SerializedName("isNPA") var npa: Boolean? = null, - @SerializedName("daysInMonthType") var daysInMonthType: DaysInMonthType? = null, - @SerializedName("daysInYearType") var daysInYearType: DaysInYearType? = null, @SerializedName("isInterestRecalculationEnabled") var interestRecalculationEnabled: Boolean? = null, - @SerializedName("interestRecalculationData") var interestRecalculationData: InterestRecalculationData? = null, - @SerializedName("createStandingInstructionAtDisbursement") var createStandingInstructionAtDisbursement: Boolean? = null, @SerializedName("isVariableInstallmentsAllowed") var variableInstallmentsAllowed: Boolean? = null, - @SerializedName("minimumGap") var minimumGap: Int? = null, - @SerializedName("maximumGap") var maximumGap: Int? = null, - @SerializedName("transactions") - var transactions: List = ArrayList(), + var transactions: MutableList? = ArrayList(), - @SerializedName("loanPurposeName") var loanPurposeName: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithdraw.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithdraw.kt index f9b3851bef..8da4041743 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithdraw.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/LoanWithdraw.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,10 +9,8 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class LoanWithdraw( - @SerializedName("withdrawnOnDate") var withdrawnOnDate: String? = null, - @SerializedName("note") var note: String? = null, internal var dateFormat : String = "dd MMMM yyyy", diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Periods.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Periods.kt index 8dda999796..fa49ea9ad1 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Periods.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Periods.kt @@ -1,11 +1,8 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - -import java.util.ArrayList +import java.util.* /** * Created by Rajan Maurya on 04/03/17. @@ -13,124 +10,84 @@ import java.util.ArrayList @Parcelize data class Periods( - @SerializedName("period") var period: Int? = null, - @SerializedName("fromDate") var fromDate: List = ArrayList(), - @SerializedName("dueDate") var dueDate: List = ArrayList(), - @SerializedName("obligationsMetOnDate") var obligationsMetOnDate: List = ArrayList(), - @SerializedName("principalDisbursed") var principalDisbursed: Double? = null, - @SerializedName("complete") var complete: Boolean? = null, - @SerializedName("daysInPeriod") var daysInPeriod: Int? = null, - @SerializedName("principalOriginalDue") var principalOriginalDue: Double? = null, - @SerializedName("principalDue") var principalDue: Double? = null, - @SerializedName("principalPaid") var principalPaid: Double? = null, - @SerializedName("principalWrittenOff") var principalWrittenOff: Double? = null, - @SerializedName("principalOutstanding") var principalOutstanding: Double? = null, - @SerializedName("principalLoanBalanceOutstanding") var principalLoanBalanceOutstanding: Double? = null, - @SerializedName("interestOriginalDue") var interestOriginalDue: Double? = null, - @SerializedName("interestDue") var interestDue: Double? = null, - @SerializedName("interestPaid") var interestPaid: Double? = null, - @SerializedName("interestWaived") var interestWaived: Double? = null, - @SerializedName("interestWrittenOff") var interestWrittenOff: Double? = null, - @SerializedName("interestOutstanding") var interestOutstanding: Double? = null, - @SerializedName("feeChargesDue") var feeChargesDue: Double? = null, - @SerializedName("feeChargesPaid") var feeChargesPaid: Double? = null, - @SerializedName("feeChargesWaived") var feeChargesWaived: Double? = null, - @SerializedName("feeChargesWrittenOff") var feeChargesWrittenOff: Double? = null, - @SerializedName("feeChargesOutstanding") var feeChargesOutstanding: Double? = null, - @SerializedName("penaltyChargesDue") var penaltyChargesDue: Double? = null, - @SerializedName("penaltyChargesPaid") var penaltyChargesPaid: Double? = null, - @SerializedName("penaltyChargesWaived") var penaltyChargesWaived: Double? = null, - @SerializedName("penaltyChargesWrittenOff") var penaltyChargesWrittenOff: Double? = null, - @SerializedName("penaltyChargesOutstanding") var penaltyChargesOutstanding: Double? = null, - @SerializedName("totalOriginalDueForPeriod") var totalOriginalDueForPeriod: Double? = null, - @SerializedName("totalDueForPeriod") var totalDueForPeriod: Double? = null, - @SerializedName("totalPaidForPeriod") var totalPaidForPeriod: Double? = null, - @SerializedName("totalPaidInAdvanceForPeriod") var totalPaidInAdvanceForPeriod: Double? = null, - @SerializedName("totalPaidLateForPeriod") var totalPaidLateForPeriod: Double? = null, - @SerializedName("totalWaivedForPeriod") var totalWaivedForPeriod: Double? = null, - @SerializedName("totalWrittenOffForPeriod") var totalWrittenOffForPeriod: Double? = null, - @SerializedName("totalOutstandingForPeriod") var totalOutstandingForPeriod: Double? = null, - @SerializedName("totalOverdue") var totalOverdue: Double? = null, - @SerializedName("totalActualCostOfLoanForPeriod") var totalActualCostOfLoanForPeriod: Double? = null, - @SerializedName("totalInstallmentAmountForPeriod") var totalInstallmentAmountForPeriod: Double? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationCompoundingFrequencyType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationCompoundingFrequencyType.kt index 1e0bfe015f..4bdb52d30c 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationCompoundingFrequencyType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationCompoundingFrequencyType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class RecalculationCompoundingFrequencyType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationRestFrequencyType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationRestFrequencyType.kt index c8d75a148d..6e48280ed7 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationRestFrequencyType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RecalculationRestFrequencyType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class RecalculationRestFrequencyType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentFrequencyType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentFrequencyType.kt index 48db3c3d05..8496a09de3 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentFrequencyType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentFrequencyType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class RepaymentFrequencyType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentSchedule.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentSchedule.kt index d37e116b75..3cb1bbe301 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentSchedule.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentSchedule.kt @@ -1,11 +1,8 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - -import java.util.ArrayList +import java.util.* /** * Created by Rajan Maurya on 04/03/17. @@ -13,52 +10,36 @@ import java.util.ArrayList @Parcelize data class RepaymentSchedule( - @SerializedName("currency") - var currency: Currency, + var currency: Currency? = null, - @SerializedName("loanTermInDays") var loanTermInDays: Int? = null, - @SerializedName("totalPrincipalDisbursed") var totalPrincipalDisbursed: Double? = null, - @SerializedName("totalPrincipalExpected") var totalPrincipalExpected: Double? = null, - @SerializedName("totalPrincipalPaid") var totalPrincipalPaid: Double? = null, - @SerializedName("totalInterestCharged") var totalInterestCharged: Double? = null, - @SerializedName("totalFeeChargesCharged") var totalFeeChargesCharged: Double? = null, - @SerializedName("totalPenaltyChargesCharged") var totalPenaltyChargesCharged: Double? = null, - @SerializedName("totalWaived") var totalWaived: Double? = null, - @SerializedName("totalWrittenOff") var totalWrittenOff: Double? = null, - @SerializedName("totalRepaymentExpected") var totalRepaymentExpected: Double? = null, - @SerializedName("totalRepayment") var totalRepayment: Double? = null, - @SerializedName("totalPaidInAdvance") var totalPaidInAdvance: Double? = null, - @SerializedName("totalPaidLate") var totalPaidLate: Double? = null, - @SerializedName("totalOutstanding") var totalOutstanding: Double? = null, - @SerializedName("periods") var periods: List = ArrayList() ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RescheduleStrategyType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RescheduleStrategyType.kt index 818761e523..f09c56309d 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/RescheduleStrategyType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/RescheduleStrategyType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,13 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class RescheduleStrategyType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, - - @SerializedName("value") - var value: String + var code: String? = null, + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Status.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Status.kt index f395a67f53..3991203647 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Status.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Status.kt @@ -1,51 +1,38 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Status( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") var code: String? = null, - @SerializedName("value") var value: String? = null, - @SerializedName("pendingApproval") var pendingApproval: Boolean? = null, - @SerializedName("waitingForDisbursal") var waitingForDisbursal: Boolean? = null, - @SerializedName("active") var active: Boolean? = null, - @SerializedName("closedObligationsMet") var closedObligationsMet: Boolean? = null, - @SerializedName("closedWrittenOff") var closedWrittenOff: Boolean? = null, - @SerializedName("closedRescheduled") var closedRescheduled: Boolean? = null, - @SerializedName("closed") var closed: Boolean? = null, - @SerializedName("overpaid") var overpaid: Boolean? = null ) : Parcelable { fun isLoanTypeWithdrawn(): Boolean { - return !(this.active!! || this.closed!! || this.pendingApproval!! - || this.waitingForDisbursal!! || this.closedObligationsMet!! - || this.closedWrittenOff!! || this.closedRescheduled!! - || this.overpaid!!) + return !(this.active == true || this.closed == true || this.pendingApproval == true + || this.waitingForDisbursal == true || this.closedObligationsMet == true + || this.closedWrittenOff == true || this.closedRescheduled == true + || this.overpaid == true) } } \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Summary.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Summary.kt index ab135608a0..31da9868e7 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Summary.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Summary.kt @@ -1,59 +1,43 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Summary( - @SerializedName("principalDisbursed") var principalDisbursed: Double = 0.toDouble(), - @SerializedName("principalPaid") var principalPaid: Double = 0.toDouble(), - @SerializedName("interestCharged") var interestCharged: Double = 0.toDouble(), - @SerializedName("interestPaid") var interestPaid: Double = 0.toDouble(), - @SerializedName("feeChargesCharged") var feeChargesCharged: Double = 0.toDouble(), - @SerializedName("penaltyChargesCharged") var penaltyChargesCharged: Double = 0.toDouble(), - @SerializedName("penaltyChargesWaived") var penaltyChargesWaived: Double = 0.toDouble(), - @SerializedName("totalExpectedRepayment") var totalExpectedRepayment: Double = 0.toDouble(), - @SerializedName("interestWaived") var interestWaived: Double = 0.toDouble(), - @SerializedName("totalRepayment") var totalRepayment: Double = 0.toDouble(), - @SerializedName("feeChargesWaived") var feeChargesWaived: Double = 0.toDouble(), - @SerializedName("totalOutstanding") var totalOutstanding: Double = 0.toDouble(), - @SerializedName("overdueSinceDate") private var overdueSinceDate: List? = null, - @SerializedName("currency") var currency: Currency? = null ) : Parcelable { fun getOverdueSinceDate(): List? { - if (overdueSinceDate==null) - return null + return if (overdueSinceDate == null) + null else - return overdueSinceDate + overdueSinceDate } } \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/TermPeriodFrequencyType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/TermPeriodFrequencyType.kt index 4f1e1c6798..08a9637925 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/TermPeriodFrequencyType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/TermPeriodFrequencyType.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +10,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class TermPeriodFrequencyType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Timeline.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Timeline.kt index a5817e706b..b83dfa6f24 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/Timeline.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/Timeline.kt @@ -7,55 +7,38 @@ package org.mifos.mobile.models.accounts.loan import android.os.Parcel import android.os.Parcelable -import com.google.gson.annotations.SerializedName data class Timeline( - @SerializedName("submittedOnDate") - var submittedOnDate: List, + var submittedOnDate: List? = null, - @SerializedName("submittedByUsername") - var submittedByUsername: String, + var submittedByUsername: String?, - @SerializedName("submittedByFirstname") - var submittedByFirstname: String, + var submittedByFirstname: String?, - @SerializedName("submittedByLastname") - var submittedByLastname: String, + var submittedByLastname: String?, - @SerializedName("approvedOnDate") - var approvedOnDate: List, + var approvedOnDate: List? = null, - @SerializedName("approvedByUsername") - var approvedByUsername: String, + var approvedByUsername: String?, - @SerializedName("approvedByFirstname") - var approvedByFirstname: String, + var approvedByFirstname: String?, - @SerializedName("approvedByLastname") - var approvedByLastname: String, + var approvedByLastname: String?, - @SerializedName("expectedDisbursementDate") - var expectedDisbursementDate: List, + var expectedDisbursementDate: List? = null, - @SerializedName("actualDisbursementDate") - var actualDisbursementDate: List, + var actualDisbursementDate: List? = null, - @SerializedName("disbursedByUsername") - var disbursedByUsername: String, + var disbursedByUsername: String?, - @SerializedName("disbursedByFirstname") - var disbursedByFirstname: String, + var disbursedByFirstname: String?, - @SerializedName("disbursedByLastname") - var disbursedByLastname: String, + var disbursedByLastname: String?, - @SerializedName("closedOnDate") - var closedOnDate: List, + var closedOnDate: List? = null, - @SerializedName("expectedMaturityDate") - var expectedMaturityDate: List, + var expectedMaturityDate: List? = null, - @SerializedName("withdrawnOnDate") var withdrawnOnDate: List ) : Parcelable { @@ -89,8 +72,7 @@ data class Timeline( }, arrayListOf().apply { parcel.readArrayList(Int::class.java.classLoader) - }) { - } + }) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeList(submittedOnDate) @@ -118,7 +100,7 @@ data class Timeline( companion object { @JvmField - final var CREATOR: Parcelable.Creator = object : Parcelable.Creator { + var CREATOR: Parcelable.Creator = object : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): Timeline { return Timeline(parcel) } diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/CalendarData.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/CalendarData.kt index 0a8fbf151e..50bbb6fe66 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/CalendarData.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/CalendarData.kt @@ -1,11 +1,8 @@ package org.mifos.mobile.models.accounts.loan.calendardata import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - -import java.util.ArrayList +import java.util.* /** * Created by Rajan Maurya on 04/03/17. @@ -13,73 +10,49 @@ import java.util.ArrayList @Parcelize data class CalendarData( - @SerializedName("id") var id: Int? = null, - @SerializedName("calendarInstanceId") var calendarInstanceId: Int? = null, - @SerializedName("entityId") var entityId: Int? = null, - @SerializedName("entityType") var entityType: EntityType, - @SerializedName("title") - var title: String, + var title: String? = null, - @SerializedName("startDate") var startDate: List = ArrayList(), - @SerializedName("endDate") var endDate: List = ArrayList(), - @SerializedName("duration") var duration: Double? = null, - @SerializedName("type") var type: Type, - @SerializedName("repeating") var repeating: Boolean? = null, - @SerializedName("recurrence") - var recurrence: String, + var recurrence: String? = null, - @SerializedName("frequency") var frequency: Frequency, - @SerializedName("interval") var interval: Double? = null, - @SerializedName("repeatsOnNthDayOfMonth") var repeatsOnNthDayOfMonth: RepeatsOnNthDayOfMonth, - @SerializedName("firstReminder") var firstReminder: Int? = null, - @SerializedName("secondReminder") var secondReminder: Int? = null, - @SerializedName("humanReadable") - var humanReadable: String, + var humanReadable: String? = null, - @SerializedName("createdDate") var createdDate: List = ArrayList(), - @SerializedName("lastUpdatedDate") var lastUpdatedDate: List = ArrayList(), - @SerializedName("createdByUserId") var createdByUserId: Int? = null, - @SerializedName("createdByUsername") - var createdByUsername: String, + var createdByUsername: String? = null, - @SerializedName("lastUpdatedByUserId") var lastUpdatedByUserId: Int? = null, - @SerializedName("lastUpdatedByUsername") - var lastUpdatedByUsername: String - + var lastUpdatedByUsername: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/EntityType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/EntityType.kt index 3b4d19526f..169476679a 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/EntityType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/EntityType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan.calendardata import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class EntityType( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Frequency.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Frequency.kt index e9f2dfb0ac..fedf6d99b5 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Frequency.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Frequency.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan.calendardata import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,13 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Frequency( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, - - @SerializedName("value") - var value: String + var code: String? = null, + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/RepeatsOnNthDayOfMonth.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/RepeatsOnNthDayOfMonth.kt index b8b4250f2e..87fd743dc1 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/RepeatsOnNthDayOfMonth.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/RepeatsOnNthDayOfMonth.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan.calendardata import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class RepeatsOnNthDayOfMonth( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Type.kt b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Type.kt index 2ff6adb260..4cb5f7cb54 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Type.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/loan/calendardata/Type.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.loan.calendardata import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Type( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Currency.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Currency.kt index 871ddd2284..24943b924c 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Currency.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Currency.kt @@ -1,30 +1,21 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Currency( - @SerializedName("code") var code: String? = null, - @SerializedName("name") var name: String? = null, - @SerializedName("decimalPlaces") var decimalPlaces: Int? = null, - @SerializedName("inMultiplesOf") var inMultiplesOf: Int? = null, - @SerializedName("displaySymbol") var displaySymbol: String? = null, - @SerializedName("nameCode") var nameCode: String? = null, - @SerializedName("displayLabel") var displayLabel: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentDetailData.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentDetailData.kt index 75fb300e5f..af1436eaba 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentDetailData.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentDetailData.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,24 +9,17 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class PaymentDetailData( - @SerializedName("id") var id: Int? = null, - @SerializedName("paymentType") var paymentType: PaymentType, - @SerializedName("accountNumber") - var accountNumber: String, + var accountNumber: String? = null, - @SerializedName("checkNumber") - var checkNumber: String, + var checkNumber: String? = null, - @SerializedName("routingCode") - var routingCode: String, + var routingCode: String? = null, - @SerializedName("receiptNumber") - var receiptNumber: String, + var receiptNumber: String? = null, - @SerializedName("bankNumber") - var bankNumber: String + var bankNumber: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentType.kt index 17b4c84497..d619ab10d0 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/PaymentType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,9 +9,7 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class PaymentType( - @SerializedName("id") var id: Int? = null, - @SerializedName("name") - var name: String + var name: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingAccount.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingAccount.kt index c32705e2e5..fec92269ac 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingAccount.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingAccount.kt @@ -1,10 +1,7 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.accounts.Account import org.mifos.mobile.models.client.DepositType @@ -15,55 +12,40 @@ import org.mifos.mobile.models.client.DepositType @Parcelize data class SavingAccount( - @SerializedName("accountNo") + var accountNo: String? = null, - @SerializedName("productName") var productName: String? = null, - @SerializedName("productId") var productId: Int? = null, - @SerializedName("overdraftLimit") var overdraftLimit: Long = 0, - @SerializedName("minRequiredBalance") var minRequiredBalance: Long = 0, - @SerializedName("accountBalance") var accountBalance: Double = 0.toDouble(), - @SerializedName("totalDeposits") var totalDeposits: Double = 0.toDouble(), - @SerializedName("savingsProductName") var savingsProductName: String? = null, - @SerializedName("clientName") var clientName: String? = null, - @SerializedName("savingsProductId") var savingsProductId: String? = null, - @SerializedName("nominalAnnualInterestRate") var nominalAnnualInterestRate: Double = 0.toDouble(), - @SerializedName("status") var status: Status? = null, - @SerializedName("currency") var currency: Currency? = null, - @SerializedName("depositType") var depositType: DepositType? = null, - @SerializedName("lastActiveTransactionDate") var lastActiveTransactionDate: List? = null, - @SerializedName("timeline") var timeLine: TimeLine? = null ) : Parcelable, Account() { fun isRecurring(): Boolean { - return this.depositType != null && this.depositType!!.isRecurring() + return this.depositType != null && (this.depositType?.isRecurring() == true) } } \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsAccountUpdatePayload.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsAccountUpdatePayload.kt index 770f1423e8..03a5d1c74a 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsAccountUpdatePayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsAccountUpdatePayload.kt @@ -5,16 +5,13 @@ package org.mifos.mobile.models.accounts.savings */ import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class SavingsAccountUpdatePayload( - @SerializedName("clientId") - var clientId: Long = 0, + var clientId: Long? = 0, - @SerializedName("productId") - var productId: Long = 0 + var productId: Long? = 0 ) : Parcelable diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsWithAssociations.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsWithAssociations.kt index 6f6541daa5..ec7b05f918 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsWithAssociations.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsWithAssociations.kt @@ -1,13 +1,9 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.client.DepositType - -import java.util.ArrayList +import java.util.* /** * @author Vishwajeet @@ -16,79 +12,57 @@ import java.util.ArrayList @Parcelize data class SavingsWithAssociations( - @SerializedName("id") + var id: Long? = null, - @SerializedName("accountNo") var accountNo: String? = null, - @SerializedName("depositType") var depositType: DepositType? = null, - @SerializedName("externalId") var externalId: String? = null, - @SerializedName("clientId") var clientId: Int? = null, - @SerializedName("clientName") var clientName: String? = null, - @SerializedName("savingsProductId") var savingsProductId: Int? = null, - @SerializedName("savingsProductName") var savingsProductName: String? = null, - @SerializedName("fieldOfficerId") var fieldOfficerId: Int? = null, - @SerializedName("status") var status: Status? = null, - @SerializedName("timeline") var timeline: TimeLine? = null, - @SerializedName("currency") var currency: Currency? = null, - @SerializedName("nominalAnnualInterestRate") internal var nominalAnnualInterestRate: Double? = null, - @SerializedName("minRequiredOpeningBalance") var minRequiredOpeningBalance: Double? = null, - @SerializedName("lockinPeriodFrequency") var lockinPeriodFrequency: Double? = null, - @SerializedName("withdrawalFeeForTransfers") var withdrawalFeeForTransfers: Boolean? = null, - @SerializedName("allowOverdraft") var allowOverdraft: Boolean? = null, - @SerializedName("enforceMinRequiredBalance") var enforceMinRequiredBalance: Boolean? = null, - @SerializedName("withHoldTax") var withHoldTax: Boolean? = null, - @SerializedName("lastActiveTransactionDate") var lastActiveTransactionDate: List? = null, - @SerializedName("isDormancyTrackingActive") var dormancyTrackingActive: Boolean? = null, - @SerializedName("summary") var summary: Summary? = null, - @SerializedName("transactions") var transactions: List = ArrayList() ) : Parcelable { - fun isRecurring() : Boolean { - return this.depositType != null && this.depositType!!.isRecurring() + fun isRecurring(): Boolean { + return this.depositType != null && (this.depositType?.isRecurring() == true) } fun setNominalAnnualInterestRate(nominalAnnualInterestRate: Double?) { diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Status.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Status.kt index ad3a50c190..df68f934d2 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Status.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Status.kt @@ -1,49 +1,33 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Status( - @SerializedName("id") var id: Int? = null, + var code: String? = null, - @SerializedName("code") - var code: String, - - @SerializedName("value") - var value: String, + var value: String? = null, - @SerializedName("submittedAndPendingApproval") var submittedAndPendingApproval: Boolean? = null, - @SerializedName("approved") var approved: Boolean? = null, - @SerializedName("rejected") var rejected: Boolean? = null, - @SerializedName("withdrawnByApplicant") var withdrawnByApplicant: Boolean? = null, - @SerializedName("active") var active: Boolean? = null, - @SerializedName("closed") var closed: Boolean? = null, - @SerializedName("prematureClosed") var prematureClosed: Boolean? = null, - @SerializedName("transferInProgress") internal var transferInProgress: Boolean? = null, - @SerializedName("transferOnHold") internal var transferOnHold: Boolean? = null, - @SerializedName("matured") var matured: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Summary.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Summary.kt index c75c284f51..30c958b58e 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Summary.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Summary.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @@ -12,31 +10,23 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Summary( - @SerializedName("currency") - var currency: Currency, - @SerializedName("totalDeposits") + var currency: Currency? = null, + var totalDeposits: Double? = null, - @SerializedName("totalWithdrawals") var totalWithdrawals: Double? = null, - @SerializedName("totalInterestEarned") var totalInterestEarned: Double? = null, - @SerializedName("totalInterestPosted") var totalInterestPosted: Double? = null, - @SerializedName("accountBalance") var accountBalance: Double? = null, - @SerializedName("totalOverdraftInterestDerived") var totalOverdraftInterestDerived: Double? = null, - @SerializedName("interestNotPosted") var interestNotPosted: Double? = null, - @SerializedName("lastInterestCalculationDate") var lastInterestCalculationDate: List ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/TimeLine.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/TimeLine.kt index 2c5de959d6..f8c0ce0165 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/TimeLine.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/TimeLine.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcel import android.os.Parcelable -import com.google.gson.annotations.SerializedName import java.util.* /** @@ -10,43 +9,30 @@ import java.util.* */ data class TimeLine( - @SerializedName("submittedOnDate") var submittedOnDate: List = ArrayList(), - @SerializedName("submittedByUsername") - var submittedByUsername: String, + var submittedByUsername: String?, - @SerializedName("submittedByFirstname") - var submittedByFirstname: String, + var submittedByFirstname: String?, - @SerializedName("submittedByLastname") - var submittedByLastname: String, + var submittedByLastname: String?, - @SerializedName("approvedOnDate") var approvedOnDate: List = ArrayList(), - @SerializedName("approvedByUsername") - var approvedByUsername: String, + var approvedByUsername: String?, - @SerializedName("approvedByFirstname") - var approvedByFirstname: String, + var approvedByFirstname: String?, - @SerializedName("approvedByLastname") - var approvedByLastname: String, + var approvedByLastname: String?, - @SerializedName("activatedOnDate") - var activatedOnDate: List, + var activatedOnDate: List? = null, - @SerializedName("activatedByUsername") - var activatedByUsername: String, + var activatedByUsername: String?, - @SerializedName("activatedByFirstname") - var activatedByFirstname: String, + var activatedByFirstname: String?, - @SerializedName("activatedByLastname") - var activatedByLastname: String, + var activatedByLastname: String?, - @SerializedName("closedOnDate") var closedOnDate: List ) : Parcelable { @@ -71,8 +57,7 @@ data class TimeLine( parcel.readString(), arrayListOf().apply { parcel.readArrayList(Int::class.java.classLoader) - }) { - } + }) override fun writeToParcel(parcel: Parcel, flags: Int) { @@ -98,7 +83,7 @@ data class TimeLine( companion object { @JvmField - final val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): TimeLine { return TimeLine(parcel) } diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/TransactionType.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/TransactionType.kt index bdf3dff868..686f34e9bb 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/TransactionType.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/TransactionType.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,55 +9,37 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class TransactionType( - @SerializedName("id") var id: Int? = null, + var code: String? = null, - @SerializedName("code") - var code: String, - - @SerializedName("value") - var value: String, + var value: String? = null, - @SerializedName("deposit") var deposit: Boolean? = null, - @SerializedName("dividendPayout") var dividendPayout: Boolean? = null, - @SerializedName("withdrawal") var withdrawal: Boolean? = null, - @SerializedName("interestPosting") var interestPosting: Boolean? = null, - @SerializedName("feeDeduction") var feeDeduction: Boolean? = null, - @SerializedName("initiateTransfer") var initiateTransfer: Boolean? = null, - @SerializedName("approveTransfer") var approveTransfer: Boolean? = null, - @SerializedName("withdrawTransfer") var withdrawTransfer: Boolean? = null, - @SerializedName("rejectTransfer") var rejectTransfer: Boolean? = null, - @SerializedName("overdraftInterest") var overdraftInterest: Boolean? = null, - @SerializedName("writtenoff") var writtenoff: Boolean? = null, - @SerializedName("overdraftFee") var overdraftFee: Boolean? = null, - @SerializedName("withholdTax") var withholdTax: Boolean? = null, - @SerializedName("escheat") var escheat: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Transactions.kt b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Transactions.kt index c4278db51b..b346e57299 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/savings/Transactions.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/savings/Transactions.kt @@ -1,11 +1,8 @@ package org.mifos.mobile.models.accounts.savings import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - -import java.util.ArrayList +import java.util.* /** * Created by Rajan Maurya on 05/03/17. @@ -13,40 +10,28 @@ import java.util.ArrayList @Parcelize data class Transactions( - @SerializedName("id") var id: Int? = null, - @SerializedName("transactionType") var transactionType: TransactionType? = null, - @SerializedName("accountId") var accountId: Int? = null, - @SerializedName("accountNo") var accountNo: String? = null, - @SerializedName("date") var date: List = ArrayList(), - @SerializedName("currency") var currency: Currency? = null, - @SerializedName("paymentDetailData") var paymentDetailData: PaymentDetailData? = null, - @SerializedName("amount") var amount: Double? = null, - @SerializedName("runningBalance") var runningBalance: Double? = null, - @SerializedName("reversed") var reversed: Boolean? = null, - @SerializedName("submittedOnDate") var submittedOnDate: List? = null, - @SerializedName("interestedPostedAsOn") var interestedPostedAsOn: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/share/ShareAccount.kt b/app/src/main/java/org/mifos/mobile/models/accounts/share/ShareAccount.kt index b9b608eac0..a3f04cd85d 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/share/ShareAccount.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/share/ShareAccount.kt @@ -1,50 +1,38 @@ package org.mifos.mobile.models.accounts.share import android.os.Parcelable - import com.google.gson.annotations.Expose -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.accounts.Account import org.mifos.mobile.models.accounts.savings.Currency @Parcelize data class ShareAccount( - @SerializedName("accountNo") @Expose var accountNo: String? = null, - @SerializedName("totalApprovedShares") @Expose var totalApprovedShares: Int? = null, - @SerializedName("totalPendingForApprovalShares") @Expose var totalPendingForApprovalShares: Int? = null, - @SerializedName("productId") @Expose var productId: Int? = null, - @SerializedName("productName") @Expose var productName: String? = null, - @SerializedName("shortProductName") @Expose var shortProductName: String? = null, - @SerializedName("status") @Expose var status: Status? = null, - @SerializedName("currency") @Expose var currency: Currency? = null, - @SerializedName("timeline") @Expose var timeline: Timeline? = null diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/share/Status.kt b/app/src/main/java/org/mifos/mobile/models/accounts/share/Status.kt index d8735611be..8afe6b24f8 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/share/Status.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/share/Status.kt @@ -1,42 +1,31 @@ package org.mifos.mobile.models.accounts.share import android.os.Parcelable - import com.google.gson.annotations.Expose -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Status( - @SerializedName("id") @Expose var id: Int? = null, - - @SerializedName("code") @Expose var code: String? = null, - @SerializedName("value") @Expose var value: String? = null, - @SerializedName("submittedAndPendingApproval") @Expose var submittedAndPendingApproval: Boolean? = null, - @SerializedName("approved") @Expose var approved: Boolean? = null, - @SerializedName("rejected") @Expose var rejected: Boolean? = null, - @SerializedName("active") @Expose var active: Boolean? = null, - @SerializedName("closed") @Expose var closed: Boolean? = null diff --git a/app/src/main/java/org/mifos/mobile/models/accounts/share/Timeline.kt b/app/src/main/java/org/mifos/mobile/models/accounts/share/Timeline.kt index 903897d8b0..c832d76914 100644 --- a/app/src/main/java/org/mifos/mobile/models/accounts/share/Timeline.kt +++ b/app/src/main/java/org/mifos/mobile/models/accounts/share/Timeline.kt @@ -1,59 +1,45 @@ package org.mifos.mobile.models.accounts.share import android.os.Parcelable - import com.google.gson.annotations.Expose -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Timeline( - @SerializedName("submittedOnDate") @Expose var submittedOnDate: List? = null, - @SerializedName("submittedByUsername") @Expose var submittedByUsername: String? = null, - @SerializedName("submittedByFirstname") @Expose var submittedByFirstname: String? = null, - @SerializedName("submittedByLastname") @Expose var submittedByLastname: String? = null, - @SerializedName("approvedDate") @Expose var approvedDate: List? = null, - @SerializedName("approvedByUsername") @Expose var approvedByUsername: String? = null, - @SerializedName("approvedByFirstname") @Expose var approvedByFirstname: String? = null, - @SerializedName("approvedByLastname") @Expose var approvedByLastname: String? = null, - @SerializedName("activatedDate") @Expose var activatedDate: List? = null, - @SerializedName("activatedByUsername") @Expose var activatedByUsername: String? = null, - @SerializedName("activatedByFirstname") @Expose var activatedByFirstname: String? = null, - @SerializedName("activatedByLastname") @Expose var activatedByLastname: String? = null diff --git a/app/src/main/java/org/mifos/mobile/models/beneficiary/Beneficiary.kt b/app/src/main/java/org/mifos/mobile/models/beneficiary/Beneficiary.kt index 3cdee0ef36..e3d38902eb 100644 --- a/app/src/main/java/org/mifos/mobile/models/beneficiary/Beneficiary.kt +++ b/app/src/main/java/org/mifos/mobile/models/beneficiary/Beneficiary.kt @@ -1,10 +1,7 @@ package org.mifos.mobile.models.beneficiary import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.templates.account.AccountType /** @@ -13,25 +10,18 @@ import org.mifos.mobile.models.templates.account.AccountType @Parcelize data class Beneficiary( - @SerializedName("id") var id: Int? = null, - @SerializedName("name") var name: String? = null, - @SerializedName("officeName") var officeName: String? = null, - @SerializedName("clientName") var clientName: String? = null, - @SerializedName("accountType") var accountType: AccountType? = null, - @SerializedName("accountNumber") var accountNumber: String? = null, - @SerializedName("transferLimit") var transferLimit: Double? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryDetail.java b/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryDetail.java deleted file mode 100644 index 46fcbc6f22..0000000000 --- a/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryDetail.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.mifos.mobile.models.beneficiary; - -/* - * Created by saksham on 18/June/2018 - */ - -public class BeneficiaryDetail { - - String accountNumber; - String beneficiaryName; - - public BeneficiaryDetail(String accountNumber, String beneficiaryName) { - this.accountNumber = accountNumber; - this.beneficiaryName = beneficiaryName; - } - - public String getAccountNumber() { - return accountNumber; - } - - public void setAccountNumber(String accountNumber) { - this.accountNumber = accountNumber; - } - - public String getBeneficiaryName() { - return beneficiaryName; - } - - public void setBeneficiaryName(String beneficiaryName) { - this.beneficiaryName = beneficiaryName; - } -} diff --git a/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryDetail.kt b/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryDetail.kt new file mode 100644 index 0000000000..cf3e09de27 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryDetail.kt @@ -0,0 +1,6 @@ +package org.mifos.mobile.models.beneficiary + +/* + * Created by saksham on 18/June/2018 + */ +class BeneficiaryDetail(var accountNumber: String?, var beneficiaryName: String?) \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryPayload.kt b/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryPayload.kt index e1a1675757..84e77ff854 100644 --- a/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryPayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryPayload.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.beneficiary import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,20 +9,15 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class BeneficiaryPayload( - internal var locale : String = "en_GB", + internal var locale: String = "en_GB", - @SerializedName("name") var name: String? = null, - @SerializedName("accountNumber") var accountNumber: String? = null, - @SerializedName("accountType") - var accountType: Int = 0, + var accountType: Int? = 0, - @SerializedName("transferLimit") - var transferLimit: Float = 0f, + var transferLimit: Float? = 0f, - @SerializedName("officeName") var officeName: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryUpdatePayload.kt b/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryUpdatePayload.kt index 45a1f92475..9ad66a2769 100644 --- a/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryUpdatePayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/beneficiary/BeneficiaryUpdatePayload.kt @@ -1,13 +1,10 @@ package org.mifos.mobile.models.beneficiary -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 16/6/17. */ data class BeneficiaryUpdatePayload @JvmOverloads constructor( - - @SerializedName("name") var name: String? = null, - - @SerializedName("transferLimit") var transferLimit: Float = 0f) + var name: String? = null, + var transferLimit: Float = 0f +) diff --git a/app/src/main/java/org/mifos/mobile/models/client/Client.java b/app/src/main/java/org/mifos/mobile/models/client/Client.java deleted file mode 100644 index 2c828d9051..0000000000 --- a/app/src/main/java/org/mifos/mobile/models/client/Client.java +++ /dev/null @@ -1,305 +0,0 @@ -package org.mifos.mobile.models.client; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.google.gson.annotations.SerializedName; - -import org.mifos.mobile.models.Timeline; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vishwajeet - * @since 20/06/16 - */ -public class Client implements Parcelable { - - @SerializedName("id") - private int id; - - @SerializedName("accountNo") - private String accountNo; - - @SerializedName("status") - private Status status; - - @SerializedName("active") - private Boolean active; - - @SerializedName("activationDate") - private List activationDate = new ArrayList<>(); - - @SerializedName("dateOfBirth") - private List dobDate = new ArrayList<>(); - - @SerializedName("firstname") - private String firstname; - - @SerializedName("middlename") - private String middlename; - - @SerializedName("lastname") - private String lastname; - - @SerializedName("displayName") - private String displayName; - - @SerializedName("fullname") - private String fullname; - - @SerializedName("officeId") - private Integer officeId; - - @SerializedName("officeName") - private String officeName; - - @SerializedName("staffId") - private Integer staffId; - - @SerializedName("staffName") - private String staffName; - - @SerializedName("timeline") - private Timeline timeline; - - @SerializedName("imageId") - private int imageId; - - @SerializedName("imagePresent") - private boolean imagePresent; - - @SerializedName("externalId") - private String externalId; - - @SerializedName("mobileNo") - String mobileNo; - - @SerializedName("clientClassification") - private ClientClassification clientClassification; - - @SerializedName("clientType") - private ClientType clientType; - - @SerializedName("gender") - private Gender gender; - - @SerializedName("groups") - private List groups = new ArrayList<>(); - - public List getGroups() { - return groups; - } - - public void setGroups(List groups) { - this.groups = groups; - } - - public Gender getGender() { - return gender; - } - - public void setGender(Gender gender) { - this.gender = gender; - } - - public String getMobileNo() { - return mobileNo; - } - - public void setMobileNo(String mobileNo) { - this.mobileNo = mobileNo; - } - - public ClientClassification getClientClassification() { - return clientClassification; - } - - public void setClientClassification(ClientClassification clientClassification) { - this.clientClassification = clientClassification; - } - - public ClientType getClientType() { - return clientType; - } - - public void setClientType(ClientType clientType) { - this.clientType = clientType; - } - - public String getOfficeName() { - return officeName; - } - - public void setOfficeName(String officeName) { - this.officeName = officeName; - } - - public List getDobDate() { - return dobDate; - } - - public void setDobDate(List dobDate) { - this.dobDate = dobDate; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getAccountNo() { - return accountNo; - } - - public void setAccountNo(String accountNo) { - this.accountNo = accountNo; - } - - public List getActivationDate() { - return activationDate; - } - - public void setActivationDate(List activationDate) { - this.activationDate = activationDate; - } - - public String getFirstname() { - return firstname; - } - - public void setFirstname(String firstname) { - this.firstname = firstname; - } - - public String getMiddlename() { - return middlename; - } - - public void setMiddlename(String middlename) { - this.middlename = middlename; - } - - public String getLastname() { - return lastname; - } - - public void setLastname(String lastname) { - this.lastname = lastname; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - public String getFullname() { - return fullname; - } - - public void setFullname(String fullname) { - this.fullname = fullname; - } - - public int getImageId() { - return imageId; - } - - public void setImageId(int imageId) { - this.imageId = imageId; - } - - public boolean isImagePresent() { - return imagePresent; - } - - public void setImagePresent(boolean imagePresent) { - this.imagePresent = imagePresent; - } - - @Override - public String toString() { - return "Client{" + - "id=" + id + - ", accountNo='" + accountNo + '\'' + - ", activationDate=" + activationDate + - ", firstname='" + firstname + '\'' + - ", middlename='" + middlename + '\'' + - ", lastname='" + lastname + '\'' + - ", displayName='" + displayName + '\'' + - ", fullname='" + fullname + '\'' + - '}'; - } - - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(this.id); - dest.writeString(this.accountNo); - dest.writeParcelable(this.status, flags); - dest.writeValue(this.active); - dest.writeList(this.activationDate); - dest.writeList(this.dobDate); - dest.writeString(this.firstname); - dest.writeString(this.middlename); - dest.writeString(this.lastname); - dest.writeString(this.displayName); - dest.writeString(this.fullname); - dest.writeValue(this.officeId); - dest.writeString(this.officeName); - dest.writeValue(this.staffId); - dest.writeString(this.staffName); - } - - public Client() { - } - - protected Client(Parcel in) { - this.id = in.readInt(); - this.accountNo = in.readString(); - this.status = in.readParcelable(Status.class.getClassLoader()); - this.active = (Boolean) in.readValue(Boolean.class.getClassLoader()); - this.activationDate = new ArrayList<>(); - in.readList(this.activationDate, Integer.class.getClassLoader()); - this.dobDate = new ArrayList<>(); - in.readList(this.dobDate, Integer.class.getClassLoader()); - this.firstname = in.readString(); - this.middlename = in.readString(); - this.lastname = in.readString(); - this.displayName = in.readString(); - this.fullname = in.readString(); - this.officeId = (Integer) in.readValue(Integer.class.getClassLoader()); - this.officeName = in.readString(); - this.staffId = (Integer) in.readValue(Integer.class.getClassLoader()); - this.staffName = in.readString(); - this.timeline = in.readParcelable(Timeline.class.getClassLoader()); - this.fullname = in.readString(); - this.imageId = in.readInt(); - this.imagePresent = in.readByte() != 0; - this.externalId = in.readString(); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public Client createFromParcel(Parcel source) { - return new Client(source); - } - - @Override - public Client[] newArray(int size) { - return new Client[size]; - } - }; -} diff --git a/app/src/main/java/org/mifos/mobile/models/client/Client.kt b/app/src/main/java/org/mifos/mobile/models/client/Client.kt new file mode 100644 index 0000000000..3bde8e1c64 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/models/client/Client.kt @@ -0,0 +1,132 @@ +package org.mifos.mobile.models.client + +import android.os.Parcel +import android.os.Parcelable +import org.mifos.mobile.models.Timeline +import java.util.* + +/** + * @author Vishwajeet + * @since 20/06/16 + */ +class Client : Parcelable { + var id = 0 + + var accountNo: String? = null + + private var status: Status? = null + + private var active: Boolean? = null + + var activationDate: List? = ArrayList() + + var dobDate: List = ArrayList() + + var firstname: String? = null + + var middlename: String? = null + + var lastname: String? = null + + var displayName: String? = null + + var fullname: String? = null + + private var officeId: Int? = null + + var officeName: String? = null + + private var staffId: Int? = null + + private var staffName: String? = null + + private var timeline: Timeline? = null + + var imageId = 0 + + var isImagePresent = false + + private var externalId: String? = null + + var mobileNo: String? = null + + var clientClassification: ClientClassification? = null + + var clientType: ClientType? = null + + var gender: Gender? = null + + var groups: List = ArrayList() + override fun toString(): String { + return "Client{" + + "id=" + id + + ", accountNo='" + accountNo + '\'' + + ", activationDate=" + activationDate + + ", firstname='" + firstname + '\'' + + ", middlename='" + middlename + '\'' + + ", lastname='" + lastname + '\'' + + ", displayName='" + displayName + '\'' + + ", fullname='" + fullname + '\'' + + '}' + } + + override fun describeContents(): Int { + return 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeInt(id) + dest.writeString(accountNo) + dest.writeParcelable(status, flags) + dest.writeValue(active) + dest.writeList(activationDate) + dest.writeList(dobDate) + dest.writeString(firstname) + dest.writeString(middlename) + dest.writeString(lastname) + dest.writeString(displayName) + dest.writeString(fullname) + dest.writeValue(officeId) + dest.writeString(officeName) + dest.writeValue(staffId) + dest.writeString(staffName) + } + + constructor() + protected constructor(`in`: Parcel) { + id = `in`.readInt() + accountNo = `in`.readString() + status = `in`.readParcelable(Status::class.java.classLoader) + active = `in`.readValue(Boolean::class.java.classLoader) as Boolean + activationDate = ArrayList() + `in`.readList(activationDate, Int::class.java.classLoader) + dobDate = ArrayList() + `in`.readList(dobDate, Int::class.java.classLoader) + firstname = `in`.readString() + middlename = `in`.readString() + lastname = `in`.readString() + displayName = `in`.readString() + fullname = `in`.readString() + officeId = `in`.readValue(Int::class.java.classLoader) as Int + officeName = `in`.readString() + staffId = `in`.readValue(Int::class.java.classLoader) as Int + staffName = `in`.readString() + timeline = `in`.readParcelable(Timeline::class.java.classLoader) + fullname = `in`.readString() + imageId = `in`.readInt() + isImagePresent = `in`.readByte().toInt() != 0 + externalId = `in`.readString() + } + + companion object { + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(source: Parcel): Client? { + return Client(source) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/client/ClientAccounts.kt b/app/src/main/java/org/mifos/mobile/models/client/ClientAccounts.kt index 62e0fc2fa9..ccb778b38b 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/ClientAccounts.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/ClientAccounts.kt @@ -1,22 +1,17 @@ package org.mifos.mobile.models.client import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.accounts.loan.LoanAccount import org.mifos.mobile.models.accounts.savings.SavingAccount import org.mifos.mobile.models.accounts.share.ShareAccount - -import java.util.ArrayList +import java.util.* @Parcelize data class ClientAccounts( var loanAccounts: List = ArrayList(), var savingsAccounts: List? = ArrayList(), - @SerializedName("shareAccounts") var shareAccounts: List = ArrayList() ) : Parcelable { diff --git a/app/src/main/java/org/mifos/mobile/models/client/ClientClassification.kt b/app/src/main/java/org/mifos/mobile/models/client/ClientClassification.kt index 3f3213bef4..4196fe5ad0 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/ClientClassification.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/ClientClassification.kt @@ -1,18 +1,12 @@ package org.mifos.mobile.models.client -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 10/7/17. */ -data class ClientClassification ( - - @SerializedName("id") var id: Int, - - @SerializedName("name") var name: String, - - @SerializedName("active") var active: Boolean, - - @SerializedName("mandatory") var mandatory: Boolean +data class ClientClassification( + var id: Int, + var name: String? = null, + var active: Boolean, + var mandatory: Boolean ) diff --git a/app/src/main/java/org/mifos/mobile/models/client/ClientType.kt b/app/src/main/java/org/mifos/mobile/models/client/ClientType.kt index eb1f1ef169..63f13afd47 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/ClientType.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/ClientType.kt @@ -1,18 +1,12 @@ package org.mifos.mobile.models.client -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 10/7/17. */ -data class ClientType ( - - @SerializedName("id") var id: Int, - - @SerializedName("name") var name: String, - - @SerializedName("active") var active: Boolean, - - @SerializedName("mandatory") var mandatory: Boolean +data class ClientType( + var id: Int, + var name: String? = null, + var active: Boolean, + var mandatory: Boolean ) diff --git a/app/src/main/java/org/mifos/mobile/models/client/Currency.kt b/app/src/main/java/org/mifos/mobile/models/client/Currency.kt index 90925d8a8d..bb3c11ee03 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/Currency.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/Currency.kt @@ -1,27 +1,19 @@ package org.mifos.mobile.models.client import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Currency( - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("name") - var name: String, + var name: String? = null, - @SerializedName("decimalPlaces") var decimalPlaces: Int? = null, - @SerializedName("displaySymbol") var displaySymbol: String? = null, - @SerializedName("nameCode") - var nameCode: String, + var nameCode: String? = null, - @SerializedName("displayLabel") - var displayLabel: String + var displayLabel: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/client/DepositType.kt b/app/src/main/java/org/mifos/mobile/models/client/DepositType.kt index 6c65a53d60..3ddb4d4899 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/DepositType.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/DepositType.kt @@ -1,22 +1,15 @@ package org.mifos.mobile.models.client import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.api.ApiEndPoints @Parcelize data class DepositType( - @SerializedName("id") var id: Int? = null, + var code: String? = null, - @SerializedName("code") - var code: String, - - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable { fun isRecurring(): Boolean { @@ -32,7 +25,7 @@ data class DepositType( } - enum class ServerTypes constructor(val id: Int?, val code: String, val endpoint: String) { + enum class ServerTypes constructor(val id: Int?, val code: String? = null, val endpoint: String) { SAVINGS(100, "depositAccountType.savingsDeposit", ApiEndPoints.SAVINGS_ACCOUNTS), FIXED(200, "depositAccountType.fixedDeposit", ApiEndPoints.SAVINGS_ACCOUNTS), RECURRING(300, "depositAccountType.recurringDeposit", ApiEndPoints.RECURRING_ACCOUNTS); @@ -41,7 +34,7 @@ data class DepositType( companion object { fun fromId(id: Int): ServerTypes { - for (type in ServerTypes.values()) { + for (type in values()) { if (type.id == id) { return type } diff --git a/app/src/main/java/org/mifos/mobile/models/client/Gender.kt b/app/src/main/java/org/mifos/mobile/models/client/Gender.kt index 1c33b87233..2caea5e423 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/Gender.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/Gender.kt @@ -1,18 +1,12 @@ package org.mifos.mobile.models.client -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 10/7/17. */ -data class Gender ( - - @SerializedName("id") var id: Int, - - @SerializedName("name") var name: String, - - @SerializedName("active") var active: Boolean, - - @SerializedName("mandatory") var mandatory: Boolean +data class Gender( + var id: Int, + var name: String? = null, + var active: Boolean, + var mandatory: Boolean ) diff --git a/app/src/main/java/org/mifos/mobile/models/client/Group.kt b/app/src/main/java/org/mifos/mobile/models/client/Group.kt index 67192fc21c..2eb6757204 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/Group.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/Group.kt @@ -1,16 +1,11 @@ package org.mifos.mobile.models.client -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 10/7/17. */ -data class Group ( - - @SerializedName("id") var id: Int, - - @SerializedName("accountNo") var accountNo: String, - - @SerializedName("name") var name: String +data class Group( + var id: Int, + var accountNo: String? = null, + var name: String? = null ) diff --git a/app/src/main/java/org/mifos/mobile/models/client/Status.kt b/app/src/main/java/org/mifos/mobile/models/client/Status.kt index 6b57f396d4..3d697c2089 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/Status.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/Status.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.client import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,8 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Status( - @SerializedName("id") var id: Int? = null, - - @SerializedName("code") var code: String? = null, - @SerializedName("value") var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/client/Type.kt b/app/src/main/java/org/mifos/mobile/models/client/Type.kt index e76b7b4d08..c63d490870 100644 --- a/app/src/main/java/org/mifos/mobile/models/client/Type.kt +++ b/app/src/main/java/org/mifos/mobile/models/client/Type.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.client import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,8 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Type( - @SerializedName("id") var id: Int? = null, + var code: String? = null, - @SerializedName("code") - var code: String, - - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorApplicationPayload.kt b/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorApplicationPayload.kt index 24579008e5..d587c904de 100644 --- a/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorApplicationPayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorApplicationPayload.kt @@ -4,17 +4,13 @@ package org.mifos.mobile.models.guarantor * Created by saksham on 23/July/2018 */ -import com.google.gson.annotations.SerializedName - data class GuarantorApplicationPayload( - var guarantorType: GuarantorType, + var guarantorType: GuarantorType?, - @SerializedName("firstname") - var firstName: String, + var firstName: String?, - @SerializedName("lastname") - var lastName: String, + var lastName: String?, - var officeName: String + var officeName: String? ) \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorPayload.kt b/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorPayload.kt index 5b693c6ded..717ffffb62 100644 --- a/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorPayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorPayload.kt @@ -5,24 +5,20 @@ package org.mifos.mobile.models.guarantor */ import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import kotlinx.android.parcel.RawValue @Parcelize data class GuarantorPayload( - var id: Long = 0, + var id: Long? = 0, var officeName: String? = null, - @SerializedName("lastname") var lastname: String? = null, var guarantorType: @RawValue GuarantorType? = null, - @SerializedName("firstname") var firstname: String? = null, var joinedDate: List? = null, diff --git a/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorTemplatePayload.kt b/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorTemplatePayload.kt index 1692a036ff..41df3584c5 100644 --- a/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorTemplatePayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/guarantor/GuarantorTemplatePayload.kt @@ -4,7 +4,7 @@ package org.mifos.mobile.models.guarantor * Created by saksham on 23/July/2018 */ -import java.util.ArrayList +import java.util.* data class GuarantorTemplatePayload( diff --git a/app/src/main/java/org/mifos/mobile/models/mifoserror/MifosError.kt b/app/src/main/java/org/mifos/mobile/models/mifoserror/MifosError.kt index 3180bee914..1a62e209c9 100644 --- a/app/src/main/java/org/mifos/mobile/models/mifoserror/MifosError.kt +++ b/app/src/main/java/org/mifos/mobile/models/mifoserror/MifosError.kt @@ -3,8 +3,7 @@ package org.mifos.mobile.models.mifoserror import android.os.Parcelable import kotlinx.android.parcel.Parcelize - -import java.util.ArrayList +import java.util.* @Parcelize data class MifosError( diff --git a/app/src/main/java/org/mifos/mobile/models/notification/MifosNotification.java b/app/src/main/java/org/mifos/mobile/models/notification/MifosNotification.java deleted file mode 100644 index 195211ab2b..0000000000 --- a/app/src/main/java/org/mifos/mobile/models/notification/MifosNotification.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.mifos.mobile.models.notification; - -import com.raizlabs.android.dbflow.annotation.Column; -import com.raizlabs.android.dbflow.annotation.PrimaryKey; -import com.raizlabs.android.dbflow.annotation.Table; -import com.raizlabs.android.dbflow.structure.BaseModel; - -import org.mifos.mobile.api.local.SelfServiceDatabase; - -/** - * Created by dilpreet on 13/9/17. - */ -@Table(database = SelfServiceDatabase.class) -public class MifosNotification extends BaseModel { - - @PrimaryKey - Long timeStamp; - - @Column - String msg; - - @Column - Boolean read; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public long getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(long timeStamp) { - this.timeStamp = timeStamp; - } - - public boolean isRead() { - return read; - } - - public void setRead(boolean read) { - this.read = read; - } -} diff --git a/app/src/main/java/org/mifos/mobile/models/notification/MifosNotification.kt b/app/src/main/java/org/mifos/mobile/models/notification/MifosNotification.kt new file mode 100644 index 0000000000..77db02b597 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/models/notification/MifosNotification.kt @@ -0,0 +1,42 @@ +package org.mifos.mobile.models.notification + +import com.raizlabs.android.dbflow.annotation.Column +import com.raizlabs.android.dbflow.annotation.PrimaryKey +import com.raizlabs.android.dbflow.annotation.Table +import com.raizlabs.android.dbflow.structure.BaseModel + +import org.mifos.mobile.api.local.SelfServiceDatabase + +/** + * Created by dilpreet on 13/9/17. + */ +@Table(database = SelfServiceDatabase::class) +class MifosNotification : BaseModel() { + + @JvmField + @PrimaryKey + var timeStamp: Long = 0 + + @JvmField + @Column + var msg: String? = null + + @JvmField + @Column + var read: Boolean? = null + fun getTimeStamp(): Long { + return timeStamp + } + + fun setTimeStamp(timeStamp: Long) { + this.timeStamp = timeStamp + } + + fun isRead(): Boolean? { + return read + } + + fun setRead(read: Boolean?) { + this.read = read + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/notification/NotificationUserDetail.kt b/app/src/main/java/org/mifos/mobile/models/notification/NotificationUserDetail.kt index 49820e0613..c480e85b48 100644 --- a/app/src/main/java/org/mifos/mobile/models/notification/NotificationUserDetail.kt +++ b/app/src/main/java/org/mifos/mobile/models/notification/NotificationUserDetail.kt @@ -1,12 +1,10 @@ package org.mifos.mobile.models.notification -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 17/12/17. */ -data class NotificationUserDetail ( +data class NotificationUserDetail( - @SerializedName("id") var id: Int = 0 + var id: Int = 0 ) diff --git a/app/src/main/java/org/mifos/mobile/models/payload/AccountDetail.kt b/app/src/main/java/org/mifos/mobile/models/payload/AccountDetail.kt index 4d69711b34..7635fb0860 100644 --- a/app/src/main/java/org/mifos/mobile/models/payload/AccountDetail.kt +++ b/app/src/main/java/org/mifos/mobile/models/payload/AccountDetail.kt @@ -5,5 +5,6 @@ package org.mifos.mobile.models.payload */ data class AccountDetail( - var accountNumber: String, - var accountType: String) + var accountNumber: String?, + var accountType: String? +) diff --git a/app/src/main/java/org/mifos/mobile/models/payload/LoansPayload.kt b/app/src/main/java/org/mifos/mobile/models/payload/LoansPayload.kt index 542a147a3b..de4066134a 100644 --- a/app/src/main/java/org/mifos/mobile/models/payload/LoansPayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/payload/LoansPayload.kt @@ -6,7 +6,6 @@ package org.mifos.mobile.models.payload import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -15,72 +14,52 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class LoansPayload( - @SerializedName("clientId") + var clientId: Int? = null, - @SerializedName("productId") var productId: Int? = null, - @SerializedName("productName") var productName: String? = null, - @SerializedName("principal") var principal: Double? = null, - @SerializedName("loanTermFrequency") var loanTermFrequency: Int? = null, - @SerializedName("loanTermFrequencyType") var loanTermFrequencyType: Int? = null, - @SerializedName("loanType") var loanType: String? = null, - @SerializedName("numberOfRepayments") var numberOfRepayments: Int? = null, - @SerializedName("repaymentEvery") var repaymentEvery: Int? = null, - @SerializedName("repaymentFrequencyType") var repaymentFrequencyType: Int? = null, - @SerializedName("interestRatePerPeriod") var interestRatePerPeriod: Double? = null, - @SerializedName("amortizationType") var amortizationType: Int? = null, - @SerializedName("interestType") var interestType: Int? = null, - @SerializedName("interestCalculationPeriodType") var interestCalculationPeriodType: Int? = null, - @SerializedName("transactionProcessingStrategyId") var transactionProcessingStrategyId: Int? = null, - @SerializedName("expectedDisbursementDate") var expectedDisbursementDate: String? = null, - @SerializedName("submittedOnDate") var submittedOnDate: String? = null, - @SerializedName("linkAccountId") var linkAccountId: Int? = null, - @SerializedName("loanPurposeId") var loanPurposeId: Int? = null, - @SerializedName("loanPurpose") var loanPurpose: String? = null, - @SerializedName("maxOutstandingLoanBalance") var maxOutstandingLoanBalance: Double? = null, - @SerializedName("currency") var currency: String? = null, - var dateFormat : String = "dd MMMM yyyy", - var locale : String = "en" + var dateFormat: String = "dd MMMM yyyy", + + var locale: String = "en" ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/payload/LoginPayload.kt b/app/src/main/java/org/mifos/mobile/models/payload/LoginPayload.kt new file mode 100644 index 0000000000..7019a4062a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/models/payload/LoginPayload.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.models.payload + +/** + * Created by Ashwin on 23rd June 2020 + */ + +data class LoginPayload( + + var username: String? = null, + + var password: String? = null +) \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/payload/TransferPayload.kt b/app/src/main/java/org/mifos/mobile/models/payload/TransferPayload.kt index 21812774dd..58e07b74f7 100644 --- a/app/src/main/java/org/mifos/mobile/models/payload/TransferPayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/payload/TransferPayload.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.payload import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,48 +9,35 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class TransferPayload( - @SerializedName("fromOfficeId") var fromOfficeId: Int? = null, - @SerializedName("fromClientId") var fromClientId: Long? = null, - @SerializedName("fromAccountType") var fromAccountType: Int? = null, - @SerializedName("fromAccountId") var fromAccountId: Int? = null, - @SerializedName("toOfficeId") var toOfficeId: Int? = null, - @SerializedName("toClientId") var toClientId: Long? = null, - @SerializedName("toAccountType") var toAccountType: Int? = null, - @SerializedName("toAccountId") var toAccountId: Int? = null, - @SerializedName("transferDate") var transferDate: String? = null, - @SerializedName("transferAmount") var transferAmount: Double? = null, - @SerializedName("transferDescription") var transferDescription: String? = null, var dateFormat : String = "dd MMMM yyyy", var locale : String = "en", - @SerializedName("fromAccountNumber") @Transient var fromAccountNumber: String? = null, - @SerializedName("toAccountNumber") @Transient var toAccountNumber: String? = null diff --git a/app/src/main/java/org/mifos/mobile/models/register/RegisterPayload.kt b/app/src/main/java/org/mifos/mobile/models/register/RegisterPayload.kt index 6e86a879cc..9b88ec0e20 100644 --- a/app/src/main/java/org/mifos/mobile/models/register/RegisterPayload.kt +++ b/app/src/main/java/org/mifos/mobile/models/register/RegisterPayload.kt @@ -1,34 +1,24 @@ package org.mifos.mobile.models.register -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 31/7/17. */ data class RegisterPayload ( - @SerializedName("username") var username: String? = null, - @SerializedName("firstName") var firstName: String? = null, - @SerializedName("lastName") var lastName: String? = null, - @SerializedName("email") var email: String? = null, - @SerializedName("mobileNumber") var mobileNumber: String? = null, - @SerializedName("accountNumber") var accountNumber: String? = null, - @SerializedName("password") var password: String? = null, - @SerializedName("authenticationMode") var authenticationMode: String? = null ) diff --git a/app/src/main/java/org/mifos/mobile/models/register/UserVerify.kt b/app/src/main/java/org/mifos/mobile/models/register/UserVerify.kt index 9cfc29be68..d7dec1473e 100644 --- a/app/src/main/java/org/mifos/mobile/models/register/UserVerify.kt +++ b/app/src/main/java/org/mifos/mobile/models/register/UserVerify.kt @@ -1,14 +1,10 @@ package org.mifos.mobile.models.register -import com.google.gson.annotations.SerializedName - /** * Created by dilpreet on 31/7/17. */ -data class UserVerify ( - - @SerializedName("requestId") var requestId: String? = null, - - @SerializedName("authenticationToken") var authenticationToken: String? = null +data class UserVerify( + var requestId: String? = null, + var authenticationToken: String? = null ) diff --git a/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOption.kt b/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOption.kt index b621d92992..3fc2d4a42c 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOption.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOption.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.templates.account import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,25 +10,18 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class AccountOption( - @SerializedName("accountId") var accountId: Int? = null, - @SerializedName("accountNo") var accountNo: String? = null, - @SerializedName("accountType") var accountType: AccountType? = null, - @SerializedName("clientId") var clientId: Long? = null, - @SerializedName("clientName") var clientName: String? = null, - @SerializedName("officeId") var officeId: Int? = null, - @SerializedName("officeName") var officeName: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOptionsTemplate.kt b/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOptionsTemplate.kt index ba6acf6501..d4ce77935e 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOptionsTemplate.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/account/AccountOptionsTemplate.kt @@ -1,21 +1,16 @@ package org.mifos.mobile.models.templates.account import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize -import java.util.ArrayList - /** * Created by Rajan Maurya on 10/03/17. */ @Parcelize data class AccountOptionsTemplate( - @SerializedName("fromAccountOptions") + var fromAccountOptions: List = ArrayList(), - @SerializedName("toAccountOptions") var toAccountOptions: List = ArrayList() ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/account/AccountType.kt b/app/src/main/java/org/mifos/mobile/models/templates/account/AccountType.kt index e1ec0879bb..24e86df04d 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/account/AccountType.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/account/AccountType.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.templates.account import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +10,10 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class AccountType( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") var code: String? = null, - @SerializedName("value") var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/AccountTypeOption.kt b/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/AccountTypeOption.kt index 3365a226de..127392452e 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/AccountTypeOption.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/AccountTypeOption.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.beneficiary import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,10 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class AccountTypeOption( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") var code: String? = null, - @SerializedName("value") var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/BeneficiaryTemplate.kt b/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/BeneficiaryTemplate.kt index 69da810b38..4950dab082 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/BeneficiaryTemplate.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/beneficiary/BeneficiaryTemplate.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.templates.beneficiary import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,6 +10,5 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class BeneficiaryTemplate( - @SerializedName("accountTypeOptions") var accountTypeOptions: List? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountLinkingOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountLinkingOptions.kt index 6f2ed49312..a1746fc4fb 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountLinkingOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountLinkingOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,28 +9,20 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class AccountLinkingOptions( - @SerializedName("accountNo") - var accountNo: String, - @SerializedName("clientId") + var accountNo: String? = null, + var clientId: Int? = null, - @SerializedName("clientName") - var clientName: String, + var clientName: String? = null, - @SerializedName("currency") - var currency: Currency, + var currency: Currency? = null, - @SerializedName("fieldOfficerId") var fieldOfficerId: Int? = null, - @SerializedName("id") var id: Int? = null, - @SerializedName("productId") var productId: Int? = null, - @SerializedName("productName") - var productName: String - + var productName: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountingRule.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountingRule.kt index 77c1de6980..b830476149 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountingRule.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/AccountingRule.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -10,12 +9,10 @@ import kotlinx.android.parcel.Parcelize */ @Parcelize data class AccountingRule( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/AllowAttributeOverrides.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/AllowAttributeOverrides.kt index 3cda1a3bc5..88d358a0d9 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/AllowAttributeOverrides.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/AllowAttributeOverrides.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -12,28 +11,20 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class AllowAttributeOverrides( - @SerializedName("amortizationType") var amortizationType: Boolean? = null, - @SerializedName("interestType") var interestType: Boolean? = null, - @SerializedName("transactionProcessingStrategyId") var transactionProcessingStrategyId: Boolean? = null, - @SerializedName("interestCalculationPeriodType") var interestCalculationPeriodType: Boolean? = null, - @SerializedName("inArrearsTolerance") var inArrearsTolerance: Boolean? = null, - @SerializedName("repaymentEvery") var repaymentEvery: Boolean? = null, - @SerializedName("graceOnPrincipalAndInterestPayment") var graceOnPrincipalAndInterestPayment: Boolean? = null, - @SerializedName("graceOnArrearsAgeing") var graceOnArrearsAgeing: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/AmortizationTypeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/AmortizationTypeOptions.kt index 7d63bd4ef6..2fdbd7fefb 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/AmortizationTypeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/AmortizationTypeOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,10 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class AmortizationTypeOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeAppliesTo.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeAppliesTo.kt index ac02aa4e96..5da38239ee 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeAppliesTo.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeAppliesTo.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,10 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class ChargeAppliesTo( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeOptions.kt index af8192c6bb..e26f1c7cf7 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargeOptions.kt @@ -1,10 +1,7 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - import org.mifos.mobile.models.ChargeCalculationType import org.mifos.mobile.models.ChargeTimeType @@ -14,37 +11,27 @@ import org.mifos.mobile.models.ChargeTimeType @Parcelize data class ChargeOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("name") - var name: String, + var name: String? = null, - @SerializedName("active") var active: Boolean? = null, - @SerializedName("penalty") var penalty: Boolean? = null, - @SerializedName("currency") - var currency: Currency, + var currency: Currency? = null, - @SerializedName("amount") var amount: Double? = null, - @SerializedName("chargeTimeType") - var chargeTimeType: ChargeTimeType, + var chargeTimeType: ChargeTimeType? = null, - @SerializedName("chargeAppliesTo") - var chargeAppliesTo: ChargeAppliesTo, + var chargeAppliesTo: ChargeAppliesTo? = null, - @SerializedName("chargeCalculationType") - var chargeCalculationType: ChargeCalculationType, + var chargeCalculationType: ChargeCalculationType? = null, - @SerializedName("chargePaymentMode") - var chargePaymentMode: ChargePaymentMode, + var chargePaymentMode: ChargePaymentMode? = null, - @SerializedName("taxGroup") - var taxGroup: TaxGroup + var taxGroup: TaxGroup? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargePaymentMode.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargePaymentMode.kt index b68fa29fe7..9d09f49269 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargePaymentMode.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/ChargePaymentMode.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,13 +9,10 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class ChargePaymentMode( - @SerializedName("id") - var id: Int? = null, - @SerializedName("code") - var code: String, + var id: Int? = null, - @SerializedName("value") - var value: String + var code: String? = null, + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/Currency.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/Currency.kt index 23075f8096..a6053cdda4 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/Currency.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/Currency.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,24 +9,18 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Currency( - @SerializedName("code") - var code: String, - @SerializedName("name") - var name: String, + var code: String? = null, + + var name: String? = null, - @SerializedName("decimalPlaces") var decimalPlaces: Double? = null, - @SerializedName("inMultiplesOf") var inMultiplesOf: Int? = null, - @SerializedName("displaySymbol") - var displaySymbol: String, + var displaySymbol: String? = null, - @SerializedName("nameCode") - var nameCode: String, + var nameCode: String? = null, - @SerializedName("displayLabel") - var displayLabel: String + var displayLabel: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/FundOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/FundOptions.kt index 7e2f90b322..dde2e44816 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/FundOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/FundOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,9 +9,8 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class FundOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("name") - var name: String + var name: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestRateFrequencyTypeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestRateFrequencyTypeOptions.kt index 30f4476096..c4e54379f0 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestRateFrequencyTypeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestRateFrequencyTypeOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,10 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class InterestRateFrequencyTypeOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestTypeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestTypeOptions.kt index 34f228b9ac..fafc2a3646 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestTypeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/InterestTypeOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,10 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class InterestTypeOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanCollateralOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanCollateralOptions.kt index 494445adfe..6b90c64c4b 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanCollateralOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanCollateralOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,18 +9,14 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class LoanCollateralOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("name") - var name: String, + var name: String? = null, - @SerializedName("position") var position: Int? = null, - @SerializedName("description") - var description: String, + var description: String? = null, - @SerializedName("isActive") var active: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanOfficerOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanOfficerOptions.kt index d6f749e9e2..4bfa3257f2 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanOfficerOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanOfficerOptions.kt @@ -11,26 +11,20 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class LoanOfficerOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("firstname") - var firstname: String, + var firstname: String? = null, - @SerializedName("lastname") - var lastname: String, + var lastname: String? = null, - @SerializedName("displayName") - var displayName: String, + var displayName: String? = null, - @SerializedName("mobileNo") - var mobileNo: String, + var mobileNo: String? = null, - @SerializedName("officeId") var officeId: Int? = null, - @SerializedName("officeName") - var officeName: String, + var officeName: String? = null, @SerializedName("isLoanOfficer") var loanOfficer: Boolean? = null, @@ -38,7 +32,6 @@ data class LoanOfficerOptions( @SerializedName("isActive") var active: Boolean? = null, - @SerializedName("joiningDate") - var joiningDate: List + var joiningDate: List? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanPurposeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanPurposeOptions.kt index 54a3e9ee5c..f59e759a82 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanPurposeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanPurposeOptions.kt @@ -11,17 +11,14 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class LoanPurposeOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("name") - var name: String, + var name: String? = null, - @SerializedName("position") var position: Int? = null, - @SerializedName("description") - var description: String, + var description: String? = null, @SerializedName("isActive") var active: Boolean? = null diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanTemplate.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanTemplate.kt index 63d8bb6188..8f11923300 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanTemplate.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/LoanTemplate.kt @@ -1,20 +1,10 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - -import org.mifos.mobile.models.accounts.loan.AmortizationType -import org.mifos.mobile.models.accounts.loan.DaysInMonthType -import org.mifos.mobile.models.accounts.loan.DaysInYearType -import org.mifos.mobile.models.accounts.loan.InterestCalculationPeriodType -import org.mifos.mobile.models.accounts.loan.InterestRateFrequencyType -import org.mifos.mobile.models.accounts.loan.InterestType -import org.mifos.mobile.models.accounts.loan.RepaymentFrequencyType -import org.mifos.mobile.models.accounts.loan.TermPeriodFrequencyType - -import java.util.ArrayList +import org.mifos.mobile.models.accounts.loan.* +import java.util.* /** * Created by Rajan Maurya on 15/07/16. @@ -22,155 +12,108 @@ import java.util.ArrayList @Parcelize data class LoanTemplate( - @SerializedName("clientId") + var clientId: Int? = null, - @SerializedName("clientAccountNo") - var clientAccountNo: String, + var clientAccountNo: String? = null, - @SerializedName("clientName") - var clientName: String, + var clientName: String? = null, - @SerializedName("clientOfficeId") var clientOfficeId: Int? = null, - @SerializedName("loanProductId") var loanProductId: Int? = null, - @SerializedName("loanProductName") - var loanProductName: String, + var loanProductName: String? = null, @SerializedName("isLoanProductLinkedToFloatingRate") var loanProductLinkedToFloatingRate: Boolean? = null, - @SerializedName("fundId") var fundId: Int? = null, - @SerializedName("fundName") - var fundName: String, + var fundName: String? = null, - @SerializedName("currency") - var currency: Currency, + var currency: Currency? = null, - @SerializedName("principal") var principal: Double? = null, - @SerializedName("approvedPrincipal") var approvedPrincipal: Double? = null, - @SerializedName("proposedPrincipal") var proposedPrincipal: Double? = null, - @SerializedName("termFrequency") var termFrequency: Int? = null, - @SerializedName("termPeriodFrequencyType") - var termPeriodFrequencyType: TermPeriodFrequencyType, + var termPeriodFrequencyType: TermPeriodFrequencyType? = null, - @SerializedName("numberOfRepayments") var numberOfRepayments: Int? = null, - @SerializedName("repaymentEvery") var repaymentEvery: Int? = null, - @SerializedName("repaymentFrequencyType") - var repaymentFrequencyType: RepaymentFrequencyType, + var repaymentFrequencyType: RepaymentFrequencyType? = null, - @SerializedName("interestRatePerPeriod") var interestRatePerPeriod: Double? = null, - @SerializedName("interestRateFrequencyType") - var interestRateFrequencyType: InterestRateFrequencyType, + var interestRateFrequencyType: InterestRateFrequencyType? = null, - @SerializedName("annualInterestRate") var annualInterestRate: Double? = null, @SerializedName("isFloatingInterestRate") var floatingInterestRate: Boolean? = null, - @SerializedName("amortizationType") - var amortizationType: AmortizationType, + var amortizationType: AmortizationType? = null, - @SerializedName("interestType") - var interestType: InterestType, + var interestType: InterestType? = null, - @SerializedName("interestCalculationPeriodType") - var interestCalculationPeriodType: InterestCalculationPeriodType, + var interestCalculationPeriodType: InterestCalculationPeriodType? = null, - @SerializedName("allowPartialPeriodInterestCalcualtion") var allowPartialPeriodInterestCalcualtion: Boolean? = null, - @SerializedName("transactionProcessingStrategyId") var transactionProcessingStrategyId: Int? = null, - @SerializedName("graceOnArrearsAgeing") var graceOnArrearsAgeing: Int? = null, - @SerializedName("timeline") - var timeline: Timeline, + var timeline: Timeline? = null, - @SerializedName("productOptions") var productOptions: List = ArrayList(), - @SerializedName("loanOfficerOptions") var loanOfficerOptions: List = ArrayList(), - @SerializedName("loanPurposeOptions") var loanPurposeOptions: List = ArrayList(), - @SerializedName("fundOptions") var fundOptions: List = ArrayList(), - @SerializedName("termFrequencyTypeOptions") var termFrequencyTypeOptions: List = ArrayList(), - @SerializedName("repaymentFrequencyTypeOptions") var repaymentFrequencyTypeOptions: List = ArrayList(), - @SerializedName("repaymentFrequencyNthDayTypeOptions") var repaymentFrequencyNthDayTypeOptions: List = ArrayList(), - @SerializedName("repaymentFrequencyDaysOfWeekTypeOptions") var repaymentFrequencyDaysOfWeekTypeOptions: List = ArrayList(), - @SerializedName("interestRateFrequencyTypeOptions") var interestRateFrequencyTypeOptions: List = ArrayList(), - @SerializedName("amortizationTypeOptions") var amortizationTypeOptions: List = ArrayList(), - @SerializedName("interestTypeOptions") var interestTypeOptions: List = ArrayList(), - @SerializedName("interestCalculationPeriodTypeOptions") var interestCalculationPeriodTypeOptions: List = ArrayList(), - @SerializedName("transactionProcessingStrategyOptions") var transactionProcessingStrategyOptions: List = ArrayList(), - @SerializedName("chargeOptions") var chargeOptions: List = ArrayList(), - @SerializedName("loanCollateralOptions") var loanCollateralOptions: List = ArrayList(), - @SerializedName("multiDisburseLoan") var multiDisburseLoan: Boolean? = null, - @SerializedName("canDefineInstallmentAmount") var canDefineInstallmentAmount: Boolean? = null, - @SerializedName("canDisburse") var canDisburse: Boolean? = null, - @SerializedName("product") - var product: Product, + var product: Product? = null, - @SerializedName("daysInMonthType") - var daysInMonthType: DaysInMonthType, + var daysInMonthType: DaysInMonthType? = null, - @SerializedName("daysInYearType") - var daysInYearType: DaysInYearType, + var daysInYearType: DaysInYearType? = null, @SerializedName("isInterestRecalculationEnabled") var interestRecalculationEnabled: Boolean? = null, @@ -178,13 +121,10 @@ data class LoanTemplate( @SerializedName("isVariableInstallmentsAllowed") var variableInstallmentsAllowed: Boolean? = null, - @SerializedName("minimumGap") var minimumGap: Int? = null, - @SerializedName("maximumGap") var maximumGap: Int? = null, - @SerializedName("accountLinkingOptions") var accountLinkingOptions: List = ArrayList() ) : Parcelable { diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/Product.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/Product.kt index 651668c85a..2d92809c39 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/Product.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/Product.kt @@ -1,18 +1,9 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize - -import org.mifos.mobile.models.accounts.loan.AmortizationType -import org.mifos.mobile.models.accounts.loan.DaysInMonthType -import org.mifos.mobile.models.accounts.loan.DaysInYearType -import org.mifos.mobile.models.accounts.loan.InterestCalculationPeriodType -import org.mifos.mobile.models.accounts.loan.InterestRateFrequencyType -import org.mifos.mobile.models.accounts.loan.InterestRecalculationData -import org.mifos.mobile.models.accounts.loan.InterestType -import org.mifos.mobile.models.accounts.loan.RepaymentFrequencyType +import org.mifos.mobile.models.accounts.loan.* /** * Created by Rajan Maurya on 16/07/16. @@ -20,73 +11,51 @@ import org.mifos.mobile.models.accounts.loan.RepaymentFrequencyType @Parcelize data class Product( - @SerializedName("id") + var id: Int? = null, - @SerializedName("name") - var name: String, + var name: String? = null, - @SerializedName("shortName") - var shortName: String, + var shortName: String? = null, - @SerializedName("fundId") var fundId: Int? = null, - @SerializedName("fundName") - var fundName: String, + var fundName: String? = null, - @SerializedName("includeInBorrowerCycle") var includeInBorrowerCycle: Boolean? = null, - @SerializedName("useBorrowerCycle") var useBorrowerCycle: Boolean? = null, - @SerializedName("startDate") - var startDate: List, + var startDate: List? = null, - @SerializedName("status") - var status: String, + var status: String? = null, - @SerializedName("currency") - var currency: Currency, + var currency: Currency? = null, - @SerializedName("principal") var principal: Double? = null, - @SerializedName("minPrincipal") var minPrincipal: Double? = null, - @SerializedName("maxPrincipal") var maxPrincipal: Double? = null, - @SerializedName("numberOfRepayments") var numberOfRepayments: Int? = null, - @SerializedName("minNumberOfRepayments") var minNumberOfRepayments: Int? = null, - @SerializedName("maxNumberOfRepayments") var maxNumberOfRepayments: Int? = null, - @SerializedName("repaymentEvery") var repaymentEvery: Int? = null, - @SerializedName("repaymentFrequencyType") - var repaymentFrequencyType: RepaymentFrequencyType, + var repaymentFrequencyType: RepaymentFrequencyType? = null, - @SerializedName("interestRatePerPeriod") var interestRatePerPeriod: Double? = null, - @SerializedName("minInterestRatePerPeriod") var minInterestRatePerPeriod: Double? = null, - @SerializedName("maxInterestRatePerPeriod") var maxInterestRatePerPeriod: Double? = null, - @SerializedName("interestRateFrequencyType") - var interestRateFrequencyType: InterestRateFrequencyType, + var interestRateFrequencyType: InterestRateFrequencyType? = null, - @SerializedName("annualInterestRate") var annualInterestRate: Double? = null, @SerializedName("isLinkedToFloatingInterestRates") @@ -95,73 +64,51 @@ data class Product( @SerializedName("isFloatingInterestRateCalculationAllowed") var floatingInterestRateCalculationAllowed: Boolean? = null, - @SerializedName("allowVariableInstallments") var allowVariableInstallments: Boolean? = null, - @SerializedName("minimumGap") var minimumGap: Double? = null, - @SerializedName("maximumGap") var maximumGap: Double? = null, - @SerializedName("amortizationType") var amortizationType: AmortizationType, - @SerializedName("interestType") var interestType: InterestType, - @SerializedName("interestCalculationPeriodType") - var interestCalculationPeriodType: InterestCalculationPeriodType, + var interestCalculationPeriodType: InterestCalculationPeriodType? = null, - @SerializedName("allowPartialPeriodInterestCalcualtion") var allowPartialPeriodInterestCalcualtion: Boolean? = null, - @SerializedName("transactionProcessingStrategyId") var transactionProcessingStrategyId: Int? = null, - @SerializedName("transactionProcessingStrategyName") - var transactionProcessingStrategyName: String, + var transactionProcessingStrategyName: String? = null, - @SerializedName("graceOnArrearsAgeing") var graceOnArrearsAgeing: Int? = null, - @SerializedName("overdueDaysForNPA") var overdueDaysForNPA: Int? = null, - @SerializedName("daysInMonthType") - var daysInMonthType: DaysInMonthType, + var daysInMonthType: DaysInMonthType? = null, - @SerializedName("daysInYearType") var daysInYearType: DaysInYearType, @SerializedName("isInterestRecalculationEnabled") var interestRecalculationEnabled: Boolean? = null, - @SerializedName("interestRecalculationData") - var interestRecalculationData: InterestRecalculationData, + var interestRecalculationData: InterestRecalculationData? = null, - @SerializedName("canDefineInstallmentAmount") var canDefineInstallmentAmount: Boolean? = null, - @SerializedName("accountingRule") - var accountingRule: AccountingRule, + var accountingRule: AccountingRule? = null, - @SerializedName("multiDisburseLoan") var multiDisburseLoan: Boolean? = null, - @SerializedName("maxTrancheCount") var maxTrancheCount: Int? = null, - @SerializedName("principalThresholdForLastInstallment") var principalThresholdForLastInstallment: Int? = null, - @SerializedName("holdGuaranteeFunds") var holdGuaranteeFunds: Boolean? = null, - @SerializedName("accountMovesOutOfNPAOnlyOnArrearsCompletion") var accountMovesOutOfNPAOnlyOnArrearsCompletion: Boolean? = null, - @SerializedName("allowAttributeOverrides") - var allowAttributeOverrides: AllowAttributeOverrides + var allowAttributeOverrides: AllowAttributeOverrides? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/ProductOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/ProductOptions.kt index 3c11d99288..9e72da123f 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/ProductOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/ProductOptions.kt @@ -11,16 +11,13 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class ProductOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("name") - var name: String, + var name: String? = null, - @SerializedName("includeInBorrowerCycle") var includeInBorrowerCycle: Boolean? = null, - @SerializedName("useBorrowerCycle") var useBorrowerCycle: Boolean? = null, @SerializedName("isLinkedToFloatingInterestRates") @@ -29,18 +26,14 @@ data class ProductOptions( @SerializedName("isFloatingInterestRateCalculationAllowed") var floatingInterestRateCalculationAllowed: Boolean? = null, - @SerializedName("allowVariableInstallments") var allowVariableInstallments: Boolean? = null, @SerializedName("isInterestRecalculationEnabled") var interestRecalculationEnabled: Boolean? = null, - @SerializedName("canDefineInstallmentAmount") var canDefineInstallmentAmount: Boolean? = null, - @SerializedName("holdGuaranteeFunds") var holdGuaranteeFunds: Boolean? = null, - @SerializedName("accountMovesOutOfNPAOnlyOnArrearsCompletion") var accountMovesOutOfNPAOnlyOnArrearsCompletion: Boolean? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyDaysOfWeekTypeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyDaysOfWeekTypeOptions.kt index 024c47109b..3df8f67d9a 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyDaysOfWeekTypeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyDaysOfWeekTypeOptions.kt @@ -1,18 +1,14 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class RepaymentFrequencyDaysOfWeekTypeOptions( - @SerializedName("id") + var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyNthDayTypeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyNthDayTypeOptions.kt index 8c8c1bb479..2187e60ad1 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyNthDayTypeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyNthDayTypeOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class RepaymentFrequencyNthDayTypeOptions( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyTypeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyTypeOptions.kt index ea3a045209..afa44d1fca 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyTypeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/RepaymentFrequencyTypeOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class RepaymentFrequencyTypeOptions( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/TaxGroup.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/TaxGroup.kt index 3c86746415..d34e05e2dd 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/TaxGroup.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/TaxGroup.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,9 +9,7 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class TaxGroup( - @SerializedName("id") var id: Int? = null, - @SerializedName("name") - var name: String + var name: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/TermFrequencyTypeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/TermFrequencyTypeOptions.kt index d97a1a6939..c39d6d1ae8 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/TermFrequencyTypeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/TermFrequencyTypeOptions.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +9,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class TermFrequencyTypeOptions( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("value") - var value: String + var value: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/Timeline.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/Timeline.kt index b39c91b2c9..066f527fb0 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/Timeline.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/Timeline.kt @@ -1,8 +1,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable - -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,6 +9,5 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class Timeline( - @SerializedName("expectedDisbursementDate") var expectedDisbursementDate: List ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/loans/TransactionProcessingStrategyOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/loans/TransactionProcessingStrategyOptions.kt index 5ebc719c2e..585d94036f 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/loans/TransactionProcessingStrategyOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/loans/TransactionProcessingStrategyOptions.kt @@ -2,7 +2,6 @@ package org.mifos.mobile.models.templates.loans import android.os.Parcelable -import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** @@ -11,12 +10,9 @@ import kotlinx.android.parcel.Parcelize @Parcelize data class TransactionProcessingStrategyOptions( - @SerializedName("id") var id: Int? = null, - @SerializedName("code") - var code: String, + var code: String? = null, - @SerializedName("name") - var name: String + var name: String? = null ) : Parcelable \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/models/templates/savings/ChargeOptions.kt b/app/src/main/java/org/mifos/mobile/models/templates/savings/ChargeOptions.kt index 190d2a3b52..983b1f9a0f 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/savings/ChargeOptions.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/savings/ChargeOptions.kt @@ -10,7 +10,7 @@ data class ChargeOptions( var name: String? = null, var active: Boolean? = null, var penalty: Boolean? = null, - var currency: Currency, + var currency: Currency? = null, var amount: Float = 0.toFloat(), var chargeTimeType: ChargeTimeType, var chargeAppliesTo: ChargeAppliesTo, diff --git a/app/src/main/java/org/mifos/mobile/models/templates/savings/SavingsAccountTemplate.kt b/app/src/main/java/org/mifos/mobile/models/templates/savings/SavingsAccountTemplate.kt index 18a393657e..a35a740a6b 100644 --- a/app/src/main/java/org/mifos/mobile/models/templates/savings/SavingsAccountTemplate.kt +++ b/app/src/main/java/org/mifos/mobile/models/templates/savings/SavingsAccountTemplate.kt @@ -6,7 +6,7 @@ package org.mifos.mobile.models.templates.savings import android.os.Parcelable import kotlinx.android.parcel.Parcelize -import java.util.ArrayList +import java.util.* @Parcelize data class SavingsAccountTemplate( diff --git a/app/src/main/java/org/mifos/mobile/presenters/AccountOverviewPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/AccountOverviewPresenter.java deleted file mode 100644 index b849fc5923..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/AccountOverviewPresenter.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.models.client.ClientAccounts; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.AccountOverviewMvpView; - -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * @author Rajan Maurya - * On 16/10/17. - */ -public class AccountOverviewPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - @Inject - public AccountOverviewPresenter(@ApplicationContext Context context, - DataManager dataManager) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(AccountOverviewMvpView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Fetches Client account details as {@link ClientAccounts} from the server and notifies the - * view to display the {@link List} of {@link LoanAccount} and {@link SavingAccount}. And in - * case of any error during fetching the required details it notifies the view. - */ - public void loadClientAccountDetails() { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getClientAccounts() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.error_fetching_accounts)); - } - - @Override - public void onNext(ClientAccounts clientAccounts) { - getMvpView().hideProgress(); - getMvpView().showTotalLoanSavings( - getLoanAccountDetails(clientAccounts.getLoanAccounts()), - getSavingAccountDetails(clientAccounts.getSavingsAccounts())); - } - }) - ); - } - - /** - * Returns total Loan balance - * - * @param loanAccountList {@link List} of {@link LoanAccount} associated with the client - * @return Returns {@code totalAmount} which is calculated by adding all {@link LoanAccount} - * balance. - */ - public double getLoanAccountDetails(List loanAccountList) { - double totalAmount = 0; - for (LoanAccount loanAccount : loanAccountList) { - totalAmount += loanAccount.getLoanBalance(); - } - return totalAmount; - } - - /** - * Returns total Savings balance - * - * @param savingAccountList {@link List} of {@link SavingAccount} associated with the client - * @return Returns {@code totalAmount} which is calculated by adding all {@link SavingAccount} - * balance. - */ - public double getSavingAccountDetails(List savingAccountList) { - double totalAmount = 0; - for (SavingAccount savingAccount : savingAccountList) { - totalAmount += savingAccount.getAccountBalance(); - } - return totalAmount; - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/AccountOverviewPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/AccountOverviewPresenter.kt new file mode 100644 index 0000000000..793389f37c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/AccountOverviewPresenter.kt @@ -0,0 +1,97 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.AccountOverviewMvpView + +import javax.inject.Inject + +/** + * @author Rajan Maurya + * On 16/10/17. + */ +class AccountOverviewPresenter @Inject constructor( + @ApplicationContext context: Context?, + private val dataManager: DataManager? +) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Fetches Client account details as [ClientAccounts] from the server and notifies the + * view to display the [List] of [LoanAccount] and [SavingAccount]. And in + * case of any error during fetching the required details it notifies the view. + */ + fun loadClientAccountDetails() { + checkViewAttached() + mvpView?.showProgress() + dataManager?.clientAccounts + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + override fun onNext(clientAccounts: ClientAccounts) { + mvpView?.hideProgress() + mvpView?.showTotalLoanSavings( + getLoanAccountDetails(clientAccounts.loanAccounts), + getSavingAccountDetails(clientAccounts.savingsAccounts)) + } + })?.let { + compositeDisposable.add(it + ) + } + } + + /** + * Returns total Loan balance + * + * @param loanAccountList [List] of [LoanAccount] associated with the client + * @return Returns `totalAmount` which is calculated by adding all [LoanAccount] + * balance. + */ + fun getLoanAccountDetails(loanAccountList: List?): Double { + var totalAmount = 0.0 + if (loanAccountList != null) + for ((_, _, _, _, _, _, _, _, _, _, _, _, _, _, loanBalance) in loanAccountList) { + totalAmount += loanBalance + } + return totalAmount + } + + /** + * Returns total Savings balance + * + * @param savingAccountList [List] of [SavingAccount] associated with the client + * @return Returns `totalAmount` which is calculated by adding all [SavingAccount] + * balance. + */ + fun getSavingAccountDetails(savingAccountList: List?): Double { + var totalAmount = 0.0 + for ((_, _, _, _, _, accountBalance) in savingAccountList!!) { + totalAmount += accountBalance + } + return totalAmount + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/AccountsPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/AccountsPresenter.java deleted file mode 100644 index 915b57166b..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/AccountsPresenter.java +++ /dev/null @@ -1,331 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.CheckboxStatus; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.models.accounts.share.ShareAccount; -import org.mifos.mobile.models.client.ClientAccounts; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.AccountsView; -import org.mifos.mobile.utils.Constants; - -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.Observable; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.functions.Predicate; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * Created by Rajan Maurya on 23/10/16. - */ - -public class AccountsPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the AccountsPresenter by automatically injecting an instance of - * {@link Context} and {@link DataManager} . - * - * @param context Context of the view attached to the presenter. - * @param dataManager DataManager class that provides access to the data - * via the API. - */ - @Inject - public AccountsPresenter(@ApplicationContext Context context, DataManager dataManager) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(AccountsView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Loads savings, loan and share accounts associated with the Client from the server - * and notifies the view to display it. And in case of any error during fetching the required - * details it notifies the view. - */ - public void loadClientAccounts() { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getClientAccounts() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.error_fetching_accounts)); - } - - @Override - public void onNext(ClientAccounts clientAccounts) { - getMvpView().hideProgress(); - getMvpView().showSavingsAccounts(clientAccounts.getSavingsAccounts()); - getMvpView().showLoanAccounts(clientAccounts.getLoanAccounts()); - getMvpView().showShareAccounts(clientAccounts.getShareAccounts()); - } - }) - ); - } - - /** - * Loads savings, loan or share account depending upon {@code accountType} provided from the - * server and notifies the view to display it.And in case of any error during fetching the - * required details it notifies the view. - * @param accountType Type of account for which we need to fetch details - */ - public void loadAccounts(final String accountType) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getAccounts(accountType) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.error_fetching_accounts)); - } - - @Override - public void onNext(ClientAccounts clientAccounts) { - getMvpView().hideProgress(); - switch (accountType) { - case Constants.SAVINGS_ACCOUNTS: - getMvpView().showSavingsAccounts( - clientAccounts.getSavingsAccounts()); - break; - case Constants.LOAN_ACCOUNTS: - getMvpView().showLoanAccounts(clientAccounts.getLoanAccounts()); - break; - case Constants.SHARE_ACCOUNTS: - getMvpView().showShareAccounts(clientAccounts.getShareAccounts()); - break; - } - } - }) - ); - } - - /** - * Filters {@link List} of {@link SavingAccount} - * @param accounts {@link List} of {@link SavingAccount} - * @param input {@link String} which is used for filtering - * @return Returns {@link List} of filtered {@link SavingAccount} according to the {@code input} - * provided. - */ - public List searchInSavingsList(List accounts, - final String input) { - return Observable.fromIterable(accounts) - .filter(new Predicate() { - @Override - public boolean test(SavingAccount savingAccount) throws Exception { - return (savingAccount.getProductName().toLowerCase().contains(input. - toLowerCase()) || - savingAccount.getAccountNo().toLowerCase().contains(input. - toLowerCase())); - } - }).toList().blockingGet(); - } - - /** - * Filters {@link List} of {@link LoanAccount} - * @param accounts {@link List} of {@link LoanAccount} - * @param input {@link String} which is used for filtering - * @return Returns {@link List} of filtered {@link LoanAccount} according to the {@code input} - * provided. - */ - public List searchInLoanList(List accounts, - final String input) { - return Observable.fromIterable(accounts) - .filter(new Predicate() { - @Override - public boolean test(LoanAccount loanAccount) throws Exception { - return (loanAccount.getProductName().toLowerCase().contains(input. - toLowerCase()) || - loanAccount.getAccountNo().toLowerCase().contains(input. - toLowerCase())); - } - }).toList().blockingGet(); - } - - /** - * Filters {@link List} of {@link ShareAccount} - * @param accounts {@link List} of {@link ShareAccount} - * @param input {@link String} which is used for filtering - * @return Returns {@link List} of filtered {@link ShareAccount} according to the {@code input} - * provided. - */ - public List searchInSharesList(List accounts, - final String input) { - return Observable.fromIterable(accounts) - .filter(new Predicate() { - @Override - public boolean test(ShareAccount shareAccount) throws Exception { - return (shareAccount.getProductName().toLowerCase().contains(input. - toLowerCase()) || - shareAccount.getAccountNo().toLowerCase().contains(input. - toLowerCase())); - } - }).toList().blockingGet(); - } - - /** - * Filters {@link List} of {@link CheckboxStatus} - * @param statusModelList {@link List} of {@link CheckboxStatus} - * @return Returns {@link List} of {@link CheckboxStatus} which have - * {@code checkboxStatus.isChecked()} as true. - */ - public List getCheckedStatus(List statusModelList) { - return Observable.fromIterable(statusModelList) - .filter(new Predicate() { - - @Override - public boolean test(CheckboxStatus checkboxStatus) throws Exception { - return checkboxStatus.isChecked(); - } - }).toList().blockingGet(); - } - - /** - * Filters {@link List} of {@link SavingAccount} according to {@link CheckboxStatus} - * @param accounts {@link List} of filtered {@link SavingAccount} - * @param status Used for filtering the {@link List} - * @return Returns {@link List} of filtered {@link SavingAccount} according to the - * {@code status} provided. - */ - public List getFilteredSavingsAccount(List accounts, - final CheckboxStatus status) { - return Observable.fromIterable(accounts) - .filter(new Predicate() { - @Override - public boolean test(SavingAccount account) { - if (status.getStatus().compareTo(context.getString(R.string. - active)) == 0 && account.getStatus().getActive()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - approved)) == 0 && account.getStatus().getApproved()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - approval_pending)) == 0 && account.getStatus(). - getSubmittedAndPendingApproval()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - matured)) == 0 && account.getStatus().getMatured()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - closed)) == 0 && account.getStatus().getClosed()) { - return true; - } - return false; - } - }).toList().blockingGet(); - } - - /** - * Filters {@link List} of {@link LoanAccount} according to {@link CheckboxStatus} - * @param accounts {@link List} of filtered {@link LoanAccount} - * @param status Used for filtering the {@link List} - * @return Returns {@link List} of filtered {@link LoanAccount} according to the - * {@code status} provided. - */ - public List getFilteredLoanAccount(List accounts, - final CheckboxStatus status) { - return Observable.fromIterable(accounts) - .filter(new Predicate() { - @Override - public boolean test(LoanAccount account) { - if (status.getStatus().compareTo(context.getString(R.string.in_arrears)) - == 0 && account.getInArrears()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - active)) == 0 && account.getStatus().getActive()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - waiting_for_disburse)) == 0 && account.getStatus(). - getWaitingForDisbursal()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - approval_pending)) == 0 && account.getStatus(). - getPendingApproval()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - overpaid)) == 0 && account.getStatus().getOverpaid()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - closed)) == 0 && account.getStatus().getClosed()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - withdrawn)) == 0 && account.getStatus().isLoanTypeWithdrawn()) { - return true; - } - return false; - } - }).toList().blockingGet(); - } - - /** - * Filters {@link List} of {@link ShareAccount} according to {@link CheckboxStatus} - * @param accounts {@link List} of filtered {@link ShareAccount} - * @param status Used for filtering the {@link List} - * @return Returns {@link List} of filtered {@link ShareAccount} according to the - * {@code status} provided. - */ - public List getFilteredShareAccount(List accounts, - final CheckboxStatus status) { - return Observable.fromIterable(accounts) - .filter(new Predicate() { - @Override - public boolean test(ShareAccount account) { - if (status.getStatus().compareTo(context.getString(R.string.active)) == 0 && - account.getStatus().getActive()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - approved)) == 0 && account.getStatus().getApproved()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - approval_pending)) == 0 && account.getStatus(). - getSubmittedAndPendingApproval()) { - return true; - } else if (status.getStatus().compareTo(context.getString(R.string. - closed)) == 0 && account.getStatus().getClosed()) { - return true; - } - return false; - } - }).toList().blockingGet(); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/AccountsPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/AccountsPresenter.kt new file mode 100644 index 0000000000..9db87c9846 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/AccountsPresenter.kt @@ -0,0 +1,257 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.Observable +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.functions.Predicate +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.CheckboxStatus +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.models.accounts.share.ShareAccount +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.AccountsView +import org.mifos.mobile.utils.Constants +import java.util.* + +import javax.inject.Inject + +/** + * Created by Rajan Maurya on 23/10/16. + */ +class AccountsPresenter @Inject constructor(@ApplicationContext context: Context?, private val dataManager: DataManager?) : + BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Loads savings, loan and share accounts associated with the Client from the server + * and notifies the view to display it. And in case of any error during fetching the required + * details it notifies the view. + */ + fun loadClientAccounts() { + checkViewAttached() + mvpView?.showProgress() + dataManager?.clientAccounts + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + override fun onNext(clientAccounts: ClientAccounts) { + mvpView?.hideProgress() + mvpView?.showSavingsAccounts(clientAccounts.savingsAccounts) + mvpView?.showLoanAccounts(clientAccounts.loanAccounts) + mvpView?.showShareAccounts(clientAccounts.shareAccounts) + } + })?.let { + compositeDisposable.add(it + ) + } + } + + /** + * Loads savings, loan or share account depending upon `accountType` provided from the + * server and notifies the view to display it.And in case of any error during fetching the + * required details it notifies the view. + * @param accountType Type of account for which we need to fetch details + */ + fun loadAccounts(accountType: String?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getAccounts(accountType) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + override fun onNext(clientAccounts: ClientAccounts) { + mvpView?.hideProgress() + when (accountType) { + Constants.SAVINGS_ACCOUNTS -> mvpView?.showSavingsAccounts( + clientAccounts.savingsAccounts) + Constants.LOAN_ACCOUNTS -> mvpView?.showLoanAccounts(clientAccounts.loanAccounts) + Constants.SHARE_ACCOUNTS -> mvpView?.showShareAccounts(clientAccounts.shareAccounts) + } + } + })?.let { + compositeDisposable.add(it + ) + } + } + + /** + * Filters [List] of [SavingAccount] + * @param accounts [List] of [SavingAccount] + * @param input [String] which is used for filtering + * @return Returns [List] of filtered [SavingAccount] according to the `input` + * provided. + */ + fun searchInSavingsList( + accounts: List?, + input: String? + ): List { + return Observable.fromIterable(accounts) + .filter { (accountNo, productName) -> + input?.toLowerCase(Locale.ROOT)?.let { productName?.toLowerCase(Locale.ROOT)?.contains(it) } == true || + input?.toLowerCase(Locale.ROOT)?.let { accountNo?.toLowerCase(Locale.ROOT)?.contains(it) } == true + }.toList().blockingGet() + } + + /** + * Filters [List] of [LoanAccount] + * @param accounts [List] of [LoanAccount] + * @param input [String] which is used for filtering + * @return Returns [List] of filtered [LoanAccount] according to the `input` + * provided. + */ + fun searchInLoanList( + accounts: List?, + input: String? + ): List? { + return Observable.fromIterable(accounts) + .filter { (_, _, _, accountNo, productName) -> + input?.toLowerCase(Locale.ROOT)?.let { productName?.toLowerCase(Locale.ROOT)?.contains(it) } == true || + input?.toLowerCase(Locale.ROOT)?.let { accountNo?.toLowerCase(Locale.ROOT)?.contains(it) } == true + }.toList().blockingGet() + } + + /** + * Filters [List] of [ShareAccount] + * @param accounts [List] of [ShareAccount] + * @param input [String] which is used for filtering + * @return Returns [List] of filtered [ShareAccount] according to the `input` + * provided. + */ + fun searchInSharesList( + accounts: Collection?, + input: String? + ): List? { + return Observable.fromIterable(accounts) + .filter { (accountNo, _, _, _, productName) -> + input?.toLowerCase(Locale.ROOT)?.let { productName?.toLowerCase(Locale.ROOT)?.contains(it) } == true || + input?.toLowerCase(Locale.ROOT)?.let { accountNo?.toLowerCase(Locale.ROOT)?.contains(it) } == true + }.toList().blockingGet() + } + + /** + * Filters [List] of [CheckboxStatus] + * @param statusModelList [List] of [CheckboxStatus] + * @return Returns [List] of [CheckboxStatus] which have + * `checkboxStatus.isChecked()` as true. + */ + fun getCheckedStatus(statusModelList: List?): List? { + return Observable.fromIterable(statusModelList) + .filter { (_, _, isChecked) -> isChecked }.toList().blockingGet() + } + + /** + * Filters [List] of [SavingAccount] according to [CheckboxStatus] + * @param accounts [List] of filtered [SavingAccount] + * @param status Used for filtering the [List] + * @return Returns [List] of filtered [SavingAccount] according to the + * `status` provided. + */ + fun getFilteredSavingsAccount( + accounts: List?, + status: CheckboxStatus? + ): Collection? { + return Observable.fromIterable(accounts) + .filter(Predicate { (_, _, _, _, _, _, _, _, _, _, _, status1) -> + if (context?.getString(R.string.active)?.let { status?.status?.compareTo(it) } == 0 && status1?.active == true) { + return@Predicate true + } else if (context?.getString(R.string.approved)?.let { status?.status?.compareTo(it) } == 0 && status1?.approved == true) { + return@Predicate true + } else if (context?.getString(R.string.approval_pending)?.let { status?.status?.compareTo(it) } == 0 && status1?.submittedAndPendingApproval == true) { + return@Predicate true + } else if (context?.getString(R.string.matured)?.let { status?.status?.compareTo(it) } == 0 && status1?.matured == true) { + return@Predicate true + } else if (context?.getString(R.string.closed)?.let { status?.status?.compareTo(it) } == 0 && status1?.closed == true) { + return@Predicate true + } + false + }).toList().blockingGet() + } + + /** + * Filters [List] of [LoanAccount] according to [CheckboxStatus] + * @param accounts [List] of filtered [LoanAccount] + * @param status Used for filtering the [List] + * @return Returns [List] of filtered [LoanAccount] according to the + * `status` provided. + */ + fun getFilteredLoanAccount( + accounts: List?, + status: CheckboxStatus? + ): Collection? { + return Observable.fromIterable(accounts) + .filter(Predicate { (_, _, _, _, _, _, _, _, _, _, _, status1, _, _, _, _, _, inArrears) -> + if (context?.getString(R.string.in_arrears)?.let { status?.status?.compareTo(it) } + == 0 && inArrears == true) { + return@Predicate true + } else if (context?.getString(R.string.active)?.let { status?.status?.compareTo(it) } == 0 && status1?.active == true) { + return@Predicate true + } else if (context?.getString(R.string.waiting_for_disburse)?.let { status?.status?.compareTo(it) } == 0 && status1?.waitingForDisbursal == true) { + return@Predicate true + } else if (context?.getString(R.string.approval_pending)?.let { status?.status?.compareTo(it) } == 0 && status1?.pendingApproval == true) { + return@Predicate true + } else if (context?.getString(R.string.overpaid)?.let { status?.status?.compareTo(it) } == 0 && status1?.overpaid == true) { + return@Predicate true + } else if (context?.getString(R.string.closed)?.let { status?.status?.compareTo(it) } == 0 && status1?.closed == true) { + return@Predicate true + } else if (context?.getString(R.string.withdrawn)?.let { status?.status?.compareTo(it) } == 0 && status1?.isLoanTypeWithdrawn() == true) { + return@Predicate true + } + false + }).toList().blockingGet() + } + + /** + * Filters [List] of [ShareAccount] according to [CheckboxStatus] + * @param accounts [List] of filtered [ShareAccount] + * @param status Used for filtering the [List] + * @return Returns [List] of filtered [ShareAccount] according to the + * `status` provided. + */ + fun getFilteredShareAccount( + accounts: List?, + status: CheckboxStatus? + ): Collection? { + return Observable.fromIterable(accounts) + .filter(Predicate { (_, _, _, _, _, _, status1) -> + if (context?.getString(R.string.active)?.let { status?.status?.compareTo(it) } == 0 && + status1?.active == true) { + return@Predicate true + } else if (context?.getString(R.string.approved)?.let { status?.status?.compareTo(it) } == 0 && status1?.approved == true) { + return@Predicate true + } else if (context?.getString(R.string.approval_pending)?.let { status?.status?.compareTo(it) } == 0 && status1?.submittedAndPendingApproval == true) { + return@Predicate true + } else if (context?.getString(R.string.closed)?.let { status?.status?.compareTo(it) } == 0 && status1?.closed == true) { + return@Predicate true + } + false + }).toList().blockingGet() + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/AddGuarantorPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/AddGuarantorPresenter.java deleted file mode 100644 index aa1e8011b8..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/AddGuarantorPresenter.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.mifos.mobile.presenters; - -/* - * Created by saksham on 23/July/2018 - */ - -import android.content.Context; -import android.util.Log; - -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload; -import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.enums.GuarantorState; -import org.mifos.mobile.ui.views.AddGuarantorView; - -import java.io.IOException; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -public class AddGuarantorPresenter extends BasePresenter { - - public static final String TAG = AddGuarantorPresenter.class.getSimpleName(); - DataManager dataManager; - CompositeDisposable compositeDisposable; - - @Inject - protected AddGuarantorPresenter(@ActivityContext Context context, DataManager dataManager) { - super(context); - compositeDisposable = new CompositeDisposable(); - this.dataManager = dataManager; - } - - @Override - public void attachView(AddGuarantorView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - public void getGuarantorTemplate(final GuarantorState state, long loanId) { - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getGuarantorTemplate(loanId) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(GuarantorTemplatePayload payload) { - getMvpView().hideProgress(); - if (state == GuarantorState.CREATE) { - getMvpView().showGuarantorApplication(payload); - - } else if (state == GuarantorState.UPDATE) { - getMvpView().showGuarantorUpdation(payload); - } - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - } - - @Override - public void onComplete() { - - } - })); - } - - public void createGuarantor(long loanId, final GuarantorApplicationPayload payload) { - getMvpView().showProgress(); - compositeDisposable.add(dataManager.createGuarantor(loanId, payload) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - try { - getMvpView().submittedSuccessfully(responseBody.string(), payload); - } catch (IOException e) { - Log.d(TAG, e.getMessage()); - } - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - - } - - @Override - public void onComplete() { - - } - })); - } - - public void updateGuarantor(GuarantorApplicationPayload payload, long loanId, - long guarantorId) { - getMvpView().showProgress(); - compositeDisposable.add(dataManager.updateGuarantor(payload, loanId, guarantorId) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - try { - getMvpView().updatedSuccessfully(responseBody.string()); - } catch (IOException e) { - Log.d(TAG, e.getMessage()); - } - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(e.getMessage()); - } - - @Override - public void onComplete() { - - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/AddGuarantorPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/AddGuarantorPresenter.kt new file mode 100644 index 0000000000..f36ea37b32 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/AddGuarantorPresenter.kt @@ -0,0 +1,114 @@ +package org.mifos.mobile.presenters + +import android.content.Context +import android.util.Log + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload +import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.enums.GuarantorState +import org.mifos.mobile.ui.views.AddGuarantorView + +import java.io.IOException +import javax.inject.Inject + +/* +* Created by saksham on 23/July/2018 +*/ +class AddGuarantorPresenter @Inject constructor(@ActivityContext context: Context?, var dataManager: DataManager?) : + BasePresenter(context) { + + var compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun getGuarantorTemplate(state: GuarantorState?, loanId: Long?) { + mvpView?.showProgress() + dataManager?.getGuarantorTemplate(loanId) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(payload: GuarantorTemplatePayload) { + mvpView?.hideProgress() + if (state === GuarantorState.CREATE) { + mvpView?.showGuarantorApplication(payload) + } else if (state === GuarantorState.UPDATE) { + mvpView?.showGuarantorUpdation(payload) + } + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + + fun createGuarantor(loanId: Long?, payload: GuarantorApplicationPayload?) { + mvpView?.showProgress() + dataManager?.createGuarantor(loanId, payload) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + try { + mvpView?.submittedSuccessfully(responseBody.string(), payload) + } catch (e: IOException) { + Log.d(TAG, e.message) + } + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + + fun updateGuarantor( + payload: GuarantorApplicationPayload?, loanId: Long?, + guarantorId: Long? + ) { + mvpView?.showProgress() + dataManager?.updateGuarantor(payload, loanId, guarantorId) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + try { + mvpView?.updatedSuccessfully(responseBody.string()) + } catch (e: IOException) { + Log.d(TAG, e.message) + } + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(e.message) + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + + companion object { + val TAG: String? = AddGuarantorPresenter::class.java.simpleName + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryApplicationPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryApplicationPresenter.java deleted file mode 100644 index 30ffcd55aa..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryApplicationPresenter.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; -import android.view.View; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.beneficiary.BeneficiaryPayload; -import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload; -import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.BeneficiaryApplicationView; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -/** - * Created by dilpreet on 16/6/17. - */ - -public class BeneficiaryApplicationPresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public BeneficiaryApplicationPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Loads BeneficiaryTemplate from the server and notifies the view to display it. And in case of - * any error during fetching the required details it notifies the view. - */ - public void loadBeneficiaryTemplate() { - checkViewAttached(); - getMvpView().setVisibility(View.GONE); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getBeneficiaryTemplate() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - getMvpView().setVisibility(View.VISIBLE); - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context - .getString(R.string.error_fetching_beneficiary_template)); - } - - @Override - public void onNext(BeneficiaryTemplate beneficiaryTemplate) { - getMvpView().hideProgress(); - getMvpView().showBeneficiaryTemplate(beneficiaryTemplate); - } - })); - } - - /** - * Used to create a Beneficiary and notifies the view after successful creation of Beneficiary. - * And in case of any error during creation, it notifies the view. - * - * @param payload {@link BeneficiaryPayload} used for creating a Beneficiary. - */ - public void createBeneficiary(BeneficiaryPayload payload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.createBeneficiary(payload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context - .getString(R.string.error_creating_beneficiary)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showBeneficiaryCreatedSuccessfully(); - } - })); - } - - /** - * Update a Beneficiary with provided {@code beneficiaryId} and notifies the view after - * successful updation of Beneficiary. And in case of any error during updation, it notifies the - * view. - * - * @param beneficiaryId Id of Beneficiary which you want to update - * @param payload {@link BeneficiaryPayload} used for updation a Beneficiary. - */ - public void updateBeneficiary(long beneficiaryId, BeneficiaryUpdatePayload payload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.updateBeneficiary(beneficiaryId, payload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context - .getString(R.string.error_updating_beneficiary)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showBeneficiaryUpdatedSuccessfully(); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryApplicationPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryApplicationPresenter.kt new file mode 100644 index 0000000000..7f8404bbd3 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryApplicationPresenter.kt @@ -0,0 +1,122 @@ +package org.mifos.mobile.presenters + +import android.content.Context +import android.view.View + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.beneficiary.BeneficiaryPayload +import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload +import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.BeneficiaryApplicationView + +import javax.inject.Inject + +/** + * Created by dilpreet on 16/6/17. + */ +class BeneficiaryApplicationPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Loads BeneficiaryTemplate from the server and notifies the view to display it. And in case of + * any error during fetching the required details it notifies the view. + */ + fun loadBeneficiaryTemplate() { + checkViewAttached() + mvpView?.setVisibility(View.GONE) + mvpView?.showProgress() + dataManager?.beneficiaryTemplate + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() { + mvpView?.setVisibility(View.VISIBLE) + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context + ?.getString(R.string.error_fetching_beneficiary_template)) + } + + override fun onNext(beneficiaryTemplate: BeneficiaryTemplate) { + mvpView?.hideProgress() + mvpView?.showBeneficiaryTemplate(beneficiaryTemplate) + } + })?.let { compositeDisposable.add(it) } + } + + /** + * Used to create a Beneficiary and notifies the view after successful creation of Beneficiary. + * And in case of any error during creation, it notifies the view. + * + * @param payload [BeneficiaryPayload] used for creating a Beneficiary. + */ + fun createBeneficiary(payload: BeneficiaryPayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.createBeneficiary(payload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context + ?.getString(R.string.error_creating_beneficiary)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showBeneficiaryCreatedSuccessfully() + } + })?.let { compositeDisposable.add(it) } + } + + /** + * Update a Beneficiary with provided `beneficiaryId` and notifies the view after + * successful updation of Beneficiary. And in case of any error during updation, it notifies the + * view. + * + * @param beneficiaryId Id of Beneficiary which you want to update + * @param payload [BeneficiaryPayload] used for updation a Beneficiary. + */ + fun updateBeneficiary(beneficiaryId: Long?, payload: BeneficiaryUpdatePayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.updateBeneficiary(beneficiaryId, payload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context + ?.getString(R.string.error_updating_beneficiary)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showBeneficiaryUpdatedSuccessfully() + } + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryDetailPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryDetailPresenter.java deleted file mode 100644 index a969b9913a..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryDetailPresenter.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.BeneficiaryDetailView; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -/** - * Created by dilpreet on 16/6/17. - */ - -public class BeneficiaryDetailPresenter extends BasePresenter { - - private DataManager manager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param manager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public BeneficiaryDetailPresenter(DataManager manager, @ApplicationContext Context context) { - super(context); - this.manager = manager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Used to delete a Beneficiary with given {@code beneficiaryId} and notifies the view after - * successful deletion of a beneficiary. And in case of any error during deletion, it notifies - * the view. - * - * @param beneficiaryId Id of Beneficiary which you want to delete. - */ - public void deleteBeneficiary(long beneficiaryId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(manager.deleteBeneficiary(beneficiaryId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context. - getString(R.string.error_deleting_beneficiary)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showBeneficiaryDeletedSuccessfully(); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryDetailPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryDetailPresenter.kt new file mode 100644 index 0000000000..e0406b8a63 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryDetailPresenter.kt @@ -0,0 +1,59 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.BeneficiaryDetailView + +import javax.inject.Inject + +/** + * Created by dilpreet on 16/6/17. + */ +class BeneficiaryDetailPresenter @Inject constructor(private val manager: DataManager?, @ApplicationContext context: Context?) : + BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Used to delete a Beneficiary with given `beneficiaryId` and notifies the view after + * successful deletion of a beneficiary. And in case of any error during deletion, it notifies + * the view. + * + * @param beneficiaryId Id of Beneficiary which you want to delete. + */ + fun deleteBeneficiary(beneficiaryId: Long?) { + checkViewAttached() + mvpView?.showProgress() + manager?.deleteBeneficiary(beneficiaryId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_deleting_beneficiary)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showBeneficiaryDeletedSuccessfully() + } + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryListPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryListPresenter.java deleted file mode 100644 index 3a617e09a1..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryListPresenter.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.BeneficiariesView; - -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - -/** - * Created by dilpreet on 14/6/17. - */ - -public class BeneficiaryListPresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public BeneficiaryListPresenter(DataManager dataManager, @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Used to load Beneficiaries as a {@link List} of {@link Beneficiary} from server and notifies - * the view to display it. And in case of any error during fetching the required details it - * notifies the view. - */ - public void loadBeneficiaries() { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getBeneficiaryList() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context - .getString(R.string.beneficiaries)); - } - - @Override - public void onNext(List beneficiaries) { - getMvpView().hideProgress(); - getMvpView().showBeneficiaryList(beneficiaries); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryListPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryListPresenter.kt new file mode 100644 index 0000000000..89b2d55c32 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/BeneficiaryListPresenter.kt @@ -0,0 +1,55 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.BeneficiariesView + +import javax.inject.Inject + +/** + * Created by dilpreet on 14/6/17. + */ +class BeneficiaryListPresenter @Inject constructor(private val dataManager: DataManager?, @ApplicationContext context: Context?) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Used to load Beneficiaries as a [List] of [Beneficiary] from server and notifies + * the view to display it. And in case of any error during fetching the required details it + * notifies the view. + */ + fun loadBeneficiaries() { + checkViewAttached() + mvpView?.showProgress() + dataManager?.beneficiaryList + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context + ?.getString(R.string.beneficiaries)) + } + + override fun onNext(beneficiaries: List) { + mvpView?.hideProgress() + mvpView?.showBeneficiaryList(beneficiaries) + } + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/ClientChargePresenter.java b/app/src/main/java/org/mifos/mobile/presenters/ClientChargePresenter.java deleted file mode 100644 index 52d6ab870d..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/ClientChargePresenter.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.ClientChargeView; - -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * @author Vishwajeet - * @since 17/8/16. - */ -public class ClientChargePresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the ClientChargePresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - - @Inject - public ClientChargePresenter(DataManager dataManager, @ActivityContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(ClientChargeView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - public void loadClientCharges(long clientId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getClientCharges(clientId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingClientCharges( - context.getString(R.string.client_charges)); - } - - @Override - public void onNext(Page chargePage) { - getMvpView().hideProgress(); - if (chargePage != null) { - getMvpView().showClientCharges(chargePage.getPageItems()); - } - } - }) - ); - } - - public void loadLoanAccountCharges(long loanId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getLoanCharges(loanId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingClientCharges( - context.getString(R.string.client_charges)); - } - - @Override - public void onNext(List chargeList) { - getMvpView().hideProgress(); - getMvpView().showClientCharges(chargeList); - } - }) - ); - } - - public void loadSavingsAccountCharges(long savingsId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getSavingsCharges(savingsId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingClientCharges( - context.getString(R.string.client_charges)); - } - - @Override - public void onNext(List chargeList) { - getMvpView().hideProgress(); - getMvpView().showClientCharges(chargeList); - } - }) - ); - } - - public void loadClientLocalCharges() { - checkViewAttached(); - compositeDisposable.add(dataManager.getClientLocalCharges() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().showErrorFetchingClientCharges( - context.getString(R.string.client_charges)); - } - - @Override - public void onNext(Page chargePage) { - getMvpView().showClientCharges(chargePage.getPageItems()); - } - }) - ); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/ClientChargePresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/ClientChargePresenter.kt new file mode 100644 index 0000000000..3ea837c5a5 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/ClientChargePresenter.kt @@ -0,0 +1,127 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.Charge +import org.mifos.mobile.models.Page +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.ClientChargeView + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 17/8/16. + */ +class ClientChargePresenter @Inject constructor(private val dataManager: DataManager?, @ActivityContext context: Context?) : + BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun loadClientCharges(clientId: Long) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getClientCharges(clientId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingClientCharges( + context?.getString(R.string.client_charges)) + } + + override fun onNext(chargePage: Page) { + mvpView?.hideProgress() + mvpView?.showClientCharges(chargePage.pageItems) + } + })?.let { + compositeDisposable.add(it + ) + } + } + + fun loadLoanAccountCharges(loanId: Long) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getLoanCharges(loanId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingClientCharges( + context?.getString(R.string.client_charges)) + } + + override fun onNext(chargeList: List) { + mvpView?.hideProgress() + mvpView?.showClientCharges(chargeList) + } + })?.let { + compositeDisposable.add(it + ) + } + } + + fun loadSavingsAccountCharges(savingsId: Long) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getSavingsCharges(savingsId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingClientCharges( + context?.getString(R.string.client_charges)) + } + + override fun onNext(chargeList: List) { + mvpView?.hideProgress() + mvpView?.showClientCharges(chargeList) + } + })?.let { + compositeDisposable.add(it + ) + } + } + + fun loadClientLocalCharges() { + checkViewAttached() + dataManager?.clientLocalCharges + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.showErrorFetchingClientCharges( + context?.getString(R.string.client_charges)) + } + + override fun onNext(chargePage: Page) { + mvpView?.showClientCharges(chargePage.pageItems) + } + })?.let { + compositeDisposable.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/GuarantorDetailPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/GuarantorDetailPresenter.java deleted file mode 100644 index 3c3a9fe090..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/GuarantorDetailPresenter.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.mifos.mobile.presenters; - -/* - * Created by saksham on 25/July/2018 - */ - -import android.content.Context; -import android.util.Log; - -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.GuarantorDetailView; - -import java.io.IOException; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -public class GuarantorDetailPresenter extends BasePresenter { - - public static final String TAG = GuarantorDetailPresenter.class.getSimpleName(); - - CompositeDisposable compositeDisposable; - DataManager dataManager; - - @Override - public void attachView(GuarantorDetailView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - @Inject - public GuarantorDetailPresenter(@ApplicationContext Context context, - DataManager dataManager) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - public void deleteGuarantor(long loanId, long guarantorId) { - getMvpView().showProgress(); - compositeDisposable.add(dataManager.deleteGuarantor(loanId, guarantorId) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - try { - getMvpView().guarantorDeletedSuccessfully(responseBody.string()); - } catch (IOException e) { - Log.d(TAG, e.getMessage()); - } - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(e.getMessage()); - } - - @Override - public void onComplete() { - - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/GuarantorDetailPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/GuarantorDetailPresenter.kt new file mode 100644 index 0000000000..1212c4f82d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/GuarantorDetailPresenter.kt @@ -0,0 +1,63 @@ +package org.mifos.mobile.presenters + +import android.content.Context +import android.util.Log + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.GuarantorDetailView + +import java.io.IOException +import javax.inject.Inject + +/* +* Created by saksham on 25/July/2018 +*/ +class GuarantorDetailPresenter @Inject constructor( + @ApplicationContext context: Context?, + var dataManager: DataManager? +) : BasePresenter(context) { + var compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun deleteGuarantor(loanId: Long?, guarantorId: Long?) { + mvpView?.showProgress() + dataManager?.deleteGuarantor(loanId, guarantorId) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + try { + mvpView?.guarantorDeletedSuccessfully(responseBody.string()) + } catch (e: IOException) { + Log.d(TAG, e.message) + } + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(e.message) + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + + companion object { + val TAG: String? = GuarantorDetailPresenter::class.java.simpleName + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/GuarantorListPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/GuarantorListPresenter.java deleted file mode 100644 index 54d5a7f39a..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/GuarantorListPresenter.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.mifos.mobile.presenters; - -/* - * Created by saksham on 24/July/2018 - */ - -import android.content.Context; - -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.GuarantorListView; - -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - -public class GuarantorListPresenter extends BasePresenter { - - DataManager dataManager; - CompositeDisposable compositeDisposable; - - @Inject - public GuarantorListPresenter(@ApplicationContext Context context, DataManager dataManager) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(GuarantorListView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - public void getGuarantorList(long loanId) { - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getGuarantorList(loanId) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onNext(List payload) { - getMvpView().hideProgress(); - getMvpView().showGuarantorListSuccessfully(payload); - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(e.getMessage()); - - } - - @Override - public void onComplete() { - - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/GuarantorListPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/GuarantorListPresenter.kt new file mode 100644 index 0000000000..dd6e99df34 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/GuarantorListPresenter.kt @@ -0,0 +1,51 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers +import org.mifos.mobile.api.DataManager + +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.GuarantorListView + +import javax.inject.Inject + +/* +* Created by saksham on 24/July/2018 +*/ +class GuarantorListPresenter @Inject constructor(@ApplicationContext context: Context?, var dataManager: DataManager?) : + BasePresenter(context) { + + var compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun getGuarantorList(loanId: Long) { + mvpView?.showProgress() + dataManager?.getGuarantorList(loanId) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onNext(payload: List) { + mvpView?.hideProgress() + mvpView?.showGuarantorListSuccessfully(payload) + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(e.message) + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/HelpPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/HelpPresenter.java deleted file mode 100644 index 9e4cded76d..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/HelpPresenter.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.FAQ; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.HelpView; - -import java.util.ArrayList; - -import javax.inject.Inject; - -/** - * Created by dilpreet on 12/8/17. - */ - -public class HelpPresenter extends BasePresenter { - - @Inject - protected HelpPresenter(@ApplicationContext Context context) { - super(context); - } - - @Override - public void attachView(HelpView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - } - - public void loadFaq() { - - String[] qs = context.getResources().getStringArray(R.array.faq_qs); - String[] ans = context.getResources().getStringArray(R.array.faq_ans); - ArrayList faqArrayList = new ArrayList<>(); - - for (int i = 0; i < qs.length; i++) { - faqArrayList.add(new FAQ(qs[i], ans[i])); - } - - getMvpView().showFaq(faqArrayList); - } - - public ArrayList filterList(ArrayList faqArrayList, String query) { - ArrayList filteredList = new ArrayList<>(); - for (FAQ faq : faqArrayList) { - if (faq.getQuestion().toLowerCase().contains(query.toLowerCase())) { - filteredList.add(faq); - } - } - return filteredList; - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/HelpPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/HelpPresenter.kt new file mode 100644 index 0000000000..7ba4d111e6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/HelpPresenter.kt @@ -0,0 +1,42 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.FAQ +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.HelpView + +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 12/8/17. + */ +class HelpPresenter @Inject constructor(@ApplicationContext context: Context?) : + BasePresenter(context) { + + fun loadFaq() { + val qs = context?.resources?.getStringArray(R.array.faq_qs) + val ans = context?.resources?.getStringArray(R.array.faq_ans) + val faqArrayList = ArrayList() + if (qs != null) + for (i in qs.indices) { + faqArrayList.add(FAQ(qs[i], ans?.get(i))) + } + mvpView?.showFaq(faqArrayList) + } + + fun filterList(faqArrayList: ArrayList?, query: String): ArrayList? { + val filteredList = ArrayList() + if (faqArrayList != null) { + for (faq in faqArrayList) { + if (faq?.question?.toLowerCase(Locale.ROOT)?.contains(query.toLowerCase(Locale.ROOT)) == true) { + filteredList.add(faq) + } + } + } + return filteredList + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/HomeOldPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/HomeOldPresenter.java deleted file mode 100644 index 77ca7f9077..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/HomeOldPresenter.java +++ /dev/null @@ -1,243 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; -import android.graphics.Bitmap; -import android.util.Base64; -import android.util.Log; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.client.ClientAccounts; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.HomeOldView; -import org.mifos.mobile.utils.ImageUtil; - -import java.io.IOException; -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - - -/** - * Created by dilpreet on 19/6/17. - */ - -public class HomeOldPresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposable; - private PreferencesHelper preferencesHelper; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public HomeOldPresenter(DataManager dataManager, @ActivityContext Context context, - PreferencesHelper preferencesHelper) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - this.preferencesHelper = preferencesHelper; - } - - @Override - public void attachView(HomeOldView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Fetches Client account details as {@link ClientAccounts} from the server and notifies the - * view to display the {@link List} of {@link LoanAccount} and {@link SavingAccount}. And in - * case of any error during fetching the required details it notifies the view. - */ - public void loadClientAccountDetails() { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getClientAccounts() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.error_fetching_accounts)); - } - - @Override - public void onNext(ClientAccounts clientAccounts) { - getMvpView().hideProgress(); - getMvpView().showLoanAccountDetails(getLoanAccountDetails(clientAccounts - .getLoanAccounts())); - getMvpView().showSavingAccountDetails(getSavingAccountDetails(clientAccounts - .getSavingsAccounts())); - } - }) - ); - } - - /** - * Fetches Details about Client from the server as {@link Client} and notifies the view to - * display the details. And in case of any error during fetching the required details it - * notifies the view. - */ - public void getUserDetails() { - checkViewAttached(); - compositeDisposable.add(dataManager.getCurrentClient() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().showError(context.getString(R.string.error_fetching_client)); - getMvpView().hideProgress(); - } - - @Override - public void onNext(Client client) { - if (client != null) { - preferencesHelper.setOfficeName(client.getOfficeName()); - getMvpView().showUserDetails(client); - } else { - getMvpView().showError(context - .getString(R.string.error_client_not_found)); - } - } - }) - ); - } - - /** - * Fetches Client image from the server in {@link Base64} format which is then decoded into a - * {@link Bitmap} after which the view notified to display it. - */ - public void getUserImage() { - checkViewAttached(); - setUserProfile(preferencesHelper.getUserProfileImage()); - - compositeDisposable.add(dataManager.getClientImage() - .observeOn(Schedulers.newThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().showUserImage(null); - } - - @Override - public void onNext(ResponseBody response) { - try { - - final String encodedString = response.string(); - - final String pureBase64Encoded = - encodedString.substring(encodedString.indexOf(',') + 1); - preferencesHelper.setUserProfileImage(pureBase64Encoded); - setUserProfile(pureBase64Encoded); - } catch (IOException e) { - Log.d("userimage", e.toString()); - } - } - }) - ); - } - - public void setUserProfile(String image) { - if (image == null) { - return; - } - final byte[] decodedBytes = Base64.decode(image, Base64.DEFAULT); - Bitmap decodedBitmap = ImageUtil.getInstance().compressImage(decodedBytes); - getMvpView().showUserImage(decodedBitmap); - } - - public void getUnreadNotificationsCount() { - compositeDisposable.add(dataManager.getUnreadNotificationsCount() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.computation()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().showNotificationCount(0); - } - - @Override - public void onNext(Integer integer) { - getMvpView().showNotificationCount(integer); - } - })); - } - - /** - * Returns total Loan balance - * - * @param loanAccountList {@link List} of {@link LoanAccount} associated with the client - * @return Returns {@code totalAmount} which is calculated by adding all {@link LoanAccount} - * balance. - */ - private double getLoanAccountDetails(List loanAccountList) { - double totalAmount = 0; - for (LoanAccount loanAccount : loanAccountList) { - totalAmount += loanAccount.getLoanBalance(); - } - return totalAmount; - } - - /** - * Returns total Savings balance - * - * @param savingAccountList {@link List} of {@link SavingAccount} associated with the client - * @return Returns {@code totalAmount} which is calculated by adding all {@link SavingAccount} - * balance. - */ - private double getSavingAccountDetails(List savingAccountList) { - double totalAmount = 0; - for (SavingAccount savingAccount : savingAccountList) { - totalAmount += savingAccount.getAccountBalance(); - } - return totalAmount; - } - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/HomeOldPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/HomeOldPresenter.kt new file mode 100644 index 0000000000..80eb785104 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/HomeOldPresenter.kt @@ -0,0 +1,193 @@ +package org.mifos.mobile.presenters + +import android.content.Context +import android.graphics.Bitmap +import android.util.Base64 +import android.util.Log + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.HomeOldView +import org.mifos.mobile.utils.ImageUtil.Companion.instance + +import java.io.IOException +import javax.inject.Inject + +/** + * Created by dilpreet on 19/6/17. + */ +class HomeOldPresenter @Inject constructor( + private val dataManager: DataManager?, @ActivityContext context: Context?, + private val preferencesHelper: PreferencesHelper? +) : BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Fetches Client account details as [ClientAccounts] from the server and notifies the + * view to display the [List] of [LoanAccount] and [SavingAccount]. And in + * case of any error during fetching the required details it notifies the view. + */ + fun loadClientAccountDetails() { + checkViewAttached() + mvpView?.showProgress() + dataManager?.clientAccounts + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + override fun onNext(clientAccounts: ClientAccounts) { + mvpView?.hideProgress() + mvpView?.showLoanAccountDetails(getLoanAccountDetails(clientAccounts + .loanAccounts)) + mvpView?.showSavingAccountDetails(getSavingAccountDetails(clientAccounts + .savingsAccounts)) + } + })?.let { + compositeDisposable.add(it + ) + } + } + + /** + * Fetches Details about Client from the server as [Client] and notifies the view to + * display the details. And in case of any error during fetching the required details it + * notifies the view. + */ + val userDetails: Unit + get() { + checkViewAttached() + dataManager?.currentClient + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.showError(context?.getString(R.string.error_fetching_client)) + mvpView?.hideProgress() + } + + override fun onNext(client: Client) { + preferencesHelper?.officeName = client.officeName + mvpView?.showUserDetails(client) + } + })?.let { + compositeDisposable.add(it + ) + } + } + + /** + * Fetches Client image from the server in [Base64] format which is then decoded into a + * [Bitmap] after which the view notified to display it. + */ + val userImage: Unit + get() { + checkViewAttached() + setUserProfile(preferencesHelper?.userProfileImage) + dataManager?.clientImage + ?.observeOn(Schedulers.newThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.showUserImage(null) + } + + override fun onNext(response: ResponseBody) { + try { + val encodedString = response.string() + val pureBase64Encoded = encodedString.substring(encodedString.indexOf(',') + 1) + preferencesHelper?.userProfileImage = pureBase64Encoded + setUserProfile(pureBase64Encoded) + } catch (e: IOException) { + Log.d("userimage", e.toString()) + } + } + })?.let { + compositeDisposable.add(it + ) + } + } + + fun setUserProfile(image: String?) { + if (image == null) { + return + } + val decodedBytes = Base64.decode(image, Base64.DEFAULT) + val decodedBitmap = instance?.compressImage(decodedBytes) + mvpView?.showUserImage(decodedBitmap) + } + + val unreadNotificationsCount: Unit + get() { + dataManager?.unreadNotificationsCount + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.computation()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.showNotificationCount(0) + } + + override fun onNext(integer: Int) { + mvpView?.showNotificationCount(integer) + } + })?.let { compositeDisposable.add(it) } + } + + /** + * Returns total Loan balance + * + * @param loanAccountList [List] of [LoanAccount] associated with the client + * @return Returns `totalAmount` which is calculated by adding all [LoanAccount] + * balance. + */ + private fun getLoanAccountDetails(loanAccountList: List): Double { + var totalAmount = 0.0 + for ((_, _, _, _, _, _, _, _, _, _, _, _, _, _, loanBalance) in loanAccountList) { + totalAmount += loanBalance + } + return totalAmount + } + + /** + * Returns total Savings balance + * + * @param savingAccountList [List] of [SavingAccount] associated with the client + * @return Returns `totalAmount` which is calculated by adding all [SavingAccount] + * balance. + */ + private fun getSavingAccountDetails(savingAccountList: List?): Double { + var totalAmount = 0.0 + for ((_, _, _, _, _, accountBalance) in savingAccountList!!) { + totalAmount += accountBalance + } + return totalAmount + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/HomePresenter.java b/app/src/main/java/org/mifos/mobile/presenters/HomePresenter.java deleted file mode 100644 index a9f8e67186..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/HomePresenter.java +++ /dev/null @@ -1,167 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; -import android.graphics.Bitmap; -import android.util.Base64; -import android.util.Log; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.HomeView; -import org.mifos.mobile.utils.ImageUtil; - -import java.io.IOException; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -/** - * Created by dilpreet on 19/6/17. - */ - -public class HomePresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposable; - @Inject - PreferencesHelper preferencesHelper; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public HomePresenter(DataManager dataManager, @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(HomeView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Fetches Details about Client from the server as {@link Client} and notifies the view to - * display the details. And in case of any error during fetching the required details it - * notifies the view. - */ - public void getUserDetails() { - checkViewAttached(); - compositeDisposable.add(dataManager.getCurrentClient() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().showError(context.getString(R.string.error_fetching_client)); - getMvpView().hideProgress(); - } - - @Override - public void onNext(Client client) { - getMvpView().hideProgress(); - if (client != null) { - preferencesHelper.setOfficeName(client.getOfficeName()); - preferencesHelper.setClientName(client.getDisplayName()); - getMvpView().showUserDetails(preferencesHelper.getClientName()); - } else { - getMvpView().showError(context - .getString(R.string.error_client_not_found)); - } - } - }) - ); - } - - /** - * Fetches Client image from the server in {@link Base64} format which is then decoded into a - * {@link Bitmap} after which the view notified to display it. - */ - public void getUserImage() { - checkViewAttached(); - compositeDisposable.add(dataManager.getClientImage() - .observeOn(Schedulers.newThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().showUserImageNotFound(); - } - - @Override - public void onNext(ResponseBody response) { - try { - - final String encodedString = response.string(); - - final String pureBase64Encoded = - encodedString.substring(encodedString.indexOf(',') + 1); - - final byte[] decodedBytes = - Base64.decode(pureBase64Encoded, Base64.DEFAULT); - - Bitmap decodedBitmap = ImageUtil.getInstance(). - compressImage(decodedBytes, 256, 256); - getMvpView().showUserImage(decodedBitmap); - } catch (IOException e) { - Log.d("userimage", e.toString()); - } - } - }) - ); - } - - public void getUnreadNotificationsCount() { - compositeDisposable.add(dataManager.getUnreadNotificationsCount() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.computation()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - - } - - @Override - public void onNext(Integer integer) { - getMvpView().showNotificationCount(integer); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/HomePresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/HomePresenter.kt new file mode 100644 index 0000000000..1bde3ad801 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/HomePresenter.kt @@ -0,0 +1,118 @@ +package org.mifos.mobile.presenters + +import android.content.Context +import android.graphics.Bitmap +import android.util.Base64 +import android.util.Log + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.HomeView +import org.mifos.mobile.utils.ImageUtil + +import java.io.IOException +import javax.inject.Inject + +/** + * Created by dilpreet on 19/6/17. + */ +class HomePresenter @Inject constructor(private val dataManager: DataManager?, @ApplicationContext context: Context?) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable? = CompositeDisposable() + + @JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + + override fun detachView() { + super.detachView() + compositeDisposable?.clear() + } + + /** + * Fetches Details about Client from the server as [Client] and notifies the view to + * display the details. And in case of any error during fetching the required details it + * notifies the view. + */ + val userDetails: Unit + get() { + checkViewAttached() + dataManager?.currentClient + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.showError(context?.getString(R.string.error_fetching_client)) + mvpView?.hideProgress() + } + + override fun onNext(client: Client) { + mvpView?.hideProgress() + preferencesHelper?.officeName = client.officeName + preferencesHelper?.clientName = client.displayName + mvpView?.showUserDetails(preferencesHelper?.clientName) + } + })?.let { + compositeDisposable?.add(it + ) + } + } + + /** + * Fetches Client image from the server in [Base64] format which is then decoded into a + * [Bitmap] after which the view notified to display it. + */ + val userImage: Unit + get() { + checkViewAttached() + dataManager?.clientImage + ?.observeOn(Schedulers.newThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.showUserImageNotFound() + } + + override fun onNext(response: ResponseBody) { + try { + val encodedString = response.string() + val pureBase64Encoded = encodedString.substring(encodedString.indexOf(',') + 1) + val decodedBytes = Base64.decode(pureBase64Encoded, Base64.DEFAULT) + val decodedBitmap = ImageUtil.instance?.compressImage(decodedBytes, 256f, 256f) + mvpView?.showUserImage(decodedBitmap) + } catch (e: IOException) { + Log.d("userimage", e.toString()) + } + } + })?.let { + compositeDisposable?.add(it + ) + } + } + val unreadNotificationsCount: Unit + get() { + dataManager?.unreadNotificationsCount + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.computation()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) {} + override fun onNext(integer: Int) { + mvpView?.showNotificationCount(integer) + } + })?.let { compositeDisposable?.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountWithdrawPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountWithdrawPresenter.java deleted file mode 100644 index 0ddb9a3a87..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountWithdrawPresenter.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.loan.LoanWithdraw; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.LoanAccountWithdrawView; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -/** - * Created by dilpreet on 7/6/17. - */ - -public class LoanAccountWithdrawPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoanAccountDetailsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public LoanAccountWithdrawPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(LoanAccountWithdrawView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Used for withdrawing a LoanAccount using the given {@code loanId} and notifies the view after - * successful withdrawing of a LoanAccount. And in case of any error during withdrawing, it - * notifies the view. - * - * @param loanId Id of LoanAccount which you want to delete - * @param loanWithdraw {@link LoanWithdraw} for the Withdrawing LoanAccount - */ - public void withdrawLoanAccount(long loanId, LoanWithdraw loanWithdraw) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.withdrawLoanAccount(loanId, loanWithdraw) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showLoanAccountWithdrawError( - context.getString(R.string.error_loan_account_withdraw)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showLoanAccountWithdrawSuccess(); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountWithdrawPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountWithdrawPresenter.kt new file mode 100644 index 0000000000..a57e96bfd6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountWithdrawPresenter.kt @@ -0,0 +1,65 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.loan.LoanWithdraw +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.LoanAccountWithdrawView + +import javax.inject.Inject + +/** + * Created by dilpreet on 7/6/17. + */ +class LoanAccountWithdrawPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Used for withdrawing a LoanAccount using the given `loanId` and notifies the view after + * successful withdrawing of a LoanAccount. And in case of any error during withdrawing, it + * notifies the view. + * + * @param loanId Id of LoanAccount which you want to delete + * @param loanWithdraw [LoanWithdraw] for the Withdrawing LoanAccount + */ + fun withdrawLoanAccount(loanId: Long?, loanWithdraw: LoanWithdraw?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.withdrawLoanAccount(loanId, loanWithdraw) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showLoanAccountWithdrawError( + context?.getString(R.string.error_loan_account_withdraw)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showLoanAccountWithdrawSuccess() + } + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsDetailPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsDetailPresenter.java deleted file mode 100644 index 8c32b04dd9..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsDetailPresenter.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.LoanAccountsDetailView; -import org.mifos.mobile.utils.Constants; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * @author Vishwajeet - * @since 19/08/16 - */ - -public class LoanAccountsDetailPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoanAccountDetailsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public LoanAccountsDetailPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(LoanAccountsDetailView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Load details of a particular loan account from the server and notify the view - * to display it. Notify the view, in case there is any error in fetching - * the details from server. - * - * @param loanId Id of Loan Account - */ - public void loadLoanAccountDetails(long loanId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, - loanId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingLoanAccountsDetail( - context.getString(R.string.loan_account_details)); - } - - @Override - public void onNext(LoanWithAssociations loanWithAssociations) { - getMvpView().hideProgress(); - if (loanWithAssociations != null) { - getMvpView().showLoanAccountsDetail(loanWithAssociations); - } - } - }) - ); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsDetailPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsDetailPresenter.kt new file mode 100644 index 0000000000..04ac24e081 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsDetailPresenter.kt @@ -0,0 +1,68 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.LoanAccountsDetailView +import org.mifos.mobile.utils.Constants + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 19/08/16 + */ +class LoanAccountsDetailPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Load details of a particular loan account from the server and notify the view + * to display it. Notify the view, in case there is any error in fetching + * the details from server. + * + * @param loanId Id of Loan Account + */ + fun loadLoanAccountDetails(loanId: Long?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, + loanId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingLoanAccountsDetail( + context?.getString(R.string.loan_account_details)) + } + + override fun onNext(loanWithAssociations: LoanWithAssociations) { + mvpView?.hideProgress() + mvpView?.showLoanAccountsDetail(loanWithAssociations) + } + })?.let { + compositeDisposable.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsTransactionPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsTransactionPresenter.java deleted file mode 100644 index d400a085c9..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsTransactionPresenter.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.mifos.mobile.presenters; -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.LoanAccountsTransactionView; -import org.mifos.mobile.utils.Constants; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * Created by dilpreet on 4/3/17. - */ - -public class LoanAccountsTransactionPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public LoanAccountsTransactionPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(LoanAccountsTransactionView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Load details of a particular loan account from the server and notify the view - * to display it. Notify the view, in case there is any error in fetching - * the details from server. - * - * @param loanId Id of Loan Account - */ - public void loadLoanAccountDetails(long loanId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getLoanWithAssociations(Constants.TRANSACTIONS, loanId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingLoanAccountsDetail( - context.getString(R.string.loan_transaction_details)); - } - - @Override - public void onNext(LoanWithAssociations loanWithAssociations) { - getMvpView().hideProgress(); - if (loanWithAssociations.getTransactions() != null && - !loanWithAssociations.getTransactions().isEmpty()) { - getMvpView().showLoanTransactions(loanWithAssociations); - } else { - getMvpView().showEmptyTransactions(loanWithAssociations); - } - } - }) - ); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsTransactionPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsTransactionPresenter.kt new file mode 100644 index 0000000000..610a37dbaf --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/LoanAccountsTransactionPresenter.kt @@ -0,0 +1,73 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.LoanAccountsTransactionView +import org.mifos.mobile.utils.Constants + +import javax.inject.Inject + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ /** + * Created by dilpreet on 4/3/17. + */ +class LoanAccountsTransactionPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Load details of a particular loan account from the server and notify the view + * to display it. Notify the view, in case there is any error in fetching + * the details from server. + * + * @param loanId Id of Loan Account + */ + fun loadLoanAccountDetails(loanId: Long?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getLoanWithAssociations(Constants.TRANSACTIONS, loanId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingLoanAccountsDetail( + context?.getString(R.string.loan_transaction_details)) + } + + override fun onNext(loanWithAssociations: LoanWithAssociations) { + mvpView?.hideProgress() + if (loanWithAssociations.transactions != null && + loanWithAssociations.transactions?.isNotEmpty() == true) { + mvpView?.showLoanTransactions(loanWithAssociations) + } else { + mvpView?.showEmptyTransactions(loanWithAssociations) + } + } + })?.let { + compositeDisposable.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanApplicationPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/LoanApplicationPresenter.java deleted file mode 100644 index 8848aa9f0a..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/LoanApplicationPresenter.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.templates.loans.LoanTemplate; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.enums.LoanState; -import org.mifos.mobile.ui.views.LoanApplicationMvpView; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * Created by Rajan Maurya on 06/03/17. - */ -public class LoanApplicationPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoanAccountDetailsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public LoanApplicationPresenter(DataManager dataManager, @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(LoanApplicationMvpView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Loads LoanApplicationTemplate from the server as {@link LoanTemplate} and notifies the view - * depending upon the {@code loanState}. And in case of any error during fetching the required - * details it notifies the view. - * - * @param loanState State of Loan i.e. {@code LoanState.CREATE} or {@code LoanState.UPDATE} - */ - public void loadLoanApplicationTemplate(final LoanState loanState) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getLoanTemplate() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.error_fetching_template)); - } - - @Override - public void onNext(LoanTemplate loanTemplate) { - getMvpView().hideProgress(); - if (loanState == LoanState.CREATE) { - getMvpView().showLoanTemplate(loanTemplate); - } else { - getMvpView().showUpdateLoanTemplate(loanTemplate); - } - } - }) - ); - } - - /** - * Loads LoanApplicationTemplate from the server as {@link LoanTemplate} and notifies the view - * depending upon the {@code productId} and {@code loanState}. And in case of any error during - * fetching the required details it notifies the view. - * - * @param productId ProductId required for Fetching loan template according to it. - * @param loanState State of Loan i.e. {@code LoanState.CREATE} or {@code LoanState.UPDATE} - */ - public void loadLoanApplicationTemplateByProduct(int productId, final LoanState loanState) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getLoanTemplateByProduct(productId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.error_fetching_template)); - } - - @Override - public void onNext(LoanTemplate loanTemplate) { - getMvpView().hideProgress(); - if (loanState == LoanState.CREATE) { - getMvpView().showLoanTemplateByProduct(loanTemplate); - } else { - getMvpView().showUpdateLoanTemplateByProduct(loanTemplate); - } - } - }) - ); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanApplicationPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/LoanApplicationPresenter.kt new file mode 100644 index 0000000000..c97e4c7dfd --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/LoanApplicationPresenter.kt @@ -0,0 +1,102 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.templates.loans.LoanTemplate +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.enums.LoanState +import org.mifos.mobile.ui.views.LoanApplicationMvpView + +import javax.inject.Inject + +/** + * Created by Rajan Maurya on 06/03/17. + */ +class LoanApplicationPresenter @Inject constructor(private val dataManager: DataManager?, @ApplicationContext context: Context?) : + BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Loads LoanApplicationTemplate from the server as [LoanTemplate] and notifies the view + * depending upon the `loanState`. And in case of any error during fetching the required + * details it notifies the view. + * + * @param loanState State of Loan i.e. `LoanState.CREATE` or `LoanState.UPDATE` + */ + fun loadLoanApplicationTemplate(loanState: LoanState) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.loanTemplate + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_fetching_template)) + } + + override fun onNext(loanTemplate: LoanTemplate) { + mvpView?.hideProgress() + if (loanState === LoanState.CREATE) { + mvpView?.showLoanTemplate(loanTemplate) + } else { + mvpView?.showUpdateLoanTemplate(loanTemplate) + } + } + })?.let { + compositeDisposable.add(it + ) + } + } + + /** + * Loads LoanApplicationTemplate from the server as [LoanTemplate] and notifies the view + * depending upon the `productId` and `loanState`. And in case of any error during + * fetching the required details it notifies the view. + * + * @param productId ProductId required for Fetching loan template according to it. + * @param loanState State of Loan i.e. `LoanState.CREATE` or `LoanState.UPDATE` + */ + fun loadLoanApplicationTemplateByProduct(productId: Int?, loanState: LoanState?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getLoanTemplateByProduct(productId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_fetching_template)) + } + + override fun onNext(loanTemplate: LoanTemplate) { + mvpView?.hideProgress() + if (loanState === LoanState.CREATE) { + mvpView?.showLoanTemplateByProduct(loanTemplate) + } else { + mvpView?.showUpdateLoanTemplateByProduct(loanTemplate) + } + } + })?.let { + compositeDisposable.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanRepaymentSchedulePresenter.java b/app/src/main/java/org/mifos/mobile/presenters/LoanRepaymentSchedulePresenter.java deleted file mode 100644 index 94c19c4220..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/LoanRepaymentSchedulePresenter.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.LoanRepaymentScheduleMvpView; -import org.mifos.mobile.utils.Constants; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * Created by Rajan Maurya on 03/03/17. - */ -public class LoanRepaymentSchedulePresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the AccountsPresenter by automatically injecting an instance of - * {@link Context} and {@link DataManager} . - * - * @param context Context of the view attached to the presenter. - * @param dataManager DataManager class that provides access to the data - * via the API. - */ - @Inject - public LoanRepaymentSchedulePresenter(@ApplicationContext Context context, - DataManager dataManager) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(LoanRepaymentScheduleMvpView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Load details of a particular loan account with its Repayment Schedule as - * {@link LoanWithAssociations} from the server and notify the view to display it. Notify the - * view, in case there is any error in fetching the details from server. - * @param loanId Id of Loan Account - */ - public void loanLoanWithAssociations(long loanId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, - loanId) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context - .getString(R.string.repayment_schedule)); - } - - @Override - public void onNext(LoanWithAssociations loanWithAssociations) { - getMvpView().hideProgress(); - if (!loanWithAssociations.getRepaymentSchedule().getPeriods().isEmpty()) { - getMvpView().showLoanRepaymentSchedule(loanWithAssociations); - } else { - getMvpView().showEmptyRepaymentsSchedule(loanWithAssociations); - } - } - }) - ); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoanRepaymentSchedulePresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/LoanRepaymentSchedulePresenter.kt new file mode 100644 index 0000000000..3518f00660 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/LoanRepaymentSchedulePresenter.kt @@ -0,0 +1,69 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.LoanRepaymentScheduleMvpView +import org.mifos.mobile.utils.Constants + +import javax.inject.Inject + +/** + * Created by Rajan Maurya on 03/03/17. + */ +class LoanRepaymentSchedulePresenter @Inject constructor( + @ApplicationContext context: Context?, + private val dataManager: DataManager? +) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Load details of a particular loan account with its Repayment Schedule as + * [LoanWithAssociations] from the server and notify the view to display it. Notify the + * view, in case there is any error in fetching the details from server. + * @param loanId Id of Loan Account + */ + fun loanLoanWithAssociations(loanId: Long?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, + loanId) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context + ?.getString(R.string.repayment_schedule)) + } + + override fun onNext(loanWithAssociations: LoanWithAssociations) { + mvpView?.hideProgress() + if (loanWithAssociations.repaymentSchedule?.periods?.isNotEmpty() == true) { + mvpView?.showLoanRepaymentSchedule(loanWithAssociations) + } else { + mvpView?.showEmptyRepaymentsSchedule(loanWithAssociations) + } + } + })?.let { + compositeDisposable.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoginPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/LoginPresenter.java deleted file mode 100644 index 89e5a4744c..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/LoginPresenter.java +++ /dev/null @@ -1,235 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; -import android.content.res.Resources; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.BaseApiManager; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.User; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.LoginView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.MFErrorParser; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; -import retrofit2.HttpException; - -/** - * @author Vishwajeet - * @since 05/06/16 - */ -public class LoginPresenter extends BasePresenter { - - private final DataManager dataManager; - private PreferencesHelper preferencesHelper; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public LoginPresenter(DataManager dataManager, @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - preferencesHelper = this.dataManager.getPreferencesHelper(); - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(LoginView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * This method validates the username and password entered by the user - * and reports any errors that might exists in any of the inputs. - * If there are no errors, then we attempt to authenticate the user from - * the server and then persist the authentication data if we successfully - * authenticate the credentials or notify the view about any errors. - * - * @param username Username of the user trying to login. - * @param password Password of the user trying to login. - */ - public void login(final String username, final String password) { - checkViewAttached(); - if (isCredentialsValid(username, password)) { - getMvpView().showProgress(); - compositeDisposable.add(dataManager.login(username, password) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - String errorMessage; - try { - if (e instanceof HttpException) { - if (((HttpException) e).code() == 503) { - getMvpView(). - showMessage(context. - getString(R.string.error_server_down)); - } else { - errorMessage = - ((HttpException) e).response().errorBody().string(); - getMvpView() - .showMessage(MFErrorParser.parseError(errorMessage) - .getDeveloperMessage()); - } - } - } catch (Throwable throwable) { - RxJavaPlugins.getErrorHandler(); - } - } - - @Override - public void onNext(User user) { - if (user != null) { - final String userName = user.getUsername(); - final long userID = user.getUserId(); - final String authToken = Constants.BASIC + - user.getBase64EncodedAuthenticationKey(); - saveAuthenticationTokenForSession(userName, userID, authToken); - getMvpView().onLoginSuccess(userName); - } else { - getMvpView().hideProgress(); - } - } - }) - ); - } - } - - /** - * This method fetching the Client, associated with current Access Token. - */ - public void loadClient() { - checkViewAttached(); - compositeDisposable.add(dataManager.getClients() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - if (((HttpException) e).code() == 401) { - getMvpView().showMessage(context.getString(R.string. - unauthorized_client)); - } else { - getMvpView().showMessage(context.getString(R.string. - error_fetching_client)); - } - preferencesHelper.clear(); - reInitializeService(); - } - - @Override - public void onNext(Page clientPage) { - getMvpView().hideProgress(); - if (clientPage.getPageItems().size() != 0) { - long clientId = clientPage.getPageItems().get(0).getId(); - preferencesHelper.setClientId(clientId); - dataManager.setClientId(clientId); - reInitializeService(); - getMvpView().showPassCodeActivity(); - } else { - getMvpView().showMessage(context - .getString(R.string.error_client_not_found)); - } - } - }) - ); - } - - - private boolean isCredentialsValid(final String username, final String password) { - boolean credentialValid = true; - final Resources resources = context.getResources(); - final String correctUsername = username.replaceFirst("\\s++$", "").trim(); - if (username == null || username.matches("\\s*") || username.isEmpty()) { - getMvpView().showUsernameError(context.getString(R.string.error_validation_blank, - context.getString(R.string.username))); - credentialValid = false; - } else if (username.length() < 5) { - getMvpView().showUsernameError(context.getString(R.string.error_validation_minimum_chars - , resources.getString(R.string.username), resources.getInteger(R.integer. - username_minimum_length))); - credentialValid = false; - } else if (correctUsername.contains(" ")) { - getMvpView().showUsernameError(context.getString( - R.string.error_validation_cannot_contain_spaces, - resources.getString(R.string.username), - context.getString(R.string.not_contain_username))); - credentialValid = false; - } else { - getMvpView().clearUsernameError(); - } - - if (password == null || password.isEmpty()) { - getMvpView().showPasswordError(context.getString(R.string.error_validation_blank, - context.getString(R.string.password))); - credentialValid = false; - } else if (password.length() < 6) { - getMvpView().showPasswordError(context.getString(R.string.error_validation_minimum_chars - , resources.getString(R.string.password), resources.getInteger(R.integer. - password_minimum_length))); - credentialValid = false; - } else { - getMvpView().clearPasswordError(); - } - - return credentialValid; - } - - /** - * Save the authentication token from the server and the user ID. - * The authentication token would be used for accessing the authenticated - * APIs. - * - * @param userID - The userID of the user to be saved. - * @param authToken - The authentication token to be saved. - */ - private void saveAuthenticationTokenForSession(String userName, long userID, String authToken) { - preferencesHelper.setUserName(userName); - preferencesHelper.setUserId(userID); - preferencesHelper.saveToken(authToken); - reInitializeService(); - } - - private void reInitializeService() { - BaseApiManager.createService(preferencesHelper.getBaseUrl(), preferencesHelper.getTenant(), - preferencesHelper.getToken()); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/LoginPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/LoginPresenter.kt new file mode 100644 index 0000000000..b69c62a310 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/LoginPresenter.kt @@ -0,0 +1,200 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.plugins.RxJavaPlugins +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.BaseApiManager +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.Page +import org.mifos.mobile.models.User +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.payload.LoginPayload +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.LoginView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.MFErrorParser + +import retrofit2.HttpException + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 05/06/16 + */ +class LoginPresenter @Inject constructor(private val dataManager: DataManager?, @ApplicationContext context: Context?) : + BasePresenter(context) { + + private val preferencesHelper: PreferencesHelper? = dataManager?.preferencesHelper + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * This method validates the username and password entered by the user + * and reports any errors that might exists in any of the inputs. + * If there are no errors, then we attempt to authenticate the user from + * the server and then persist the authentication data if we successfully + * authenticate the credentials or notify the view about any errors. + */ + fun login(loginPayload: LoginPayload?) { + checkViewAttached() + if (isCredentialsValid(loginPayload)) { + mvpView?.showProgress() + compositeDisposable.add(dataManager?.login(loginPayload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io())!! + .subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + val errorMessage: String + try { + if (e is HttpException) { + if (e.code() == 503) { + mvpView?.showMessage(context?.getString(R.string.error_server_down)) + } else { + errorMessage = e.response().errorBody().string() + mvpView + ?.showMessage(MFErrorParser.parseError(errorMessage) + .developerMessage) + } + } + } catch (throwable: Throwable) { + RxJavaPlugins.getErrorHandler() + } + } + + override fun onNext(user: User) { + val userName = user.username + val userID = user.userId + val authToken = Constants.BASIC + + user.base64EncodedAuthenticationKey + saveAuthenticationTokenForSession(userName, userID, authToken) + mvpView?.onLoginSuccess(userName) + } + }) + ) + } + } + + /** + * This method fetching the Client, associated with current Access Token. + */ + fun loadClient() { + checkViewAttached() + dataManager?.clients + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + if ((e as HttpException).code() == 401) { + mvpView?.showMessage(context?.getString(R.string.unauthorized_client)) + } else { + mvpView?.showMessage(context?.getString(R.string.error_fetching_client)) + } + preferencesHelper?.clear() + reInitializeService() + } + + override fun onNext(clientPage: Page) { + mvpView?.hideProgress() + if (clientPage.pageItems.isNotEmpty()) { + val clientId = clientPage.pageItems[0]?.id?.toLong() + preferencesHelper?.clientId = clientId + dataManager.clientId = clientId + reInitializeService() + mvpView?.showPassCodeActivity() + } else { + mvpView?.showMessage(context + ?.getString(R.string.error_client_not_found)) + } + } + })?.let { + compositeDisposable.add(it + ) + } + } + + private fun isCredentialsValid(loginPayload: LoginPayload?): Boolean { + val username: String = loginPayload?.username.toString() + val password: String = loginPayload?.password.toString() + var credentialValid = true + val resources = context?.resources + val correctUsername = username.replaceFirst("\\s++$".toRegex(), "").trim { it <= ' ' } + when { + username.isEmpty() -> { + mvpView?.showUsernameError(context?.getString(R.string.error_validation_blank, + context?.getString(R.string.username))) + credentialValid = false + } + username.length < 5 -> { + mvpView?.showUsernameError(context?.getString(R.string.error_validation_minimum_chars, + resources?.getString(R.string.username), + resources?.getInteger(R.integer.username_minimum_length))) + credentialValid = false + } + correctUsername.contains(" ") -> { + mvpView?.showUsernameError(context?.getString( + R.string.error_validation_cannot_contain_spaces, + resources?.getString(R.string.username), + context?.getString(R.string.not_contain_username))) + credentialValid = false + } + else -> { + mvpView?.clearUsernameError() + } + } + when { + password.isEmpty() -> { + mvpView?.showPasswordError(context?.getString(R.string.error_validation_blank, + context?.getString(R.string.password))) + credentialValid = false + } + password.length < 6 -> { + mvpView?.showPasswordError(context?.getString(R.string.error_validation_minimum_chars, + resources?.getString(R.string.password), + resources?.getInteger(R.integer.password_minimum_length))) + credentialValid = false + } + else -> { + mvpView?.clearPasswordError() + } + } + return credentialValid + } + + /** + * Save the authentication token from the server and the user ID. + * The authentication token would be used for accessing the authenticated + * APIs. + * + * @param userID - The userID of the user to be saved. + * @param authToken - The authentication token to be saved. + */ + private fun saveAuthenticationTokenForSession(userName: String?, userID: Long, authToken: String) { + preferencesHelper?.userName = userName + preferencesHelper?.userId = userID + preferencesHelper?.saveToken(authToken) + reInitializeService() + } + + private fun reInitializeService() { + BaseApiManager.createService(preferencesHelper?.baseUrl, preferencesHelper?.tenant, + preferencesHelper?.token) + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/NotificationPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/NotificationPresenter.java deleted file mode 100644 index 81d69c1475..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/NotificationPresenter.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.NotificationView; - -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - -/** - * Created by dilpreet on 14/9/17. - */ - -public class NotificationPresenter extends BasePresenter { - - private DataManager manager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param manager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public NotificationPresenter(DataManager manager, @ActivityContext Context context) { - super(context); - this.manager = manager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(NotificationView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - public void loadNotifications() { - - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(manager.getNotifications() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context - .getString(R.string.notification)); - } - - @Override - public void onNext(List notificationModels) { - getMvpView().hideProgress(); - getMvpView().showNotifications(notificationModels); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/NotificationPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/NotificationPresenter.kt new file mode 100644 index 0000000000..0721e28389 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/NotificationPresenter.kt @@ -0,0 +1,53 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.NotificationView + +import javax.inject.Inject + +/** + * Created by dilpreet on 14/9/17. + */ +class NotificationPresenter @Inject constructor(private val manager: DataManager?, @ActivityContext context: Context?) : + BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun loadNotifications() { + checkViewAttached() + mvpView?.showProgress() + manager?.notifications + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context + ?.getString(R.string.notification)) + } + + override fun onNext(notificationModels: List) { + mvpView?.hideProgress() + mvpView?.showNotifications(notificationModels) + } + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/QrCodeImportPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/QrCodeImportPresenter.java deleted file mode 100644 index aa7ded2419..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/QrCodeImportPresenter.java +++ /dev/null @@ -1,137 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; -import android.graphics.Bitmap; -import android.net.Uri; - -import com.google.zxing.BinaryBitmap; -import com.google.zxing.DecodeHintType; -import com.google.zxing.LuminanceSource; -import com.google.zxing.MultiFormatReader; -import com.google.zxing.RGBLuminanceSource; -import com.google.zxing.Reader; -import com.google.zxing.Result; -import com.google.zxing.common.HybridBinarizer; -import com.isseiaoki.simplecropview.CropImageView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.QrCodeImportView; - -import java.util.EnumMap; -import java.util.Map; - -import javax.inject.Inject; - -import io.reactivex.Single; -import io.reactivex.SingleSource; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.annotations.NonNull; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.functions.Consumer; -import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; - -/** - * Created by manishkumar on 19/05/18. - */ - -public class QrCodeImportPresenter extends BasePresenter { - - private Result result; - private CompositeDisposable compositeDisposable; - private boolean hasErrorOccured = false; - - /** - * Initialises the LoanAccountDetailsPresenter by automatically injecting an instance of - * {@link Context}. - * - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public QrCodeImportPresenter(@ApplicationContext Context context) { - super(context); - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(QrCodeImportView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - context = null; - } - - /** - * This method decodes the Qr code from the selected region - * - * @param sourceUri contains the Uri of qr code from gallery - * @param cropImageView contains cropImageView of layout - */ - public void getDecodedResult(Uri sourceUri, final CropImageView cropImageView) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(cropImageView.crop(sourceUri) - .executeAsSingle() - .flatMap(new Function>() { - @Override - public SingleSource apply(@NonNull Bitmap bMap) - throws Exception { - - int[] intArray = new int[bMap.getWidth() * bMap.getHeight()]; - //copy pixel data from the Bitmap into the 'intArray' array - bMap.getPixels(intArray, 0, bMap.getWidth(), 0, 0, - bMap.getWidth(), bMap.getHeight()); - LuminanceSource source = new RGBLuminanceSource(bMap.getWidth(), - bMap.getHeight(), intArray); - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); - //flags for decoding since it is large file - Map tmpHintsMap - = new EnumMap<>(DecodeHintType.class); - tmpHintsMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); - tmpHintsMap.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); - - Reader reader = new MultiFormatReader(); - - try { - result = reader.decode(bitmap, tmpHintsMap); - } catch (Exception e) { - getMvpView().hideProgress(); - hasErrorOccured = true; - getMvpView().showErrorReadingQr(context - .getString(R.string.error_reading_qr)); - } - return Single.just(result); - } - }) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(new Consumer() { - @Override - public void accept(Result result) throws Exception { - getMvpView().hideProgress(); - getMvpView().handleDecodedResult(result); - } - }, new Consumer() { - @Override - public void accept(Throwable throwable) throws Exception { - getMvpView().hideProgress(); - if (!hasErrorOccured) { - getMvpView() - .showErrorReadingQr( - context.getString(R.string.error_reading_qr)); - } - hasErrorOccured = false; - } - })); - - } - - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/QrCodeImportPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/QrCodeImportPresenter.kt new file mode 100644 index 0000000000..2402a458d0 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/QrCodeImportPresenter.kt @@ -0,0 +1,90 @@ +package org.mifos.mobile.presenters + +import android.content.Context +import android.net.Uri + +import com.google.zxing.* +import com.google.zxing.common.HybridBinarizer + +import com.isseiaoki.simplecropview.CropImageView + +import io.reactivex.Single +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.QrCodeImportView + +import java.util.* +import javax.inject.Inject + +/** + * Created by manishkumar on 19/05/18. + */ +class QrCodeImportPresenter @Inject constructor(@ApplicationContext context: Context?) : + BasePresenter(context) { + + private var result: Result? = null + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + private var hasErrorOccured = false + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + context = null + } + + /** + * This method decodes the Qr code from the selected region + * + * @param sourceUri contains the Uri of qr code from gallery + * @param cropImageView contains cropImageView of layout + */ + fun getDecodedResult(sourceUri: Uri?, cropImageView: CropImageView?) { + checkViewAttached() + mvpView?.showProgress() + cropImageView?.crop(sourceUri) + ?.executeAsSingle() + ?.flatMap { bMap -> + val intArray = IntArray(bMap.width * bMap.height) + //copy pixel data from the Bitmap into the 'intArray' array + bMap.getPixels(intArray, 0, bMap.width, 0, 0, + bMap.width, bMap.height) + val source: LuminanceSource = RGBLuminanceSource(bMap.width, + bMap.height, intArray) + val bitmap = BinaryBitmap(HybridBinarizer(source)) + //flags for decoding since it is large file + val tmpHintsMap: MutableMap = EnumMap(DecodeHintType::class.java) + tmpHintsMap[DecodeHintType.TRY_HARDER] = java.lang.Boolean.TRUE + tmpHintsMap[DecodeHintType.PURE_BARCODE] = java.lang.Boolean.TRUE + val reader: Reader = MultiFormatReader() + try { + result = reader.decode(bitmap, tmpHintsMap) + } catch (e: Exception) { + mvpView?.hideProgress() + hasErrorOccured = true + mvpView?.showErrorReadingQr(context + ?.getString(R.string.error_reading_qr)) + } + Single.just(result) + } + ?.subscribeOn(Schedulers.newThread()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribe({ result -> + mvpView?.hideProgress() + mvpView?.handleDecodedResult(result) + }) { + mvpView?.hideProgress() + if (!hasErrorOccured) { + mvpView + ?.showErrorReadingQr( + context?.getString(R.string.error_reading_qr)) + } + hasErrorOccured = false + }?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/RecentTransactionsPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/RecentTransactionsPresenter.java deleted file mode 100644 index 8dd66d371c..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/RecentTransactionsPresenter.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.Transaction; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.RecentTransactionsView; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - -/** - * @author Vishwajeet - * @since 10/08/16 - */ -public class RecentTransactionsPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposables; - - private int limit = 50; - private boolean loadmore; - - /** - * Initialises the RecentTransactionsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - - @Inject - public RecentTransactionsPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - } - - @Override - public void attachView(RecentTransactionsView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - /** - * Used to call function {@code loadRecentTransactions(int offset, int limit)} which is used for - * fetching RecentTransaction from server. - * - * @param loadmore Set {@code false} if calling First time and {@code true} if you need to fetch - * more {@link Transaction} - * @param offset Set {@code 0} if calling first time or set length of {@code totalItemsCount} - * if - * you need to fetch more {@link Transaction} - */ - public void loadRecentTransactions(boolean loadmore, int offset) { - this.loadmore = loadmore; - loadRecentTransactions(offset, limit); - } - - /** - * Used to load List of {@link Transaction} from server depending upon the {@code offset} and - * the max {@code limit} and notifies the view to display it. And in case of any - * error during fetching the required details it notifies the view. - * - * @param offset Starting position for fetching the list of {@link Transaction} - * @param limit Maximum size of List of {@link Transaction} which is fetched from server - */ - public void loadRecentTransactions(int offset, int limit) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.getRecentTransactions(offset, limit) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingRecentTransactions( - context.getString(R.string.recent_transactions)); - } - - @Override - public void onNext(Page transactions) { - getMvpView().hideProgress(); - if (transactions.getTotalFilteredRecords() == 0) { - getMvpView().showEmptyTransaction(); - } else if (loadmore && !transactions.getPageItems().isEmpty()) { - getMvpView() - .showLoadMoreRecentTransactions(transactions.getPageItems()); - } else if (!transactions.getPageItems().isEmpty()) { - getMvpView().showRecentTransactions(transactions.getPageItems()); - } else { - getMvpView().showMessage( - context.getString(R.string.no_more_transactions_available)); - } - } - }) - ); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/RecentTransactionsPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/RecentTransactionsPresenter.kt new file mode 100644 index 0000000000..668a9edecd --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/RecentTransactionsPresenter.kt @@ -0,0 +1,95 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.Page +import org.mifos.mobile.models.Transaction +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.RecentTransactionsView + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 10/08/16 + */ +class RecentTransactionsPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + private val compositeDisposables: CompositeDisposable = CompositeDisposable() + private val limit = 50 + private var loadmore = false + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + /** + * Used to call function `loadRecentTransactions(int offset, int limit)` which is used for + * fetching RecentTransaction from server. + * + * @param loadmore Set `false` if calling First time and `true` if you need to fetch + * more [Transaction] + * @param offset Set `0` if calling first time or set length of `totalItemsCount` + * if + * you need to fetch more [Transaction] + */ + fun loadRecentTransactions(loadmore: Boolean, offset: Int) { + this.loadmore = loadmore + loadRecentTransactions(offset, limit) + } + + /** + * Used to load List of [Transaction] from server depending upon the `offset` and + * the max `limit` and notifies the view to display it. And in case of any + * error during fetching the required details it notifies the view. + * + * @param offset Starting position for fetching the list of [Transaction] + * @param limit Maximum size of List of [Transaction] which is fetched from server + */ + private fun loadRecentTransactions(offset: Int, limit: Int) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getRecentTransactions(offset, limit) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver?>() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingRecentTransactions( + context?.getString(R.string.recent_transactions)) + } + + override fun onNext(transactions: Page) { + mvpView?.hideProgress() + if (transactions.totalFilteredRecords == 0) { + mvpView?.showEmptyTransaction() + } else if (loadmore && transactions.pageItems.isNotEmpty()) { + mvpView + ?.showLoadMoreRecentTransactions(transactions.pageItems) + } else if (transactions.pageItems.isNotEmpty()) { + mvpView?.showRecentTransactions(transactions.pageItems) + } else { + mvpView?.showMessage( + context?.getString(R.string.no_more_transactions_available)) + } + } + })?.let { + compositeDisposables.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/RegistrationPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/RegistrationPresenter.java deleted file mode 100644 index 787a072304..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/RegistrationPresenter.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.register.RegisterPayload; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.RegistrationView; -import org.mifos.mobile.utils.MFErrorParser; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - - -/** - * Created by dilpreet on 31/7/17. - */ - -public class RegistrationPresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposables; - - /** - * Initialises the RecentTransactionsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public RegistrationPresenter(DataManager dataManager, @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - } - - @Override - public void attachView(RegistrationView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - public void registerUser(RegisterPayload registerPayload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.registerUser(registerPayload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(MFErrorParser.errorMessage(e)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showRegisteredSuccessfully(); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/RegistrationPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/RegistrationPresenter.kt new file mode 100644 index 0000000000..28ac599813 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/RegistrationPresenter.kt @@ -0,0 +1,55 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.register.RegisterPayload +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.RegistrationView +import org.mifos.mobile.utils.MFErrorParser + +import javax.inject.Inject + +/** + * Created by dilpreet on 31/7/17. + */ +class RegistrationPresenter @Inject constructor(private val dataManager: DataManager?, @ApplicationContext context: Context?) : BasePresenter(context) { + private val compositeDisposables: CompositeDisposable = CompositeDisposable() + fun attachView(mvpView: RegistrationView) { + super.attachView(mvpView) + } + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + fun registerUser(registerPayload: RegisterPayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.registerUser(registerPayload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(MFErrorParser.errorMessage(e)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showRegisteredSuccessfully() + } + })?.let { compositeDisposables.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/RegistrationVerificationPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/RegistrationVerificationPresenter.java deleted file mode 100644 index 74a5c7e867..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/RegistrationVerificationPresenter.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.register.UserVerify; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.RegistrationVerificationView; -import org.mifos.mobile.utils.MFErrorParser; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - - -/** - * Created by dilpreet on 31/7/17. - */ - -public class RegistrationVerificationPresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposables; - - /** - * Initialises the RecentTransactionsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public RegistrationVerificationPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - } - - @Override - public void attachView(RegistrationVerificationView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - public void verifyUser(UserVerify userVerify) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.verifyUser(userVerify) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(MFErrorParser.errorMessage(e)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showVerifiedSuccessfully(); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/RegistrationVerificationPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/RegistrationVerificationPresenter.kt new file mode 100644 index 0000000000..c701a518e9 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/RegistrationVerificationPresenter.kt @@ -0,0 +1,56 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.register.UserVerify +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.RegistrationVerificationView +import org.mifos.mobile.utils.MFErrorParser.errorMessage + +import javax.inject.Inject + +/** + * Created by dilpreet on 31/7/17. + */ +class RegistrationVerificationPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + private val compositeDisposables: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + fun verifyUser(userVerify: UserVerify?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.verifyUser(userVerify) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(errorMessage(e)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showVerifiedSuccessfully() + } + })?.let { compositeDisposables.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsDetailPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsDetailPresenter.java deleted file mode 100644 index aa5bbe4cf0..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsDetailPresenter.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.SavingAccountsDetailView; -import org.mifos.mobile.utils.Constants; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * @author Vishwajeet - * @since 18/8/16. - */ - -public class SavingAccountsDetailPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposables; - - /** - * Initialises the SavingAccountsDetailPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public SavingAccountsDetailPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - } - - @Override - public void attachView(SavingAccountsDetailView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - /** - * Load details of a particular saving account from the server and notify the view - * to display it. Notify the view, in case there is any error in fetching - * the details from server. - * - * @param accountId Id of Savings Account - */ - public void loadSavingsWithAssociations(long accountId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.getSavingsWithAssociations(accountId, - Constants.TRANSACTIONS) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingSavingAccountsDetail( - context.getString(R.string.error_saving_account_details_loading)); - } - - @Override - public void onNext(SavingsWithAssociations savingAccount) { - getMvpView().hideProgress(); - getMvpView().showSavingAccountsDetail(savingAccount); - } - }) - ); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsDetailPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsDetailPresenter.kt new file mode 100644 index 0000000000..4363448dea --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsDetailPresenter.kt @@ -0,0 +1,68 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.SavingAccountsDetailView +import org.mifos.mobile.utils.Constants + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 18/8/16. + */ +class SavingAccountsDetailPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + private val compositeDisposables: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + /** + * Load details of a particular saving account from the server and notify the view + * to display it. Notify the view, in case there is any error in fetching + * the details from server. + * + * @param accountId Id of Savings Account + */ + fun loadSavingsWithAssociations(accountId: Long?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getSavingsWithAssociations(accountId, + Constants.TRANSACTIONS) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingSavingAccountsDetail( + context?.getString(R.string.error_saving_account_details_loading)) + } + + override fun onNext(savingAccount: SavingsWithAssociations) { + mvpView?.hideProgress() + mvpView?.showSavingAccountsDetail(savingAccount) + } + })?.let { + compositeDisposables.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsTransactionPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsTransactionPresenter.java deleted file mode 100644 index 17e6fe5ee6..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsTransactionPresenter.java +++ /dev/null @@ -1,198 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.CheckboxStatus; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.accounts.savings.Transactions; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.SavingAccountsTransactionView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; - -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.Observable; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.functions.Predicate; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * Created by dilpreet on 6/3/17. - */ - - -public class SavingAccountsTransactionPresenter extends - BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposables; - - /** - * Initialises the SavingAccountsDetailPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public SavingAccountsTransactionPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - } - - @Override - public void attachView(SavingAccountsTransactionView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - /** - * Filters {@link List} of {@link CheckboxStatus} - * @param statusModelList {@link List} of {@link CheckboxStatus} - * @return Returns {@link List} of {@link CheckboxStatus} which have - * {@code checkboxStatus.isChecked()} as true. - */ - public List getCheckedStatus(List statusModelList) { - return Observable.fromIterable(statusModelList) - .filter(new Predicate() { - - @Override - public boolean test(CheckboxStatus checkboxStatus) throws Exception { - return checkboxStatus.isChecked(); - } - }).toList().blockingGet(); - } - - - /** - * Load details of a particular saving account from the server and notify the view - * to display it. Notify the view, in case there is any error in fetching - * the details from server. - * - * @param accountId Id of Savings Account - */ - public void loadSavingsWithAssociations(long accountId) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.getSavingsWithAssociations(accountId, - Constants.TRANSACTIONS) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showErrorFetchingSavingAccountsDetail( - context.getString(R.string.saving_account_details)); - } - - @Override - public void onNext(SavingsWithAssociations savingAccount) { - getMvpView().hideProgress(); - getMvpView().showSavingAccountsDetail(savingAccount); - } - }) - ); - } - - /** - * Used for filtering {@link List} of {@link Transactions} according to {@code startDate} and - * {@code lastDate} - * - * @param savingAccountsTransactionList {@link List} of {@link Transactions} - * @param startDate Starting date for filtering - * @param lastDate Last date for filtering - */ - public void filterTransactionList(List savingAccountsTransactionList, - final long startDate, final long lastDate) { - List list = Observable.fromIterable(savingAccountsTransactionList) - .filter(new Predicate() { - @Override - public boolean test(Transactions transactions) { - return startDate <= DateHelper.getDateAsLongFromList(transactions.getDate()) - && lastDate >= DateHelper. - getDateAsLongFromList(transactions.getDate()); - } - }) - .toList().blockingGet(); - - getMvpView().showFilteredList(list); - } - - /** - * Filters {@link List} of {@link Transactions} according to {@link CheckboxStatus} - * @param savingAccountsTransactionList {@link List} of filtered {@link Transactions} - * @param status Used for filtering the {@link List} - * @return Returns {@link List} of filtered {@link Transactions} according to the - * {@code status} provided. - */ - - - public List filterTranactionListbyType( - List savingAccountsTransactionList, final CheckboxStatus status) { - - return Observable.fromIterable(savingAccountsTransactionList) - .filter(new Predicate() { - @Override - public boolean test(Transactions transactions) throws Exception { - if (status.getStatus().compareTo(context.getString(R.string.deposit)) == 0 - && transactions.getTransactionType().getDeposit()) { - return true; - } else if (status.getStatus().compareTo( - context.getString(R.string.dividend_payout)) == 0 && - transactions.getTransactionType().getDividendPayout()) { - return true; - } else if (status.getStatus().compareTo( - context.getString(R.string.withdrawal)) == 0 && - transactions.getTransactionType().getWithdrawal()) { - return true; - } else if (status.getStatus().compareTo( - context.getString(R.string.interest_posting)) == 0 && - transactions.getTransactionType().getInterestPosting()) { - return true; - } else if (status.getStatus().compareTo( - context.getString(R.string.fee_deduction)) == 0 && - transactions.getTransactionType().getFeeDeduction()) { - return true; - } else if (status.getStatus().compareTo( - context.getString(R.string.withdrawal_transfer)) == 0 && - transactions.getTransactionType().getApproveTransfer()) { - return true; - } else if (status.getStatus().compareTo(context.getString( - R.string.rejected_transfer)) == 0 && transactions - .getTransactionType().getRejectTransfer()) { - return true; - } else if (status.getStatus().compareTo(context.getString( - R.string.overdraft_fee)) == 0 && - transactions.getTransactionType().getOverdraftFee()) { - return true; - } - return false; - } - }).toList().blockingGet(); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsTransactionPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsTransactionPresenter.kt new file mode 100644 index 0000000000..487138a576 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/SavingAccountsTransactionPresenter.kt @@ -0,0 +1,163 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.Observable +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.functions.Predicate +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.CheckboxStatus +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.accounts.savings.Transactions +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.SavingAccountsTransactionView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DateHelper.getDateAsLongFromList + +import javax.inject.Inject + + +/** + * Created by dilpreet on 6/3/17. + */ +class SavingAccountsTransactionPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + private val compositeDisposables: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + /** + * Filters [List] of [CheckboxStatus] + * @param statusModelList [List] of [CheckboxStatus] + * @return Returns [List] of [CheckboxStatus] which have + * `checkboxStatus.isChecked()` as true. + */ + fun getCheckedStatus(statusModelList: List?): List? { + return Observable.fromIterable(statusModelList) + .filter { (_, _, isChecked) -> isChecked }.toList().blockingGet() + } + + /** + * Load details of a particular saving account from the server and notify the view + * to display it. Notify the view, in case there is any error in fetching + * the details from server. + * + * @param accountId Id of Savings Account + */ + fun loadSavingsWithAssociations(accountId: Long) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getSavingsWithAssociations(accountId, + Constants.TRANSACTIONS) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showErrorFetchingSavingAccountsDetail( + context?.getString(R.string.saving_account_details)) + } + + override fun onNext(savingAccount: SavingsWithAssociations) { + mvpView?.hideProgress() + mvpView?.showSavingAccountsDetail(savingAccount) + } + })?.let { + compositeDisposables.add(it + ) + } + } + + /** + * Used for filtering [List] of [Transactions] according to `startDate` and + * `lastDate` + * + * @param savingAccountsTransactionList [List] of [Transactions] + * @param startDate Starting date for filtering + * @param lastDate Last date for filtering + */ + fun filterTransactionList( + savingAccountsTransactionList: List?, + startDate: Long?, lastDate: Long? + ) { + val list = if (startDate != null && lastDate != null) + Observable.fromIterable(savingAccountsTransactionList) + .filter { (_, _, _, _, date) -> + (getDateAsLongFromList(date) in startDate..lastDate) + } + .toList().blockingGet() + else null + mvpView?.showFilteredList(list) + } + + /** + * Filters [List] of [Transactions] according to [CheckboxStatus] + * @param savingAccountsTransactionList [List] of filtered [Transactions] + * @param status Used for filtering the [List] + * @return Returns [List] of filtered [Transactions] according to the + * `status` provided. + */ + fun filterTranactionListbyType( + savingAccountsTransactionList: List?, status: CheckboxStatus? + ): Collection? { + return Observable.fromIterable(savingAccountsTransactionList) + .filter(Predicate { (_, transactionType) -> + if (context?.getString(R.string.deposit)?.let { status?.status?.compareTo(it) } == 0 + && transactionType?.deposit!!) { + return@Predicate true + } else if (context?.getString(R.string.dividend_payout)?.let { + status?.status?.compareTo( + it) + } == 0 && + transactionType?.dividendPayout!!) { + return@Predicate true + } else if (context?.getString(R.string.withdrawal)?.let { + status?.status?.compareTo( + it) + } == 0 && + transactionType?.withdrawal!!) { + return@Predicate true + } else if (context?.getString(R.string.interest_posting)?.let { + status?.status?.compareTo( + it) + } == 0 && + transactionType?.interestPosting!!) { + return@Predicate true + } else if (context?.getString(R.string.fee_deduction)?.let { + status?.status?.compareTo( + it) + } == 0 && + transactionType?.feeDeduction!!) { + return@Predicate true + } else if (context?.getString(R.string.withdrawal_transfer)?.let { + status?.status?.compareTo( + it) + } == 0 && + transactionType?.approveTransfer!!) { + return@Predicate true + } else if (context?.getString( + R.string.rejected_transfer)?.let { status?.status?.compareTo(it) } == 0 && transactionType?.rejectTransfer!!) { + return@Predicate true + } else if (context?.getString( + R.string.overdraft_fee)?.let { status?.status?.compareTo(it) } == 0 && + transactionType?.overdraftFee!!) { + return@Predicate true + } + false + }).toList().blockingGet() + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountApplicationPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountApplicationPresenter.java deleted file mode 100644 index d1d27dba8b..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountApplicationPresenter.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.mifos.mobile.presenters; - -/* - * Created by saksham on 30/June/2018 - */ - -import android.content.Context; - -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload; -import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload; -import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.enums.SavingsAccountState; -import org.mifos.mobile.ui.views.SavingsAccountApplicationView; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -public class SavingsAccountApplicationPresenter - extends BasePresenter { - - private CompositeDisposable compositeDisposable; - private DataManager dataManager; - - @Inject - public SavingsAccountApplicationPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(SavingsAccountApplicationView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - public void loadSavingsAccountApplicationTemplate(long clientId, - final SavingsAccountState state) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.getSavingAccountApplicationTemplate(clientId) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - - @Override - public void onNext(SavingsAccountTemplate template) { - getMvpView().hideProgress(); - - if (state == SavingsAccountState.CREATE) { - getMvpView().showUserInterfaceSavingAccountApplication(template); - } else { - getMvpView().showUserInterfaceSavingAccountUpdate(template); - } - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(e.getMessage()); - } - - @Override - public void onComplete() { - - } - })); - } - - public void submitSavingsAccountApplication(SavingsAccountApplicationPayload payload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.submitSavingAccountApplication(payload) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(e.getMessage()); - } - - @Override - public void onComplete() { - getMvpView().showSavingsAccountApplicationSuccessfully(); - - } - })); - } - - public void updateSavingsAccount(String accountId, SavingsAccountUpdatePayload payload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.updateSavingsAccount(accountId, payload) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(e.getMessage()); - - } - - @Override - public void onComplete() { - getMvpView().showSavingsAccountUpdateSuccessfully(); - } - })); - - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountApplicationPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountApplicationPresenter.kt new file mode 100644 index 0000000000..b0bdc6f540 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountApplicationPresenter.kt @@ -0,0 +1,109 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload +import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload +import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.enums.SavingsAccountState +import org.mifos.mobile.ui.views.SavingsAccountApplicationView + +import javax.inject.Inject + +/* +* Created by saksham on 30/June/2018 +*/ +class SavingsAccountApplicationPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun loadSavingsAccountApplicationTemplate( + clientId: Long?, + state: SavingsAccountState? + ) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.getSavingAccountApplicationTemplate(clientId) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(template: SavingsAccountTemplate) { + mvpView?.hideProgress() + if (state === SavingsAccountState.CREATE) { + mvpView?.showUserInterfaceSavingAccountApplication(template) + } else { + mvpView?.showUserInterfaceSavingAccountUpdate(template) + } + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(e.message) + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + + fun submitSavingsAccountApplication(payload: SavingsAccountApplicationPayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.submitSavingAccountApplication(payload) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(e.message) + } + + override fun onComplete() { + mvpView?.showSavingsAccountApplicationSuccessfully() + } + })?.let { compositeDisposable.add(it) } + } + + fun updateSavingsAccount(accountId: String?, payload: SavingsAccountUpdatePayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.updateSavingsAccount(accountId, payload) + ?.subscribeOn(Schedulers.newThread()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(e.message) + } + + override fun onComplete() { + mvpView?.showSavingsAccountUpdateSuccessfully() + } + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountWithdrawPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountWithdrawPresenter.java deleted file mode 100644 index bc0b1aec29..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountWithdrawPresenter.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.mifos.mobile.presenters; - -/* - * Created by saksham on 02/July/2018 - */ - -import android.content.Context; - -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.SavingsAccountWithdrawView; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - -public class SavingsAccountWithdrawPresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposable; - - @Inject - public SavingsAccountWithdrawPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(SavingsAccountWithdrawView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - public void submitWithdrawSavingsAccount(String accountId, - SavingsAccountWithdrawPayload payload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.submitWithdrawSavingsAccount(accountId, payload) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(ResponseBody responseBodyObservable) { - getMvpView().hideProgress(); - getMvpView().showSavingsAccountWithdrawSuccessfully(); - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(e.getMessage()); - } - - @Override - public void onComplete() { - - } - })); - - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountWithdrawPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountWithdrawPresenter.kt new file mode 100644 index 0000000000..0c434b8868 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/SavingsAccountWithdrawPresenter.kt @@ -0,0 +1,59 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.SavingsAccountWithdrawView + +import javax.inject.Inject + +/* +* Created by saksham on 02/July/2018 +*/ +class SavingsAccountWithdrawPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun submitWithdrawSavingsAccount( + accountId: String?, + payload: SavingsAccountWithdrawPayload? + ) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.submitWithdrawSavingsAccount(accountId, payload) + ?.subscribeOn(Schedulers.newThread()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(responseBodyObservable: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showSavingsAccountWithdrawSuccessfully() + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(e.message) + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingsMakeTransferPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/SavingsMakeTransferPresenter.java deleted file mode 100644 index ccc7768455..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/SavingsMakeTransferPresenter.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.payload.AccountDetail; -import org.mifos.mobile.models.templates.account.AccountOption; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.SavingsMakeTransferMvpView; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.Observable; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.functions.Consumer; -import io.reactivex.functions.Function; -import io.reactivex.functions.Predicate; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * Created by Rajan Maurya on 10/03/17. - */ -public class SavingsMakeTransferPresenter extends BasePresenter { - - public final DataManager dataManager; - public CompositeDisposable compositeDisposables; - - /** - * Initialises the RecentTransactionsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public SavingsMakeTransferPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - } - - @Override - public void attachView(SavingsMakeTransferMvpView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - /** - * Fetches {@link AccountOptionsTemplate} from server and notifies the view to display it. And - * in case of any error during fetching the required details it notifies the view. - */ - public void loanAccountTransferTemplate() { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.getAccountTransferTemplate() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString( - R.string.error_fetching_account_transfer_template)); - } - - @Override - public void onNext(AccountOptionsTemplate accountOptionsTemplate) { - getMvpView().hideProgress(); - getMvpView().showSavingsAccountTemplate(accountOptionsTemplate); - } - }) - ); - } - - /** - * Retrieving {@link List} of {@code accountNo} from {@link List} of {@link AccountOption} - * - * @param accountOptions {@link List} of {@link AccountOption} - * @return Returns {@link List} containing {@code accountNo} - */ - public List getAccountNumbers(List accountOptions, - final boolean isTypePayFrom) { - final List accountNumber = new ArrayList<>(); - Observable.fromIterable(accountOptions) - .filter(new Predicate() { - @Override - public boolean test(AccountOption accountOption) throws Exception { - return !(accountOption.getAccountType().getCode().equals(context. - getString(R.string.account_type_loan)) - && isTypePayFrom); - } - }) - .flatMap(new Function>() { - @Override - public Observable apply(AccountOption accountOption) { - return Observable.just(new AccountDetail(accountOption.getAccountNo(), - accountOption.getAccountType().getValue())); - } - }) - .subscribe(new Consumer() { - @Override - public void accept(AccountDetail accountDetail) throws Exception { - accountNumber.add(accountDetail); - - } - }); - return accountNumber; - } - - /** - * Searches for a {@link AccountOption} with provided {@code accountId} from {@link List} of - * {@link AccountOption} and returns it. - * - * @param accountOptions {@link List} of {@link AccountOption} - * @param accountId AccountId which needs to searched in {@link List} of {@link - * AccountOption} - * @return Returns {@link AccountOption} which has accountId same as the provided - * {@code accountId} in function parameter. - */ - public AccountOption searchAccount(List accountOptions, final long accountId) { - final AccountOption[] accountOption = {new AccountOption()}; - Observable.fromIterable(accountOptions) - .filter(new Predicate() { - @Override - public boolean test(AccountOption accountOption) { - return (accountId == accountOption.getAccountId()); - } - }) - .subscribe(new Consumer() { - @Override - public void accept(AccountOption account) throws Exception { - accountOption[0] = account; - - } - }); - return accountOption[0]; - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/SavingsMakeTransferPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/SavingsMakeTransferPresenter.kt new file mode 100644 index 0000000000..a617c3d98d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/SavingsMakeTransferPresenter.kt @@ -0,0 +1,103 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.Observable +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.payload.AccountDetail +import org.mifos.mobile.models.templates.account.AccountOption +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.SavingsMakeTransferMvpView + +import java.util.* +import javax.inject.Inject + +/** + * Created by Rajan Maurya on 10/03/17. + */ +class SavingsMakeTransferPresenter @Inject constructor( + val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + private var compositeDisposables: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + /** + * Fetches [AccountOptionsTemplate] from server and notifies the view to display it. And + * in case of any error during fetching the required details it notifies the view. + */ + fun loanAccountTransferTemplate() { + checkViewAttached() + mvpView?.showProgress() + dataManager?.accountTransferTemplate + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString( + R.string.error_fetching_account_transfer_template)) + } + + override fun onNext(accountOptionsTemplate: AccountOptionsTemplate) { + mvpView?.hideProgress() + mvpView?.showSavingsAccountTemplate(accountOptionsTemplate) + } + })?.let { + compositeDisposables.add(it + ) + } + } + + /** + * Retrieving [List] of `accountNo` from [List] of [AccountOption] + * + * @param accountOptions [List] of [AccountOption] + * @return Returns [List] containing `accountNo` + */ + fun getAccountNumbers( + accountOptions: List?, + isTypePayFrom: Boolean + ): List { + val accountNumber: MutableList = ArrayList() + Observable.fromIterable(accountOptions) + .filter { (_, _, accountType) -> !(accountType?.code == context?.getString(R.string.account_type_loan) && isTypePayFrom) } + .flatMap { (_, accountNo, accountType) -> + Observable.just(AccountDetail(accountNo!!, + accountType?.value!!)) + } + .subscribe { accountDetail -> accountNumber.add(accountDetail) } + return accountNumber + } + + /** + * Searches for a [AccountOption] with provided `accountId` from [List] of + * [AccountOption] and returns it. + * + * @param accountOptions [List] of [AccountOption] + * @param accountId AccountId which needs to searched in [List] of [ ] + * @return Returns [AccountOption] which has accountId same as the provided + * `accountId` in function parameter. + */ + fun searchAccount(accountOptions: List?, accountId: Long?): AccountOption { + val accountOption = arrayOf(AccountOption()) + Observable.fromIterable(accountOptions) + .filter { (accountId1) -> accountId == accountId1?.toLong() } + .subscribe { account -> accountOption[0] = account } + return accountOption[0] + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/ThirdPartyTransferPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/ThirdPartyTransferPresenter.java deleted file mode 100644 index a788363f8c..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/ThirdPartyTransferPresenter.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.AccountOptionAndBeneficiary; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.beneficiary.BeneficiaryDetail; -import org.mifos.mobile.models.payload.AccountDetail; -import org.mifos.mobile.models.templates.account.AccountOption; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.ThirdPartyTransferView; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.reactivex.Observable; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.functions.BiFunction; -import io.reactivex.functions.Consumer; -import io.reactivex.functions.Function; -import io.reactivex.functions.Predicate; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; - - -/** - * Created by dilpreet on 21/6/17. - */ - -public class ThirdPartyTransferPresenter extends BasePresenter { - - private DataManager dataManager; - private CompositeDisposable compositeDisposable; - - /** - * Initialises the RecentTransactionsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public ThirdPartyTransferPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposable = new CompositeDisposable(); - } - - @Override - public void attachView(ThirdPartyTransferView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - /** - * Fetches {@link AccountOptionsTemplate} and {@link List} of {@link Beneficiary} from server - * and notifies the view to display them. And in case of any error during fetching the required - * details it notifies the view. - */ - public void loadTransferTemplate() { - - checkViewAttached(); - getMvpView().showProgress(); - - compositeDisposable.add(Observable.zip(dataManager.getThirdPartyTransferTemplate(), - dataManager.getBeneficiaryList(), - new BiFunction, - AccountOptionAndBeneficiary>() { - @Override - public AccountOptionAndBeneficiary apply(AccountOptionsTemplate - accountOptionsTemplate, - List beneficiaries) { - return new AccountOptionAndBeneficiary(accountOptionsTemplate, - beneficiaries); - } - }) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString( - R.string.error_fetching_third_party_transfer_template)); - } - - @Override - public void onNext(AccountOptionAndBeneficiary accountOptionAndBeneficiary) { - getMvpView().hideProgress(); - getMvpView().showThirdPartyTransferTemplate(accountOptionAndBeneficiary. - getAccountOptionsTemplate()); - getMvpView().showBeneficiaryList(accountOptionAndBeneficiary. - getBeneficiaryList()); - } - })); - } - - /** - * Retrieving {@link List} of {@code accountNumbers} from {@link List} of {@link AccountOption} - * - * @param accountOptions {@link List} of {@link AccountOption} - * @return Returns {@link List} containing {@code accountNumbers} - */ - public List getAccountNumbersFromAccountOptions(List - accountOptions) { - final List accountNumber = new ArrayList<>(); - Observable.fromIterable(accountOptions) - .filter(new Predicate() { - @Override - public boolean test(AccountOption accountOption) throws Exception { - return !accountOption.getAccountType().getCode().equals(context. - getString(R.string.account_type_loan)); - } - }) - .flatMap(new Function>() { - @Override - public Observable apply(AccountOption accountOption) { - return Observable.just(new AccountDetail(accountOption.getAccountNo(), - accountOption.getAccountType().getValue())); - } - }) - .subscribe(new Consumer() { - @Override - public void accept(AccountDetail accountDetail) throws Exception { - accountNumber.add(accountDetail); - - } - }); - return accountNumber; - } - - /** - * Retrieving {@link List} of {@code accountNumbers} from {@link List} of {@link Beneficiary} - * - * @param beneficiaries {@link List} of {@link Beneficiary} - * @return Returns {@link List} containing {@code accountNumbers} - */ - public List getAccountNumbersFromBeneficiaries(final List - beneficiaries) { - final List accountNumbers = new ArrayList<>(); - Observable.fromIterable(beneficiaries) - .flatMap(new Function>() { - @Override - public Observable apply(Beneficiary beneficiary) { - return Observable.just(new BeneficiaryDetail(beneficiary.getAccountNumber(), - beneficiary.getName())); - } - }) - .subscribe(new Consumer() { - @Override - public void accept(BeneficiaryDetail beneficiaryDetail) throws Exception { - accountNumbers.add(beneficiaryDetail); - - } - }); - return accountNumbers; - } - - /** - * Searches for a {@link AccountOption} with provided {@code accountNo} from {@link List} of - * {@link AccountOption} and returns it. - * - * @param accountOptions {@link List} of {@link AccountOption} - * @param accountNo Account Number which needs to searched in {@link List} of - * {@link AccountOption} - * @return Returns {@link AccountOption} which has Account Number same as the provided - * {@code accountNo} in function parameter. - */ - public AccountOption searchAccount(List accountOptions, final String accountNo) { - final AccountOption[] account = {new AccountOption()}; - Observable.fromIterable(accountOptions) - .filter(new Predicate() { - @Override - public boolean test(AccountOption accountOption) { - return accountOption.getAccountNo().equals(accountNo); - } - }) - .subscribe(new Consumer() { - @Override - public void accept(AccountOption accountOption) throws Exception { - account[0] = accountOption; - } - }); - return account[0]; - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/ThirdPartyTransferPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/ThirdPartyTransferPresenter.kt new file mode 100644 index 0000000000..f9c580ca88 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/ThirdPartyTransferPresenter.kt @@ -0,0 +1,126 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.Observable +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.functions.BiFunction +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.AccountOptionAndBeneficiary +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.beneficiary.BeneficiaryDetail +import org.mifos.mobile.models.payload.AccountDetail +import org.mifos.mobile.models.templates.account.AccountOption +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.ThirdPartyTransferView + +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 21/6/17. + */ +class ThirdPartyTransferPresenter @Inject constructor( + private val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + /** + * Fetches [AccountOptionsTemplate] and [List] of [Beneficiary] from server + * and notifies the view to display them. And in case of any error during fetching the required + * details it notifies the view. + */ + fun loadTransferTemplate() { + checkViewAttached() + mvpView?.showProgress() + compositeDisposable.add(Observable.zip(dataManager?.thirdPartyTransferTemplate, + dataManager?.beneficiaryList, + BiFunction?, AccountOptionAndBeneficiary> { accountOptionsTemplate, beneficiaries -> + AccountOptionAndBeneficiary(accountOptionsTemplate, + beneficiaries) + }) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeOn(Schedulers.io()) + .subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString( + R.string.error_fetching_third_party_transfer_template)) + } + + override fun onNext(accountOptionAndBeneficiary: AccountOptionAndBeneficiary) { + mvpView?.hideProgress() + mvpView?.showThirdPartyTransferTemplate(accountOptionAndBeneficiary.accountOptionsTemplate) + mvpView?.showBeneficiaryList(accountOptionAndBeneficiary.beneficiaryList) + } + })) + } + + /** + * Retrieving [List] of `accountNumbers` from [List] of [AccountOption] + * + * @param accountOptions [List] of [AccountOption] + * @return Returns [List] containing `accountNumbers` + */ + fun getAccountNumbersFromAccountOptions(accountOptions: List?): List { + val accountNumber: MutableList = ArrayList() + Observable.fromIterable(accountOptions) + .filter { (_, _, accountType) -> accountType?.code != context?.getString(R.string.account_type_loan) } + .flatMap { (_, accountNo, accountType) -> + Observable.just(AccountDetail(accountNo!!, + accountType?.value!!)) + } + .subscribe { accountDetail -> accountNumber.add(accountDetail) } + return accountNumber + } + + /** + * Retrieving [List] of `accountNumbers` from [List] of [Beneficiary] + * + * @param beneficiaries [List] of [Beneficiary] + * @return Returns [List] containing `accountNumbers` + */ + fun getAccountNumbersFromBeneficiaries(beneficiaries: List?): List { + val accountNumbers: MutableList = ArrayList() + Observable.fromIterable(beneficiaries) + .flatMap { (_, name, _, _, _, accountNumber) -> + Observable.just(BeneficiaryDetail(accountNumber, + name)) + } + .subscribe { beneficiaryDetail -> accountNumbers.add(beneficiaryDetail) } + return accountNumbers + } + + /** + * Searches for a [AccountOption] with provided `accountNo` from [List] of + * [AccountOption] and returns it. + * + * @param accountOptions [List] of [AccountOption] + * @param accountNo Account Number which needs to searched in [List] of + * [AccountOption] + * @return Returns [AccountOption] which has Account Number same as the provided + * `accountNo` in function parameter. + */ + fun searchAccount(accountOptions: List?, accountNo: String?): AccountOption { + val account = arrayOf(AccountOption()) + Observable.fromIterable(accountOptions) + .filter { (_, accountNo1) -> accountNo1 == accountNo } + .subscribe { accountOption -> account[0] = accountOption } + return account[0] + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/TransferProcessPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/TransferProcessPresenter.java deleted file mode 100644 index 94f89630cb..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/TransferProcessPresenter.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.TransferProcessView; -import org.mifos.mobile.utils.MFErrorParser; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; - - -/** - * Created by dilpreet on 1/7/17. - */ - -public class TransferProcessPresenter extends BasePresenter { - - public final DataManager dataManager; - public CompositeDisposable compositeDisposables; - - /** - * Initialises the RecentTransactionsPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public TransferProcessPresenter(DataManager dataManager, - @ApplicationContext Context context) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - } - - @Override - public void attachView(TransferProcessView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - /** - * Used for making a Transfer with the help of {@code transferPayload} provided in function - * parameter. It notifies the view after successful making a Transfer. And in case of any error - * during transfer, it notifies the view. - * - * @param transferPayload Contains details about the Transfer - */ - public void makeSavingsTransfer(TransferPayload transferPayload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.makeTransfer(transferPayload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(MFErrorParser.errorMessage(e)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showTransferredSuccessfully(); - } - }) - ); - } - - /** - * Used for making a Third Party Transfer with the help of {@code transferPayload} provided in - * function parameter. It notifies the view after successful making a Third Party Transfer. And - * in case of any error during transfer, it notifies the view. - * - * @param transferPayload Contains details about the Third Party Transfer - */ - public void makeTPTTransfer(TransferPayload transferPayload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.makeThirdPartyTransfer(transferPayload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.transfer_error)); - } - - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showTransferredSuccessfully(); - } - }) - ); - } - - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/TransferProcessPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/TransferProcessPresenter.kt new file mode 100644 index 0000000000..dbf2bb7a89 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/TransferProcessPresenter.kt @@ -0,0 +1,97 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.TransferProcessView +import org.mifos.mobile.utils.MFErrorParser.errorMessage + +import javax.inject.Inject + +/** + * Created by dilpreet on 1/7/17. + */ +class TransferProcessPresenter @Inject constructor( + val dataManager: DataManager?, + @ApplicationContext context: Context? +) : BasePresenter(context) { + + var compositeDisposables: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + /** + * Used for making a Transfer with the help of `transferPayload` provided in function + * parameter. It notifies the view after successful making a Transfer. And in case of any error + * during transfer, it notifies the view. + * + * @param transferPayload Contains details about the Transfer + */ + fun makeSavingsTransfer(transferPayload: TransferPayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.makeTransfer(transferPayload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(errorMessage(e)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showTransferredSuccessfully() + } + })?.let { + compositeDisposables.add(it + ) + } + } + + /** + * Used for making a Third Party Transfer with the help of `transferPayload` provided in + * function parameter. It notifies the view after successful making a Third Party Transfer. And + * in case of any error during transfer, it notifies the view. + * + * @param transferPayload Contains details about the Third Party Transfer + */ + fun makeTPTTransfer(transferPayload: TransferPayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.makeThirdPartyTransfer(transferPayload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.transfer_error)) + } + + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showTransferredSuccessfully() + } + })?.let { + compositeDisposables.add(it + ) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/UpdatePasswordPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/UpdatePasswordPresenter.java deleted file mode 100644 index 6074a9d146..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/UpdatePasswordPresenter.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.mifos.mobile.presenters; - -/* - * Created by saksham on 13/July/2018 - */ - -import android.content.Context; - -import org.mifos.mobile.api.BaseApiManager; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.UpdatePasswordPayload; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.UpdatePasswordView; -import org.mifos.mobile.utils.MFErrorParser; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.Credentials; -import okhttp3.ResponseBody; - -public class UpdatePasswordPresenter extends BasePresenter { - - private CompositeDisposable compositeDisposable; - private DataManager dataManager; - private PreferencesHelper preferencesHelper; - - @Inject - public UpdatePasswordPresenter(@ApplicationContext Context context, DataManager dataManager, - PreferencesHelper preferencesHelper) { - super(context); - compositeDisposable = new CompositeDisposable(); - this.dataManager = dataManager; - this.preferencesHelper = preferencesHelper; - } - - @Override - public void attachView(UpdatePasswordView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposable.clear(); - } - - public void updateAccountPassword(final UpdatePasswordPayload payload) { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposable.add(dataManager.updateAccountPassword(payload) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver() { - @Override - public void onNext(ResponseBody responseBody) { - getMvpView().hideProgress(); - getMvpView().showPasswordUpdatedSuccessfully(); - updateAuthenticationToken(payload.getPassword()); - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(MFErrorParser.errorMessage(e)); - } - - @Override - public void onComplete() { - - } - })); - } - - public void updateAuthenticationToken(String password) { - String authenticationToken = Credentials.basic(preferencesHelper.getUserName(), password); - preferencesHelper.saveToken(authenticationToken); - BaseApiManager.createService(preferencesHelper.getBaseUrl(), - preferencesHelper.getTenant(), - preferencesHelper.getToken()); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/UpdatePasswordPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/UpdatePasswordPresenter.kt new file mode 100644 index 0000000000..399466c020 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/UpdatePasswordPresenter.kt @@ -0,0 +1,69 @@ +package org.mifos.mobile.presenters + +import android.content.Context + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.Credentials +import okhttp3.ResponseBody + +import org.mifos.mobile.api.BaseApiManager.Companion.createService +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.UpdatePasswordPayload +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.UpdatePasswordView +import org.mifos.mobile.utils.MFErrorParser.errorMessage + +import javax.inject.Inject + +/* +* Created by saksham on 13/July/2018 +*/ +class UpdatePasswordPresenter @Inject constructor( + @ApplicationContext context: Context?, private val dataManager: DataManager?, + private val preferencesHelper: PreferencesHelper? +) : BasePresenter(context) { + + private val compositeDisposable: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposable.clear() + } + + fun updateAccountPassword(payload: UpdatePasswordPayload?) { + checkViewAttached() + mvpView?.showProgress() + dataManager?.updateAccountPassword(payload) + ?.subscribeOn(Schedulers.io()) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeWith(object : DisposableObserver() { + override fun onNext(responseBody: ResponseBody) { + mvpView?.hideProgress() + mvpView?.showPasswordUpdatedSuccessfully() + updateAuthenticationToken(payload?.password) + } + + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(errorMessage(e)) + } + + override fun onComplete() {} + })?.let { compositeDisposable.add(it) } + } + + fun updateAuthenticationToken(password: String?) { + val authenticationToken = Credentials.basic(preferencesHelper?.userName, password) + preferencesHelper?.saveToken(authenticationToken) + createService(preferencesHelper?.baseUrl, + preferencesHelper?.tenant, + preferencesHelper?.token) + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/UserDetailsPresenter.java b/app/src/main/java/org/mifos/mobile/presenters/UserDetailsPresenter.java deleted file mode 100644 index e8ccf9560d..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/UserDetailsPresenter.java +++ /dev/null @@ -1,234 +0,0 @@ -package org.mifos.mobile.presenters; - -import android.content.Context; -import android.graphics.Bitmap; -import android.util.Base64; -import android.util.Log; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.notification.NotificationRegisterPayload; -import org.mifos.mobile.models.notification.NotificationUserDetail; -import org.mifos.mobile.presenters.base.BasePresenter; -import org.mifos.mobile.ui.views.UserDetailsView; -import org.mifos.mobile.utils.ImageUtil; - -import java.io.IOException; - -import javax.inject.Inject; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.ResponseBody; -import retrofit2.HttpException; - -/** - * Created by naman on 07/04/17. - */ - -public class UserDetailsPresenter extends BasePresenter { - - private final DataManager dataManager; - private CompositeDisposable compositeDisposables; - private PreferencesHelper preferencesHelper; - - /** - * Initialises the LoginPresenter by automatically injecting an instance of - * {@link DataManager} and {@link Context}. - * - * @param dataManager DataManager class that provides access to the data - * via the API. - * @param context Context of the view attached to the presenter. In this case - * it is that of an {@link androidx.appcompat.app.AppCompatActivity} - */ - @Inject - public UserDetailsPresenter(@ApplicationContext Context context, DataManager dataManager, - PreferencesHelper preferencesHelper) { - super(context); - this.dataManager = dataManager; - compositeDisposables = new CompositeDisposable(); - this.preferencesHelper = preferencesHelper; - } - - @Override - public void attachView(UserDetailsView mvpView) { - super.attachView(mvpView); - } - - @Override - public void detachView() { - super.detachView(); - compositeDisposables.clear(); - } - - /** - * Fetches Details about Client from the server as {@link Client} and notifies the view to - * display the details. And in case of any error during fetching the required details it - * notifies the view. - */ - public void getUserDetails() { - checkViewAttached(); - getMvpView().showProgress(); - compositeDisposables.add(dataManager.getCurrentClient() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().hideProgress(); - getMvpView().showError(context.getString(R.string.error_fetching_client)); - } - - @Override - public void onNext(Client client) { - getMvpView().hideProgress(); - if (client != null) { - getMvpView().showUserDetails(client); - } else { - getMvpView().showError(context - .getString(R.string.error_client_not_found)); - } - } - }) - ); - } - - /** - * Fetches Client image from the server in {@link Base64} format which is then decoded into a - * {@link Bitmap} after which the view notified to display it. - */ - public void getUserImage() { - checkViewAttached(); - setUserProfile(preferencesHelper.getUserProfileImage()); - - compositeDisposables.add(dataManager.getClientImage() - .observeOn(Schedulers.newThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - getMvpView().showUserImage(null); - } - - @Override - public void onNext(ResponseBody response) { - try { - - final String encodedString = response.string(); - - //removing 'data:image/jpg;base64' from the response - //the response is of the form of 'data:image/jpg;base64, .....' - final String pureBase64Encoded = - encodedString.substring(encodedString.indexOf(',') + 1); - preferencesHelper.setUserProfileImage(pureBase64Encoded); - setUserProfile(pureBase64Encoded); - } catch (IOException e) { - Log.e("userimage", e.getMessage()); - } - } - }) - ); - } - - public void setUserProfile(String image) { - if (image == null) { - return; - } - final byte[] decodedBytes = Base64.decode(image, Base64.DEFAULT); - Bitmap decodedBitmap = ImageUtil.getInstance().compressImage(decodedBytes); - getMvpView().showUserImage(decodedBitmap); - } - - public void registerNotification(final String token) { - checkViewAttached(); - final NotificationRegisterPayload payload = new - NotificationRegisterPayload(preferencesHelper.getClientId(), token); - compositeDisposables.add(dataManager.registerNotification(payload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - Log.e(UserDetailsPresenter.class.getSimpleName(), e.toString()); - if (e instanceof HttpException && ((HttpException) e).code() == 500) { - getUserNotificationId(payload, token); - } - } - - @Override - public void onNext(ResponseBody responseBody) { - preferencesHelper.setSentTokenToServer(true); - preferencesHelper.saveGcmToken(token); - } - })); - } - - private void getUserNotificationId(final NotificationRegisterPayload payload, final String - token) { - checkViewAttached(); - compositeDisposables.add(dataManager.getUserNotificationId(preferencesHelper.getClientId()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - Log.e(UserDetailsPresenter.class.getSimpleName(), e.toString()); - } - - @Override - public void onNext(NotificationUserDetail userDetail) { - updateRegistrationNotification(userDetail.getId(), payload, token); - } - })); - } - - private void updateRegistrationNotification(long id, NotificationRegisterPayload payload, - final String token) { - checkViewAttached(); - compositeDisposables.add(dataManager.updateRegisterNotification(id, payload) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(new DisposableObserver() { - @Override - public void onComplete() { - - } - - @Override - public void onError(Throwable e) { - Log.e(UserDetailsPresenter.class.getSimpleName(), e.toString()); - } - - @Override - public void onNext(ResponseBody responseBody) { - preferencesHelper.setSentTokenToServer(true); - preferencesHelper.saveGcmToken(token); - } - })); - } -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/UserDetailsPresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/UserDetailsPresenter.kt new file mode 100644 index 0000000000..17d99e8dd1 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/UserDetailsPresenter.kt @@ -0,0 +1,181 @@ +package org.mifos.mobile.presenters + +import android.content.Context +import android.graphics.Bitmap +import android.util.Base64 +import android.util.Log + +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.observers.DisposableObserver +import io.reactivex.schedulers.Schedulers + +import okhttp3.ResponseBody + +import org.mifos.mobile.R +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.notification.NotificationRegisterPayload +import org.mifos.mobile.models.notification.NotificationUserDetail +import org.mifos.mobile.presenters.base.BasePresenter +import org.mifos.mobile.ui.views.UserDetailsView +import org.mifos.mobile.utils.ImageUtil.Companion.instance + +import retrofit2.HttpException + +import java.io.IOException + +import javax.inject.Inject + +/** + * Created by naman on 07/04/17. + */ +class UserDetailsPresenter @Inject constructor( + @ApplicationContext context: Context?, private val dataManager: DataManager?, + private val preferencesHelper: PreferencesHelper? +) : BasePresenter(context) { + + private val compositeDisposables: CompositeDisposable = CompositeDisposable() + + override fun detachView() { + super.detachView() + compositeDisposables.clear() + } + + /** + * Fetches Details about Client from the server as [Client] and notifies the view to + * display the details. And in case of any error during fetching the required details it + * notifies the view. + */ + val userDetails: Unit + get() { + checkViewAttached() + mvpView?.showProgress() + dataManager?.currentClient + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.hideProgress() + mvpView?.showError(context?.getString(R.string.error_fetching_client)) + } + + override fun onNext(client: Client) { + mvpView?.hideProgress() + mvpView?.showUserDetails(client) + } + })?.let { + compositeDisposables.add(it + ) + } + }//removing 'data:image/jpg;base64' from the response + //the response is of the form of 'data:image/jpg;base64, .....' + /** + * Fetches Client image from the server in [Base64] format which is then decoded into a + * [Bitmap] after which the view notified to display it. + */ + val userImage: Unit + get() { + checkViewAttached() + setUserProfile(preferencesHelper?.userProfileImage) + dataManager?.clientImage + ?.observeOn(Schedulers.newThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + mvpView?.showUserImage(null) + } + + override fun onNext(response: ResponseBody) { + try { + val encodedString = response.string() + + //removing 'data:image/jpg;base64' from the response + //the response is of the form of 'data:image/jpg;base64, .....' + val pureBase64Encoded = encodedString.substring(encodedString.indexOf(',') + 1) + preferencesHelper?.userProfileImage = pureBase64Encoded + setUserProfile(pureBase64Encoded) + } catch (e: IOException) { + Log.e("userimage", e.message) + } + } + })?.let { + compositeDisposables.add(it + ) + } + } + + fun setUserProfile(image: String?) { + if (image == null) { + return + } + val decodedBytes = Base64.decode(image, Base64.DEFAULT) + val decodedBitmap = instance?.compressImage(decodedBytes) + mvpView?.showUserImage(decodedBitmap) + } + + fun registerNotification(token: String) { + checkViewAttached() + val payload = NotificationRegisterPayload(preferencesHelper?.clientId!!, token) + dataManager?.registerNotification(payload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + Log.e(UserDetailsPresenter::class.java.simpleName, e.toString()) + if (e is HttpException && e.code() == 500) { + getUserNotificationId(payload, token) + } + } + + override fun onNext(responseBody: ResponseBody) { + preferencesHelper.setSentTokenToServer(true) + preferencesHelper.saveGcmToken(token) + } + })?.let { compositeDisposables.add(it) } + } + + private fun getUserNotificationId(payload: NotificationRegisterPayload, token: String) { + checkViewAttached() + dataManager?.getUserNotificationId(preferencesHelper?.clientId!!) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + Log.e(UserDetailsPresenter::class.java.simpleName, e.toString()) + } + + override fun onNext(userDetail: NotificationUserDetail) { + updateRegistrationNotification(userDetail.id.toLong(), payload, token) + } + })?.let { compositeDisposables.add(it) } + } + + private fun updateRegistrationNotification( + id: Long, payload: NotificationRegisterPayload, + token: String + ) { + checkViewAttached() + dataManager?.updateRegisterNotification(id, payload) + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { + override fun onComplete() {} + override fun onError(e: Throwable) { + Log.e(UserDetailsPresenter::class.java.simpleName, e.toString()) + } + + override fun onNext(responseBody: ResponseBody) { + preferencesHelper?.setSentTokenToServer(true) + preferencesHelper?.saveGcmToken(token) + } + })?.let { compositeDisposables.add(it) } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/base/BasePresenter.java b/app/src/main/java/org/mifos/mobile/presenters/base/BasePresenter.java deleted file mode 100644 index 887db7df28..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/base/BasePresenter.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.mifos.mobile.presenters.base; - -import android.content.Context; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * @author ishan - * @since 19/05/16 - */ -public class BasePresenter implements Presenter { - - protected Context context; - private T mMvpView; - - protected BasePresenter(Context context) { - this.context = context; - } - - @Override - public void attachView(T mvpView) { - mMvpView = mvpView; - } - - @Override - public void detachView() { - mMvpView = null; - } - - public boolean isViewAttached() { - return mMvpView != null; - } - - public T getMvpView() { - return mMvpView; - } - - public void checkViewAttached() { - if (!isViewAttached()) throw new MvpViewNotAttachedException(); - } - - public static class MvpViewNotAttachedException extends RuntimeException { - public MvpViewNotAttachedException() { - super("Please call Presenter.attachView(MvpView) before" + - " requesting data to the Presenter"); - } - } - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/base/BasePresenter.kt b/app/src/main/java/org/mifos/mobile/presenters/base/BasePresenter.kt new file mode 100644 index 0000000000..ff95df0a54 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/base/BasePresenter.kt @@ -0,0 +1,32 @@ +package org.mifos.mobile.presenters.base + +import android.content.Context + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * @author ishan + * @since 19/05/16 + */ +open class BasePresenter protected constructor(protected var context: Context?) : Presenter { + var mvpView: T? = null + private set + + override fun attachView(mvpView: T) { + this.mvpView = mvpView + } + + override fun detachView() { + mvpView = null + } + + val isViewAttached: Boolean + get() = mvpView != null + + fun checkViewAttached() { + if (!isViewAttached) throw MvpViewNotAttachedException() + } + + class MvpViewNotAttachedException : RuntimeException("Please call Presenter.attachView(MvpView) before" + + " requesting data to the Presenter") +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/presenters/base/Presenter.java b/app/src/main/java/org/mifos/mobile/presenters/base/Presenter.java deleted file mode 100644 index db717e5fc2..0000000000 --- a/app/src/main/java/org/mifos/mobile/presenters/base/Presenter.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.mifos.mobile.presenters.base; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * @author ishan - * @since 19/05/16 - */ -public interface Presenter { - - void attachView(V mvpView); - - void detachView(); - -} diff --git a/app/src/main/java/org/mifos/mobile/presenters/base/Presenter.kt b/app/src/main/java/org/mifos/mobile/presenters/base/Presenter.kt new file mode 100644 index 0000000000..50286db1ab --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/presenters/base/Presenter.kt @@ -0,0 +1,15 @@ +package org.mifos.mobile.presenters.base + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * @author ishan + * @since 19/05/16 + */ +interface Presenter { + + fun attachView(mvpView: V) + + fun detachView() + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/AboutUsActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/AboutUsActivity.java deleted file mode 100644 index 6c6cf3c586..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/AboutUsActivity.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.AboutUsFragment; - -/** - * @author Rajan Maurya - * On 11/03/19. - */ -public class AboutUsActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_container); - setToolbarTitle(getString(R.string.about_us)); - showBackButton(); - replaceFragment(AboutUsFragment.newInstance(), false, R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/AboutUsActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/AboutUsActivity.kt new file mode 100644 index 0000000000..62b6239f1a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/AboutUsActivity.kt @@ -0,0 +1,22 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.AboutUsFragment + +/** + * @author Rajan Maurya + * On 11/03/19. + */ +class AboutUsActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_container) + setToolbarTitle(getString(R.string.about_us)) + showBackButton() + replaceFragment(AboutUsFragment.newInstance(), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/AccountOverviewActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/AccountOverviewActivity.java deleted file mode 100644 index ca7d729295..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/AccountOverviewActivity.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.AccountOverviewFragment; - -/** - * @author Rajan Maurya - * On 16/10/17. - */ -public class AccountOverviewActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_container); - replaceFragment(AccountOverviewFragment.newInstance(), false, R.id.container); - showBackButton(); - hideToolbarElevation(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/AccountOverviewActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/AccountOverviewActivity.kt new file mode 100644 index 0000000000..9c1adc76d1 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/AccountOverviewActivity.kt @@ -0,0 +1,22 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.AccountOverviewFragment + +/** + * @author Rajan Maurya + * On 16/10/17. + */ +class AccountOverviewActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_container) + replaceFragment(AccountOverviewFragment.newInstance(), false, R.id.container) + showBackButton() + hideToolbarElevation() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/AddBeneficiaryActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/AddBeneficiaryActivity.java deleted file mode 100644 index 9134a11e6b..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/AddBeneficiaryActivity.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.BeneficiaryAddOptionsFragment; - -/** - * @author Rajan Maurya - * On 04/06/18. - */ -public class AddBeneficiaryActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_container); - showBackButton(); - replaceFragment(BeneficiaryAddOptionsFragment.newInstance(), false, R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/AddBeneficiaryActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/AddBeneficiaryActivity.kt new file mode 100644 index 0000000000..a972521896 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/AddBeneficiaryActivity.kt @@ -0,0 +1,21 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.BeneficiaryAddOptionsFragment + +/** + * @author Rajan Maurya + * On 04/06/18. + */ +class AddBeneficiaryActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_container) + showBackButton() + replaceFragment(BeneficiaryAddOptionsFragment.newInstance(), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/EditUserDetailActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/EditUserDetailActivity.java deleted file mode 100644 index a104bd6dae..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/EditUserDetailActivity.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.mifos.mobile.ui.activities; - -/* - * Created by saksham on 14/July/2018 - */ - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.UpdatePasswordFragment; - -import butterknife.ButterKnife; - -public class EditUserDetailActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_edit_user_detail); - - ButterKnife.bind(this); - setToolbarTitle(getString(R.string.string_and_string, getString(R.string.edit), - getString(R.string.user_details))); - showBackButton(); - - replaceFragment(UpdatePasswordFragment.newInstance(), false, R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/EditUserDetailActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/EditUserDetailActivity.kt new file mode 100644 index 0000000000..78c26b7256 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/EditUserDetailActivity.kt @@ -0,0 +1,25 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.UpdatePasswordFragment + +/* +* Created by saksham on 14/July/2018 +*/ +class EditUserDetailActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_edit_user_detail) + ButterKnife.bind(this) + setToolbarTitle(getString(R.string.string_and_string, getString(R.string.edit), + getString(R.string.user_details))) + showBackButton() + replaceFragment(UpdatePasswordFragment.newInstance(), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/HelpActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/HelpActivity.java deleted file mode 100644 index f470df5df7..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/HelpActivity.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.HelpFragment; - -/** - * @author Rajan Maurya - * On 11/03/19. - */ -public class HelpActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_container); - setToolbarTitle(getString(R.string.help)); - showBackButton(); - replaceFragment(HelpFragment.newInstance(), false, R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/HelpActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/HelpActivity.kt new file mode 100644 index 0000000000..6563575a66 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/HelpActivity.kt @@ -0,0 +1,22 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.HelpFragment + +/** + * @author Rajan Maurya + * On 11/03/19. + */ +class HelpActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_container) + setToolbarTitle(getString(R.string.help)) + showBackButton() + replaceFragment(HelpFragment.newInstance(), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/HomeActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/HomeActivity.java deleted file mode 100644 index 761c304a3f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/HomeActivity.java +++ /dev/null @@ -1,476 +0,0 @@ -package org.mifos.mobile.ui.activities; - - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.Bitmap; -import android.os.Bundle; -import android.os.Handler; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.view.inputmethod.InputMethodManager; -import android.widget.ImageView; -import android.widget.TextView; -import android.widget.Toast; - -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.GoogleApiAvailability; -import com.google.android.material.navigation.NavigationView; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.presenters.UserDetailsPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.AccountType; -import org.mifos.mobile.ui.enums.ChargeType; -import org.mifos.mobile.ui.fragments.BeneficiaryListFragment; -import org.mifos.mobile.ui.fragments.ClientAccountsFragment; -import org.mifos.mobile.ui.fragments.ClientChargeFragment; -import org.mifos.mobile.ui.fragments.HomeOldFragment; -import org.mifos.mobile.ui.fragments.NotificationFragment; -import org.mifos.mobile.ui.fragments.RecentTransactionsFragment; -import org.mifos.mobile.ui.fragments.ThirdPartyTransferFragment; -import org.mifos.mobile.ui.views.UserDetailsView; -import org.mifos.mobile.utils.CircularImageView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.TextDrawable; -import org.mifos.mobile.utils.Toaster; -import org.mifos.mobile.utils.fcm.RegistrationIntentService; - -import javax.inject.Inject; - -import androidx.appcompat.app.ActionBarDrawerToggle; -import androidx.core.content.ContextCompat; -import androidx.core.view.GravityCompat; -import androidx.drawerlayout.widget.DrawerLayout; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Vishwajeet - * @since 14/07/2016 - */ -public class HomeActivity extends BaseActivity implements UserDetailsView, NavigationView. - OnNavigationItemSelectedListener, View.OnClickListener { - - @BindView(R.id.navigation_view) - NavigationView navigationView; - - @BindView(R.id.drawer) - DrawerLayout drawerLayout; - - @Inject - PreferencesHelper preferencesHelper; - - @Inject - UserDetailsPresenter detailsPresenter; - - private TextView tvUsername; - private CircularImageView ivCircularUserProfilePicture; - private ImageView ivTextDrawableUserProfilePicture; - private long clientId; - private Bitmap userProfileBitmap; - private Client client; - private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; - private boolean isReceiverRegistered; - private int menuItem; - boolean doubleBackToExitPressedOnce = false; - - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - getActivityComponent().inject(this); - setContentView(R.layout.activity_home); - ButterKnife.bind(this); - clientId = preferencesHelper.getClientId(); - - setupNavigationBar(); - setToolbarElevation(); - setToolbarTitle(getString(R.string.home)); - replaceFragment(HomeOldFragment.newInstance(), false, R.id.container); - - if (getIntent() != null && getIntent().getBooleanExtra(getString(R.string.notification), - false)) { - replaceFragment(NotificationFragment.newInstance(), true, R.id.container); - } - - if (savedInstanceState == null) { - detailsPresenter.attachView(this); - detailsPresenter.getUserDetails(); - detailsPresenter.getUserImage(); - showUserImage(null); - } else { - client = savedInstanceState.getParcelable(Constants.USER_DETAILS); - detailsPresenter.setUserProfile(preferencesHelper.getUserProfileImage()); - showUserDetails(client); - } - - if (checkPlayServices() && !preferencesHelper.sentTokenToServerState()) { - // Start IntentService to register this application with GCM. - Intent intent = new Intent(this, RegistrationIntentService.class); - startService(intent); - } - - } - - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.USER_DETAILS, client); - } - - @Override - protected void onPause() { - LocalBroadcastManager.getInstance(this).unregisterReceiver(registerReceiver); - isReceiverRegistered = false; - super.onPause(); - } - - @Override - protected void onResume() { - super.onResume(); - if (!isReceiverRegistered) { - LocalBroadcastManager.getInstance(this).registerReceiver(registerReceiver, - new IntentFilter(Constants.REGISTER_ON_SERVER)); - isReceiverRegistered = true; - } - } - - /** - * Called whenever any item is selected in {@link NavigationView} - * - * @param item {@link MenuItem} which is selected by the user - */ - @Override - public boolean onNavigationItemSelected(MenuItem item) { - // select which item to open - setToolbarElevation(); - menuItem = item.getItemId(); - if (menuItem != R.id.item_settings && menuItem != R.id.item_share - && menuItem != R.id.item_about_us && menuItem != R.id.item_help) { - // If we have clicked something other than settings or share - // we can safely clear the back stack as a new fragment will replace - // the current fragment. - clearFragmentBackStack(); - } - switch (item.getItemId()) { - case R.id.item_home: - hideToolbarElevation(); - replaceFragment(HomeOldFragment.newInstance(), true, R.id.container); - break; - case R.id.item_accounts: - hideToolbarElevation(); - replaceFragment(ClientAccountsFragment.newInstance(AccountType.SAVINGS), - true, R.id.container); - break; - case R.id.item_recent_transactions: - replaceFragment(RecentTransactionsFragment.newInstance(), true, R.id.container); - break; - case R.id.item_charges: - replaceFragment(ClientChargeFragment.newInstance(clientId, ChargeType.CLIENT), true, - R.id.container); - break; - case R.id.item_third_party_transfer: - replaceFragment(ThirdPartyTransferFragment.newInstance(), true, R.id.container); - break; - case R.id.item_beneficiaries: - replaceFragment(BeneficiaryListFragment.newInstance(), true, R.id.container); - break; - case R.id.item_settings: - startActivity(new Intent(HomeActivity.this, SettingsActivity.class)); - break; - case R.id.item_about_us: - startActivity(new Intent(HomeActivity.this, AboutUsActivity.class)); - break; - case R.id.item_help: - startActivity(new Intent(HomeActivity.this, HelpActivity.class)); - break; - case R.id.item_share: - Intent i = new Intent(Intent.ACTION_SEND); - i.setType("text/plain"); - i.putExtra(Intent.EXTRA_TEXT, getString(R.string.playstore_link, - getString(R.string.share_msg), getApplication().getPackageName())); - startActivity(Intent.createChooser(i, getString(R.string.choose))); - break; - case R.id.item_logout: - showLogoutDialog(); - break; - } - - // close the drawer - drawerLayout.closeDrawer(GravityCompat.START); - return true; - } - - /** - * Asks users to confirm whether he want to logout or not - */ - private void showLogoutDialog() { - new MaterialDialog.Builder().init(HomeActivity.this) - .setCancelable(false) - .setMessage(R.string.dialog_logout) - .setPositiveButton(getString(R.string.logout), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - preferencesHelper.clear(); - Intent i = new Intent(HomeActivity.this, LoginActivity.class); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent. - FLAG_ACTIVITY_CLEAR_TASK); - startActivity(i); - finish(); - } - }) - .setNegativeButton(getString(R.string.cancel), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - setNavigationViewSelectedItem(R.id.item_home); - } - }) - .createMaterialDialog() - .show(); - } - - /** - * This method is used to set up the navigation drawer for - * self-service application - */ - private void setupNavigationBar() { - - navigationView.setNavigationItemSelectedListener(this); - - ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, - drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) { - - @Override - public void onDrawerClosed(View drawerView) { - super.onDrawerClosed(drawerView); - } - - @Override - public void onDrawerOpened(View drawerView) { - super.onDrawerOpened(drawerView); - hideKeyboard(drawerView); - } - }; - drawerLayout.addDrawerListener(actionBarDrawerToggle); - actionBarDrawerToggle.syncState(); - setupHeaderView(navigationView.getHeaderView(0)); - setUpBackStackListener(); - } - - /** - * Used for initializing values for HeaderView of NavigationView - * - * @param headerView Header view of NavigationView - */ - private void setupHeaderView(View headerView) { - tvUsername = ButterKnife.findById(headerView, R.id.tv_user_name); - ivCircularUserProfilePicture = ButterKnife.findById(headerView, - R.id.iv_circular_user_image); - ivTextDrawableUserProfilePicture = ButterKnife.findById(headerView, R.id.iv_user_image); - - ivTextDrawableUserProfilePicture.setOnClickListener(this); - ivCircularUserProfilePicture.setOnClickListener(this); - } - - /** - * Shows Client username in HeaderView of NavigationView - * - * @param client Contains details about the client - */ - @Override - public void showUserDetails(Client client) { - this.client = client; - preferencesHelper.setClientName(client.getDisplayName()); - tvUsername.setText(client.getDisplayName()); - } - - /** - * Displays UserProfile Picture in HeaderView in NavigationView - * - * @param bitmap UserProfile Picture - */ - @Override - public void showUserImage(final Bitmap bitmap) { - if (bitmap != null) { - runOnUiThread(new Runnable() { - @Override - public void run() { - userProfileBitmap = bitmap; - ivCircularUserProfilePicture.setImageBitmap(bitmap); - ivCircularUserProfilePicture.setVisibility(View.VISIBLE); - ivTextDrawableUserProfilePicture.setVisibility(View.GONE); - } - }); - } else { - runOnUiThread(new Runnable() { - @Override - public void run() { - String userName; - if (!preferencesHelper.getClientName().isEmpty()) { - userName = preferencesHelper.getClientName(); - } else { - userName = getString(R.string.app_name); - } - ivCircularUserProfilePicture.setVisibility(View.GONE); - ivTextDrawableUserProfilePicture.setVisibility(View.VISIBLE); - TextDrawable drawable = TextDrawable.builder() - .beginConfig() - .toUpperCase() - .endConfig() - .buildRound(userName.substring(0, 1), - ContextCompat.getColor( - HomeActivity.this, R.color.primary_dark)); - ivTextDrawableUserProfilePicture.setImageDrawable(drawable); - } - }); - } - } - - @Override - public void showProgress() { - //empty, no need to show/hide progress in headerview - } - - @Override - public void hideProgress() { - //empty - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message contains information about error occurred - */ - @Override - public void showError(String message) { - showToast(message, Toast.LENGTH_SHORT); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - detailsPresenter.detachView(); - } - - /** - * Handling back press - */ - @Override - public void onBackPressed() { - - if (drawerLayout.isDrawerOpen(GravityCompat.START)) { - drawerLayout.closeDrawer(GravityCompat.START); - return; - } - - Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container); - if (fragment instanceof HomeOldFragment) { - if (doubleBackToExitPressedOnce && stackCount() == 0) { - HomeActivity.this.finish(); - return; - } - this.doubleBackToExitPressedOnce = true; - Toaster.show(findViewById(android.R.id.content), getString(R.string.exit_message)); - new Handler().postDelayed(new Runnable() { - - @Override - public void run() { - doubleBackToExitPressedOnce = false; - } - }, 2000); - } - - if (stackCount() != 0) { - super.onBackPressed(); - } - } - - private void setUpBackStackListener() { - getSupportFragmentManager(). - addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { - @Override - public void onBackStackChanged() { - Fragment fragment = getSupportFragmentManager(). - findFragmentById(R.id.container); - setToolbarElevation(); - if (fragment instanceof HomeOldFragment) { - setNavigationViewSelectedItem(R.id.item_home); - } else if (fragment instanceof ClientAccountsFragment) { - hideToolbarElevation(); - setNavigationViewSelectedItem(R.id.item_accounts); - } else if (fragment instanceof RecentTransactionsFragment) { - setNavigationViewSelectedItem(R.id.item_recent_transactions); - } else if (fragment instanceof ClientChargeFragment) { - setNavigationViewSelectedItem(R.id.item_charges); - } else if (fragment instanceof ThirdPartyTransferFragment) { - setNavigationViewSelectedItem(R.id.item_third_party_transfer); - } else if (fragment instanceof BeneficiaryListFragment) { - setNavigationViewSelectedItem(R.id.item_beneficiaries); - } - } - }); - } - - public void setNavigationViewSelectedItem(int id) { - navigationView.setCheckedItem(id); - } - - @Override - public void onClick(View v) { - // Click Header to view full profile of User - startActivity(new Intent(HomeActivity.this, UserProfileActivity.class)); - drawerLayout.closeDrawer(GravityCompat.START); - } - - /** - * Check the device to make sure it has the Google Play Services APK. If - * it doesn't, display a dialog that allows users to download the APK from - * the Google Play Store or enable it in the device's system settings. - */ - private boolean checkPlayServices() { - GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); - int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); - if (resultCode != ConnectionResult.SUCCESS) { - if (apiAvailability.isUserResolvableError(resultCode)) { - apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) - .show(); - } else { - Log.i(HomeActivity.class.getName(), "This device is not supported."); - finish(); - } - return false; - } - return true; - } - - private BroadcastReceiver registerReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String token = intent.getStringExtra(Constants.TOKEN); - detailsPresenter.registerNotification(token); - } - }; - - public int getCheckedItem() { - return menuItem; - } - - public void hideKeyboard(View view) { - InputMethodManager inputManager = (InputMethodManager) this - .getSystemService(Context.INPUT_METHOD_SERVICE); - inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager - .RESULT_UNCHANGED_SHOWN); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/HomeActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/HomeActivity.kt new file mode 100644 index 0000000000..75004e97ff --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/HomeActivity.kt @@ -0,0 +1,391 @@ +package org.mifos.mobile.ui.activities + +import android.content.* +import android.graphics.Bitmap +import android.os.Bundle +import android.os.Handler +import android.util.Log +import android.view.MenuItem +import android.view.View +import android.view.inputmethod.InputMethodManager +import android.widget.ImageView +import android.widget.TextView +import android.widget.Toast + +import androidx.appcompat.app.ActionBarDrawerToggle +import androidx.core.content.ContextCompat +import androidx.core.view.GravityCompat +import androidx.drawerlayout.widget.DrawerLayout +import androidx.localbroadcastmanager.content.LocalBroadcastManager + +import butterknife.BindView +import butterknife.ButterKnife + +import com.google.android.gms.common.ConnectionResult +import com.google.android.gms.common.GoogleApiAvailability +import com.google.android.material.navigation.NavigationView + +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.presenters.UserDetailsPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.AccountType +import org.mifos.mobile.ui.enums.ChargeType +import org.mifos.mobile.ui.fragments.* +import org.mifos.mobile.ui.views.UserDetailsView +import org.mifos.mobile.utils.* +import org.mifos.mobile.utils.fcm.RegistrationIntentService + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 14/07/2016 + */ +class HomeActivity : BaseActivity(), UserDetailsView, NavigationView.OnNavigationItemSelectedListener, View.OnClickListener { + @JvmField + @BindView(R.id.navigation_view) + var navigationView: NavigationView? = null + + @JvmField + @BindView(R.id.drawer) + var drawerLayout: DrawerLayout? = null + + @JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + + @JvmField + @Inject + var detailsPresenter: UserDetailsPresenter? = null + private var tvUsername: TextView? = null + private var ivCircularUserProfilePicture: CircularImageView? = null + private var ivTextDrawableUserProfilePicture: ImageView? = null + private var clientId: Long? = 0 + private var userProfileBitmap: Bitmap? = null + private var client: Client? = null + private var isReceiverRegistered = false + var checkedItem = 0 + private set + var doubleBackToExitPressedOnce = false + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + activityComponent?.inject(this) + setContentView(R.layout.activity_home) + ButterKnife.bind(this) + clientId = preferencesHelper?.clientId + setupNavigationBar() + setToolbarElevation() + setToolbarTitle(getString(R.string.home)) + replaceFragment(HomeOldFragment.newInstance(), false, R.id.container) + if (intent != null && intent.getBooleanExtra(getString(R.string.notification), + false)) { + replaceFragment(NotificationFragment.newInstance(), true, R.id.container) + } + if (savedInstanceState == null) { + detailsPresenter?.attachView(this) + detailsPresenter?.userDetails + detailsPresenter?.userImage + showUserImage(null) + } else { + client = savedInstanceState.getParcelable(Constants.USER_DETAILS) + detailsPresenter?.setUserProfile(preferencesHelper?.userProfileImage) + showUserDetails(client) + } + if (checkPlayServices() && preferencesHelper?.sentTokenToServerState() == false) { + // Start IntentService to register this application with GCM. + val intent = Intent(this, RegistrationIntentService::class.java) + startService(intent) + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.USER_DETAILS, client) + } + + override fun onPause() { + LocalBroadcastManager.getInstance(this).unregisterReceiver(registerReceiver) + isReceiverRegistered = false + super.onPause() + } + + override fun onResume() { + super.onResume() + if (!isReceiverRegistered) { + LocalBroadcastManager.getInstance(this).registerReceiver(registerReceiver, + IntentFilter(Constants.REGISTER_ON_SERVER)) + isReceiverRegistered = true + } + } + + /** + * Called whenever any item is selected in [NavigationView] + * + * @param item [MenuItem] which is selected by the user + */ + override fun onNavigationItemSelected(item: MenuItem): Boolean { + // select which item to open + setToolbarElevation() + checkedItem = item.itemId + if (checkedItem != R.id.item_settings && checkedItem != R.id.item_share && checkedItem != R.id.item_about_us && checkedItem != R.id.item_help) { + // If we have clicked something other than settings or share + // we can safely clear the back stack as a new fragment will replace + // the current fragment. + clearFragmentBackStack() + } + when (item.itemId) { + R.id.item_home -> { + hideToolbarElevation() + replaceFragment(HomeOldFragment.newInstance(), true, R.id.container) + } + R.id.item_accounts -> { + hideToolbarElevation() + replaceFragment(ClientAccountsFragment.newInstance(AccountType.SAVINGS), + true, R.id.container) + } + R.id.item_recent_transactions -> replaceFragment(RecentTransactionsFragment.newInstance(), true, R.id.container) + R.id.item_charges -> replaceFragment(ClientChargeFragment.newInstance(clientId, ChargeType.CLIENT), true, + R.id.container) + R.id.item_third_party_transfer -> replaceFragment(ThirdPartyTransferFragment.newInstance(), true, R.id.container) + R.id.item_beneficiaries -> replaceFragment(BeneficiaryListFragment.newInstance(), true, R.id.container) + R.id.item_settings -> startActivity(Intent(this@HomeActivity, SettingsActivity::class.java)) + R.id.item_about_us -> startActivity(Intent(this@HomeActivity, AboutUsActivity::class.java)) + R.id.item_help -> startActivity(Intent(this@HomeActivity, HelpActivity::class.java)) + R.id.item_share -> { + val i = Intent(Intent.ACTION_SEND) + i.type = "text/plain" + i.putExtra(Intent.EXTRA_TEXT, getString(R.string.playstore_link, + getString(R.string.share_msg), application.packageName)) + startActivity(Intent.createChooser(i, getString(R.string.choose))) + } + R.id.item_logout -> showLogoutDialog() + } + + // close the drawer + drawerLayout?.closeDrawer(GravityCompat.START) + return true + } + + /** + * Asks users to confirm whether he want to logout or not + */ + private fun showLogoutDialog() { + MaterialDialog.Builder().init(this@HomeActivity) + .setCancelable(false) + .setMessage(R.string.dialog_logout) + .setPositiveButton(getString(R.string.logout), + DialogInterface.OnClickListener { _, _ -> + preferencesHelper?.clear() + val i = Intent(this@HomeActivity, LoginActivity::class.java) + i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK + startActivity(i) + finish() + }) + .setNegativeButton(getString(R.string.cancel), + DialogInterface.OnClickListener { _, _ -> setNavigationViewSelectedItem(R.id.item_home) }) + .createMaterialDialog() + .show() + } + + /** + * This method is used to set up the navigation drawer for + * self-service application + */ + private fun setupNavigationBar() { + navigationView?.setNavigationItemSelectedListener(this) + val actionBarDrawerToggle: ActionBarDrawerToggle = object : ActionBarDrawerToggle(this, + drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) { + + override fun onDrawerOpened(drawerView: View) { + super.onDrawerOpened(drawerView) + hideKeyboard(drawerView) + } + } + drawerLayout?.addDrawerListener(actionBarDrawerToggle) + actionBarDrawerToggle.syncState() + navigationView?.getHeaderView(0)?.let { setupHeaderView(it) } + setUpBackStackListener() + } + + /** + * Used for initializing values for HeaderView of NavigationView + * + * @param headerView Header view of NavigationView + */ + private fun setupHeaderView(headerView: View) { + tvUsername = ButterKnife.findById(headerView, R.id.tv_user_name) + ivCircularUserProfilePicture = ButterKnife.findById(headerView, + R.id.iv_circular_user_image) + ivTextDrawableUserProfilePicture = ButterKnife.findById(headerView, R.id.iv_user_image) + ivTextDrawableUserProfilePicture?.setOnClickListener(this) + ivCircularUserProfilePicture?.setOnClickListener(this) + } + + /** + * Shows Client username in HeaderView of NavigationView + * + * @param client Contains details about the client + */ + override fun showUserDetails(client: Client?) { + this.client = client + preferencesHelper?.clientName = client?.displayName + tvUsername?.text = client?.displayName + } + + /** + * Displays UserProfile Picture in HeaderView in NavigationView + * + * @param bitmap UserProfile Picture + */ + override fun showUserImage(bitmap: Bitmap?) { + if (bitmap != null) { + runOnUiThread { + userProfileBitmap = bitmap + ivCircularUserProfilePicture?.setImageBitmap(bitmap) + ivCircularUserProfilePicture?.visibility = View.VISIBLE + ivTextDrawableUserProfilePicture?.visibility = View.GONE + } + } else { + runOnUiThread { + val userName: String? = if (preferencesHelper?.clientName?.isEmpty() == false) { + preferencesHelper?.clientName + } else { + getString(R.string.app_name) + } + ivCircularUserProfilePicture?.visibility = View.GONE + ivTextDrawableUserProfilePicture?.visibility = View.VISIBLE + val drawable = TextDrawable.builder() + .beginConfig() + .toUpperCase() + .endConfig() + .buildRound(userName?.substring(0, 1), + ContextCompat.getColor( + this@HomeActivity, R.color.primary_dark)) + ivTextDrawableUserProfilePicture?.setImageDrawable(drawable) + } + } + } + + override fun showProgress() { + //empty, no need to show/hide progress in headerview + } + + override fun hideProgress() { + //empty + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message contains information about error occurred + */ + override fun showError(message: String?) { + showToast(message, Toast.LENGTH_SHORT) + } + + override fun onDestroy() { + super.onDestroy() + detailsPresenter?.detachView() + } + + /** + * Handling back press + */ + override fun onBackPressed() { + if (drawerLayout?.isDrawerOpen(GravityCompat.START) == true) { + drawerLayout?.closeDrawer(GravityCompat.START) + return + } + val fragment = supportFragmentManager.findFragmentById(R.id.container) + if (fragment is HomeOldFragment) { + if (doubleBackToExitPressedOnce && stackCount() == 0) { + finish() + return + } + doubleBackToExitPressedOnce = true + Toaster.show(findViewById(android.R.id.content), getString(R.string.exit_message)) + Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000) + } + if (stackCount() != 0) { + super.onBackPressed() + } + } + + private fun setUpBackStackListener() { + supportFragmentManager.addOnBackStackChangedListener { + val fragment = supportFragmentManager.findFragmentById(R.id.container) + setToolbarElevation() + when (fragment) { + is HomeOldFragment -> { + setNavigationViewSelectedItem(R.id.item_home) + } + is ClientAccountsFragment -> { + hideToolbarElevation() + setNavigationViewSelectedItem(R.id.item_accounts) + } + is RecentTransactionsFragment -> { + setNavigationViewSelectedItem(R.id.item_recent_transactions) + } + is ClientChargeFragment -> { + setNavigationViewSelectedItem(R.id.item_charges) + } + is ThirdPartyTransferFragment -> { + setNavigationViewSelectedItem(R.id.item_third_party_transfer) + } + is BeneficiaryListFragment -> { + setNavigationViewSelectedItem(R.id.item_beneficiaries) + } + } + } + } + + fun setNavigationViewSelectedItem(id: Int) { + navigationView?.setCheckedItem(id) + } + + override fun onClick(v: View) { + // Click Header to view full profile of User + startActivity(Intent(this@HomeActivity, UserProfileActivity::class.java)) + drawerLayout?.closeDrawer(GravityCompat.START) + } + + /** + * Check the device to make sure it has the Google Play Services APK. If + * it doesn't, display a dialog that allows users to download the APK from + * the Google Play Store or enable it in the device's system settings. + */ + private fun checkPlayServices(): Boolean { + val apiAvailability = GoogleApiAvailability.getInstance() + val resultCode = apiAvailability.isGooglePlayServicesAvailable(this) + if (resultCode != ConnectionResult.SUCCESS) { + if (apiAvailability.isUserResolvableError(resultCode)) { + apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) + .show() + } else { + Log.i(HomeActivity::class.java.name, "This device is not supported.") + finish() + } + return false + } + return true + } + + private val registerReceiver: BroadcastReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val token = intent.getStringExtra(Constants.TOKEN) + detailsPresenter?.registerNotification(token) + } + } + + fun hideKeyboard(view: View) { + val inputManager = this + .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.RESULT_UNCHANGED_SHOWN) + } + + companion object { + private const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000 + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/LoanAccountContainerActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/LoanAccountContainerActivity.java deleted file mode 100644 index 3242dbb958..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/LoanAccountContainerActivity.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.mifos.mobile.ui.activities; -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.LoanAccountsDetailFragment; -import org.mifos.mobile.utils.Constants; - -public class LoanAccountContainerActivity extends BaseActivity { - - private long loanId; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_container); - - loanId = getIntent().getExtras().getLong(Constants.LOAN_ID); - - replaceFragment(LoanAccountsDetailFragment.newInstance(loanId), false, R.id.container); - showBackButton(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/LoanAccountContainerActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/LoanAccountContainerActivity.kt new file mode 100644 index 0000000000..5ffa306e88 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/LoanAccountContainerActivity.kt @@ -0,0 +1,24 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.LoanAccountsDetailFragment +import org.mifos.mobile.utils.Constants + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ +class LoanAccountContainerActivity : BaseActivity() { + + private var loanId: Long = 0 + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_container) + loanId = intent?.extras?.getLong(Constants.LOAN_ID)!! + replaceFragment(LoanAccountsDetailFragment.newInstance(loanId), false, R.id.container) + showBackButton() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/LoanApplicationActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/LoanApplicationActivity.java deleted file mode 100644 index fcce3a9dab..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/LoanApplicationActivity.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.LoanState; -import org.mifos.mobile.ui.fragments.LoanApplicationFragment; - -public class LoanApplicationActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_loan_application); - if (savedInstanceState == null) { - replaceFragment(LoanApplicationFragment.newInstance(LoanState.CREATE), false, - R.id.container); - } - showBackButton(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/LoanApplicationActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/LoanApplicationActivity.kt new file mode 100644 index 0000000000..4ec112c68d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/LoanApplicationActivity.kt @@ -0,0 +1,21 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.LoanState +import org.mifos.mobile.ui.fragments.LoanApplicationFragment + +class LoanApplicationActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_loan_application) + if (savedInstanceState == null) { + replaceFragment(LoanApplicationFragment.newInstance(LoanState.CREATE), false, + R.id.container) + } + showBackButton() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/LoginActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/LoginActivity.java deleted file mode 100644 index d04a1d9924..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/LoginActivity.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.content.Intent; -import android.os.Bundle; -import android.view.View; -import android.widget.LinearLayout; -import android.widget.Toast; - -import com.google.android.material.textfield.TextInputLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.presenters.LoginPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.views.LoginView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.appcompat.widget.AppCompatButton; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * @author Vishwajeet - * @since 05/06/16 - */ - -public class LoginActivity extends BaseActivity implements LoginView { - - @Inject - LoginPresenter loginPresenter; - - @BindView(R.id.btn_login) - AppCompatButton btnLogin; - - @BindView(R.id.til_username) - TextInputLayout tilUsername; - - @BindView(R.id.til_password) - TextInputLayout tilPassword; - - @BindView(R.id.ll_login) - LinearLayout llLogin; - - private String userName; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - getActivityComponent().inject(this); - - setContentView(R.layout.activity_login); - ButterKnife.bind(this); - loginPresenter.attachView(this); - } - - /** - * Called when Login is user has successfully logged in - * - * @param userName Username of the user that successfully logged in! - */ - @Override - public void onLoginSuccess(String userName) { - this.userName = userName; - loginPresenter.loadClient(); - } - - /** - * Shows ProgressDialog when called - */ - @Override - public void showProgress() { - showProgressDialog(getString(R.string.progress_message_login)); - } - - /** - * Hides the progressDialog which is being shown - */ - @Override - public void hideProgress() { - hideProgressDialog(); - } - - /** - * Starts {@link PassCodeActivity} - */ - @Override - public void showPassCodeActivity() { - showToast(getString(R.string.toast_welcome, userName)); - startPassCodeActivity(); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param errorMessage Error message that tells the user about the problem. - */ - @Override - public void showMessage(String errorMessage) { - showToast(errorMessage, Toast.LENGTH_LONG); - llLogin.setVisibility(View.VISIBLE); - } - - @Override - public void showUsernameError(String error) { - tilUsername.setError(error); - } - - @Override - public void showPasswordError(String error) { - tilPassword.setError(error); - } - - @Override - public void clearUsernameError() { - tilUsername.setErrorEnabled(false); - } - - @Override - public void clearPasswordError() { - tilPassword.setErrorEnabled(false); - } - - /** - * Called when Login Button is clicked, used for logging in the user - */ - @OnClick(R.id.btn_login) - public void onLoginClicked() { - - final String username = tilUsername.getEditText().getEditableText().toString(); - final String password = tilPassword.getEditText().getEditableText().toString(); - - if (Network.isConnected(this)) { - loginPresenter.login(username, password); - } else { - Toaster.show(llLogin, getString(R.string.no_internet_connection)); - } - } - - @OnClick(R.id.btn_register) - public void onRegisterClicked() { - startActivity(new Intent(LoginActivity.this, RegistrationActivity.class)); - - } - - @Override - protected void onDestroy() { - super.onDestroy(); - loginPresenter.detachView(); - } - - /** - * Starts {@link PassCodeActivity} with {@code Constans.INTIAL_LOGIN} as true - */ - private void startPassCodeActivity() { - Intent intent = new Intent(LoginActivity.this, PassCodeActivity.class); - intent.putExtra(Constants.INTIAL_LOGIN, true); - startActivity(intent); - finish(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/LoginActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/LoginActivity.kt new file mode 100644 index 0000000000..5d37a66641 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/LoginActivity.kt @@ -0,0 +1,159 @@ +package org.mifos.mobile.ui.activities + +import android.content.Intent +import android.os.Bundle +import android.view.View +import android.widget.LinearLayout +import android.widget.Toast + +import androidx.appcompat.widget.AppCompatButton + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.google.android.material.textfield.TextInputLayout + +import org.mifos.mobile.R +import org.mifos.mobile.models.payload.LoginPayload +import org.mifos.mobile.presenters.LoginPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.views.LoginView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.Network +import org.mifos.mobile.utils.Toaster + +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 05/06/16 + */ +class LoginActivity : BaseActivity(), LoginView { + + @JvmField + @Inject + var loginPresenter: LoginPresenter? = null + + @JvmField + @BindView(R.id.btn_login) + var btnLogin: AppCompatButton? = null + + @JvmField + @BindView(R.id.til_username) + var tilUsername: TextInputLayout? = null + + @JvmField + @BindView(R.id.til_password) + var tilPassword: TextInputLayout? = null + + @JvmField + @BindView(R.id.ll_login) + var llLogin: LinearLayout? = null + private var userName: String? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + activityComponent?.inject(this) + setContentView(R.layout.activity_login) + ButterKnife.bind(this) + loginPresenter?.attachView(this) + } + + /** + * Called when Login is user has successfully logged in + * + * @param userName Username of the user that successfully logged in! + */ + override fun onLoginSuccess(userName: String?) { + this.userName = userName + loginPresenter?.loadClient() + } + + /** + * Shows ProgressDialog when called + */ + override fun showProgress() { + showProgressDialog(getString(R.string.progress_message_login)) + } + + /** + * Hides the progressDialog which is being shown + */ + override fun hideProgress() { + hideProgressDialog() + } + + /** + * Starts [PassCodeActivity] + */ + override fun showPassCodeActivity() { + showToast(getString(R.string.toast_welcome, userName)) + startPassCodeActivity() + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param errorMessage Error message that tells the user about the problem. + */ + override fun showMessage(errorMessage: String?) { + showToast(errorMessage!!, Toast.LENGTH_LONG) + llLogin?.visibility = View.VISIBLE + } + + override fun showUsernameError(error: String?) { + tilUsername?.error = error + } + + override fun showPasswordError(error: String?) { + tilPassword?.error = error + } + + override fun clearUsernameError() { + tilUsername?.isErrorEnabled = false + } + + override fun clearPasswordError() { + tilPassword?.isErrorEnabled = false + } + + /** + * Called when Login Button is clicked, used for logging in the user + */ + + @OnClick(R.id.btn_login) + fun onLoginClicked() { + val username = tilUsername?.editText?.editableText.toString() + val password = tilPassword?.editText?.editableText.toString() + if (Network.isConnected(this)) { + val payload = LoginPayload() + payload.username = username + payload.password = password + loginPresenter?.login(payload) + } else { + Toaster.show(llLogin, getString(R.string.no_internet_connection)) + } + } + + @OnClick(R.id.btn_register) + fun onRegisterClicked() { + startActivity(Intent(this@LoginActivity, RegistrationActivity::class.java)) + } + + override fun onDestroy() { + super.onDestroy() + loginPresenter?.detachView() + } + + /** + * Starts [PassCodeActivity] with `Constans.INTIAL_LOGIN` as true + */ + + private fun startPassCodeActivity() { + val intent = Intent(this@LoginActivity, PassCodeActivity::class.java) + intent.putExtra(Constants.INTIAL_LOGIN, true) + startActivity(intent) + finish() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/NotificationActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/NotificationActivity.java deleted file mode 100644 index 4590c973cd..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/NotificationActivity.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.NotificationFragment; - -public class NotificationActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_notification); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - replaceFragment(NotificationFragment.newInstance(), false, R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/NotificationActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/NotificationActivity.kt new file mode 100644 index 0000000000..972b10d8b6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/NotificationActivity.kt @@ -0,0 +1,17 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.NotificationFragment + +class NotificationActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_notification) + supportActionBar?.setDisplayHomeAsUpEnabled(true) + replaceFragment(NotificationFragment.newInstance(), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/PassCodeActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/PassCodeActivity.java deleted file mode 100644 index e469d9482d..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/PassCodeActivity.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.Manifest; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; -import android.view.View; - -import com.mifos.mobile.passcode.MifosPassCodeActivity; -import com.mifos.mobile.passcode.utils.EncryptionUtil; - -import org.mifos.mobile.R; -import org.mifos.mobile.utils.CheckSelfPermissionAndRequest; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.Toaster; - -public class PassCodeActivity extends MifosPassCodeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (!CheckSelfPermissionAndRequest.checkSelfPermission(this, - Manifest.permission.READ_PHONE_STATE)) { - requestPermission(); - } - } - - /** - * Uses {@link CheckSelfPermissionAndRequest} to check for runtime permissions - */ - private void requestPermission() { - CheckSelfPermissionAndRequest.requestPermission( - this, - Manifest.permission.READ_PHONE_STATE, - Constants.PERMISSIONS_REQUEST_READ_PHONE_STATE, - getResources().getString( - R.string.dialog_message_phone_state_permission_denied_prompt), - getResources().getString(R.string. - dialog_message_phone_state_permission_never_ask_again), - Constants.PERMISSIONS_READ_PHONE_STATE_STATUS); - } - - @Override - public int getLogo() { - return R.drawable.mifos_logo; - } - - @Override - public void startNextActivity() { - startActivity(new Intent(PassCodeActivity.this, HomeActivity.class)); - } - - @Override - public void startLoginActivity() { - new MaterialDialog.Builder().init(PassCodeActivity.this) - .setCancelable(false) - .setMessage(R.string.login_using_password_confirmation) - .setPositiveButton(getString(R.string.logout), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Intent i = new Intent(PassCodeActivity.this, - LoginActivity.class); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent. - FLAG_ACTIVITY_CLEAR_TASK); - startActivity(i); - finish(); - } - }) - .setNegativeButton(getString(R.string.cancel), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }) - .createMaterialDialog() - .show(); - } - - @Override - public void showToaster(View view, int msg) { - Toaster.show(view, msg); - } - - @Override - public int getEncryptionType() { - return EncryptionUtil.MOBILE_BANKING; - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/PassCodeActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/PassCodeActivity.kt new file mode 100644 index 0000000000..6aeb9921b3 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/PassCodeActivity.kt @@ -0,0 +1,74 @@ +package org.mifos.mobile.ui.activities + +import android.Manifest +import android.content.DialogInterface +import android.content.Intent +import android.os.Bundle +import android.view.View + +import com.mifos.mobile.passcode.MifosPassCodeActivity +import com.mifos.mobile.passcode.utils.EncryptionUtil + +import org.mifos.mobile.R +import org.mifos.mobile.utils.CheckSelfPermissionAndRequest +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.MaterialDialog +import org.mifos.mobile.utils.Toaster + +class PassCodeActivity : MifosPassCodeActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (!CheckSelfPermissionAndRequest.checkSelfPermission(this, + Manifest.permission.READ_PHONE_STATE)) { + requestPermission() + } + } + + /** + * Uses [CheckSelfPermissionAndRequest] to check for runtime permissions + */ + private fun requestPermission() { + CheckSelfPermissionAndRequest.requestPermission( + this, + Manifest.permission.READ_PHONE_STATE, + Constants.PERMISSIONS_REQUEST_READ_PHONE_STATE, + resources.getString( + R.string.dialog_message_phone_state_permission_denied_prompt), + resources.getString(R.string.dialog_message_phone_state_permission_never_ask_again), + Constants.PERMISSIONS_READ_PHONE_STATE_STATUS) + } + + override fun getLogo(): Int { + return R.drawable.mifos_logo + } + + override fun startNextActivity() { + startActivity(Intent(this@PassCodeActivity, HomeActivity::class.java)) + } + + override fun startLoginActivity() { + MaterialDialog.Builder().init(this@PassCodeActivity) + .setCancelable(false) + .setMessage(R.string.login_using_password_confirmation) + .setPositiveButton(getString(R.string.logout), + DialogInterface.OnClickListener { _, _ -> + val i = Intent(this@PassCodeActivity, + LoginActivity::class.java) + i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK + startActivity(i) + finish() + }) + .setNegativeButton(getString(R.string.cancel), + DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() }) + .createMaterialDialog() + .show() + } + + override fun showToaster(view: View, msg: Int) { + Toaster.show(view, msg) + } + + override fun getEncryptionType(): Int { + return EncryptionUtil.MOBILE_BANKING + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/PrivacyPolicyActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/PrivacyPolicyActivity.java deleted file mode 100644 index b9197c910f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/PrivacyPolicyActivity.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.os.Bundle; -import android.view.View; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.webkit.WebViewClient; -import android.widget.ProgressBar; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; - -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Rajan Maurya - * On 11/03/19. - */ -public class PrivacyPolicyActivity extends BaseActivity { - - @BindView(R.id.webView) - WebView webView; - - @BindView(R.id.progress_bar) - ProgressBar progressBar; - - private String showOrHideWebViewInitialUse = "show"; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_privacy_policy); - ButterKnife.bind(this); - setToolbarTitle(getString(R.string.privacy_policy)); - showBackButton(); - - // Force links and redirects to open in the WebView instead of in a browser - webView.setWebViewClient(new WebViewClient()); - - // Enable Javascript - WebSettings webSettings = webView.getSettings(); - webSettings.setJavaScriptEnabled(true); - - // REMOTE RESOURCE - webView.getSettings().setDomStorageEnabled(true); - webView.setOverScrollMode(WebView.OVER_SCROLL_NEVER); - webView.loadUrl(getString(R.string.privacy_policy_host_url)); - webView.setWebViewClient(new MyWebViewClient()); - } - - @Override - public void onBackPressed() { - if (webView.canGoBack()) { - webView.goBack(); - } else { - super.onBackPressed(); - } - } - - class MyWebViewClient extends WebViewClient { - - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) { - if (Uri.parse(url).getHost() - .endsWith(getString(R.string.privacy_policy_host))) { - return false; - } - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); - return true; - } - - @Override - public void onPageStarted(WebView view, String url, Bitmap favicon) { - // only make it invisible the FIRST time the app is run - if (showOrHideWebViewInitialUse.equals("show")) { - webView.setVisibility(View.INVISIBLE); - } - } - - @Override - public void onPageFinished(WebView view, String url) { - showOrHideWebViewInitialUse = "hide"; - progressBar.setVisibility(View.GONE); - view.setVisibility(View.VISIBLE); - super.onPageFinished(view, url); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/PrivacyPolicyActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/PrivacyPolicyActivity.kt new file mode 100644 index 0000000000..5df8968ff1 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/PrivacyPolicyActivity.kt @@ -0,0 +1,85 @@ +package org.mifos.mobile.ui.activities + +import android.content.Intent +import android.graphics.Bitmap +import android.net.Uri +import android.os.Bundle +import android.view.View +import android.webkit.WebView +import android.webkit.WebViewClient +import android.widget.ProgressBar + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity + +/** + * @author Rajan Maurya + * On 11/03/19. + */ +class PrivacyPolicyActivity : BaseActivity() { + + @JvmField + @BindView(R.id.webView) + var webView: WebView? = null + + @JvmField + @BindView(R.id.progress_bar) + var progressBar: ProgressBar? = null + private var showOrHideWebViewInitialUse = "show" + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_privacy_policy) + ButterKnife.bind(this) + setToolbarTitle(getString(R.string.privacy_policy)) + showBackButton() + + // Force links and redirects to open in the WebView instead of in a browser + webView?.webViewClient = WebViewClient() + + // Enable Javascript + val webSettings = webView?.settings + webSettings?.javaScriptEnabled = true + + // REMOTE RESOURCE + webView?.settings?.domStorageEnabled = true + webView?.overScrollMode = WebView.OVER_SCROLL_NEVER + webView?.loadUrl(getString(R.string.privacy_policy_host_url)) + webView?.webViewClient = MyWebViewClient() + } + + override fun onBackPressed() { + if (webView?.canGoBack() == true) { + webView?.goBack() + } else { + super.onBackPressed() + } + } + + internal inner class MyWebViewClient : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { + if (Uri.parse(url)?.host + ?.endsWith(getString(R.string.privacy_policy_host)) == true) { + return false + } + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) + return true + } + + override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) { + // only make it invisible the FIRST time the app is run + if (showOrHideWebViewInitialUse == "show") { + webView?.visibility = View.INVISIBLE + } + } + + override fun onPageFinished(view: WebView, url: String) { + showOrHideWebViewInitialUse = "hide" + progressBar?.visibility = View.GONE + view.visibility = View.VISIBLE + super.onPageFinished(view, url) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/RegistrationActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/RegistrationActivity.java deleted file mode 100644 index a95fb81612..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/RegistrationActivity.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.RegistrationFragment; - -public class RegistrationActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_registration); - replaceFragment(RegistrationFragment.newInstance(), false, R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/RegistrationActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/RegistrationActivity.kt new file mode 100644 index 0000000000..735d85988e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/RegistrationActivity.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.RegistrationFragment + +class RegistrationActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_registration) + replaceFragment(RegistrationFragment.newInstance(), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountApplicationActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountApplicationActivity.java deleted file mode 100644 index 2aea9eca22..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountApplicationActivity.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifos.mobile.ui.activities; - -/* - * Created by saksham on 30/June/2018 - */ - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.SavingsAccountState; -import org.mifos.mobile.ui.fragments.SavingsAccountApplicationFragment; - -public class SavingsAccountApplicationActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_savings_account_application); - setToolbarTitle(getString(R.string.apply_savings_account)); - showBackButton(); - replaceFragment(SavingsAccountApplicationFragment.newInstance(SavingsAccountState.CREATE, - null), false, R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountApplicationActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountApplicationActivity.kt new file mode 100644 index 0000000000..d01d5c6210 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountApplicationActivity.kt @@ -0,0 +1,23 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.SavingsAccountState +import org.mifos.mobile.ui.fragments.SavingsAccountApplicationFragment.Companion.newInstance + +/* +* Created by saksham on 30/June/2018 +*/ +class SavingsAccountApplicationActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_savings_account_application) + setToolbarTitle(getString(R.string.apply_savings_account)) + showBackButton() + replaceFragment(newInstance(SavingsAccountState.CREATE, + null), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountContainerActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountContainerActivity.java deleted file mode 100644 index 29c72da242..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountContainerActivity.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.SavingAccountsDetailFragment; -import org.mifos.mobile.utils.Constants; - -/** - * Created by Rajan Maurya on 05/03/17. - */ - -public class SavingsAccountContainerActivity extends BaseActivity { - - private long savingsId; - public static boolean transferSuccess = false; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_container); - - savingsId = getIntent().getExtras().getLong(Constants.SAVINGS_ID); - - replaceFragment(SavingAccountsDetailFragment.newInstance(savingsId), false, R.id.container); - showBackButton(); - } - - @Override - public void onBackPressed() { - int count = getSupportFragmentManager().getBackStackEntryCount(); - if (count == 2 && transferSuccess == true) { - getSupportFragmentManager().popBackStack(); - getSupportFragmentManager().popBackStack(); - transferSuccess = false; - } else { - super.onBackPressed(); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountContainerActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountContainerActivity.kt new file mode 100644 index 0000000000..acc58b3616 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/SavingsAccountContainerActivity.kt @@ -0,0 +1,38 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.SavingAccountsDetailFragment +import org.mifos.mobile.utils.Constants + +/** + * Created by Rajan Maurya on 05/03/17. + */ +class SavingsAccountContainerActivity : BaseActivity() { + + private var savingsId: Long = 0 + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_container) + savingsId = intent?.extras?.getLong(Constants.SAVINGS_ID)!! + replaceFragment(SavingAccountsDetailFragment.newInstance(savingsId), false, R.id.container) + showBackButton() + } + + override fun onBackPressed() { + val count = supportFragmentManager.backStackEntryCount + if (count == 2 && transferSuccess) { + supportFragmentManager.popBackStack() + supportFragmentManager.popBackStack() + transferSuccess = false + } else { + super.onBackPressed() + } + } + + companion object { + var transferSuccess = false + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SettingsActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/SettingsActivity.java deleted file mode 100644 index f734d934b3..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/SettingsActivity.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.content.Intent; -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.SettingsFragment; -import org.mifos.mobile.utils.Constants; - -import androidx.core.app.ActivityCompat; - -public class SettingsActivity extends BaseActivity { - - private boolean hasSettingsChanged; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_settings); - setToolbarTitle(getString(R.string.settings)); - showBackButton(); - replaceFragment(SettingsFragment.newInstance(), false, R.id.container); - if (getIntent().hasExtra(Constants.HAS_SETTINGS_CHANGED)) { - hasSettingsChanged = getIntent().getBooleanExtra(Constants.HAS_SETTINGS_CHANGED, - false); - } - } - - @Override - public void onBackPressed() { - super.onBackPressed(); - if (hasSettingsChanged) { - ActivityCompat.finishAffinity(this); - Intent i = new Intent(this, HomeActivity.class); - startActivity(i); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SettingsActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/SettingsActivity.kt new file mode 100644 index 0000000000..f33b1cb37a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/SettingsActivity.kt @@ -0,0 +1,36 @@ +package org.mifos.mobile.ui.activities + +import android.content.Intent +import android.os.Bundle + +import androidx.core.app.ActivityCompat + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.SettingsFragment +import org.mifos.mobile.utils.Constants + +class SettingsActivity : BaseActivity() { + + private var hasSettingsChanged = false + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_settings) + setToolbarTitle(getString(R.string.settings)) + showBackButton() + replaceFragment(SettingsFragment.newInstance(), false, R.id.container) + if (intent.hasExtra(Constants.HAS_SETTINGS_CHANGED)) { + hasSettingsChanged = intent.getBooleanExtra(Constants.HAS_SETTINGS_CHANGED, + false) + } + } + + override fun onBackPressed() { + super.onBackPressed() + if (hasSettingsChanged) { + ActivityCompat.finishAffinity(this) + val i = Intent(this, HomeActivity::class.java) + startActivity(i) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SplashActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/SplashActivity.java deleted file mode 100644 index 2bdfd0606d..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/SplashActivity.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.mifos.mobile.ui.activities; - -/* - * Created by saksham on 01/June/2018 - */ - -import android.content.Intent; -import android.os.Bundle; - -import com.mifos.mobile.passcode.utils.PasscodePreferencesHelper; - -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.utils.Constants; - -public class SplashActivity extends BaseActivity { - - PasscodePreferencesHelper passcodePreferencesHelper; - Intent intent; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - getActivityComponent().inject(this); - - passcodePreferencesHelper = new PasscodePreferencesHelper(this); - if (!passcodePreferencesHelper.getPassCode().isEmpty()) { - intent = new Intent(this, PassCodeActivity.class); - intent.putExtra(Constants.INTIAL_LOGIN, true); - } else { - intent = new Intent(this, LoginActivity.class); - } - startActivity(intent); - finish(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/SplashActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/SplashActivity.kt new file mode 100644 index 0000000000..9680fd65ec --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/SplashActivity.kt @@ -0,0 +1,31 @@ +package org.mifos.mobile.ui.activities + +import android.content.Intent +import android.os.Bundle + +import com.mifos.mobile.passcode.utils.PasscodePreferencesHelper +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.utils.Constants + +/* +* Created by saksham on 01/June/2018 +*/ +class SplashActivity : BaseActivity() { + + private var passcodePreferencesHelper: PasscodePreferencesHelper? = null + + override fun onCreate(savedInstanceState: Bundle?) { + val intent: Intent? + super.onCreate(savedInstanceState) + activityComponent?.inject(this) + passcodePreferencesHelper = PasscodePreferencesHelper(this) + if (passcodePreferencesHelper?.passCode?.isNotEmpty() == true) { + intent = Intent(this, PassCodeActivity::class.java) + intent.putExtra(Constants.INTIAL_LOGIN, true) + } else { + intent = Intent(this, LoginActivity::class.java) + } + startActivity(intent) + finish() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/UserProfileActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/UserProfileActivity.java deleted file mode 100644 index 8dda7489e8..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/UserProfileActivity.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.mifos.mobile.ui.activities; - -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.UserProfileFragment; - -public class UserProfileActivity extends BaseActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_user_profile); - replaceFragment(UserProfileFragment.newInstance(), false , R.id.container); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/UserProfileActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/UserProfileActivity.kt new file mode 100644 index 0000000000..9a95391b56 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/UserProfileActivity.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.activities + +import android.os.Bundle + +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.UserProfileFragment + +class UserProfileActivity : BaseActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_user_profile) + replaceFragment(UserProfileFragment.newInstance(), false, R.id.container) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/base/BaseActivity.java b/app/src/main/java/org/mifos/mobile/ui/activities/base/BaseActivity.java deleted file mode 100644 index 02697bf088..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/activities/base/BaseActivity.java +++ /dev/null @@ -1,251 +0,0 @@ -package org.mifos.mobile.ui.activities.base; - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.app.ProgressDialog; -import android.content.Context; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.inputmethod.InputMethodManager; -import android.widget.Toast; - -import com.mifos.mobile.passcode.BasePassCodeActivity; - -import org.mifos.mobile.MifosSelfServiceApp; -import org.mifos.mobile.R; -import org.mifos.mobile.injection.component.ActivityComponent; -import org.mifos.mobile.injection.component.DaggerActivityComponent; -import org.mifos.mobile.injection.module.ActivityModule; -import org.mifos.mobile.ui.activities.PassCodeActivity; -import org.mifos.mobile.ui.views.BaseActivityCallback; -import org.mifos.mobile.utils.LanguageHelper; - -import androidx.annotation.NonNull; -import androidx.appcompat.widget.Toolbar; -import androidx.core.view.ViewCompat; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentTransaction; - -/** - * @author ishan - * @since 08/07/16 - */ -@SuppressLint("Registered") -public class BaseActivity extends BasePassCodeActivity implements BaseActivityCallback { - - protected Toolbar toolbar; - private ActivityComponent activityComponent; - private ProgressDialog progress; - - @Override - public void setContentView(int layoutResID) { - super.setContentView(layoutResID); - toolbar = findViewById(R.id.toolbar); - if (toolbar != null) { - setSupportActionBar(toolbar); - setToolbarElevation(); - } - } - - /** - * Used for removing elevation from toolbar - */ - public void hideToolbarElevation() { - ViewCompat.setElevation(toolbar, 0); - } - - /** - * Used for setting toolbar elevation - */ - public void setToolbarElevation() { - ViewCompat.setElevation(toolbar, 8f); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - /** - * Used for dependency injection - * @return {@link ActivityComponent} which is used for injection - */ - public ActivityComponent getActivityComponent() { - if (activityComponent == null) { - activityComponent = DaggerActivityComponent.builder() - .activityModule(new ActivityModule(this)) - .applicationComponent(MifosSelfServiceApp.get(this).component()) - .build(); - } - return activityComponent; - } - - /** - * This method is use to provide back button feature in the toolbar of activities - */ - protected void showBackButton() { - if (getSupportActionBar() != null) { - getSupportActionBar().setHomeButtonEnabled(true); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - onBackPressed(); - break; - } - return super.onOptionsItemSelected(item); - } - - /** - * Displays a toast in current activity. In this method the duration - * supplied is Short by default. If you want to specify duration - * use {@link BaseActivity#showToast(String, int)} method. - * - * @param message Message that the toast must show. - */ - public void showToast(String message) { - showToast(message, Toast.LENGTH_SHORT); - } - - /** - * Displays a toast in current activity. The duration can of two types: - *

    - *
  • SHORT
  • - *
  • LONG
  • - *
- * - * @param message Message that the toast must show. - * @param toastType Duration for which the toast must be visible. - */ - public void showToast(@NonNull String message, @NonNull int toastType) { - Toast.makeText(BaseActivity.this, message, toastType).show(); - } - - /** - * Calls a method {@code showProgressDialog("Working")} which displays ProgressDialog - */ - public void showProgressDialog() { - showProgressDialog(getString(R.string.working)); - } - - /** - * Displays a ProgressDialog - * @param message Message you want to display in Progress Dialog - */ - @Override - public void showProgressDialog(String message) { - if (progress == null) { - progress = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER); - progress.setCancelable(false); - } - progress.setMessage(message); - progress.show(); - - } - - /** - * Hides the progress dialog if it is currently being shown - */ - @Override - public void hideProgressDialog() { - if (progress != null && progress.isShowing()) { - progress.dismiss(); - progress = null; - } - } - - /** - * Used for setting title of Toolbar - * @param title String you want to display as title - */ - public void setActionBarTitle(String title) { - if (getSupportActionBar() != null && getTitle() != null) { - setTitle(title); - } - } - - protected void setActionBarTitle(int title) { - setActionBarTitle(getResources().getString(title)); - } - - /** - * @return Returns toolbar linked with current activity - */ - public Toolbar getToolbar() { - return toolbar; - } - - /** - * Calls {@code setActionBarTitle()} to set Toolbar title - * @param title String you want to set as title - */ - @Override - public void setToolbarTitle(String title) { - setActionBarTitle(title); - } - - @Override - public Class getPassCodeClass() { - return PassCodeActivity.class; - } - - @Override - protected void attachBaseContext(Context base) { - super.attachBaseContext(LanguageHelper.onAttach(base)); - } - - /** - * Replace Fragment in FrameLayout Container. - * - * @param fragment Fragment - * @param addToBackStack Add to BackStack - * @param containerId Container Id - */ - public void replaceFragment(Fragment fragment, boolean addToBackStack, int containerId) { - invalidateOptionsMenu(); - String backStateName = fragment.getClass().getName(); - boolean fragmentPopped = getSupportFragmentManager().popBackStackImmediate(backStateName, - 0); - - if (!fragmentPopped && getSupportFragmentManager().findFragmentByTag(backStateName) == - null) { - FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); - transaction.replace(containerId, fragment, backStateName); - if (addToBackStack) { - transaction.addToBackStack(backStateName); - } - transaction.commit(); - } - } - - /** - * It pops all the fragments which are currently in the backStack - */ - public void clearFragmentBackStack() { - FragmentManager fm = getSupportFragmentManager(); - int backStackCount = getSupportFragmentManager().getBackStackEntryCount(); - for (int i = 0; i < backStackCount; i++) { - int backStackId = getSupportFragmentManager().getBackStackEntryAt(i).getId(); - fm.popBackStack(backStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE); - } - } - - public int stackCount() { - return getSupportFragmentManager().getBackStackEntryCount(); - } - - - public static void hideKeyboard(Context context) { - Activity activity = (Activity) context; - InputMethodManager inputMethodManager = - (InputMethodManager) context.getSystemService( - Activity.INPUT_METHOD_SERVICE); - inputMethodManager.hideSoftInputFromWindow( - activity.getCurrentFocus().getWindowToken(), 0); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/activities/base/BaseActivity.kt b/app/src/main/java/org/mifos/mobile/ui/activities/base/BaseActivity.kt new file mode 100644 index 0000000000..70a65baaf1 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/activities/base/BaseActivity.kt @@ -0,0 +1,221 @@ +package org.mifos.mobile.ui.activities.base + +import android.annotation.SuppressLint +import android.app.Activity +import android.app.ProgressDialog +import android.content.Context +import android.view.MenuItem +import android.view.inputmethod.InputMethodManager +import android.widget.Toast +import androidx.appcompat.widget.Toolbar +import androidx.core.view.ViewCompat +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import com.mifos.mobile.passcode.BasePassCodeActivity +import org.mifos.mobile.MifosSelfServiceApp +import org.mifos.mobile.R +import org.mifos.mobile.injection.component.ActivityComponent +import org.mifos.mobile.injection.component.DaggerActivityComponent +import org.mifos.mobile.injection.module.ActivityModule +import org.mifos.mobile.ui.activities.PassCodeActivity +import org.mifos.mobile.ui.views.BaseActivityCallback +import org.mifos.mobile.utils.LanguageHelper + +/** + * @author ishan + * @since 08/07/16 + */ +@SuppressLint("Registered") +open class BaseActivity : BasePassCodeActivity(), BaseActivityCallback { + /** + * @return Returns toolbar linked with current activity + */ + var toolbar: Toolbar? = null + protected set + + /** + * Used for dependency injection + * @return [ActivityComponent] which is used for injection + */ + var activityComponent: ActivityComponent? = null + get() { + if (field == null) { + field = DaggerActivityComponent.builder() + .activityModule(ActivityModule(this)) + .applicationComponent(MifosSelfServiceApp.get(this).component()) + .build() + } + return field + } + private set + private var progress: ProgressDialog? = null + override fun setContentView(layoutResID: Int) { + super.setContentView(layoutResID) + toolbar = findViewById(R.id.toolbar) + if (toolbar != null) { + setSupportActionBar(toolbar) + setToolbarElevation() + } + } + + /** + * Used for removing elevation from toolbar + */ + fun hideToolbarElevation() { + ViewCompat.setElevation(toolbar!!, 0f) + } + + /** + * Used for setting toolbar elevation + */ + fun setToolbarElevation() { + ViewCompat.setElevation(toolbar!!, 8f) + } + + /** + * This method is use to provide back button feature in the toolbar of activities + */ + protected fun showBackButton() { + if (supportActionBar != null) { + supportActionBar?.setHomeButtonEnabled(true) + supportActionBar?.setDisplayHomeAsUpEnabled(true) + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + android.R.id.home -> onBackPressed() + } + return super.onOptionsItemSelected(item) + } + + /** + * Displays a toast in current activity. In this method the duration + * supplied is Short by default. If you want to specify duration + * use [BaseActivity.showToast] method. + * + * @param message Message that the toast must show. + */ + fun showToast(message: String) { + showToast(message, Toast.LENGTH_SHORT) + } + + /** + * Displays a toast in current activity. The duration can of two types: + * + * * SHORT + * * LONG + * + * + * @param message Message that the toast must show. + * @param toastType Duration for which the toast must be visible. + */ + fun showToast(message: String?, toastType: Int) { + Toast.makeText(this@BaseActivity, message, toastType).show() + } + + /** + * Calls a method `showProgressDialog("Working")` which displays ProgressDialog + */ + fun showProgressDialog() { + showProgressDialog(getString(R.string.working)) + } + + /** + * Displays a ProgressDialog + * @param message Message you want to display in Progress Dialog + */ + override fun showProgressDialog(message: String?) { + if (progress == null) { + progress = ProgressDialog(this, ProgressDialog.STYLE_SPINNER) + progress?.setCancelable(false) + } + progress?.setMessage(message) + progress?.show() + } + + /** + * Hides the progress dialog if it is currently being shown + */ + override fun hideProgressDialog() { + if (progress != null && (progress?.isShowing == true)) { + progress?.dismiss() + progress = null + } + } + + /** + * Used for setting title of Toolbar + * @param title String you want to display as title + */ + private fun setActionBarTitle(title: String?) { + if (supportActionBar != null && getTitle() != null) { + setTitle(title) + } + } + + /** + * Calls `setActionBarTitle()` to set Toolbar title + * @param title String you want to set as title + */ + override fun setToolbarTitle(title: String?) { + setActionBarTitle(title) + } + + override fun getPassCodeClass(): Class<*> { + return PassCodeActivity::class.java + } + + override fun attachBaseContext(base: Context) { + super.attachBaseContext(LanguageHelper.onAttach(base)) + } + + /** + * Replace Fragment in FrameLayout Container. + * + * @param fragment Fragment + * @param addToBackStack Add to BackStack + * @param containerId Container Id + */ + fun replaceFragment(fragment: Fragment, addToBackStack: Boolean, containerId: Int) { + invalidateOptionsMenu() + val backStateName = fragment.javaClass.name + val fragmentPopped = supportFragmentManager.popBackStackImmediate(backStateName, + 0) + if (!fragmentPopped && supportFragmentManager.findFragmentByTag(backStateName) == + null) { + val transaction = supportFragmentManager.beginTransaction() + transaction.replace(containerId, fragment, backStateName) + if (addToBackStack) { + transaction.addToBackStack(backStateName) + } + transaction.commit() + } + } + + /** + * It pops all the fragments which are currently in the backStack + */ + fun clearFragmentBackStack() { + val fm = supportFragmentManager + val backStackCount = supportFragmentManager.backStackEntryCount + for (i in 0 until backStackCount) { + val backStackId = supportFragmentManager.getBackStackEntryAt(i).id + fm.popBackStack(backStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE) + } + } + + fun stackCount(): Int { + return supportFragmentManager.backStackEntryCount + } + + companion object { + fun hideKeyboard(context: Context) { + val activity = context as Activity + val inputMethodManager = context.getSystemService( + Activity.INPUT_METHOD_SERVICE) as InputMethodManager + inputMethodManager.hideSoftInputFromWindow( + activity.currentFocus?.windowToken, 0) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/AccountsSpinnerAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/AccountsSpinnerAdapter.java deleted file mode 100644 index f26fa16149..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/AccountsSpinnerAdapter.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.payload.AccountDetail; - -import java.util.List; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 19/03/18. - */ - -public class AccountsSpinnerAdapter extends ArrayAdapter { - - private final LayoutInflater mInflater; - private final List accountDetails; - private final int mResource; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_account_type) - TextView tvAccountType; - - public AccountsSpinnerAdapter(Context context, @LayoutRes int resource, List objects) { - super(context, resource, 0, objects); - - mInflater = LayoutInflater.from(context); - mResource = resource; - accountDetails = objects; - } - - @Override - public View getDropDownView(int position, @Nullable View convertView, - @NonNull ViewGroup parent) { - return createItemView(position, convertView, parent); - } - - @Override - public View getView(int position, @Nullable View convertView, - @NonNull ViewGroup parent) { - return createItemView(position, convertView, parent); - } - - private View createItemView(int position, View convertView, ViewGroup parent) { - final View view = mInflater.inflate(mResource, parent, false); - ButterKnife.bind(this, view); - AccountDetail accountDetail = accountDetails.get(position); - tvAccountNumber.setText(accountDetail.getAccountNumber()); - tvAccountType.setText(accountDetail.getAccountType()); - return view; - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/AccountsSpinnerAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/AccountsSpinnerAdapter.kt new file mode 100644 index 0000000000..59d94335d4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/AccountsSpinnerAdapter.kt @@ -0,0 +1,58 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ArrayAdapter +import android.widget.TextView + +import androidx.annotation.LayoutRes + +import butterknife.BindView +import butterknife.ButterKnife +import org.mifos.mobile.R +import org.mifos.mobile.models.payload.AccountDetail + + +/** + * Created by dilpreet on 19/03/18. + */ +class AccountsSpinnerAdapter(context: Context, @LayoutRes resource: Int, objects: MutableList) : + ArrayAdapter(context, resource, 0, objects as List) { + + private val mInflater: LayoutInflater = LayoutInflater.from(context) + private val accountDetails: MutableList = objects + private val mResource: Int = resource + + @JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @JvmField + @BindView(R.id.tv_account_type) + var tvAccountType: TextView? = null + override fun getDropDownView( + position: Int, convertView: View?, + parent: ViewGroup + ): View { + return createItemView(position, convertView, parent) + } + + override fun getView( + position: Int, convertView: View?, + parent: ViewGroup + ): View { + return createItemView(position, convertView, parent) + } + + private fun createItemView(position: Int, convertView: View?, parent: ViewGroup): View { + val view = mInflater.inflate(mResource, parent, false) + ButterKnife.bind(this, view) + val (accountNumber: String?, accountType) = accountDetails[position]!! + tvAccountNumber?.text = accountNumber + tvAccountType?.text = accountType + return view + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiaryListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiaryListAdapter.java deleted file mode 100644 index 025778884b..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiaryListAdapter.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.beneficiary.Beneficiary; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 15/6/17. - */ - -public class BeneficiaryListAdapter extends RecyclerView.Adapter { - - private Context context; - - private List beneficiaryList; - - @Inject - public BeneficiaryListAdapter(@ActivityContext Context context) { - this.context = context; - beneficiaryList = new ArrayList<>(); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.row_beneficiary, parent, false); - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - Beneficiary beneficiary = beneficiaryList.get(position); - ((ViewHolder) holder).tvAccountNumber.setText(beneficiary.getAccountNumber()); - ((ViewHolder) holder).tvName.setText(beneficiary.getName()); - ((ViewHolder) holder).tvOfficeName.setText(beneficiary.getOfficeName()); - } - - @Override - public int getItemCount() { - return beneficiaryList.size(); - } - - public void setBeneficiaryList(List beneficiaryList) { - this.beneficiaryList = beneficiaryList; - notifyDataSetChanged(); - } - - public class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_beneficiary_name) - TextView tvName; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_office_name) - TextView tvOfficeName; - - public ViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiaryListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiaryListAdapter.kt new file mode 100644 index 0000000000..ef99981683 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiaryListAdapter.kt @@ -0,0 +1,64 @@ +package org.mifos.mobile.ui.adapters + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import butterknife.BindView +import butterknife.ButterKnife +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.Beneficiary +import javax.inject.Inject + +/** + * Created by dilpreet on 15/6/17. + */ +class BeneficiaryListAdapter @Inject constructor() : + RecyclerView.Adapter() { + + private var beneficiaryList: List? = ArrayList() + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.row_beneficiary, parent, false) + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + if (beneficiaryList?.get(position) != null) { + val (_, name, officeName, _, _, accountNumber, transferLimit) = + beneficiaryList?.get(position)!! + (holder as ViewHolder).tvAccountNumber?.text = accountNumber + holder.tvName?.text = name + holder.tvOfficeName?.text = officeName + } + } + + override fun getItemCount(): Int { + return if (beneficiaryList != null) beneficiaryList!!.size + else 0 + } + + fun setBeneficiaryList(beneficiaryList: List?) { + this.beneficiaryList = beneficiaryList + notifyDataSetChanged() + } + + inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) { + @JvmField + @BindView(R.id.tv_beneficiary_name) + var tvName: TextView? = null + + @JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @JvmField + @BindView(R.id.tv_office_name) + var tvOfficeName: TextView? = null + + init { + ButterKnife.bind(this, itemView!!) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiarySpinnerAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiarySpinnerAdapter.java deleted file mode 100644 index 70a8f8de9a..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiarySpinnerAdapter.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -/* - * Created by saksham on 18/June/2018 - */ - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.beneficiary.BeneficiaryDetail; - -import java.util.List; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; - -public class BeneficiarySpinnerAdapter extends ArrayAdapter { - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_beneficiary_name) - TextView tvBeneficiaryName; - - int resource; - LayoutInflater layoutInflater; - Context context; - List list; - - public BeneficiarySpinnerAdapter(Context context, int resource, List list) { - super(context, resource, 0, list); - this.resource = resource; - this.context = context; - this.list = list; - layoutInflater = LayoutInflater.from(context); - } - - @NonNull - @Override - public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { - return createItemView(position, convertView, parent); - } - - @Override - public View getDropDownView(int position, @Nullable View convertView, - @NonNull ViewGroup parent) { - return createItemView(position, convertView, parent); - } - - public View createItemView(int position, View convertView, ViewGroup parent) { - View view = layoutInflater.inflate(resource, parent, false); - ButterKnife.bind(this, view); - - tvAccountNumber.setText(list.get(position).getAccountNumber()); - tvBeneficiaryName.setText(list.get(position).getBeneficiaryName()); - return view; - } - - @Nullable - @Override - public String getItem(int position) { - return list.get(position).getAccountNumber(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiarySpinnerAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiarySpinnerAdapter.kt new file mode 100644 index 0000000000..a036c0d25e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/BeneficiarySpinnerAdapter.kt @@ -0,0 +1,53 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ArrayAdapter +import android.widget.TextView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.BeneficiaryDetail + +/* +* Created by saksham on 18/June/2018 +*/ +class BeneficiarySpinnerAdapter(context: Context, private var resource: Int, var list: MutableList) : + ArrayAdapter(context, resource, 0, list as List) { + + @JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @JvmField + @BindView(R.id.tv_beneficiary_name) + var tvBeneficiaryName: TextView? = null + private var layoutInflater: LayoutInflater = LayoutInflater.from(context) + override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { + return createItemView(position, convertView, parent) + } + + override fun getDropDownView( + position: Int, convertView: View?, + parent: ViewGroup + ): View { + return createItemView(position, convertView, parent) + } + + private fun createItemView(position: Int, convertView: View?, parent: ViewGroup?): View { + val view = layoutInflater.inflate(resource, parent, false) + ButterKnife.bind(this, view) + tvAccountNumber?.text = list[position]?.accountNumber + tvBeneficiaryName?.text = list[position]?.beneficiaryName + return view + } + + override fun getItem(position: Int): String? { + return list[position]?.accountNumber + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/CheckBoxAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/CheckBoxAdapter.java deleted file mode 100644 index b6016f3c13..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/CheckBoxAdapter.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.content.res.ColorStateList; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.CheckboxStatus; - -import java.util.List; - -import javax.inject.Inject; - -import androidx.appcompat.widget.AppCompatCheckBox; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnCheckedChanged; -import butterknife.OnClick; - -/** - * Created by dilpreet on 3/7/17. - */ - -public class CheckBoxAdapter extends RecyclerView.Adapter { - - private Context context; - private List statusList; - - @Inject - public CheckBoxAdapter(@ActivityContext Context context) { - this.context = context; - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - - View v = LayoutInflater.from(parent.getContext()).inflate( - R.layout.row_checkbox, parent, false); - return new ViewHolder(v); - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - - CheckboxStatus statusModel = statusList.get(position); - - int[][] states = {{android.R.attr.state_checked}, {}}; - int[] colors = {statusModel.getColor(), statusModel.getColor()}; - - ((ViewHolder) holder).cbStatusSelect.setChecked(statusModel.isChecked()); - ((ViewHolder) holder).cbStatusSelect.setSupportButtonTintList(new ColorStateList(states, - colors)); - ((ViewHolder) holder).tvStatus.setText(statusModel.getStatus()); - } - - @Override - public int getItemCount() { - return statusList.size(); - } - - public void setStatusList(List statusList) { - this.statusList = statusList; - } - - public List getStatusList() { - return statusList; - } - - public class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.cb_status_select) - AppCompatCheckBox cbStatusSelect; - - @BindView(R.id.tv_status) - TextView tvStatus; - - public ViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - } - - @OnClick(R.id.ll_row_checkbox) - public void rowClicked() { - cbStatusSelect.setChecked(!cbStatusSelect.isChecked()); - } - - @OnCheckedChanged(R.id.cb_status_select) - public void checkChanges() { - statusList.get(getAdapterPosition()).setChecked(cbStatusSelect.isChecked()); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/CheckBoxAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/CheckBoxAdapter.kt new file mode 100644 index 0000000000..1b2d2315ba --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/CheckBoxAdapter.kt @@ -0,0 +1,69 @@ +package org.mifos.mobile.ui.adapters + +import android.content.res.ColorStateList +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.appcompat.widget.AppCompatCheckBox +import androidx.recyclerview.widget.RecyclerView +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnCheckedChanged +import butterknife.OnClick +import org.mifos.mobile.R +import org.mifos.mobile.models.CheckboxStatus +import javax.inject.Inject + +/** + * Created by dilpreet on 3/7/17. + */ +class CheckBoxAdapter @Inject constructor() : + RecyclerView.Adapter() { + + var statusList: List? = null + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val v = LayoutInflater.from(parent.context).inflate( + R.layout.row_checkbox, parent, false) + return ViewHolder(v) + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val (status, color, isChecked) = statusList?.get(position)!! + val states = arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf()) + val colors = intArrayOf(color, color) + (holder as ViewHolder).cbStatusSelect?.isChecked = isChecked + holder.cbStatusSelect?.supportButtonTintList = ColorStateList(states, + colors) + holder.tvStatus?.text = status + } + + override fun getItemCount(): Int { + return if (statusList != null) statusList!!.size + else 0 + } + + inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) { + @JvmField + @BindView(R.id.cb_status_select) + var cbStatusSelect: AppCompatCheckBox? = null + + @JvmField + @BindView(R.id.tv_status) + var tvStatus: TextView? = null + + @OnClick(R.id.ll_row_checkbox) + fun rowClicked() { + cbStatusSelect?.isChecked = (cbStatusSelect?.isChecked == false) + } + + @OnCheckedChanged(R.id.cb_status_select) + fun checkChanges() { + statusList!![adapterPosition]?.isChecked = (cbStatusSelect?.isChecked == true) + } + + init { + ButterKnife.bind(this, itemView!!) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ClientChargeAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/ClientChargeAdapter.java deleted file mode 100644 index 564b5b2c4d..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/ClientChargeAdapter.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Vishwajeet - * @since 17/8/16. - */ - -public class ClientChargeAdapter extends RecyclerView.Adapter { - private final Context context; - private List clientChargeList = new ArrayList<>(); - - @Inject - public ClientChargeAdapter(@ActivityContext Context context) { - this.context = context; - } - - public void setClientChargeList(List clientChargeList) { - this.clientChargeList = clientChargeList; - } - - public Charge getItem(int position) { - return clientChargeList.get(position); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - RecyclerView.ViewHolder vh; - View v = LayoutInflater.from(parent.getContext()).inflate( - R.layout.row_client_charge, parent, false); - vh = new ViewHolder(v); - return vh; - } - - // Binds the values for each of the stored variables to the view - // Also changes the color of the circle depending on whether the charge is active or not - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - if (holder instanceof RecyclerView.ViewHolder) { - - Charge charge = getItem(position); - String currencyRepresentation = charge.getCurrency().getDisplaySymbol(); - if (currencyRepresentation == null) { - currencyRepresentation = charge.getCurrency().getCode(); - } - ((ViewHolder) holder).tvAmountDue.setText(context.getString(R.string.string_and_string, - currencyRepresentation, CurrencyUtil.formatCurrency(context, - charge.getAmount()))); - ((ViewHolder) holder).tvAmountPaid.setText(context.getString(R.string.string_and_string, - currencyRepresentation, CurrencyUtil.formatCurrency(context, - charge.getAmountPaid()))); - ((ViewHolder) holder).tvAmountWaived.setText(context.getString(R.string. - string_and_string, currencyRepresentation, - CurrencyUtil.formatCurrency(context, charge.getAmountWaived()))); - ((ViewHolder) holder).tvAmountOutstanding.setText(context.getString(R.string. - string_and_string, currencyRepresentation, - CurrencyUtil.formatCurrency(context, charge.getAmountOutstanding()))); - ((ViewHolder) holder).tvClientName.setText(charge.getName()); - if (charge.getDueDate().size() > 0) { - ((ViewHolder) holder).tvDueDate.setText(DateHelper.getDateAsString(charge. - getDueDate())); - } - - if (charge.isIsPaid() || charge.isIsWaived() || charge.getPaid() || charge. - getWaived()) { - ((ViewHolder) holder).circle_status.setBackgroundColor(ContextCompat. - getColor(context, R.color.black)); - } else { - ((ViewHolder) holder).circle_status.setBackgroundColor(ContextCompat. - getColor(context, R.color.deposit_green)); - } - - } - - } - - - @Override - public int getItemCount() { - return clientChargeList.size(); - } - - public static class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_clientName) - TextView tvClientName; - - @BindView(R.id.tv_due_date) - TextView tvDueDate; - - @BindView(R.id.tv_amount) - TextView tvAmountDue; - - @BindView(R.id.tv_amount_paid) - TextView tvAmountPaid; - - @BindView(R.id.tv_amount_waived) - TextView tvAmountWaived; - - @BindView(R.id.tv_amount_outstanding) - TextView tvAmountOutstanding; - - @BindView(R.id.circle_status) - View circle_status; - - public ViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ClientChargeAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/ClientChargeAdapter.kt new file mode 100644 index 0000000000..7c77cb6454 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/ClientChargeAdapter.kt @@ -0,0 +1,114 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.Charge +import org.mifos.mobile.utils.CurrencyUtil.formatCurrency +import org.mifos.mobile.utils.DateHelper.getDateAsString + +import java.util.* +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 17/8/16. + */ +class ClientChargeAdapter @Inject constructor(@param:ActivityContext private val context: Context) : + RecyclerView.Adapter() { + + private var clientChargeList: List? = ArrayList() + fun setClientChargeList(clientChargeList: List?) { + this.clientChargeList = clientChargeList + } + + fun getItem(position: Int): Charge? { + return clientChargeList?.get(position) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val vh: RecyclerView.ViewHolder + val v = LayoutInflater.from(parent.context).inflate( + R.layout.row_client_charge, parent, false) + vh = ViewHolder(v) + return vh + } + + // Binds the values for each of the stored variables to the view + // Also changes the color of the circle depending on whether the charge is active or not + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val charge = getItem(position) + var currencyRepresentation = charge?.currency?.displaySymbol + if (currencyRepresentation == null) { + currencyRepresentation = charge?.currency?.code + } + (holder as ViewHolder).tvAmountDue?.text = context.getString(R.string.string_and_string, + currencyRepresentation, formatCurrency(context, + charge?.amount)) + holder.tvAmountPaid?.text = context.getString(R.string.string_and_string, + currencyRepresentation, formatCurrency(context, + charge?.amountPaid)) + holder.tvAmountWaived?.text = context.getString(R.string.string_and_string, currencyRepresentation, + formatCurrency(context, charge?.amountWaived)) + holder.tvAmountOutstanding?.text = context.getString(R.string.string_and_string, currencyRepresentation, + formatCurrency(context, charge?.amountOutstanding)) + holder.tvClientName?.text = charge?.name + if (charge?.dueDate?.isNotEmpty() == true) { + holder.tvDueDate?.text = getDateAsString(charge.dueDate) + } + if (charge?.isPaid == true || charge?.isWaived == true || charge?.paid == true || charge?.waived == true) { + holder.circle_status?.setBackgroundColor(ContextCompat.getColor(context, R.color.black)) + } else { + holder.circle_status?.setBackgroundColor(ContextCompat.getColor(context, R.color.deposit_green)) + } + } + + override fun getItemCount(): Int { + return if (clientChargeList != null) clientChargeList!!.size + else 0 + } + + class ViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) { + @JvmField + @BindView(R.id.tv_clientName) + var tvClientName: TextView? = null + + @JvmField + @BindView(R.id.tv_due_date) + var tvDueDate: TextView? = null + + @JvmField + @BindView(R.id.tv_amount) + var tvAmountDue: TextView? = null + + @JvmField + @BindView(R.id.tv_amount_paid) + var tvAmountPaid: TextView? = null + + @JvmField + @BindView(R.id.tv_amount_waived) + var tvAmountWaived: TextView? = null + + @JvmField + @BindView(R.id.tv_amount_outstanding) + var tvAmountOutstanding: TextView? = null + + @JvmField + @BindView(R.id.circle_status) + var circle_status: View? = null + + init { + ButterKnife.bind(this, v!!) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ClientListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/ClientListAdapter.java deleted file mode 100644 index 1b51266e3e..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/ClientListAdapter.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.client.Client; - -import java.util.List; - -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Vishwajeet - * @since 20/06/16 - */ - -public class ClientListAdapter extends RecyclerView.Adapter { - - LayoutInflater layoutInflater; - List listItems; - private Context mContext; - - public ClientListAdapter(Context context, List listItems) { - - layoutInflater = LayoutInflater.from(context); - this.listItems = listItems; - this.mContext = context; - } - - public Client getItem(int position) { - return listItems.get(position); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - RecyclerView.ViewHolder vh; - View v = LayoutInflater.from(parent.getContext()).inflate( - R.layout.row_client_name, parent, false); - vh = new ViewHolder(v); - return vh; - } - - @Override - public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { - if (holder instanceof RecyclerView.ViewHolder) { - - Client client = getItem(position); - ((ViewHolder) holder).tv_clientName.setText(client.getFirstname() + " " + client - .getLastname()); - ((ViewHolder) holder).tv_clientAccountNumber.setText(client.getAccountNo()); - - } - } - - @Override - public long getItemId(int i) { - return 0; - } - - @Override - public int getItemCount() { - return listItems.size(); - } - - - public static class ViewHolder extends RecyclerView.ViewHolder { - @BindView(R.id.tv_clientName) - TextView tv_clientName; - @BindView(R.id.tv_clientAccountNumber) - TextView tv_clientAccountNumber; - - public ViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ClientListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/ClientListAdapter.kt new file mode 100644 index 0000000000..2a555b80bd --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/ClientListAdapter.kt @@ -0,0 +1,62 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import butterknife.BindView +import butterknife.ButterKnife +import org.mifos.mobile.R +import org.mifos.mobile.models.client.Client + +/** + * @author Vishwajeet + * @since 20/06/16 + */ +class ClientListAdapter(context: Context, private var listItems: List) : RecyclerView.Adapter() { + var layoutInflater: LayoutInflater = LayoutInflater.from(context) + private val mContext: Context = context + fun getItem(position: Int): Client { + return listItems[position] + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val vh: RecyclerView.ViewHolder + val v = LayoutInflater.from(parent.context).inflate( + R.layout.row_client_name, parent, false) + vh = ViewHolder(v) + return vh + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val client = getItem(position) + (holder as ViewHolder).tv_clientName?.text = client.firstname + " " + client + .lastname + holder.tv_clientAccountNumber?.text = client.accountNo + } + + override fun getItemId(i: Int): Long { + return 0 + } + + override fun getItemCount(): Int { + return listItems.size + } + + class ViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) { + @JvmField + @BindView(R.id.tv_clientName) + var tv_clientName: TextView? = null + + @JvmField + @BindView(R.id.tv_clientAccountNumber) + var tv_clientAccountNumber: TextView? = null + + init { + ButterKnife.bind(this, v!!) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/FAQAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/FAQAdapter.java deleted file mode 100644 index 831cd8f82b..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/FAQAdapter.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.FAQ; -import org.mifos.mobile.utils.FaqDiffUtil; - -import java.util.ArrayList; - -import javax.inject.Inject; - -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.DiffUtil; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 12/8/17. - */ - -public class FAQAdapter extends RecyclerView.Adapter { - - private ArrayList faqArrayList; - private int alreadySelectedPosition; - private Context context; - - @Inject - public FAQAdapter(@ActivityContext Context context) { - faqArrayList = new ArrayList<>(); - this.context = context; - } - - public void setFaqArrayList(ArrayList faqArrayList) { - this.faqArrayList = faqArrayList; - alreadySelectedPosition = -1; - } - - public void updateList(ArrayList faqArrayList) { - DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new FaqDiffUtil(this.faqArrayList, - faqArrayList)); - diffResult.dispatchUpdatesTo(this); - setFaqArrayList(faqArrayList); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_faq, parent, false); - return new ViewHolder(v); - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - FAQ faq = faqArrayList.get(position); - - ((ViewHolder) holder).tvFaqQs.setText(faq.getQuestion()); - ((ViewHolder) holder).tvFaqAns.setText(faq.getAnswer()); - - if (faq.isSelected()) { - ((ViewHolder) holder).tvFaqAns.setVisibility(View.VISIBLE); - ((ViewHolder) holder).ivArrow.setImageDrawable(ContextCompat.getDrawable(context, - R.drawable.ic_arrow_up)); - } else { - ((ViewHolder) holder).tvFaqAns.setVisibility(View.GONE); - ((ViewHolder) holder).ivArrow.setImageDrawable(ContextCompat.getDrawable(context, - R.drawable.ic_arrow_drop_down)); - } - - } - - private void updateView(int position) { - if (alreadySelectedPosition == position) { - faqArrayList.get(alreadySelectedPosition).setSelected(false); - notifyItemChanged(alreadySelectedPosition); - alreadySelectedPosition = -1; - return; - } - if (alreadySelectedPosition != -1) { - faqArrayList.get(alreadySelectedPosition).setSelected(false); - notifyItemChanged(alreadySelectedPosition); - } - - faqArrayList.get(position).setSelected(true); - notifyItemChanged(position); - alreadySelectedPosition = position; - } - - @Override - public int getItemCount() { - return faqArrayList.size(); - } - - public class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_qs) - TextView tvFaqQs; - - @BindView(R.id.tv_ans) - TextView tvFaqAns; - - @BindView(R.id.ll_faq) - LinearLayout llFaq; - - @BindView(R.id.iv_arrow) - ImageView ivArrow; - - public ViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - } - - @OnClick(R.id.ll_faq) - public void faqHeaderClicked() { - updateView(getAdapterPosition()); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/FAQAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/FAQAdapter.kt new file mode 100644 index 0000000000..852bc59093 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/FAQAdapter.kt @@ -0,0 +1,119 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView + +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.FAQ +import org.mifos.mobile.utils.FaqDiffUtil + +import javax.inject.Inject + +/** + * Created by dilpreet on 12/8/17. + */ +class FAQAdapter @Inject constructor(@ActivityContext context: Context) : + RecyclerView.Adapter() { + + private var faqArrayList: ArrayList? + private var alreadySelectedPosition = 0 + private val context: Context + fun setFaqArrayList(faqArrayList: ArrayList?) { + this.faqArrayList = faqArrayList + alreadySelectedPosition = -1 + } + + fun updateList(faqArrayList: java.util.ArrayList?) { + val diffResult = DiffUtil.calculateDiff(FaqDiffUtil(this.faqArrayList, + faqArrayList)) + diffResult.dispatchUpdatesTo(this) + setFaqArrayList(faqArrayList) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val v = LayoutInflater.from(parent.context).inflate(R.layout.row_faq, parent, false) + return ViewHolder(v) + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val (question, answer, isSelected) = faqArrayList?.get(position)!! + (holder as ViewHolder).tvFaqQs?.text = question + holder.tvFaqAns?.text = answer + if (isSelected) { + holder.tvFaqAns?.visibility = View.VISIBLE + holder.ivArrow?.setImageDrawable(ContextCompat.getDrawable(context, + R.drawable.ic_arrow_up)) + } else { + holder.tvFaqAns?.visibility = View.GONE + holder.ivArrow?.setImageDrawable(ContextCompat.getDrawable(context, + R.drawable.ic_arrow_drop_down)) + } + } + + private fun updateView(position: Int) { + if (alreadySelectedPosition == position) { + faqArrayList?.get(alreadySelectedPosition)?.isSelected = false + notifyItemChanged(alreadySelectedPosition) + alreadySelectedPosition = -1 + return + } + if (alreadySelectedPosition != -1) { + faqArrayList?.get(alreadySelectedPosition)?.isSelected = false + notifyItemChanged(alreadySelectedPosition) + } + faqArrayList?.get(position)?.isSelected = true + notifyItemChanged(position) + alreadySelectedPosition = position + } + + override fun getItemCount(): Int { + return if (faqArrayList != null) faqArrayList!!.size + else 0 + } + + inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) { + @JvmField + @BindView(R.id.tv_qs) + var tvFaqQs: TextView? = null + + @JvmField + @BindView(R.id.tv_ans) + var tvFaqAns: TextView? = null + + @JvmField + @BindView(R.id.ll_faq) + var llFaq: LinearLayout? = null + + @JvmField + @BindView(R.id.iv_arrow) + var ivArrow: ImageView? = null + + @OnClick(R.id.ll_faq) + fun faqHeaderClicked() { + updateView(adapterPosition) + } + + init { + ButterKnife.bind(this, itemView!!) + } + } + + init { + faqArrayList = ArrayList() + this.context = context + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/GuarantorListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/GuarantorListAdapter.java deleted file mode 100644 index 082a8d7742..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/GuarantorListAdapter.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -/* - * Created by saksham on 24/July/2018 - */ - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.utils.DateHelper; - -import java.util.ArrayList; -import java.util.List; - -import androidx.cardview.widget.CardView; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -public class GuarantorListAdapter extends RecyclerView.Adapter { - - - List list; - Context context; - OnClickListener listener; - - public interface OnClickListener { - void setOnClickListener(int position); - } - - public GuarantorListAdapter(Context context, - OnClickListener listener) { - this.context = context; - list = new ArrayList<>(); - this.listener = listener; - } - - - @Override - public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - LayoutInflater inflater = LayoutInflater.from(context); - return new ViewHolder(inflater.inflate(R.layout.row_guarantor, parent, false)); - } - - @Override - public void onBindViewHolder(ViewHolder holder, final int position) { - holder.tvGuarantorName.setText(list.get(position).getFirstname() + " " - + list.get(position).getLastname()); - holder.tvJoinedDate.setText(DateHelper.getDateAsString(list.get(position) - .getJoinedDate())); - holder.cvContainer.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - listener.setOnClickListener(position); - } - }); - } - - @Override - public int getItemCount() { - return list.size(); - } - - public void setGuarantorList(List payload) { - this.list = payload; - notifyDataSetChanged(); - } - - public class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_guarantor_name) - TextView tvGuarantorName; - - @BindView(R.id.tv_joined_date) - TextView tvJoinedDate; - - @BindView(R.id.cv_container) - CardView cvContainer; - - public ViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/GuarantorListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/GuarantorListAdapter.kt new file mode 100644 index 0000000000..9197760f16 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/GuarantorListAdapter.kt @@ -0,0 +1,81 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView + +import androidx.cardview.widget.CardView +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.utils.DateHelper.getDateAsString + +import java.util.* + +/* +* Created by saksham on 24/July/2018 +*/ +class GuarantorListAdapter( + var context: Context?, + listener: OnClickListener +) : RecyclerView.Adapter() { + + var list: MutableList? + var listener: OnClickListener + + interface OnClickListener { + fun setOnClickListener(position: Int) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val inflater = LayoutInflater.from(context) + return ViewHolder(inflater.inflate(R.layout.row_guarantor, parent, false)) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + holder.tvGuarantorName?.text = (list?.get(position)?.firstname + " " + + list?.get(position)?.lastname) + holder.tvJoinedDate?.text = getDateAsString(list?.get(position) + ?.joinedDate) + holder.cvContainer?.setOnClickListener { listener.setOnClickListener(position) } + } + + override fun getItemCount(): Int { + return if (list?.size != null) list?.size!! + else 0 + } + + fun setGuarantorList(payload: MutableList?) { + list = payload + notifyDataSetChanged() + } + + inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) { + @JvmField + @BindView(R.id.tv_guarantor_name) + var tvGuarantorName: TextView? = null + + @JvmField + @BindView(R.id.tv_joined_date) + var tvJoinedDate: TextView? = null + + @JvmField + @BindView(R.id.cv_container) + var cvContainer: CardView? = null + + init { + ButterKnife.bind(this, itemView!!) + } + } + + init { + list = ArrayList() + this.listener = listener + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/LoanAccountsListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/LoanAccountsListAdapter.java deleted file mode 100644 index 4925420fec..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/LoanAccountsListAdapter.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.appcompat.widget.AppCompatImageView; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Vishwajeet - * @since 22/6/16. - */ -public class LoanAccountsListAdapter extends RecyclerView.Adapter { - private final Context context; - private List loanAccountsList = new ArrayList<>(); - - @Inject - public LoanAccountsListAdapter(@ActivityContext Context context) { - this.context = context; - } - - public void setLoanAccountsList(List loanAccountsList) { - this.loanAccountsList = loanAccountsList; - notifyDataSetChanged(); - } - - public List getLoanAccountsList() { - return loanAccountsList; - } - - public LoanAccount getItem(int position) { - return loanAccountsList.get(position); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - RecyclerView.ViewHolder vh; - View v = LayoutInflater.from(parent.getContext()).inflate( - R.layout.row_loan_account, parent, false); - vh = new ViewHolder(v); - return vh; - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - if (holder instanceof ViewHolder) { - - LoanAccount loanAccount = getItem(position); - ((ViewHolder) holder).tvClientLoanAccountNumber.setText(loanAccount.getAccountNo()); - ((ViewHolder) holder).tvLoanAccountProductName.setText(loanAccount.getProductName()); - ((ViewHolder) holder).tvAccountBalance.setVisibility(View.GONE); - - if (loanAccount.getStatus().getActive() && loanAccount.getInArrears()) { - - setLoanAccountsGeneralDetails(holder, R.color.red, context.getString(R.string. - string_and_string, context.getString(R.string.disbursement), DateHelper - .getDateAsString(loanAccount.getTimeline().getActualDisbursementDate()))); - setLoanAccountsDetails(((ViewHolder) holder), loanAccount, R.color.red); - - } else if (loanAccount.getStatus().getActive()) { - - setLoanAccountsGeneralDetails(holder, R.color.deposit_green, context.getString(R. - string.string_and_string, context.getString(R.string.disbursement), - DateHelper.getDateAsString(loanAccount.getTimeline(). - getActualDisbursementDate()))); - setLoanAccountsDetails(((ViewHolder) holder), loanAccount, R.color.deposit_green); - - } else if (loanAccount.getStatus().getWaitingForDisbursal()) { - - setLoanAccountsGeneralDetails(holder, R.color.blue, context.getString(R.string. - string_and_string, context.getString(R.string.approved), DateHelper - .getDateAsString(loanAccount.getTimeline().getApprovedOnDate()))); - - } else if (loanAccount.getStatus().getPendingApproval()) { - - setLoanAccountsGeneralDetails(holder, R.color.light_yellow, context.getString(R. - string.string_and_string, context.getString(R.string. - submitted), DateHelper.getDateAsString(loanAccount. - getTimeline().getSubmittedOnDate()))); - - } else if (loanAccount.getStatus().getOverpaid()) { - - setLoanAccountsDetails(((ViewHolder) holder), loanAccount, R.color.purple); - setLoanAccountsGeneralDetails(holder, R.color.purple, context.getString(R.string. - string_and_string, context.getString(R.string.disbursement), DateHelper - .getDateAsString(loanAccount.getTimeline().getActualDisbursementDate()))); - - } else if (loanAccount.getStatus().getClosed()) { - - setLoanAccountsGeneralDetails(holder, R.color.black, context.getString(R.string. - string_and_string, context.getString(R.string.closed), DateHelper - .getDateAsString(loanAccount.getTimeline().getClosedOnDate()))); - - } else { - setLoanAccountsGeneralDetails(holder, R.color.gray_dark, context.getString(R.string. - string_and_string, context.getString(R.string.withdrawn), DateHelper - .getDateAsString(loanAccount.getTimeline().getWithdrawnOnDate()))); - - } - } - - } - - private void setLoanAccountsDetails(ViewHolder viewHolder, LoanAccount loanAccount, int color) { - - double amountBalance = loanAccount.getLoanBalance() != 0 ? loanAccount.getLoanBalance() : 0; - viewHolder.tvAccountBalance.setVisibility(View.VISIBLE); - viewHolder.tvAccountBalance.setText(CurrencyUtil.formatCurrency(context, amountBalance)); - viewHolder.tvAccountBalance.setTextColor(ContextCompat.getColor(context, color)); - } - - private void setLoanAccountsGeneralDetails(RecyclerView.ViewHolder holder, int colorId, - String dateStr) { - ((ViewHolder) holder).ivStatusIndicator.setColorFilter(ContextCompat. - getColor(context, colorId)); - ((ViewHolder) holder).tvDate.setText(dateStr); - } - - @Override - public int getItemCount() { - return loanAccountsList.size(); - } - - public static class ViewHolder extends RecyclerView.ViewHolder { - @BindView(R.id.tv_clientLoanAccountNumber) - TextView tvClientLoanAccountNumber; - - @BindView(R.id.tv_loanAccountProductName) - TextView tvLoanAccountProductName; - - @BindView(R.id.iv_status_indicator) - AppCompatImageView ivStatusIndicator; - - @BindView(R.id.tv_date) - TextView tvDate; - - @BindView(R.id.tv_account_balance) - TextView tvAccountBalance; - - public ViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/LoanAccountsListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/LoanAccountsListAdapter.kt new file mode 100644 index 0000000000..3c20ca2579 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/LoanAccountsListAdapter.kt @@ -0,0 +1,144 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.appcompat.widget.AppCompatImageView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.utils.CurrencyUtil.formatCurrency +import org.mifos.mobile.utils.DateHelper.getDateAsString + +import java.util.* +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 22/6/16. + */ +class LoanAccountsListAdapter @Inject constructor(@param:ActivityContext private val context: Context) : + RecyclerView.Adapter() { + + private var loanAccountsList: List? = ArrayList() + + fun setLoanAccountsList(loanAccountsList: List?) { + this.loanAccountsList = loanAccountsList + notifyDataSetChanged() + } + + fun getLoanAccountsList(): List? { + return loanAccountsList + } + + fun getItem(position: Int): LoanAccount? { + return loanAccountsList?.get(position) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val vh: RecyclerView.ViewHolder + val v = LayoutInflater.from(parent.context).inflate( + R.layout.row_loan_account, parent, false) + vh = ViewHolder(v) + return vh + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + if (holder is ViewHolder) { + val loanAccount = getItem(position) + holder.tvClientLoanAccountNumber?.text = loanAccount?.accountNo + holder.tvLoanAccountProductName?.text = loanAccount?.productName + holder.tvAccountBalance?.visibility = View.GONE + if (loanAccount?.status?.active == true && loanAccount.inArrears == true) { + setLoanAccountsGeneralDetails(holder, R.color.red, context.getString( + R.string.string_and_string, context.getString(R.string.disbursement), + getDateAsString(loanAccount.timeline?.actualDisbursementDate) + )) + setLoanAccountsDetails(holder, loanAccount, R.color.red) + } else if (loanAccount?.status?.active == true) { + setLoanAccountsGeneralDetails(holder, R.color.deposit_green, context.getString( + R.string.string_and_string, context.getString(R.string.disbursement), + getDateAsString(loanAccount.timeline?.actualDisbursementDate) + )) + setLoanAccountsDetails(holder, loanAccount, R.color.deposit_green) + } else if (loanAccount?.status?.waitingForDisbursal == true) { + setLoanAccountsGeneralDetails(holder, R.color.blue, context.getString( + R.string.string_and_string, context.getString(R.string.approved), + getDateAsString(loanAccount.timeline?.approvedOnDate) + )) + } else if (loanAccount?.status?.pendingApproval == true) { + setLoanAccountsGeneralDetails(holder, R.color.light_yellow, context.getString( + R.string.string_and_string, context.getString(R.string.submitted), + getDateAsString(loanAccount.timeline?.submittedOnDate) + )) + } else if (loanAccount?.status?.overpaid == true) { + setLoanAccountsDetails(holder, loanAccount, R.color.purple) + setLoanAccountsGeneralDetails(holder, R.color.purple, context.getString( + R.string.string_and_string, context.getString(R.string.disbursement), + getDateAsString(loanAccount.timeline?.actualDisbursementDate) + )) + } else if (loanAccount?.status?.closed == true) { + setLoanAccountsGeneralDetails(holder, R.color.black, context.getString( + R.string.string_and_string, context.getString(R.string.closed), + getDateAsString(loanAccount.timeline?.closedOnDate) + )) + } else { + setLoanAccountsGeneralDetails(holder, R.color.gray_dark, context.getString(R.string.string_and_string, context.getString(R.string.withdrawn), getDateAsString(loanAccount?.timeline?.withdrawnOnDate))) + } + } + } + + private fun setLoanAccountsDetails(viewHolder: ViewHolder, loanAccount: LoanAccount, color: Int) { + val amountBalance: Double = if (loanAccount.loanBalance != 0.0) loanAccount.loanBalance else 0.0 + viewHolder.tvAccountBalance?.visibility = View.VISIBLE + viewHolder.tvAccountBalance?.text = formatCurrency(context, amountBalance) + viewHolder.tvAccountBalance?.setTextColor(ContextCompat.getColor(context, color)) + } + + private fun setLoanAccountsGeneralDetails( + holder: RecyclerView.ViewHolder, colorId: Int, + dateStr: String + ) { + (holder as ViewHolder).ivStatusIndicator?.setColorFilter(ContextCompat.getColor(context, colorId)) + holder.tvDate?.text = dateStr + } + + override fun getItemCount(): Int { + return if (loanAccountsList != null) loanAccountsList!!.size + else 0 + } + + class ViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) { + @JvmField + @BindView(R.id.tv_clientLoanAccountNumber) + var tvClientLoanAccountNumber: TextView? = null + + @JvmField + @BindView(R.id.tv_loanAccountProductName) + var tvLoanAccountProductName: TextView? = null + + @JvmField + @BindView(R.id.iv_status_indicator) + var ivStatusIndicator: AppCompatImageView? = null + + @JvmField + @BindView(R.id.tv_date) + var tvDate: TextView? = null + + @JvmField + @BindView(R.id.tv_account_balance) + var tvAccountBalance: TextView? = null + + init { + ButterKnife.bind(this, v!!) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/LoanRepaymentScheduleAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/LoanRepaymentScheduleAdapter.java deleted file mode 100644 index 5f36ba37cf..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/LoanRepaymentScheduleAdapter.java +++ /dev/null @@ -1,195 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.evrencoskun.tableview.adapter.AbstractTableAdapter; -import com.evrencoskun.tableview.adapter.recyclerview.holder.AbstractViewHolder; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.accounts.loan.Periods; -import org.mifos.mobile.models.accounts.loan.tableview.Cell; -import org.mifos.mobile.models.accounts.loan.tableview.ColumnHeader; -import org.mifos.mobile.models.accounts.loan.tableview.RowHeader; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; - -import javax.inject.Inject; - -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by Rajan Maurya on 04/03/17. - */ - -public class LoanRepaymentScheduleAdapter extends - AbstractTableAdapter { - - private String currency = ""; - - public void setCurrency(String currency) { - this.currency = currency; - } - - @Inject - LoanRepaymentScheduleAdapter(@ApplicationContext Context context) { - super(context); - } - - class CellViewHolder extends AbstractViewHolder { - - @BindView(R.id.cell_data) - TextView tvCell; - - CellViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } - - @Override - public AbstractViewHolder onCreateCellViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.cell_loan_repayment_schedule, parent, false); - return new CellViewHolder(view); - } - - @Override - public void onBindCellViewHolder(AbstractViewHolder holder, Object cellItemModel, - int columnPosition, int rowPosition) { - Cell cell = (Cell) cellItemModel; - Periods period = (Periods) cell.getData(); - - // Get the holder to update cell item text - CellViewHolder viewHolder = (CellViewHolder) holder; - - switch (columnPosition) { - case 0: - viewHolder.tvCell.setText(DateHelper.getDateAsString(period.getDueDate())); - break; - case 1: - Double principal = period.getPrincipalOriginalDue(); - if (principal == null) { - principal = 0.00; - } - viewHolder.tvCell.setText(mContext.getString(R.string.string_and_double, - currency, principal)); - break; - case 2: - principal = period.getPrincipalLoanBalanceOutstanding(); - if (principal == null) { - principal = 0.00; - } - viewHolder.tvCell.setText(mContext.getString(R.string.string_and_string, - currency, CurrencyUtil.formatCurrency(mContext, principal))); - break; - default: - viewHolder.tvCell.setText(""); - } - } - - class ColumnHeaderViewHolder extends AbstractViewHolder { - - @BindView(R.id.column_header_textView) - TextView tvColumnHeader; - - ColumnHeaderViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - } - } - - @Override - public AbstractViewHolder onCreateColumnHeaderViewHolder(ViewGroup parent, int viewType) { - - // Get Column Header xml Layout - View layout = LayoutInflater.from(mContext).inflate(R.layout - .column_header_loan_repayment_schedule, parent, false); - - // Create a ColumnHeader ViewHolder - return new ColumnHeaderViewHolder(layout); - } - - @Override - public void onBindColumnHeaderViewHolder(AbstractViewHolder holder, - Object columnHeaderItemModel, int position) { - ColumnHeader columnHeader = (ColumnHeader) columnHeaderItemModel; - - // Get the holder to update cell item text - ColumnHeaderViewHolder columnHeaderViewHolder = (ColumnHeaderViewHolder) holder; - - columnHeaderViewHolder.tvColumnHeader.setText(String.valueOf(columnHeader.getData())); - } - - class RowHeaderViewHolder extends AbstractViewHolder { - - @BindView(R.id.row_header_textview) - TextView tvRowHeader; - - RowHeaderViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - } - } - - @Override - public AbstractViewHolder onCreateRowHeaderViewHolder(ViewGroup parent, int viewType) { - -// Get Row Header xml Layout - View layout = LayoutInflater.from(mContext).inflate(R.layout - .row_header_loan_repayment_schedule, parent, false); - - // Create a Row Header ViewHolder - return new RowHeaderViewHolder(layout); -// return null; - } - - @Override - public void onBindRowHeaderViewHolder(AbstractViewHolder holder, Object rowHeaderItemModel, int - position) { - RowHeader rowHeader = (RowHeader) rowHeaderItemModel; - - // Get the holder to update row header item text - RowHeaderViewHolder rowHeaderViewHolder = (RowHeaderViewHolder) holder; - rowHeaderViewHolder.tvRowHeader.setText(String.valueOf(rowHeader.getData())); - } - - @Override - public View onCreateCornerView() { - return LayoutInflater.from(mContext).inflate(R.layout - .corner_view_loan_repayment_schedule, null, false); - } - - @Override - public int getColumnHeaderItemViewType(int columnPosition) { - // The unique ID for this type of column header item - // If you have different items for Cell View by X (Column) position, - // then you should fill this method to be able create different - // type of CellViewHolder on "onCreateCellViewHolder" - return 0; - } - - @Override - public int getRowHeaderItemViewType(int rowPosition) { - // The unique ID for this type of row header item - // If you have different items for Row Header View by Y (Row) position, - // then you should fill this method to be able create different - // type of RowHeaderViewHolder on "onCreateRowHeaderViewHolder" - return 0; - } - - @Override - public int getCellItemViewType(int columnPosition) { - // The unique ID for this type of cell item - // If you have different items for Cell View by X (Column) position, - // then you should fill this method to be able create different - // type of CellViewHolder on "onCreateCellViewHolder" - return 0; - } - -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/LoanRepaymentScheduleAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/LoanRepaymentScheduleAdapter.kt new file mode 100644 index 0000000000..ab352ce5bd --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/LoanRepaymentScheduleAdapter.kt @@ -0,0 +1,171 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView + +import butterknife.BindView +import butterknife.ButterKnife + +import com.evrencoskun.tableview.adapter.AbstractTableAdapter +import com.evrencoskun.tableview.adapter.recyclerview.holder.AbstractViewHolder + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.accounts.loan.Periods +import org.mifos.mobile.models.accounts.loan.tableview.Cell +import org.mifos.mobile.models.accounts.loan.tableview.ColumnHeader +import org.mifos.mobile.models.accounts.loan.tableview.RowHeader +import org.mifos.mobile.utils.CurrencyUtil.formatCurrency +import org.mifos.mobile.utils.DateHelper.getDateAsString + +import javax.inject.Inject + +/** + * Created by Rajan Maurya on 04/03/17. + */ +class LoanRepaymentScheduleAdapter @Inject internal constructor(@ApplicationContext context: Context?) : + AbstractTableAdapter(context) { + + private var currency: String? = "" + fun setCurrency(currency: String?) { + this.currency = currency + } + + internal inner class CellViewHolder(v: View?) : AbstractViewHolder(v) { + @JvmField + @BindView(R.id.cell_data) + var tvCell: TextView? = null + + init { + ButterKnife.bind(this, v!!) + } + } + + override fun onCreateCellViewHolder(parent: ViewGroup, viewType: Int): AbstractViewHolder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.cell_loan_repayment_schedule, parent, false) + return CellViewHolder(view) + } + + override fun onBindCellViewHolder( + holder: AbstractViewHolder, cellItemModel: Any, + columnPosition: Int, rowPosition: Int + ) { + val (data) = cellItemModel as Cell + val period = data as Periods + + // Get the holder to update cell item text + val viewHolder = holder as CellViewHolder + var principal: Double? + + when (columnPosition) { + 0 -> viewHolder.tvCell?.text = getDateAsString(period.dueDate) + 1 -> { + principal = period.principalOriginalDue + if (principal == null) { + principal = 0.00 + } + viewHolder.tvCell?.text = mContext.getString(R.string.string_and_double, + currency, principal) + } + 2 -> { + principal = period.principalLoanBalanceOutstanding + if (principal == null) { + principal = 0.00 + } + viewHolder.tvCell?.text = mContext.getString(R.string.string_and_string, + currency, formatCurrency(mContext, principal)) + } + else -> viewHolder.tvCell?.text = "" + } + } + + internal inner class ColumnHeaderViewHolder(itemView: View?) : AbstractViewHolder(itemView) { + @JvmField + @BindView(R.id.column_header_textView) + var tvColumnHeader: TextView? = null + + init { + ButterKnife.bind(this, itemView!!) + } + } + + override fun onCreateColumnHeaderViewHolder(parent: ViewGroup, viewType: Int): AbstractViewHolder { + + // Get Column Header xml Layout + val layout = LayoutInflater.from(mContext).inflate(R.layout.column_header_loan_repayment_schedule, parent, false) + + // Create a ColumnHeader ViewHolder + return ColumnHeaderViewHolder(layout) + } + + override fun onBindColumnHeaderViewHolder( + holder: AbstractViewHolder, + columnHeaderItemModel: Any, position: Int + ) { + val (data) = columnHeaderItemModel as ColumnHeader + + // Get the holder to update cell item text + val columnHeaderViewHolder = holder as ColumnHeaderViewHolder + columnHeaderViewHolder.tvColumnHeader?.text = data.toString() + } + + internal inner class RowHeaderViewHolder(itemView: View?) : AbstractViewHolder(itemView) { + @JvmField + @BindView(R.id.row_header_textview) + var tvRowHeader: TextView? = null + + init { + ButterKnife.bind(this, itemView!!) + } + } + + override fun onCreateRowHeaderViewHolder(parent: ViewGroup, viewType: Int): AbstractViewHolder { + +// Get Row Header xml Layout + val layout = LayoutInflater.from(mContext).inflate(R.layout.row_header_loan_repayment_schedule, parent, false) + + // Create a Row Header ViewHolder + return RowHeaderViewHolder(layout) + // return null; + } + + override fun onBindRowHeaderViewHolder(holder: AbstractViewHolder, rowHeaderItemModel: Any, position: Int) { + val (data) = rowHeaderItemModel as RowHeader + + // Get the holder to update row header item text + val rowHeaderViewHolder = holder as RowHeaderViewHolder + rowHeaderViewHolder.tvRowHeader?.text = data.toString() + } + + override fun onCreateCornerView(): View { + return LayoutInflater.from(mContext).inflate(R.layout.corner_view_loan_repayment_schedule, null, false) + } + + override fun getColumnHeaderItemViewType(columnPosition: Int): Int { + // The unique ID for this type of column header item + // If you have different items for Cell View by X (Column) position, + // then you should fill this method to be able create different + // type of CellViewHolder on "onCreateCellViewHolder" + return 0 + } + + override fun getRowHeaderItemViewType(rowPosition: Int): Int { + // The unique ID for this type of row header item + // If you have different items for Row Header View by Y (Row) position, + // then you should fill this method to be able create different + // type of RowHeaderViewHolder on "onCreateRowHeaderViewHolder" + return 0 + } + + override fun getCellItemViewType(columnPosition: Int): Int { + // The unique ID for this type of cell item + // If you have different items for Cell View by X (Column) position, + // then you should fill this method to be able create different + // type of CellViewHolder on "onCreateCellViewHolder" + return 0 + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/NotificationAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/NotificationAdapter.java deleted file mode 100644 index d73fa6d809..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/NotificationAdapter.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.utils.DateHelper; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 13/9/17. - */ - -public class NotificationAdapter extends RecyclerView.Adapter { - - private Context context; - private List notificationList; - - @Inject - public NotificationAdapter(@ActivityContext Context context) { - this.context = context; - this.notificationList = new ArrayList<>(); - } - - public void setNotificationList(List notificationList) { - this.notificationList = notificationList; - notifyDataSetChanged(); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View v = LayoutInflater.from(context).inflate(R.layout.row_notification, parent, false); - return new ViewHolder(v); - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - MifosNotification notification = notificationList.get(position); - - ((ViewHolder) holder).tvNotificationText.setText(notification.getMsg()); - ((ViewHolder) holder).tvNotificationTime.setText(DateHelper. - getDateAndTimeAsStringFromLong(notification.getTimeStamp())); - - if (notification.isRead()) { - ((ViewHolder) holder).ivNotificationIcon.setColorFilter(ContextCompat. - getColor(context, R.color.gray_dark)); - ((ViewHolder) holder).btnDismissNotification.setVisibility(View.GONE); - } else { - ((ViewHolder) holder).ivNotificationIcon.setColorFilter(ContextCompat. - getColor(context, R.color.primary)); - ((ViewHolder) holder).btnDismissNotification.setVisibility(View.VISIBLE); - } - } - - @Override - public int getItemCount() { - return notificationList.size(); - } - - public class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_notification_text) - TextView tvNotificationText; - - @BindView(R.id.tv_notification_time) - TextView tvNotificationTime; - - @BindView(R.id.iv_notification_icon) - ImageView ivNotificationIcon; - - @BindView(R.id.btn_dismiss_notification) - Button btnDismissNotification; - - public ViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - } - - @OnClick(R.id.btn_dismiss_notification) - public void dismissNotification() { - notificationList.get(getAdapterPosition()).setRead(true); - notificationList.get(getAdapterPosition()).save(); - notifyItemChanged(getAdapterPosition()); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/NotificationAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/NotificationAdapter.kt new file mode 100644 index 0000000000..dd3dc911a5 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/NotificationAdapter.kt @@ -0,0 +1,93 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import android.widget.ImageView +import android.widget.TextView + +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.utils.DateHelper.getDateAndTimeAsStringFromLong + +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 13/9/17. + */ +class NotificationAdapter @Inject constructor(@param:ActivityContext private val context: Context) : + RecyclerView.Adapter() { + + private var notificationList: List? + fun setNotificationList(notificationList: List?) { + this.notificationList = notificationList + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val v = LayoutInflater.from(context).inflate(R.layout.row_notification, parent, false) + return ViewHolder(v) + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val notification = notificationList?.get(position) + (holder as ViewHolder).tvNotificationText?.text = notification?.msg + holder.tvNotificationTime?.text = getDateAndTimeAsStringFromLong(notification?.timeStamp) + if (notification?.isRead() == true) { + holder.ivNotificationIcon?.setColorFilter(ContextCompat.getColor(context, R.color.gray_dark)) + holder.btnDismissNotification?.visibility = View.GONE + } else { + holder.ivNotificationIcon?.setColorFilter(ContextCompat.getColor(context, R.color.primary)) + holder.btnDismissNotification?.visibility = View.VISIBLE + } + } + + override fun getItemCount(): Int { + return if (notificationList != null) notificationList!!.size + else 0 + } + + inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) { + @JvmField + @BindView(R.id.tv_notification_text) + var tvNotificationText: TextView? = null + + @JvmField + @BindView(R.id.tv_notification_time) + var tvNotificationTime: TextView? = null + + @JvmField + @BindView(R.id.iv_notification_icon) + var ivNotificationIcon: ImageView? = null + + @JvmField + @BindView(R.id.btn_dismiss_notification) + var btnDismissNotification: Button? = null + + @OnClick(R.id.btn_dismiss_notification) + fun dismissNotification() { + notificationList?.get(adapterPosition)?.setRead(true) + notificationList?.get(adapterPosition)?.save() + notifyItemChanged(adapterPosition) + } + + init { + ButterKnife.bind(this, itemView!!) + } + } + + init { + notificationList = ArrayList() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/RecentTransactionListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/RecentTransactionListAdapter.java deleted file mode 100644 index 0be635d7e1..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/RecentTransactionListAdapter.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.Transaction; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.Utils; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Vishwajeet - * @since 10/08/16 - */ -public class RecentTransactionListAdapter extends - RecyclerView.Adapter { - - private List transactions; - private Context context; - - @Inject - public RecentTransactionListAdapter(@ActivityContext Context context) { - transactions = new ArrayList<>(); - this.context = context; - } - - @Override - public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.row_recent_transaction, parent, false); - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(ViewHolder holder, int position) { - Transaction transaction = getItem(position); - String currencyRepresentation = transaction.getCurrency().getDisplaySymbol(); - if (currencyRepresentation == null) { - currencyRepresentation = transaction.getCurrency().getCode(); - } - holder.tvAmount.setText(context.getString(R.string.string_and_string, - currencyRepresentation, CurrencyUtil.formatCurrency(context, - transaction.getAmount()))); - holder.tvTypeValue.setText(Utils.formatTransactionType(transaction.getType().getValue())); - holder.tvTransactionsDate.setText(DateHelper.getDateAsString(transaction. - getSubmittedOnDate())); - } - - public void setTransactions(List transactions) { - this.transactions = transactions; - notifyDataSetChanged(); - } - - - public Transaction getItem(int position) { - return transactions.get(position); - } - - @Override - public int getItemCount() { - return transactions.size(); - } - - public static class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_transactionDate) - TextView tvTransactionsDate; - - @BindView(R.id.tv_amount) - TextView tvAmount; - - @BindView(R.id.tv_value) - TextView tvTypeValue; - - public ViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/RecentTransactionListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/RecentTransactionListAdapter.kt new file mode 100644 index 0000000000..72962c75ad --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/RecentTransactionListAdapter.kt @@ -0,0 +1,89 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.Transaction +import org.mifos.mobile.utils.CurrencyUtil.formatCurrency +import org.mifos.mobile.utils.DateHelper.getDateAsString +import org.mifos.mobile.utils.Utils.formatTransactionType + +import java.util.* +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 10/08/16 + */ +class RecentTransactionListAdapter @Inject constructor(@ActivityContext context: Context) : + RecyclerView.Adapter() { + + private var transactions: MutableList + private val context: Context + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.row_recent_transaction, parent, false) + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val (_, _, _, type, _, currency, amount, submittedOnDate) = getItem(position) + var currencyRepresentation = currency?.displaySymbol + if (currencyRepresentation == null) { + currencyRepresentation = currency?.code + } + holder.tvAmount?.text = context.getString(R.string.string_and_string, + currencyRepresentation, formatCurrency(context, + amount!!)) + holder.tvTypeValue?.text = formatTransactionType(type.value) + holder.tvTransactionsDate?.text = getDateAsString(submittedOnDate) + } + + fun setTransactions(transactions: MutableList?) { + if (transactions != null) { + this.transactions = transactions + } + notifyDataSetChanged() + } + + fun getItem(position: Int): Transaction { + return transactions[position]!! + } + + override fun getItemCount(): Int { + return transactions.size + } + + class ViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) { + @JvmField + @BindView(R.id.tv_transactionDate) + var tvTransactionsDate: TextView? = null + + @JvmField + @BindView(R.id.tv_amount) + var tvAmount: TextView? = null + + @JvmField + @BindView(R.id.tv_value) + var tvTypeValue: TextView? = null + + init { + ButterKnife.bind(this, v!!) + } + } + + init { + transactions = ArrayList() + this.context = context + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsListAdapter.java deleted file mode 100644 index 17b391f32c..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsListAdapter.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.appcompat.widget.AppCompatImageView; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Vishwajeet - * @since 22/6/16. - */ -public class SavingAccountsListAdapter extends RecyclerView.Adapter { - - private final Context context; - - private List savingAccountsList = new ArrayList<>(); - - @Inject - public SavingAccountsListAdapter(@ActivityContext Context context) { - this.context = context; - } - - public void setSavingAccountsList(List savingAccountsList) { - this.savingAccountsList = savingAccountsList; - notifyDataSetChanged(); - } - - public List getSavingAccountsList() { - return savingAccountsList; - } - - public SavingAccount getItem(int position) { - return savingAccountsList.get(position); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - RecyclerView.ViewHolder vh; - View v = LayoutInflater.from(parent.getContext()).inflate( - R.layout.row_saving_account, parent, false); - vh = new ViewHolder(v); - return vh; - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - if (holder instanceof ViewHolder) { - - SavingAccount savingAccount = getItem(position); - - ((ViewHolder) holder).tvClientSavingAccountNumber.setText( - savingAccount.getAccountNo()); - - ((ViewHolder) holder).tvSavingAccountProductName.setText( - savingAccount.getProductName()); - ((ViewHolder) holder).tvAccountBalance.setVisibility(View.GONE); - - if (savingAccount.getStatus().getActive()) { - - setSavingAccountsDetails(((ViewHolder) holder), savingAccount, - R.color.deposit_green); - setSavingAccountsGeneralDetails(holder, R.color.deposit_green, DateHelper. - getDateAsString(savingAccount.getLastActiveTransactionDate())); - - } else if (savingAccount.getStatus().getApproved()) { - - setSavingAccountsGeneralDetails(holder, R.color.light_green, context.getString(R. - string.string_and_string, context.getString(R.string.approved), DateHelper. - getDateAsString(savingAccount.getTimeLine().getApprovedOnDate()))); - - } else if (savingAccount.getStatus().getSubmittedAndPendingApproval()) { - - setSavingAccountsGeneralDetails(holder, R.color.light_yellow, context.getString(R. - string.string_and_string, context.getString(R.string.submitted), DateHelper. - getDateAsString(savingAccount.getTimeLine().getSubmittedOnDate()))); - - } else if (savingAccount.getStatus().getMatured()) { - - setSavingAccountsDetails(((ViewHolder) holder), savingAccount, R.color.red_light); - setSavingAccountsGeneralDetails(holder, R.color.red_light, DateHelper. - getDateAsString(savingAccount.getLastActiveTransactionDate())); - - } else { - - setSavingAccountsGeneralDetails(holder, R.color.black, context.getString(R.string. - string_and_string, context.getString(R.string.closed), DateHelper. - getDateAsString(savingAccount.getTimeLine().getClosedOnDate()))); - - } - } - - } - - private void setSavingAccountsDetails(ViewHolder viewHolder, SavingAccount savingAccount, - int colorId) { - viewHolder.tvAccountBalance.setVisibility(View.VISIBLE); - viewHolder.tvAccountBalance.setTextColor(ContextCompat.getColor(context, - colorId)); - viewHolder.tvAccountBalance.setText(context.getString(R.string.string_and_string, - savingAccount.getCurrency().getDisplaySymbol(), CurrencyUtil.formatCurrency(context, - savingAccount.getAccountBalance()))); - } - - private void setSavingAccountsGeneralDetails(RecyclerView.ViewHolder holder, int colorId, - String dateStr) { - ((ViewHolder) holder).ivStatusIndicator.setColorFilter(ContextCompat. - getColor(context, colorId)); - ((ViewHolder) holder).tvLastActive.setText(dateStr); - } - - @Override - public int getItemCount() { - return savingAccountsList.size(); - } - - public static class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_clientSavingAccountNumber) - TextView tvClientSavingAccountNumber; - - @BindView(R.id.tv_savingAccountProductName) - TextView tvSavingAccountProductName; - - @BindView(R.id.iv_status_indicator) - AppCompatImageView ivStatusIndicator; - - @BindView(R.id.tv_last_active) - TextView tvLastActive; - - @BindView(R.id.tv_account_balance) - TextView tvAccountBalance; - - public ViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsListAdapter.kt new file mode 100644 index 0000000000..d8e382c680 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsListAdapter.kt @@ -0,0 +1,133 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView + +import androidx.appcompat.widget.AppCompatImageView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.utils.CurrencyUtil.formatCurrency +import org.mifos.mobile.utils.DateHelper.getDateAsString + +import java.util.* +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 22/6/16. + */ +class SavingAccountsListAdapter @Inject constructor(@param:ActivityContext private val context: Context) : + RecyclerView.Adapter() { + + private var savingAccountsList: List? = ArrayList() + fun setSavingAccountsList(savingAccountsList: List?) { + this.savingAccountsList = savingAccountsList + notifyDataSetChanged() + } + + fun getSavingAccountsList(): List? { + return savingAccountsList + } + + fun getItem(position: Int): SavingAccount? { + return savingAccountsList?.get(position) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val vh: RecyclerView.ViewHolder + val v = LayoutInflater.from(parent.context).inflate( + R.layout.row_saving_account, parent, false) + vh = ViewHolder(v) + return vh + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + if (holder is ViewHolder) { + val savingAccount = getItem(position) + holder.tvClientSavingAccountNumber?.text = savingAccount?.accountNo + holder.tvSavingAccountProductName?.text = savingAccount?.productName + holder.tvAccountBalance?.visibility = View.GONE + when { + savingAccount?.status?.active == true -> { + setSavingAccountsDetails(holder, savingAccount, + R.color.deposit_green) + setSavingAccountsGeneralDetails(holder, R.color.deposit_green, getDateAsString(savingAccount.lastActiveTransactionDate)) + } + savingAccount?.status?.approved == true -> { + setSavingAccountsGeneralDetails(holder, R.color.light_green, context.getString(R.string.string_and_string, context.getString(R.string.approved), getDateAsString(savingAccount.timeLine?.approvedOnDate))) + } + savingAccount?.status?.submittedAndPendingApproval == true -> { + setSavingAccountsGeneralDetails(holder, R.color.light_yellow, context.getString(R.string.string_and_string, context.getString(R.string.submitted), getDateAsString(savingAccount.timeLine?.submittedOnDate))) + } + savingAccount?.status?.matured == true -> { + setSavingAccountsDetails(holder, savingAccount, R.color.red_light) + setSavingAccountsGeneralDetails(holder, R.color.red_light, getDateAsString(savingAccount.lastActiveTransactionDate)) + } + else -> { + setSavingAccountsGeneralDetails(holder, R.color.black, context.getString(R.string.string_and_string, context.getString(R.string.closed), getDateAsString(savingAccount?.timeLine?.closedOnDate))) + } + } + } + } + + private fun setSavingAccountsDetails( + viewHolder: ViewHolder, savingAccount: SavingAccount, + colorId: Int + ) { + viewHolder.tvAccountBalance?.visibility = View.VISIBLE + viewHolder.tvAccountBalance?.setTextColor(ContextCompat.getColor(context, + colorId)) + viewHolder.tvAccountBalance?.text = context.getString(R.string.string_and_string, + savingAccount.currency?.displaySymbol, formatCurrency(context, + savingAccount.accountBalance)) + } + + private fun setSavingAccountsGeneralDetails( + holder: RecyclerView.ViewHolder, colorId: Int, + dateStr: String + ) { + (holder as ViewHolder).ivStatusIndicator?.setColorFilter(ContextCompat.getColor(context, colorId)) + holder.tvLastActive?.text = dateStr + } + + override fun getItemCount(): Int { + return if (savingAccountsList != null) savingAccountsList!!.size + else 0 + } + + class ViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) { + @JvmField + @BindView(R.id.tv_clientSavingAccountNumber) + var tvClientSavingAccountNumber: TextView? = null + + @JvmField + @BindView(R.id.tv_savingAccountProductName) + var tvSavingAccountProductName: TextView? = null + + @JvmField + @BindView(R.id.iv_status_indicator) + var ivStatusIndicator: AppCompatImageView? = null + + @JvmField + @BindView(R.id.tv_last_active) + var tvLastActive: TextView? = null + + @JvmField + @BindView(R.id.tv_account_balance) + var tvAccountBalance: TextView? = null + + init { + ButterKnife.bind(this, v!!) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsTransactionListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsTransactionListAdapter.java deleted file mode 100644 index 88d211dd90..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsTransactionListAdapter.java +++ /dev/null @@ -1,171 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.savings.TransactionType; -import org.mifos.mobile.models.accounts.savings.Transactions; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 6/3/17. - */ - -public class SavingAccountsTransactionListAdapter extends - RecyclerView.Adapter { - - private List savingAccountsTransactionList; - private Context context; - - @Inject - public SavingAccountsTransactionListAdapter() { - savingAccountsTransactionList = new ArrayList<>(); - } - - public void setContext(Context context) { - this.context = context; - } - - public Transactions getItem(int position) { - return savingAccountsTransactionList.get(position); - } - - public void setSavingAccountsTransactionList(List savingAccountsTransactionList) { - this.savingAccountsTransactionList = savingAccountsTransactionList; - notifyDataSetChanged(); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - RecyclerView.ViewHolder vh; - View v = LayoutInflater.from(parent.getContext()).inflate( - R.layout.row_saving_account_transaction, parent, false); - vh = new ViewHolder(v); - return vh; - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - - - Transactions transaction = getItem(position); - - ((ViewHolder) holder).tvSavingAccountAmount.setText(context.getString(R.string. - string_and_string, transaction.getCurrency().getDisplaySymbol(), CurrencyUtil. - formatCurrency(context, transaction.getAmount()))); - - ((ViewHolder) holder).tvSavingAccountRunningBalance.setText(context.getString(R.string. - string_and_string, transaction.getCurrency().getDisplaySymbol(), CurrencyUtil. - formatCurrency(context, transaction.getRunningBalance()))); - - ((ViewHolder) holder).tvTransactionType.setText(transaction. - getTransactionType().getValue()); - - if (transaction.getPaymentDetailData() != null) { - ((ViewHolder) holder).tvTransactionDetailData.setVisibility(View.VISIBLE); - ((ViewHolder) holder).tvTransactionDetailData.setText(transaction. - getPaymentDetailData().getPaymentType().getName()); - } - - ((ViewHolder) holder).tvTransactionDate.setText(DateHelper. - getDateAsString(transaction.getDate())); - - ColorSelect color = getColor(transaction.getTransactionType()); - if (color == ColorSelect.RED) { - ((ViewHolder) holder).vIndicator.setRotation(180); - ((ViewHolder) holder).vIndicator.setBackgroundDrawable( - ContextCompat.getDrawable(context, R.drawable.triangular_red_view)); - } else { - ((ViewHolder) holder).vIndicator.setRotation(0); - ((ViewHolder) holder).vIndicator.setBackgroundDrawable( - ContextCompat.getDrawable(context, R.drawable.triangular_green_view)); - } - - } - - private enum ColorSelect { - RED, - GREEN - } - - @Override - public int getItemCount() { - return savingAccountsTransactionList.size(); - } - - private ColorSelect getColor(TransactionType transactionType) { - if (transactionType.getDeposit()) { - return ColorSelect.GREEN; - } - if (transactionType.getDividendPayout()) { - return ColorSelect.RED; - } - if (transactionType.getWithdrawal()) { - return ColorSelect.RED; - } - if (transactionType.getInterestPosting()) { - return ColorSelect.GREEN; - } - if (transactionType.getFeeDeduction()) { - return ColorSelect.RED; - } - if (transactionType.getInitiateTransfer()) { - return ColorSelect.RED; - } - if (transactionType.getApproveTransfer()) { - return ColorSelect.RED; - } - if (transactionType.getWithdrawTransfer()) { - return ColorSelect.RED; - } - if (transactionType.getRejectTransfer()) { - return ColorSelect.GREEN; - } - if (transactionType.getOverdraftFee()) { - return ColorSelect.RED; - } - - return ColorSelect.GREEN; - } - - public static class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_transaction_date) - TextView tvTransactionDate; - - @BindView(R.id.tv_transaction_type) - TextView tvTransactionType; - - @BindView(R.id.tv_transaction_detail_data) - TextView tvTransactionDetailData; - - @BindView(R.id.tv_savingAccountAmount) - TextView tvSavingAccountAmount; - - @BindView(R.id.tv_saving_account_running_balance) - TextView tvSavingAccountRunningBalance; - - @BindView(R.id.v_indicator) - View vIndicator; - - public ViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsTransactionListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsTransactionListAdapter.kt new file mode 100644 index 0000000000..7628c55dd3 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/SavingAccountsTransactionListAdapter.kt @@ -0,0 +1,148 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.savings.TransactionType +import org.mifos.mobile.models.accounts.savings.Transactions +import org.mifos.mobile.utils.CurrencyUtil.formatCurrency +import org.mifos.mobile.utils.DateHelper.getDateAsString + +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 6/3/17. + */ +class SavingAccountsTransactionListAdapter @Inject constructor() : + RecyclerView.Adapter() { + + private var savingAccountsTransactionList: List? + private var context: Context? = null + fun setContext(context: Context?) { + this.context = context + } + + fun getItem(position: Int?): Transactions? { + return position?.let { savingAccountsTransactionList?.get(it) } + } + + fun setSavingAccountsTransactionList(savingAccountsTransactionList: List?) { + if (savingAccountsTransactionList != null) this.savingAccountsTransactionList = savingAccountsTransactionList + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val vh: RecyclerView.ViewHolder + val v = LayoutInflater.from(parent.context).inflate( + R.layout.row_saving_account_transaction, parent, false) + vh = ViewHolder(v) + return vh + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val (_, transactionType, _, _, date, currency, paymentDetailData, amount, runningBalance) = getItem(position)!! + (holder as ViewHolder).tvSavingAccountAmount?.text = context?.getString(R.string.string_and_string, currency?.displaySymbol, formatCurrency(context, amount!!)) + holder.tvSavingAccountRunningBalance?.text = context?.getString(R.string.string_and_string, currency?.displaySymbol, formatCurrency(context, runningBalance!!)) + holder.tvTransactionType?.text = transactionType?.value + if (paymentDetailData != null) { + holder.tvTransactionDetailData?.visibility = View.VISIBLE + holder.tvTransactionDetailData?.text = paymentDetailData.paymentType.name + } + holder.tvTransactionDate?.text = getDateAsString(date) + val color = getColor(transactionType) + if (color == ColorSelect.RED) { + holder.vIndicator?.rotation = 180f + holder.vIndicator?.background = ContextCompat.getDrawable(context!!, R.drawable.triangular_red_view) + } else { + holder.vIndicator?.rotation = 0f + holder.vIndicator?.background = ContextCompat.getDrawable(context!!, R.drawable.triangular_green_view) + } + } + + private enum class ColorSelect { + RED, GREEN + } + + override fun getItemCount(): Int { + return if (savingAccountsTransactionList != null) savingAccountsTransactionList!!.size + else 0 + } + + private fun getColor(transactionType: TransactionType?): ColorSelect { + if (transactionType?.deposit == true) { + return ColorSelect.GREEN + } + if (transactionType?.dividendPayout == true) { + return ColorSelect.RED + } + if (transactionType?.withdrawal == true) { + return ColorSelect.RED + } + if (transactionType?.interestPosting == true) { + return ColorSelect.GREEN + } + if (transactionType?.feeDeduction == true) { + return ColorSelect.RED + } + if (transactionType?.initiateTransfer == true) { + return ColorSelect.RED + } + if (transactionType?.approveTransfer == true) { + return ColorSelect.RED + } + if (transactionType?.withdrawTransfer == true) { + return ColorSelect.RED + } + if (transactionType?.rejectTransfer == true) { + return ColorSelect.GREEN + } + return if (transactionType?.overdraftFee == true) { + ColorSelect.RED + } else ColorSelect.GREEN + } + + class ViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) { + + @JvmField + @BindView(R.id.tv_transaction_date) + var tvTransactionDate: TextView? = null + + @JvmField + @BindView(R.id.tv_transaction_type) + var tvTransactionType: TextView? = null + + @JvmField + @BindView(R.id.tv_transaction_detail_data) + var tvTransactionDetailData: TextView? = null + + @JvmField + @BindView(R.id.tv_savingAccountAmount) + var tvSavingAccountAmount: TextView? = null + + @JvmField + @BindView(R.id.tv_saving_account_running_balance) + var tvSavingAccountRunningBalance: TextView? = null + + @JvmField + @BindView(R.id.v_indicator) + var vIndicator: View? = null + + init { + ButterKnife.bind(this, v!!) + } + } + + init { + savingAccountsTransactionList = ArrayList() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ShareAccountsListAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/ShareAccountsListAdapter.java deleted file mode 100644 index d23e12ffff..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/ShareAccountsListAdapter.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import android.content.Context; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.LayerDrawable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.injection.ActivityContext; -import org.mifos.mobile.models.accounts.share.ShareAccount; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.appcompat.widget.AppCompatImageView; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -public class ShareAccountsListAdapter extends RecyclerView.Adapter { - private final Context context; - private List shareAccountsList = new ArrayList<>(); - - @Inject - public ShareAccountsListAdapter(@ActivityContext Context context) { - this.context = context; - } - - public void setShareAccountsList(List shareAccountsList) { - this.shareAccountsList = shareAccountsList; - notifyDataSetChanged(); - } - - public ShareAccount getItem(int position) { - return shareAccountsList.get(position); - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - RecyclerView.ViewHolder vh; - View v = LayoutInflater.from(parent.getContext()).inflate( - R.layout.row_share_account, parent, false); - vh = new ViewHolder(v); - return vh; - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - if (holder instanceof ViewHolder) { - - ShareAccount shareAccount = getItem(position); - ((ViewHolder) holder).tvClientShareAccountsNumber - .setText(shareAccount.getAccountNo()); - ((ViewHolder) holder).tvShareAccountsProductName - .setText(shareAccount.getProductName()); - ((ViewHolder) holder).llAccountDetail.setVisibility(View.GONE); - - if (shareAccount.getStatus().getActive()) { - - ((ViewHolder) holder).ivStatusIndicator.setColorFilter(ContextCompat. - getColor(context, R.color.deposit_green)); - setSharingAccountDetail(((ViewHolder) holder), shareAccount); - - } else if (shareAccount.getStatus().getApproved()) { - - ((ViewHolder) holder).ivStatusIndicator.setColorFilter(ContextCompat. - getColor(context, R.color.light_green)); - - } else if (shareAccount.getStatus().getSubmittedAndPendingApproval()) { - - ((ViewHolder) holder).ivStatusIndicator.setColorFilter(ContextCompat. - getColor(context, R.color.light_yellow)); - - } else { - - ((ViewHolder) holder).ivStatusIndicator.setColorFilter(ContextCompat. - getColor(context, R.color.light_blue)); - - } - } - } - - private void setSharingAccountDetail(ViewHolder viewHolder, ShareAccount shareAccount) { - viewHolder.llAccountDetail.setVisibility(View.VISIBLE); - viewHolder.tvSharesPending.setText(String.valueOf(shareAccount - .getTotalPendingForApprovalShares())); - viewHolder.tvSharesApproved.setText(String.valueOf(shareAccount - .getTotalApprovedShares())); - } - - @Override - public int getItemCount() { - return shareAccountsList.size(); - } - - private LayerDrawable setCircularBackground(int colorId) { - Drawable color = new ColorDrawable(ContextCompat.getColor(context, colorId)); - Drawable image = ContextCompat.getDrawable(context, R.drawable.circular_background); - LayerDrawable ld = new LayerDrawable(new Drawable[]{image, color}); - return ld; - } - - public static class ViewHolder extends RecyclerView.ViewHolder { - - @BindView(R.id.tv_clientSharingAccountNumber) - TextView tvClientShareAccountsNumber; - - @BindView(R.id.tv_shareAccountProductName) - TextView tvShareAccountsProductName; - - @BindView(R.id.iv_status_indicator) - AppCompatImageView ivStatusIndicator; - - @BindView(R.id.ll_account_detail) - LinearLayout llAccountDetail; - - @BindView(R.id.tv_shares_pending) - TextView tvSharesPending; - - @BindView(R.id.tv_shares_approved) - TextView tvSharesApproved; - - public ViewHolder(View v) { - super(v); - ButterKnife.bind(this, v); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ShareAccountsListAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/ShareAccountsListAdapter.kt new file mode 100644 index 0000000000..caa7ad0ff4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/ShareAccountsListAdapter.kt @@ -0,0 +1,122 @@ +package org.mifos.mobile.ui.adapters + +import android.content.Context +import android.graphics.drawable.ColorDrawable +import android.graphics.drawable.Drawable +import android.graphics.drawable.LayerDrawable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout +import android.widget.TextView + +import androidx.appcompat.widget.AppCompatImageView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.injection.ActivityContext +import org.mifos.mobile.models.accounts.share.ShareAccount + +import java.util.* +import javax.inject.Inject + +class ShareAccountsListAdapter @Inject constructor(@param:ActivityContext private val context: Context) : + RecyclerView.Adapter() { + + private var shareAccountsList: List? = ArrayList() + fun setShareAccountsList(shareAccountsList: List?) { + if (shareAccountsList != null) + this.shareAccountsList = shareAccountsList + notifyDataSetChanged() + } + + fun getItem(position: Int): ShareAccount? { + return shareAccountsList?.get(position) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val vh: RecyclerView.ViewHolder + val v = LayoutInflater.from(parent.context).inflate( + R.layout.row_share_account, parent, false) + vh = ViewHolder(v) + return vh + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + if (holder is ViewHolder) { + val shareAccount = getItem(position) + holder.tvClientShareAccountsNumber?.text = shareAccount?.accountNo + holder.tvShareAccountsProductName?.text = shareAccount?.productName + holder.llAccountDetail?.visibility = View.GONE + when { + shareAccount?.status?.active == true -> { + holder.ivStatusIndicator?.setColorFilter(ContextCompat.getColor(context, R.color.deposit_green)) + setSharingAccountDetail(holder, shareAccount) + } + shareAccount?.status?.approved == true -> { + holder.ivStatusIndicator?.setColorFilter(ContextCompat.getColor(context, R.color.light_green)) + } + shareAccount?.status?.submittedAndPendingApproval == true -> { + holder.ivStatusIndicator?.setColorFilter(ContextCompat.getColor(context, R.color.light_yellow)) + } + else -> { + holder.ivStatusIndicator?.setColorFilter(ContextCompat.getColor(context, R.color.light_blue)) + } + } + } + } + + private fun setSharingAccountDetail(viewHolder: ViewHolder, shareAccount: ShareAccount) { + viewHolder.llAccountDetail?.visibility = View.VISIBLE + viewHolder.tvSharesPending?.text = shareAccount + .totalPendingForApprovalShares.toString() + viewHolder.tvSharesApproved?.text = shareAccount + .totalApprovedShares.toString() + } + + override fun getItemCount(): Int { + if (shareAccountsList != null) + return shareAccountsList!!.size + return 0 + } + + private fun setCircularBackground(colorId: Int): LayerDrawable { + val color: Drawable = ColorDrawable(ContextCompat.getColor(context, colorId)) + val image = ContextCompat.getDrawable(context, R.drawable.circular_background) + return LayerDrawable(arrayOf(image, color)) + } + + class ViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) { + @JvmField + @BindView(R.id.tv_clientSharingAccountNumber) + var tvClientShareAccountsNumber: TextView? = null + + @JvmField + @BindView(R.id.tv_shareAccountProductName) + var tvShareAccountsProductName: TextView? = null + + @JvmField + @BindView(R.id.iv_status_indicator) + var ivStatusIndicator: AppCompatImageView? = null + + @JvmField + @BindView(R.id.ll_account_detail) + var llAccountDetail: LinearLayout? = null + + @JvmField + @BindView(R.id.tv_shares_pending) + var tvSharesPending: TextView? = null + + @JvmField + @BindView(R.id.tv_shares_approved) + var tvSharesApproved: TextView? = null + + init { + ButterKnife.bind(this, v!!) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ViewPagerAdapter.java b/app/src/main/java/org/mifos/mobile/ui/adapters/ViewPagerAdapter.java deleted file mode 100644 index 96b7ef2c8e..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/adapters/ViewPagerAdapter.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.mifos.mobile.ui.adapters; - -import java.util.ArrayList; -import java.util.List; - -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentPagerAdapter; - -/** - * @author Vishwajeet - * @since 21/6/16. - */ -public class ViewPagerAdapter extends FragmentPagerAdapter { - private final List mFragmentList = new ArrayList<>(); - private final List mFragmentTitleList = new ArrayList<>(); - - public ViewPagerAdapter(FragmentManager manager) { - super(manager); - } - - @Override - public Fragment getItem(int position) { - return mFragmentList.get(position); - } - - @Override - public int getCount() { - return mFragmentList.size(); - } - - public void addFragment(Fragment fragment, String title) { - mFragmentList.add(fragment); - mFragmentTitleList.add(title); - } - - @Override - public CharSequence getPageTitle(int position) { - return mFragmentTitleList.get(position); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/adapters/ViewPagerAdapter.kt b/app/src/main/java/org/mifos/mobile/ui/adapters/ViewPagerAdapter.kt new file mode 100644 index 0000000000..fd678c4f54 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/adapters/ViewPagerAdapter.kt @@ -0,0 +1,32 @@ +package org.mifos.mobile.ui.adapters + +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import androidx.fragment.app.FragmentPagerAdapter +import java.util.* + +/** + * @author Vishwajeet + * @since 21/6/16. + */ +class ViewPagerAdapter(manager: FragmentManager?) : FragmentPagerAdapter(manager) { + + private val mFragmentList: MutableList = ArrayList() + private val mFragmentTitleList: MutableList = ArrayList() + override fun getItem(position: Int): Fragment { + return mFragmentList[position] + } + + override fun getCount(): Int { + return mFragmentList.size + } + + fun addFragment(fragment: Fragment, title: String) { + mFragmentList.add(fragment) + mFragmentTitleList.add(title) + } + + override fun getPageTitle(position: Int): CharSequence? { + return mFragmentTitleList[position] + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/AccountType.java b/app/src/main/java/org/mifos/mobile/ui/enums/AccountType.java deleted file mode 100644 index 6e79cd8f50..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/enums/AccountType.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.mifos.mobile.ui.enums; - -/** - * @author Rajan Maurya - * On 24/03/17. - */ - -public enum AccountType { - - SAVINGS, - - LOAN, - - SHARE - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/AccountType.kt b/app/src/main/java/org/mifos/mobile/ui/enums/AccountType.kt new file mode 100644 index 0000000000..79cb993931 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/enums/AccountType.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.enums + +/** + * @author Rajan Maurya + * On 24/03/17. + */ + +enum class AccountType { + + SAVINGS, + + LOAN, + + SHARE + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/BeneficiaryState.java b/app/src/main/java/org/mifos/mobile/ui/enums/BeneficiaryState.kt similarity index 56% rename from app/src/main/java/org/mifos/mobile/ui/enums/BeneficiaryState.java rename to app/src/main/java/org/mifos/mobile/ui/enums/BeneficiaryState.kt index a7ef2ca4f5..a7ad10ac18 100644 --- a/app/src/main/java/org/mifos/mobile/ui/enums/BeneficiaryState.java +++ b/app/src/main/java/org/mifos/mobile/ui/enums/BeneficiaryState.kt @@ -1,11 +1,15 @@ -package org.mifos.mobile.ui.enums; +package org.mifos.mobile.ui.enums /** * Created by dilpreet on 16/6/17. */ -public enum BeneficiaryState { +enum class BeneficiaryState { + CREATE_MANUAL, + CREATE_QR, + UPDATE -} + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/ChargeType.java b/app/src/main/java/org/mifos/mobile/ui/enums/ChargeType.kt similarity index 55% rename from app/src/main/java/org/mifos/mobile/ui/enums/ChargeType.java rename to app/src/main/java/org/mifos/mobile/ui/enums/ChargeType.kt index d03fc8fcfd..c398446ed0 100644 --- a/app/src/main/java/org/mifos/mobile/ui/enums/ChargeType.java +++ b/app/src/main/java/org/mifos/mobile/ui/enums/ChargeType.kt @@ -1,11 +1,15 @@ -package org.mifos.mobile.ui.enums; +package org.mifos.mobile.ui.enums /** * Created by dilpreet on 19/7/17. */ -public enum ChargeType { +enum class ChargeType { + CLIENT, + SAVINGS, + LOAN -} + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/GuarantorState.java b/app/src/main/java/org/mifos/mobile/ui/enums/GuarantorState.kt similarity index 52% rename from app/src/main/java/org/mifos/mobile/ui/enums/GuarantorState.java rename to app/src/main/java/org/mifos/mobile/ui/enums/GuarantorState.kt index 1597578d96..8f57b5e833 100644 --- a/app/src/main/java/org/mifos/mobile/ui/enums/GuarantorState.java +++ b/app/src/main/java/org/mifos/mobile/ui/enums/GuarantorState.kt @@ -1,10 +1,13 @@ -package org.mifos.mobile.ui.enums; +package org.mifos.mobile.ui.enums /* * Created by saksham on 25/July/2018 */ -public enum GuarantorState { +enum class GuarantorState { + CREATE, + UPDATE + } diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/LoanState.java b/app/src/main/java/org/mifos/mobile/ui/enums/LoanState.kt similarity index 52% rename from app/src/main/java/org/mifos/mobile/ui/enums/LoanState.java rename to app/src/main/java/org/mifos/mobile/ui/enums/LoanState.kt index 9b9e1e5b56..a9af1b49b1 100644 --- a/app/src/main/java/org/mifos/mobile/ui/enums/LoanState.java +++ b/app/src/main/java/org/mifos/mobile/ui/enums/LoanState.kt @@ -1,10 +1,11 @@ -package org.mifos.mobile.ui.enums; +package org.mifos.mobile.ui.enums /** * Created by dilpreet on 3/6/17. */ +enum class LoanState { -public enum LoanState { CREATE, + UPDATE -} +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/RequestAccessType.java b/app/src/main/java/org/mifos/mobile/ui/enums/RequestAccessType.kt similarity index 62% rename from app/src/main/java/org/mifos/mobile/ui/enums/RequestAccessType.java rename to app/src/main/java/org/mifos/mobile/ui/enums/RequestAccessType.kt index 18842e50a6..1fd097d9ad 100644 --- a/app/src/main/java/org/mifos/mobile/ui/enums/RequestAccessType.java +++ b/app/src/main/java/org/mifos/mobile/ui/enums/RequestAccessType.kt @@ -1,11 +1,14 @@ -package org.mifos.mobile.ui.enums; +package org.mifos.mobile.ui.enums /** * Created by manishkumar on 19/05/18. */ +enum class RequestAccessType { -public enum RequestAccessType { CAMERA, + EXTERNAL_STORAGE_READ, + EXTERNAL_STORAGE_WRITE -} + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/SavingsAccountState.java b/app/src/main/java/org/mifos/mobile/ui/enums/SavingsAccountState.java deleted file mode 100644 index 6d66bdcb50..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/enums/SavingsAccountState.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.mifos.mobile.ui.enums; - -/* - * Created by saksham on 02/July/2018 - */ - -public enum SavingsAccountState { - CREATE, - UPDATE -} diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/SavingsAccountState.kt b/app/src/main/java/org/mifos/mobile/ui/enums/SavingsAccountState.kt new file mode 100644 index 0000000000..f45eef3987 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/enums/SavingsAccountState.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.ui.enums + +/* + * Created by saksham on 02/July/2018 + */ +enum class SavingsAccountState { + + CREATE, + + UPDATE + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/TransferType.java b/app/src/main/java/org/mifos/mobile/ui/enums/TransferType.java deleted file mode 100644 index 58cab67dce..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/enums/TransferType.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.mifos.mobile.ui.enums; - -/** - * Created by dilpreet on 6/7/17. - */ - -public enum TransferType { - TPT, - SELF -} diff --git a/app/src/main/java/org/mifos/mobile/ui/enums/TransferType.kt b/app/src/main/java/org/mifos/mobile/ui/enums/TransferType.kt new file mode 100644 index 0000000000..61b638f188 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/enums/TransferType.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.ui.enums + +/** + * Created by dilpreet on 6/7/17. + */ +enum class TransferType { + + TPT, + + SELF + +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AboutUsFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/AboutUsFragment.java deleted file mode 100644 index 733e597c8c..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/AboutUsFragment.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.content.Intent; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.google.android.gms.oss.licenses.OssLicensesMenuActivity; - -import org.mifos.mobile.BuildConfig; -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.PrivacyPolicyActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; - -import java.util.Calendar; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - - -public class AboutUsFragment extends BaseFragment { - - @BindView(R.id.tv_app_version) - TextView tvAppVersion; - - @BindView(R.id.tv_copy_right) - TextView tvCopyRight; - - View rootView; - - public static AboutUsFragment newInstance() { - AboutUsFragment fragment = new AboutUsFragment(); - Bundle args = new Bundle(); - fragment.setArguments(args); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_about_us, container, false); - ButterKnife.bind(this, rootView); - setToolbarTitle(getString(R.string.about_us)); - - tvAppVersion.setText(getString(R.string.app_version, BuildConfig.VERSION_NAME)); - - tvCopyRight.setText(getString(R.string.copy_right_mifos, - String.valueOf(Calendar.getInstance().get(Calendar.YEAR)))); - - return rootView; - } - - @OnClick(R.id.tv_licenses) - void showOpenSourceLicenses() { - startActivity(new Intent(getActivity(), OssLicensesMenuActivity.class)); - } - - @OnClick(R.id.tv_privacy_policy) - void showPrivacyPolicy() { - startActivity(new Intent(getActivity(), PrivacyPolicyActivity.class)); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AboutUsFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/AboutUsFragment.kt new file mode 100644 index 0000000000..e2c3ef83d6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/AboutUsFragment.kt @@ -0,0 +1,67 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.google.android.gms.oss.licenses.OssLicensesMenuActivity + +import org.mifos.mobile.BuildConfig +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.PrivacyPolicyActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import java.util.* + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ +class AboutUsFragment : BaseFragment() { + + @kotlin.jvm.JvmField + @BindView(R.id.tv_app_version) + var tvAppVersion: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_copy_right) + var tvCopyRight: TextView? = null + var rootView: View? = null + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_about_us, container, false) + ButterKnife.bind(this, rootView!!) + setToolbarTitle(getString(R.string.about_us)) + tvAppVersion?.text = getString(R.string.app_version, BuildConfig.VERSION_NAME) + tvCopyRight?.text = getString(R.string.copy_right_mifos, Calendar.getInstance()[Calendar.YEAR].toString()) + return rootView + } + + @OnClick(R.id.tv_licenses) + fun showOpenSourceLicenses() { + startActivity(Intent(activity, OssLicensesMenuActivity::class.java)) + } + + @OnClick(R.id.tv_privacy_policy) + fun showPrivacyPolicy() { + startActivity(Intent(activity, PrivacyPolicyActivity::class.java)) + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): AboutUsFragment { + val fragment = AboutUsFragment() + val args = Bundle() + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AccountOverviewFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/AccountOverviewFragment.java deleted file mode 100644 index 59e786bac2..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/AccountOverviewFragment.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.presenters.AccountOverviewPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.AccountOverviewMvpView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.Toaster; -import org.mifos.mobile.utils.Utils; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * @author Rajan Maurya - * On 16/10/17. - */ -public class AccountOverviewFragment extends BaseFragment implements AccountOverviewMvpView, - SwipeRefreshLayout.OnRefreshListener { - - @BindView(R.id.tv_total_savings) - TextView tvTotalSavings; - - @BindView(R.id.tv_total_loan) - TextView tvTotalLoan; - - @BindView(R.id.swipe_container) - SwipeRefreshLayout swipeRefreshLayout; - - @Inject - AccountOverviewPresenter accountOverviewPresenter; - - View rootView; - - private double totalLoanBalance, totalSavingsBalance; - - public static AccountOverviewFragment newInstance() { - AccountOverviewFragment fragment = new AccountOverviewFragment(); - Bundle args = new Bundle(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_account_overview, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - accountOverviewPresenter.attachView(this); - setToolbarTitle(getString(R.string.accounts_overview)); - - swipeRefreshLayout.setColorSchemeResources(R.color.blue_light, R.color.green_light, R - .color.orange_light, R.color.red_light); - swipeRefreshLayout.setOnRefreshListener(this); - - if (savedInstanceState == null) { - accountOverviewPresenter.loadClientAccountDetails(); - } - - return rootView; - } - - @Override - public void onRefresh() { - accountOverviewPresenter.loadClientAccountDetails(); - } - - @Override - public void showTotalLoanSavings(double totalLoan, double totalSavings) { - this.totalLoanBalance = totalLoan; - this.totalSavingsBalance = totalSavings; - tvTotalLoan.setText(CurrencyUtil.formatCurrency(getContext(), totalLoan)); - tvTotalSavings.setText(CurrencyUtil.formatCurrency(getContext(), totalSavings)); - } - - @Override - public void showError(String message) { - Toaster.show(rootView, message); - } - - @Override - public void showProgress() { - swipeRefreshLayout.setRefreshing(true); - } - - @Override - public void hideProgress() { - swipeRefreshLayout.setRefreshing(false); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_account_overview, menu); - Utils.setToolbarIconColor(getActivity(), menu, R.color.white); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - if (id == R.id.menu_refresh_account_overview) { - accountOverviewPresenter.loadClientAccountDetails(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putDouble(Constants.TOTAL_LOAN, totalLoanBalance); - outState.putDouble(Constants.TOTAL_SAVINGS, totalSavingsBalance); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - totalLoanBalance = savedInstanceState.getDouble(Constants.TOTAL_LOAN); - totalSavingsBalance = savedInstanceState.getDouble(Constants.TOTAL_SAVINGS); - showTotalLoanSavings(totalLoanBalance, totalSavingsBalance); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - accountOverviewPresenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AccountOverviewFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/AccountOverviewFragment.kt new file mode 100644 index 0000000000..9b5ce3f5c0 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/AccountOverviewFragment.kt @@ -0,0 +1,135 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.* +import android.widget.TextView + +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener + +import butterknife.BindView +import butterknife.ButterKnife + +import org.mifos.mobile.R +import org.mifos.mobile.presenters.AccountOverviewPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.AccountOverviewMvpView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.CurrencyUtil +import org.mifos.mobile.utils.Toaster +import org.mifos.mobile.utils.Utils + +import javax.inject.Inject + +/** + * @author Rajan Maurya + * On 16/10/17. + */ +class AccountOverviewFragment : BaseFragment(), AccountOverviewMvpView, OnRefreshListener { + @kotlin.jvm.JvmField + @BindView(R.id.tv_total_savings) + var tvTotalSavings: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_total_loan) + var tvTotalLoan: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.swipe_container) + var swipeRefreshLayout: SwipeRefreshLayout? = null + + @kotlin.jvm.JvmField + @Inject + var accountOverviewPresenter: AccountOverviewPresenter? = null + var rootView: View? = null + private var totalLoanBalance = 0.0 + private var totalSavingsBalance = 0.0 + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_account_overview, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + accountOverviewPresenter?.attachView(this) + setToolbarTitle(getString(R.string.accounts_overview)) + swipeRefreshLayout?.setColorSchemeResources(R.color.blue_light, R.color.green_light, R.color.orange_light, R.color.red_light) + swipeRefreshLayout?.setOnRefreshListener(this) + if (savedInstanceState == null) { + accountOverviewPresenter?.loadClientAccountDetails() + } + return rootView + } + + override fun onRefresh() { + accountOverviewPresenter?.loadClientAccountDetails() + } + + override fun showTotalLoanSavings(totalLoan: Double?, totalSavings: Double?) { + totalLoanBalance = totalLoan!! + totalSavingsBalance = totalSavings!! + tvTotalLoan?.text = CurrencyUtil.formatCurrency(context!!, totalLoan) + tvTotalSavings?.text = CurrencyUtil.formatCurrency(context!!, totalSavings) + } + + override fun showError(message: String?) { + Toaster.show(rootView, message) + } + + override fun showProgress() { + swipeRefreshLayout?.isRefreshing = true + } + + override fun hideProgress() { + swipeRefreshLayout?.isRefreshing = false + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + super.onCreateOptionsMenu(menu, inflater) + inflater.inflate(R.menu.menu_account_overview, menu) + Utils.setToolbarIconColor(activity, menu, R.color.white) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + val id = item.itemId + if (id == R.id.menu_refresh_account_overview) { + accountOverviewPresenter?.loadClientAccountDetails() + return true + } + return super.onOptionsItemSelected(item) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putDouble(Constants.TOTAL_LOAN, totalLoanBalance) + outState.putDouble(Constants.TOTAL_SAVINGS, totalSavingsBalance) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + totalLoanBalance = savedInstanceState.getDouble(Constants.TOTAL_LOAN) + totalSavingsBalance = savedInstanceState.getDouble(Constants.TOTAL_SAVINGS) + showTotalLoanSavings(totalLoanBalance, totalSavingsBalance) + } + } + + override fun onDestroyView() { + super.onDestroyView() + accountOverviewPresenter?.detachView() + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): AccountOverviewFragment { + val fragment = AccountOverviewFragment() + val args = Bundle() + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AccountsFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/AccountsFragment.java deleted file mode 100644 index a427499c7f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/AccountsFragment.java +++ /dev/null @@ -1,487 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.Intent; -import android.os.Bundle; -import android.os.Parcelable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.CheckboxStatus; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.models.accounts.share.ShareAccount; -import org.mifos.mobile.presenters.AccountsPresenter; -import org.mifos.mobile.ui.activities.LoanAccountContainerActivity; -import org.mifos.mobile.ui.activities.SavingsAccountContainerActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.LoanAccountsListAdapter; -import org.mifos.mobile.ui.adapters.SavingAccountsListAdapter; -import org.mifos.mobile.ui.adapters.ShareAccountsListAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.AccountsView; -import org.mifos.mobile.utils.ComparatorBasedOnId; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DividerItemDecoration; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.RecyclerItemClickListener; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by Rajan Maurya on 23/10/16. - */ - -public class AccountsFragment extends BaseFragment implements - SwipeRefreshLayout.OnRefreshListener, AccountsView, - RecyclerItemClickListener.OnItemClickListener { - - public static final String LOG_TAG = AccountsFragment.class.getSimpleName(); - - @BindView(R.id.rv_accounts) - RecyclerView rvAccounts; - - @BindView(R.id.swipe_container) - SwipeRefreshLayout swipeRefreshLayout; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - AccountsPresenter accountsPresenter; - - @Inject - LoanAccountsListAdapter loanAccountsListAdapter; - - @Inject - SavingAccountsListAdapter savingAccountsListAdapter; - - @Inject - ShareAccountsListAdapter shareAccountsListAdapter; - - View rootView; - private String accountType; - private List loanAccounts; - private List savingAccounts; - private List shareAccounts; - private List currentFilterList; - private SweetUIErrorHandler sweetUIErrorHandler; - - /** - * Method to get the current filter list for the fragment - * - * @return currentFilterList - */ - public List getCurrentFilterList() { - return currentFilterList; - } - - /** - * Method to set current filter list value - */ - public void setCurrentFilterList(List currentFilterList) { - this.currentFilterList = currentFilterList; - } - - public static AccountsFragment newInstance(String accountType) { - AccountsFragment fragment = new AccountsFragment(); - Bundle args = new Bundle(); - args.putString(Constants.ACCOUNT_TYPE, accountType); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - loanAccounts = new ArrayList<>(); - savingAccounts = new ArrayList<>(); - shareAccounts = new ArrayList<>(); - if (getArguments() != null) { - accountType = getArguments().getString(Constants.ACCOUNT_TYPE); - } - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_accounts, container, false); - - ButterKnife.bind(this, rootView); - accountsPresenter.attachView(this); - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(RecyclerView.VERTICAL); - rvAccounts.setLayoutManager(layoutManager); - rvAccounts.setHasFixedSize(true); - rvAccounts.addItemDecoration(new DividerItemDecoration(getActivity(), - layoutManager.getOrientation())); - rvAccounts.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), this)); - swipeRefreshLayout.setColorSchemeColors(getActivity() - .getResources().getIntArray(R.array.swipeRefreshColors)); - swipeRefreshLayout.setOnRefreshListener(this); - if (savedInstanceState == null) { - showProgress(); - } - - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putString(Constants.ACCOUNT_TYPE, accountType); - switch (accountType) { - case Constants.SAVINGS_ACCOUNTS: - outState.putParcelableArrayList(Constants.SAVINGS_ACCOUNTS, new ArrayList - (savingAccounts)); - break; - case Constants.LOAN_ACCOUNTS: - outState.putParcelableArrayList(Constants.LOAN_ACCOUNTS, new ArrayList - (loanAccounts)); - break; - case Constants.SHARE_ACCOUNTS: - outState.putParcelableArrayList(Constants.SHARE_ACCOUNTS, new ArrayList - (shareAccounts)); - break; - } - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - if (savedInstanceState != null) { - accountType = savedInstanceState.getString(Constants.ACCOUNT_TYPE); - switch (accountType) { - case Constants.SAVINGS_ACCOUNTS: - List savingAccountList = savedInstanceState. - getParcelableArrayList(Constants.SAVINGS_ACCOUNTS); - showSavingsAccounts(savingAccountList); - break; - case Constants.LOAN_ACCOUNTS: - List loanAccountList = savedInstanceState.getParcelableArrayList( - Constants.LOAN_ACCOUNTS); - showLoanAccounts(loanAccountList); - break; - case Constants.SHARE_ACCOUNTS: - List shareAccountList = savedInstanceState.getParcelableArrayList( - Constants.SHARE_ACCOUNTS); - showShareAccounts(shareAccountList); - break; - } - } - } - - - /** - * Used for reloading account of a particular {@code accountType} in case of a network error. - */ - - @OnClick(R.id.btn_try_again) - void onRetry() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvAccounts, layoutError); - accountsPresenter.loadAccounts(accountType); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - /** - * This method is called when we swipe to refresh the view and is used for reloading account of - * a particular {@code accountType} - */ - @Override - public void onRefresh() { - if (Network.isConnected(getContext())) { - clearFilter(); - accountsPresenter.loadAccounts(accountType); - } else { - hideProgress(); - sweetUIErrorHandler.showSweetNoInternetUI(rvAccounts, layoutError); - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - /** - * Method to clear the current filters and set - * currentFilterList = null - */ - public void clearFilter() { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvAccounts, layoutError); - currentFilterList = null; - } - - /** - * Shows {@link List} of {@link LoanAccount} fetched from server using - * {@link LoanAccountsListAdapter} - * - * @param loanAccounts {@link List} of {@link LoanAccount} - */ - @Override - public void showLoanAccounts(List loanAccounts) { - Collections.sort(loanAccounts, new ComparatorBasedOnId()); - this.loanAccounts = loanAccounts; - if (loanAccounts.size() != 0) { - loanAccountsListAdapter.setLoanAccountsList(loanAccounts); - rvAccounts.setAdapter(loanAccountsListAdapter); - } else { - showEmptyAccounts(getString(R.string.loan_account)); - } - } - - /** - * Shows {@link List} of {@link SavingAccount} fetched from server using - * {@link SavingAccountsListAdapter} - * - * @param savingAccounts {@link List} of {@link SavingAccount} - */ - @Override - public void showSavingsAccounts(List savingAccounts) { - Collections.sort(savingAccounts, new ComparatorBasedOnId()); - this.savingAccounts = savingAccounts; - if (savingAccounts.size() != 0) { - savingAccountsListAdapter.setSavingAccountsList(savingAccounts); - rvAccounts.setAdapter(savingAccountsListAdapter); - } else { - showEmptyAccounts(getString(R.string.savings_account)); - } - } - - /** - * Shows {@link List} of {@link ShareAccount} fetched from server using - * {@link ShareAccountsListAdapter} - * - * @param shareAccounts {@link List} of {@link ShareAccount} - */ - @Override - public void showShareAccounts(List shareAccounts) { - Collections.sort(shareAccounts, new ComparatorBasedOnId()); - this.shareAccounts = shareAccounts; - if (shareAccounts.size() != 0) { - shareAccountsListAdapter.setShareAccountsList(shareAccounts); - rvAccounts.setAdapter(shareAccountsListAdapter); - } else { - showEmptyAccounts(getString(R.string.share_account)); - } - } - - - /** - * Shows an error layout when this function is called. - * - * @param emptyAccounts Text to show in {@code noAccountText} - */ - public void showEmptyAccounts(String emptyAccounts) { - sweetUIErrorHandler.showSweetEmptyUI(emptyAccounts, - R.drawable.ic_account_balance_wallet_black_background_24dp, - rvAccounts, layoutError); - } - - /** - * Used for searching an {@code input} String in {@code savingAccounts} and displaying it in the - * recyclerview. - * - * @param input String which is needs to be searched in list - */ - public void searchSavingsAccount(String input) { - List searchResult = accountsPresenter. - searchInSavingsList(savingAccounts, input); - if (searchResult.size() == 0) { - showEmptyAccounts(getString(R.string.no_saving_account)); - } else { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvAccounts, layoutError); - savingAccountsListAdapter.setSavingAccountsList(searchResult); - } - } - - /** - * Used for searching an {@code input} String in {@code loanAccounts} and displaying it in the - * recyclerview. - * - * @param input String which is needs to be searched in list - */ - public void searchLoanAccount(String input) { - List searchResult = accountsPresenter. - searchInLoanList(loanAccounts, input); - if (searchResult.size() == 0) { - showEmptyAccounts(getString(R.string.no_loan_account)); - } else { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvAccounts, layoutError); - loanAccountsListAdapter.setLoanAccountsList(searchResult); - } - } - - /** - * Used for searching an {@code input} String in {@code savingAccounts} and displaying it in the - * recyclerview. - * - * @param input String which is needs to be searched in list - */ - public void searchSharesAccount(String input) { - List searchResult = accountsPresenter. - searchInSharesList(shareAccounts, input); - if (searchResult.size() == 0) { - showEmptyAccounts(getString(R.string.no_sharing_account)); - } else { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvAccounts, layoutError); - shareAccountsListAdapter.setShareAccountsList(searchResult); - } - } - - /** - * Used for filtering {@code savingAccounts} depending upon {@link List} of - * {@link CheckboxStatus} - * - * @param statusModelList {@link List} of {@link CheckboxStatus} - */ - public void filterSavingsAccount(List statusModelList) { - List filteredSavings = new ArrayList<>(); - for (CheckboxStatus status : accountsPresenter.getCheckedStatus(statusModelList)) { - filteredSavings.addAll(accountsPresenter.getFilteredSavingsAccount(savingAccounts, - status)); - } - if (filteredSavings.size() == 0) { - showEmptyAccounts(getString(R.string.no_saving_account)); - } else { - savingAccountsListAdapter.setSavingAccountsList(filteredSavings); - } - } - - /** - * Used for filtering {@code loanAccounts} depending upon {@link List} of - * {@link CheckboxStatus} - * - * @param statusModelList {@link List} of {@link CheckboxStatus} - */ - public void filterLoanAccount(List statusModelList) { - List filteredSavings = new ArrayList<>(); - for (CheckboxStatus status : accountsPresenter.getCheckedStatus(statusModelList)) { - filteredSavings.addAll(accountsPresenter.getFilteredLoanAccount(loanAccounts, - status)); - } - if (filteredSavings.size() == 0) { - showEmptyAccounts(getString(R.string.no_loan_account)); - } else { - loanAccountsListAdapter.setLoanAccountsList(filteredSavings); - } - } - - /** - * Used for filtering {@code shareAccounts} depending upon {@link List} of - * {@link CheckboxStatus} - * - * @param statusModelList {@link List} of {@link CheckboxStatus} - */ - public void filterShareAccount(List statusModelList) { - List filteredSavings = new ArrayList<>(); - for (CheckboxStatus status : accountsPresenter.getCheckedStatus(statusModelList)) { - filteredSavings.addAll(accountsPresenter.getFilteredShareAccount(shareAccounts, - status)); - } - if (filteredSavings.size() == 0) { - showEmptyAccounts(getString(R.string.no_sharing_account)); - } else { - shareAccountsListAdapter.setShareAccountsList(filteredSavings); - } - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param errorMessage Error message that tells the user about the problem. - */ - @Override - public void showError(String errorMessage) { - if (!Network.isConnected(getContext())) { - sweetUIErrorHandler.showSweetNoInternetUI(rvAccounts, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(errorMessage, rvAccounts, layoutError); - Toast.makeText(getContext(), errorMessage, Toast.LENGTH_SHORT).show(); - } - hideProgress(); - } - - /** - * Shows {@link SwipeRefreshLayout} - */ - @Override - public void showProgress() { - showSwipeRefreshLayout(true); - } - - /** - * Hides {@link SwipeRefreshLayout} - */ - @Override - public void hideProgress() { - showSwipeRefreshLayout(false); - } - - public void showSwipeRefreshLayout(boolean show) { - swipeRefreshLayout.setRefreshing(show); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - accountsPresenter.detachView(); - } - - @Override - public void onItemClick(View childView, int position) { - Intent intent = null; - switch (accountType) { - case Constants.SAVINGS_ACCOUNTS: - intent = new Intent(getActivity(), SavingsAccountContainerActivity.class); - intent.putExtra(Constants.SAVINGS_ID, savingAccountsListAdapter. - getSavingAccountsList().get(position).getId()); - break; - case Constants.LOAN_ACCOUNTS: - intent = new Intent(getActivity(), LoanAccountContainerActivity.class); - intent.putExtra(Constants.LOAN_ID, loanAccountsListAdapter.getLoanAccountsList(). - get(position).getId()); - break; - } - openActivity(intent); - } - - @Override - public void onItemLongPress(View childView, int position) { - - } - - /** - * This function opens up an activity only if the intent - * is not null. - * - * This will prevent the application from crashing if the - * intent is null. - */ - private void openActivity(Intent intent) { - if (intent != null) { - startActivity(intent); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AccountsFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/AccountsFragment.kt new file mode 100644 index 0000000000..a5b44c4319 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/AccountsFragment.kt @@ -0,0 +1,467 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.os.Bundle +import android.os.Parcelable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast + +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.CheckboxStatus +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.models.accounts.share.ShareAccount +import org.mifos.mobile.presenters.AccountsPresenter +import org.mifos.mobile.ui.activities.LoanAccountContainerActivity +import org.mifos.mobile.ui.activities.SavingsAccountContainerActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.LoanAccountsListAdapter +import org.mifos.mobile.ui.adapters.SavingAccountsListAdapter +import org.mifos.mobile.ui.adapters.ShareAccountsListAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.AccountsView +import org.mifos.mobile.utils.* + +import java.util.* +import javax.inject.Inject + +import kotlin.collections.ArrayList + +/** + * Created by Rajan Maurya on 23/10/16. + */ +class AccountsFragment : BaseFragment(), OnRefreshListener, AccountsView, RecyclerItemClickListener.OnItemClickListener { + @kotlin.jvm.JvmField + @BindView(R.id.rv_accounts) + var rvAccounts: RecyclerView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.swipe_container) + var swipeRefreshLayout: SwipeRefreshLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @Inject + var accountsPresenter: AccountsPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var loanAccountsListAdapter: LoanAccountsListAdapter? = null + + @kotlin.jvm.JvmField + @Inject + var savingAccountsListAdapter: SavingAccountsListAdapter? = null + + @kotlin.jvm.JvmField + @Inject + var shareAccountsListAdapter: ShareAccountsListAdapter? = null + private var accountType: String? = null + private var loanAccounts: List? = null + private var savingAccounts: List? = null + private var shareAccounts: List? = null + private var currentFilterList: List? = null + + /** + * Method to get the current filter list for the fragment + * + * @return currentFilterList + */ + fun getCurrentFilterList(): List? { + return currentFilterList + } + + /** + * Method to set current filter list value + */ + fun setCurrentFilterList(currentFilterList: List?) { + this.currentFilterList = currentFilterList + } + + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + loanAccounts = ArrayList() + savingAccounts = ArrayList() + shareAccounts = ArrayList() + if (arguments != null) { + accountType = arguments?.getString(Constants.ACCOUNT_TYPE) + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + val rootView = inflater.inflate(R.layout.fragment_accounts, container, false) + ButterKnife.bind(this, rootView) + accountsPresenter?.attachView(this) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = RecyclerView.VERTICAL + rvAccounts?.layoutManager = layoutManager + rvAccounts?.setHasFixedSize(true) + rvAccounts?.addItemDecoration(DividerItemDecoration(activity, + layoutManager.orientation)) + rvAccounts?.addOnItemTouchListener(RecyclerItemClickListener(activity, this)) + swipeRefreshLayout?.setColorSchemeColors(*activity!! + .resources.getIntArray(R.array.swipeRefreshColors)) + swipeRefreshLayout?.setOnRefreshListener(this) + if (savedInstanceState == null) { + showProgress() + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putString(Constants.ACCOUNT_TYPE, accountType) + when (accountType) { + Constants.SAVINGS_ACCOUNTS -> outState.putParcelableArrayList(Constants.SAVINGS_ACCOUNTS, + ArrayList(savingAccounts)) + Constants.LOAN_ACCOUNTS -> outState.putParcelableArrayList(Constants.LOAN_ACCOUNTS, + ArrayList(loanAccounts)) + Constants.SHARE_ACCOUNTS -> outState.putParcelableArrayList(Constants.SHARE_ACCOUNTS, + ArrayList(shareAccounts)) + } + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + accountType = savedInstanceState.getString(Constants.ACCOUNT_TYPE) + when (accountType) { + Constants.SAVINGS_ACCOUNTS -> { + val savingAccountList: List = + savedInstanceState.getParcelableArrayList(Constants.SAVINGS_ACCOUNTS) + showSavingsAccounts(savingAccountList) + } + Constants.LOAN_ACCOUNTS -> { + val loanAccountList: List = + savedInstanceState.getParcelableArrayList( + Constants.LOAN_ACCOUNTS) + showLoanAccounts(loanAccountList) + } + Constants.SHARE_ACCOUNTS -> { + val shareAccountList: List = + savedInstanceState.getParcelableArrayList( + Constants.SHARE_ACCOUNTS) + showShareAccounts(shareAccountList) + } + } + } + } + + /** + * Used for reloading account of a particular `accountType` in case of a network error. + */ + @OnClick(R.id.btn_try_again) + fun onRetry() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvAccounts, layoutError) + accountsPresenter?.loadAccounts(accountType) + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + /** + * This method is called when we swipe to refresh the view and is used for reloading account of + * a particular `accountType` + */ + override fun onRefresh() { + if (Network.isConnected(context)) { + clearFilter() + accountsPresenter?.loadAccounts(accountType) + } else { + hideProgress() + sweetUIErrorHandler?.showSweetNoInternetUI(rvAccounts, layoutError) + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + /** + * Method to clear the current filters and set + * currentFilterList = null + */ + fun clearFilter() { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvAccounts, layoutError) + currentFilterList = null + } + + /** + * Shows [List] of [LoanAccount] fetched from server using + * [LoanAccountsListAdapter] + * + * @param loanAccounts [List] of [LoanAccount] + */ + override fun showLoanAccounts(loanAccounts: List?) { + Collections.sort(loanAccounts, ComparatorBasedOnId()) + this.loanAccounts = loanAccounts + if (loanAccounts?.isNotEmpty() == true) { + loanAccountsListAdapter?.setLoanAccountsList(loanAccounts) + rvAccounts?.adapter = loanAccountsListAdapter + } else { + showEmptyAccounts(getString(R.string.loan_account)) + } + } + + /** + * Shows [List] of [SavingAccount] fetched from server using + * [SavingAccountsListAdapter] + * + * @param savingAccounts [List] of [SavingAccount] + */ + override fun showSavingsAccounts(savingAccounts: List?) { + Collections.sort(savingAccounts, ComparatorBasedOnId()) + this.savingAccounts = savingAccounts + if (savingAccounts?.isNotEmpty() == true) { + savingAccountsListAdapter?.setSavingAccountsList(savingAccounts) + rvAccounts?.adapter = savingAccountsListAdapter + } else { + showEmptyAccounts(getString(R.string.savings_account)) + } + } + + /** + * Shows [List] of [ShareAccount] fetched from server using + * [ShareAccountsListAdapter] + * + * @param shareAccounts [List] of [ShareAccount] + */ + override fun showShareAccounts(shareAccounts: List?) { + Collections.sort(shareAccounts, ComparatorBasedOnId()) + this.shareAccounts = shareAccounts + if (shareAccounts?.isNotEmpty() == true) { + shareAccountsListAdapter?.setShareAccountsList(shareAccounts) + rvAccounts?.adapter = shareAccountsListAdapter + } else { + showEmptyAccounts(getString(R.string.share_account)) + } + } + + /** + * Shows an error layout when this function is called. + * + * @param emptyAccounts Text to show in `noAccountText` + */ + private fun showEmptyAccounts(emptyAccounts: String?) { + sweetUIErrorHandler?.showSweetEmptyUI(emptyAccounts, + R.drawable.ic_account_balance_wallet_black_background_24dp, + rvAccounts, layoutError) + } + + /** + * Used for searching an `input` String in `savingAccounts` and displaying it in the + * recyclerview. + * + * @param input String which is needs to be searched in list + */ + fun searchSavingsAccount(input: String?) { + val searchResult = accountsPresenter?.searchInSavingsList(savingAccounts, input) + if (searchResult?.size == 0) { + showEmptyAccounts(getString(R.string.no_saving_account)) + } else { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvAccounts, layoutError) + savingAccountsListAdapter?.setSavingAccountsList(searchResult) + } + } + + /** + * Used for searching an `input` String in `loanAccounts` and displaying it in the + * recyclerview. + * + * @param input String which is needs to be searched in list + */ + fun searchLoanAccount(input: String?) { + val searchResult: List? = accountsPresenter?.searchInLoanList(loanAccounts, input) + if (searchResult?.size == 0) { + showEmptyAccounts(getString(R.string.no_loan_account)) + } else { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvAccounts, layoutError) + loanAccountsListAdapter?.setLoanAccountsList(searchResult) + } + } + + /** + * Used for searching an `input` String in `savingAccounts` and displaying it in the + * recyclerview. + * + * @param input String which is needs to be searched in list + */ + fun searchSharesAccount(input: String?) { + val searchResult: List? = accountsPresenter?.searchInSharesList(shareAccounts, input) + if (searchResult?.size == 0) { + showEmptyAccounts(getString(R.string.no_sharing_account)) + } else { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvAccounts, layoutError) + shareAccountsListAdapter?.setShareAccountsList(searchResult) + } + } + + /** + * Used for filtering `savingAccounts` depending upon [List] of + * [CheckboxStatus] + * + * @param statusModelList [List] of [CheckboxStatus] + */ + fun filterSavingsAccount(statusModelList: List?) { + val filteredSavings: MutableList? = ArrayList() + if (accountsPresenter?.getCheckedStatus(statusModelList) != null && accountsPresenter != null) { + for (status in accountsPresenter?.getCheckedStatus(statusModelList)!!) { + accountsPresenter?.getFilteredSavingsAccount(savingAccounts, + status)?.let { filteredSavings?.addAll(it) } + } + } + if (filteredSavings?.size == 0) { + showEmptyAccounts(getString(R.string.no_saving_account)) + } else { + savingAccountsListAdapter?.setSavingAccountsList(filteredSavings) + } + } + + /** + * Used for filtering `loanAccounts` depending upon [List] of + * [CheckboxStatus] + * + * @param statusModelList [List] of [CheckboxStatus] + */ + fun filterLoanAccount(statusModelList: List?) { + val filteredSavings: MutableList? = ArrayList() + when { + accountsPresenter != null && accountsPresenter?.getCheckedStatus(statusModelList) != null -> { + for (status in accountsPresenter?.getCheckedStatus(statusModelList)!!) { + accountsPresenter?.getFilteredLoanAccount(loanAccounts, + status)?.let { filteredSavings?.addAll(it) } + } + } + filteredSavings?.size == 0 -> { + showEmptyAccounts(getString(R.string.no_loan_account)) + } + else -> { + loanAccountsListAdapter?.setLoanAccountsList(filteredSavings) + } + } + } + + /** + * Used for filtering `shareAccounts` depending upon [List] of + * [CheckboxStatus] + * + * @param statusModelList [List] of [CheckboxStatus] + */ + fun filterShareAccount(statusModelList: List?) { + val filteredSavings: MutableList? = ArrayList() + when { + accountsPresenter != null && accountsPresenter?.getCheckedStatus(statusModelList) != null -> { + for (status in accountsPresenter?.getCheckedStatus(statusModelList)!!) { + accountsPresenter?.getFilteredShareAccount(shareAccounts, + status)?.let { filteredSavings?.addAll(it) } + } + } + filteredSavings?.size == 0 -> { + showEmptyAccounts(getString(R.string.no_sharing_account)) + } + else -> { + shareAccountsListAdapter?.setShareAccountsList(filteredSavings) + } + } + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param errorMessage Error message that tells the user about the problem. + */ + override fun showError(errorMessage: String?) { + if (!Network.isConnected(context)) { + sweetUIErrorHandler?.showSweetNoInternetUI(rvAccounts, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(errorMessage, rvAccounts, layoutError) + Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show() + } + hideProgress() + } + + /** + * Shows [SwipeRefreshLayout] + */ + override fun showProgress() { + showSwipeRefreshLayout(true) + } + + /** + * Hides [SwipeRefreshLayout] + */ + override fun hideProgress() { + showSwipeRefreshLayout(false) + } + + private fun showSwipeRefreshLayout(show: Boolean) { + swipeRefreshLayout?.isRefreshing = show + } + + override fun onDestroyView() { + super.onDestroyView() + accountsPresenter?.detachView() + } + + override fun onItemClick(childView: View?, position: Int) { + var intent: Intent? = null + when (accountType) { + Constants.SAVINGS_ACCOUNTS -> { + intent = Intent(activity, SavingsAccountContainerActivity::class.java) + intent.putExtra(Constants.SAVINGS_ID, savingAccountsListAdapter + ?.getSavingAccountsList()?.get(position)?.id) + } + Constants.LOAN_ACCOUNTS -> { + intent = Intent(activity, LoanAccountContainerActivity::class.java) + intent.putExtra(Constants.LOAN_ID, loanAccountsListAdapter?.getLoanAccountsList() + ?.get(position)?.id) + } + } + openActivity(intent) + } + + override fun onItemLongPress(childView: View?, position: Int) {} + + /** + * This function opens up an activity only if the intent + * is not null. + * + * This will prevent the application from crashing if the + * intent is null. + */ + private fun openActivity(intent: Intent?) { + intent?.let { startActivity(it) } + } + + companion object { + val LOG_TAG: String? = AccountsFragment::class.java.simpleName + fun newInstance(accountType: String?): AccountsFragment { + val fragment = AccountsFragment() + val args = Bundle() + args.putString(Constants.ACCOUNT_TYPE, accountType) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AddGuarantorFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/AddGuarantorFragment.java deleted file mode 100644 index 85f2341871..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/AddGuarantorFragment.java +++ /dev/null @@ -1,246 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* - * Created by saksham on 23/July/2018 - */ - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.Spinner; -import android.widget.Toast; - -import com.google.android.material.textfield.TextInputLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload; -import org.mifos.mobile.models.guarantor.GuarantorType; -import org.mifos.mobile.presenters.AddGuarantorPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.GuarantorState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.AddGuarantorView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.RxBus; -import org.mifos.mobile.utils.RxEvent; -import org.mifos.mobile.utils.Toaster; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -public class AddGuarantorFragment extends BaseFragment implements AddGuarantorView { - - @BindView(R.id.sp_guarantor_type) - Spinner spGuarantorType; - - @BindView(R.id.til_first_name) - TextInputLayout tilFirstName; - - @BindView(R.id.til_last_name) - TextInputLayout tilLastName; - - @BindView(R.id.til_office_name) - TextInputLayout tilOfficeName; - - @Inject - AddGuarantorPresenter presenter; - - ArrayAdapter guarantorTypeAdapter; - GuarantorTemplatePayload template; - GuarantorPayload payload; - GuarantorState guarantorState; - GuarantorApplicationPayload guarantorApplicationPayload; - View rootView; - long loanId; - int index; - - public static AddGuarantorFragment newInstance(int index, GuarantorState guarantorState, - GuarantorPayload payload, long loanId) { - AddGuarantorFragment fragment = new AddGuarantorFragment(); - Bundle bundle = new Bundle(); - bundle.putLong(Constants.LOAN_ID, loanId); - bundle.putSerializable(Constants.GUARANTOR_STATE, guarantorState); - bundle.putParcelable(Constants.PAYLOAD, payload); - bundle.putInt(Constants.INDEX, index); - fragment.setArguments(bundle); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - loanId = getArguments().getLong(Constants.LOAN_ID); - guarantorState = (GuarantorState) getArguments() - .getSerializable(Constants.GUARANTOR_STATE); - payload = getArguments().getParcelable(Constants.PAYLOAD); - index = getArguments().getInt(Constants.INDEX); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_add_guarantor, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - presenter.attachView(this); - if (guarantorState == GuarantorState.CREATE) { - setToolbarTitle(getString(R.string.add_guarantor)); - } else if (guarantorState == GuarantorState.UPDATE) { - setToolbarTitle(getString(R.string.update_guarantor)); - } - return rootView; - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - presenter.getGuarantorTemplate(guarantorState, loanId); - } - - @OnClick(R.id.btn_submit_guarantor) - void onSubmit() { - tilFirstName.setErrorEnabled(false); - tilLastName.setErrorEnabled(false); - tilOfficeName.setErrorEnabled(false); - if (isFieldsCompleted()) { - guarantorApplicationPayload = generatePayload(); - if (guarantorState == GuarantorState.CREATE) { - presenter.createGuarantor(loanId, guarantorApplicationPayload); - } else if (guarantorState == GuarantorState.UPDATE) { - presenter.updateGuarantor(guarantorApplicationPayload, loanId, payload.getId()); - } - } - } - - private GuarantorApplicationPayload generatePayload() { - return new GuarantorApplicationPayload( - template.getGuarantorTypeOptions() - .get(getGuarantorTypeIndex(spGuarantorType.getSelectedItem().toString())), - tilFirstName.getEditText().getText().toString().trim(), - tilLastName.getEditText().getText().toString().trim(), - tilOfficeName.getEditText().getText().toString().trim() - ); - } - - private boolean isFieldsCompleted() { - boolean rv = true; - if (tilFirstName.getEditText().getText().toString().trim().length() == 0) { - tilFirstName.setError(getString(R.string.error_validation_blank, - getString(R.string.first_name))); - rv = false; - } - if (tilLastName.getEditText().getText().toString().trim().length() == 0) { - tilLastName.setError(getString(R.string.error_validation_blank, - getString(R.string.last_name))); - rv = false; - } - if (tilOfficeName.getEditText().getText().toString().trim().length() == 0) { - tilOfficeName.setError(getString(R.string.error_validation_blank, - getString(R.string.office_name))); - rv = false; - } - return rv; - } - - private int getGuarantorTypeIndex(String optionSelected) { - int rv = 0; - for (GuarantorType option : template.getGuarantorTypeOptions()) { - if (option.getValue().equals(optionSelected)) { - return rv; - } - rv++; - } - return rv; - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroy() { - super.onDestroy(); - presenter.detachView(); - hideProgressBar(); - } - - @Override - public void showGuarantorApplication(GuarantorTemplatePayload template) { - this.template = template; - setUpSpinner(); - } - - - @Override - public void showGuarantorUpdation(GuarantorTemplatePayload template) { - this.template = template; - setUpSpinner(); - tilFirstName.getEditText().setText(payload.getFirstname()); - tilLastName.getEditText().setText(payload.getLastname()); - tilOfficeName.getEditText().setText(payload.getOfficeName()); - spGuarantorType.setSelection(findPreviouslySelectedGuarantorType(payload.getGuarantorType() - .getValue())); - } - - private int findPreviouslySelectedGuarantorType(String value) { - int rv = 0; - int counter = 0; - for (GuarantorType option : template.getGuarantorTypeOptions()) { - if (option.getValue().equals(value)) { - rv = counter; - } - counter++; - } - return rv; - } - - private void setUpSpinner() { - List options = new ArrayList<>(); - for (GuarantorType option : template.getGuarantorTypeOptions()) { - options.add(option.getValue()); - } - guarantorTypeAdapter = new ArrayAdapter<>(getContext(), - android.R.layout.simple_spinner_dropdown_item, options); - spGuarantorType.setAdapter(guarantorTypeAdapter); - } - - @Override - public void updatedSuccessfully(String message) { - Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); - RxBus.publish(new RxEvent.UpdateGuarantorEvent(guarantorApplicationPayload, index)); - getActivity().getSupportFragmentManager().popBackStack(); - } - - @Override - public void submittedSuccessfully(String message, GuarantorApplicationPayload payload) { - Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); - RxBus.publish(new RxEvent.AddGuarantorEvent(payload, index)); - getActivity().getSupportFragmentManager().popBackStack(); - } - - @Override - public void showError(String message) { - Toaster.show(rootView, message); - } - -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/AddGuarantorFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/AddGuarantorFragment.kt new file mode 100644 index 0000000000..522dbf4e1c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/AddGuarantorFragment.kt @@ -0,0 +1,238 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ArrayAdapter +import android.widget.Spinner +import android.widget.Toast + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.google.android.material.textfield.TextInputLayout + +import org.mifos.mobile.R +import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload +import org.mifos.mobile.presenters.AddGuarantorPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.GuarantorState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.AddGuarantorView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.RxBus.publish +import org.mifos.mobile.utils.RxEvent.AddGuarantorEvent +import org.mifos.mobile.utils.RxEvent.UpdateGuarantorEvent +import org.mifos.mobile.utils.Toaster + +import java.util.* +import javax.inject.Inject + +/* +* Created by saksham on 23/July/2018 +*/ +class AddGuarantorFragment : BaseFragment(), AddGuarantorView { + + @kotlin.jvm.JvmField + @BindView(R.id.sp_guarantor_type) + var spGuarantorType: Spinner? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_first_name) + var tilFirstName: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_last_name) + var tilLastName: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_office_name) + var tilOfficeName: TextInputLayout? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: AddGuarantorPresenter? = null + var guarantorTypeAdapter: ArrayAdapter? = null + var template: GuarantorTemplatePayload? = null + var payload: GuarantorPayload? = null + private var guarantorState: GuarantorState? = null + private var guarantorApplicationPayload: GuarantorApplicationPayload? = null + var rootView: View? = null + var loanId: Long? = 0 + var index: Int? = 0 + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + loanId = arguments?.getLong(Constants.LOAN_ID) + guarantorState = arguments!! + .getSerializable(Constants.GUARANTOR_STATE) as GuarantorState + payload = arguments?.getParcelable(Constants.PAYLOAD) + index = arguments?.getInt(Constants.INDEX) + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_add_guarantor, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + presenter?.attachView(this) + if (guarantorState == GuarantorState.CREATE) { + setToolbarTitle(getString(R.string.add_guarantor)) + } else if (guarantorState == GuarantorState.UPDATE) { + setToolbarTitle(getString(R.string.update_guarantor)) + } + return rootView + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + presenter?.getGuarantorTemplate(guarantorState, loanId) + } + + @OnClick(R.id.btn_submit_guarantor) + fun onSubmit() { + tilFirstName?.isErrorEnabled = false + tilLastName?.isErrorEnabled = false + tilOfficeName?.isErrorEnabled = false + if (isFieldsCompleted) { + guarantorApplicationPayload = generatePayload() + if (guarantorState == GuarantorState.CREATE) { + presenter?.createGuarantor(loanId, guarantorApplicationPayload) + } else if (guarantorState == GuarantorState.UPDATE) { + presenter?.updateGuarantor(guarantorApplicationPayload, loanId, payload?.id) + } + } + } + + private fun generatePayload(): GuarantorApplicationPayload { + return GuarantorApplicationPayload( + template?.guarantorTypeOptions + ?.get(getGuarantorTypeIndex(spGuarantorType?.selectedItem.toString())), + tilFirstName?.editText?.text.toString().trim { it <= ' ' }, + tilLastName?.editText?.text.toString().trim { it <= ' ' }, + tilOfficeName?.editText?.text.toString().trim { it <= ' ' } + ) + } + + private val isFieldsCompleted: Boolean + get() { + var rv = true + if (tilFirstName?.editText?.text.toString().trim { it <= ' ' }.isEmpty()) { + tilFirstName?.error = getString(R.string.error_validation_blank, + getString(R.string.first_name)) + rv = false + } + if (tilLastName?.editText?.text.toString().trim { it <= ' ' }.isEmpty()) { + tilLastName?.error = getString(R.string.error_validation_blank, + getString(R.string.last_name)) + rv = false + } + if (tilOfficeName?.editText?.text.toString().trim { it <= ' ' }.isEmpty()) { + tilOfficeName?.error = getString(R.string.error_validation_blank, + getString(R.string.office_name)) + rv = false + } + return rv + } + + private fun getGuarantorTypeIndex(optionSelected: String): Int { + var rv = 0 + for (option in template?.guarantorTypeOptions!!) { + if (option.value == optionSelected) { + return rv + } + rv++ + } + return rv + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroy() { + super.onDestroy() + presenter?.detachView() + hideProgressBar() + } + + override fun showGuarantorApplication(template: GuarantorTemplatePayload?) { + this.template = template + setUpSpinner() + } + + override fun showGuarantorUpdation(template: GuarantorTemplatePayload?) { + this.template = template + setUpSpinner() + tilFirstName?.editText?.setText(payload?.firstname) + tilLastName?.editText?.setText(payload?.lastname) + tilOfficeName?.editText?.setText(payload?.officeName) + spGuarantorType?.setSelection(findPreviouslySelectedGuarantorType(payload?.guarantorType + ?.value)) + } + + private fun findPreviouslySelectedGuarantorType(value: String?): Int { + var rv = 0 + var counter = 0 + for (option in template?.guarantorTypeOptions!!) { + if (option.value == value) { + rv = counter + } + counter++ + } + return rv + } + + private fun setUpSpinner() { + val options: MutableList = ArrayList() + for (option in template?.guarantorTypeOptions!!) { + options.add(option.value) + } + guarantorTypeAdapter = ArrayAdapter(context, + android.R.layout.simple_spinner_dropdown_item, options) + spGuarantorType?.adapter = guarantorTypeAdapter + } + + override fun updatedSuccessfully(message: String?) { + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + publish(UpdateGuarantorEvent(guarantorApplicationPayload, index)) + activity?.supportFragmentManager?.popBackStack() + } + + override fun submittedSuccessfully(message: String?, payload: GuarantorApplicationPayload?) { + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + publish(AddGuarantorEvent(payload, index)) + activity?.supportFragmentManager?.popBackStack() + } + + override fun showError(message: String?) { + Toaster.show(rootView, message) + } + + companion object { + fun newInstance( + index: Int?, guarantorState: GuarantorState?, + payload: GuarantorPayload?, loanId: Long? + ): AddGuarantorFragment { + val fragment = AddGuarantorFragment() + val bundle = Bundle() + if (loanId != null) bundle.putLong(Constants.LOAN_ID, loanId) + bundle.putSerializable(Constants.GUARANTOR_STATE, guarantorState) + if (index != null) bundle.putInt(Constants.INDEX, index) + bundle.putParcelable(Constants.PAYLOAD, payload) + fragment.arguments = bundle + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryAddOptionsFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryAddOptionsFragment.java deleted file mode 100644 index 201b83a5fb..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryAddOptionsFragment.java +++ /dev/null @@ -1,214 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.Manifest; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.BeneficiaryState; -import org.mifos.mobile.ui.enums.RequestAccessType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.utils.CheckSelfPermissionAndRequest; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.Toaster; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 5/7/17. - */ - -public class BeneficiaryAddOptionsFragment extends BaseFragment { - - private View rootView; - private boolean external_storage_read_status = false; - private boolean external_storage_write_status = false; - - public static BeneficiaryAddOptionsFragment newInstance() { - BeneficiaryAddOptionsFragment fragment = new BeneficiaryAddOptionsFragment(); - Bundle args = new Bundle(); - fragment.setArguments(args); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_beneficiary_add_options, container, false); - setToolbarTitle(getString(R.string.add_beneficiary)); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - - return rootView; - } - - /** - * Opens {@link BeneficiaryApplicationFragment} with {@link BeneficiaryState} as - * {@code BeneficiaryState.CREATE_MANUAL} - */ - @OnClick(R.id.ll_add_beneficiary_manually) - public void addManually() { - ((BaseActivity) getActivity()).replaceFragment(BeneficiaryApplicationFragment. - newInstance(BeneficiaryState.CREATE_MANUAL, null), true, R.id.container); - } - - /** - * It first checks CAMERA runtime permission and if it returns true then it opens - * {@link QrCodeReaderFragment} , if it returns false then ask for permissions. - */ - @OnClick(R.id.ll_add_beneficiary_qrcode) - public void addUsingQrCode() { - - if (CheckSelfPermissionAndRequest.checkSelfPermission(getActivity(), - Manifest.permission.CAMERA)) { - ((BaseActivity) getActivity()).replaceFragment(QrCodeReaderFragment. - newInstance(), true, R.id.container); - } else { - requestPermission(RequestAccessType.CAMERA); - } - } - - /** - * It first checks Storage Read and Write Permission then if both of them are true then it opens - * Intent to all gallery app - */ - @OnClick(R.id.ll_upload_beneficiary_qrcode) - public void addByImportingQrCode() { - - //request permission for writing external storage - accessReadWriteAccess(); - if (external_storage_write_status && external_storage_read_status) { - Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT); - getIntent.setType("image/*"); - Intent pickIntent = new Intent(Intent.ACTION_PICK, - android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); - pickIntent.setType("image/*"); - Intent chooserIntent = Intent.createChooser(getIntent, "Select Image"); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent}); - startActivityForResult(chooserIntent, Constants.GALLERY_QR_PICK); - } - - } - - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - if (requestCode == Constants.GALLERY_QR_PICK && data != null) { - getActivity().getSupportFragmentManager().popBackStack(); - ((BaseActivity) getActivity()).replaceFragment(QrCodeImportFragment - .newInstance(data.getData()), true, R.id.container); - } - } - - public void accessReadWriteAccess() { - if (CheckSelfPermissionAndRequest.checkSelfPermission(getActivity(), - Manifest.permission.READ_EXTERNAL_STORAGE)) { - external_storage_read_status = true; - } else { - requestPermission(RequestAccessType.EXTERNAL_STORAGE_READ); - } - if (CheckSelfPermissionAndRequest.checkSelfPermission(getActivity(), - Manifest.permission.WRITE_EXTERNAL_STORAGE)) { - external_storage_write_status = true; - } else { - requestPermission(RequestAccessType.EXTERNAL_STORAGE_WRITE); - } - } - - /** - * Uses {@link CheckSelfPermissionAndRequest} to check for runtime permissions - */ - private void requestPermission(RequestAccessType requestAccessType) { - - switch (requestAccessType) { - case CAMERA: { - CheckSelfPermissionAndRequest.requestPermission( - (BaseActivity) getActivity(), - Manifest.permission.CAMERA, - Constants.PERMISSIONS_REQUEST_CAMERA, - getResources().getString( - R.string.dialog_message_camera_permission_denied_prompt), - getResources().getString(R - .string.dialog_message_camera_permission_never_ask_again), - Constants.PERMISSIONS_CAMERA_STATUS); - } - break; - case EXTERNAL_STORAGE_READ: { - CheckSelfPermissionAndRequest.requestPermission((BaseActivity) getActivity(), - Manifest.permission.READ_EXTERNAL_STORAGE, - Constants.PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE, - getResources().getString(R - .string.dialog_message_storage_permission_denied_prompt), - getResources() - .getString(R.string - .dialog_message_read_storage_permission_never_ask_again), - Constants.PERMISSIONS_STORAGE_STATUS); - - } - break; - case EXTERNAL_STORAGE_WRITE: { - CheckSelfPermissionAndRequest.requestPermission((BaseActivity) getActivity(), - Manifest.permission.WRITE_EXTERNAL_STORAGE, - Constants.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE, - getResources().getString(R - .string.dialog_message_storage_permission_denied_prompt), - getResources().getString(R - .string.dialog_message_write_storage_permission_never_ask_again), - Constants.PERMISSIONS_STORAGE_STATUS); - } - - } - - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { - switch (requestCode) { - case Constants.PERMISSIONS_REQUEST_CAMERA: { - - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - ((BaseActivity) getActivity()).replaceFragment(QrCodeReaderFragment. - newInstance(), true, R.id.container); - - } else { - - Toaster.show(rootView, getResources() - .getString(R.string.permission_denied_camera)); - } - } - break; - case Constants.PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { - - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - external_storage_read_status = true; - } else { - Toaster.show(rootView, getResources() - .getString(R.string.permission_denied_storage)); - } - - } - break; - case Constants.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - external_storage_write_status = true; - } else { - Toaster.show(rootView, getResources() - .getString(R.string.permission_denied_storage)); - } - } - - } - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryAddOptionsFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryAddOptionsFragment.kt new file mode 100644 index 0000000000..cb4e2c08ce --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryAddOptionsFragment.kt @@ -0,0 +1,183 @@ +package org.mifos.mobile.ui.fragments + +import android.Manifest +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Bundle +import android.provider.MediaStore +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import butterknife.ButterKnife +import butterknife.OnClick +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.BeneficiaryState +import org.mifos.mobile.ui.enums.RequestAccessType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.utils.CheckSelfPermissionAndRequest +import org.mifos.mobile.utils.CheckSelfPermissionAndRequest.checkSelfPermission +import org.mifos.mobile.utils.CheckSelfPermissionAndRequest.requestPermission +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.Toaster + +/** + * Created by dilpreet on 5/7/17. + */ +class BeneficiaryAddOptionsFragment : BaseFragment() { + private var rootView: View? = null + private var external_storage_read_status = false + private var external_storage_write_status = false + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_beneficiary_add_options, container, false) + setToolbarTitle(getString(R.string.add_beneficiary)) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + return rootView + } + + /** + * Opens [BeneficiaryApplicationFragment] with [BeneficiaryState] as + * `BeneficiaryState.CREATE_MANUAL` + */ + @OnClick(R.id.ll_add_beneficiary_manually) + fun addManually() { + (activity as BaseActivity?)?.replaceFragment(BeneficiaryApplicationFragment.newInstance(BeneficiaryState.CREATE_MANUAL, null), true, R.id.container) + } + + /** + * It first checks CAMERA runtime permission and if it returns true then it opens + * [QrCodeReaderFragment] , if it returns false then ask for permissions. + */ + @OnClick(R.id.ll_add_beneficiary_qrcode) + fun addUsingQrCode() { + if (checkSelfPermission(activity, + Manifest.permission.CAMERA)) { + (activity as BaseActivity?)?.replaceFragment(QrCodeReaderFragment.newInstance(), true, R.id.container) + } else { + requestPermission(RequestAccessType.CAMERA) + } + } + + /** + * It first checks Storage Read and Write Permission then if both of them are true then it opens + * Intent to all gallery app + */ + @OnClick(R.id.ll_upload_beneficiary_qrcode) + fun addByImportingQrCode() { + + //request permission for writing external storage + accessReadWriteAccess() + if (external_storage_write_status && external_storage_read_status) { + val getIntent = Intent(Intent.ACTION_GET_CONTENT) + getIntent.type = "image/*" + val pickIntent = Intent(Intent.ACTION_PICK, + MediaStore.Images.Media.EXTERNAL_CONTENT_URI) + pickIntent.type = "image/*" + val chooserIntent = Intent.createChooser(getIntent, "Select Image") + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(pickIntent)) + startActivityForResult(chooserIntent, Constants.GALLERY_QR_PICK) + } + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (requestCode == Constants.GALLERY_QR_PICK && data != null) { + activity?.supportFragmentManager?.popBackStack() + (activity as BaseActivity?)?.replaceFragment(QrCodeImportFragment.newInstance(data.data), true, R.id.container) + } + } + + private fun accessReadWriteAccess() { + if (checkSelfPermission(activity, + Manifest.permission.READ_EXTERNAL_STORAGE)) { + external_storage_read_status = true + } else { + requestPermission(RequestAccessType.EXTERNAL_STORAGE_READ) + } + if (checkSelfPermission(activity, + Manifest.permission.WRITE_EXTERNAL_STORAGE)) { + external_storage_write_status = true + } else { + requestPermission(RequestAccessType.EXTERNAL_STORAGE_WRITE) + } + } + + /** + * Uses [CheckSelfPermissionAndRequest] to check for runtime permissions + */ + private fun requestPermission(requestAccessType: RequestAccessType) { + when (requestAccessType) { + RequestAccessType.CAMERA -> { + requestPermission( + (activity as BaseActivity?)!!, + Manifest.permission.CAMERA, + Constants.PERMISSIONS_REQUEST_CAMERA, + resources.getString( + R.string.dialog_message_camera_permission_denied_prompt), + resources.getString(R.string.dialog_message_camera_permission_never_ask_again), + Constants.PERMISSIONS_CAMERA_STATUS) + } + RequestAccessType.EXTERNAL_STORAGE_READ -> { + requestPermission((activity as BaseActivity?)!!, + Manifest.permission.READ_EXTERNAL_STORAGE, + Constants.PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE, + resources.getString(R.string.dialog_message_storage_permission_denied_prompt), + resources + .getString(R.string.dialog_message_read_storage_permission_never_ask_again), + Constants.PERMISSIONS_STORAGE_STATUS) + } + RequestAccessType.EXTERNAL_STORAGE_WRITE -> { + requestPermission((activity as BaseActivity?)!!, + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Constants.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE, + resources.getString(R.string.dialog_message_storage_permission_denied_prompt), + resources.getString(R.string.dialog_message_write_storage_permission_never_ask_again), + Constants.PERMISSIONS_STORAGE_STATUS) + } + } + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, + grantResults: IntArray) { + when (requestCode) { + Constants.PERMISSIONS_REQUEST_CAMERA -> { + if (grantResults.size > 0 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + (activity as BaseActivity?)?.replaceFragment(QrCodeReaderFragment.newInstance(), true, R.id.container) + } else { + Toaster.show(rootView, resources + .getString(R.string.permission_denied_camera)) + } + } + Constants.PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE -> { + if (grantResults.size > 0 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + external_storage_read_status = true + } else { + Toaster.show(rootView, resources + .getString(R.string.permission_denied_storage)) + } + } + Constants.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE -> { + if (grantResults.size > 0 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + external_storage_write_status = true + } else { + Toaster.show(rootView, resources + .getString(R.string.permission_denied_storage)) + } + } + } + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): BeneficiaryAddOptionsFragment { + val fragment = BeneficiaryAddOptionsFragment() + val args = Bundle() + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryApplicationFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryApplicationFragment.java deleted file mode 100644 index ff1f6be31f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryApplicationFragment.java +++ /dev/null @@ -1,343 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.LinearLayout; -import android.widget.Spinner; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; -import com.google.android.material.snackbar.Snackbar; -import com.google.android.material.textfield.TextInputLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.beneficiary.BeneficiaryPayload; -import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload; -import org.mifos.mobile.models.templates.beneficiary.AccountTypeOption; -import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; -import org.mifos.mobile.presenters.BeneficiaryApplicationPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.BeneficiaryState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.BeneficiaryApplicationView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.Toaster; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.core.widget.NestedScrollView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 16/6/17. - */ - -public class BeneficiaryApplicationFragment extends BaseFragment implements - BeneficiaryApplicationView, AdapterView.OnItemSelectedListener { - - @BindView(R.id.sp_account_type) - Spinner spAccountType; - - @BindView(R.id.ll_application_beneficiary) - LinearLayout llApplicationBeneficiary; - - @BindView(R.id.til_account_number) - TextInputLayout tilAccountNumber; - - @BindView(R.id.til_office_name) - TextInputLayout tilOfficeName; - - @BindView(R.id.til_transfer_limit) - TextInputLayout tilTransferLimit; - - @BindView(R.id.til_beneficiary_name) - TextInputLayout tilBeneficiaryName; - - @BindView(R.id.layout_error) - View layoutError; - - @BindView(R.id.view_flipper) - NestedScrollView nsvBeneficiary; - - @Inject - BeneficiaryApplicationPresenter presenter; - - private List listAccountType = new ArrayList<>(); - private ArrayAdapter accountTypeAdapter; - - private BeneficiaryState beneficiaryState; - private Beneficiary beneficiary; - private BeneficiaryTemplate beneficiaryTemplate; - private int accountTypeId = -1; - private View rootView; - private SweetUIErrorHandler sweetUIErrorHandler; - - public static BeneficiaryApplicationFragment newInstance(BeneficiaryState beneficiaryState, - @Nullable Beneficiary beneficiary) { - BeneficiaryApplicationFragment fragment = new BeneficiaryApplicationFragment(); - Bundle args = new Bundle(); - args.putSerializable(Constants.BENEFICIARY_STATE, beneficiaryState); - if (beneficiary != null) { - args.putParcelable(Constants.BENEFICIARY, beneficiary); - } - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setToolbarTitle(getString(R.string.add_beneficiary)); - if (getArguments() != null) { - beneficiaryState = (BeneficiaryState) getArguments() - .getSerializable(Constants.BENEFICIARY_STATE); - if (beneficiaryState == BeneficiaryState.UPDATE) { - beneficiary = getArguments().getParcelable(Constants.BENEFICIARY); - setToolbarTitle(getString(R.string.update_beneficiary)); - } else if (beneficiaryState == BeneficiaryState.CREATE_QR) { - beneficiary = getArguments().getParcelable(Constants.BENEFICIARY); - setToolbarTitle(getString(R.string.add_beneficiary)); - } else { - setToolbarTitle(getString(R.string.add_beneficiary)); - } - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_beneficiary_application, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - showUserInterface(); - - presenter.attachView(this); - if (savedInstanceState == null) { - presenter.loadBeneficiaryTemplate(); - } - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.TEMPLATE, beneficiaryTemplate); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showBeneficiaryTemplate((BeneficiaryTemplate) savedInstanceState. - getParcelable(Constants.TEMPLATE)); - } - } - - /** - * Setting up {@code accountTypeAdapter} and {@code} spAccountType - */ - @Override - public void showUserInterface() { - accountTypeAdapter = new ArrayAdapter<>(getActivity(), - android.R.layout.simple_spinner_item, listAccountType); - accountTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - spAccountType.setOnItemSelectedListener(this); - if (!Network.isConnected(getContext())) { - spAccountType.setEnabled(false); - } - spAccountType.setAdapter(accountTypeAdapter); - } - - /** - * Fetches {@link BeneficiaryTemplate} from server and further updates the UI according to - * {@link BeneficiaryState} which is initialized in {@code newInstance()} as - * {@code beneficiaryState} - * - * @param beneficiaryTemplate {@link BeneficiaryTemplate} fetched from server - */ - @Override - public void showBeneficiaryTemplate(BeneficiaryTemplate beneficiaryTemplate) { - this.beneficiaryTemplate = beneficiaryTemplate; - for (AccountTypeOption accountTypeOption : beneficiaryTemplate.getAccountTypeOptions()) { - listAccountType.add(accountTypeOption.getValue()); - } - accountTypeAdapter.notifyDataSetChanged(); - - if (beneficiaryState == BeneficiaryState.UPDATE) { - spAccountType.setSelection(accountTypeAdapter.getPosition(beneficiary - .getAccountType().getValue())); - spAccountType.setEnabled(false); - tilAccountNumber.getEditText().setText(beneficiary.getAccountNumber()); - tilAccountNumber.setEnabled(false); - tilOfficeName.getEditText().setText(beneficiary.getOfficeName()); - tilOfficeName.setEnabled(false); - tilBeneficiaryName.getEditText().setText(beneficiary.getName()); - tilTransferLimit.getEditText().setText(String.valueOf(beneficiary.getTransferLimit())); - } else if (beneficiaryState == BeneficiaryState.CREATE_QR) { - spAccountType.setSelection(beneficiary.getAccountType().getId()); - tilAccountNumber.getEditText().setText(beneficiary.getAccountNumber()); - tilOfficeName.getEditText().setText(beneficiary.getOfficeName()); - } - } - - /** - * Used for submitting a new or updating beneficiary application - */ - @OnClick(R.id.btn_beneficiary_submit) - public void submitBeneficiary() { - - tilAccountNumber.setErrorEnabled(false); - tilOfficeName.setErrorEnabled(false); - tilTransferLimit.setErrorEnabled(false); - tilBeneficiaryName.setErrorEnabled(false); - - if (accountTypeId == -1) { - Toaster.show(rootView, getString(R.string.choose_account_type)); - return; - } else if (tilAccountNumber.getEditText().getText().toString().trim().equals("")) { - tilAccountNumber.setError(getString(R.string.enter_account_number)); - return; - } else if (tilOfficeName.getEditText().getText().toString().trim().equals("")) { - tilOfficeName.setError(getString(R.string.enter_office_name)); - return; - } else if (tilTransferLimit.getEditText().getText().toString().equals("")) { - tilTransferLimit.setError(getString(R.string.enter_transfer_limit)); - return; - } else if (tilTransferLimit.getEditText().getText().toString().equals(".")) { - tilTransferLimit.setError(getString(R.string.invalid_amount)); - return; - } else if (tilTransferLimit.getEditText().getText().toString().matches("^0*")) { - tilTransferLimit.setError(getString(R.string.amount_greater_than_zero)); - return; - } else if (tilBeneficiaryName.getEditText().getText().toString().trim().equals("")) { - tilBeneficiaryName.setError(getString(R.string.enter_beneficiary_name)); - return; - } - - if (beneficiaryState == BeneficiaryState.CREATE_MANUAL || - beneficiaryState == BeneficiaryState.CREATE_QR) { - submitNewBeneficiaryApplication(); - } else if (beneficiaryState == BeneficiaryState.UPDATE) { - submitUpdateBeneficiaryApplication(); - } - - } - - @OnClick(R.id.btn_try_again) - public void onRetry() { - if (Network.isConnected(getContext())) { - presenter.loadBeneficiaryTemplate(); - sweetUIErrorHandler.hideSweetErrorLayoutUI(nsvBeneficiary, layoutError); - } else { - Toaster.show(rootView, getString(R.string.internet_not_connected)); - } - } - - /** - * Submit a new Beneficiary application - */ - private void submitNewBeneficiaryApplication() { - BeneficiaryPayload beneficiaryPayload = new BeneficiaryPayload(); - beneficiaryPayload.setAccountNumber(tilAccountNumber.getEditText().getText().toString()); - beneficiaryPayload.setOfficeName(tilOfficeName.getEditText().getText().toString()); - beneficiaryPayload.setAccountType(accountTypeId); - beneficiaryPayload.setName(tilBeneficiaryName.getEditText().getText().toString()); - beneficiaryPayload.setTransferLimit(Integer.parseInt(tilTransferLimit.getEditText(). - getText().toString())); - presenter.createBeneficiary(beneficiaryPayload); - } - - /** - * Updates an existing beneficiary application - */ - private void submitUpdateBeneficiaryApplication() { - BeneficiaryUpdatePayload payload = new BeneficiaryUpdatePayload(); - payload.setName(tilBeneficiaryName.getEditText().getText().toString()); - payload.setTransferLimit(Float.parseFloat(tilTransferLimit.getEditText().getText(). - toString())); - presenter.updateBeneficiary(beneficiary.getId(), payload); - } - - /** - * Displays a {@link Snackbar} on successfully creation of - * Beneficiary and pops fragments in order to go back to {@link BeneficiaryListFragment} - */ - @Override - public void showBeneficiaryCreatedSuccessfully() { - Toaster.show(rootView, getString(R.string.beneficiary_created_successfully)); - getActivity().finish(); - } - - /** - * Displays a {@link Snackbar} on successfully updation of - * Beneficiary and pops fragments in order to go back to {@link BeneficiaryListFragment} - */ - @Override - public void showBeneficiaryUpdatedSuccessfully() { - Toaster.show(rootView, getString(R.string.beneficiary_updated_successfully)); - getActivity().getSupportFragmentManager().popBackStack(); - getActivity().getSupportFragmentManager().popBackStack(); - - } - - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - accountTypeId = beneficiaryTemplate.getAccountTypeOptions().get(position).getId(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param msg Error message that tells the user about the problem. - */ - @Override - public void showError(String msg) { - if (!Network.isConnected(getContext())) { - sweetUIErrorHandler.showSweetNoInternetUI(nsvBeneficiary, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(msg, nsvBeneficiary, layoutError); - Toaster.show(rootView, msg); - } - } - - @Override - public void setVisibility(int state) { - llApplicationBeneficiary.setVisibility(state); - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryApplicationFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryApplicationFragment.kt new file mode 100644 index 0000000000..9092aba4f6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryApplicationFragment.kt @@ -0,0 +1,320 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.os.Parcelable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.AdapterView +import android.widget.AdapterView.OnItemSelectedListener +import android.widget.ArrayAdapter +import android.widget.LinearLayout +import android.widget.Spinner +import androidx.core.widget.NestedScrollView +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler +import com.google.android.material.textfield.TextInputLayout +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.beneficiary.BeneficiaryPayload +import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload +import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate +import org.mifos.mobile.presenters.BeneficiaryApplicationPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.BeneficiaryState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.BeneficiaryApplicationView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.Network +import org.mifos.mobile.utils.Toaster +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 16/6/17. + */ +class BeneficiaryApplicationFragment : BaseFragment(), BeneficiaryApplicationView, OnItemSelectedListener { + @kotlin.jvm.JvmField + @BindView(R.id.sp_account_type) + var spAccountType: Spinner? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_application_beneficiary) + var llApplicationBeneficiary: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_account_number) + var tilAccountNumber: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_office_name) + var tilOfficeName: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_transfer_limit) + var tilTransferLimit: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_beneficiary_name) + var tilBeneficiaryName: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @BindView(R.id.view_flipper) + var nsvBeneficiary: NestedScrollView? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: BeneficiaryApplicationPresenter? = null + private val listAccountType: MutableList = ArrayList() + private var accountTypeAdapter: ArrayAdapter? = null + private var beneficiaryState: BeneficiaryState? = null + private var beneficiary: Beneficiary? = null + private var beneficiaryTemplate: BeneficiaryTemplate? = null + private var accountTypeId: Int? = -1 + private var rootView: View? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setToolbarTitle(getString(R.string.add_beneficiary)) + if (arguments != null) { + beneficiaryState = arguments!! + .getSerializable(Constants.BENEFICIARY_STATE) as BeneficiaryState + when (beneficiaryState) { + BeneficiaryState.UPDATE -> { + beneficiary = arguments?.getParcelable(Constants.BENEFICIARY) + setToolbarTitle(getString(R.string.update_beneficiary)) + } + BeneficiaryState.CREATE_QR -> { + beneficiary = arguments?.getParcelable(Constants.BENEFICIARY) + setToolbarTitle(getString(R.string.add_beneficiary)) + } + else -> { + setToolbarTitle(getString(R.string.add_beneficiary)) + } + } + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_beneficiary_application, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + showUserInterface() + presenter?.attachView(this) + if (savedInstanceState == null) { + presenter?.loadBeneficiaryTemplate() + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.TEMPLATE, beneficiaryTemplate) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showBeneficiaryTemplate(savedInstanceState.getParcelable(Constants.TEMPLATE) as BeneficiaryTemplate) + } + } + + /** + * Setting up `accountTypeAdapter` and `` spAccountType + */ + override fun showUserInterface() { + accountTypeAdapter = ArrayAdapter(activity, + android.R.layout.simple_spinner_item, listAccountType) + accountTypeAdapter?.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + spAccountType?.onItemSelectedListener = this + if (!Network.isConnected(context)) { + spAccountType?.isEnabled = false + } + spAccountType?.adapter = accountTypeAdapter + } + + /** + * Fetches [BeneficiaryTemplate] from server and further updates the UI according to + * [BeneficiaryState] which is initialized in `newInstance()` as + * `beneficiaryState` + * + * @param beneficiaryTemplate [BeneficiaryTemplate] fetched from server + */ + override fun showBeneficiaryTemplate(beneficiaryTemplate: BeneficiaryTemplate?) { + this.beneficiaryTemplate = beneficiaryTemplate + for ((_, _, value) in beneficiaryTemplate?.accountTypeOptions!!) { + listAccountType.add(value) + } + accountTypeAdapter?.notifyDataSetChanged() + if (beneficiaryState == BeneficiaryState.UPDATE) { + accountTypeAdapter?.getPosition(beneficiary + ?.accountType?.value)?.let { spAccountType?.setSelection(it) } + spAccountType?.isEnabled = false + tilAccountNumber?.editText?.setText(beneficiary?.accountNumber) + tilAccountNumber?.isEnabled = false + tilOfficeName?.editText?.setText(beneficiary?.officeName) + tilOfficeName?.isEnabled = false + tilBeneficiaryName?.editText?.setText(beneficiary?.name) + tilTransferLimit?.editText?.setText(beneficiary?.transferLimit.toString()) + } else if (beneficiaryState == BeneficiaryState.CREATE_QR) { + spAccountType?.setSelection(beneficiary?.accountType?.id!!) + tilAccountNumber?.editText?.setText(beneficiary?.accountNumber) + tilOfficeName?.editText?.setText(beneficiary?.officeName) + } + } + + /** + * Used for submitting a new or updating beneficiary application + */ + @OnClick(R.id.btn_beneficiary_submit) + fun submitBeneficiary() { + tilAccountNumber?.isErrorEnabled = false + tilOfficeName?.isErrorEnabled = false + tilTransferLimit?.isErrorEnabled = false + tilBeneficiaryName?.isErrorEnabled = false + if (accountTypeId == -1) { + Toaster.show(rootView, getString(R.string.choose_account_type)) + return + } else if (tilAccountNumber?.editText?.text.toString().trim { it <= ' ' } == "") { + tilAccountNumber?.error = getString(R.string.enter_account_number) + return + } else if (tilOfficeName?.editText?.text.toString().trim { it <= ' ' } == "") { + tilOfficeName?.error = getString(R.string.enter_office_name) + return + } else if (tilTransferLimit?.editText?.text.toString() == "") { + tilTransferLimit?.error = getString(R.string.enter_transfer_limit) + return + } else if (tilTransferLimit?.editText?.text.toString() == ".") { + tilTransferLimit?.error = getString(R.string.invalid_amount) + return + } else if (tilTransferLimit?.editText?.text.toString().matches("^0*".toRegex())) { + tilTransferLimit?.error = getString(R.string.amount_greater_than_zero) + return + } else if (tilBeneficiaryName?.editText?.text.toString().trim { it <= ' ' } == "") { + tilBeneficiaryName?.error = getString(R.string.enter_beneficiary_name) + return + } + if (beneficiaryState == BeneficiaryState.CREATE_MANUAL || + beneficiaryState == BeneficiaryState.CREATE_QR) { + submitNewBeneficiaryApplication() + } else if (beneficiaryState == BeneficiaryState.UPDATE) { + submitUpdateBeneficiaryApplication() + } + } + + @OnClick(R.id.btn_try_again) + fun onRetry() { + if (Network.isConnected(context)) { + presenter?.loadBeneficiaryTemplate() + sweetUIErrorHandler?.hideSweetErrorLayoutUI(nsvBeneficiary, layoutError) + } else { + Toaster.show(rootView, getString(R.string.internet_not_connected)) + } + } + + /** + * Submit a new Beneficiary application + */ + private fun submitNewBeneficiaryApplication() { + val beneficiaryPayload = BeneficiaryPayload() + beneficiaryPayload.accountNumber = tilAccountNumber?.editText?.text.toString() + beneficiaryPayload.officeName = tilOfficeName?.editText?.text.toString() + beneficiaryPayload.accountType = accountTypeId + beneficiaryPayload.name = tilBeneficiaryName?.editText?.text.toString() + beneficiaryPayload.transferLimit = tilTransferLimit?.editText?.text.toString().toInt().toFloat() + presenter?.createBeneficiary(beneficiaryPayload) + } + + /** + * Updates an existing beneficiary application + */ + private fun submitUpdateBeneficiaryApplication() { + val payload = BeneficiaryUpdatePayload() + payload.name = tilBeneficiaryName?.editText?.text.toString() + payload.transferLimit = tilTransferLimit?.editText?.text.toString().toFloat() + presenter?.updateBeneficiary(beneficiary?.id?.toLong(), payload) + } + + /** + * Displays a {@link Snackbar} on successfully creation of + * Beneficiary and pops fragments in order to go back to [BeneficiaryListFragment] + */ + override fun showBeneficiaryCreatedSuccessfully() { + Toaster.show(rootView, getString(R.string.beneficiary_created_successfully)) + activity?.finish() + } + + /** + * Displays a {@link Snackbar} on successfully updation of + * Beneficiary and pops fragments in order to go back to [BeneficiaryListFragment] + */ + override fun showBeneficiaryUpdatedSuccessfully() { + Toaster.show(rootView, getString(R.string.beneficiary_updated_successfully)) + activity?.supportFragmentManager?.popBackStack() + activity?.supportFragmentManager?.popBackStack() + } + + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + accountTypeId = beneficiaryTemplate?.accountTypeOptions?.get(position)?.id + } + + override fun onNothingSelected(parent: AdapterView<*>?) {} + + /** + * It is called whenever any error occurs while executing a request + * + * @param msg Error message that tells the user about the problem. + */ + override fun showError(msg: String?) { + if (!Network.isConnected(context)) { + sweetUIErrorHandler?.showSweetNoInternetUI(nsvBeneficiary, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(msg, nsvBeneficiary, layoutError) + Toaster.show(rootView, msg) + } + } + + override fun setVisibility(state: Int) { + llApplicationBeneficiary?.visibility = state + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + presenter?.detachView() + } + + companion object { + fun newInstance( + beneficiaryState: BeneficiaryState?, + beneficiary: Beneficiary? + ): BeneficiaryApplicationFragment { + val fragment = BeneficiaryApplicationFragment() + val args = Bundle() + args.putSerializable(Constants.BENEFICIARY_STATE, beneficiaryState) + if (beneficiary != null) { + args.putParcelable(Constants.BENEFICIARY, beneficiary) + } + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryDetailFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryDetailFragment.java deleted file mode 100644 index 6db5b65ec8..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryDetailFragment.java +++ /dev/null @@ -1,191 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.DialogInterface; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.presenters.BeneficiaryDetailPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.BeneficiaryState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.BeneficiaryDetailView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 15/6/17. - */ - -public class BeneficiaryDetailFragment extends BaseFragment implements BeneficiaryDetailView { - - @BindView(R.id.tv_beneficiary_name) - TextView tvName; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_client_name) - TextView tvClientName; - - @BindView(R.id.tv_account_type) - TextView tvAccountType; - - @BindView(R.id.tv_transfer_limit) - TextView tvTransferLimit; - - @BindView(R.id.tv_office_name) - TextView tvOfficeName; - - @Inject - BeneficiaryDetailPresenter presenter; - - private Beneficiary beneficiary; - private View rootView; - - public static BeneficiaryDetailFragment newInstance(Beneficiary beneficiary) { - BeneficiaryDetailFragment fragment = new BeneficiaryDetailFragment(); - Bundle args = new Bundle(); - args.putParcelable(Constants.BENEFICIARY, beneficiary); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - beneficiary = getArguments().getParcelable(Constants.BENEFICIARY); - } - setHasOptionsMenu(true); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_beneficiary_detail, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - setToolbarTitle(getString(R.string.beneficiary_detail)); - - ButterKnife.bind(this, rootView); - presenter.attachView(this); - - showUserInterface(); - - return rootView; - } - - /** - * Used for setting up of User Interface - */ - @Override - public void showUserInterface() { - tvName.setText(beneficiary.getName()); - tvAccountNumber.setText(beneficiary.getAccountNumber()); - tvClientName.setText(beneficiary.getClientName()); - tvAccountType.setText(beneficiary.getAccountType().getValue()); - tvTransferLimit.setText(CurrencyUtil.formatCurrency(getActivity(), beneficiary. - getTransferLimit())); - tvOfficeName.setText(beneficiary.getOfficeName()); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_beneficiary, menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.item_update_beneficiary: - ((BaseActivity) getActivity()).replaceFragment(BeneficiaryApplicationFragment. - newInstance(BeneficiaryState.UPDATE, beneficiary), true, R.id.container); - break; - case R.id.item_delete_beneficiary: - new MaterialDialog.Builder().init(getActivity()) - .setTitle(getString(R.string.delete_beneficiary)) - .setMessage(getString(R.string.delete_beneficiary_confirmation)) - .setPositiveButton(getString(R.string.delete), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - presenter.deleteBeneficiary(beneficiary.getId()); - } - }) - .setNegativeButton(getString(R.string.cancel), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }) - .createMaterialDialog() - .show(); - break; - } - return true; - } - - /** - * Shows a {@link Snackbar} on successfull deletion of a - * Beneficiary and then pops current fragment - */ - @Override - public void showBeneficiaryDeletedSuccessfully() { - Toaster.show(rootView, getString(R.string.beneficiary_deleted_successfully)); - getActivity().getSupportFragmentManager().popBackStack(); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param msg Error message that tells the user about the problem. - */ - @Override - public void showError(String msg) { - Toaster.show(rootView, msg); - } - - /** - * Shows {@link org.mifos.mobile.utils.ProgressBarHandler} - */ - @Override - public void showProgress() { - showProgressBar(); - } - - /** - * Hides {@link org.mifos.mobile.utils.ProgressBarHandler} - */ - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryDetailFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryDetailFragment.kt new file mode 100644 index 0000000000..66a41aa520 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryDetailFragment.kt @@ -0,0 +1,157 @@ +package org.mifos.mobile.ui.fragments + +import android.content.DialogInterface +import android.os.Bundle +import android.view.* +import android.widget.TextView +import butterknife.BindView +import butterknife.ButterKnife +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.presenters.BeneficiaryDetailPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.BeneficiaryState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.BeneficiaryDetailView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.CurrencyUtil +import org.mifos.mobile.utils.MaterialDialog +import org.mifos.mobile.utils.Toaster +import javax.inject.Inject + +/** + * Created by dilpreet on 15/6/17. + */ +class BeneficiaryDetailFragment : BaseFragment(), BeneficiaryDetailView { + @kotlin.jvm.JvmField + @BindView(R.id.tv_beneficiary_name) + var tvName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_client_name) + var tvClientName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_type) + var tvAccountType: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_transfer_limit) + var tvTransferLimit: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_office_name) + var tvOfficeName: TextView? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: BeneficiaryDetailPresenter? = null + private var beneficiary: Beneficiary? = null + private var rootView: View? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + beneficiary = arguments?.getParcelable(Constants.BENEFICIARY) + } + setHasOptionsMenu(true) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_beneficiary_detail, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + setToolbarTitle(getString(R.string.beneficiary_detail)) + ButterKnife.bind(this, rootView!!) + presenter?.attachView(this) + showUserInterface() + return rootView + } + + /** + * Used for setting up of User Interface + */ + override fun showUserInterface() { + tvName?.text = beneficiary?.name + tvAccountNumber?.text = beneficiary?.accountNumber + tvClientName?.text = beneficiary?.clientName + tvAccountType?.text = beneficiary?.accountType?.value + tvTransferLimit?.text = CurrencyUtil.formatCurrency(activity!!, beneficiary?.transferLimit!!) + tvOfficeName?.text = beneficiary?.officeName + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + super.onCreateOptionsMenu(menu, inflater) + inflater.inflate(R.menu.menu_beneficiary, menu) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + R.id.item_update_beneficiary -> (activity as BaseActivity?)?.replaceFragment(BeneficiaryApplicationFragment.newInstance(BeneficiaryState.UPDATE, beneficiary), true, R.id.container) + R.id.item_delete_beneficiary -> MaterialDialog.Builder().init(activity) + .setTitle(getString(R.string.delete_beneficiary)) + .setMessage(getString(R.string.delete_beneficiary_confirmation)) + .setPositiveButton(getString(R.string.delete), + DialogInterface.OnClickListener { dialog, _ -> + dialog.dismiss() + presenter?.deleteBeneficiary(beneficiary?.id?.toLong()) + }) + .setNegativeButton(getString(R.string.cancel), + DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() }) + .createMaterialDialog() + .show() + } + return true + } + + /** + * Shows a {@link Snackbar} on successfull deletion of a + * Beneficiary and then pops current fragment + */ + override fun showBeneficiaryDeletedSuccessfully() { + Toaster.show(rootView, getString(R.string.beneficiary_deleted_successfully)) + activity?.supportFragmentManager?.popBackStack() + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param msg Error message that tells the user about the problem. + */ + override fun showError(msg: String?) { + Toaster.show(rootView, msg) + } + + /** + * Shows [org.mifos.mobile.utils.ProgressBarHandler] + */ + override fun showProgress() { + showProgressBar() + } + + /** + * Hides [org.mifos.mobile.utils.ProgressBarHandler] + */ + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + presenter?.detachView() + } + + companion object { + fun newInstance(beneficiary: Beneficiary?): BeneficiaryDetailFragment { + val fragment = BeneficiaryDetailFragment() + val args = Bundle() + args.putParcelable(Constants.BENEFICIARY, beneficiary) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryListFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryListFragment.java deleted file mode 100644 index 58c7da42bc..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryListFragment.java +++ /dev/null @@ -1,251 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.Intent; -import android.os.Bundle; -import android.os.Parcelable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; -import com.google.android.material.floatingactionbutton.FloatingActionButton; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.presenters.BeneficiaryListPresenter; -import org.mifos.mobile.ui.activities.AddBeneficiaryActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.BeneficiaryListAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.BeneficiariesView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DividerItemDecoration; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.RecyclerItemClickListener; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 14/6/17. - */ - -public class BeneficiaryListFragment extends BaseFragment implements RecyclerItemClickListener. - OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, BeneficiariesView { - - @BindView(R.id.rv_beneficiaries) - RecyclerView rvBeneficiaries; - - @BindView(R.id.swipe_container) - SwipeRefreshLayout swipeRefreshLayout; - - @BindView(R.id.fab_add_beneficiary) - FloatingActionButton fabAddBeneficiary; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - BeneficiaryListPresenter beneficiaryListPresenter; - - @Inject - BeneficiaryListAdapter beneficiaryListAdapter; - - private View rootView; - private List beneficiaryList; - private SweetUIErrorHandler sweetUIErrorHandler; - - public static BeneficiaryListFragment newInstance() { - BeneficiaryListFragment fragment = new BeneficiaryListFragment(); - return fragment; - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_beneficiary_list, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - setToolbarTitle(getString(R.string.beneficiaries)); - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - - showUserInterface(); - - beneficiaryListPresenter.attachView(this); - if (savedInstanceState == null) { - beneficiaryListPresenter.loadBeneficiaries(); - } - - return rootView; - } - - @Override - public void onResume() { - super.onResume(); - beneficiaryListPresenter.loadBeneficiaries(); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - if (beneficiaryList != null) { - outState.putParcelableArrayList(Constants.BENEFICIARY, new ArrayList( - beneficiaryList)); - } - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - List beneficiaries = savedInstanceState.getParcelableArrayList(Constants. - BENEFICIARY); - showBeneficiaryList(beneficiaries); - } - } - - /** - * Setup Initial User Interface - */ - @Override - public void showUserInterface() { - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - rvBeneficiaries.setLayoutManager(layoutManager); - rvBeneficiaries.setHasFixedSize(true); - rvBeneficiaries.addItemDecoration(new DividerItemDecoration(getActivity(), layoutManager. - getOrientation())); - rvBeneficiaries.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), this)); - rvBeneficiaries.setAdapter(beneficiaryListAdapter); - - swipeRefreshLayout.setColorSchemeColors(getActivity() - .getResources().getIntArray(R.array.swipeRefreshColors)); - swipeRefreshLayout.setOnRefreshListener(this); - - fabAddBeneficiary.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - startActivity(new Intent(getActivity(), AddBeneficiaryActivity.class)); - } - }); - } - - - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvBeneficiaries, layoutError); - beneficiaryListPresenter.loadBeneficiaries(); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - /** - * Refreshes {@code beneficiaryList} by calling {@code loadBeneficiaries()} - */ - - @Override - public void onRefresh() { - if (layoutError.getVisibility() == View.VISIBLE) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvBeneficiaries, layoutError); - } - beneficiaryListPresenter.loadBeneficiaries(); - } - - /** - * Shows {@link SwipeRefreshLayout} - */ - @Override - public void showProgress() { - showSwipeRefreshLayout(true); - } - - /** - * Hides {@link SwipeRefreshLayout} - */ - @Override - public void hideProgress() { - showSwipeRefreshLayout(false); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param msg Error message that tells the user about the problem. - */ - @Override - public void showError(String msg) { - - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(rvBeneficiaries, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(msg, - rvBeneficiaries, layoutError); - Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); - } - } - - /** - * Set the {@code beneficiaryList} fetched from server to {@code beneficiaryListAdapter} - */ - @Override - public void showBeneficiaryList(List beneficiaryList) { - this.beneficiaryList = beneficiaryList; - if (beneficiaryList.size() != 0) { - beneficiaryListAdapter.setBeneficiaryList(beneficiaryList); - } else { - showEmptyBeneficiary(); - } - } - - @Override - public void onItemClick(View childView, int position) { - ((BaseActivity) getActivity()).replaceFragment(BeneficiaryDetailFragment - .newInstance(beneficiaryList.get(position)), true, R.id.container); - } - - @Override - public void onItemLongPress(View childView, int position) { - - } - - public void showSwipeRefreshLayout(final boolean show) { - swipeRefreshLayout.post(new Runnable() { - @Override - public void run() { - swipeRefreshLayout.setRefreshing(show); - } - }); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - beneficiaryListPresenter.detachView(); - } - - /** - * Shows an error layout when this function is called. - */ - public void showEmptyBeneficiary() { - sweetUIErrorHandler.showSweetEmptyUI(getString(R.string.beneficiary), - getString(R.string.beneficiary), - R.drawable.ic_beneficiaries_48px, rvBeneficiaries, layoutError); - rvBeneficiaries.setVisibility(View.GONE); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryListFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryListFragment.kt new file mode 100644 index 0000000000..cdc1640a1c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/BeneficiaryListFragment.kt @@ -0,0 +1,209 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.os.Bundle +import android.os.Parcelable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler +import com.google.android.material.floatingactionbutton.FloatingActionButton +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.presenters.BeneficiaryListPresenter +import org.mifos.mobile.ui.activities.AddBeneficiaryActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.BeneficiaryListAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.BeneficiariesView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DividerItemDecoration +import org.mifos.mobile.utils.Network +import org.mifos.mobile.utils.RecyclerItemClickListener +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 14/6/17. + */ +class BeneficiaryListFragment : BaseFragment(), RecyclerItemClickListener.OnItemClickListener, OnRefreshListener, BeneficiariesView { + + @kotlin.jvm.JvmField + @BindView(R.id.rv_beneficiaries) + var rvBeneficiaries: RecyclerView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.swipe_container) + var swipeRefreshLayout: SwipeRefreshLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.fab_add_beneficiary) + var fabAddBeneficiary: FloatingActionButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @Inject + var beneficiaryListPresenter: BeneficiaryListPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var beneficiaryListAdapter: BeneficiaryListAdapter? = null + private var rootView: View? = null + private var beneficiaryList: List? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_beneficiary_list, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + setToolbarTitle(getString(R.string.beneficiaries)) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + showUserInterface() + beneficiaryListPresenter?.attachView(this) + if (savedInstanceState == null) { + beneficiaryListPresenter?.loadBeneficiaries() + } + return rootView + } + + override fun onResume() { + super.onResume() + beneficiaryListPresenter?.loadBeneficiaries() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + if (beneficiaryList != null) { + outState.putParcelableArrayList(Constants.BENEFICIARY, ArrayList( + beneficiaryList)) + } + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + val beneficiaries: List = savedInstanceState.getParcelableArrayList(Constants.BENEFICIARY) + showBeneficiaryList(beneficiaries) + } + } + + /** + * Setup Initial User Interface + */ + override fun showUserInterface() { + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = LinearLayoutManager.VERTICAL + rvBeneficiaries?.layoutManager = layoutManager + rvBeneficiaries?.setHasFixedSize(true) + rvBeneficiaries?.addItemDecoration(DividerItemDecoration((activity?.applicationContext)!!, layoutManager.orientation)) + rvBeneficiaries?.addOnItemTouchListener(RecyclerItemClickListener(activity, this)) + rvBeneficiaries?.adapter = beneficiaryListAdapter + swipeRefreshLayout?.setColorSchemeColors(*activity!! + .resources.getIntArray(R.array.swipeRefreshColors)) + swipeRefreshLayout?.setOnRefreshListener(this) + fabAddBeneficiary?.setOnClickListener { startActivity(Intent(activity, AddBeneficiaryActivity::class.java)) } + } + + @OnClick(R.id.btn_try_again) + fun retryClicked() { + if (Network.isConnected((context?.applicationContext)!!)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvBeneficiaries, layoutError) + beneficiaryListPresenter?.loadBeneficiaries() + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + /** + * Refreshes `beneficiaryList` by calling `loadBeneficiaries()` + */ + override fun onRefresh() { + if (layoutError?.visibility == View.VISIBLE) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvBeneficiaries, layoutError) + } + beneficiaryListPresenter?.loadBeneficiaries() + } + + /** + * Shows [SwipeRefreshLayout] + */ + override fun showProgress() { + showSwipeRefreshLayout(true) + } + + /** + * Hides [SwipeRefreshLayout] + */ + override fun hideProgress() { + showSwipeRefreshLayout(false) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param msg Error message that tells the user about the problem. + */ + override fun showError(msg: String?) { + if (!Network.isConnected((activity?.applicationContext)!!)) { + sweetUIErrorHandler?.showSweetNoInternetUI(rvBeneficiaries, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(msg, + rvBeneficiaries, layoutError) + Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show() + } + } + + /** + * Set the `beneficiaryList` fetched from server to `beneficiaryListAdapter` + */ + override fun showBeneficiaryList(beneficiaryList: List?) { + this.beneficiaryList = beneficiaryList + if (beneficiaryList?.isNotEmpty() == true) { + beneficiaryListAdapter?.setBeneficiaryList(beneficiaryList) + } else { + showEmptyBeneficiary() + } + } + + override fun onItemClick(childView: View?, position: Int) { + (activity as BaseActivity?)?.replaceFragment(BeneficiaryDetailFragment.newInstance(beneficiaryList!![position]), true, R.id.container) + } + + override fun onItemLongPress(childView: View?, position: Int) {} + private fun showSwipeRefreshLayout(show: Boolean?) { + swipeRefreshLayout?.post { swipeRefreshLayout?.isRefreshing = (show == true) } + } + + override fun onDestroyView() { + super.onDestroyView() + beneficiaryListPresenter?.detachView() + } + + /** + * Shows an error layout when this function is called. + */ + private fun showEmptyBeneficiary() { + sweetUIErrorHandler?.showSweetEmptyUI(getString(R.string.beneficiary), + getString(R.string.beneficiary), + R.drawable.ic_beneficiaries_48px, rvBeneficiaries, layoutError) + rvBeneficiaries?.visibility = View.GONE + } + + companion object { + fun newInstance(): BeneficiaryListFragment { + return BeneficiaryListFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/ClientAccountsFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/ClientAccountsFragment.java deleted file mode 100644 index 7deacea90f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/ClientAccountsFragment.java +++ /dev/null @@ -1,501 +0,0 @@ -package org.mifos.mobile.ui.fragments; -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.app.SearchManager; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; -import android.util.DisplayMetrics; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.google.android.material.floatingactionbutton.FloatingActionButton; -import com.google.android.material.tabs.TabLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.models.accounts.share.ShareAccount; -import org.mifos.mobile.presenters.AccountsPresenter; -import org.mifos.mobile.ui.activities.HomeActivity; -import org.mifos.mobile.ui.activities.LoanApplicationActivity; -import org.mifos.mobile.ui.activities.SavingsAccountApplicationActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.CheckBoxAdapter; -import org.mifos.mobile.ui.adapters.ViewPagerAdapter; -import org.mifos.mobile.ui.enums.AccountType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.AccountsView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.StatusUtils; - -import java.util.List; - -import javax.inject.Inject; - -import androidx.appcompat.widget.SearchView; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.viewpager.widget.ViewPager; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -public class ClientAccountsFragment extends BaseFragment implements AccountsView { - - @BindView(R.id.viewpager) - ViewPager viewPager; - - @BindView(R.id.tabs) - TabLayout tabLayout; - - - @BindView(R.id.fab_create_loan) - FloatingActionButton fabCreateLoan; - - @Inject - AccountsPresenter accountsPresenter; - - @Inject - CheckBoxAdapter checkBoxAdapter; - - private RecyclerView checkBoxRecyclerView; - private AccountType accountType; - private boolean isDialogBoxSelected = false; - - public static ClientAccountsFragment newInstance(AccountType accountType) { - ClientAccountsFragment clientAccountsFragment = new ClientAccountsFragment(); - Bundle args = new Bundle(); - args.putSerializable(Constants.ACCOUNT_TYPE, accountType); - clientAccountsFragment.setArguments(args); - return clientAccountsFragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - if (getArguments() != null) { - accountType = (AccountType) getArguments().getSerializable(Constants.ACCOUNT_TYPE); - } - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle - savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_client_accounts, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, view); - accountsPresenter.attachView(this); - setToolbarTitle(getString(R.string.accounts)); - - setUpViewPagerAndTabLayout(); - - if (savedInstanceState == null) { - accountsPresenter.loadClientAccounts(); - } - - return view; - } - - /** - * Setting up {@link ViewPagerAdapter} and {@link TabLayout} for Savings, Loans and Share - * accounts. {@code accountType} is used for setting the current Fragment - */ - private void setUpViewPagerAndTabLayout() { - ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager()); - - viewPagerAdapter.addFragment(AccountsFragment.newInstance(Constants.SAVINGS_ACCOUNTS), - getString(R.string.savings)); - viewPagerAdapter.addFragment(AccountsFragment.newInstance(Constants.LOAN_ACCOUNTS), - getString(R.string.loan)); - viewPagerAdapter.addFragment(AccountsFragment.newInstance(Constants.SHARE_ACCOUNTS), - getString(R.string.share)); - - viewPager.setOffscreenPageLimit(2); - viewPager.setAdapter(viewPagerAdapter); - switch (accountType) { - case SAVINGS: - viewPager.setCurrentItem(0); - break; - case LOAN: - viewPager.setCurrentItem(1); - break; - case SHARE: - viewPager.setCurrentItem(2); - break; - } - tabLayout.setupWithViewPager(viewPager); - viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { - @Override - public void onPageScrolled(int position, float positionOffset, - int positionOffsetPixels) { - } - - @Override - public void onPageSelected(int position) { - getActivity().invalidateOptionsMenu(); - ((HomeActivity) getActivity()).hideKeyboard(getView()); - - if (position == 0 || position == 1) { - fabCreateLoan.setVisibility(View.VISIBLE); - } else { - fabCreateLoan.hide(); - } - } - - @Override - public void onPageScrollStateChanged(int state) { - } - }); - } - - /** - * Returns tag of Fragment present at {@code position} - * - * @param position position of Fragment - * @return Tag of Fragment - */ - private String getFragmentTag(int position) { - return "android:switcher:" + R.id.viewpager + ":" + position; - } - - /** - * It provides with {@code shareAccounts} fetched from server which is then passed to fragment - * implementing {@link AccountsView} i.e. {@link AccountsFragment} which further displays them - * in a recyclerView - * - * @param shareAccounts {@link List} of {@link ShareAccount} - */ - @Override - public void showShareAccounts(List shareAccounts) { - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(2))). - showShareAccounts(shareAccounts); - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(2))). - hideProgress(); - } - - /** - * It provides with {@code loanAccounts} fetched from server which is then passed to fragment - * implementing {@link AccountsView} i.e. {@link AccountsFragment} which further displays them - * in a recyclerView - * - * @param loanAccounts {@link List} of {@link LoanAccount} - */ - @Override - public void showLoanAccounts(List loanAccounts) { - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(1))) - .showLoanAccounts(loanAccounts); - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(1))) - .hideProgress(); - } - - /** - * It provides with {@code savingAccounts} fetched from server which is then passed to fragment - * implementing {@link AccountsView} i.e. {@link AccountsFragment} which further displays them - * in a recyclerView - * - * @param savingAccounts {@link List} of {@link SavingAccount} - */ - @Override - public void showSavingsAccounts(List savingAccounts) { - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(0))) - .showSavingsAccounts(savingAccounts); - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(0))) - .hideProgress(); - } - - - @OnClick(R.id.fab_create_loan) - public void createLoan() { - switch (viewPager.getCurrentItem()) { - case 0: - startActivity(new Intent(getActivity(), SavingsAccountApplicationActivity.class)); - break; - case 1: - startActivity(new Intent(getActivity(), LoanApplicationActivity.class)); - break; - } - } - - - /** - * It is called whenever any error occurs while executing a request which passes errorMessage to - * fragment implementing {@link AccountsView} i.e. {@link AccountsFragment} which further - * displays the errorMessage - * - * @param errorMessage Error message that tells the user about the problem. - */ - @Override - public void showError(String errorMessage) { - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(0))) - .showError(getString(R.string.error_fetching_accounts)); - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(1))) - .showError(getString(R.string.error_fetching_accounts)); - ((AccountsView) getChildFragmentManager().findFragmentByTag(getFragmentTag(2))) - .showError(getString(R.string.error_fetching_accounts)); - Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show(); - } - - @Override - public void showProgress() { - } - - @Override - public void hideProgress() { - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - accountsPresenter.detachView(); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_account, menu); - if (viewPager.getCurrentItem() == 0) { - menu.findItem(R.id.menu_filter_savings).setVisible(true); - menu.findItem(R.id.menu_filter_loan).setVisible(false); - menu.findItem(R.id.menu_filter_shares).setVisible(false); - menu.findItem(R.id.menu_search_saving).setVisible(true); - menu.findItem(R.id.menu_search_loan).setVisible(false); - menu.findItem(R.id.menu_search_share).setVisible(false); - initSearch(menu, AccountType.SAVINGS); - } else if (viewPager.getCurrentItem() == 1) { - menu.findItem(R.id.menu_filter_savings).setVisible(false); - menu.findItem(R.id.menu_filter_loan).setVisible(true); - menu.findItem(R.id.menu_filter_shares).setVisible(false); - menu.findItem(R.id.menu_search_saving).setVisible(false); - menu.findItem(R.id.menu_search_loan).setVisible(true); - menu.findItem(R.id.menu_search_share).setVisible(false); - initSearch(menu, AccountType.LOAN); - } else if (viewPager.getCurrentItem() == 2) { - menu.findItem(R.id.menu_filter_savings).setVisible(false); - menu.findItem(R.id.menu_filter_loan).setVisible(false); - menu.findItem(R.id.menu_filter_shares).setVisible(true); - menu.findItem(R.id.menu_search_saving).setVisible(false); - menu.findItem(R.id.menu_search_loan).setVisible(false); - menu.findItem(R.id.menu_search_share).setVisible(true); - initSearch(menu, AccountType.SHARE); - } - super.onCreateOptionsMenu(menu, inflater); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_filter_savings: - showFilterDialog(AccountType.SAVINGS); - break; - case R.id.menu_filter_loan: - showFilterDialog(AccountType.LOAN); - break; - case R.id.menu_filter_shares: - showFilterDialog(AccountType.SHARE); - break; - } - return true; - } - - /** - * Initializes the search option in {@link Menu} depending upon {@code account} - * - * @param menu Interface for managing the items in a menu. - * @param account An enum of {@link AccountType} - */ - private void initSearch(Menu menu, final AccountType account) { - SearchManager manager = (SearchManager) getActivity(). - getSystemService(Context.SEARCH_SERVICE); - SearchView search = null; - - if (account == AccountType.SAVINGS) { - search = (SearchView) menu.findItem(R.id.menu_search_saving).getActionView(); - } else if (account == AccountType.LOAN) { - search = (SearchView) menu.findItem(R.id.menu_search_loan).getActionView(); - } else if (account == AccountType.SHARE) { - search = (SearchView) menu.findItem(R.id.menu_search_share).getActionView(); - } - - DisplayMetrics displayMetrics = new DisplayMetrics(); - getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); - int width = displayMetrics.widthPixels; - search.setMaxWidth((int) (0.75 * width)); - search.setSearchableInfo(manager.getSearchableInfo(getActivity().getComponentName())); - search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - return false; - } - - @Override - public boolean onQueryTextChange(String newText) { - - if (account == AccountType.SAVINGS) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(0))).searchSavingsAccount(newText); - } else if (account == AccountType.LOAN) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(1))).searchLoanAccount(newText); - } else if (account == AccountType.SHARE) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(2))).searchSharesAccount(newText); - } - - return false; - } - }); - } - - /** - * Displays a filter dialog according to the {@code account} provided in the parameter - * - * @param account An enum of {@link AccountType} - */ - private void showFilterDialog(final AccountType account) { - if (isDialogBoxSelected) { - return; - } - isDialogBoxSelected = true; - String title = ""; - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(RecyclerView.VERTICAL); - - checkBoxRecyclerView = new RecyclerView(getActivity()); - checkBoxRecyclerView.setLayoutManager(layoutManager); - checkBoxRecyclerView.setAdapter(checkBoxAdapter); - - if (account == AccountType.SAVINGS) { - if (((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(0))).getCurrentFilterList() == null) { - checkBoxAdapter.setStatusList(StatusUtils. - getSavingsAccountStatusList(getActivity())); - } else { - checkBoxAdapter.setStatusList(((AccountsFragment) getChildFragmentManager() - .findFragmentByTag(getFragmentTag(0))).getCurrentFilterList()); - } - - title = getString(R.string.filter_savings); - } else if (account == AccountType.LOAN) { - if (((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(1))).getCurrentFilterList() == null) { - checkBoxAdapter.setStatusList(StatusUtils. - getLoanAccountStatusList(getActivity())); - } else { - checkBoxAdapter.setStatusList(((AccountsFragment) getChildFragmentManager() - .findFragmentByTag(getFragmentTag(1))).getCurrentFilterList()); - } - - title = getString(R.string.filter_loan); - } else if (account == AccountType.SHARE) { - if (((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(2))).getCurrentFilterList() == null) { - checkBoxAdapter.setStatusList(StatusUtils. - getShareAccountStatusList(getActivity())); - } else { - checkBoxAdapter.setStatusList(((AccountsFragment) getChildFragmentManager() - .findFragmentByTag(getFragmentTag(2))).getCurrentFilterList()); - } - - title = getString(R.string.filter_share); - } - - new MaterialDialog.Builder().init(getActivity()) - .setTitle(title) - .setCancelable(false) - .setMessage(getString(R.string.select_you_want)) - .addView(checkBoxRecyclerView) - .setPositiveButton(getString(R.string.filter), new DialogInterface. - OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - isDialogBoxSelected = false; - if (account == AccountType.SAVINGS) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(0))) - .setCurrentFilterList(checkBoxAdapter.getStatusList()); - - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(0))) - .filterSavingsAccount(checkBoxAdapter.getStatusList()); - } else if (account == AccountType.LOAN) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(1))) - .setCurrentFilterList(checkBoxAdapter.getStatusList()); - - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(1))) - .filterLoanAccount(checkBoxAdapter.getStatusList()); - } else if (account == AccountType.SHARE) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(2))) - .setCurrentFilterList(checkBoxAdapter.getStatusList()); - - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(2))) - .filterShareAccount(checkBoxAdapter.getStatusList()); - } - - } - }) - .setNeutralButton(R.string.clear_filters, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - isDialogBoxSelected = false; - if (account == AccountType.SAVINGS) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(0))).clearFilter(); - checkBoxAdapter.setStatusList(StatusUtils. - getSavingsAccountStatusList(getActivity())); - accountsPresenter.loadAccounts(Constants.SAVINGS_ACCOUNTS); - } else if (account == AccountType.LOAN) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(1))).clearFilter(); - checkBoxAdapter.setStatusList(StatusUtils. - getLoanAccountStatusList(getActivity())); - accountsPresenter.loadAccounts(Constants.LOAN_ACCOUNTS); - } else if (account == AccountType.SHARE) { - ((AccountsFragment) getChildFragmentManager().findFragmentByTag( - getFragmentTag(2))).clearFilter(); - checkBoxAdapter.setStatusList(StatusUtils. - getShareAccountStatusList(getActivity())); - accountsPresenter.loadAccounts(Constants.SHARE_ACCOUNTS); - } - - } - }) - .setNegativeButton(getString(R.string.cancel), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - isDialogBoxSelected = false; - } - }) - .createMaterialDialog() - .show(); - } - - @Override - public void onResume() { - super.onResume(); - ((BaseActivity) getActivity()).hideToolbarElevation(); - } - - @Override - public void onPause() { - super.onPause(); - ((BaseActivity) getActivity()).setToolbarElevation(); - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/ClientAccountsFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/ClientAccountsFragment.kt new file mode 100644 index 0000000000..c6bc15151d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/ClientAccountsFragment.kt @@ -0,0 +1,441 @@ +package org.mifos.mobile.ui.fragments + +import android.app.SearchManager +import android.content.Context +import android.content.DialogInterface +import android.content.Intent +import android.os.Bundle +import android.util.DisplayMetrics +import android.view.* +import android.widget.Toast + +import androidx.appcompat.widget.SearchView +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.viewpager.widget.ViewPager +import androidx.viewpager.widget.ViewPager.OnPageChangeListener + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.google.android.material.floatingactionbutton.FloatingActionButton +import com.google.android.material.tabs.TabLayout + +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.models.accounts.share.ShareAccount +import org.mifos.mobile.presenters.AccountsPresenter +import org.mifos.mobile.ui.activities.HomeActivity +import org.mifos.mobile.ui.activities.LoanApplicationActivity +import org.mifos.mobile.ui.activities.SavingsAccountApplicationActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.CheckBoxAdapter +import org.mifos.mobile.ui.adapters.ViewPagerAdapter +import org.mifos.mobile.ui.enums.AccountType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.AccountsView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.MaterialDialog +import org.mifos.mobile.utils.StatusUtils + +import javax.inject.Inject + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ class ClientAccountsFragment : BaseFragment(), AccountsView { + @JvmField + @BindView(R.id.viewpager) + var viewPager: ViewPager? = null + + @JvmField + @BindView(R.id.tabs) + var tabLayout: TabLayout? = null + + @JvmField + @BindView(R.id.fab_create_loan) + var fabCreateLoan: FloatingActionButton? = null + + @JvmField + @Inject + var accountsPresenter: AccountsPresenter? = null + + @JvmField + @Inject + var checkBoxAdapter: CheckBoxAdapter? = null + private var checkBoxRecyclerView: RecyclerView? = null + private var accountType: AccountType? = null + private var isDialogBoxSelected = false + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + if (arguments != null) { + accountType = arguments?.getSerializable(Constants.ACCOUNT_TYPE) as AccountType + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val view = inflater.inflate(R.layout.fragment_client_accounts, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, view) + accountsPresenter?.attachView(this) + setToolbarTitle(getString(R.string.accounts)) + setUpViewPagerAndTabLayout() + if (savedInstanceState == null) { + accountsPresenter?.loadClientAccounts() + } + return view + } + + /** + * Setting up [ViewPagerAdapter] and [TabLayout] for Savings, Loans and Share + * accounts. `accountType` is used for setting the current Fragment + */ + private fun setUpViewPagerAndTabLayout() { + val viewPagerAdapter = ViewPagerAdapter(childFragmentManager) + viewPagerAdapter.addFragment(AccountsFragment.newInstance(Constants.SAVINGS_ACCOUNTS), + getString(R.string.savings)) + viewPagerAdapter.addFragment(AccountsFragment.newInstance(Constants.LOAN_ACCOUNTS), + getString(R.string.loan)) + viewPagerAdapter.addFragment(AccountsFragment.newInstance(Constants.SHARE_ACCOUNTS), + getString(R.string.share)) + viewPager?.offscreenPageLimit = 2 + viewPager?.adapter = viewPagerAdapter + when (accountType) { + AccountType.SAVINGS -> viewPager?.currentItem = 0 + AccountType.LOAN -> viewPager?.currentItem = 1 + AccountType.SHARE -> viewPager?.currentItem = 2 + } + tabLayout?.setupWithViewPager(viewPager) + viewPager?.addOnPageChangeListener(object : OnPageChangeListener { + override fun onPageScrolled( + position: Int, positionOffset: Float, + positionOffsetPixels: Int + ) { + } + + override fun onPageSelected(position: Int) { + activity?.invalidateOptionsMenu() + view?.let { (activity as HomeActivity?)?.hideKeyboard(it) } + if (position == 0 || position == 1) { + fabCreateLoan?.show() + } else { + fabCreateLoan?.hide() + } + } + + override fun onPageScrollStateChanged(state: Int) {} + }) + } + + /** + * Returns tag of Fragment present at `position` + * + * @param position position of Fragment + * @return Tag of Fragment + */ + private fun getFragmentTag(position: Int): String { + return "android:switcher:" + R.id.viewpager + ":" + position + } + + /** + * It provides with `shareAccounts` fetched from server which is then passed to fragment + * implementing [AccountsView] i.e. [AccountsFragment] which further displays them + * in a recyclerView + * + * @param shareAccounts [List] of [ShareAccount] + */ + override fun showShareAccounts(shareAccounts: List?) { + (childFragmentManager.findFragmentByTag(getFragmentTag(2)) as AccountsView?)?.showShareAccounts(shareAccounts) + (childFragmentManager.findFragmentByTag(getFragmentTag(2)) as AccountsView?)?.hideProgress() + } + + /** + * It provides with `loanAccounts` fetched from server which is then passed to fragment + * implementing [AccountsView] i.e. [AccountsFragment] which further displays them + * in a recyclerView + * + * @param loanAccounts [List] of [LoanAccount] + */ + override fun showLoanAccounts(loanAccounts: List?) { + (childFragmentManager.findFragmentByTag(getFragmentTag(1)) as AccountsView?) + ?.showLoanAccounts(loanAccounts) + (childFragmentManager.findFragmentByTag(getFragmentTag(1)) as AccountsView?) + ?.hideProgress() + } + + /** + * It provides with `savingAccounts` fetched from server which is then passed to fragment + * implementing [AccountsView] i.e. [AccountsFragment] which further displays them + * in a recyclerView + * + * @param savingAccounts [List] of [SavingAccount] + */ + override fun showSavingsAccounts(savingAccounts: List?) { + (childFragmentManager.findFragmentByTag(getFragmentTag(0)) as AccountsView?) + ?.showSavingsAccounts(savingAccounts) + (childFragmentManager.findFragmentByTag(getFragmentTag(0)) as AccountsView?) + ?.hideProgress() + } + + @OnClick(R.id.fab_create_loan) + fun createLoan() { + when (viewPager?.currentItem) { + 0 -> startActivity(Intent(activity, SavingsAccountApplicationActivity::class.java)) + 1 -> startActivity(Intent(activity, LoanApplicationActivity::class.java)) + } + } + + /** + * It is called whenever any error occurs while executing a request which passes errorMessage to + * fragment implementing [AccountsView] i.e. [AccountsFragment] which further + * displays the errorMessage + * + * @param errorMessage Error message that tells the user about the problem. + */ + override fun showError(errorMessage: String?) { + (childFragmentManager.findFragmentByTag(getFragmentTag(0)) as AccountsView?) + ?.showError(getString(R.string.error_fetching_accounts)) + (childFragmentManager.findFragmentByTag(getFragmentTag(1)) as AccountsView?) + ?.showError(getString(R.string.error_fetching_accounts)) + (childFragmentManager.findFragmentByTag(getFragmentTag(2)) as AccountsView?) + ?.showError(getString(R.string.error_fetching_accounts)) + Toast.makeText(activity, errorMessage, Toast.LENGTH_SHORT).show() + } + + override fun showProgress() {} + override fun hideProgress() {} + override fun onDestroyView() { + super.onDestroyView() + accountsPresenter?.detachView() + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + inflater.inflate(R.menu.menu_account, menu) + if (viewPager?.currentItem == 0) { + menu.findItem(R.id.menu_filter_savings).isVisible = true + menu.findItem(R.id.menu_filter_loan).isVisible = false + menu.findItem(R.id.menu_filter_shares).isVisible = false + menu.findItem(R.id.menu_search_saving).isVisible = true + menu.findItem(R.id.menu_search_loan).isVisible = false + menu.findItem(R.id.menu_search_share).isVisible = false + initSearch(menu, AccountType.SAVINGS) + } else if (viewPager?.currentItem == 1) { + menu.findItem(R.id.menu_filter_savings).isVisible = false + menu.findItem(R.id.menu_filter_loan).isVisible = true + menu.findItem(R.id.menu_filter_shares).isVisible = false + menu.findItem(R.id.menu_search_saving).isVisible = false + menu.findItem(R.id.menu_search_loan).isVisible = true + menu.findItem(R.id.menu_search_share).isVisible = false + initSearch(menu, AccountType.LOAN) + } else if (viewPager?.currentItem == 2) { + menu.findItem(R.id.menu_filter_savings).isVisible = false + menu.findItem(R.id.menu_filter_loan).isVisible = false + menu.findItem(R.id.menu_filter_shares).isVisible = true + menu.findItem(R.id.menu_search_saving).isVisible = false + menu.findItem(R.id.menu_search_loan).isVisible = false + menu.findItem(R.id.menu_search_share).isVisible = true + initSearch(menu, AccountType.SHARE) + } + super.onCreateOptionsMenu(menu, inflater) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + R.id.menu_filter_savings -> showFilterDialog(AccountType.SAVINGS) + R.id.menu_filter_loan -> showFilterDialog(AccountType.LOAN) + R.id.menu_filter_shares -> showFilterDialog(AccountType.SHARE) + } + return true + } + + /** + * Initializes the search option in [Menu] depending upon `account` + * + * @param menu Interface for managing the items in a menu. + * @param account An enum of [AccountType] + */ + private fun initSearch(menu: Menu, account: AccountType) { + val manager = activity?.getSystemService(Context.SEARCH_SERVICE) as SearchManager + var search: SearchView? = null + + when (account) { + AccountType.SAVINGS -> { + search = menu.findItem(R.id.menu_search_saving).actionView as SearchView + } + AccountType.LOAN -> { + search = menu.findItem(R.id.menu_search_loan).actionView as SearchView + } + AccountType.SHARE -> { + search = menu.findItem(R.id.menu_search_share).actionView as SearchView + } + } + val displayMetrics = DisplayMetrics() + activity?.windowManager?.defaultDisplay?.getMetrics(displayMetrics) + val width = displayMetrics.widthPixels + search.maxWidth = (0.75 * width).toInt() + search.setSearchableInfo(manager.getSearchableInfo(activity?.componentName)) + search.setOnQueryTextListener(object : SearchView.OnQueryTextListener { + override fun onQueryTextSubmit(query: String): Boolean { + return false + } + + override fun onQueryTextChange(newText: String): Boolean { + when (account) { + AccountType.SAVINGS -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(0)) as AccountsFragment?)?.searchSavingsAccount(newText) + } + AccountType.LOAN -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(1)) as AccountsFragment?)?.searchLoanAccount(newText) + } + AccountType.SHARE -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(2)) as AccountsFragment?)?.searchSharesAccount(newText) + } + } + return false + } + }) + } + + /** + * Displays a filter dialog according to the `account` provided in the parameter + * + * @param account An enum of [AccountType] + */ + private fun showFilterDialog(account: AccountType) { + if (isDialogBoxSelected) { + return + } + isDialogBoxSelected = true + var title = "" + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = RecyclerView.VERTICAL + checkBoxRecyclerView = RecyclerView(activity!!) + checkBoxRecyclerView?.layoutManager = layoutManager + checkBoxRecyclerView?.adapter = checkBoxAdapter + when (account) { + AccountType.SAVINGS -> { + if ((childFragmentManager.findFragmentByTag( + getFragmentTag(0)) as AccountsFragment?)?.getCurrentFilterList() == null) { + checkBoxAdapter?.statusList = StatusUtils.getSavingsAccountStatusList(activity) + } else { + checkBoxAdapter?.statusList = (childFragmentManager + .findFragmentByTag(getFragmentTag(0)) as AccountsFragment?)?.getCurrentFilterList() + } + title = getString(R.string.filter_savings) + } + AccountType.LOAN -> { + if ((childFragmentManager.findFragmentByTag( + getFragmentTag(1)) as AccountsFragment?)?.getCurrentFilterList() == null) { + checkBoxAdapter?.statusList = StatusUtils.getLoanAccountStatusList(activity) + } else { + checkBoxAdapter?.statusList = (childFragmentManager + .findFragmentByTag(getFragmentTag(1)) as AccountsFragment?)?.getCurrentFilterList() + } + title = getString(R.string.filter_loan) + } + AccountType.SHARE -> { + if ((childFragmentManager.findFragmentByTag( + getFragmentTag(2)) as AccountsFragment?)?.getCurrentFilterList() == null) { + checkBoxAdapter?.statusList = StatusUtils.getShareAccountStatusList(activity) + } else { + checkBoxAdapter?.statusList = (childFragmentManager + .findFragmentByTag(getFragmentTag(2)) as AccountsFragment?)?.getCurrentFilterList() + } + title = getString(R.string.filter_share) + } + } + MaterialDialog.Builder().init(activity) + .setTitle(title) + .setCancelable(false) + .setMessage(getString(R.string.select_you_want)) + .addView(checkBoxRecyclerView) + .setPositiveButton(getString(R.string.filter), + DialogInterface.OnClickListener { _, _ -> + isDialogBoxSelected = false + when (account) { + AccountType.SAVINGS -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(0)) as AccountsFragment?) + ?.setCurrentFilterList(checkBoxAdapter?.statusList) + (childFragmentManager.findFragmentByTag( + getFragmentTag(0)) as AccountsFragment?) + ?.filterSavingsAccount(checkBoxAdapter?.statusList) + } + AccountType.LOAN -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(1)) as AccountsFragment?) + ?.setCurrentFilterList(checkBoxAdapter?.statusList) + (childFragmentManager.findFragmentByTag( + getFragmentTag(1)) as AccountsFragment?) + ?.filterLoanAccount(checkBoxAdapter?.statusList) + } + AccountType.SHARE -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(2)) as AccountsFragment?) + ?.setCurrentFilterList(checkBoxAdapter?.statusList) + (childFragmentManager.findFragmentByTag( + getFragmentTag(2)) as AccountsFragment?) + ?.filterShareAccount(checkBoxAdapter?.statusList) + } + } + }) + .setNeutralButton(R.string.clear_filters, + DialogInterface.OnClickListener { _, _ -> + isDialogBoxSelected = false + when (account) { + AccountType.SAVINGS -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(0)) as AccountsFragment?)?.clearFilter() + checkBoxAdapter?.statusList = StatusUtils.getSavingsAccountStatusList(activity) + accountsPresenter?.loadAccounts(Constants.SAVINGS_ACCOUNTS) + } + AccountType.LOAN -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(1)) as AccountsFragment?)?.clearFilter() + checkBoxAdapter?.statusList = StatusUtils.getLoanAccountStatusList(activity) + accountsPresenter?.loadAccounts(Constants.LOAN_ACCOUNTS) + } + AccountType.SHARE -> { + (childFragmentManager.findFragmentByTag( + getFragmentTag(2)) as AccountsFragment?)?.clearFilter() + checkBoxAdapter?.statusList = StatusUtils.getShareAccountStatusList(activity) + accountsPresenter?.loadAccounts(Constants.SHARE_ACCOUNTS) + } + } + + }) + .setNegativeButton(getString(R.string.cancel), + DialogInterface.OnClickListener { _, _ -> + isDialogBoxSelected = false + } + ) + .createMaterialDialog() + .show() + } + + override fun onResume() { + super.onResume() + (activity as BaseActivity?)?.hideToolbarElevation() + } + + override fun onPause() { + super.onPause() + (activity as BaseActivity?)?.setToolbarElevation() + } + + companion object { + fun newInstance(accountType: AccountType?): ClientAccountsFragment { + val clientAccountsFragment = ClientAccountsFragment() + val args = Bundle() + args.putSerializable(Constants.ACCOUNT_TYPE, accountType) + clientAccountsFragment.arguments = args + return clientAccountsFragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/ClientChargeFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/ClientChargeFragment.java deleted file mode 100644 index addcef621c..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/ClientChargeFragment.java +++ /dev/null @@ -1,238 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.os.Parcelable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.presenters.ClientChargePresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.ClientChargeAdapter; -import org.mifos.mobile.ui.enums.ChargeType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.ClientChargeView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.RecyclerItemClickListener; -import org.mifos.mobile.utils.Toaster; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * @author Vishwajeet - * @since 17/8/16. - */ - -public class ClientChargeFragment extends BaseFragment implements - RecyclerItemClickListener.OnItemClickListener, ClientChargeView { - - @BindView(R.id.rv_client_charge) - RecyclerView rvClientCharge; - - @BindView(R.id.swipe_charge_container) - SwipeRefreshLayout swipeChargeContainer; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - ClientChargePresenter clientChargePresenter; - - @Inject - ClientChargeAdapter clientChargeAdapter; - - private long id; - private ChargeType chargeType; - private View rootView; - private LinearLayoutManager layoutManager; - private List clientChargeList = new ArrayList<>(); - private SweetUIErrorHandler sweetUIErrorHandler; - - public static ClientChargeFragment newInstance(long clientId, ChargeType chargeType) { - ClientChargeFragment clientChargeFragment = new ClientChargeFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.CLIENT_ID, clientId); - args.putSerializable(Constants.CHARGE_TYPE, chargeType); - clientChargeFragment.setArguments(args); - return clientChargeFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - if (getArguments() != null) { - id = getArguments().getLong(Constants.CLIENT_ID); - chargeType = (ChargeType) getArguments().getSerializable(Constants.CHARGE_TYPE); - } - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_client_charge, container, false); - ButterKnife.bind(this, rootView); - - clientChargePresenter.attachView(this); - setToolbarTitle(getString(R.string.charges)); - - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - - layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - - rvClientCharge.setLayoutManager(layoutManager); - rvClientCharge.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), this)); - - swipeChargeContainer.setColorSchemeResources(R.color.blue_light, R.color.green_light, R - .color.orange_light, R.color.red_light); - swipeChargeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - loadCharges(); - } - }); - if (savedInstanceState == null) { - loadCharges(); - } - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelableArrayList(Constants.CHARGES, new ArrayList( - clientChargeList)); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - List charges = savedInstanceState.getParcelableArrayList(Constants.CHARGES); - showClientCharges(charges); - } - } - - /** - * Fetches Charges for {@code id} according to {@code chargeType} provided. - */ - private void loadCharges() { - if (layoutError.getVisibility() == View.VISIBLE) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvClientCharge, layoutError); - } - - if (chargeType == ChargeType.CLIENT) { - clientChargePresenter.loadClientCharges(id); - } else if (chargeType == ChargeType.SAVINGS) { - clientChargePresenter.loadSavingsAccountCharges(id); - } else if (chargeType == ChargeType.LOAN) { - clientChargePresenter.loadLoanAccountCharges(id); - } - } - - /** - * It is called whenever any error occurs while executing a request. If not connected to - * internet then it shows display a message to user to connect to internet other it just - * displays the {@code message} in a {@link Snackbar} - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showErrorFetchingClientCharges(String message) { - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(rvClientCharge, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, rvClientCharge, layoutError); - Toaster.show(rootView, message); - } - } - - /** - * Tries to fetch charges again. - */ - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvClientCharge, layoutError); - loadCharges(); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - /** - * Receives {@code clientChargeList} from server and calls {@code inflateClientChargeList()} to - * update the {@code clientChargeAdapter} adapter. - * - * @param clientChargeList {@link List} of {@link Charge} - */ - @Override - public void showClientCharges(List clientChargeList) { - this.clientChargeList = clientChargeList; - inflateClientChargeList(); - if (swipeChargeContainer.isRefreshing()) { - swipeChargeContainer.setRefreshing(false); - } - } - - /** - * Updates {@code clientChargeAdapter} with updated {@code clientChargeList} if - * {@code clientChargeList} size if greater than 0 else shows the error layout - */ - private void inflateClientChargeList() { - if (clientChargeList.size() > 0) { - clientChargeAdapter.setClientChargeList(clientChargeList); - rvClientCharge.setAdapter(clientChargeAdapter); - } else { - sweetUIErrorHandler.showSweetEmptyUI(getString(R.string.charges), R.drawable.ic_charges, - rvClientCharge, layoutError); - } - } - - @Override - public void showProgress() { - swipeChargeContainer.setRefreshing(true); - } - - @Override - public void hideProgress() { - swipeChargeContainer.setRefreshing(false); - } - - @Override - public void onItemClick(View childView, int position) { - - } - - @Override - public void onItemLongPress(View childView, int position) { - - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - clientChargePresenter.detachView(); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/ClientChargeFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/ClientChargeFragment.kt new file mode 100644 index 0000000000..f93293eb4e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/ClientChargeFragment.kt @@ -0,0 +1,200 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.os.Parcelable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler +import org.mifos.mobile.R +import org.mifos.mobile.models.Charge +import org.mifos.mobile.presenters.ClientChargePresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.ClientChargeAdapter +import org.mifos.mobile.ui.enums.ChargeType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.ClientChargeView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.Network +import org.mifos.mobile.utils.RecyclerItemClickListener +import org.mifos.mobile.utils.Toaster +import java.util.* +import javax.inject.Inject + + +/** + * @author Vishwajeet + * @since 17/8/16. + */ +class ClientChargeFragment : + BaseFragment(), RecyclerItemClickListener.OnItemClickListener, ClientChargeView { + + @kotlin.jvm.JvmField + @BindView(R.id.rv_client_charge) + var rvClientCharge: RecyclerView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.swipe_charge_container) + var swipeChargeContainer: SwipeRefreshLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @Inject + var clientChargePresenter: ClientChargePresenter? = null + + @kotlin.jvm.JvmField + @Inject + var clientChargeAdapter: ClientChargeAdapter? = null + private var id: Long? = 0 + private var chargeType: ChargeType? = null + private var rootView: View? = null + private var layoutManager: LinearLayoutManager? = null + private var clientChargeList: List? = ArrayList() + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + if (arguments != null) { + id = arguments?.getLong(Constants.CLIENT_ID) + chargeType = arguments?.getSerializable(Constants.CHARGE_TYPE) as ChargeType + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_client_charge, container, false) + ButterKnife.bind(this, rootView!!) + clientChargePresenter?.attachView(this) + setToolbarTitle(getString(R.string.charges)) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + layoutManager = LinearLayoutManager(activity) + layoutManager?.orientation = LinearLayoutManager.VERTICAL + rvClientCharge?.layoutManager = layoutManager + rvClientCharge?.addOnItemTouchListener(RecyclerItemClickListener(activity, this)) + swipeChargeContainer?.setColorSchemeResources(R.color.blue_light, R.color.green_light, R.color.orange_light, R.color.red_light) + swipeChargeContainer?.setOnRefreshListener { loadCharges() } + if (savedInstanceState == null) { + loadCharges() + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelableArrayList(Constants.CHARGES, ArrayList( + clientChargeList)) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + val charges: List = savedInstanceState.getParcelableArrayList(Constants.CHARGES) + showClientCharges(charges) + } + } + + /** + * Fetches Charges for `id` according to `chargeType` provided. + */ + private fun loadCharges() { + if (layoutError?.visibility == View.VISIBLE) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvClientCharge, layoutError) + } + when (chargeType) { + ChargeType.CLIENT -> id?.let { clientChargePresenter?.loadClientCharges(it) } + ChargeType.SAVINGS -> id?.let { clientChargePresenter?.loadSavingsAccountCharges(it) } + ChargeType.LOAN -> id?.let { clientChargePresenter?.loadLoanAccountCharges(it) } + } + } + + /** + * It is called whenever any error occurs while executing a request. If not connected to + * internet then it shows display a message to user to connect to internet other it just + * displays the `message` in a {@link Snackbar} + * + * @param message Error message that tells the user about the problem. + */ + override fun showErrorFetchingClientCharges(message: String?) { + if (!Network.isConnected(activity)) { + sweetUIErrorHandler?.showSweetNoInternetUI(rvClientCharge, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(message, rvClientCharge, layoutError) + Toaster.show(rootView, message) + } + } + + /** + * Tries to fetch charges again. + */ + @OnClick(R.id.btn_try_again) + fun retryClicked() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvClientCharge, layoutError) + loadCharges() + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + override fun showClientCharges(clientChargeList: List?) { + this.clientChargeList = clientChargeList + inflateClientChargeList() + if (swipeChargeContainer!!.isRefreshing) { + swipeChargeContainer!!.isRefreshing = false + } + } + + /** + * Updates `clientChargeAdapter` with updated `clientChargeList` if + * `clientChargeList` size if greater than 0 else shows the error layout + */ + private fun inflateClientChargeList() { + if (clientChargeList?.isNotEmpty() == true) { + clientChargeAdapter?.setClientChargeList(clientChargeList) + rvClientCharge?.adapter = clientChargeAdapter + } else { + sweetUIErrorHandler?.showSweetEmptyUI(getString(R.string.charges), R.drawable.ic_charges, + rvClientCharge, layoutError) + } + } + + override fun showProgress() { + swipeChargeContainer?.isRefreshing = true + } + + override fun hideProgress() { + swipeChargeContainer?.isRefreshing = false + } + + override fun onItemClick(childView: View?, position: Int) {} + override fun onItemLongPress(childView: View?, position: Int) {} + override fun onDestroyView() { + super.onDestroyView() + clientChargePresenter?.detachView() + } + + companion object { + fun newInstance(clientId: Long?, chargeType: ChargeType?): ClientChargeFragment { + val clientChargeFragment = ClientChargeFragment() + val args = Bundle() + if (clientId != null) + args.putLong(Constants.CLIENT_ID, clientId) + args.putSerializable(Constants.CHARGE_TYPE, chargeType) + clientChargeFragment.arguments = args + return clientChargeFragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorDetailFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorDetailFragment.java deleted file mode 100644 index 3ddf89547e..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorDetailFragment.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* - * Created by saksham on 24/July/2018 - */ - -import android.content.DialogInterface; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; -import android.widget.Toast; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.presenters.GuarantorDetailPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.GuarantorState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.GuarantorDetailView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.RxBus; -import org.mifos.mobile.utils.RxEvent; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import io.reactivex.disposables.Disposable; -import io.reactivex.functions.Consumer; - -public class GuarantorDetailFragment extends BaseFragment implements GuarantorDetailView { - - @BindView(R.id.tv_first_name) - TextView tvFirstName; - - @BindView(R.id.tv_last_name) - TextView tvLastName; - - @BindView(R.id.tv_joined_date) - TextView tvJoinedDate; - - @BindView(R.id.tv_guarantor_type) - TextView tvGuarantorType; - - @BindView(R.id.tv_office_name) - TextView tvOfficeName; - - @Inject - GuarantorDetailPresenter presenter; - - View rootView; - long loanId; - long guarantorId; - int index; - GuarantorPayload payload; - Disposable disposableUpdateGuarantor; - boolean isFirstTime = true; - - public static GuarantorDetailFragment newInstance(int index, long loanId, - GuarantorPayload payload) { - GuarantorDetailFragment fragment = new GuarantorDetailFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.LOAN_ID, loanId); - args.putParcelable(Constants.GUARANTOR_DETAILS, payload); - args.putInt(Constants.INDEX, index); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - loanId = getArguments().getLong(Constants.LOAN_ID); - payload = getArguments().getParcelable(Constants.GUARANTOR_DETAILS); - index = getArguments().getInt(Constants.INDEX); - guarantorId = payload.getId(); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_guarantor_detail, container, false); - setToolbarTitle(getString(R.string.guarantor_details)); - setHasOptionsMenu(true); - ButterKnife.bind(this, rootView); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - - if (isFirstTime) { - isFirstTime = false; - setUpRxBus(); - } - - presenter.attachView(this); - return rootView; - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - tvFirstName.setText(payload.getFirstname()); - tvLastName.setText(payload.getLastname()); - tvGuarantorType.setText(payload.getGuarantorType().getValue()); - tvJoinedDate.setText(DateHelper.getDateAsString(payload.getJoinedDate())); - tvOfficeName.setText(payload.getOfficeName()); - } - - private void setUpRxBus() { - disposableUpdateGuarantor = RxBus.listen(RxEvent.UpdateGuarantorEvent.class) - .subscribe(new Consumer() { - @Override - public void accept(RxEvent.UpdateGuarantorEvent updateGuarantorEvent) - throws Exception { - payload.setFirstname(updateGuarantorEvent.getPayload().getFirstName()); - payload.setLastname(updateGuarantorEvent.getPayload().getLastName()); - payload.setGuarantorType(updateGuarantorEvent.getPayload() - .getGuarantorType()); - payload.setOfficeName(updateGuarantorEvent.getPayload().getOfficeName()); - } - }); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_guarantor, menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int itemId = item.getItemId(); - switch (itemId) { - case R.id.menu_delete_guarantor: - new MaterialDialog.Builder() - .init(getContext()) - .setTitle(getString(R.string.delete_guarantor)) - .setMessage(getString(R.string.dialog_are_you_sure_that_you_want_to_string, - getString(R.string.delete_guarantor))) - .setPositiveButton(getString(R.string.yes), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - presenter.deleteGuarantor(loanId, guarantorId); - } - }) - .setNegativeButton(getString(R.string.cancel)) - .createMaterialDialog() - .show(); - break; - case R.id.menu_update_guarantor: - ((BaseActivity) getActivity()).replaceFragment(AddGuarantorFragment - .newInstance(index, GuarantorState.UPDATE, payload, loanId), - true, R.id.container); - break; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void guarantorDeletedSuccessfully(String message) { - getActivity().getSupportFragmentManager().popBackStack(); - RxBus.publish(new RxEvent.DeleteGuarantorEvent(index)); - Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); - } - - @Override - public void showError(String message) { - Toaster.show(rootView, message); - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroy() { - super.onDestroy(); - presenter.detachView(); - if (!disposableUpdateGuarantor.isDisposed()) { - disposableUpdateGuarantor.dispose(); - } - hideProgressBar(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorDetailFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorDetailFragment.kt new file mode 100644 index 0000000000..533a31cfbb --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorDetailFragment.kt @@ -0,0 +1,174 @@ +package org.mifos.mobile.ui.fragments + +import android.content.DialogInterface +import android.os.Bundle +import android.view.* +import android.widget.TextView +import android.widget.Toast +import butterknife.BindView +import butterknife.ButterKnife +import io.reactivex.disposables.Disposable +import org.mifos.mobile.R +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.presenters.GuarantorDetailPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.GuarantorState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.GuarantorDetailView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DateHelper +import org.mifos.mobile.utils.MaterialDialog +import org.mifos.mobile.utils.RxBus.listen +import org.mifos.mobile.utils.RxBus.publish +import org.mifos.mobile.utils.RxEvent.DeleteGuarantorEvent +import org.mifos.mobile.utils.RxEvent.UpdateGuarantorEvent +import org.mifos.mobile.utils.Toaster +import javax.inject.Inject + +/* +* Created by saksham on 24/July/2018 +*/ class GuarantorDetailFragment : BaseFragment(), GuarantorDetailView { + @kotlin.jvm.JvmField + @BindView(R.id.tv_first_name) + var tvFirstName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_last_name) + var tvLastName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_joined_date) + var tvJoinedDate: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_guarantor_type) + var tvGuarantorType: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_office_name) + var tvOfficeName: TextView? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: GuarantorDetailPresenter? = null + var rootView: View? = null + var loanId: Long? = 0 + private var guarantorId: Long? = 0 + var index: Int? = 0 + var payload: GuarantorPayload? = null + var disposableUpdateGuarantor: Disposable? = null + var isFirstTime = true + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + loanId = arguments?.getLong(Constants.LOAN_ID) + payload = arguments?.getParcelable(Constants.GUARANTOR_DETAILS) + index = arguments?.getInt(Constants.INDEX) + guarantorId = payload?.id + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_guarantor_detail, container, false) + setToolbarTitle(getString(R.string.guarantor_details)) + setHasOptionsMenu(true) + ButterKnife.bind(this, rootView!!) + (activity as BaseActivity?)?.activityComponent?.inject(this) + if (isFirstTime) { + isFirstTime = false + setUpRxBus() + } + presenter?.attachView(this) + return rootView + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + tvFirstName?.text = payload?.firstname + tvLastName?.text = payload?.lastname + tvGuarantorType?.text = payload?.guarantorType?.value + tvJoinedDate?.text = DateHelper.getDateAsString(payload?.joinedDate) + tvOfficeName?.text = payload?.officeName + } + + private fun setUpRxBus() { + disposableUpdateGuarantor = listen(UpdateGuarantorEvent::class.java) + .subscribe { (payload1) -> + payload?.firstname = payload1?.firstName + payload?.lastname = payload1?.lastName + payload?.guarantorType = payload1 + ?.guarantorType + payload?.officeName = payload1?.officeName + } + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + super.onCreateOptionsMenu(menu, inflater) + inflater.inflate(R.menu.menu_guarantor, menu) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + R.id.menu_delete_guarantor -> MaterialDialog.Builder() + .init(context) + .setTitle(R.string.delete_guarantor) + .setMessage(getString(R.string.dialog_are_you_sure_that_you_want_to_string, + getString(R.string.delete_guarantor))) + .setPositiveButton(getString(R.string.yes), + DialogInterface.OnClickListener { _, _ -> + presenter?.deleteGuarantor(loanId, guarantorId) + }) + .setNegativeButton(R.string.cancel) + .createMaterialDialog() + .show() + R.id.menu_update_guarantor -> (activity as BaseActivity?)?.replaceFragment(AddGuarantorFragment.newInstance(index, GuarantorState.UPDATE, payload, loanId), + true, R.id.container) + } + return super.onOptionsItemSelected(item) + } + + override fun guarantorDeletedSuccessfully(message: String?) { + activity?.supportFragmentManager?.popBackStack() + publish(DeleteGuarantorEvent(index)) + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + } + + override fun showError(message: String?) { + Toaster.show(rootView, message) + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroy() { + super.onDestroy() + presenter?.detachView() + if (disposableUpdateGuarantor?.isDisposed == false) { + disposableUpdateGuarantor?.dispose() + } + hideProgressBar() + } + + companion object { + fun newInstance( + index: Int, loanId: Long, + payload: GuarantorPayload? + ): GuarantorDetailFragment { + val fragment = GuarantorDetailFragment() + val args = Bundle() + args.putLong(Constants.LOAN_ID, loanId) + args.putParcelable(Constants.GUARANTOR_DETAILS, payload) + args.putInt(Constants.INDEX, index) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorListFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorListFragment.java deleted file mode 100644 index 2a21e87e55..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorListFragment.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* - * Created by saksham on 23/July/2018 - */ - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.presenters.GuarantorListPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.GuarantorListAdapter; -import org.mifos.mobile.ui.enums.GuarantorState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.GuarantorListView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.RxBus; -import org.mifos.mobile.utils.RxEvent; - -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import io.reactivex.disposables.Disposable; -import io.reactivex.functions.Consumer; - -public class GuarantorListFragment extends BaseFragment implements GuarantorListView { - - @BindView(R.id.layout_error) - View layoutError; - - @BindView(R.id.ll_container) - LinearLayout llContainer; - - @BindView(R.id.rv_guarantors) - RecyclerView rvGuarantors; - - @Inject - GuarantorListPresenter presenter; - - GuarantorListAdapter adapter; - - View rootView; - long loanId; - SweetUIErrorHandler sweetUIErrorHandler; - List list; - Disposable disposableAddGuarantor, disposableDeleteGuarantor; - - public static GuarantorListFragment newInstance(long loanId) { - GuarantorListFragment fragment = new GuarantorListFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.LOAN_ID, loanId); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - loanId = getArguments().getLong(Constants.LOAN_ID); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_guarantor_list, container, false); - ButterKnife.bind(this, rootView); - setToolbarTitle(getString(R.string.view_guarantor)); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - presenter.attachView(this); - if (list == null) { - presenter.getGuarantorList(loanId); - adapter = new GuarantorListAdapter(getContext(), - new GuarantorListAdapter.OnClickListener() { - @Override - public void setOnClickListener(int position) { - ((BaseActivity) getActivity()).replaceFragment(GuarantorDetailFragment - .newInstance(position, loanId, list.get(position)), - true, R.id.container); - } - }); - setUpRxBus(); - } - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - return rootView; - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (list != null && list.size() == 0) { - sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.no_guarantors), - getString(R.string.tap_to_add_guarantor), - R.drawable.ic_person_black_24dp, llContainer, layoutError); - } - rvGuarantors.setAdapter(adapter); - rvGuarantors.setLayoutManager(new LinearLayoutManager(getContext())); - } - - private void setUpRxBus() { - disposableAddGuarantor = RxBus.listen(RxEvent.AddGuarantorEvent.class) - .subscribe(new Consumer() { - @Override - public void accept(RxEvent.AddGuarantorEvent event) - throws Exception { - //TODO wrong guarantor id is assigned, although it wont affect the working - list.add(event.getIndex(), new GuarantorPayload(list.size(), - event.getPayload().getOfficeName(), - event.getPayload().getLastName(), - event.getPayload().getGuarantorType(), - event.getPayload().getFirstName(), - DateHelper.getCurrentDate("yyyy-MM-dd", "-"), - loanId)); - adapter.setGuarantorList(list); - } - }); - disposableDeleteGuarantor = RxBus.listen(RxEvent.DeleteGuarantorEvent.class) - .subscribe(new Consumer() { - @Override - public void accept(RxEvent.DeleteGuarantorEvent deleteGuarantorEvent) - throws Exception { - int index = deleteGuarantorEvent.getIndex(); - list.remove(index); - adapter.setGuarantorList(list); - } - }); - } - - @OnClick(R.id.fab_add_loan_guarantor) - void addGuarantor() { - ((BaseActivity) getActivity()).replaceFragment(AddGuarantorFragment - .newInstance(0, GuarantorState.CREATE, null, loanId), true, R.id.container); - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - - } - - @Override - public void showGuarantorListSuccessfully(final List list) { - this.list = list; - if (list.size() == 0) { - sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.no_guarantors), - getString(R.string.tap_to_add_guarantor), - R.drawable.ic_person_black_24dp, llContainer, layoutError); - } else { - adapter.setGuarantorList(list); - } - } - - @Override - public void showError(String message) { - - } - - @Override - public void onDestroy() { - super.onDestroy(); - presenter.detachView(); - if (!disposableAddGuarantor.isDisposed()) { - disposableAddGuarantor.dispose(); - } - if (!disposableDeleteGuarantor.isDisposed()) { - disposableDeleteGuarantor.dispose(); - } - hideProgress(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorListFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorListFragment.kt new file mode 100644 index 0000000000..e50c040d51 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/GuarantorListFragment.kt @@ -0,0 +1,169 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout + +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import io.reactivex.disposables.Disposable + +import org.mifos.mobile.R +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.presenters.GuarantorListPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.GuarantorListAdapter +import org.mifos.mobile.ui.enums.GuarantorState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.GuarantorListView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DateHelper +import org.mifos.mobile.utils.RxBus.listen +import org.mifos.mobile.utils.RxEvent.AddGuarantorEvent +import org.mifos.mobile.utils.RxEvent.DeleteGuarantorEvent + +import javax.inject.Inject + +/* +* Created by saksham on 23/July/2018 +*/ +class GuarantorListFragment : BaseFragment(), GuarantorListView { + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_container) + var llContainer: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.rv_guarantors) + var rvGuarantors: RecyclerView? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: GuarantorListPresenter? = null + var adapter: GuarantorListAdapter? = null + var rootView: View? = null + var loanId: Long = 0 + var sweetUIErrorHandler: SweetUIErrorHandler? = null + var list: MutableList? = null + private var disposableAddGuarantor: Disposable? = null + private var disposableDeleteGuarantor: Disposable? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) loanId = arguments!!.getLong(Constants.LOAN_ID) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + val rootView: View = inflater.inflate(R.layout.fragment_guarantor_list, container, false) + ButterKnife.bind(this, rootView) + setToolbarTitle(getString(R.string.view_guarantor)) + (activity as BaseActivity?)?.activityComponent?.inject(this) + presenter?.attachView(this) + if (list == null) { + presenter?.getGuarantorList(loanId) + adapter = GuarantorListAdapter(context, + object : GuarantorListAdapter.OnClickListener { + override fun setOnClickListener(position: Int) { + (activity as BaseActivity?)?.replaceFragment(GuarantorDetailFragment + .newInstance(position, loanId, list!![position]), + true, R.id.container) + } + }) + setUpRxBus() + } + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + return rootView + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (list != null && list?.size == 0) { + sweetUIErrorHandler?.showSweetCustomErrorUI(getString(R.string.no_guarantors), + getString(R.string.tap_to_add_guarantor), + R.drawable.ic_person_black_24dp, llContainer, layoutError) + } + rvGuarantors?.adapter = adapter + rvGuarantors?.layoutManager = LinearLayoutManager(context) + } + + private fun setUpRxBus() { + disposableAddGuarantor = listen(AddGuarantorEvent::class.java) + .subscribe { (payload, index) -> //TODO wrong guarantor id is assigned, although it wont affect the working + if (index != null) + list?.add(index, GuarantorPayload(list?.size?.toLong(), + payload?.officeName, + payload?.lastName, + payload?.guarantorType, + payload?.firstName, + DateHelper.getCurrentDate("yyyy-MM-dd", "-"), + loanId)) + adapter?.setGuarantorList(list) + } + disposableDeleteGuarantor = listen(DeleteGuarantorEvent::class.java) + .subscribe { (index) -> + if (index != null) list?.removeAt(index) + adapter?.setGuarantorList(list) + } + } + + @OnClick(R.id.fab_add_loan_guarantor) + fun addGuarantor() { + (activity as BaseActivity?)?.replaceFragment(AddGuarantorFragment.newInstance(0, GuarantorState.CREATE, null, loanId), true, R.id.container) + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + override fun showGuarantorListSuccessfully(list: List?) { + this.list = list as MutableList? + if (list?.size == 0) { + sweetUIErrorHandler?.showSweetCustomErrorUI(getString(R.string.no_guarantors), + getString(R.string.tap_to_add_guarantor), + R.drawable.ic_person_black_24dp, llContainer, layoutError) + } else { + adapter?.setGuarantorList(list) + } + } + + override fun showError(message: String?) {} + override fun onDestroy() { + super.onDestroy() + presenter?.detachView() + if (disposableAddGuarantor?.isDisposed == false) { + disposableAddGuarantor?.dispose() + } + if (disposableDeleteGuarantor?.isDisposed == false) { + disposableDeleteGuarantor?.dispose() + } + hideProgress() + } + + companion object { + fun newInstance(loanId: Long?): GuarantorListFragment { + val fragment = GuarantorListFragment() + val args = Bundle() + if (loanId != null) args.putLong(Constants.LOAN_ID, loanId) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/HelpFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/HelpFragment.java deleted file mode 100644 index 11b1004361..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/HelpFragment.java +++ /dev/null @@ -1,179 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.app.SearchManager; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Parcelable; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import com.google.android.material.bottomnavigation.BottomNavigationView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.FAQ; -import org.mifos.mobile.presenters.HelpPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.FAQAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.HelpView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DividerItemDecoration; - -import java.util.ArrayList; - -import javax.inject.Inject; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.SearchView; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; - -public class HelpFragment extends BaseFragment implements HelpView, BottomNavigationView. - OnNavigationItemSelectedListener { - - @BindView(R.id.rv_faq) - RecyclerView rvFaq; - - @BindView(R.id.bnv_help) - BottomNavigationView bnvHelp; - - @Inject - FAQAdapter faqAdapter; - - @Inject - HelpPresenter presenter; - - private View rootView; - private ArrayList faqArrayList; - - public static HelpFragment newInstance() { - HelpFragment fragment = new HelpFragment(); - Bundle args = new Bundle(); - fragment.setArguments(args); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_help, container, false); - setHasOptionsMenu(true); - - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - presenter.attachView(this); - setToolbarTitle(getString(R.string.help)); - - showUserInterface(); - if (savedInstanceState == null) { - presenter.loadFaq(); - } - - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelableArrayList(Constants.HELP, new ArrayList(faqArrayList)); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - ArrayList faqs = savedInstanceState.getParcelableArrayList(Constants.HELP); - showFaq(faqs); - } - } - - private void showUserInterface() { - - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - rvFaq.setLayoutManager(layoutManager); - rvFaq.addItemDecoration(new DividerItemDecoration(getActivity(), - layoutManager.getOrientation())); - - bnvHelp.setOnNavigationItemSelectedListener(this); - } - - @Override - public void showFaq(ArrayList faqArrayList) { - faqAdapter.setFaqArrayList(faqArrayList); - rvFaq.setAdapter(faqAdapter); - this.faqArrayList = faqArrayList; - } - - @Override - public boolean onNavigationItemSelected(@NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_call: - Intent intent = new Intent(Intent.ACTION_DIAL); - intent.setData(Uri.parse("tel:" + getString(R.string.help_line_number))); - startActivity(intent); - break; - case R.id.menu_email: - Intent emailIntent = new Intent(Intent.ACTION_SENDTO); - emailIntent.setData(Uri.parse("mailto:" + getString(R.string.contact_email))); - emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.user_query)); - if (emailIntent.resolveActivity(getActivity().getPackageManager()) != null) { - startActivity(emailIntent); - } - break; - case R.id.menu_locations: - ((BaseActivity) getActivity()).replaceFragment(LocationsFragment.newInstance(), - true, R.id.container); - break; - } - return true; - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_help, menu); - - SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context. - SEARCH_SERVICE); - - SearchView searchView = (SearchView) menu.findItem(R.id.menu_search_faq).getActionView(); - searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity(). - getComponentName())); - searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - return false; - } - - @Override - public boolean onQueryTextChange(String newText) { - faqAdapter.updateList(presenter.filterList(faqArrayList, newText)); - return false; - } - }); - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/HelpFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/HelpFragment.kt new file mode 100644 index 0000000000..983bb721b3 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/HelpFragment.kt @@ -0,0 +1,147 @@ +package org.mifos.mobile.ui.fragments + +import android.app.SearchManager +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Parcelable +import android.view.* +import androidx.appcompat.widget.SearchView +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import butterknife.BindView +import butterknife.ButterKnife +import com.google.android.material.bottomnavigation.BottomNavigationView +import org.mifos.mobile.R +import org.mifos.mobile.models.FAQ +import org.mifos.mobile.presenters.HelpPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.FAQAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.HelpView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DividerItemDecoration +import java.util.* +import javax.inject.Inject + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ class HelpFragment : BaseFragment(), HelpView, BottomNavigationView.OnNavigationItemSelectedListener { + @kotlin.jvm.JvmField + @BindView(R.id.rv_faq) + var rvFaq: RecyclerView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.bnv_help) + var bnvHelp: BottomNavigationView? = null + + @kotlin.jvm.JvmField + @Inject + var faqAdapter: FAQAdapter? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: HelpPresenter? = null + private var rootView: View? = null + private var faqArrayList: ArrayList? = null + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_help, container, false) + setHasOptionsMenu(true) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + presenter?.attachView(this) + setToolbarTitle(getString(R.string.help)) + showUserInterface() + if (savedInstanceState == null) { + presenter?.loadFaq() + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelableArrayList(Constants.HELP, ArrayList(faqArrayList)) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + val faqs: ArrayList = savedInstanceState.getParcelableArrayList(Constants.HELP) + showFaq(faqs) + } + } + + private fun showUserInterface() { + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = LinearLayoutManager.VERTICAL + rvFaq?.layoutManager = layoutManager + rvFaq?.addItemDecoration(DividerItemDecoration(activity, + layoutManager.orientation)) + bnvHelp?.setOnNavigationItemSelectedListener(this) + } + + override fun showFaq(faqArrayList: ArrayList?) { + faqAdapter?.setFaqArrayList(faqArrayList) + rvFaq?.adapter = faqAdapter + this.faqArrayList = faqArrayList + } + + override fun onNavigationItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + R.id.menu_call -> { + val intent = Intent(Intent.ACTION_DIAL) + intent.data = Uri.parse("tel:" + getString(R.string.help_line_number)) + startActivity(intent) + } + R.id.menu_email -> { + val emailIntent = Intent(Intent.ACTION_SENDTO) + emailIntent.data = Uri.parse("mailto:" + getString(R.string.contact_email)) + emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.user_query)) + if (emailIntent.resolveActivity(activity?.packageManager) != null) { + startActivity(emailIntent) + } + } + R.id.menu_locations -> (activity as BaseActivity?)?.replaceFragment(LocationsFragment.newInstance(), + true, R.id.container) + } + return true + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + inflater.inflate(R.menu.menu_help, menu) + val searchManager = activity?.getSystemService(Context.SEARCH_SERVICE) as SearchManager + val searchView = menu.findItem(R.id.menu_search_faq).actionView as SearchView + searchView.setSearchableInfo(searchManager.getSearchableInfo(activity?.componentName)) + searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { + override fun onQueryTextSubmit(query: String): Boolean { + return false + } + + override fun onQueryTextChange(newText: String): Boolean { + faqAdapter?.updateList(presenter?.filterList(faqArrayList, newText)) + return false + } + }) + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): HelpFragment { + val fragment = HelpFragment() + val args = Bundle() + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/HomeFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/HomeFragment.java deleted file mode 100644 index 414f0701f4..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/HomeFragment.java +++ /dev/null @@ -1,396 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.Bitmap; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.presenters.HomePresenter; -import org.mifos.mobile.ui.activities.AccountOverviewActivity; -import org.mifos.mobile.ui.activities.HomeActivity; -import org.mifos.mobile.ui.activities.LoanApplicationActivity; -import org.mifos.mobile.ui.activities.UserProfileActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.AccountType; -import org.mifos.mobile.ui.enums.ChargeType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.HomeView; -import org.mifos.mobile.utils.CircularImageView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.TextDrawable; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.core.content.ContextCompat; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by michaelsosnick on 1/1/17. - */ - -public class HomeFragment extends BaseFragment implements HomeView, - SwipeRefreshLayout.OnRefreshListener { - - public static final String LOG_TAG = HomeFragment.class.getSimpleName(); - - @BindView(R.id.iv_user_image) - ImageView ivUserImage; - - @BindView(R.id.iv_circular_user_image) - CircularImageView ivCircularUserImage; - - @BindView(R.id.tv_user_name) - TextView tvUserName; - - @BindView(R.id.swipe_home_container) - SwipeRefreshLayout slHomeContainer; - - @Inject - HomePresenter presenter; - - @Inject - PreferencesHelper preferencesHelper; - - View rootView; - - private Bitmap userProfileBitmap; - private long clientId; - private int notifCount = 0; - private boolean isReceiverRegistered; - private TextView tvNotificationCount; - - public static HomeFragment newInstance() { - HomeFragment fragment = new HomeFragment(); - Bundle args = new Bundle(); - fragment.setArguments(args); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_home_ui, container, false); - ((HomeActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - clientId = preferencesHelper.getClientId(); - - setHasOptionsMenu(true); - - presenter.attachView(this); - - slHomeContainer.setColorSchemeResources(R.color.blue_light, R.color.green_light, R - .color.orange_light, R.color.red_light); - slHomeContainer.setOnRefreshListener(this); - - if (savedInstanceState == null) { - loadClientData(); - } - - setToolbarTitle(getString(R.string.home)); - showUserImageTextDrawable(); - - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.USER_PROFILE, userProfileBitmap); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showUserImage((Bitmap) savedInstanceState.getParcelable(Constants.USER_PROFILE)); - showUserDetails(preferencesHelper.getClientName()); - } - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_main, menu); - MenuItem menuItem = menu.findItem(R.id.menu_notifications); - View count = menuItem.getActionView(); - tvNotificationCount = count.findViewById(R.id.tv_notification_indicator); - count.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ((BaseActivity) getActivity()).replaceFragment(NotificationFragment.newInstance(), - true, R.id.container); - } - }); - super.onCreateOptionsMenu(menu, inflater); - } - - @Override - public void onResume() { - super.onResume(); - registerReceiver(); - getActivity().invalidateOptionsMenu(); - } - - @Override - public void onPause() { - LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(notificationReceiver); - isReceiverRegistered = false; - super.onPause(); - } - - private void registerReceiver() { - if (!isReceiverRegistered) { - LocalBroadcastManager.getInstance(getActivity()).registerReceiver(notificationReceiver, - new IntentFilter(Constants.NOTIFY_HOME_FRAGMENT)); - isReceiverRegistered = true; - } - } - - @Override - public void onRefresh() { - loadClientData(); - } - - private void loadClientData() { - if (!preferencesHelper.getClientName().isEmpty()) { - tvUserName.setText(getString(R.string.hello_client, preferencesHelper.getClientName())); - hideProgress(); - } else { - presenter.getUserDetails(); - } - presenter.getUserImage(); - presenter.getUnreadNotificationsCount(); - } - - /** - * Opens {@link ClientAccountsFragment} according to the {@code accountType} provided - * - * @param accountType Enum of {@link AccountType} - */ - public void openAccount(AccountType accountType) { - ((BaseActivity) getActivity()).replaceFragment( - ClientAccountsFragment.newInstance(accountType), true, R.id.container); - } - - /** - * Fetches Client details and display clientName - * - * @param userName of the client - */ - @Override - public void showUserDetails(String userName) { - tvUserName.setText(getString(R.string.hello_client, userName)); - } - - @Override - public void showUserImageTextDrawable() { - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - String userName; - if (!preferencesHelper.getClientName().isEmpty()) { - userName = preferencesHelper.getClientName(); - } else { - userName = getString(R.string.app_name); - } - TextDrawable drawable = TextDrawable.builder() - .beginConfig() - .toUpperCase() - .endConfig() - .buildRound(userName.substring(0, 1), - ContextCompat.getColor(getActivity(), R.color.primary_dark)); - ivUserImage.setImageDrawable(drawable); - ivUserImage.setVisibility(View.VISIBLE); - ivCircularUserImage.setVisibility(View.GONE); - } - }); - } - - /** - * Provides with Client image fetched from server - * - * @param bitmap Client Image - */ - @Override - public void showUserImage(final Bitmap bitmap) { - if (bitmap != null) { - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - userProfileBitmap = bitmap; - ivCircularUserImage.setImageBitmap(bitmap); - ivCircularUserImage.setVisibility(View.VISIBLE); - ivUserImage.setVisibility(View.GONE); - } - }); - } - } - - @Override - public void showNotificationCount(int count) { - if (count > 0) { - tvNotificationCount.setText(String.valueOf(count)); - } else { - tvNotificationCount.setVisibility(View.GONE); - } - } - - @OnClick(R.id.iv_user_image) - public void userImageClicked() { - startActivity(new Intent(getActivity(), UserProfileActivity.class)); - } - - @OnClick(R.id.iv_circular_user_image) - void userCirCularImageClick() { - startActivity(new Intent(getActivity(), UserProfileActivity.class)); - } - - /** - * Calls for opening Account Overview - */ - @OnClick(R.id.ll_account_overview) - void onAccountOverview() { - startActivity(new Intent(getActivity(), AccountOverviewActivity.class)); - } - - /** - * Calls {@code openAccount()} for opening {@link ClientAccountsFragment} - */ - @OnClick(R.id.ll_accounts) - public void accountsClicked() { - openAccount(AccountType.SAVINGS); - ((HomeActivity) getActivity()).setNavigationViewSelectedItem(R.id.item_accounts); - } - - /** - * Shows a dialog with options: Normal Transfer and Third Party Transfer - */ - @OnClick(R.id.ll_transfer) - public void transferClicked() { - String[] transferTypes = {getString(R.string.transfer), getString(R.string. - third_party_transfer)}; - new MaterialDialog.Builder().init(getActivity()) - .setTitle(R.string.choose_transfer_type) - .setItems(transferTypes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == 0) { - ((HomeActivity) getActivity()).replaceFragment( - SavingsMakeTransferFragment.newInstance(1, ""), true, - R.id.container); - } else { - ((HomeActivity) getActivity()).replaceFragment( - ThirdPartyTransferFragment.newInstance(), true, R.id.container); - } - } - }) - .createMaterialDialog() - .show(); - } - - /** - * Opens {@link ClientChargeFragment} to display all Charges associated with client's account - */ - @OnClick(R.id.ll_charges) - public void chargesClicked() { - ((HomeActivity) getActivity()).replaceFragment(ClientChargeFragment.newInstance(clientId, - ChargeType.CLIENT), true, R.id.container); - } - - /** - * Opens {@link LoanApplicationFragment} to apply for a loan - */ - @OnClick(R.id.ll_apply_for_loan) - public void applyForLoan() { - startActivity(new Intent(getActivity(), LoanApplicationActivity.class)); - } - - /** - * Opens {@link BeneficiaryListFragment} which contains list of Beneficiaries associated with - * Client's account - */ - @OnClick(R.id.ll_beneficiaries) - public void beneficiaries() { - ((HomeActivity) getActivity()).replaceFragment(BeneficiaryListFragment. - newInstance(), true, R.id.container); - } - - @OnClick(R.id.ll_surveys) - public void surveys() { - - } - - @OnClick(R.id.ll_recent_transactions) - public void showRecentTransactions() { - ((HomeActivity) getActivity()).replaceFragment(RecentTransactionsFragment.newInstance(), - true, R.id.container); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param errorMessage Error message that tells the user about the problem. - */ - @Override - public void showError(String errorMessage) { - Toaster.show(rootView, errorMessage); - } - - @Override - public void showUserImageNotFound() { - showUserImageTextDrawable(); - } - - /** - * Shows {@link SwipeRefreshLayout} - */ - @Override - public void showProgress() { - slHomeContainer.setRefreshing(true); - } - - /** - * Hides {@link SwipeRefreshLayout} - */ - @Override - public void hideProgress() { - slHomeContainer.setRefreshing(false); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - presenter.detachView(); - if (slHomeContainer.isRefreshing()) { - slHomeContainer.setRefreshing(false); - } - slHomeContainer.removeAllViews(); - } - - private BroadcastReceiver notificationReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - getActivity().invalidateOptionsMenu(); - } - }; - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/HomeFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/HomeFragment.kt new file mode 100644 index 0000000000..a6675a31c1 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/HomeFragment.kt @@ -0,0 +1,351 @@ +package org.mifos.mobile.ui.fragments + +import android.content.* +import android.graphics.Bitmap +import android.os.Bundle +import android.os.Parcelable +import android.view.* +import android.widget.ImageView +import android.widget.TextView + +import androidx.core.content.ContextCompat +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.presenters.HomePresenter +import org.mifos.mobile.ui.activities.AccountOverviewActivity +import org.mifos.mobile.ui.activities.HomeActivity +import org.mifos.mobile.ui.activities.LoanApplicationActivity +import org.mifos.mobile.ui.activities.UserProfileActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.AccountType +import org.mifos.mobile.ui.enums.ChargeType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.HomeView +import org.mifos.mobile.utils.* + +import javax.inject.Inject + +/** + * Created by michaelsosnick on 1/1/17. + */ +class HomeFragment : BaseFragment(), HomeView, OnRefreshListener { + + @JvmField + @BindView(R.id.iv_user_image) + var ivUserImage: ImageView? = null + + @JvmField + @BindView(R.id.iv_circular_user_image) + var ivCircularUserImage: CircularImageView? = null + + + @JvmField + @BindView(R.id.tv_user_name) + var tvUserName: TextView? = null + + + @JvmField + @BindView(R.id.swipe_home_container) + var slHomeContainer: SwipeRefreshLayout? = null + + @JvmField + @Inject + var presenter: HomePresenter? = null + + @JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + + lateinit var rootView: View + private var userProfileBitmap: Bitmap? = null + private var clientId: Long? = 0 + private val notifCount = 0 + private var isReceiverRegistered = false + private var tvNotificationCount: TextView? = null + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_home_ui, container, false) + (activity as HomeActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView) + clientId = preferencesHelper?.clientId + setHasOptionsMenu(true) + presenter?.attachView(this) + slHomeContainer?.setColorSchemeResources(R.color.blue_light, R.color.green_light, R.color.orange_light, R.color.red_light) + slHomeContainer?.setOnRefreshListener(this) + if (savedInstanceState == null) { + loadClientData() + } + setToolbarTitle(getString(R.string.home)) + showUserImageTextDrawable() + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.USER_PROFILE, userProfileBitmap) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showUserImage(savedInstanceState.getParcelable(Constants.USER_PROFILE) as Bitmap) + showUserDetails(preferencesHelper?.clientName) + } + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + inflater.inflate(R.menu.menu_main, menu) + val menuItem = menu.findItem(R.id.menu_notifications) + val count = menuItem.actionView + tvNotificationCount = count.findViewById(R.id.tv_notification_indicator) + count.setOnClickListener { + (activity as BaseActivity?)?.replaceFragment(NotificationFragment.newInstance(), + true, R.id.container) + } + super.onCreateOptionsMenu(menu, inflater) + } + + override fun onResume() { + super.onResume() + registerReceiver() + activity?.invalidateOptionsMenu() + } + + override fun onPause() { + LocalBroadcastManager.getInstance(activity!!).unregisterReceiver(notificationReceiver) + isReceiverRegistered = false + super.onPause() + } + + private fun registerReceiver() { + if (!isReceiverRegistered) { + LocalBroadcastManager.getInstance(activity!!).registerReceiver(notificationReceiver, + IntentFilter(Constants.NOTIFY_HOME_FRAGMENT)) + isReceiverRegistered = true + } + } + + override fun onRefresh() { + loadClientData() + } + + private fun loadClientData() { + if (preferencesHelper?.clientName?.isBlank() == true) { + tvUserName?.text = getString(R.string.hello_client, preferencesHelper?.clientName) + hideProgress() + } else { + presenter?.userDetails + } + presenter?.userImage + presenter?.unreadNotificationsCount + } + + /** + * Opens [ClientAccountsFragment] according to the `accountType` provided + * + * @param accountType Enum of [AccountType] + */ + private fun openAccount(accountType: AccountType?) { + (activity as BaseActivity?)?.replaceFragment( + ClientAccountsFragment.newInstance(accountType), true, R.id.container) + } + + /** + * Fetches Client details and display clientName + * + * @param userName of the client + */ + override fun showUserDetails(userName: String?) { + tvUserName?.text = getString(R.string.hello_client, userName) + } + + override fun showUserImageTextDrawable() { + activity?.runOnUiThread { + val userName: String? = if (preferencesHelper?.clientName?.isNotEmpty() == true) { + preferencesHelper?.clientName + } else { + getString(R.string.app_name) + } + val drawable = TextDrawable.builder() + .beginConfig() + .toUpperCase() + .endConfig() + .buildRound(userName?.substring(0, 1), + ContextCompat.getColor(activity!!, R.color.primary_dark)) + ivUserImage?.setImageDrawable(drawable) + ivUserImage?.visibility = View.VISIBLE + ivCircularUserImage?.visibility = View.GONE + } + } + + /** + * Provides with Client image fetched from server + * + * @param bitmap Client Image + */ + override fun showUserImage(bitmap: Bitmap?) { + if (bitmap != null) { + activity?.runOnUiThread { + userProfileBitmap = bitmap + ivCircularUserImage?.setImageBitmap(bitmap) + ivCircularUserImage?.visibility = View.VISIBLE + ivUserImage?.visibility = View.GONE + } + } + } + + override fun showNotificationCount(count: Int) { + if (count > 0) { + tvNotificationCount?.text = count.toString() + } else { + tvNotificationCount?.visibility = View.GONE + } + } + + @OnClick(R.id.iv_user_image) + fun userImageClicked() { + startActivity(Intent(activity, UserProfileActivity::class.java)) + } + + @OnClick(R.id.iv_circular_user_image) + fun userCircularImageClick() { + startActivity(Intent(activity, UserProfileActivity::class.java)) + } + + /** + * Calls for opening Account Overview + */ + @OnClick(R.id.ll_account_overview) + fun onAccountOverview() { + startActivity(Intent(activity, AccountOverviewActivity::class.java)) + } + + /** + * Calls `openAccount()` for opening [ClientAccountsFragment] + */ + @OnClick(R.id.ll_accounts) + fun accountsClicked() { + openAccount(AccountType.SAVINGS) + (activity as HomeActivity?)?.setNavigationViewSelectedItem(R.id.item_accounts) + } + + /** + * Shows a dialog with options: Normal Transfer and Third Party Transfer + */ + @OnClick(R.id.ll_transfer) + fun transferClicked() { + val transferTypes = arrayOf(getString(R.string.transfer), getString(R.string.third_party_transfer)) + MaterialDialog.Builder().init(activity) + .setTitle(R.string.choose_transfer_type) + .setItems(transferTypes, + DialogInterface.OnClickListener { _, which -> + if (which == 0) { + (activity as HomeActivity?)?.replaceFragment( + SavingsMakeTransferFragment.newInstance(1, ""), true, + R.id.container) + } else { + (activity as HomeActivity?)?.replaceFragment( + ThirdPartyTransferFragment.newInstance(), true, R.id.container) + } + }) + .createMaterialDialog() + .show() + } + + /** + * Opens [ClientChargeFragment] to display all Charges associated with client's account + */ + @OnClick(R.id.ll_charges) + fun chargesClicked() { + (activity as HomeActivity?)?.replaceFragment(ClientChargeFragment.newInstance(clientId, + ChargeType.CLIENT), true, R.id.container) + } + + /** + * Opens [LoanApplicationFragment] to apply for a loan + */ + @OnClick(R.id.ll_apply_for_loan) + fun applyForLoan() { + startActivity(Intent(activity, LoanApplicationActivity::class.java)) + } + + /** + * Opens [BeneficiaryListFragment] which contains list of Beneficiaries associated with + * Client's account + */ + @OnClick(R.id.ll_beneficiaries) + fun beneficiaries() { + (activity as HomeActivity?)?.replaceFragment(BeneficiaryListFragment.newInstance(), true, R.id.container) + } + + @OnClick(R.id.ll_surveys) + fun surveys() { + } + + @OnClick(R.id.ll_recent_transactions) + fun showRecentTransactions() { + (activity as HomeActivity?)?.replaceFragment(RecentTransactionsFragment.newInstance(), + true, R.id.container) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param errorMessage Error message that tells the user about the problem. + */ + override fun showError(errorMessage: String?) { + Toaster.show(rootView, errorMessage) + } + + override fun showUserImageNotFound() { + showUserImageTextDrawable() + } + + /** + * Shows [SwipeRefreshLayout] + */ + override fun showProgress() { + slHomeContainer?.isRefreshing = true + } + + /** + * Hides [SwipeRefreshLayout] + */ + override fun hideProgress() { + slHomeContainer?.isRefreshing = false + } + + override fun onDestroyView() { + super.onDestroyView() + presenter?.detachView() + if (slHomeContainer?.isRefreshing == true) + slHomeContainer?.isRefreshing = false + slHomeContainer?.removeAllViews() + } + + private val notificationReceiver: BroadcastReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + activity?.invalidateOptionsMenu() + } + } + + companion object { + val LOG_TAG: String? = HomeFragment::class.java.simpleName + fun newInstance(): HomeFragment { + val fragment = HomeFragment() + val args = Bundle() + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/HomeOldFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/HomeOldFragment.java deleted file mode 100644 index d130dc3a29..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/HomeOldFragment.java +++ /dev/null @@ -1,488 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.animation.LayoutTransition; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.Bitmap; -import android.os.Build; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.presenters.HomeOldPresenter; -import org.mifos.mobile.ui.activities.HomeActivity; -import org.mifos.mobile.ui.activities.LoanApplicationActivity; -import org.mifos.mobile.ui.activities.NotificationActivity; -import org.mifos.mobile.ui.activities.UserProfileActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.AccountType; -import org.mifos.mobile.ui.enums.ChargeType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.HomeOldView; -import org.mifos.mobile.utils.CircularImageView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.TextDrawable; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.core.content.ContextCompat; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by michaelsosnick on 1/1/17. - */ - -public class HomeOldFragment extends BaseFragment implements HomeOldView, - SwipeRefreshLayout.OnRefreshListener { - - public static final String LOG_TAG = HomeFragment.class.getSimpleName(); - - @BindView(R.id.tv_saving_total_amount) - TextView tvSavingTotalAmount; - - @BindView(R.id.tv_loan_total_amount) - TextView tvLoanTotalAmount; - - @BindView(R.id.ll_account_detail) - LinearLayout llAccountDetail; - - @BindView(R.id.iv_visibility) - ImageView ivVisibility; - - @BindView(R.id.iv_user_image) - ImageView ivUserImage; - - @BindView(R.id.iv_circular_user_image) - CircularImageView ivCircularUserImage; - - @BindView(R.id.tv_user_name) - TextView tvUserName; - - @BindView(R.id.swipe_home_container) - SwipeRefreshLayout slHomeContainer; - - @BindView(R.id.ll_container) - LinearLayout llContainer; - - @Inject - HomeOldPresenter presenter; - - @Inject - PreferencesHelper preferencesHelper; - - View rootView; - private double totalLoanAmount, totalSavingAmount; - private Client client; - private long clientId; - private View toolbarView; - private boolean isDetailVisible; - private boolean isReceiverRegistered = false; - private TextView tvNotificationCount; - - public static HomeOldFragment newInstance() { - HomeOldFragment fragment = new HomeOldFragment(); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_home_old, container, false); - ((HomeActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - clientId = preferencesHelper.getClientId(); - - presenter.attachView(this); - setHasOptionsMenu(true); - - slHomeContainer.setColorSchemeResources(R.color.blue_light, R.color.green_light, R - .color.orange_light, R.color.red_light); - slHomeContainer.setOnRefreshListener(this); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - llContainer.getLayoutTransition() - .enableTransitionType(LayoutTransition.CHANGING); - } - if (savedInstanceState == null) { - loadClientData(); - } - - setToolbarTitle(getString(R.string.home)); - showUserInterface(); - return rootView; - } - - private BroadcastReceiver notificationReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - getActivity().invalidateOptionsMenu(); - } - }; - - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_main, menu); - MenuItem menuItem = menu.findItem(R.id.menu_notifications); - View count = menuItem.getActionView(); - tvNotificationCount = count.findViewById(R.id.tv_notification_indicator); - presenter.getUnreadNotificationsCount(); - count.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - - startActivity(new Intent(getContext(), NotificationActivity.class)); - } - }); - super.onCreateOptionsMenu(menu, inflater); - } - - @Override - public void onResume() { - super.onResume(); - registerReceiver(); - getActivity().invalidateOptionsMenu(); - } - - @Override - public void onPause() { - LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(notificationReceiver); - isReceiverRegistered = false; - super.onPause(); - } - - private void registerReceiver() { - if (!isReceiverRegistered) { - LocalBroadcastManager.getInstance(getActivity()).registerReceiver(notificationReceiver, - new IntentFilter(Constants.NOTIFY_HOME_FRAGMENT)); - isReceiverRegistered = true; - } - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putDouble(Constants.TOTAL_LOAN, totalLoanAmount); - outState.putDouble(Constants.TOTAL_SAVINGS, totalSavingAmount); - outState.putParcelable(Constants.USER_DETAILS, client); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showUserDetails((Client) savedInstanceState.getParcelable(Constants.USER_DETAILS)); - presenter.setUserProfile(preferencesHelper.getUserProfileImage()); - showLoanAccountDetails(savedInstanceState.getDouble(Constants.TOTAL_LOAN)); - showSavingAccountDetails(savedInstanceState.getDouble(Constants.TOTAL_SAVINGS)); - } - } - - @Override - public void onRefresh() { - loadClientData(); - } - - private void loadClientData() { - presenter.loadClientAccountDetails(); - presenter.getUserDetails(); - presenter.getUserImage(); - } - - @Override - public void showUserInterface() { - toolbarView = ((HomeActivity) getActivity()).getToolbar().getRootView(); - isDetailVisible = preferencesHelper.overviewState(); - if (isDetailVisible) { - showOverviewState(); - } else { - hideOverviewState(); - } - } - - /** - * Opens {@link ClientAccountsFragment} according to the {@code accountType} provided - * - * @param accountType Enum of {@link AccountType} - */ - public void openAccount(AccountType accountType) { - ((BaseActivity) getActivity()).replaceFragment( - ClientAccountsFragment.newInstance(accountType), true, R.id.container); - } - - /** - * Provides {@code totalLoanAmount} fetched from server - * - * @param totalLoanAmount Total Loan amount - */ - @Override - public void showLoanAccountDetails(double totalLoanAmount) { - this.totalLoanAmount = totalLoanAmount; - tvLoanTotalAmount.setText(CurrencyUtil.formatCurrency(getContext(), totalLoanAmount)); - } - - /** - * Open LOAN tab under ClientAccountsFragment - */ - @OnClick(R.id.ll_total_loan) - public void onClickLoan() { - openAccount(AccountType.LOAN); - ((HomeActivity) getActivity()).setNavigationViewSelectedItem(R.id.item_accounts); - } - - /** - * Provides {@code totalSavingAmount} fetched from server - * - * @param totalSavingAmount Total Saving amount - */ - @Override - public void showSavingAccountDetails(double totalSavingAmount) { - this.totalSavingAmount = totalSavingAmount; - tvSavingTotalAmount.setText(CurrencyUtil.formatCurrency(getContext(), totalSavingAmount)); - } - - /** - * Open SAVINGS tab under ClientAccountsFragment - */ - @OnClick(R.id.ll_total_savings) - public void onClickSavings() { - openAccount(AccountType.SAVINGS); - ((HomeActivity) getActivity()).setNavigationViewSelectedItem(R.id.item_accounts); - } - - /** - * Fetches Client details and display clientName - * - * @param client Details about client - */ - @Override - public void showUserDetails(Client client) { - this.client = client; - tvUserName.setText(getString(R.string.hello_client, client.getDisplayName())); - } - - /** - * Provides with Client image fetched from server - * - * @param bitmap Client Image - */ - @Override - public void showUserImage(final Bitmap bitmap) { - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - if (bitmap != null) { - - ivUserImage.setVisibility(View.GONE); - ivCircularUserImage.setVisibility(View.VISIBLE); - ivCircularUserImage.setImageBitmap(bitmap); - - } else { - - String userName; - if (!preferencesHelper.getClientName().isEmpty()) { - - userName = preferencesHelper.getClientName(); - } else { - - userName = getString(R.string.app_name); - } - TextDrawable drawable = TextDrawable.builder() - .beginConfig() - .toUpperCase() - .endConfig() - .buildRound(userName.substring(0, 1), - ContextCompat.getColor( - getContext(), R.color.primary)); - ivUserImage.setVisibility(View.VISIBLE); - ivUserImage.setImageDrawable(drawable); - ivCircularUserImage.setVisibility(View.GONE); - - } - } - }); - } - - @Override - public void showNotificationCount(int count) { - - if (count > 0) { - tvNotificationCount.setVisibility(View.VISIBLE); - tvNotificationCount.setText(String.valueOf(count)); - } else { - tvNotificationCount.setVisibility(View.GONE); - } - } - - @OnClick({R.id.iv_user_image, R.id.iv_circular_user_image}) - public void userImageClicked() { - startActivity(new Intent(getActivity(), UserProfileActivity.class)); - } - - /** - * Reverses the state of Account Overview section i.e. visible to hidden or vice a versa - */ - @OnClick(R.id.iv_visibility) - public void reverseDetailState() { - if (isDetailVisible) { - isDetailVisible = false; - preferencesHelper.setOverviewState(false); - hideOverviewState(); - } else { - isDetailVisible = true; - preferencesHelper.setOverviewState(true); - showOverviewState(); - } - } - - /** - * Makes Overview state visible - */ - private void showOverviewState() { - ivVisibility.setImageDrawable(getResources().getDrawable(R.drawable.ic_visibility_24px)); - ivVisibility.setColorFilter(ContextCompat.getColor(getActivity(), R.color.gray_dark)); - llAccountDetail.setVisibility(View.VISIBLE); - } - - /** - * Hides Overview state - */ - private void hideOverviewState() { - ivVisibility.setImageDrawable(getResources() - .getDrawable(R.drawable.ic_visibility_off_24px)); - ivVisibility.setColorFilter(ContextCompat.getColor(getActivity(), R.color.light_grey)); - llAccountDetail.setVisibility(View.GONE); - } - - - /** - * Calls {@code openAccount()} for opening {@link ClientAccountsFragment} - */ - @OnClick(R.id.ll_accounts) - public void accountsClicked() { - openAccount(AccountType.SAVINGS); - ((HomeActivity) getActivity()).setNavigationViewSelectedItem(R.id.item_accounts); - } - - /** - * Shows a dialog with options: Normal Transfer and Third Party Transfer - */ - @OnClick(R.id.ll_transfer) - public void transferClicked() { - String[] transferTypes = {getString(R.string.transfer), getString(R.string. - third_party_transfer)}; - new MaterialDialog.Builder().init(getActivity()) - .setTitle(R.string.choose_transfer_type) - .setItems(transferTypes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == 0) { - ((HomeActivity) getActivity()).replaceFragment( - SavingsMakeTransferFragment.newInstance(1, ""), true, - R.id.container); - } else { - ((HomeActivity) getActivity()).replaceFragment( - ThirdPartyTransferFragment.newInstance(), true, R.id.container); - } - } - }) - .createMaterialDialog() - .show(); - } - - /** - * Opens {@link ClientChargeFragment} to display all Charges associated with client's account - */ - @OnClick(R.id.ll_charges) - public void chargesClicked() { - ((HomeActivity) getActivity()).replaceFragment(ClientChargeFragment.newInstance(clientId, - ChargeType.CLIENT), true, R.id.container); - } - - /** - * Opens {@link LoanApplicationFragment} to apply for a loan - */ - @OnClick(R.id.ll_apply_for_loan) - public void applyForLoan() { - startActivity(new Intent(getActivity(), LoanApplicationActivity.class)); - } - - /** - * Opens {@link BeneficiaryListFragment} which contains list of Beneficiaries associated with - * Client's account - */ - @OnClick(R.id.ll_beneficiaries) - public void beneficiaries() { - ((HomeActivity) getActivity()).replaceFragment(BeneficiaryListFragment. - newInstance(), true, R.id.container); - } - - @OnClick(R.id.ll_surveys) - public void surveys() { - - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param errorMessage Error message that tells the user about the problem. - */ - @Override - public void showError(String errorMessage) { - int checkedItem = ((HomeActivity) getActivity()).getCheckedItem(); - if (checkedItem == R.id.item_about_us || checkedItem == R.id.item_help || - checkedItem == R.id.item_settings) { - return; - } - Toaster.show(rootView, errorMessage); - } - - /** - * Shows {@link SwipeRefreshLayout} - */ - @Override - public void showProgress() { - slHomeContainer.setRefreshing(true); - } - - /** - * Hides {@link SwipeRefreshLayout} - */ - @Override - public void hideProgress() { - slHomeContainer.setRefreshing(false); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (slHomeContainer.isRefreshing()) { - slHomeContainer.setRefreshing(false); - slHomeContainer.removeAllViews(); - } - presenter.detachView(); - } - -} - diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/HomeOldFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/HomeOldFragment.kt new file mode 100644 index 0000000000..a07fa3a852 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/HomeOldFragment.kt @@ -0,0 +1,438 @@ + +package org.mifos.mobile.ui.fragments + +import android.animation.LayoutTransition +import android.content.* +import android.graphics.Bitmap +import android.os.Build +import android.os.Bundle +import android.os.Parcelable +import android.view.* +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView + +import androidx.core.content.ContextCompat +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.presenters.HomeOldPresenter +import org.mifos.mobile.ui.activities.HomeActivity +import org.mifos.mobile.ui.activities.LoanApplicationActivity +import org.mifos.mobile.ui.activities.NotificationActivity +import org.mifos.mobile.ui.activities.UserProfileActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.AccountType +import org.mifos.mobile.ui.enums.ChargeType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.HomeOldView +import org.mifos.mobile.utils.* + +import javax.inject.Inject + +/** + * Created by michaelsosnick on 1/1/17. + */ +class HomeOldFragment : BaseFragment(), HomeOldView, OnRefreshListener { + @kotlin.jvm.JvmField + @BindView(R.id.tv_saving_total_amount) + var tvSavingTotalAmount: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_loan_total_amount) + var tvLoanTotalAmount: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_account_detail) + var llAccountDetail: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_visibility) + var ivVisibility: ImageView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_user_image) + var ivUserImage: ImageView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_circular_user_image) + var ivCircularUserImage: CircularImageView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_user_name) + var tvUserName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.swipe_home_container) + var slHomeContainer: SwipeRefreshLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_container) + var llContainer: LinearLayout? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: HomeOldPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + var rootView: View? = null + private var totalLoanAmount = 0.0 + private var totalSavingAmount = 0.0 + private var client: Client? = null + private var clientId: Long? = 0 + private var toolbarView: View? = null + private var isDetailVisible: Boolean? = false + private var isReceiverRegistered = false + private var tvNotificationCount: TextView? = null + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_home_old, container, false) + (activity as HomeActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + clientId = preferencesHelper?.clientId + presenter?.attachView(this) + setHasOptionsMenu(true) + slHomeContainer?.setColorSchemeResources(R.color.blue_light, R.color.green_light, R.color.orange_light, R.color.red_light) + slHomeContainer?.setOnRefreshListener(this) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + llContainer?.layoutTransition + ?.enableTransitionType(LayoutTransition.CHANGING) + } + if (savedInstanceState == null) { + loadClientData() + } + setToolbarTitle(getString(R.string.home)) + showUserInterface() + return rootView + } + + private val notificationReceiver: BroadcastReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + activity?.invalidateOptionsMenu() + } + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + inflater.inflate(R.menu.menu_main, menu) + val menuItem = menu.findItem(R.id.menu_notifications) + val count = menuItem.actionView + tvNotificationCount = count.findViewById(R.id.tv_notification_indicator) + presenter?.unreadNotificationsCount + count.setOnClickListener { startActivity(Intent(context, NotificationActivity::class.java)) } + super.onCreateOptionsMenu(menu, inflater) + } + + override fun onResume() { + super.onResume() + registerReceiver() + activity?.invalidateOptionsMenu() + } + + override fun onPause() { + LocalBroadcastManager.getInstance(activity!!).unregisterReceiver(notificationReceiver) + isReceiverRegistered = false + super.onPause() + } + + private fun registerReceiver() { + if (!isReceiverRegistered) { + LocalBroadcastManager.getInstance(activity!!).registerReceiver(notificationReceiver, + IntentFilter(Constants.NOTIFY_HOME_FRAGMENT)) + isReceiverRegistered = true + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putDouble(Constants.TOTAL_LOAN, totalLoanAmount) + outState.putDouble(Constants.TOTAL_SAVINGS, totalSavingAmount) + outState.putParcelable(Constants.USER_DETAILS, client) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showUserDetails(savedInstanceState.getParcelable(Constants.USER_DETAILS) as Client) + presenter?.setUserProfile(preferencesHelper?.userProfileImage) + showLoanAccountDetails(savedInstanceState.getDouble(Constants.TOTAL_LOAN)) + showSavingAccountDetails(savedInstanceState.getDouble(Constants.TOTAL_SAVINGS)) + } + } + + override fun onRefresh() { + loadClientData() + } + + private fun loadClientData() { + presenter?.loadClientAccountDetails() + presenter?.userDetails + presenter?.userImage + } + + override fun showUserInterface() { + toolbarView = (activity as HomeActivity?)?.toolbar?.rootView + isDetailVisible = preferencesHelper?.overviewState() + if (isDetailVisible == true) { + showOverviewState() + } else { + hideOverviewState() + } + } + + /** + * Opens [ClientAccountsFragment] according to the `accountType` provided + * + * @param accountType Enum of [AccountType] + */ + fun openAccount(accountType: AccountType?) { + (activity as BaseActivity?)?.replaceFragment( + ClientAccountsFragment.newInstance(accountType), true, R.id.container) + } + + /** + * Provides `totalLoanAmount` fetched from server + * + * @param totalLoanAmount Total Loan amount + */ + override fun showLoanAccountDetails(totalLoanAmount: Double) { + this.totalLoanAmount = totalLoanAmount + tvLoanTotalAmount?.text = CurrencyUtil.formatCurrency(context, totalLoanAmount) + } + + /** + * Open LOAN tab under ClientAccountsFragment + */ + @OnClick(R.id.ll_total_loan) + fun onClickLoan() { + openAccount(AccountType.LOAN) + (activity as HomeActivity?)?.setNavigationViewSelectedItem(R.id.item_accounts) + } + + /** + * Provides `totalSavingAmount` fetched from server + * + * @param totalSavingAmount Total Saving amount + */ + override fun showSavingAccountDetails(totalSavingAmount: Double) { + this.totalSavingAmount = totalSavingAmount + tvSavingTotalAmount?.text = CurrencyUtil.formatCurrency(context, totalSavingAmount) + } + + /** + * Open SAVINGS tab under ClientAccountsFragment + */ + @OnClick(R.id.ll_total_savings) + fun onClickSavings() { + openAccount(AccountType.SAVINGS) + (activity as HomeActivity?)?.setNavigationViewSelectedItem(R.id.item_accounts) + } + + /** + * Fetches Client details and display clientName + * + * @param client Details about client + */ + override fun showUserDetails(client: Client?) { + this.client = client + tvUserName?.text = getString(R.string.hello_client, client?.displayName) + } + + /** + * Provides with Client image fetched from server + * + * @param bitmap Client Image + */ + override fun showUserImage(bitmap: Bitmap?) { + activity?.runOnUiThread { + if (bitmap != null) { + ivUserImage?.visibility = View.GONE + ivCircularUserImage?.visibility = View.VISIBLE + ivCircularUserImage?.setImageBitmap(bitmap) + } else { + val userName: String = (if (preferencesHelper?.clientName?.isNotEmpty() == true) { + preferencesHelper?.clientName + } else { + getString(R.string.app_name) + }) as String + + val drawable = TextDrawable.builder() + .beginConfig() + .toUpperCase() + .endConfig() + .buildRound(userName.substring(0, 1), + ContextCompat.getColor( + context!!, R.color.primary)) + ivUserImage?.visibility = View.VISIBLE + ivUserImage?.setImageDrawable(drawable) + ivCircularUserImage?.visibility = View.GONE + } + } + } + + override fun showNotificationCount(count: Int) { + if (count > 0) { + tvNotificationCount?.visibility = View.VISIBLE + tvNotificationCount?.text = count.toString() + } else { + tvNotificationCount?.visibility = View.GONE + } + } + + @OnClick(R.id.iv_user_image, R.id.iv_circular_user_image) + fun userImageClicked() { + startActivity(Intent(activity, UserProfileActivity::class.java)) + } + + /** + * Reverses the state of Account Overview section i.e. visible to hidden or vice a versa + */ + @OnClick(R.id.iv_visibility) + fun reverseDetailState() { + if (isDetailVisible == true) { + isDetailVisible = false + preferencesHelper?.setOverviewState(false) + hideOverviewState() + } else { + isDetailVisible = true + preferencesHelper?.setOverviewState(true) + showOverviewState() + } + } + + /** + * Makes Overview state visible + */ + private fun showOverviewState() { + ivVisibility?.setImageDrawable(resources.getDrawable(R.drawable.ic_visibility_24px)) + ivVisibility?.setColorFilter(ContextCompat.getColor(activity?.applicationContext!!, R.color.gray_dark)) + llAccountDetail?.visibility = View.VISIBLE + } + + /** + * Hides Overview state + */ + private fun hideOverviewState() { + ivVisibility?.setImageDrawable(resources + .getDrawable(R.drawable.ic_visibility_off_24px)) + ivVisibility?.setColorFilter(ContextCompat.getColor(activity?.applicationContext!!, R.color.light_grey)) + llAccountDetail?.visibility = View.GONE + } + + /** + * Calls `openAccount()` for opening [ClientAccountsFragment] + */ + @OnClick(R.id.ll_accounts) + fun accountsClicked() { + openAccount(AccountType.SAVINGS) + (activity as HomeActivity?)?.setNavigationViewSelectedItem(R.id.item_accounts) + } + + /** + * Shows a dialog with options: Normal Transfer and Third Party Transfer + */ + @OnClick(R.id.ll_transfer) + fun transferClicked() { + val transferTypes = arrayOf(getString(R.string.transfer), getString(R.string.third_party_transfer)) + MaterialDialog.Builder().init(activity) + .setTitle(R.string.choose_transfer_type) + .setItems(transferTypes, + DialogInterface.OnClickListener { _, which -> + if (which == 0) { + (activity as HomeActivity?)?.replaceFragment( + SavingsMakeTransferFragment.newInstance(1, ""), true, + R.id.container) + } else { + (activity as HomeActivity?)?.replaceFragment( + ThirdPartyTransferFragment.newInstance(), true, R.id.container) + } + }) + .createMaterialDialog() + .show() + } + + /** + * Opens [ClientChargeFragment] to display all Charges associated with client's account + */ + @OnClick(R.id.ll_charges) + fun chargesClicked() { + (activity as HomeActivity?)?.replaceFragment(ClientChargeFragment.newInstance(clientId, + ChargeType.CLIENT), true, R.id.container) + } + + /** + * Opens [LoanApplicationFragment] to apply for a loan + */ + @OnClick(R.id.ll_apply_for_loan) + fun applyForLoan() { + startActivity(Intent(activity, LoanApplicationActivity::class.java)) + } + + /** + * Opens [BeneficiaryListFragment] which contains list of Beneficiaries associated with + * Client's account + */ + @OnClick(R.id.ll_beneficiaries) + fun beneficiaries() { + (activity as HomeActivity?)?.replaceFragment(BeneficiaryListFragment.newInstance(), true, R.id.container) + } + + @OnClick(R.id.ll_surveys) + fun surveys() { + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param errorMessage Error message that tells the user about the problem. + */ + override fun showError(errorMessage: String?) { + val checkedItem = (activity as HomeActivity?)?.checkedItem + if (checkedItem == R.id.item_about_us || checkedItem == R.id.item_help || checkedItem == R.id.item_settings) { + return + } + Toaster.show(rootView, errorMessage) + } + + /** + * Shows [SwipeRefreshLayout] + */ + override fun showProgress() { + slHomeContainer?.isRefreshing = true + } + + /** + * Hides [SwipeRefreshLayout] + */ + override fun hideProgress() { + slHomeContainer?.isRefreshing = false + } + + override fun onDestroyView() { + super.onDestroyView() + if (slHomeContainer?.isRefreshing == true) { + slHomeContainer?.isRefreshing = false + slHomeContainer?.removeAllViews() + } + presenter?.detachView() + } + + companion object { + val LOG_TAG: String? = HomeFragment::class.java.simpleName + fun newInstance(): HomeOldFragment { + return HomeOldFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountSummaryFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountSummaryFragment.java deleted file mode 100644 index fd19b0a9d6..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountSummaryFragment.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.CurrencyUtil; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 25/2/17. - */ - -public class LoanAccountSummaryFragment extends BaseFragment { - - @BindView(R.id.tv_loan_product_name) - TextView tvLoanProductName; - - @BindView(R.id.tv_principal) - TextView tvPrincipalName; - - @BindView(R.id.tv_interest_charged) - TextView tvInterestChargedName; - - @BindView(R.id.tv_fees) - TextView tvFeesName; - - @BindView(R.id.tv_penalties) - TextView tvPenaltiesName; - - @BindView(R.id.tv_total_repayment) - TextView tvTotalRepaymentName; - - @BindView(R.id.tv_total_paid) - TextView tvTotalPaidName; - - @BindView(R.id.tv_interest_waived) - TextView tvInterestWaivedName; - - @BindView(R.id.tv_penalties_waived) - TextView tvPenaltiesWaivedName; - - @BindView(R.id.tv_fees_waived) - TextView tvFeesWaivedName; - - @BindView(R.id.tv_outstanding_balance) - TextView tvOutstandingBalanceName; - - @BindView(R.id.ll_error) - View layoutError; - - @BindView(R.id.tv_account_status) - TextView tvAccountStatus; - - @BindView(R.id.tv_status) - TextView tvStatus; - - @BindView(R.id.ll_loan_summary) - LinearLayout llLoanSummary; - - @BindView(R.id.ll_loan_purpose) - LinearLayout llLoanPurpose; - - @BindView(R.id.tv_loan_account_number) - TextView tvLoanAccountNumber; - - @BindView(R.id.tv_loan_purpose) - TextView tvLoanPurpose; - - @BindView(R.id.iv_account_status) - ImageView ivAccountStatus; - - private LoanWithAssociations loanWithAssociations; - - private View rootView; - - public static LoanAccountSummaryFragment newInstance( - LoanWithAssociations loanWithAssociations) { - LoanAccountSummaryFragment loanAccountSummaryFragment = - new LoanAccountSummaryFragment(); - Bundle args = new Bundle(); - args.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations); - loanAccountSummaryFragment.setArguments(args); - return loanAccountSummaryFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - if (getArguments() != null) { - loanWithAssociations = getArguments().getParcelable(Constants.LOAN_ACCOUNT); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_loan_account_summary, container, false); - setToolbarTitle(getString(R.string.loan_summary)); - - ButterKnife.bind(this, rootView); - - showLoanAccountsDetail(loanWithAssociations); - - return rootView; - } - - /** - * Sets basic information about a Loan Account - * - * @param loanWithAssociations object containing details of each loan account, - */ - public void showLoanAccountsDetail(LoanWithAssociations loanWithAssociations) { - llLoanSummary.setVisibility(View.VISIBLE); - String currencySymbol = loanWithAssociations.getCurrency().getDisplaySymbol(); - if (currencySymbol == null) { - currencySymbol = loanWithAssociations.getCurrency().getCode(); - } - tvLoanProductName.setText(loanWithAssociations.getLoanProductName()); - tvPrincipalName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getPrincipal())); - tvInterestChargedName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getInterestCharged())); - tvFeesName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getFeeChargesCharged())); - tvPenaltiesName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getPenaltyChargesCharged())); - tvTotalRepaymentName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getTotalExpectedRepayment())); - tvTotalPaidName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getTotalRepayment())); - tvInterestWaivedName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getInterestWaived())); - tvPenaltiesWaivedName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getPenaltyChargesWaived())); - tvFeesWaivedName.setText(getString(R.string.string_and_double, - currencySymbol, - loanWithAssociations.getSummary().getFeeChargesWaived())); - tvOutstandingBalanceName.setText(getResources().getString(R.string.string_and_string, - currencySymbol, CurrencyUtil.formatCurrency(getActivity(), - loanWithAssociations.getSummary().getTotalOutstanding()))); - tvLoanAccountNumber.setText(loanWithAssociations.getAccountNo()); - if (loanWithAssociations.getLoanPurposeName() != null) { - llLoanPurpose.setVisibility(View.VISIBLE); - tvLoanPurpose.setText(loanWithAssociations.getLoanPurposeName()); - } - if (loanWithAssociations.getStatus().getActive()) { - tvAccountStatus.setText(R.string.active_uc); - ivAccountStatus.setImageResource(R.drawable.ic_check_circle_green_24px - ); - } else { - tvAccountStatus.setText(R.string.inactive_uc); - ivAccountStatus.setImageResource(R.drawable.ic_report_problem_red_24px); - } - - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgressBar(); - } - - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountSummaryFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountSummaryFragment.kt new file mode 100644 index 0000000000..23d6234f13 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountSummaryFragment.kt @@ -0,0 +1,192 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import butterknife.BindView +import butterknife.ButterKnife +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.CurrencyUtil + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ /** + * Created by dilpreet on 25/2/17. + */ +class LoanAccountSummaryFragment : BaseFragment() { + @kotlin.jvm.JvmField + @BindView(R.id.tv_loan_product_name) + var tvLoanProductName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_principal) + var tvPrincipalName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_interest_charged) + var tvInterestChargedName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_fees) + var tvFeesName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_penalties) + var tvPenaltiesName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_total_repayment) + var tvTotalRepaymentName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_total_paid) + var tvTotalPaidName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_interest_waived) + var tvInterestWaivedName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_penalties_waived) + var tvPenaltiesWaivedName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_fees_waived) + var tvFeesWaivedName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_outstanding_balance) + var tvOutstandingBalanceName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_status) + var tvAccountStatus: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_status) + var tvStatus: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_loan_summary) + var llLoanSummary: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_loan_purpose) + var llLoanPurpose: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_loan_account_number) + var tvLoanAccountNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_loan_purpose) + var tvLoanPurpose: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_account_status) + var ivAccountStatus: ImageView? = null + private var loanWithAssociations: LoanWithAssociations? = null + private var rootView: View? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + if (arguments != null) { + loanWithAssociations = arguments?.getParcelable(Constants.LOAN_ACCOUNT) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_loan_account_summary, container, false) + setToolbarTitle(getString(R.string.loan_summary)) + ButterKnife.bind(this, rootView!!) + showLoanAccountsDetail(loanWithAssociations) + return rootView + } + + /** + * Sets basic information about a Loan Account + * + * @param loanWithAssociations object containing details of each loan account, + */ + fun showLoanAccountsDetail(loanWithAssociations: LoanWithAssociations?) { + llLoanSummary?.visibility = View.VISIBLE + var currencySymbol = loanWithAssociations?.currency?.displaySymbol + if (currencySymbol == null) { + currencySymbol = loanWithAssociations?.currency?.code + } + tvLoanProductName?.text = loanWithAssociations?.loanProductName + tvPrincipalName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.principal) + tvInterestChargedName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.interestCharged) + tvFeesName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.feeChargesCharged) + tvPenaltiesName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.penaltyChargesCharged) + tvTotalRepaymentName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.totalExpectedRepayment) + tvTotalPaidName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.totalRepayment) + tvInterestWaivedName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.interestWaived) + tvPenaltiesWaivedName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.penaltyChargesWaived) + tvFeesWaivedName?.text = getString(R.string.string_and_double, + currencySymbol, + loanWithAssociations?.summary?.feeChargesWaived) + tvOutstandingBalanceName?.text = resources.getString(R.string.string_and_string, + currencySymbol, CurrencyUtil.formatCurrency(activity, + loanWithAssociations?.summary?.totalOutstanding)) + tvLoanAccountNumber?.text = loanWithAssociations?.accountNo + if (loanWithAssociations?.loanPurposeName != null) { + llLoanPurpose?.visibility = View.VISIBLE + tvLoanPurpose?.text = loanWithAssociations.loanPurposeName + } + if (loanWithAssociations?.status?.active == true) { + tvAccountStatus?.setText(R.string.active_uc) + ivAccountStatus?.setImageResource(R.drawable.ic_check_circle_green_24px + ) + } else { + tvAccountStatus?.setText(R.string.inactive_uc) + ivAccountStatus?.setImageResource(R.drawable.ic_report_problem_red_24px) + } + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgressBar() + } + + companion object { + fun newInstance( + loanWithAssociations: LoanWithAssociations?): LoanAccountSummaryFragment { + val loanAccountSummaryFragment = LoanAccountSummaryFragment() + val args = Bundle() + args.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations) + loanAccountSummaryFragment.arguments = args + return loanAccountSummaryFragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountTransactionFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountTransactionFragment.java deleted file mode 100644 index b0060f3c1a..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountTransactionFragment.java +++ /dev/null @@ -1,195 +0,0 @@ -package org.mifos.mobile.ui.fragments; -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.presenters.LoanAccountsTransactionPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.RecentTransactionListAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.LoanAccountsTransactionView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.Network; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 4/3/17. - */ - -public class LoanAccountTransactionFragment extends BaseFragment - implements LoanAccountsTransactionView { - - @BindView(R.id.layout_error) - View layoutError; - - @BindView(R.id.ll_loan_account_trans) - LinearLayout llLoanAccountTrans; - - @BindView(R.id.tv_loan_product_name) - TextView tvLoanProductName; - - @BindView(R.id.rv_loan_transactions) - RecyclerView rvLoanTransactions; - - @Inject - RecentTransactionListAdapter transactionsListAdapter; - - @Inject - LoanAccountsTransactionPresenter loanAccountsTransactionPresenter; - - private long loanId; - private View rootView; - private LoanWithAssociations loanWithAssociations; - private SweetUIErrorHandler sweetUIErrorHandler; - - public static LoanAccountTransactionFragment newInstance(long loanId) { - LoanAccountTransactionFragment fragment = new LoanAccountTransactionFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.LOAN_ID, loanId); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - if (getArguments() != null) { - loanId = getArguments().getLong(Constants.LOAN_ID); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - - rootView = inflater.inflate(R.layout.fragment_loan_account_transactions, container, false); - setToolbarTitle(getString(R.string.transactions)); - - ButterKnife.bind(this, rootView); - loanAccountsTransactionPresenter.attachView(this); - - sweetUIErrorHandler = new SweetUIErrorHandler(getContext(), rootView); - showUserInterface(); - if (savedInstanceState == null) { - loanAccountsTransactionPresenter.loadLoanAccountDetails(loanId); - } - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showLoanTransactions((LoanWithAssociations) savedInstanceState. - getParcelable(Constants.LOAN_ACCOUNT)); - } - } - - /** - * Initialized {@link RecyclerView} {@code rvLoanTransactions} - */ - @Override - public void showUserInterface() { - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - rvLoanTransactions.setHasFixedSize(true); - rvLoanTransactions.setLayoutManager(layoutManager); - rvLoanTransactions.setAdapter(transactionsListAdapter); - } - - /** - * Fetches {@code loanWithAssociations} from server and intializes it in - * {@code transactionsListAdapter} - * - * @param loanWithAssociations object containing details about a Loan Account with Associations - */ - @Override - public void showLoanTransactions(LoanWithAssociations loanWithAssociations) { - this.loanWithAssociations = loanWithAssociations; - llLoanAccountTrans.setVisibility(View.VISIBLE); - tvLoanProductName.setText(loanWithAssociations.getLoanProductName()); - transactionsListAdapter.setTransactions(loanWithAssociations.getTransactions()); - } - - /** - * Sets a {@link TextView} with a msg if Transactions list is empty - */ - @Override - public void showEmptyTransactions(LoanWithAssociations loanWithAssociations) { - sweetUIErrorHandler.showSweetEmptyUI(getString(R.string.transactions), - R.drawable.ic_compare_arrows_black_24dp, rvLoanTransactions, layoutError); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showErrorFetchingLoanAccountsDetail(String message) { - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(rvLoanTransactions, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, - rvLoanTransactions, layoutError); - Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); - } - } - - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvLoanTransactions, layoutError); - loanAccountsTransactionPresenter.loadLoanAccountDetails(loanId); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgressBar(); - loanAccountsTransactionPresenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountTransactionFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountTransactionFragment.kt new file mode 100644 index 0000000000..367595a250 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountTransactionFragment.kt @@ -0,0 +1,183 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.os.Parcelable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast + +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.presenters.LoanAccountsTransactionPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.RecentTransactionListAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.LoanAccountsTransactionView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.Network + +import javax.inject.Inject + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ /** + * Created by dilpreet on 4/3/17. + */ +class LoanAccountTransactionFragment : BaseFragment(), LoanAccountsTransactionView { + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_loan_account_trans) + var llLoanAccountTrans: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_loan_product_name) + var tvLoanProductName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.rv_loan_transactions) + var rvLoanTransactions: RecyclerView? = null + + @kotlin.jvm.JvmField + @Inject + var transactionsListAdapter: RecentTransactionListAdapter? = null + + @kotlin.jvm.JvmField + @Inject + var loanAccountsTransactionPresenter: LoanAccountsTransactionPresenter? = null + private var loanId: Long? = 0 + private var rootView: View? = null + private var loanWithAssociations: LoanWithAssociations? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + if (arguments != null) { + loanId = arguments?.getLong(Constants.LOAN_ID) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_loan_account_transactions, container, false) + setToolbarTitle(getString(R.string.transactions)) + ButterKnife.bind(this, rootView!!) + loanAccountsTransactionPresenter?.attachView(this) + sweetUIErrorHandler = SweetUIErrorHandler(context, rootView) + showUserInterface() + if (savedInstanceState == null) { + loanAccountsTransactionPresenter?.loadLoanAccountDetails(loanId) + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showLoanTransactions(savedInstanceState.getParcelable(Constants.LOAN_ACCOUNT) as LoanWithAssociations) + } + } + + /** + * Initialized [RecyclerView] `rvLoanTransactions` + */ + override fun showUserInterface() { + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = LinearLayoutManager.VERTICAL + rvLoanTransactions?.setHasFixedSize(true) + rvLoanTransactions?.layoutManager = layoutManager + rvLoanTransactions?.adapter = transactionsListAdapter + } + + /** + * Fetches `loanWithAssociations` from server and intializes it in + * `transactionsListAdapter` + * + * @param loanWithAssociations object containing details about a Loan Account with Associations + */ + override fun showLoanTransactions(loanWithAssociations: LoanWithAssociations?) { + this.loanWithAssociations = loanWithAssociations + llLoanAccountTrans?.visibility = View.VISIBLE + tvLoanProductName?.text = loanWithAssociations?.loanProductName + transactionsListAdapter?.setTransactions(loanWithAssociations?.transactions) + } + + /** + * Sets a [TextView] with a msg if Transactions list is empty + */ + override fun showEmptyTransactions(loanWithAssociations: LoanWithAssociations?) { + sweetUIErrorHandler?.showSweetEmptyUI(getString(R.string.transactions), + R.drawable.ic_compare_arrows_black_24dp, rvLoanTransactions, layoutError) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showErrorFetchingLoanAccountsDetail(message: String?) { + if (!Network.isConnected(activity)) { + sweetUIErrorHandler?.showSweetNoInternetUI(rvLoanTransactions, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(message, + rvLoanTransactions, layoutError) + Toast.makeText(activity, message, Toast.LENGTH_SHORT).show() + } + } + + @OnClick(R.id.btn_try_again) + fun retryClicked() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvLoanTransactions, layoutError) + loanAccountsTransactionPresenter?.loadLoanAccountDetails(loanId) + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgressBar() + loanAccountsTransactionPresenter?.detachView() + } + + companion object { + fun newInstance(loanId: Long?): LoanAccountTransactionFragment { + val fragment = LoanAccountTransactionFragment() + val args = Bundle() + if (loanId != null) args.putLong(Constants.LOAN_ID, loanId) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountWithdrawFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountWithdrawFragment.java deleted file mode 100644 index 73b543ae66..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountWithdrawFragment.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.TextView; - -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.models.accounts.loan.LoanWithdraw; -import org.mifos.mobile.presenters.LoanAccountWithdrawPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.LoanAccountWithdrawView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 7/6/17. - */ - -public class LoanAccountWithdrawFragment extends BaseFragment implements LoanAccountWithdrawView { - - @BindView(R.id.tv_client_name) - TextView tvClientName; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.et_withdraw_reason) - EditText etWithdrawReason; - - @Inject - LoanAccountWithdrawPresenter loanAccountWithdrawPresenter; - - View rootView; - private LoanWithAssociations loanWithAssociations; - - - public static LoanAccountWithdrawFragment newInstance( - LoanWithAssociations loanWithAssociations) { - LoanAccountWithdrawFragment fragment = new LoanAccountWithdrawFragment(); - Bundle args = new Bundle(); - args.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - if (getArguments() != null) { - loanWithAssociations = getArguments().getParcelable(Constants.LOAN_ACCOUNT); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_loan_withdraw, container, false); - setToolbarTitle(getString(R.string.withdraw_loan)); - - ButterKnife.bind(this, rootView); - showUserInterface(); - - loanAccountWithdrawPresenter.attachView(this); - - return rootView; - } - - /** - * Sets Basic Information about that Loan Application - */ - private void showUserInterface() { - tvClientName.setText(loanWithAssociations.getClientName()); - tvAccountNumber.setText(loanWithAssociations.getAccountNo()); - } - - /** - * Sends a request to server to withdraw that Loan Account - */ - @OnClick(R.id.btn_withdraw_loan) - public void onLoanWithdraw() { - LoanWithdraw loanWithdraw = new LoanWithdraw(); - loanWithdraw.setNote(etWithdrawReason.getText().toString()); - loanWithdraw.setWithdrawnOnDate(DateHelper - .getDateAsStringFromLong(System.currentTimeMillis())); - loanAccountWithdrawPresenter.withdrawLoanAccount(loanWithAssociations.getId(), - loanWithdraw); - } - - /** - * Receives A confirmation after successfull withdrawing of Loan Application. - */ - @Override - public void showLoanAccountWithdrawSuccess() { - Toaster.show(rootView, R.string.loan_application_withdrawn_successfully); - getActivity().getSupportFragmentManager().popBackStack(); - } - - /** - * Shows an error in {@link Snackbar} if any error occurs during - * withdrawing of Loan - * - * @param message Error Message displayed - */ - @Override - public void showLoanAccountWithdrawError(String message) { - Toaster.show(rootView, message); - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - loanAccountWithdrawPresenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountWithdrawFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountWithdrawFragment.kt new file mode 100644 index 0000000000..e363a69233 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountWithdrawFragment.kt @@ -0,0 +1,133 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.EditText +import android.widget.TextView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.models.accounts.loan.LoanWithdraw +import org.mifos.mobile.presenters.LoanAccountWithdrawPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.LoanAccountWithdrawView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DateHelper +import org.mifos.mobile.utils.Toaster + +import javax.inject.Inject + +/** + * Created by dilpreet on 7/6/17. + */ +class LoanAccountWithdrawFragment : BaseFragment(), LoanAccountWithdrawView { + + @kotlin.jvm.JvmField + @BindView(R.id.tv_client_name) + var tvClientName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.et_withdraw_reason) + var etWithdrawReason: EditText? = null + + @kotlin.jvm.JvmField + @Inject + var loanAccountWithdrawPresenter: LoanAccountWithdrawPresenter? = null + var rootView: View? = null + private var loanWithAssociations: LoanWithAssociations? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + if (arguments != null) { + loanWithAssociations = arguments?.getParcelable(Constants.LOAN_ACCOUNT) + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_loan_withdraw, container, false) + setToolbarTitle(getString(R.string.withdraw_loan)) + ButterKnife.bind(this, rootView!!) + showUserInterface() + loanAccountWithdrawPresenter?.attachView(this) + return rootView + } + + /** + * Sets Basic Information about that Loan Application + */ + private fun showUserInterface() { + tvClientName?.text = loanWithAssociations?.clientName + tvAccountNumber?.text = loanWithAssociations?.accountNo + } + + /** + * Sends a request to server to withdraw that Loan Account + */ + @OnClick(R.id.btn_withdraw_loan) + fun onLoanWithdraw() { + val loanWithdraw = LoanWithdraw() + loanWithdraw.note = etWithdrawReason?.text.toString() + loanWithdraw.withdrawnOnDate = DateHelper + .getDateAsStringFromLong(System.currentTimeMillis()) + loanAccountWithdrawPresenter?.withdrawLoanAccount(loanWithAssociations?.id?.toLong(), + loanWithdraw) + } + + /** + * Receives A confirmation after successfull withdrawing of Loan Application. + */ + override fun showLoanAccountWithdrawSuccess() { + Toaster.show(rootView, R.string.loan_application_withdrawn_successfully) + activity?.supportFragmentManager?.popBackStack() + } + + /** + * Shows an error in {@link Snackbar} if any error occurs during + * withdrawing of Loan + * + * @param message Error Message displayed + */ + override fun showLoanAccountWithdrawError(message: String?) { + Toaster.show(rootView, message) + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + loanAccountWithdrawPresenter?.detachView() + } + + companion object { + fun newInstance( + loanWithAssociations: LoanWithAssociations? + ): LoanAccountWithdrawFragment { + val fragment = LoanAccountWithdrawFragment() + val args = Bundle() + args.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountsDetailFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountsDetailFragment.java deleted file mode 100644 index c6baba726c..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanAccountsDetailFragment.java +++ /dev/null @@ -1,336 +0,0 @@ -package org.mifos.mobile.ui.fragments; -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.models.accounts.loan.Periods; -import org.mifos.mobile.presenters.LoanAccountsDetailPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.AccountType; -import org.mifos.mobile.ui.enums.ChargeType; -import org.mifos.mobile.ui.enums.LoanState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.LoanAccountsDetailView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.QrCodeGenerator; - -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * @author Vishwajeet - * @since 19/08/16 - */ - -public class LoanAccountsDetailFragment extends BaseFragment implements LoanAccountsDetailView { - - @Inject - LoanAccountsDetailPresenter loanAccountDetailsPresenter; - - @BindView(R.id.tv_outstanding_balance) - TextView tvOutstandingBalanceName; - - @BindView(R.id.tv_next_installment) - TextView tvNextInstallmentName; - - @BindView(R.id.tv_due_date) - TextView tvDueDateName; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumberName; - - @BindView(R.id.tv_loan_type) - TextView tvLoanTypeName; - - @BindView(R.id.tv_currency) - TextView tvCurrencyName; - - @BindView(R.id.ll_account_detail) - LinearLayout llAccountDetail; - - @BindView(R.id.layout_error) - View layoutError; - - @BindView(R.id.btn_make_payment) - Button btMakePayment; - - @Inject - PreferencesHelper preferencesHelper; - - - private LoanWithAssociations loanWithAssociations; - private boolean showLoanUpdateOption = false; - private long loanId; - private SweetUIErrorHandler sweetUIErrorHandler; - - View rootView; - - public static LoanAccountsDetailFragment newInstance(long loanId) { - LoanAccountsDetailFragment fragment = new LoanAccountsDetailFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.LOAN_ID, loanId); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - loanId = getArguments().getLong(Constants.LOAN_ID); - } - setHasOptionsMenu(true); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - - rootView = inflater.inflate(R.layout.fragment_loan_account_details, container, false); - setToolbarTitle(getString(R.string.loan_account_details)); - - ButterKnife.bind(this, rootView); - loanAccountDetailsPresenter.attachView(this); - - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - - if (savedInstanceState == null) { - loanAccountDetailsPresenter.loadLoanAccountDetails(loanId); - } - - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showLoanAccountsDetail((LoanWithAssociations) savedInstanceState. - getParcelable(Constants.LOAN_ACCOUNT)); - } - } - - - /** - * Shows details about loan account fetched from server is status is Active else shows and - * error layout i.e. {@code layoutError} with a msg related to the status. - * - * @param loanWithAssociations object containing details of each loan account, - */ - @Override - public void showLoanAccountsDetail(LoanWithAssociations loanWithAssociations) { - llAccountDetail.setVisibility(View.VISIBLE); - this.loanWithAssociations = loanWithAssociations; - if (loanWithAssociations.getStatus().getActive()) { - List overdueSinceDate = - loanWithAssociations.getSummary().getOverdueSinceDate(); - if (overdueSinceDate == null) { - tvDueDateName.setText(R.string.not_available); - } else { - tvDueDateName.setText(DateHelper.getDateAsString(overdueSinceDate)); - } - showDetails(loanWithAssociations); - } else if (loanWithAssociations.getStatus().getPendingApproval()) { - sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.approval_pending), - R.drawable.ic_assignment_turned_in_black_24dp, llAccountDetail, layoutError); - showLoanUpdateOption = true; - } else if (loanWithAssociations.getStatus().getWaitingForDisbursal()) { - sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.waiting_for_disburse), - R.drawable.ic_assignment_turned_in_black_24dp, llAccountDetail, layoutError); - } else { - btMakePayment.setVisibility(View.GONE); - tvDueDateName.setText(R.string.not_available); - showDetails(loanWithAssociations); - } - - getActivity().invalidateOptionsMenu(); - } - - /** - * Sets basic information about a loan - * - * @param loanWithAssociations object containing details of each loan account, - */ - public void showDetails(LoanWithAssociations loanWithAssociations) { - - tvOutstandingBalanceName.setText(getResources().getString(R.string.string_and_string, - loanWithAssociations.getSummary().getCurrency().getDisplaySymbol(), CurrencyUtil. - formatCurrency(getActivity(), - loanWithAssociations.getSummary().getTotalOutstanding()))); - for (Periods thisPeriod : loanWithAssociations.getRepaymentSchedule().getPeriods()) { - if (thisPeriod.getDueDate().equals(loanWithAssociations. - getSummary().getOverdueSinceDate())) { - tvNextInstallmentName.setText(getResources().getString(R.string.string_and_string, - loanWithAssociations.getSummary().getCurrency().getDisplaySymbol(), - CurrencyUtil.formatCurrency(getActivity(), - thisPeriod.getTotalDueForPeriod()))); - break; - } else if (loanWithAssociations.getSummary().getOverdueSinceDate() == null) { - tvNextInstallmentName.setText(R.string.not_available); - } - } - tvAccountNumberName.setText(loanWithAssociations.getAccountNo()); - tvLoanTypeName.setText(loanWithAssociations.getLoanType().getValue()); - tvCurrencyName.setText(loanWithAssociations.getSummary().getCurrency().getCode()); - } - - /** - * Opens {@link SavingsMakeTransferFragment} to Make a payment for loan account with given - * {@code loanId} - */ - @OnClick(R.id.btn_make_payment) - public void onMakePaymentClicked() { - ((BaseActivity) getActivity()).replaceFragment(SavingsMakeTransferFragment - .newInstance(loanId, loanWithAssociations.getSummary().getTotalOutstanding(), - Constants.TRANSFER_PAY_TO), true, R.id.container); - } - - /** - * Opens {@link LoanAccountSummaryFragment} - */ - @OnClick(R.id.ll_summary) - public void onLoanSummaryClicked() { - ((BaseActivity) getActivity()).replaceFragment(LoanAccountSummaryFragment - .newInstance(loanWithAssociations), true, R.id.container); - } - - /** - * Opens {@link LoanRepaymentScheduleFragment} - */ - @OnClick(R.id.ll_repayment) - public void onRepaymentScheduleClicked() { - ((BaseActivity) getActivity()).replaceFragment(LoanRepaymentScheduleFragment - .newInstance(loanId), true, R.id.container); - } - - /** - * Opens {@link LoanAccountTransactionFragment} - */ - @OnClick(R.id.ll_loan_transactions) - public void onTransactionsClicked() { - ((BaseActivity) getActivity()).replaceFragment(LoanAccountTransactionFragment - .newInstance(loanId), true, R.id.container); - } - - @OnClick(R.id.ll_loan_charges) - public void chargesClicked() { - ((BaseActivity) getActivity()).replaceFragment(ClientChargeFragment - .newInstance(loanWithAssociations.getId(), ChargeType.LOAN), true, R.id.container); - } - - @OnClick(R.id.ll_loan_qr_code) - public void onQrCodeClicked() { - String accountDetailsInJson = QrCodeGenerator. - getAccountDetailsInString(loanWithAssociations.getAccountNo(), - preferencesHelper.getOfficeName(), AccountType.LOAN); - ((BaseActivity) getActivity()).replaceFragment(QrCodeDisplayFragment. - newInstance(accountDetailsInJson), true, R.id.container); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showErrorFetchingLoanAccountsDetail(String message) { - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(llAccountDetail, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, - llAccountDetail, layoutError); - Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); - } - } - - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(llAccountDetail, layoutError); - loanAccountDetailsPresenter.loadLoanAccountDetails(loanId); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgressBar(); - loanAccountDetailsPresenter.detachView(); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_loan_details, menu); - if (showLoanUpdateOption) { - menu.findItem(R.id.menu_update_loan).setVisible(true); - menu.findItem(R.id.menu_withdraw_loan).setVisible(true); - menu.findItem(R.id.menu_view_guarantor).setVisible(true); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - if (id == R.id.menu_update_loan) { - ((BaseActivity) getActivity()).replaceFragment(LoanApplicationFragment - .newInstance(LoanState.UPDATE, loanWithAssociations), true, R.id.container); - return true; - } else if (id == R.id.menu_withdraw_loan) { - ((BaseActivity) getActivity()).replaceFragment(LoanAccountWithdrawFragment - .newInstance(loanWithAssociations), true, R.id.container); - } else if (id == R.id.menu_view_guarantor) { - ((BaseActivity) getActivity()).replaceFragment(GuarantorListFragment - .newInstance(loanId), true, R.id.container); - } - return super.onOptionsItemSelected(item); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanApplicationFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanApplicationFragment.java deleted file mode 100644 index 79881bb751..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanApplicationFragment.java +++ /dev/null @@ -1,569 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import androidx.fragment.app.DialogFragment; - -import com.google.android.material.textfield.TextInputLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.models.payload.LoansPayload; -import org.mifos.mobile.models.templates.loans.LoanPurposeOptions; -import org.mifos.mobile.models.templates.loans.LoanTemplate; -import org.mifos.mobile.models.templates.loans.ProductOptions; -import org.mifos.mobile.presenters.LoanApplicationPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.LoanState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.LoanApplicationMvpView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.MFDatePicker; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.Toaster; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import javax.inject.Inject; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by Rajan Maurya on 06/03/17. - */ -public class LoanApplicationFragment extends BaseFragment implements LoanApplicationMvpView, - MFDatePicker.OnDatePickListener, AdapterView.OnItemSelectedListener { - - @BindView(R.id.tv_new_loan_application) - TextView tvNewLoanApplication; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_submission_date) - TextView tvSubmissionDate; - - @BindView(R.id.sp_loan_products) - Spinner spLoanProducts; - - @BindView(R.id.sp_loan_purpose) - Spinner spLoanPurpose; - - @BindView(R.id.til_principal_amount) - TextInputLayout tilPrincipalAmount; - - @BindView(R.id.tv_currency) - TextView tvCurrency; - - @BindView(R.id.tv_expected_disbursement_date) - TextView tvExpectedDisbursementDate; - - @BindView(R.id.ll_add_loan) - LinearLayout llAddLoan; - - @BindView(R.id.ll_error) - RelativeLayout llError; - - @BindView(R.id.tv_status) - TextView tvErrorStatus; - - @BindView(R.id.iv_status) - ImageView ivReload; - - @Inject - LoanApplicationPresenter loanApplicationPresenter; - - View rootView; - - private List listLoanProducts = new ArrayList<>(); - private List listLoanPurpose = new ArrayList<>(); - - private ArrayAdapter loanProductAdapter; - private ArrayAdapter loanPurposeAdapter; - - private LoanTemplate loanTemplate; - private DialogFragment mfDatePicker; - private LoanState loanState; - private LoanWithAssociations loanWithAssociations; - private int productId; - private int purposeId = -1; - private String disbursementDate; - private String submittedDate; - private boolean isDisbursementDate = false; - private boolean isLoanUpdatePurposesInitialization = true; - public boolean active = false; - - - /** - * Used when we want to apply for a Loan - * - * @param loanState {@link LoanState} is set to {@code LoanState.CREATE} - * @return Instance of {@link LoanApplicationFragment} - */ - public static LoanApplicationFragment newInstance(LoanState loanState) { - LoanApplicationFragment fragment = new LoanApplicationFragment(); - Bundle args = new Bundle(); - args.putSerializable(Constants.LOAN_STATE, loanState); - fragment.setArguments(args); - return fragment; - } - - /** - * Used when we want to update a Loan Application - * - * @param loanState {@link LoanState} is set to {@code LoanState.UPDATE} - * @param loanWithAssociations {@link LoanAccount} to modify - * @return Instance of {@link LoanApplicationFragment} - */ - public static LoanApplicationFragment newInstance(LoanState loanState, - LoanWithAssociations loanWithAssociations) { - LoanApplicationFragment fragment = new LoanApplicationFragment(); - Bundle args = new Bundle(); - args.putSerializable(Constants.LOAN_STATE, loanState); - args.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - if (getArguments() != null) { - loanState = (LoanState) getArguments().getSerializable(Constants.LOAN_STATE); - - if (loanState == LoanState.CREATE) { - setToolbarTitle(getString(R.string.apply_for_loan)); - } else { - setToolbarTitle(getString(R.string.update_loan)); - loanWithAssociations = getArguments().getParcelable(Constants.LOAN_ACCOUNT); - } - } - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_add_loan_application, container, false); - - ButterKnife.bind(this, rootView); - loanApplicationPresenter.attachView(this); - - showUserInterface(); - if (savedInstanceState == null) { - loadLoanTemplate(); - } - - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.TEMPLATE, loanTemplate); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - LoanTemplate template = savedInstanceState.getParcelable(Constants.TEMPLATE); - if (loanState == LoanState.CREATE) { - showLoanTemplate(template); - } else { - showUpdateLoanTemplate(template); - } - } - } - - /** - * Loads {@link LoanTemplate} according to the {@code loanState} - */ - private void loadLoanTemplate() { - if (loanState == LoanState.CREATE) { - loanApplicationPresenter.loadLoanApplicationTemplate(LoanState.CREATE); - } else { - loanApplicationPresenter.loadLoanApplicationTemplate(LoanState.UPDATE); - } - } - - /** - * Calls function which applies for a new Loan Application or updates a Loan Application - * according to {@code loanState} - */ - @OnClick(R.id.btn_loan_review) - void onReviewLoanApplication() { - if (tilPrincipalAmount.getEditText().getText().toString().equals("")) { - tilPrincipalAmount.setError(getString(R.string.enter_amount)); - return; - } - - if (tilPrincipalAmount.getEditText().getText().toString().equals(".")) { - tilPrincipalAmount.setError(getString(R.string.invalid_amount)); - return; - } - - if (tilPrincipalAmount.getEditText().getText().toString().matches("^0*")) { - tilPrincipalAmount.setError(getString(R.string.amount_greater_than_zero)); - return; - } - - tilPrincipalAmount.setError(null); - if (loanState == LoanState.CREATE) { - reviewNewLoanApplication(); - } else { - submitUpdateLoanApplication(); - } - } - - /** - * Submits a New Loan Application to the server - */ - private void reviewNewLoanApplication() { - LoansPayload loansPayload = new LoansPayload(); - loansPayload.setClientId(loanTemplate.getClientId()); - loansPayload.setLoanPurpose(spLoanPurpose.getSelectedItem().toString()); - loansPayload.setProductName(spLoanProducts.getSelectedItem().toString()); - loansPayload.setCurrency(tvCurrency.getText().toString()); - if (purposeId > 0) - loansPayload.setLoanPurposeId(purposeId); - loansPayload.setProductId(productId); - loansPayload.setPrincipal(Double. - parseDouble(tilPrincipalAmount.getEditText().getText().toString())); - loansPayload.setLoanTermFrequency(loanTemplate.getTermFrequency()); - loansPayload.setLoanTermFrequencyType(loanTemplate.getInterestRateFrequencyType().getId()); - loansPayload.setLoanType("individual"); - loansPayload.setNumberOfRepayments(loanTemplate.getNumberOfRepayments()); - loansPayload.setRepaymentEvery(loanTemplate.getRepaymentEvery()); - loansPayload.setRepaymentFrequencyType(loanTemplate.getInterestRateFrequencyType().getId()); - loansPayload.setInterestRatePerPeriod(loanTemplate.getInterestRatePerPeriod()); - loansPayload.setExpectedDisbursementDate(disbursementDate); - loansPayload.setSubmittedOnDate(submittedDate); - - loansPayload.setTransactionProcessingStrategyId( - loanTemplate.getTransactionProcessingStrategyId()); - loansPayload.setAmortizationType(loanTemplate.getAmortizationType().getId()); - loansPayload.setInterestCalculationPeriodType( - loanTemplate.getInterestCalculationPeriodType().getId()); - loansPayload.setInterestType(loanTemplate.getInterestType().getId()); - - ((BaseActivity) getActivity()).replaceFragment(ReviewLoanApplicationFragment - .Companion.newInstance(loanState, loansPayload, - tvNewLoanApplication.getText().toString(), - tvAccountNumber.getText().toString()), - true, R.id.container); - } - - /** - * Requests server to update the Loan Application with new values - */ - private void submitUpdateLoanApplication() { - LoansPayload loansPayload = new LoansPayload(); - loansPayload.setPrincipal(Double. - parseDouble(tilPrincipalAmount.getEditText().getText().toString())); - loansPayload.setProductId(productId); - loansPayload.setLoanPurpose(spLoanPurpose.getSelectedItem().toString()); - loansPayload.setProductName(spLoanProducts.getSelectedItem().toString()); - loansPayload.setCurrency(tvCurrency.getText().toString()); - if (purposeId > 0) - loansPayload.setLoanPurposeId(purposeId); - loansPayload.setLoanTermFrequency(loanTemplate.getTermFrequency()); - loansPayload.setLoanTermFrequencyType(loanTemplate.getInterestRateFrequencyType().getId()); - loansPayload.setNumberOfRepayments(loanTemplate.getNumberOfRepayments()); - loansPayload.setRepaymentEvery(loanTemplate.getRepaymentEvery()); - loansPayload.setRepaymentFrequencyType(loanTemplate.getInterestRateFrequencyType().getId()); - loansPayload.setInterestRatePerPeriod(loanTemplate.getInterestRatePerPeriod()); - loansPayload.setInterestType(loanTemplate.getInterestType().getId()); - loansPayload.setInterestCalculationPeriodType( - loanTemplate.getInterestCalculationPeriodType().getId()); - loansPayload.setAmortizationType(loanTemplate.getAmortizationType().getId()); - loansPayload.setTransactionProcessingStrategyId( - loanTemplate.getTransactionProcessingStrategyId()); - loansPayload.setExpectedDisbursementDate(disbursementDate); - - ((BaseActivity) getActivity()).replaceFragment(ReviewLoanApplicationFragment - .Companion.newInstance(loanState, - loansPayload, - loanWithAssociations.getId(), - tvNewLoanApplication.getText().toString(), - tvAccountNumber.getText().toString()), - false, R.id.container); - } - - /** - * Retries to fetch {@link LoanTemplate} by calling {@code loadLoanTemplate()} - */ - @OnClick(R.id.iv_status) - void onRetry() { - llError.setVisibility(View.GONE); - llAddLoan.setVisibility(View.VISIBLE); - loadLoanTemplate(); - } - - /** - * Initializes {@code tvSubmissionDate} with current Date - */ - public void inflateSubmissionDate() { - tvSubmissionDate.setText(MFDatePicker.getDatePickedAsString()); - } - - /** - * Initializes {@code tvExpectedDisbursementDate} with current Date - */ - public void inflateDisbursementDate() { - mfDatePicker = MFDatePicker.newInstance(this, MFDatePicker.FUTURE_DAYS, active); - tvExpectedDisbursementDate.setText(MFDatePicker.getDatePickedAsString()); - active = true; - } - - /** - * Sets {@code submittedDate} and {@code disbursementDate} in a specific format - */ - public void setSubmissionDisburseDate() { - disbursementDate = tvExpectedDisbursementDate.getText().toString(); - submittedDate = tvSubmissionDate.getText().toString(); - submittedDate = DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, submittedDate); - disbursementDate = DateHelper.getSpecificFormat( - DateHelper.FORMAT_dd_MMMM_yyyy, disbursementDate); - } - - /** - * Shows a {@link DialogFragment} for selecting a Date for Disbursement - */ - @OnClick(R.id.ll_expected_disbursement_date_edit) - public void setTvDisbursementOnDate() { - isDisbursementDate = true; - mfDatePicker.show(getActivity().getSupportFragmentManager(), Constants - .DFRAG_DATE_PICKER); - } - - /** - * A CallBack for {@link MFDatePicker} which provides us with the date selected from the - * {@link android.app.DatePickerDialog} - * - * @param date Date selected by user in {@link String} - */ - @Override - public void onDatePicked(String date) { - if (isDisbursementDate) { - tvExpectedDisbursementDate.setText(date); - disbursementDate = date; - isDisbursementDate = false; - } - setSubmissionDisburseDate(); - } - - - /** - * Initializes the layout - */ - @Override - public void showUserInterface() { - loanProductAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, - listLoanProducts); - loanProductAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - spLoanProducts.setAdapter(loanProductAdapter); - spLoanProducts.setOnItemSelectedListener(this); - - loanPurposeAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, - listLoanPurpose); - loanPurposeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - spLoanPurpose.setAdapter(loanPurposeAdapter); - spLoanPurpose.setOnItemSelectedListener(this); - - inflateSubmissionDate(); - inflateDisbursementDate(); - setSubmissionDisburseDate(); - } - - /** - * Fetches the {@link LoanTemplate} from server for {@code loanState} as CREATE - * - * @param loanTemplate Template for Loan Application - */ - @Override - public void showLoanTemplate(LoanTemplate loanTemplate) { - this.loanTemplate = loanTemplate; - for (ProductOptions productOption : loanTemplate.getProductOptions()) { - listLoanProducts.add(productOption.getName()); - } - loanProductAdapter.notifyDataSetChanged(); - } - - /** - * Fetches the {@link LoanTemplate} from server for {@code loanState} as UPDATE - * - * @param loanTemplate Template for Loan Application - */ - @Override - public void showUpdateLoanTemplate(LoanTemplate loanTemplate) { - this.loanTemplate = loanTemplate; - - for (ProductOptions productOption : loanTemplate.getProductOptions()) { - listLoanProducts.add(productOption.getName()); - } - loanProductAdapter.notifyDataSetChanged(); - - spLoanProducts.setSelection(loanProductAdapter - .getPosition(loanWithAssociations.getLoanProductName())); - tvAccountNumber.setText(getString(R.string.string_and_string, - getString(R.string.account_number) + " ", loanWithAssociations.getAccountNo())); - tvNewLoanApplication.setText(getString(R.string.string_and_string, - getString(R.string.update_loan_application) + " ", - loanWithAssociations.getClientName())); - tilPrincipalAmount.getEditText().setText(String.format(Locale.getDefault(), - "%.2f", loanWithAssociations.getPrincipal())); - tvCurrency.setText(loanWithAssociations.getCurrency().getDisplayLabel()); - - tvSubmissionDate.setText(DateHelper.getDateAsString(loanWithAssociations. - getTimeline().getSubmittedOnDate(), "dd-MM-yyyy")); - tvExpectedDisbursementDate.setText(DateHelper.getDateAsString(loanWithAssociations. - getTimeline().getExpectedDisbursementDate(), "dd-MM-yyyy")); - setSubmissionDisburseDate(); - } - - /** - * Fetches the {@link LoanTemplate} according to product from server for {@code loanState} as - * CREATE - * - * @param loanTemplate Template for Loan Application - */ - @Override - public void showLoanTemplateByProduct(LoanTemplate loanTemplate) { - this.loanTemplate = loanTemplate; - tvAccountNumber.setText(getString(R.string.string_and_string, - getString(R.string.account_number) + " ", loanTemplate.getClientAccountNo())); - tvNewLoanApplication.setText(getString(R.string.string_and_string, - getString(R.string.new_loan_application) + " ", loanTemplate.getClientName())); - tilPrincipalAmount.getEditText().setText(String.valueOf(loanTemplate.getPrincipal())); - tvCurrency.setText(loanTemplate.getCurrency().getDisplayLabel()); - - listLoanPurpose.clear(); - listLoanPurpose.add(getActivity().getString(R.string.loan_purpose_not_provided)); - - if (loanTemplate.getLoanPurposeOptions() != null) { - for (LoanPurposeOptions loanPurposeOptions : loanTemplate.getLoanPurposeOptions()) { - listLoanPurpose.add(loanPurposeOptions.getName()); - } - } - loanPurposeAdapter.notifyDataSetChanged(); - spLoanPurpose.setSelection(0); - - } - - /** - * Fetches the {@link LoanTemplate} according to product from server for {@code loanState} as - * UPDATE - * - * @param loanTemplate Template for Loan Application - */ - @Override - public void showUpdateLoanTemplateByProduct(LoanTemplate loanTemplate) { - this.loanTemplate = loanTemplate; - listLoanPurpose.clear(); - listLoanPurpose.add(getActivity().getString(R.string.loan_purpose_not_provided)); - - if (loanTemplate.getLoanPurposeOptions() != null) { - for (LoanPurposeOptions loanPurposeOptions : loanTemplate.getLoanPurposeOptions()) { - listLoanPurpose.add(loanPurposeOptions.getName()); - } - } - loanPurposeAdapter.notifyDataSetChanged(); - spLoanPurpose.setSelection(0); - - if (isLoanUpdatePurposesInitialization && - loanWithAssociations.getLoanPurposeName() != null) { - spLoanPurpose.setSelection(loanPurposeAdapter - .getPosition(loanWithAssociations.getLoanPurposeName())); - isLoanUpdatePurposesInitialization = false; - } else { - tvAccountNumber.setText(getString(R.string.string_and_string, - getString(R.string.account_number) + " ", loanTemplate.getClientAccountNo())); - tvNewLoanApplication.setText(getString(R.string.string_and_string, - getString(R.string.new_loan_application) + " ", loanTemplate.getClientName())); - tilPrincipalAmount.getEditText().setText(String.valueOf(loanTemplate.getPrincipal())); - tvCurrency.setText(loanTemplate.getCurrency().getDisplayLabel()); - } - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showError(String message) { - if (!Network.isConnected(getActivity())) { - ivReload.setImageResource(R.drawable.ic_error_black_24dp); - tvErrorStatus.setText(getString(R.string.internet_not_connected)); - llAddLoan.setVisibility(View.GONE); - llError.setVisibility(View.VISIBLE); - } else { - Toaster.show(rootView, message); - } - } - - @Override - public void showProgress() { - llAddLoan.setVisibility(View.GONE); - showProgressBar(); - } - - @Override - public void hideProgress() { - llAddLoan.setVisibility(View.VISIBLE); - hideProgressBar(); - } - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (parent.getId()) { - case R.id.sp_loan_products: - productId = loanTemplate.getProductOptions().get(position).getId(); - - if (loanState == LoanState.CREATE) { - loanApplicationPresenter.loadLoanApplicationTemplateByProduct(productId, - LoanState.CREATE); - } else { - loanApplicationPresenter.loadLoanApplicationTemplateByProduct(productId, - LoanState.UPDATE); - } - break; - - case R.id.sp_loan_purpose: - if (loanTemplate.getLoanPurposeOptions() != null) { - purposeId = loanTemplate.getLoanPurposeOptions().get(position).getId(); - } - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgressBar(); - loanApplicationPresenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanApplicationFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanApplicationFragment.kt new file mode 100644 index 0000000000..303b2e87e4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanApplicationFragment.kt @@ -0,0 +1,545 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.* +import android.widget.AdapterView.OnItemSelectedListener + +import androidx.fragment.app.DialogFragment + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.google.android.material.textfield.TextInputLayout + +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.models.payload.LoansPayload +import org.mifos.mobile.models.templates.loans.LoanTemplate +import org.mifos.mobile.presenters.LoanApplicationPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.LoanState +import org.mifos.mobile.ui.fragments.ReviewLoanApplicationFragment.Companion.newInstance +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.LoanApplicationMvpView +import org.mifos.mobile.utils.* +import org.mifos.mobile.utils.MFDatePicker.OnDatePickListener + +import java.util.* +import javax.inject.Inject + + +/** + * Created by Rajan Maurya on 06/03/17. + */ +class LoanApplicationFragment : BaseFragment(), LoanApplicationMvpView, OnDatePickListener, OnItemSelectedListener { + + @JvmField + @BindView(R.id.tv_new_loan_application) + var tvNewLoanApplication: TextView? = null + + @JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @JvmField + @BindView(R.id.tv_submission_date) + var tvSubmissionDate: TextView? = null + + @JvmField + @BindView(R.id.sp_loan_products) + var spLoanProducts: Spinner? = null + + @JvmField + @BindView(R.id.sp_loan_purpose) + var spLoanPurpose: Spinner? = null + + @JvmField + @BindView(R.id.til_principal_amount) + var tilPrincipalAmount: TextInputLayout? = null + + @JvmField + @BindView(R.id.tv_currency) + var tvCurrency: TextView? = null + + @JvmField + @BindView(R.id.tv_expected_disbursement_date) + var tvExpectedDisbursementDate: TextView? = null + + @JvmField + @BindView(R.id.ll_add_loan) + var llAddLoan: LinearLayout? = null + + @JvmField + @BindView(R.id.ll_error) + var llError: RelativeLayout? = null + + @JvmField + @BindView(R.id.tv_status) + var tvErrorStatus: TextView? = null + + @JvmField + @BindView(R.id.iv_status) + var ivReload: ImageView? = null + + @JvmField + @Inject + var loanApplicationPresenter: LoanApplicationPresenter? = null + var rootView: View? = null + private val listLoanProducts: MutableList = ArrayList() + private val listLoanPurpose: MutableList = ArrayList() + private var loanProductAdapter: ArrayAdapter? = null + private var loanPurposeAdapter: ArrayAdapter? = null + private var loanTemplate: LoanTemplate? = null + private var mfDatePicker: DialogFragment? = null + private var loanState: LoanState? = null + private var loanWithAssociations: LoanWithAssociations? = null + private var productId: Int? = 0 + private var purposeId: Int? = -1 + private var disbursementDate: String? = null + private var submittedDate: String? = null + private var isDisbursementDate = false + private var isLoanUpdatePurposesInitialization = true + var active: Boolean = false + + + /** + * Used when we want to apply for a Loan + * + * @param loanState [LoanState] is set to `LoanState.CREATE` + * @return Instance of [LoanApplicationFragment] + */ + fun newInstance(loanState: LoanState): LoanApplicationFragment? { + val fragment = LoanApplicationFragment() + val args = Bundle() + args.putSerializable(Constants.LOAN_STATE, loanState) + fragment.arguments = args + return fragment + } + + /** + * Used when we want to update a Loan Application + * + * @param loanState [LoanState] is set to `LoanState.UPDATE` + * @param loanWithAssociations [LoanAccount] to modify + * @return Instance of [LoanApplicationFragment] + */ + fun newInstance( + loanState: LoanState?, + loanWithAssociations: LoanWithAssociations? + ): LoanApplicationFragment? { + val fragment = LoanApplicationFragment() + val args = Bundle() + args.putSerializable(Constants.LOAN_STATE, loanState) + args.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations) + fragment.arguments = args + return fragment + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + if (arguments != null) { + loanState = arguments?.getSerializable(Constants.LOAN_STATE) as LoanState + if (loanState == LoanState.CREATE) { + setToolbarTitle(getString(R.string.apply_for_loan)) + } else { + setToolbarTitle(getString(R.string.update_loan)) + loanWithAssociations = arguments?.getParcelable(Constants.LOAN_ACCOUNT) + } + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_add_loan_application, container, false) + ButterKnife.bind(this, rootView!!) + loanApplicationPresenter?.attachView(this) + showUserInterface() + if (savedInstanceState == null) { + loadLoanTemplate() + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.TEMPLATE, loanTemplate) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + val template: LoanTemplate? = savedInstanceState.getParcelable(Constants.TEMPLATE) + if (loanState == LoanState.CREATE) { + showLoanTemplate(template) + } else { + showUpdateLoanTemplate(template) + } + } + } + + /** + * Loads [LoanTemplate] according to the `loanState` + */ + private fun loadLoanTemplate() { + if (loanState == LoanState.CREATE) { + loanApplicationPresenter?.loadLoanApplicationTemplate(LoanState.CREATE) + } else { + loanApplicationPresenter?.loadLoanApplicationTemplate(LoanState.UPDATE) + } + } + + /** + * Calls function which applies for a new Loan Application or updates a Loan Application + * according to `loanState` + */ + @OnClick(R.id.btn_loan_review) + fun onReviewLoanApplication() { + if (tilPrincipalAmount?.editText?.text.toString() == "") { + tilPrincipalAmount?.error = getString(R.string.enter_amount) + return + } + if (tilPrincipalAmount?.editText?.text.toString() == ".") { + tilPrincipalAmount?.error = getString(R.string.invalid_amount) + return + } + if (tilPrincipalAmount?.editText?.text.toString().matches("^0*".toRegex())) { + tilPrincipalAmount?.error = getString(R.string.amount_greater_than_zero) + return + } + tilPrincipalAmount?.error = null + if (loanState == LoanState.CREATE) { + reviewNewLoanApplication() + } else { + submitUpdateLoanApplication() + } + } + + /** + * Submits a New Loan Application to the server + */ + private fun reviewNewLoanApplication() { + val loansPayload = LoansPayload() + loansPayload.clientId = loanTemplate?.clientId + loansPayload.loanPurpose = spLoanPurpose?.selectedItem.toString() + loansPayload.productName = spLoanProducts?.selectedItem.toString() + loansPayload.currency = tvCurrency?.text.toString() + if (purposeId != null && purposeId!! > 0) loansPayload.loanPurposeId = purposeId + loansPayload.productId = productId + loansPayload.principal = tilPrincipalAmount?.editText?.text.toString().toDouble() + loansPayload.loanTermFrequency = loanTemplate?.termFrequency + loansPayload.loanTermFrequencyType = loanTemplate?.interestRateFrequencyType?.id + loansPayload.loanType = "individual" + loansPayload.numberOfRepayments = loanTemplate?.numberOfRepayments + loansPayload.repaymentEvery = loanTemplate?.repaymentEvery + loansPayload.repaymentFrequencyType = loanTemplate?.interestRateFrequencyType?.id + loansPayload.interestRatePerPeriod = loanTemplate?.interestRatePerPeriod + loansPayload.expectedDisbursementDate = disbursementDate + loansPayload.submittedOnDate = submittedDate + loansPayload.transactionProcessingStrategyId = loanTemplate?.transactionProcessingStrategyId + loansPayload.amortizationType = loanTemplate?.amortizationType?.id + loansPayload.interestCalculationPeriodType = loanTemplate?.interestCalculationPeriodType?.id + loansPayload.interestType = loanTemplate?.interestType?.id + (activity as BaseActivity?)?.replaceFragment(newInstance(loanState!!, loansPayload, + tvNewLoanApplication?.text.toString(), + tvAccountNumber?.text.toString()), + true, R.id.container) + } + + /** + * Requests server to update the Loan Application with new values + */ + private fun submitUpdateLoanApplication() { + val loansPayload = LoansPayload() + loansPayload.principal = tilPrincipalAmount?.editText?.text.toString().toDouble() + loansPayload.productId = productId + loansPayload.loanPurpose = spLoanPurpose?.selectedItem.toString() + loansPayload.productName = spLoanProducts?.selectedItem.toString() + loansPayload.currency = tvCurrency?.text.toString() + if (purposeId != null && purposeId!! > 0) loansPayload.loanPurposeId = purposeId + loansPayload.loanTermFrequency = loanTemplate?.termFrequency + loansPayload.loanTermFrequencyType = loanTemplate?.interestRateFrequencyType?.id + loansPayload.numberOfRepayments = loanTemplate?.numberOfRepayments + loansPayload.repaymentEvery = loanTemplate?.repaymentEvery + loansPayload.repaymentFrequencyType = loanTemplate?.interestRateFrequencyType?.id + loansPayload.interestRatePerPeriod = loanTemplate?.interestRatePerPeriod + loansPayload.interestType = loanTemplate?.interestType?.id + loansPayload.interestCalculationPeriodType = loanTemplate?.interestCalculationPeriodType?.id + loansPayload.amortizationType = loanTemplate?.amortizationType?.id + loansPayload.transactionProcessingStrategyId = loanTemplate?.transactionProcessingStrategyId + loansPayload.expectedDisbursementDate = disbursementDate + (activity as BaseActivity?)?.replaceFragment(newInstance(loanState, + loansPayload, + loanWithAssociations?.id?.toLong(), + tvNewLoanApplication?.text.toString(), + tvAccountNumber?.text.toString()), + false, R.id.container) + } + + /** + * Retries to fetch [LoanTemplate] by calling `loadLoanTemplate()` + */ + @OnClick(R.id.iv_status) + fun onRetry() { + llError?.visibility = View.GONE + llAddLoan?.visibility = View.VISIBLE + loadLoanTemplate() + } + + /** + * Initializes `tvSubmissionDate` with current Date + */ + private fun inflateSubmissionDate() { + tvSubmissionDate?.text = MFDatePicker.datePickedAsString + } + + /** + * Initializes `tvExpectedDisbursementDate` with current Date + */ + private fun inflateDisbursementDate() { + mfDatePicker = MFDatePicker.newInstance(this, MFDatePicker.FUTURE_DAYS, active) + tvExpectedDisbursementDate?.text = MFDatePicker.datePickedAsString + active = true + } + + /** + * Sets `submittedDate` and `disbursementDate` in a specific format + */ + fun setSubmissionDisburseDate() { + disbursementDate = tvExpectedDisbursementDate?.text.toString() + submittedDate = tvSubmissionDate?.text.toString() + submittedDate = DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, submittedDate) + disbursementDate = DateHelper.getSpecificFormat( + DateHelper.FORMAT_dd_MMMM_yyyy, disbursementDate) + } + + /** + * Shows a [DialogFragment] for selecting a Date for Disbursement + */ + @OnClick(R.id.ll_expected_disbursement_date_edit) + fun setTvDisbursementOnDate() { + isDisbursementDate = true + mfDatePicker?.show(activity?.supportFragmentManager, Constants.DFRAG_DATE_PICKER) + } + + /** + * A CallBack for [MFDatePicker] which provides us with the date selected from the + * [android.app.DatePickerDialog] + * + * @param date Date selected by user in [String] + */ + override fun onDatePicked(date: String?) { + if (isDisbursementDate) { + tvExpectedDisbursementDate?.text = date + disbursementDate = date + isDisbursementDate = false + } + setSubmissionDisburseDate() + } + + /** + * Initializes the layout + */ + override fun showUserInterface() { + loanProductAdapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, + listLoanProducts) + loanProductAdapter?.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + spLoanProducts?.adapter = loanProductAdapter + spLoanProducts?.onItemSelectedListener = this + loanPurposeAdapter = ArrayAdapter(activity, android.R.layout.simple_spinner_item, + listLoanPurpose) + loanPurposeAdapter?.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + spLoanPurpose?.adapter = loanPurposeAdapter + spLoanPurpose?.onItemSelectedListener = this + inflateSubmissionDate() + inflateDisbursementDate() + setSubmissionDisburseDate() + } + + /** + * Fetches the [LoanTemplate] from server for `loanState` as CREATE + * + * @param loanTemplate Template for Loan Application + */ + override fun showLoanTemplate(loanTemplate: LoanTemplate?) { + this.loanTemplate = loanTemplate + if (loanTemplate?.productOptions != null) + for ((_, name) in loanTemplate.productOptions) { + listLoanProducts.add(name) + } + loanProductAdapter?.notifyDataSetChanged() + } + + /** + * Fetches the [LoanTemplate] from server for `loanState` as UPDATE + * + * @param loanTemplate Template for Loan Application + */ + override fun showUpdateLoanTemplate(loanTemplate: LoanTemplate?) { + this.loanTemplate = loanTemplate + if (loanTemplate?.productOptions != null) + for ((_, name) in loanTemplate.productOptions) { + listLoanProducts.add(name) + } + loanProductAdapter?.notifyDataSetChanged() + spLoanProducts?.setSelection(loanProductAdapter!! + .getPosition(loanWithAssociations?.loanProductName)) + tvAccountNumber?.text = getString(R.string.string_and_string, + getString(R.string.account_number) + " ", loanWithAssociations?.accountNo) + tvNewLoanApplication?.text = getString(R.string.string_and_string, + getString(R.string.update_loan_application) + " ", + loanWithAssociations?.clientName) + tilPrincipalAmount?.editText?.setText(String.format(Locale.getDefault(), + "%.2f", loanWithAssociations?.principal)) + tvCurrency?.text = loanWithAssociations?.currency?.displayLabel + tvSubmissionDate?.text = DateHelper.getDateAsString(loanWithAssociations?.timeline?.submittedOnDate, "dd-MM-yyyy") + tvExpectedDisbursementDate?.text = DateHelper.getDateAsString(loanWithAssociations?.timeline?.expectedDisbursementDate, "dd-MM-yyyy") + setSubmissionDisburseDate() + } + + /** + * Fetches the [LoanTemplate] according to product from server for `loanState` as + * CREATE + * + * @param loanTemplate Template for Loan Application + */ + override fun showLoanTemplateByProduct(loanTemplate: LoanTemplate?) { + this.loanTemplate = loanTemplate + tvAccountNumber?.text = getString(R.string.string_and_string, + getString(R.string.account_number) + " ", loanTemplate?.clientAccountNo) + tvNewLoanApplication?.text = getString(R.string.string_and_string, + getString(R.string.new_loan_application) + " ", loanTemplate?.clientName) + tilPrincipalAmount?.editText?.setText(loanTemplate?.principal.toString()) + tvCurrency?.text = loanTemplate?.currency?.displayLabel + listLoanPurpose.clear() + listLoanPurpose.add(activity?.getString(R.string.loan_purpose_not_provided)) + if (loanTemplate?.loanPurposeOptions != null) + for (loanPurposeOptions in loanTemplate.loanPurposeOptions) { + listLoanPurpose.add(loanPurposeOptions.name) + } + loanPurposeAdapter?.notifyDataSetChanged() + spLoanPurpose?.setSelection(0) + } + + /** + * Fetches the [LoanTemplate] according to product from server for `loanState` as + * UPDATE + * + * @param loanTemplate Template for Loan Application + */ + override fun showUpdateLoanTemplateByProduct(loanTemplate: LoanTemplate?) { + this.loanTemplate = loanTemplate + listLoanPurpose.clear() + listLoanPurpose.add(activity?.getString(R.string.loan_purpose_not_provided)) + if (loanTemplate?.loanPurposeOptions != null) + for (loanPurposeOptions in loanTemplate.loanPurposeOptions) { + listLoanPurpose.add(loanPurposeOptions.name) + } + loanPurposeAdapter?.notifyDataSetChanged() + spLoanPurpose?.setSelection(0) + if (isLoanUpdatePurposesInitialization && + loanWithAssociations?.loanPurposeName != null) { + spLoanPurpose?.setSelection(loanPurposeAdapter!! + .getPosition(loanWithAssociations?.loanPurposeName)) + isLoanUpdatePurposesInitialization = false + } else { + tvAccountNumber?.text = getString(R.string.string_and_string, + getString(R.string.account_number) + " ", loanTemplate?.clientAccountNo) + tvNewLoanApplication?.text = getString(R.string.string_and_string, + getString(R.string.new_loan_application) + " ", loanTemplate?.clientName) + tilPrincipalAmount?.editText?.setText(loanTemplate?.principal.toString()) + tvCurrency?.text = loanTemplate?.currency?.displayLabel + } + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showError(message: String?) { + if (!Network.isConnected(activity)) { + ivReload?.setImageResource(R.drawable.ic_error_black_24dp) + tvErrorStatus?.text = getString(R.string.internet_not_connected) + llAddLoan?.visibility = View.GONE + llError?.visibility = View.VISIBLE + } else { + Toaster.show(rootView, message) + } + } + + override fun showProgress() { + llAddLoan?.visibility = View.GONE + showProgressBar() + } + + override fun hideProgress() { + llAddLoan?.visibility = View.VISIBLE + hideProgressBar() + } + + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + when (parent?.id) { + R.id.sp_loan_products -> { + productId = loanTemplate?.productOptions?.get(position)?.id + if (loanState == LoanState.CREATE) { + loanApplicationPresenter?.loadLoanApplicationTemplateByProduct(productId, + LoanState.CREATE) + } else { + loanApplicationPresenter?.loadLoanApplicationTemplateByProduct(productId, + LoanState.UPDATE) + } + } + R.id.sp_loan_purpose -> purposeId = loanTemplate?.loanPurposeOptions?.get(position)?.id + } + } + + override fun onNothingSelected(parent: AdapterView<*>?) {} + override fun onDestroyView() { + super.onDestroyView() + hideProgressBar() + loanApplicationPresenter?.detachView() + } + + companion object { + /** + * Used when we want to apply for a Loan + * + * @param loanState [LoanState] is set to `LoanState.CREATE` + * @return Instance of [LoanApplicationFragment] + */ + fun newInstance(loanState: LoanState?): LoanApplicationFragment { + val fragment = LoanApplicationFragment() + val args = Bundle() + args.putSerializable(Constants.LOAN_STATE, loanState) + fragment.arguments = args + return fragment + } + + /** + * Used when we want to update a Loan Application + * + * @param loanState [LoanState] is set to `LoanState.UPDATE` + * @param loanWithAssociations [LoanAccount] to modify + * @return Instance of [LoanApplicationFragment] + */ + fun newInstance( + loanState: LoanState?, + loanWithAssociations: LoanWithAssociations? + ): LoanApplicationFragment { + val fragment = LoanApplicationFragment() + val args = Bundle() + args.putSerializable(Constants.LOAN_STATE, loanState) + args.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanRepaymentScheduleFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanRepaymentScheduleFragment.java deleted file mode 100644 index 7d62e636f6..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanRepaymentScheduleFragment.java +++ /dev/null @@ -1,231 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.annotation.Nullable; - -import com.evrencoskun.tableview.TableView; -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.models.accounts.loan.Periods; -import org.mifos.mobile.models.accounts.loan.tableview.Cell; -import org.mifos.mobile.models.accounts.loan.tableview.ColumnHeader; -import org.mifos.mobile.models.accounts.loan.tableview.RowHeader; -import org.mifos.mobile.presenters.LoanRepaymentSchedulePresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.LoanRepaymentScheduleAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.LoanRepaymentScheduleMvpView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.Network; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by Rajan Maurya on 03/03/17. - */ -public class LoanRepaymentScheduleFragment extends BaseFragment implements - LoanRepaymentScheduleMvpView { - - @BindView(R.id.tv_repayment_schedule) - TableView tvRepaymentSchedule; - - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_disbursement_date) - TextView tvDisbursementDate; - - @BindView(R.id.tv_number_of_payments) - TextView tvNumberOfPayments; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - LoanRepaymentSchedulePresenter loanRepaymentSchedulePresenter; - - @Inject - LoanRepaymentScheduleAdapter loanRepaymentScheduleAdapter; - - SweetUIErrorHandler sweetUIErrorHandler; - - View rootView; - private long loanId; - private LoanWithAssociations loanWithAssociations; - - public static LoanRepaymentScheduleFragment newInstance(long loanId) { - LoanRepaymentScheduleFragment loanRepaymentScheduleFragment = - new LoanRepaymentScheduleFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.LOAN_ID, loanId); - loanRepaymentScheduleFragment.setArguments(args); - return loanRepaymentScheduleFragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - setToolbarTitle(getString(R.string.loan_repayment_schedule)); - if (getArguments() != null) { - loanId = getArguments().getLong(Constants.LOAN_ID); - } - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_loan_repayment_schedule, container, false); - ButterKnife.bind(this, rootView); - loanRepaymentSchedulePresenter.attachView(this); - - sweetUIErrorHandler = new SweetUIErrorHandler(getContext(), rootView); - - showUserInterface(); - if (savedInstanceState == null) { - loanRepaymentSchedulePresenter.loanLoanWithAssociations(loanId); - } - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showLoanRepaymentSchedule((LoanWithAssociations) savedInstanceState. - getParcelable(Constants.LOAN_ACCOUNT)); - } - } - - /** - * Initializes the layout - */ - @Override - public void showUserInterface() { - tvRepaymentSchedule.setAdapter(loanRepaymentScheduleAdapter); - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - /** - * Fetches {@link LoanWithAssociations} for a loan with {@code loanId} - * - * @param loanWithAssociations Contains details about Repayment Schedule - */ - @Override - public void showLoanRepaymentSchedule(LoanWithAssociations loanWithAssociations) { - this.loanWithAssociations = loanWithAssociations; - String currencyRepresentation = loanWithAssociations.getCurrency().getDisplaySymbol(); - if (currencyRepresentation == null) { - currencyRepresentation = loanWithAssociations.getCurrency().getCode(); - } - loanRepaymentScheduleAdapter - .setCurrency(currencyRepresentation); - setTableViewList(loanWithAssociations.getRepaymentSchedule().getPeriods()); - tvAccountNumber.setText(loanWithAssociations.getAccountNo()); - tvDisbursementDate.setText(DateHelper.getDateAsString(loanWithAssociations. - getTimeline().getExpectedDisbursementDate())); - tvNumberOfPayments.setText(String. - valueOf(loanWithAssociations.getNumberOfRepayments())); - } - - private void setTableViewList(List periods) { - List mColumnHeaderList = new ArrayList<>(); - List mRowHeaders = new ArrayList<>(); - List> mCellList = new ArrayList<>(); - mColumnHeaderList.add(new ColumnHeader(getString(R.string.date))); - mColumnHeaderList.add(new ColumnHeader(getString(R.string.loan_balance))); - mColumnHeaderList.add(new ColumnHeader(getString(R.string.repayment))); - int i = 0; - for (Periods period : periods) { - List cells = new ArrayList<>(); - cells.add(new Cell(period)); - cells.add(new Cell(period)); - cells.add(new Cell(period)); - mCellList.add(cells); - mRowHeaders.add(new RowHeader(++i)); - } - loanRepaymentScheduleAdapter.setAllItems(mColumnHeaderList, mRowHeaders, mCellList); - } - - /** - * Shows an empty layout for a loan with {@code loanId} which has no Repayment Schedule - * - * @param loanWithAssociations Contains details about Repayment Schedule - */ - @Override - public void showEmptyRepaymentsSchedule(LoanWithAssociations loanWithAssociations) { - tvAccountNumber.setText(loanWithAssociations.getAccountNo()); - tvDisbursementDate.setText(DateHelper.getDateAsString(loanWithAssociations. - getTimeline().getExpectedDisbursementDate())); - tvNumberOfPayments.setText(String. - valueOf(loanWithAssociations.getNumberOfRepayments())); - sweetUIErrorHandler.showSweetEmptyUI(getString(R.string.repayment_schedule), - R.drawable.ic_charges, tvRepaymentSchedule, layoutError); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showError(String message) { - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(tvRepaymentSchedule, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, - tvRepaymentSchedule, layoutError); - Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); - } - } - - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(tvRepaymentSchedule, layoutError); - loanRepaymentSchedulePresenter.loanLoanWithAssociations(loanId); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgressBar(); - loanRepaymentSchedulePresenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LoanRepaymentScheduleFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanRepaymentScheduleFragment.kt new file mode 100644 index 0000000000..0939d9ae1c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/LoanRepaymentScheduleFragment.kt @@ -0,0 +1,209 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.os.Parcelable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import android.widget.Toast + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.evrencoskun.tableview.TableView +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.models.accounts.loan.Periods +import org.mifos.mobile.models.accounts.loan.tableview.Cell +import org.mifos.mobile.models.accounts.loan.tableview.ColumnHeader +import org.mifos.mobile.models.accounts.loan.tableview.RowHeader +import org.mifos.mobile.presenters.LoanRepaymentSchedulePresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.LoanRepaymentScheduleAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.LoanRepaymentScheduleMvpView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DateHelper +import org.mifos.mobile.utils.Network + +import java.util.* +import javax.inject.Inject + +/** + * Created by Rajan Maurya on 03/03/17. + */ +class LoanRepaymentScheduleFragment : BaseFragment(), LoanRepaymentScheduleMvpView { + @kotlin.jvm.JvmField + @BindView(R.id.tv_repayment_schedule) + var tvRepaymentSchedule: TableView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_disbursement_date) + var tvDisbursementDate: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_number_of_payments) + var tvNumberOfPayments: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @Inject + var loanRepaymentSchedulePresenter: LoanRepaymentSchedulePresenter? = null + + @kotlin.jvm.JvmField + @Inject + var loanRepaymentScheduleAdapter: LoanRepaymentScheduleAdapter? = null + var sweetUIErrorHandler: SweetUIErrorHandler? = null + var rootView: View? = null + private var loanId: Long? = 0 + private var loanWithAssociations: LoanWithAssociations? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + setToolbarTitle(getString(R.string.loan_repayment_schedule)) + if (arguments != null) loanId = arguments?.getLong(Constants.LOAN_ID) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_loan_repayment_schedule, container, false) + ButterKnife.bind(this, rootView!!) + loanRepaymentSchedulePresenter?.attachView(this) + sweetUIErrorHandler = SweetUIErrorHandler(context, rootView) + showUserInterface() + if (savedInstanceState == null) { + loanRepaymentSchedulePresenter?.loanLoanWithAssociations(loanId) + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.LOAN_ACCOUNT, loanWithAssociations) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showLoanRepaymentSchedule(savedInstanceState.getParcelable(Constants.LOAN_ACCOUNT) as LoanWithAssociations) + } + } + + /** + * Initializes the layout + */ + override fun showUserInterface() { + tvRepaymentSchedule?.adapter = loanRepaymentScheduleAdapter + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + /** + * Fetches [LoanWithAssociations] for a loan with `loanId` + * + * @param loanWithAssociations Contains details about Repayment Schedule + */ + override fun showLoanRepaymentSchedule(loanWithAssociations: LoanWithAssociations?) { + this.loanWithAssociations = loanWithAssociations + var currencyRepresentation = loanWithAssociations?.currency?.displaySymbol + loanRepaymentScheduleAdapter + ?.setCurrency(currencyRepresentation) + setTableViewList(loanWithAssociations?.repaymentSchedule?.periods) + tvAccountNumber?.text = loanWithAssociations?.accountNo + tvDisbursementDate?.text = DateHelper.getDateAsString(loanWithAssociations?.timeline?.expectedDisbursementDate) + tvNumberOfPayments?.text = loanWithAssociations?.numberOfRepayments.toString() + } + + private fun setTableViewList(periods: List?) { + val mColumnHeaderList: MutableList = ArrayList() + val mRowHeaders: MutableList = ArrayList() + val mCellList: MutableList> = ArrayList() + mColumnHeaderList.add(ColumnHeader(getString(R.string.date))) + mColumnHeaderList.add(ColumnHeader(getString(R.string.loan_balance))) + mColumnHeaderList.add(ColumnHeader(getString(R.string.repayment))) + if (periods != null) + for ((i, period) in periods.withIndex()) { + val cells: MutableList = ArrayList() + cells.add(Cell(period)) + cells.add(Cell(period)) + cells.add(Cell(period)) + mCellList.add(cells) + mRowHeaders.add(RowHeader(i + 1)) + } + loanRepaymentScheduleAdapter?.setAllItems(mColumnHeaderList, mRowHeaders, mCellList) + } + + /** + * Shows an empty layout for a loan with `loanId` which has no Repayment Schedule + * + * @param loanWithAssociations Contains details about Repayment Schedule + */ + override fun showEmptyRepaymentsSchedule(loanWithAssociations: LoanWithAssociations?) { + tvAccountNumber?.text = loanWithAssociations?.accountNo + tvDisbursementDate?.text = DateHelper.getDateAsString(loanWithAssociations?.timeline?.expectedDisbursementDate) + tvNumberOfPayments?.text = loanWithAssociations?.numberOfRepayments.toString() + sweetUIErrorHandler?.showSweetEmptyUI(getString(R.string.repayment_schedule), + R.drawable.ic_charges, tvRepaymentSchedule, layoutError) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showError(message: String?) { + if (!Network.isConnected(activity)) { + sweetUIErrorHandler?.showSweetNoInternetUI(tvRepaymentSchedule, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(message, + tvRepaymentSchedule, layoutError) + Toast.makeText(activity, message, Toast.LENGTH_SHORT).show() + } + } + + @OnClick(R.id.btn_try_again) + fun retryClicked() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(tvRepaymentSchedule, layoutError) + loanRepaymentSchedulePresenter?.loanLoanWithAssociations(loanId) + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgressBar() + loanRepaymentSchedulePresenter?.detachView() + } + + companion object { + fun newInstance(loanId: Long?): LoanRepaymentScheduleFragment { + val loanRepaymentScheduleFragment = LoanRepaymentScheduleFragment() + val args = Bundle() + if (loanId != null) args.putLong(Constants.LOAN_ID, loanId) + loanRepaymentScheduleFragment.arguments = args + return loanRepaymentScheduleFragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LocationsFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/LocationsFragment.java deleted file mode 100644 index fa57c6875f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/LocationsFragment.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* -~This project is licensed under the open source MPL V2. -~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md -*/ - -import android.os.Bundle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import com.google.android.gms.maps.CameraUpdateFactory; -import com.google.android.gms.maps.GoogleMap; -import com.google.android.gms.maps.MapView; -import com.google.android.gms.maps.MapsInitializer; -import com.google.android.gms.maps.OnMapReadyCallback; -import com.google.android.gms.maps.model.LatLng; -import com.google.android.gms.maps.model.MarkerOptions; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.fragments.base.BaseFragment; - -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 25/2/17. - */ - -public class LocationsFragment extends BaseFragment implements OnMapReadyCallback { - - @BindView(R.id.map) - MapView mapView; - - private View rootView; - - public static LocationsFragment newInstance() { - LocationsFragment locationsFragment = new LocationsFragment(); - return locationsFragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_locations, container, false); - - ButterKnife.bind(this, rootView); - - mapView.onCreate(savedInstanceState); - mapView.onResume(); - try { - MapsInitializer.initialize(getActivity().getApplicationContext()); - } catch (Exception e) { - Log.d(LocationsFragment.class.getSimpleName(), e.toString()); - } - mapView.getMapAsync(this); - - return rootView; - } - - - @Override - public void onMapReady(GoogleMap googleMap) { - - LatLng headquarterLatLng = new LatLng(47.61115, -122.34481); - - addMarker(googleMap, headquarterLatLng); - addAnimationToHeadquarter(googleMap, headquarterLatLng); - - } - - private void addMarker(GoogleMap googleMap, LatLng headquarterLatLng) { - - googleMap.addMarker(new MarkerOptions().position(headquarterLatLng) - .title(getString(R.string.mifos_initiative))); - - } - - private void addAnimationToHeadquarter(GoogleMap googleMap, LatLng headquarterLatLng) { - - googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(headquarterLatLng, 16.0f)); - } - -} - diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/LocationsFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/LocationsFragment.kt new file mode 100644 index 0000000000..41f691ef78 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/LocationsFragment.kt @@ -0,0 +1,62 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import butterknife.BindView +import butterknife.ButterKnife +import com.google.android.gms.maps.* +import com.google.android.gms.maps.model.LatLng +import com.google.android.gms.maps.model.MarkerOptions +import org.mifos.mobile.R +import org.mifos.mobile.ui.fragments.base.BaseFragment + +/* +~This project is licensed under the open source MPL V2. +~See https://github.com/openMF/self-service-app/blob/master/LICENSE.md +*/ /** + * Created by dilpreet on 25/2/17. + */ +class LocationsFragment : BaseFragment(), OnMapReadyCallback { + @kotlin.jvm.JvmField + @BindView(R.id.map) + var mapView: MapView? = null + private var rootView: View? = null + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_locations, container, false) + ButterKnife.bind(this, rootView!!) + mapView?.onCreate(savedInstanceState) + mapView?.onResume() + try { + MapsInitializer.initialize(activity?.applicationContext) + } catch (e: Exception) { + Log.d(LocationsFragment::class.java.simpleName, e.toString()) + } + mapView?.getMapAsync(this) + return rootView + } + + override fun onMapReady(googleMap: GoogleMap) { + val headquarterLatLng = LatLng(47.61115, -122.34481) + addMarker(googleMap, headquarterLatLng) + addAnimationToHeadquarter(googleMap, headquarterLatLng) + } + + private fun addMarker(googleMap: GoogleMap, headquarterLatLng: LatLng) { + googleMap.addMarker(MarkerOptions().position(headquarterLatLng) + .title(getString(R.string.mifos_initiative))) + } + + private fun addAnimationToHeadquarter(googleMap: GoogleMap, headquarterLatLng: LatLng) { + googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(headquarterLatLng, 16.0f)) + } + + companion object { + fun newInstance(): LocationsFragment { + return LocationsFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/NotificationFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/NotificationFragment.java deleted file mode 100644 index 5233e86068..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/NotificationFragment.java +++ /dev/null @@ -1,147 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.presenters.NotificationPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.NotificationAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.NotificationView; -import org.mifos.mobile.utils.DividerItemDecoration; -import org.mifos.mobile.utils.Network; - -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 13/9/17. - */ - -public class NotificationFragment extends BaseFragment implements NotificationView, - SwipeRefreshLayout.OnRefreshListener { - - - @BindView(R.id.rv_notifications) - RecyclerView rvNotification; - - @BindView(R.id.swipe_notification_container) - SwipeRefreshLayout swipeNotificationContainer; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - NotificationPresenter presenter; - - @Inject - NotificationAdapter adapter; - - private View rootView; - private SweetUIErrorHandler sweetUIErrorHandler; - - - public static NotificationFragment newInstance() { - NotificationFragment fragment = new NotificationFragment(); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setToolbarTitle(getString(R.string.notification)); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_notification, container, false); - ButterKnife.bind(this, rootView); - - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - rvNotification.setLayoutManager(layoutManager); - rvNotification.addItemDecoration(new DividerItemDecoration(getActivity(), - layoutManager.getOrientation())); - rvNotification.setAdapter(adapter); - - swipeNotificationContainer.setColorSchemeResources(R.color.blue_light, - R.color.green_light, R.color.orange_light, R.color.red_light); - swipeNotificationContainer.setOnRefreshListener(this); - - presenter.attachView(this); - presenter.loadNotifications(); - - return rootView; - } - - @Override - public void showNotifications(List notifications) { - if (notifications.size() != 0) { - adapter.setNotificationList(notifications); - } else { - sweetUIErrorHandler.showSweetEmptyUI(getString(R.string.notification), - R.drawable.ic_notifications, rvNotification, layoutError); - } - } - - @Override - public void showError(String msg) { - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(rvNotification, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(msg, - rvNotification, layoutError); - Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); - } - } - - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvNotification, layoutError); - presenter.loadNotifications(); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void showProgress() { - swipeNotificationContainer.setRefreshing(true); - } - - @Override - public void hideProgress() { - swipeNotificationContainer.setRefreshing(false); - } - - @Override - public void onRefresh() { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvNotification, layoutError); - presenter.loadNotifications(); - - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/NotificationFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/NotificationFragment.kt new file mode 100644 index 0000000000..63017f9502 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/NotificationFragment.kt @@ -0,0 +1,138 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast + +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.BuildConfig +import org.mifos.mobile.R +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.presenters.NotificationPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.NotificationAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.NotificationView +import org.mifos.mobile.utils.DividerItemDecoration +import org.mifos.mobile.utils.Network + +import javax.inject.Inject + +/** + * Created by dilpreet on 13/9/17. + */ +class NotificationFragment : BaseFragment(), NotificationView, OnRefreshListener { + + @kotlin.jvm.JvmField + @BindView(R.id.rv_notifications) + var rvNotification: RecyclerView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.swipe_notification_container) + var swipeNotificationContainer: SwipeRefreshLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: NotificationPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var adapter: NotificationAdapter? = null + private var rootView: View? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setToolbarTitle(getString(R.string.notification)) + (activity as BaseActivity?)?.activityComponent?.inject(this) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_notification, container, false) + ButterKnife.bind(this, rootView!!) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = LinearLayoutManager.VERTICAL + rvNotification?.layoutManager = layoutManager + rvNotification?.addItemDecoration(DividerItemDecoration(activity, + layoutManager.orientation)) + rvNotification?.adapter = adapter + swipeNotificationContainer?.setColorSchemeResources(R.color.blue_light, + R.color.green_light, R.color.orange_light, R.color.red_light) + swipeNotificationContainer?.setOnRefreshListener(this) + presenter?.attachView(this) + presenter?.loadNotifications() + return rootView + } + + override fun showNotifications(notifications: List?) { + if (BuildConfig.DEBUG && notifications == null) { + error("Assertion failed") + } + if (notifications?.isNotEmpty() == true) { + adapter?.setNotificationList(notifications as List?) + } else { + sweetUIErrorHandler?.showSweetEmptyUI(getString(R.string.notification), + R.drawable.ic_notifications, rvNotification, layoutError) + } + } + + override fun showError(msg: String?) { + if (!Network.isConnected(activity)) { + sweetUIErrorHandler?.showSweetNoInternetUI(rvNotification, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(msg, + rvNotification, layoutError) + Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show() + } + } + + @OnClick(R.id.btn_try_again) + fun retryClicked() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvNotification, layoutError) + presenter?.loadNotifications() + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + override fun showProgress() { + swipeNotificationContainer?.isRefreshing = true + } + + override fun hideProgress() { + swipeNotificationContainer?.isRefreshing = false + } + + override fun onRefresh() { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvNotification, layoutError) + presenter?.loadNotifications() + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): NotificationFragment { + return NotificationFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeDisplayFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeDisplayFragment.java deleted file mode 100644 index f4aa772851..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeDisplayFragment.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.Intent; -import android.graphics.drawable.BitmapDrawable; -import android.net.Uri; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.QrCodeGenerator; -import org.mifos.mobile.utils.Utils; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 16/8/17. - */ - -public class QrCodeDisplayFragment extends BaseFragment { - - - @BindView(R.id.iv_qr_code) - ImageView ivQrCode; - - private View rootView; - private String json; - - public static QrCodeDisplayFragment newInstance(String json) { - QrCodeDisplayFragment fragment = new QrCodeDisplayFragment(); - Bundle args = new Bundle(); - args.putString(Constants.QR_DATA, json); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - json = getArguments().getString(Constants.QR_DATA); - } - setHasOptionsMenu(true); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_qr_code_display, container, false); - ButterKnife.bind(this, rootView); - - ivQrCode.setImageBitmap(QrCodeGenerator.encodeAsBitmap(json)); - return rootView; - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_qr_code_display, menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.item_qr_code_share: - BitmapDrawable bitmapDrawable = (BitmapDrawable) ivQrCode.getDrawable(); - Uri uri = Utils.getImageUri(getActivity(), bitmapDrawable.getBitmap()); - Intent intent = new Intent(); - intent.setAction(Intent.ACTION_SEND); - intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - intent.setType("image/*"); - intent.putExtra(Intent.EXTRA_STREAM, uri); - startActivity(Intent.createChooser(intent, getString(R.string.choose_option))); - break; - } - return super.onOptionsItemSelected(item); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeDisplayFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeDisplayFragment.kt new file mode 100644 index 0000000000..e589b0d115 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeDisplayFragment.kt @@ -0,0 +1,71 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.graphics.drawable.BitmapDrawable +import android.os.Bundle +import android.view.* +import android.widget.ImageView +import butterknife.BindView +import butterknife.ButterKnife +import org.mifos.mobile.R +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.QrCodeGenerator +import org.mifos.mobile.utils.Utils + +/** + * Created by dilpreet on 16/8/17. + */ +class QrCodeDisplayFragment : BaseFragment() { + @kotlin.jvm.JvmField + @BindView(R.id.iv_qr_code) + var ivQrCode: ImageView? = null + private var rootView: View? = null + private var json: String? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + json = arguments?.getString(Constants.QR_DATA) + } + setHasOptionsMenu(true) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_qr_code_display, container, false) + ButterKnife.bind(this, rootView!!) + ivQrCode?.setImageBitmap(QrCodeGenerator.encodeAsBitmap(json)) + return rootView + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + super.onCreateOptionsMenu(menu, inflater) + inflater.inflate(R.menu.menu_qr_code_display, menu) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + R.id.item_qr_code_share -> { + val bitmapDrawable = ivQrCode?.drawable as BitmapDrawable + val uri = Utils.getImageUri(activity, bitmapDrawable.bitmap) + val intent = Intent() + intent.action = Intent.ACTION_SEND + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + intent.type = "image/*" + intent.putExtra(Intent.EXTRA_STREAM, uri) + startActivity(Intent.createChooser(intent, getString(R.string.choose_option))) + } + } + return super.onOptionsItemSelected(item) + } + + companion object { + fun newInstance(json: String?): QrCodeDisplayFragment { + val fragment = QrCodeDisplayFragment() + val args = Bundle() + args.putString(Constants.QR_DATA, json) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeImportFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeImportFragment.java deleted file mode 100644 index 5e21c2424a..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeImportFragment.java +++ /dev/null @@ -1,213 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.RectF; -import android.net.Uri; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; -import com.google.zxing.Result; -import com.isseiaoki.simplecropview.CropImageView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.presenters.QrCodeImportPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.BeneficiaryState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.QrCodeImportView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.Toaster; - -import java.io.FileNotFoundException; -import java.io.InputStream; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - - -/** - * Created by manishkumar on 19/05/18. - */ - -public class QrCodeImportFragment extends BaseFragment implements QrCodeImportView { - - private View rootView; - private Uri qrUri; - private String uriValue; - private RectF mFrameRect = null; - private InputStream inputStream = null; - - - @BindView(R.id.iv_crop_qr_code) - CropImageView cropImageView; - - @Inject - QrCodeImportPresenter qrCodeImportPresenter; - - public static QrCodeImportFragment newInstance(Uri uri) { - - QrCodeImportFragment fragment = new QrCodeImportFragment(); - Bundle args = new Bundle(); - args.putString(Constants.QR_IMAGE_URI, uri.toString()); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - uriValue = getArguments().getString(Constants.QR_IMAGE_URI); - qrUri = Uri.parse(uriValue); - } - setHasOptionsMenu(true); - } - - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, - @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - - rootView = inflater.inflate(R.layout.fragment_qr_code_import, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - setToolbarTitle(getString(R.string.import_qr)); - - ButterKnife.bind(this, rootView); - //load the uri - - setBitmapImage(qrUri); - cropImageView.setCompressFormat(Bitmap.CompressFormat.JPEG); - cropImageView.setOutputMaxSize(150, 150); - cropImageView.load(qrUri) - .initialFrameRect(mFrameRect) - .executeAsCompletable(); - cropImageView.setCropMode(CropImageView.CropMode.FREE); - cropImageView.setInitialFrameScale(0.8f); - qrCodeImportPresenter.attachView(this); - return rootView; - } - - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - // save data - outState.putParcelable(Constants.FRAME_RECT, cropImageView.getActualCropRect()); - outState.putParcelable(Constants.SOURCE_URI, cropImageView.getSourceUri()); - } - - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - // restore data - mFrameRect = savedInstanceState.getParcelable(Constants.FRAME_RECT); - qrUri = savedInstanceState.getParcelable(Constants.SOURCE_URI); - } - } - - - @OnClick(R.id.btn_proceed) - public void proceed() { - qrCodeImportPresenter.getDecodedResult(qrUri, cropImageView); - } - - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showErrorReadingQr(String message) { - Toaster.show(rootView, message); - } - - - /** - * CallBack for{@link CropImageView} which retrieves data from QRCode - * Opens {@link BeneficiaryApplicationFragment} with {@link BeneficiaryState} as - * {@code BeneficiaryState.CREATE_QR} - * - * @param result contains the results from decoded QR bitmap - */ - @Override - public void handleDecodedResult(Result result) { - - Gson gson = new Gson(); - try { - Beneficiary beneficiary = gson.fromJson(result.getText(), Beneficiary.class); - getActivity().getSupportFragmentManager().popBackStack(); - ((BaseActivity) getActivity()).replaceFragment(BeneficiaryApplicationFragment. - newInstance(BeneficiaryState.CREATE_QR, beneficiary), - true, R.id.container); - } catch (JsonSyntaxException e) { - Toast.makeText(getActivity(), getString(R.string.invalid_qr), - Toast.LENGTH_SHORT).show(); - } - } - - - /** - * Shows {@link org.mifos.mobile.utils.ProgressBarHandler} - */ - @Override - public void showProgress() { - showProgressBar(); - } - - - /** - * Hides {@link org.mifos.mobile.utils.ProgressBarHandler} - */ - @Override - public void hideProgress() { - hideProgressBar(); - } - - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - qrCodeImportPresenter.detachView(); - } - - /** - * Initializing UI - * - * @param qrImageUri contains Uri of qr code image - */ - public void setBitmapImage(Uri qrImageUri) { - try { - inputStream = getContext().getContentResolver().openInputStream(qrImageUri); - } catch (FileNotFoundException e) { - Toaster.show(rootView, getString(R.string.error_fetching_image)); - } - - Bitmap b = BitmapFactory.decodeStream(inputStream, null, null); - try { - if (inputStream != null) { - inputStream.close(); - } - } catch (Exception e) { - Toaster.show(rootView, getString(R.string.error_fetching_image)); - } - cropImageView.setImageBitmap(b); - - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeImportFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeImportFragment.kt new file mode 100644 index 0000000000..ecd730bc10 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeImportFragment.kt @@ -0,0 +1,184 @@ +package org.mifos.mobile.ui.fragments + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.RectF +import android.net.Uri +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.google.gson.Gson +import com.google.gson.JsonSyntaxException +import com.google.zxing.Result + +import com.isseiaoki.simplecropview.CropImageView + +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.presenters.QrCodeImportPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.BeneficiaryState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.QrCodeImportView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.Toaster + +import java.io.FileNotFoundException +import java.io.InputStream +import javax.inject.Inject + +/** + * Created by manishkumar on 19/05/18. + */ +class QrCodeImportFragment : BaseFragment(), QrCodeImportView { + + private var rootView: View? = null + private lateinit var qrUri: Uri + private var uriValue: String? = null + private var mFrameRect: RectF? = null + private var inputStream: InputStream? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_crop_qr_code) + var cropImageView: CropImageView? = null + + @kotlin.jvm.JvmField + @Inject + var qrCodeImportPresenter: QrCodeImportPresenter? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + uriValue = arguments?.getString(Constants.QR_IMAGE_URI) + qrUri = Uri.parse(uriValue) + } + setHasOptionsMenu(true) + } + + override fun onCreateView(inflater: LayoutInflater, + container: ViewGroup?, savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_qr_code_import, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + setToolbarTitle(getString(R.string.import_qr)) + ButterKnife.bind(this, rootView!!) + //load the uri + setBitmapImage(qrUri) + cropImageView?.setCompressFormat(Bitmap.CompressFormat.JPEG) + cropImageView?.setOutputMaxSize(150, 150) + cropImageView?.load(qrUri) + ?.initialFrameRect(mFrameRect) + ?.executeAsCompletable() + cropImageView?.setCropMode(CropImageView.CropMode.FREE) + cropImageView?.setInitialFrameScale(0.8f) + qrCodeImportPresenter?.attachView(this) + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + // save data + outState.putParcelable(Constants.FRAME_RECT, cropImageView?.actualCropRect) + outState.putParcelable(Constants.SOURCE_URI, cropImageView?.sourceUri) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + // restore data + mFrameRect = savedInstanceState.getParcelable(Constants.FRAME_RECT) + qrUri = savedInstanceState.getParcelable(Constants.SOURCE_URI) + } + } + + @OnClick(R.id.btn_proceed) + fun proceed() { + qrCodeImportPresenter?.getDecodedResult(qrUri, cropImageView) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showErrorReadingQr(message: String?) { + Toaster.show(rootView, message) + } + + /** + * CallBack for[CropImageView] which retrieves data from QRCode + * Opens [BeneficiaryApplicationFragment] with [BeneficiaryState] as + * `BeneficiaryState.CREATE_QR` + * + * @param result contains the results from decoded QR bitmap + */ + override fun handleDecodedResult(result: Result?) { + val gson = Gson() + try { + val beneficiary = gson.fromJson(result?.text, Beneficiary::class.java) + activity?.supportFragmentManager?.popBackStack() + (activity as BaseActivity?)?.replaceFragment(BeneficiaryApplicationFragment.newInstance(BeneficiaryState.CREATE_QR, beneficiary), + true, R.id.container) + } catch (e: JsonSyntaxException) { + Toast.makeText(activity, getString(R.string.invalid_qr), + Toast.LENGTH_SHORT).show() + } + } + + /** + * Shows [org.mifos.mobile.utils.ProgressBarHandler] + */ + override fun showProgress() { + showProgressBar() + } + + /** + * Hides [org.mifos.mobile.utils.ProgressBarHandler] + */ + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + qrCodeImportPresenter?.detachView() + } + + /** + * Initializing UI + * + * @param qrImageUri contains Uri of qr code image + */ + private fun setBitmapImage(qrImageUri: Uri) { + try { + inputStream = context?.contentResolver?.openInputStream(qrImageUri) + } catch (e: FileNotFoundException) { + Toaster.show(rootView, getString(R.string.error_fetching_image)) + } + val b = BitmapFactory.decodeStream(inputStream, null, null) + try { + if (inputStream != null) { + inputStream?.close() + } + } catch (e: Exception) { + Toaster.show(rootView, getString(R.string.error_fetching_image)) + } + cropImageView?.imageBitmap = b + } + + companion object { + fun newInstance(uri: Uri): QrCodeImportFragment { + val fragment = QrCodeImportFragment() + val args = Bundle() + args.putString(Constants.QR_IMAGE_URI, uri.toString()) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeReaderFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeReaderFragment.java deleted file mode 100644 index a82aa2eab8..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeReaderFragment.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; -import com.google.zxing.Result; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.BeneficiaryState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; - -import androidx.annotation.Nullable; -import me.dm7.barcodescanner.zxing.ZXingScannerView; - -/** - * Created by dilpreet on 6/7/17. - */ - -public class QrCodeReaderFragment extends BaseFragment implements ZXingScannerView.ResultHandler { - - private ZXingScannerView mScannerView; - - public static QrCodeReaderFragment newInstance() { - QrCodeReaderFragment fragment = new QrCodeReaderFragment(); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - mScannerView = new ZXingScannerView(getActivity()); - mScannerView.setAutoFocus(true); - return mScannerView; - } - - /** - * Sets the {@link me.dm7.barcodescanner.zxing.ZXingScannerView.ResultHandler} callback and - * opens Camera - */ - @Override - public void onResume() { - super.onResume(); - mScannerView.setResultHandler(this); - mScannerView.startCamera(); - } - - /** - * Closes the Camera - */ - @Override - public void onPause() { - super.onPause(); - mScannerView.stopCamera(); - } - - /** - * Callback for {@link ZXingScannerView} which retrieves data from QRCode - * - * @param result Contains data scanned from QRCode - */ - @Override - public void handleResult(Result result) { - Gson gson = new Gson(); - try { - Beneficiary beneficiary = gson.fromJson(result.getText(), Beneficiary.class); - getActivity().getSupportFragmentManager().popBackStack(); - ((BaseActivity) getActivity()).replaceFragment(BeneficiaryApplicationFragment. - newInstance(BeneficiaryState.CREATE_QR, beneficiary), true, R.id.container); - } catch (JsonSyntaxException e) { - Toast.makeText(getActivity(), getString(R.string.invalid_qr), - Toast.LENGTH_SHORT).show(); - mScannerView.resumeCameraPreview(this); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeReaderFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeReaderFragment.kt new file mode 100644 index 0000000000..f1de7192d9 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/QrCodeReaderFragment.kt @@ -0,0 +1,76 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast + +import com.google.gson.Gson +import com.google.gson.JsonSyntaxException +import com.google.zxing.Result + +import me.dm7.barcodescanner.zxing.ZXingScannerView +import me.dm7.barcodescanner.zxing.ZXingScannerView.ResultHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.BeneficiaryState +import org.mifos.mobile.ui.fragments.base.BaseFragment + +/** + * Created by dilpreet on 6/7/17. + */ +class QrCodeReaderFragment : BaseFragment(), ResultHandler { + + private var mScannerView: ZXingScannerView? = null + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + mScannerView = ZXingScannerView(activity) + mScannerView?.setAutoFocus(true) + return mScannerView + } + + /** + * Sets the [me.dm7.barcodescanner.zxing.ZXingScannerView.ResultHandler] callback and + * opens Camera + */ + override fun onResume() { + super.onResume() + mScannerView?.setResultHandler(this) + mScannerView?.startCamera() + } + + /** + * Closes the Camera + */ + override fun onPause() { + super.onPause() + mScannerView?.stopCamera() + } + + /** + * Callback for [ZXingScannerView] which retrieves data from QRCode + * + * @param result Contains data scanned from QRCode + */ + override fun handleResult(result: Result) { + val gson = Gson() + try { + val beneficiary = gson.fromJson(result.text, Beneficiary::class.java) + activity?.supportFragmentManager?.popBackStack() + (activity as BaseActivity?)?.replaceFragment(BeneficiaryApplicationFragment.newInstance(BeneficiaryState.CREATE_QR, beneficiary), true, R.id.container) + } catch (e: JsonSyntaxException) { + Toast.makeText(activity, getString(R.string.invalid_qr), + Toast.LENGTH_SHORT).show() + mScannerView?.resumeCameraPreview(this) + } + } + + companion object { + fun newInstance(): QrCodeReaderFragment { + return QrCodeReaderFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/RecentTransactionsFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/RecentTransactionsFragment.java deleted file mode 100644 index de47363168..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/RecentTransactionsFragment.java +++ /dev/null @@ -1,244 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.os.Parcelable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.Transaction; -import org.mifos.mobile.presenters.RecentTransactionsPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.RecentTransactionListAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.RecentTransactionsView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DividerItemDecoration; -import org.mifos.mobile.utils.EndlessRecyclerViewScrollListener; -import org.mifos.mobile.utils.Network; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * @author Vishwwajeet - * @since 09/08/16 - */ -public class RecentTransactionsFragment extends BaseFragment implements RecentTransactionsView, - SwipeRefreshLayout.OnRefreshListener { - - @BindView(R.id.rv_recent_transactions) - RecyclerView rvRecentTransactions; - - @BindView(R.id.swipe_transaction_container) - SwipeRefreshLayout swipeTransactionContainer; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - RecentTransactionsPresenter recentTransactionsPresenter; - - @Inject - RecentTransactionListAdapter recentTransactionsListAdapter; - - private SweetUIErrorHandler sweetUIErrorHandler; - - private View rootView; - - private List recentTransactionList; - - public static RecentTransactionsFragment newInstance() { - RecentTransactionsFragment fragment = new RecentTransactionsFragment(); - Bundle args = new Bundle(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - recentTransactionList = new ArrayList<>(); - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_recent_transactions, container, false); - - ButterKnife.bind(this, rootView); - recentTransactionsPresenter.attachView(this); - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - - showUserInterface(); - setToolbarTitle(getString(R.string.recent_transactions)); - if (savedInstanceState == null) { - recentTransactionsPresenter.loadRecentTransactions(false, 0); - } - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelableArrayList(Constants.RECENT_TRANSACTIONS, new ArrayList( - recentTransactionList)); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - List transactions = savedInstanceState.getParcelableArrayList(Constants. - RECENT_TRANSACTIONS); - showRecentTransactions(transactions); - } - } - - /** - * Setting up {@code rvRecentTransactions} - */ - @Override - public void showUserInterface() { - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - rvRecentTransactions.setLayoutManager(layoutManager); - rvRecentTransactions.setHasFixedSize(true); - rvRecentTransactions.addItemDecoration(new DividerItemDecoration(getActivity(), - layoutManager.getOrientation())); - recentTransactionsListAdapter.setTransactions(recentTransactionList); - rvRecentTransactions.setAdapter(recentTransactionsListAdapter); - rvRecentTransactions.addOnScrollListener( - new EndlessRecyclerViewScrollListener(layoutManager) { - @Override - public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { - recentTransactionsPresenter.loadRecentTransactions(true, totalItemsCount); - } - }); - swipeTransactionContainer.setColorSchemeColors(getActivity() - .getResources().getIntArray(R.array.swipeRefreshColors)); - swipeTransactionContainer.setOnRefreshListener(this); - } - - /** - * Refreshes the List of {@link Transaction} - */ - @Override - public void onRefresh() { - if (layoutError.getVisibility() == View.VISIBLE) { - resetUI(); - } - recentTransactionsPresenter.loadRecentTransactions(false, 0); - } - - /** - * Shows a Toast - */ - @Override - public void showMessage(String message) { - ((BaseActivity) getActivity()).showToast(message); - } - - /** - * Updates {@code recentTransactionsListAdapter} with {@code recentTransactionList} fetched from - * server - * - * @param recentTransactionList List of {@link Transaction} - */ - @Override - public void showRecentTransactions(List recentTransactionList) { - this.recentTransactionList = recentTransactionList; - recentTransactionsListAdapter.setTransactions(recentTransactionList); - } - - /** - * Appends more Transactions in {@code recentTransactionList} - * - * @param transactions List of {@link Transaction} - */ - @Override - public void showLoadMoreRecentTransactions(List transactions) { - this.recentTransactionList.addAll(recentTransactionList); - recentTransactionsListAdapter.notifyDataSetChanged(); - } - - @Override - public void resetUI() { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvRecentTransactions, layoutError); - } - - /** - * Hides {@code rvRecentTransactions} and shows a textview prompting no transactions - */ - @Override - public void showEmptyTransaction() { - sweetUIErrorHandler.showSweetEmptyUI(getString(R.string.recent_transactions), - R.drawable.ic_label_black_24dp, rvRecentTransactions, layoutError); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showErrorFetchingRecentTransactions(String message) { - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(rvRecentTransactions, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, rvRecentTransactions, layoutError); - } - } - - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvRecentTransactions, layoutError); - recentTransactionsPresenter.loadRecentTransactions(false, 0); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void showProgress() { - showSwipeRefreshLayout(true); - } - - @Override - public void hideProgress() { - showSwipeRefreshLayout(false); - } - - @Override - public void showSwipeRefreshLayout(final boolean show) { - swipeTransactionContainer.post(new Runnable() { - @Override - public void run() { - swipeTransactionContainer.setRefreshing(show); - } - }); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - recentTransactionsPresenter.detachView(); - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/RecentTransactionsFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/RecentTransactionsFragment.kt new file mode 100644 index 0000000000..b56f2cbe5e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/RecentTransactionsFragment.kt @@ -0,0 +1,220 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.os.Parcelable +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast + +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.Transaction +import org.mifos.mobile.presenters.RecentTransactionsPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.RecentTransactionListAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.RecentTransactionsView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DividerItemDecoration +import org.mifos.mobile.utils.EndlessRecyclerViewScrollListener +import org.mifos.mobile.utils.Network.isConnected + +import javax.inject.Inject + +/** + * @author Vishwwajeet + * @since 09/08/16 + */ +class RecentTransactionsFragment : BaseFragment(), RecentTransactionsView, OnRefreshListener { + + @JvmField + @BindView(R.id.rv_recent_transactions) + var rvRecentTransactions: RecyclerView? = null + + @JvmField + @BindView(R.id.swipe_transaction_container) + var swipeTransactionContainer: SwipeRefreshLayout? = null + + @JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @JvmField + @Inject + var recentTransactionsPresenter: RecentTransactionsPresenter? = null + + @JvmField + @Inject + var recentTransactionsListAdapter: RecentTransactionListAdapter? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + private var rootView: View? = null + private var recentTransactionList: MutableList? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + (activity as BaseActivity?)?.activityComponent?.inject(this) + recentTransactionList = ArrayList() + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_recent_transactions, container, false) + ButterKnife.bind(this, rootView!!) + recentTransactionsPresenter?.attachView(this) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + showUserInterface() + setToolbarTitle(getString(R.string.recent_transactions)) + if (savedInstanceState == null) { + recentTransactionsPresenter?.loadRecentTransactions(false, 0) + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelableArrayList(Constants.RECENT_TRANSACTIONS, ArrayList( + recentTransactionList)) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + val transactions: List = savedInstanceState.getParcelableArrayList(Constants.RECENT_TRANSACTIONS) + showRecentTransactions(transactions) + } + } + + /** + * Setting up `rvRecentTransactions` + */ + override fun showUserInterface() { + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = LinearLayoutManager.VERTICAL + rvRecentTransactions?.layoutManager = layoutManager + rvRecentTransactions?.setHasFixedSize(true) + rvRecentTransactions?.addItemDecoration(DividerItemDecoration(activity!!, + layoutManager.orientation)) + recentTransactionsListAdapter?.setTransactions(recentTransactionList) + rvRecentTransactions?.adapter = recentTransactionsListAdapter + rvRecentTransactions?.addOnScrollListener( + object : EndlessRecyclerViewScrollListener(layoutManager) { + override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) { + recentTransactionsPresenter?.loadRecentTransactions(true, totalItemsCount) + } + }) + swipeTransactionContainer?.setColorSchemeColors(*activity!! + .resources.getIntArray(R.array.swipeRefreshColors)) + swipeTransactionContainer?.setOnRefreshListener(this) + } + + /** + * Refreshes the List of [Transaction] + */ + override fun onRefresh() { + if (layoutError?.visibility == View.VISIBLE) { + resetUI() + } + recentTransactionsPresenter?.loadRecentTransactions(false, 0) + } + + /** + * Shows a Toast + */ + override fun showMessage(message: String?) { + (activity as BaseActivity?)?.showToast(message!!) + } + + /** + * Updates `recentTransactionsListAdapter` with `recentTransactionList` fetched from + * server + * + * @param recentTransactionList List of [Transaction] + */ + override fun showRecentTransactions(recentTransactionList: List?) { + this.recentTransactionList = recentTransactionList as MutableList? + recentTransactionsListAdapter?.setTransactions(recentTransactionList) + } + + /** + * Appends more Transactions in `recentTransactionList` + * + * @param transactions List of [Transaction] + */ + override fun showLoadMoreRecentTransactions(transactions: List?) { + this.recentTransactionList?.addAll(recentTransactionList!!) + recentTransactionsListAdapter?.notifyDataSetChanged() + } + + override fun resetUI() { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvRecentTransactions, layoutError) + } + + /** + * Hides `rvRecentTransactions` and shows a textview prompting no transactions + */ + override fun showEmptyTransaction() { + sweetUIErrorHandler?.showSweetEmptyUI(getString(R.string.recent_transactions), + R.drawable.ic_label_black_24dp, rvRecentTransactions, layoutError) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showErrorFetchingRecentTransactions(message: String?) { + if (!isConnected(activity!!)) { + sweetUIErrorHandler?.showSweetNoInternetUI(rvRecentTransactions, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(message, rvRecentTransactions, layoutError) + } + } + + @OnClick(R.id.btn_try_again) + fun retryClicked() { + if (isConnected(context!!)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvRecentTransactions, layoutError) + recentTransactionsPresenter?.loadRecentTransactions(false, 0) + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + override fun showProgress() { + showSwipeRefreshLayout(true) + } + + override fun hideProgress() { + showSwipeRefreshLayout(false) + } + + override fun showSwipeRefreshLayout(show: Boolean) { + swipeTransactionContainer?.post { swipeTransactionContainer?.isRefreshing = show } + } + + override fun onDestroyView() { + super.onDestroyView() + recentTransactionsPresenter?.detachView() + } + + companion object { + fun newInstance(): RecentTransactionsFragment { + val fragment = RecentTransactionsFragment() + val args = Bundle() + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationFragment.java deleted file mode 100644 index 3be0e4f78a..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationFragment.java +++ /dev/null @@ -1,264 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.text.Editable; -import android.text.TextWatcher; -import android.util.Patterns; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.ProgressBar; -import android.widget.RadioButton; -import android.widget.RadioGroup; -import android.widget.TextView; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.register.RegisterPayload; -import org.mifos.mobile.presenters.RegistrationPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.RegistrationView; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.PasswordStrength; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 31/7/17. - */ - -public class RegistrationFragment extends BaseFragment implements RegistrationView { - - @BindView(R.id.et_account_number) - EditText etAccountNumber; - - @BindView(R.id.et_username) - EditText etUsername; - - @BindView(R.id.et_first_name) - EditText etFirstName; - - @BindView(R.id.et_last_name) - EditText etLastName; - - @BindView(R.id.et_phone_number) - EditText etPhoneNumber; - - @BindView(R.id.et_email) - EditText etEmail; - - @BindView(R.id.et_password) - EditText etPassword; - - @BindView(R.id.et_confirm_password) - EditText etConfirmPassword; - - @BindView(R.id.rg_verification_mode) - RadioGroup rgVerificationMode; - - @Inject - RegistrationPresenter presenter; - - @BindView(R.id.progressBar) - ProgressBar progressBar; - - @BindView(R.id.password_strength) - TextView strengthView; - - - private View rootView; - - public static RegistrationFragment newInstance() { - RegistrationFragment fragment = new RegistrationFragment(); - return fragment; - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_registration, container, false); - - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - presenter.attachView(this); - - progressBar.setVisibility(View.GONE); - strengthView.setVisibility(View.GONE); - - etPassword.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { - if (charSequence.length() == 0) { - progressBar.setVisibility(View.GONE); - strengthView.setVisibility(View.GONE); - } else { - progressBar.setVisibility(View.VISIBLE); - strengthView.setVisibility(View.VISIBLE); - updatePasswordStrengthView(charSequence.toString()); - } - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - - return rootView; - } - - private void updatePasswordStrengthView(String password) { - if (TextView.VISIBLE != strengthView.getVisibility()) - return; - - if (password.isEmpty()) { - strengthView.setText(""); - progressBar.setProgress(0); - return; - } - - PasswordStrength str = PasswordStrength.calculateStrength(password); - strengthView.setText(str.getText(getContext())); - strengthView.setTextColor(str.getColor()); - - PorterDuff.Mode mode = android.graphics.PorterDuff.Mode.SRC_IN; - progressBar.getProgressDrawable().setColorFilter(str.getColor(), mode); - if (str.getText(getContext()).equals(getString(R.string.password_strength_weak))) { - progressBar.setProgress(25); - } else if (str.getText(getContext()).equals(getString(R.string.password_strength_medium))) { - progressBar.setProgress(50); - } else if (str.getText(getContext()).equals(getString(R.string.password_strength_strong))) { - progressBar.setProgress(75); - } else { - progressBar.setProgress(100); - } - } - - @OnClick(R.id.btn_register) - public void registerClicked() { - - if (areFieldsValidated()) { - - RadioButton radioButton = rootView.findViewById(rgVerificationMode. - getCheckedRadioButtonId()); - - RegisterPayload payload = new RegisterPayload(); - payload.setAccountNumber(etAccountNumber.getText().toString()); - payload.setAuthenticationMode(radioButton.getText().toString()); - payload.setEmail(etEmail.getText().toString()); - payload.setFirstName(etFirstName.getText().toString()); - payload.setLastName(etLastName.getText().toString()); - payload.setMobileNumber(etPhoneNumber.getText().toString()); - if (!etPassword.getText().toString().equals(etConfirmPassword.getText().toString())) { - Toaster.show(rootView, getString(R.string.error_password_not_match)); - return; - } else { - payload.setPassword(etPassword.getText().toString()); - } - payload.setPassword(etPassword.getText().toString()); - payload.setUsername(etUsername.getText().toString().replace(" ", "")); - - if (Network.isConnected(getContext())) { - presenter.registerUser(payload); - } else { - Toaster.show(rootView, getString(R.string.no_internet_connection)); - } - } - - } - - private boolean areFieldsValidated() { - - if (etAccountNumber.getText().toString().trim().length() == 0) { - Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string. - account_number))); - return false; - } else if (etUsername.getText().toString().trim().length() == 0) { - Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string. - username))); - return false; - } else if (etUsername.getText().toString().trim().length() < 6) { - Toaster.show(rootView, getString(R.string.error_username_greater_than_six)); - return false; - } else if (etUsername.getText().toString().trim().contains(" ")) { - Toaster.show(rootView, getString(R.string.error_validation_cannot_contain_spaces, - getString(R.string.username), getString(R.string.not_contain_username))); - return false; - } else if (etFirstName.getText().length() == 0) { - Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string. - first_name))); - return false; - } else if (etLastName.getText().toString().trim().length() == 0) { - Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string. - last_name))); - return false; - } else if (etEmail.getText().toString().trim().length() == 0) { - Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string. - email))); - return false; - } else if (etPassword.getText().toString().trim().length() == 0) { - Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string. - password))); - return false; - } else if (etPassword.getText().toString().trim().length() - < etPassword.getText().toString().length()) { - Toaster.show(rootView, - getString(R.string.error_validation_cannot_contain_leading_or_trailing_spaces, - getString(R.string.password))); - return false; - } else if (!Patterns.EMAIL_ADDRESS.matcher(etEmail.getText().toString().trim()) - .matches()) { - Toaster.show(rootView, getString(R.string.error_invalid_email)); - return false; - } else if (etPassword.getText().toString().trim().length() < 6) { - Toaster.show(rootView, getString(R.string.error_validation_minimum_chars, - getString(R.string.password), getResources(). - getInteger(R.integer.password_minimum_length))); - return false; - } - - return true; - } - - @Override - public void showRegisteredSuccessfully() { - ((BaseActivity) getActivity()).replaceFragment(RegistrationVerificationFragment. - newInstance(), true, R.id.container); - } - - @Override - public void showError(String msg) { - Toaster.show(rootView, msg); - } - - @Override - public void showProgress() { - showMifosProgressDialog(getString(R.string.sign_up)); - } - - @Override - public void hideProgress() { - hideMifosProgressDialog(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationFragment.kt new file mode 100644 index 0000000000..26af9686f3 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationFragment.kt @@ -0,0 +1,232 @@ +package org.mifos.mobile.ui.fragments + +import android.graphics.PorterDuff +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.util.Patterns +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.* + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.models.register.RegisterPayload +import org.mifos.mobile.presenters.RegistrationPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.RegistrationView +import org.mifos.mobile.utils.Network +import org.mifos.mobile.utils.PasswordStrength +import org.mifos.mobile.utils.Toaster + +import javax.inject.Inject + +/** + * Created by dilpreet on 31/7/17. + */ +class RegistrationFragment : BaseFragment(), RegistrationView { + @JvmField + @BindView(R.id.et_account_number) + var etAccountNumber: EditText? = null + + @JvmField + @BindView(R.id.et_username) + var etUsername: EditText? = null + + @JvmField + @BindView(R.id.et_first_name) + var etFirstName: EditText? = null + + @JvmField + @BindView(R.id.et_last_name) + var etLastName: EditText? = null + + @JvmField + @BindView(R.id.et_phone_number) + var etPhoneNumber: EditText? = null + + @JvmField + @BindView(R.id.et_email) + var etEmail: EditText? = null + + @JvmField + @BindView(R.id.et_password) + var etPassword: EditText? = null + + @JvmField + @BindView(R.id.et_confirm_password) + var etConfirmPassword: EditText? = null + + @JvmField + @BindView(R.id.rg_verification_mode) + var rgVerificationMode: RadioGroup? = null + + @JvmField + @Inject + var presenter: RegistrationPresenter? = null + + @JvmField + @BindView(R.id.progressBar) + var progressBar: ProgressBar? = null + + @JvmField + @BindView(R.id.password_strength) + var strengthView: TextView? = null + private var rootView: View? = null + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_registration, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + val rootView = this.rootView + if (rootView != null) { + ButterKnife.bind(this, rootView) + } + presenter?.attachView(this) + progressBar?.visibility = View.GONE + strengthView?.visibility = View.GONE + etPassword?.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} + override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) { + if (charSequence.isEmpty()) { + progressBar?.visibility = View.GONE + strengthView?.visibility = View.GONE + } else { + progressBar?.visibility = View.VISIBLE + strengthView?.visibility = View.VISIBLE + updatePasswordStrengthView(charSequence.toString()) + } + } + + override fun afterTextChanged(editable: Editable) {} + }) + return rootView + } + + private fun updatePasswordStrengthView(password: String) { + if (TextView.VISIBLE != strengthView?.visibility) return + if (password.isEmpty()) { + strengthView?.text = "" + progressBar?.progress = 0 + return + } + val str = PasswordStrength.calculateStrength(password) + strengthView?.text = str.getText(context) + strengthView?.setTextColor(str.color) + val mode = PorterDuff.Mode.SRC_IN + progressBar?.progressDrawable?.setColorFilter(str.color, mode) + if (str.getText(context) == getString(R.string.password_strength_weak)) { + progressBar?.progress = 25 + } else if (str.getText(context) == getString(R.string.password_strength_medium)) { + progressBar?.progress = 50 + } else if (str.getText(context) == getString(R.string.password_strength_strong)) { + progressBar?.progress = 75 + } else { + progressBar?.progress = 100 + } + } + + @OnClick(R.id.btn_register) + fun registerClicked() { + if (areFieldsValidated()) { + val radioButton = rgVerificationMode?.checkedRadioButtonId?.let { rootView?.findViewById(it) } + val payload = RegisterPayload() + payload.accountNumber = etAccountNumber?.text.toString() + payload.authenticationMode = radioButton?.text.toString() + payload.email = etEmail?.text.toString() + payload.firstName = etFirstName?.text.toString() + payload.lastName = etLastName?.text.toString() + payload.mobileNumber = etPhoneNumber?.text.toString() + if (etPassword?.text.toString() != etConfirmPassword?.text.toString()) { + Toaster.show(rootView, getString(R.string.error_password_not_match)) + return + } else { + payload.password = etPassword?.text.toString() + } + payload.password = etPassword?.text.toString() + payload.username = etUsername?.text.toString().replace(" ", "") + if (Network.isConnected(context)) { + presenter?.registerUser(payload) + } else { + Toaster.show(rootView, getString(R.string.no_internet_connection)) + } + } + } + + private fun areFieldsValidated(): Boolean { + if (etAccountNumber?.text.toString().trim { it <= ' ' }.isEmpty()) { + Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string.account_number))) + return false + } else if (etUsername?.text.toString().trim { it <= ' ' }.isEmpty()) { + Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string.username))) + return false + } else if (etUsername?.text.toString().trim { it <= ' ' }.length < 6) { + Toaster.show(rootView, getString(R.string.error_username_greater_than_six)) + return false + } else if (etUsername?.text.toString().trim { it <= ' ' }.contains(" ")) { + Toaster.show(rootView, getString(R.string.error_validation_cannot_contain_spaces, + getString(R.string.username), getString(R.string.not_contain_username))) + return false + } else if (etFirstName?.text?.isEmpty() == true) { + Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string.first_name))) + return false + } else if (etLastName?.text.toString().trim { it <= ' ' }.isEmpty()) { + Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string.last_name))) + return false + } else if (etEmail?.text.toString().trim { it <= ' ' }.isEmpty()) { + Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string.email))) + return false + } else if (etPassword?.text.toString().trim { it <= ' ' }.isEmpty()) { + Toaster.show(rootView, getString(R.string.error_validation_blank, getString(R.string.password))) + return false + } else if (etPassword?.text.toString().trim { it <= ' ' }.length + < etPassword?.text.toString().length) { + Toaster.show(rootView, + getString(R.string.error_validation_cannot_contain_leading_or_trailing_spaces, + getString(R.string.password))) + return false + } else if (!Patterns.EMAIL_ADDRESS.matcher(etEmail?.text.toString().trim { it <= ' ' }) + .matches()) { + Toaster.show(rootView, getString(R.string.error_invalid_email)) + return false + } else if (etPassword?.text.toString().trim { it <= ' ' }.length < 6) { + Toaster.show(rootView, getString(R.string.error_validation_minimum_chars, + getString(R.string.password), resources.getInteger(R.integer.password_minimum_length))) + return false + } + return true + } + + override fun showRegisteredSuccessfully() { + (activity as BaseActivity?)?.replaceFragment(RegistrationVerificationFragment.newInstance(), true, R.id.container) + } + + override fun showError(msg: String?) { + Toaster.show(rootView, msg) + } + + override fun showProgress() { + showMifosProgressDialog(getString(R.string.sign_up)) + } + + override fun hideProgress() { + hideMifosProgressDialog() + } + + override fun onDestroyView() { + super.onDestroyView() + presenter?.detachView() + } + + companion object { + fun newInstance(): RegistrationFragment { + return RegistrationFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationVerificationFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationVerificationFragment.java deleted file mode 100644 index f23580981b..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationVerificationFragment.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.Intent; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; -import android.widget.Toast; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.register.UserVerify; -import org.mifos.mobile.presenters.RegistrationVerificationPresenter; -import org.mifos.mobile.ui.activities.LoginActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.RegistrationVerificationView; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 31/7/17. - */ - -public class RegistrationVerificationFragment extends BaseFragment implements - RegistrationVerificationView { - - @BindView(R.id.et_request_id) - EditText etRequestId; - - @BindView(R.id.et_authentication_token) - EditText etToken; - - @Inject - RegistrationVerificationPresenter presenter; - - private View rootView; - - public static RegistrationVerificationFragment newInstance() { - RegistrationVerificationFragment fragment = new RegistrationVerificationFragment(); - return fragment; - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_registration_verification, container, false); - - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - presenter.attachView(this); - - return rootView; - } - - @OnClick(R.id.btn_verify) - public void verifyClicked() { - UserVerify userVerify = new UserVerify(); - userVerify.setAuthenticationToken(etToken.getText().toString()); - userVerify.setRequestId(etRequestId.getText().toString()); - presenter.verifyUser(userVerify); - } - - @Override - public void showVerifiedSuccessfully() { - startActivity(new Intent(getActivity(), LoginActivity.class)); - Toast.makeText(getContext(), getString(R.string.verified), Toast.LENGTH_SHORT).show(); - getActivity().finish(); - } - - @Override - public void showError(String msg) { - Toaster.show(rootView, msg); - } - - @Override - public void showProgress() { - showMifosProgressDialog(getString(R.string.verifying)); - } - - @Override - public void hideProgress() { - hideMifosProgressDialog(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationVerificationFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationVerificationFragment.kt new file mode 100644 index 0000000000..26ad120abf --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/RegistrationVerificationFragment.kt @@ -0,0 +1,85 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.EditText +import android.widget.Toast +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import org.mifos.mobile.R +import org.mifos.mobile.models.register.UserVerify +import org.mifos.mobile.presenters.RegistrationVerificationPresenter +import org.mifos.mobile.ui.activities.LoginActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.RegistrationVerificationView +import org.mifos.mobile.utils.Toaster +import javax.inject.Inject + +/** + * Created by dilpreet on 31/7/17. + */ +class RegistrationVerificationFragment : BaseFragment(), RegistrationVerificationView { + + @kotlin.jvm.JvmField + @BindView(R.id.et_request_id) + var etRequestId: EditText? = null + + @kotlin.jvm.JvmField + @BindView(R.id.et_authentication_token) + var etToken: EditText? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: RegistrationVerificationPresenter? = null + private var rootView: View? = null + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_registration_verification, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView!!) + presenter?.attachView(this) + return rootView + } + + @OnClick(R.id.btn_verify) + fun verifyClicked() { + val userVerify = UserVerify() + userVerify.authenticationToken = etToken?.text.toString() + userVerify.requestId = etRequestId?.text.toString() + presenter?.verifyUser(userVerify) + } + + override fun showVerifiedSuccessfully() { + startActivity(Intent(activity, LoginActivity::class.java)) + Toast.makeText(context, getString(R.string.verified), Toast.LENGTH_SHORT).show() + activity?.finish() + } + + override fun showError(msg: String?) { + Toaster.show(rootView, msg) + } + + override fun showProgress() { + showMifosProgressDialog(getString(R.string.verifying)) + } + + override fun hideProgress() { + hideMifosProgressDialog() + } + + override fun onDestroyView() { + super.onDestroyView() + presenter?.detachView() + } + + companion object { + fun newInstance(): RegistrationVerificationFragment { + return RegistrationVerificationFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/ReviewLoanApplicationFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/ReviewLoanApplicationFragment.kt index 6d252e1eb1..ccf75df7b8 100644 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/ReviewLoanApplicationFragment.kt +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/ReviewLoanApplicationFragment.kt @@ -1,18 +1,16 @@ package org.mifos.mobile.ui.fragments -import androidx.lifecycle.ViewModelProviders import android.os.Bundle -import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.lifecycle.ViewModelProviders import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.observers.DisposableObserver import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_review_loan_application.* import kotlinx.android.synthetic.main.layout_error.* import okhttp3.ResponseBody - import org.mifos.mobile.R import org.mifos.mobile.models.payload.LoansPayload import org.mifos.mobile.ui.activities.base.BaseActivity @@ -47,12 +45,12 @@ class ReviewLoanApplicationFragment : BaseFragment() { return fragment } - fun newInstance(loanState: LoanState, loansPayload: LoansPayload, loanId: Long, loanName: String, accountNo: String) + fun newInstance(loanState: LoanState?, loansPayload: LoansPayload?, loanId: Long?, loanName: String?, accountNo: String?) : ReviewLoanApplicationFragment { val fragment = ReviewLoanApplicationFragment() val args = Bundle().apply { putSerializable(LOAN_STATE, loanState) - putLong(LOAN_ID, loanId) + if (loanId != null) putLong(LOAN_ID, loanId) putParcelable(LOANS_PAYLOAD, loansPayload) putString(LOAN_NAME, loanName) putString(ACCOUNT_NO, accountNo) @@ -73,7 +71,7 @@ class ReviewLoanApplicationFragment : BaseFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_review_loan_application, container, false) - (activity as BaseActivity).activityComponent.inject(this) + (activity as BaseActivity).activityComponent?.inject(this) viewModel = ViewModelProviders.of(this, viewModelFactory).get(ReviewLoanApplicationViewModel::class.java) val loanState = arguments?.getSerializable(LOAN_STATE) as LoanState if (loanState == LoanState.CREATE) { @@ -107,9 +105,9 @@ class ReviewLoanApplicationFragment : BaseFragment() { btn_loan_submit.setOnClickListener { showProgress() viewModel.submitLoan() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.io()) - .subscribeWith(object : DisposableObserver() { + ?.observeOn(AndroidSchedulers.mainThread()) + ?.subscribeOn(Schedulers.io()) + ?.subscribeWith(object : DisposableObserver() { override fun onComplete() { } @@ -131,10 +129,10 @@ class ReviewLoanApplicationFragment : BaseFragment() { fun showLoanAccountUpdatedSuccessfully() { Toaster.show(rootView, R.string.loan_application_updated_successfully) - activity!!.supportFragmentManager.popBackStack() + activity?.supportFragmentManager?.popBackStack() } - fun showError(message: String) = if (!Network.isConnected(activity)) { + fun showError(message: String?) = if (!Network.isConnected(activity)) { iv_status.setImageResource(R.drawable.ic_error_black_24dp) tv_status.text = getString(R.string.internet_not_connected) ll_add_loan.visibility = View.GONE @@ -155,6 +153,6 @@ class ReviewLoanApplicationFragment : BaseFragment() { fun showLoanAccountCreatedSuccessfully() { Toaster.show(rootView, R.string.loan_application_submitted_successfully) - activity!!.supportFragmentManager.popBackStack() + activity?.supportFragmentManager?.popBackStack() } } diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsDetailFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsDetailFragment.java deleted file mode 100644 index f5a5a18dcc..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsDetailFragment.java +++ /dev/null @@ -1,390 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.accounts.savings.Status; -import org.mifos.mobile.presenters.SavingAccountsDetailPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.AccountType; -import org.mifos.mobile.ui.enums.ChargeType; -import org.mifos.mobile.ui.enums.SavingsAccountState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.SavingAccountsDetailView; -import org.mifos.mobile.utils.CircularImageView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.QrCodeGenerator; -import org.mifos.mobile.utils.SymbolsUtils; -import org.mifos.mobile.utils.Toaster; -import org.mifos.mobile.utils.Utils; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * @author Vishwajeet - * @since 18/8/16. - */ - -public class SavingAccountsDetailFragment extends BaseFragment implements SavingAccountsDetailView { - - @BindView(R.id.tv_account_status) - TextView tvAccountStatus; - - @BindView(R.id.iv_circle_status) - CircularImageView ivCircularStatus; - - @BindView(R.id.tv_total_withdrawals) - TextView tvTotalWithdrawals; - - @BindView(R.id.tv_min_req_bal) - TextView tvMiniRequiredBalance; - - @BindView(R.id.tv_saving_account_number) - TextView tvSavingAccountNumber; - - @BindView(R.id.tv_nominal_interest_rate) - TextView tvNominalInterestRate; - - @BindView(R.id.tv_total_deposits) - TextView tvTotalDeposits; - - @BindView(R.id.tv_acc_balance) - TextView tvAccountBalanceMain; - - @BindView(R.id.tv_last_transaction) - TextView tvLastTransaction; - - @BindView(R.id.made_on) - TextView tvMadeOnTextView; - - @BindView(R.id.tv_made_on) - TextView tvMadeOnTransaction; - - @BindView(R.id.ll_account) - LinearLayout layoutAccount; - - @BindView(R.id.layout_error) - View layoutError; - - @BindView(R.id.tv_minRequiredBalance) - TextView tvMinRequiredBalanceLabel; - - @Inject - PreferencesHelper preferencesHelper; - - @Inject - SavingAccountsDetailPresenter savingAccountsDetailPresenter; - - private View rootView; - private long savingsId; - private Status status; - private SavingsWithAssociations savingsWithAssociations; - private SweetUIErrorHandler sweetUIErrorHandler; - private boolean isMenuVisible = false; - - public static SavingAccountsDetailFragment newInstance(long savingsId) { - SavingAccountsDetailFragment fragment = new SavingAccountsDetailFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.SAVINGS_ID, savingsId); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - savingsId = getArguments().getLong(Constants.SAVINGS_ID); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_saving_account_details, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - setToolbarTitle(getString(R.string.saving_account_details)); - ButterKnife.bind(this, rootView); - savingAccountsDetailPresenter.attachView(this); - sweetUIErrorHandler = new SweetUIErrorHandler(getContext(), rootView); - - if (savedInstanceState == null) { - savingAccountsDetailPresenter.loadSavingsWithAssociations(savingsId); - } - setHasOptionsMenu(true); - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showSavingAccountsDetail((SavingsWithAssociations) savedInstanceState. - getParcelable(Constants.SAVINGS_ACCOUNTS)); - } - } - - /** - * Opens up Phone Dialer - */ - @OnClick(R.id.tv_help_line_number) - void dialHelpLineNumber() { - Intent intent = new Intent(Intent.ACTION_DIAL); - intent.setData(Uri.parse("tel:" + getString(R.string.help_line_number))); - startActivity(intent); - } - - /** - * Opens {@link SavingsMakeTransferFragment} if status is ACTIVE else shows a - * {@link Snackbar} that Account should be Active - */ - @OnClick(R.id.tv_deposit) - void deposit() { - if (status.getActive()) { - ((BaseActivity) getActivity()).replaceFragment(SavingsMakeTransferFragment - .newInstance(savingsId, Constants.TRANSFER_PAY_TO), true, R.id.container); - } else { - Toaster.show(rootView, getString(R.string.account_not_active_to_perform_deposit)); - } - } - - /** - * Opens {@link SavingsMakeTransferFragment} if status is ACTIVE else shows a - * {@link Snackbar} that Account should be Active - */ - @OnClick(R.id.tv_make_a_transfer) - void transfer() { - if (status.getActive()) { - ((BaseActivity) getActivity()).replaceFragment(SavingsMakeTransferFragment - .newInstance(savingsId, Constants.TRANSFER_PAY_FROM), true, R.id.container); - } else { - Toaster.show(rootView, getString(R.string.account_not_active_to_perform_transfer)); - } - } - - /** - * Sets Saving account basic info fetched from the server - * - * @param savingsWithAssociations object containing details of a saving account - */ - @Override - public void showSavingAccountsDetail(SavingsWithAssociations savingsWithAssociations) { - if (savingsWithAssociations.getStatus().getSubmittedAndPendingApproval()) { - sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.approval_pending), - R.drawable.ic_assignment_turned_in_black_24dp, layoutAccount, layoutError); - isMenuVisible = savingsWithAssociations.getStatus().getSubmittedAndPendingApproval(); - } else { - layoutAccount.setVisibility(View.VISIBLE); - String currencySymbol = savingsWithAssociations.getCurrency().getDisplaySymbol(); - Double accountBalance = savingsWithAssociations.getSummary().getAccountBalance(); - - tvAccountStatus.setText(savingsWithAssociations.getClientName()); - if (savingsWithAssociations.getMinRequiredOpeningBalance() != null) { - tvMiniRequiredBalance.setText(getString(R.string.string_and_string, currencySymbol, - CurrencyUtil.formatCurrency(getActivity(), savingsWithAssociations. - getMinRequiredOpeningBalance()))); - } else { - tvMinRequiredBalanceLabel.setVisibility(View.GONE); - tvMiniRequiredBalance.setVisibility(View.GONE); - } - - if (savingsWithAssociations.getSummary().getTotalWithdrawals() != null) { - tvTotalWithdrawals.setText(getString(R.string.string_and_string, currencySymbol, - CurrencyUtil.formatCurrency(getActivity(), savingsWithAssociations. - getSummary().getTotalWithdrawals()))); - } else { - tvTotalWithdrawals.setText(R.string.no_withdrawals); - } - - tvAccountBalanceMain.setText(getString(R.string.string_and_string, - currencySymbol, CurrencyUtil.formatCurrency(getActivity(), accountBalance))); - tvNominalInterestRate.setText(getString(R.string.double_and_string, - savingsWithAssociations.getNominalAnnualInterestRate(), SymbolsUtils.PERCENT)); - tvSavingAccountNumber.setText(String.valueOf(savingsWithAssociations.getAccountNo())); - if (savingsWithAssociations.getSummary().getTotalDeposits() != null) { - tvTotalDeposits.setText(getString(R.string.string_and_string, currencySymbol, - CurrencyUtil.formatCurrency(getActivity(), savingsWithAssociations. - getSummary().getTotalDeposits()))); - } else { - tvTotalDeposits.setText(getString(R.string.not_available)); - } - - if (savingsWithAssociations.getTransactions() != null && - !savingsWithAssociations.getTransactions().isEmpty()) { - tvLastTransaction.setText(getString(R.string.string_and_double, - currencySymbol, - savingsWithAssociations.getTransactions().get(0).getAmount())); - tvMadeOnTransaction.setText(DateHelper.getDateAsString( - savingsWithAssociations.getLastActiveTransactionDate())); - } else { - tvLastTransaction.setText(R.string.no_transaction); - tvMadeOnTransaction.setVisibility(View.GONE); - tvMadeOnTextView.setVisibility(View.GONE); - } - showAccountStatus(savingsWithAssociations); - } - - this.savingsWithAssociations = savingsWithAssociations; - getActivity().invalidateOptionsMenu(); - showAccountStatus(savingsWithAssociations); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showErrorFetchingSavingAccountsDetail(String message) { - if (!Network.isConnected(getContext())) { - sweetUIErrorHandler.showSweetNoInternetUI(layoutAccount, layoutError); - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, layoutAccount, layoutError); - Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); - } - } - - @OnClick(R.id.btn_try_again) - void onRetry() { - if (!Network.isConnected(getContext())) { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } else { - sweetUIErrorHandler.hideSweetErrorLayoutUI(layoutAccount, layoutError); - savingAccountsDetailPresenter.loadSavingsWithAssociations(savingsId); - } - } - - /** - * Sets the status of account i.e. {@code tvAccountStatus} and {@code ivCircularStatus} color - * according to {@code savingsWithAssociations} - * - * @param savingsWithAssociations object containing details of a saving account - */ - @Override - public void showAccountStatus(SavingsWithAssociations savingsWithAssociations) { - status = savingsWithAssociations.getStatus(); - if (status.getActive()) { - ivCircularStatus.setImageDrawable( - Utils.setCircularBackground(R.color.deposit_green, getActivity())); - tvAccountStatus.setText(R.string.active); - } else if (status.getApproved()) { - ivCircularStatus.setImageDrawable( - Utils.setCircularBackground(R.color.blue, getActivity())); - tvAccountStatus.setText(R.string.need_approval); - } else if (status.getSubmittedAndPendingApproval()) { - ivCircularStatus.setImageDrawable( - Utils.setCircularBackground(R.color.light_yellow, getActivity())); - tvAccountStatus.setText(R.string.pending); - } else if (status.getMatured()) { - ivCircularStatus.setImageDrawable( - Utils.setCircularBackground(R.color.red_light, getActivity())); - tvAccountStatus.setText(R.string.matured); - } else { - ivCircularStatus.setImageDrawable( - Utils.setCircularBackground(R.color.black, getActivity())); - tvAccountStatus.setText(R.string.closed); - } - getActivity().invalidateOptionsMenu(); - } - - @Override - public void showProgress() { - layoutAccount.setVisibility(View.GONE); - showProgressBar(); - } - - @Override - public void hideProgress() { - layoutAccount.setVisibility(View.VISIBLE); - hideProgressBar(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgressBar(); - savingAccountsDetailPresenter.detachView(); - } - - @OnClick(R.id.ll_savings_transactions) - public void transactionsClicked() { - ((BaseActivity) getActivity()).replaceFragment(SavingAccountsTransactionFragment. - newInstance(savingsId), true, R.id.container); - } - - @OnClick(R.id.ll_savings_charges) - public void chargeClicked() { - ((BaseActivity) getActivity()).replaceFragment(ClientChargeFragment. - newInstance(savingsId, ChargeType.SAVINGS), true, R.id.container); - } - - @OnClick(R.id.ll_savings_qr_code) - public void qrCodeClicked() { - String accountDetailsInJson = QrCodeGenerator.getAccountDetailsInString( - savingsWithAssociations.getAccountNo(), preferencesHelper.getOfficeName(), - AccountType.SAVINGS); - ((BaseActivity) getActivity()).replaceFragment(QrCodeDisplayFragment. - newInstance(accountDetailsInJson), true, R.id.container); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_savings_account_detail, menu); - if (isMenuVisible) { - menu.findItem(R.id.menu_withdraw_savings_account).setVisible(true); - menu.findItem(R.id.menu_update_savings_account).setVisible(true); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - switch (id) { - case R.id.menu_withdraw_savings_account: - ((BaseActivity) getActivity()).replaceFragment( - SavingsAccountWithdrawFragment.newInstance(savingsWithAssociations), - true, R.id.container); - break; - case R.id.menu_update_savings_account: - ((BaseActivity) getActivity()).replaceFragment(SavingsAccountApplicationFragment - .newInstance(SavingsAccountState.UPDATE, savingsWithAssociations), - true, R.id.container); - break; - } - return super.onOptionsItemSelected(item); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsDetailFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsDetailFragment.kt new file mode 100644 index 0000000000..a92f3d49ff --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsDetailFragment.kt @@ -0,0 +1,359 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Parcelable +import android.view.* +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.accounts.savings.Status +import org.mifos.mobile.presenters.SavingAccountsDetailPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.AccountType +import org.mifos.mobile.ui.enums.ChargeType +import org.mifos.mobile.ui.enums.SavingsAccountState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.SavingAccountsDetailView +import org.mifos.mobile.utils.* +import javax.inject.Inject + +/** + * @author Vishwajeet + * @since 18/8/16. + */ +class SavingAccountsDetailFragment : BaseFragment(), SavingAccountsDetailView { + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_status) + var tvAccountStatus: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_circle_status) + var ivCircularStatus: CircularImageView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_total_withdrawals) + var tvTotalWithdrawals: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_min_req_bal) + var tvMiniRequiredBalance: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_saving_account_number) + var tvSavingAccountNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_nominal_interest_rate) + var tvNominalInterestRate: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_total_deposits) + var tvTotalDeposits: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_acc_balance) + var tvAccountBalanceMain: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_last_transaction) + var tvLastTransaction: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.made_on) + var tvMadeOnTextView: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_made_on) + var tvMadeOnTransaction: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_account) + var layoutAccount: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_minRequiredBalance) + var tvMinRequiredBalanceLabel: TextView? = null + + @kotlin.jvm.JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + + @kotlin.jvm.JvmField + @Inject + var savingAccountsDetailPresenter: SavingAccountsDetailPresenter? = null + private var rootView: View? = null + private var savingsId: Long? = 0 + private var status: Status? = null + private var savingsWithAssociations: SavingsWithAssociations? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + private var isMenuVisible:Boolean? = false + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + savingsId = arguments?.getLong(Constants.SAVINGS_ID) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_saving_account_details, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + setToolbarTitle(getString(R.string.saving_account_details)) + ButterKnife.bind(this, rootView!!) + savingAccountsDetailPresenter?.attachView(this) + sweetUIErrorHandler = SweetUIErrorHandler(context, rootView) + if (savedInstanceState == null) { + savingAccountsDetailPresenter?.loadSavingsWithAssociations(savingsId) + } + setHasOptionsMenu(true) + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showSavingAccountsDetail(savedInstanceState.getParcelable(Constants.SAVINGS_ACCOUNTS) as SavingsWithAssociations) + } + } + + /** + * Opens up Phone Dialer + */ + @OnClick(R.id.tv_help_line_number) + fun dialHelpLineNumber() { + val intent = Intent(Intent.ACTION_DIAL) + intent.data = Uri.parse("tel:" + getString(R.string.help_line_number)) + startActivity(intent) + } + + /** + * Opens [SavingsMakeTransferFragment] if status is ACTIVE else shows a + * {@link Snackbar} that Account should be Active + */ + @OnClick(R.id.tv_deposit) + fun deposit() { + if (status?.active == true) { + (activity as BaseActivity?)?.replaceFragment(SavingsMakeTransferFragment.newInstance(savingsId, Constants.TRANSFER_PAY_TO), true, R.id.container) + } else { + Toaster.show(rootView, getString(R.string.account_not_active_to_perform_deposit)) + } + } + + /** + * Opens [SavingsMakeTransferFragment] if status is ACTIVE else shows a + * {@link Snackbar} that Account should be Active + */ + @OnClick(R.id.tv_make_a_transfer) + fun transfer() { + if (status?.active == true) { + (activity as BaseActivity?)?.replaceFragment(SavingsMakeTransferFragment.newInstance(savingsId, Constants.TRANSFER_PAY_FROM), true, R.id.container) + } else { + Toaster.show(rootView, getString(R.string.account_not_active_to_perform_transfer)) + } + } + + /** + * Sets Saving account basic info fetched from the server + * + * @param savingsWithAssociations object containing details of a saving account + */ + override fun showSavingAccountsDetail(savingsWithAssociations: SavingsWithAssociations?) { + if (savingsWithAssociations?.status?.submittedAndPendingApproval == true) { + sweetUIErrorHandler?.showSweetCustomErrorUI(getString(R.string.approval_pending), + R.drawable.ic_assignment_turned_in_black_24dp, layoutAccount, layoutError) + isMenuVisible = (savingsWithAssociations.status?.submittedAndPendingApproval == true) + } else { + layoutAccount?.visibility = View.VISIBLE + val currencySymbol = savingsWithAssociations?.currency?.displaySymbol + val accountBalance = savingsWithAssociations?.summary?.accountBalance + tvAccountStatus?.text = savingsWithAssociations?.clientName + if (savingsWithAssociations?.minRequiredOpeningBalance != null) { + tvMiniRequiredBalance?.text = getString(R.string.string_and_string, currencySymbol, + CurrencyUtil.formatCurrency(activity, savingsWithAssociations.minRequiredOpeningBalance!!)) + } else { + tvMinRequiredBalanceLabel?.visibility = View.GONE + tvMiniRequiredBalance?.visibility = View.GONE + } + if (savingsWithAssociations?.summary?.totalWithdrawals != null) { + tvTotalWithdrawals?.text = getString(R.string.string_and_string, currencySymbol, + CurrencyUtil.formatCurrency(activity, savingsWithAssociations.summary?.totalWithdrawals!!)) + } else { + tvTotalWithdrawals?.setText(R.string.no_withdrawals) + } + tvAccountBalanceMain?.text = getString(R.string.string_and_string, + currencySymbol, CurrencyUtil.formatCurrency(activity, accountBalance!!)) + tvNominalInterestRate?.text = getString(R.string.double_and_string, + savingsWithAssociations.getNominalAnnualInterestRate(), SymbolsUtils.PERCENT) + tvSavingAccountNumber?.text = savingsWithAssociations.accountNo.toString() + if (savingsWithAssociations.summary?.totalDeposits != null) { + tvTotalDeposits?.text = getString(R.string.string_and_string, currencySymbol, + CurrencyUtil.formatCurrency(activity, savingsWithAssociations.summary?.totalDeposits!!)) + } else { + tvTotalDeposits?.text = getString(R.string.not_available) + } + if (savingsWithAssociations.transactions.isNotEmpty()) { + tvLastTransaction?.text = getString(R.string.string_and_double, + currencySymbol, + savingsWithAssociations.transactions[0].amount) + tvMadeOnTransaction?.text = DateHelper.getDateAsString( + savingsWithAssociations.lastActiveTransactionDate) + } else { + tvLastTransaction?.setText(R.string.no_transaction) + tvMadeOnTransaction?.visibility = View.GONE + tvMadeOnTextView?.visibility = View.GONE + } + showAccountStatus(savingsWithAssociations) + } + this.savingsWithAssociations = savingsWithAssociations + activity?.invalidateOptionsMenu() + showAccountStatus(savingsWithAssociations) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showErrorFetchingSavingAccountsDetail(message: String?) { + if (!Network.isConnected(context)) { + sweetUIErrorHandler?.showSweetNoInternetUI(layoutAccount, layoutError) + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } else { + sweetUIErrorHandler?.showSweetErrorUI(message, layoutAccount, layoutError) + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + } + } + + @OnClick(R.id.btn_try_again) + fun onRetry() { + if (!Network.isConnected(context)) { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } else { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(layoutAccount, layoutError) + savingAccountsDetailPresenter?.loadSavingsWithAssociations(savingsId) + } + } + + /** + * Sets the status of account i.e. `tvAccountStatus` and `ivCircularStatus` color + * according to `savingsWithAssociations` + * + * @param savingsWithAssociations object containing details of a saving account + */ + override fun showAccountStatus(savingsWithAssociations: SavingsWithAssociations?) { + status = savingsWithAssociations?.status + when { + status?.active == true -> { + ivCircularStatus?.setImageDrawable( + Utils.setCircularBackground(R.color.deposit_green, activity)) + tvAccountStatus?.setText(R.string.active) + } + status?.approved == true -> { + ivCircularStatus?.setImageDrawable( + Utils.setCircularBackground(R.color.blue, activity)) + tvAccountStatus?.setText(R.string.need_approval) + } + status?.submittedAndPendingApproval == true -> { + ivCircularStatus?.setImageDrawable( + Utils.setCircularBackground(R.color.light_yellow, activity)) + tvAccountStatus?.setText(R.string.pending) + } + status?.matured == true -> { + ivCircularStatus?.setImageDrawable( + Utils.setCircularBackground(R.color.red_light, activity)) + tvAccountStatus?.setText(R.string.matured) + } + else -> { + ivCircularStatus?.setImageDrawable( + Utils.setCircularBackground(R.color.black, activity)) + tvAccountStatus?.setText(R.string.closed) + } + } + activity?.invalidateOptionsMenu() + } + + override fun showProgress() { + layoutAccount?.visibility = View.GONE + showProgressBar() + } + + override fun hideProgress() { + layoutAccount?.visibility = View.VISIBLE + hideProgressBar() + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgressBar() + savingAccountsDetailPresenter?.detachView() + } + + @OnClick(R.id.ll_savings_transactions) + fun transactionsClicked() { + (activity as BaseActivity?)?.replaceFragment(SavingAccountsTransactionFragment.newInstance(savingsId), true, R.id.container) + } + + @OnClick(R.id.ll_savings_charges) + fun chargeClicked() { + (activity as BaseActivity?)?.replaceFragment(ClientChargeFragment.newInstance(savingsId, ChargeType.SAVINGS), true, R.id.container) + } + + @OnClick(R.id.ll_savings_qr_code) + fun qrCodeClicked() { + val accountDetailsInJson = QrCodeGenerator.getAccountDetailsInString( + savingsWithAssociations?.accountNo, preferencesHelper?.officeName, + AccountType.SAVINGS) + (activity as BaseActivity?)?.replaceFragment(QrCodeDisplayFragment.newInstance(accountDetailsInJson), true, R.id.container) + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + inflater.inflate(R.menu.menu_savings_account_detail, menu) + if (isMenuVisible == true) { + menu.findItem(R.id.menu_withdraw_savings_account).isVisible = true + menu.findItem(R.id.menu_update_savings_account).isVisible = true + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + val id = item.itemId + when (id) { + R.id.menu_withdraw_savings_account -> (activity as BaseActivity?)?.replaceFragment( + SavingsAccountWithdrawFragment.newInstance(savingsWithAssociations), + true, R.id.container) + R.id.menu_update_savings_account -> (activity as BaseActivity?)?.replaceFragment(SavingsAccountApplicationFragment.newInstance(SavingsAccountState.UPDATE, savingsWithAssociations), + true, R.id.container) + } + return super.onOptionsItemSelected(item) + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(savingsId: Long): SavingAccountsDetailFragment { + val fragment = SavingAccountsDetailFragment() + val args = Bundle() + args.putLong(Constants.SAVINGS_ID, savingsId) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsTransactionFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsTransactionFragment.java deleted file mode 100644 index 55e7389d03..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsTransactionFragment.java +++ /dev/null @@ -1,500 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.DialogInterface; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.CompoundButton; -import android.widget.LinearLayout; -import android.widget.RadioButton; -import android.widget.RadioGroup; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatCheckBox; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.CheckboxStatus; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.accounts.savings.Transactions; -import org.mifos.mobile.presenters.SavingAccountsTransactionPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.CheckBoxAdapter; -import org.mifos.mobile.ui.adapters.SavingAccountsTransactionListAdapter; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.SavingAccountsTransactionView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.DatePick; -import org.mifos.mobile.utils.MFDatePicker; -import org.mifos.mobile.utils.MaterialDialog; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.StatusUtils; -import org.mifos.mobile.utils.Toaster; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 6/3/17. - */ - -public class SavingAccountsTransactionFragment extends BaseFragment - implements SavingAccountsTransactionView, -// RadioGroup.OnCheckedChangeListener, - MFDatePicker.OnDatePickListener { - - @BindView(R.id.ll_account) - LinearLayout layoutAccount; - - @BindView(R.id.layout_error) - View layoutError; - - @BindView(R.id.rv_saving_accounts_transaction) - RecyclerView rvSavingAccountsTransaction; - - @Inject - SavingAccountsTransactionListAdapter transactionListAdapter; - - @Inject - SavingAccountsTransactionPresenter savingAccountsTransactionPresenter; - - @Inject - CheckBoxAdapter checkBoxAdapter; - - private TextView tvStartDate, tvEndDate; - private SweetUIErrorHandler sweetUIErrorHandler; - private View rootView; - private long savingsId; - private List transactionsList; - private SavingsWithAssociations savingsWithAssociations; - private DatePick datePick; - private MFDatePicker mfDatePicker; - private long startDate, endDate; - private boolean isReady; - private List statusList; - private boolean isCheckBoxPeriod; - private int selectedRadioButtonId; - public boolean active = false; - - - public static SavingAccountsTransactionFragment newInstance(long savingsId) { - SavingAccountsTransactionFragment fragment = new SavingAccountsTransactionFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.SAVINGS_ID, savingsId); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - setToolbarTitle(getString(R.string.saving_account_transactions_details)); - if (getArguments() != null) { - savingsId = getArguments().getLong(Constants.SAVINGS_ID); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, - @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_saving_account_transactions, - container, false); - - ButterKnife.bind(this, rootView); - savingAccountsTransactionPresenter.attachView(this); - - sweetUIErrorHandler = new SweetUIErrorHandler(getContext(), rootView); - showUserInterface(); - if (savedInstanceState == null) { - savingAccountsTransactionPresenter.loadSavingsWithAssociations(savingsId); - } - initializeFilterVariables(); - return rootView; - } - - private void initializeFilterVariables() { - statusList = StatusUtils.getSavingsAccountTransactionList(getActivity()); - startDate = -1; - endDate = -2; - isCheckBoxPeriod = false; - isReady = false; - selectedRadioButtonId = -1; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showSavingAccountsDetail((SavingsWithAssociations) savedInstanceState. - getParcelable(Constants.SAVINGS_ACCOUNTS)); - } - } - - /** - * Setting up basic components - */ - @Override - public void showUserInterface() { - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - rvSavingAccountsTransaction.setHasFixedSize(true); - rvSavingAccountsTransaction.setLayoutManager(layoutManager); - rvSavingAccountsTransaction.setAdapter(transactionListAdapter); - -// radioGroup.setOnCheckedChangeListener(this); - mfDatePicker = MFDatePicker.newInstance(this, MFDatePicker.ALL_DAYS, active); - active = true; - } - - /** - * Provides with {@code savingsWithAssociations} fetched from server which is used to update the - * {@code transactionListAdapter} - * - * @param savingsWithAssociations Contains {@link Transactions} for given Savings account. - */ - @Override - public void showSavingAccountsDetail(SavingsWithAssociations - savingsWithAssociations) { - layoutAccount.setVisibility(View.VISIBLE); - this.savingsWithAssociations = savingsWithAssociations; - transactionsList = savingsWithAssociations.getTransactions(); - - if (transactionsList != null && !transactionsList.isEmpty()) { - transactionListAdapter.setContext(getContext()); - transactionListAdapter. - setSavingAccountsTransactionList(transactionsList); - } else { - sweetUIErrorHandler.showSweetEmptyUI(getString(R.string.transactions), - R.drawable.ic_compare_arrows_black_24dp, rvSavingAccountsTransaction, - layoutError); - } - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showErrorFetchingSavingAccountsDetail(String message) { - if (!Network.isConnected(getActivity())) { - sweetUIErrorHandler.showSweetNoInternetUI(rvSavingAccountsTransaction, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, rvSavingAccountsTransaction, layoutError); - } - } - - @OnClick(R.id.btn_try_again) - public void retryClicked() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(rvSavingAccountsTransaction, layoutError); - savingAccountsTransactionPresenter.loadSavingsWithAssociations(savingsId); - } else { - Toast.makeText(getContext(), getString(R.string.internet_not_connected), - Toast.LENGTH_SHORT).show(); - } - } - - /** - * Provides with a filtered list according to the constraints used in {@code filter()} function - */ - @Override - public void showFilteredList(List list) { - Toaster.show(rootView, getString(R.string.filtered)); - transactionListAdapter. - setSavingAccountsTransactionList(list); - } - - /** - * Opens up Phone Dialer - */ - @OnClick(R.id.tv_help_line_number) - void dialHelpLineNumber() { - Intent intent = new Intent(Intent.ACTION_DIAL); - intent.setData(Uri.parse("tel:" + getString(R.string.help_line_number))); - startActivity(intent); - } - - private void startDatePick() { - datePick = DatePick.START; - mfDatePicker.show(getActivity().getSupportFragmentManager(), Constants - .DFRAG_DATE_PICKER); - } - - private void endDatePick() { - datePick = DatePick.END; - mfDatePicker.show(getActivity().getSupportFragmentManager(), Constants - .DFRAG_DATE_PICKER); - } - - /** - * A CallBack for {@link MFDatePicker} which provides us with the date selected from the - * {@link android.app.DatePickerDialog} by {@code mfDatePicker} - * - * @param date Date selected by user in {@link String} - */ - @Override - public void onDatePicked(String date) { - long timeInMillis = DateHelper.getDateAsLongFromString(date, "dd-MM-yyyy"); - if (datePick == DatePick.START) { - tvEndDate.setEnabled(true); - tvStartDate.setText(DateHelper.getDateAsStringFromLong(timeInMillis)); - startDate = timeInMillis; - } else { - endDate = timeInMillis; - tvEndDate.setText(DateHelper.getDateAsStringFromLong(timeInMillis)); - isReady = true; - } - } - - /** - * Checks if {@code startDate} is less than {@code endDate} - * - * @return Returns true if {@code startDate} is less than {@code endDate} - */ - private boolean isEndDateLargeThanStartDate() { - return startDate <= endDate; - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - /** - * Shows a filter dialog - */ - - private void showFilterDialog() { - - LayoutInflater inflater = getActivity().getLayoutInflater(); - final View dialogView = inflater.inflate(R.layout.layout_filter_dialog, null , false); - - final LinearLayout llcheckBoxPeriod = dialogView.findViewById(R.id.ll_row_checkbox); - final AppCompatCheckBox checkBoxPeriod = dialogView.findViewById(R.id.cb_select); - final RadioGroup radioGroupFilter = dialogView.findViewById(R.id.rg_date_filter); - tvStartDate = dialogView.findViewById(R.id.tv_start_date); - tvEndDate = dialogView.findViewById(R.id.tv_end_date); - tvStartDate.setEnabled(false); - tvEndDate.setEnabled(false); - - //setup listeners - tvStartDate.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startDatePick(); - } - }); - tvEndDate.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - endDatePick(); - } - }); - - llcheckBoxPeriod.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - checkBoxPeriod.setChecked(!checkBoxPeriod.isChecked()); - } - }); - - checkBoxPeriod.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { - isCheckBoxPeriod = isChecked; - if (!isChecked) { - isReady = false; - radioGroupFilter.clearCheck(); - selectedRadioButtonId = -1; - } else { - if (selectedRadioButtonId == -1) { - RadioButton btn = dialogView.findViewById(R.id.rb_date); - btn.setChecked(true); - } - } - } - }); - - radioGroupFilter.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(RadioGroup radioGroup, int i) { - isCheckBoxPeriod = true; - selectedRadioButtonId = radioGroup.getCheckedRadioButtonId(); - switch (radioGroup.getCheckedRadioButtonId()) { - case R.id.rb_four_weeks: - tvStartDate.setEnabled(false); - tvEndDate.setEnabled(false); - startDate = DateHelper.subtractWeeks(4); - endDate = System.currentTimeMillis(); - isReady = true; - break; - case R.id.rb_three_months: - tvStartDate.setEnabled(false); - tvEndDate.setEnabled(false); - startDate = DateHelper.subtractMonths(3); - endDate = System.currentTimeMillis(); - isReady = true; - break; - case R.id.rb_six_months: - tvStartDate.setEnabled(false); - tvEndDate.setEnabled(false); - startDate = DateHelper.subtractMonths(6); - endDate = System.currentTimeMillis(); - isReady = true; - break; - case R.id.rb_date: - tvStartDate.setEnabled(true); - tvEndDate.setEnabled(false); - break; - } - } - }); - - //restore prev state - checkBoxPeriod.setChecked(isCheckBoxPeriod); - if (selectedRadioButtonId != -1) { - RadioButton btn = dialogView.findViewById(selectedRadioButtonId); - btn.setChecked(true); - } - - RecyclerView checkBoxRecyclerView = dialogView.findViewById(R.id.recycler_view); - LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); - layoutManager.setOrientation(LinearLayoutManager.VERTICAL); - - checkBoxRecyclerView.setLayoutManager(layoutManager); - checkBoxRecyclerView.setAdapter(checkBoxAdapter); - - checkBoxAdapter.setStatusList(statusList); - - new MaterialDialog.Builder().init(getActivity()) - .setTitle(R.string.savings_account_transaction) - .addView(dialogView) - .setPositiveButton(getString(R.string.filter), new DialogInterface.OnClickListener() - { - @Override - public void onClick(DialogInterface dialog, int which) { - if (checkBoxPeriod.isChecked()) { - if (!isReady) { - Toaster.show(rootView, getString(R.string.select_date)); - return; - } else if (!isEndDateLargeThanStartDate()) { - Toaster.show(rootView, - getString(R.string.end_date_must_be_greater)); - return; - } - filter(startDate, endDate, checkBoxAdapter.getStatusList()); - } else { - filter(checkBoxAdapter.getStatusList()); - } - filterSavingsAccountTransactionsbyType(checkBoxAdapter.getStatusList()); - } - }) - .setNeutralButton(getString(R.string.clear_filters), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - transactionListAdapter - .setSavingAccountsTransactionList(transactionsList); - initializeFilterVariables(); - } - }) - .setNegativeButton(R.string.cancel) - .createMaterialDialog() - .show(); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.menu_saving_accounts_transaction, menu); - super.onCreateOptionsMenu(menu, inflater); - - } - - /** - * Will filter {@code transactionsList} according to {@code startDate} and {@code endDate} - * - * @param startDate Starting date - * @param endDate Ending date - */ - private void filter(long startDate, long endDate, List statusModelList) { - List dummyTransactionList = - filterSavingsAccountTransactionsbyType(statusModelList); - savingAccountsTransactionPresenter.filterTransactionList(dummyTransactionList, - startDate, endDate); - } - - /** - * Will filter {@code transactionsList} according to {@code startDate} and {@code endDate} - * - * @param statusModelList Status Model List - */ - private void filter(List statusModelList) { - showFilteredList(filterSavingsAccountTransactionsbyType(statusModelList)); - } - /** - * Will filter {@code transactionsList} according to {@code startDate} and {@code endDate} - * @param statusModelList Status Model List - */ - private List filterSavingsAccountTransactionsbyType(List - statusModelList) { - List filteredSavingsTransactions = new ArrayList<>(); - for (CheckboxStatus status:savingAccountsTransactionPresenter - .getCheckedStatus(statusModelList)) { - filteredSavingsTransactions.addAll(savingAccountsTransactionPresenter - .filterTranactionListbyType(transactionsList, status)); - } - - return filteredSavingsTransactions; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.menu_filter_savings_transactions: - showFilterDialog(); - break; - } - return true; - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - savingAccountsTransactionPresenter.detachView(); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsTransactionFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsTransactionFragment.kt new file mode 100644 index 0000000000..353e11d8dc --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingAccountsTransactionFragment.kt @@ -0,0 +1,428 @@ +package org.mifos.mobile.ui.fragments + +import android.content.DialogInterface +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Parcelable +import android.view.* +import android.widget.* + +import androidx.appcompat.widget.AppCompatCheckBox +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.CheckboxStatus +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.accounts.savings.Transactions +import org.mifos.mobile.presenters.SavingAccountsTransactionPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.CheckBoxAdapter +import org.mifos.mobile.ui.adapters.SavingAccountsTransactionListAdapter +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.SavingAccountsTransactionView +import org.mifos.mobile.utils.* +import org.mifos.mobile.utils.MFDatePicker.OnDatePickListener + +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 6/3/17. + */ +class SavingAccountsTransactionFragment : BaseFragment(), SavingAccountsTransactionView, OnDatePickListener { + + @kotlin.jvm.JvmField + @BindView(R.id.ll_account) + var layoutAccount: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @BindView(R.id.rv_saving_accounts_transaction) + var rvSavingAccountsTransaction: RecyclerView? = null + + @kotlin.jvm.JvmField + @Inject + var transactionListAdapter: SavingAccountsTransactionListAdapter? = null + + @kotlin.jvm.JvmField + @Inject + var savingAccountsTransactionPresenter: SavingAccountsTransactionPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var checkBoxAdapter: CheckBoxAdapter? = null + private var tvStartDate: TextView? = null + private var tvEndDate: TextView? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + private var rootView: View? = null + private var savingsId: Long = 0 + private var transactionsList: List? = null + private var savingsWithAssociations: SavingsWithAssociations? = null + private var datePick: DatePick? = null + private var mfDatePicker: MFDatePicker? = null + private var startDate: Long? = 0 + private var endDate: Long? = 0 + private var isReady = false + private var statusList: List? = null + private var isCheckBoxPeriod = false + private var selectedRadioButtonId = 0 + var active = false + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + (activity as BaseActivity?)?.activityComponent?.inject(this) + setToolbarTitle(getString(R.string.saving_account_transactions_details)) + if (arguments != null) savingsId = arguments?.getLong(Constants.SAVINGS_ID)!! + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_saving_account_transactions, + container, false) + ButterKnife.bind(this, rootView!!) + savingAccountsTransactionPresenter?.attachView(this) + sweetUIErrorHandler = SweetUIErrorHandler(context, rootView) + showUserInterface() + if (savedInstanceState == null) { + savingAccountsTransactionPresenter?.loadSavingsWithAssociations(savingsId) + } + initializeFilterVariables() + return rootView + } + + private fun initializeFilterVariables() { + statusList = StatusUtils.getSavingsAccountTransactionList(activity) + startDate = -1 + endDate = -2 + isCheckBoxPeriod = false + isReady = false + selectedRadioButtonId = -1 + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showSavingAccountsDetail(savedInstanceState.getParcelable(Constants.SAVINGS_ACCOUNTS) as SavingsWithAssociations) + } + } + + /** + * Setting up basic components + */ + override fun showUserInterface() { + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = LinearLayoutManager.VERTICAL + rvSavingAccountsTransaction?.setHasFixedSize(true) + rvSavingAccountsTransaction?.layoutManager = layoutManager + rvSavingAccountsTransaction?.adapter = transactionListAdapter + +// radioGroup.setOnCheckedChangeListener(this); + mfDatePicker = MFDatePicker.newInstance(this, MFDatePicker.ALL_DAYS, active) + active = true + } + + /** + * Provides with `savingsWithAssociations` fetched from server which is used to update the + * `transactionListAdapter` + * + * @param savingsWithAssociations Contains [Transactions] for given Savings account. + */ + override fun showSavingAccountsDetail(savingsWithAssociations: SavingsWithAssociations?) { + layoutAccount?.visibility = View.VISIBLE + this.savingsWithAssociations = savingsWithAssociations + transactionsList = savingsWithAssociations?.transactions + if (transactionsList != null && transactionsList?.isNotEmpty() == true) { + transactionListAdapter?.setContext(context) + transactionListAdapter?.setSavingAccountsTransactionList(transactionsList) + } else { + showEmptyTransactions() + } + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showErrorFetchingSavingAccountsDetail(message: String?) { + if (!Network.isConnected(activity)) { + sweetUIErrorHandler?.showSweetNoInternetUI(rvSavingAccountsTransaction, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(message, rvSavingAccountsTransaction, layoutError) + } + } + + @OnClick(R.id.btn_try_again) + fun retryClicked() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(rvSavingAccountsTransaction, layoutError) + savingAccountsTransactionPresenter?.loadSavingsWithAssociations(savingsId) + } else { + Toast.makeText(context, getString(R.string.internet_not_connected), + Toast.LENGTH_SHORT).show() + } + } + + /** + * Provides with a filtered list according to the constraints used in `filter()` function + */ + override fun showFilteredList(list: List?) { + if (list != null && list.isNotEmpty()) { + Toaster.show(rootView, getString(R.string.filtered)) + transactionListAdapter?.setSavingAccountsTransactionList(list) + } else { + showEmptyTransactions() + } + } + + override fun showEmptyTransactions() { + sweetUIErrorHandler?.showSweetEmptyUI(getString(R.string.transactions), + R.drawable.ic_compare_arrows_black_24dp, rvSavingAccountsTransaction, layoutError) + } + + /** + * Opens up Phone Dialer + */ + @OnClick(R.id.tv_help_line_number) + fun dialHelpLineNumber() { + val intent = Intent(Intent.ACTION_DIAL) + intent.data = Uri.parse("tel:" + getString(R.string.help_line_number)) + startActivity(intent) + } + + private fun startDatePick() { + datePick = DatePick.START + mfDatePicker?.show(activity?.supportFragmentManager, Constants.DFRAG_DATE_PICKER) + } + + private fun endDatePick() { + datePick = DatePick.END + mfDatePicker?.show(activity?.supportFragmentManager, Constants.DFRAG_DATE_PICKER) + } + + /** + * A CallBack for [MFDatePicker] which provides us with the date selected from the + * [android.app.DatePickerDialog] by `mfDatePicker` + * + * @param date Date selected by user in [String] + */ + override fun onDatePicked(date: String?) { + val timeInMillis = DateHelper.getDateAsLongFromString(date, "dd-MM-yyyy") + if (datePick == DatePick.START) { + tvEndDate?.isEnabled = true + tvStartDate?.text = DateHelper.getDateAsStringFromLong(timeInMillis) + startDate = timeInMillis + } else { + endDate = timeInMillis + tvEndDate?.text = DateHelper.getDateAsStringFromLong(timeInMillis) + isReady = true + } + } + + /** + * Checks if `startDate` is less than `endDate` + * + * @return Returns true if `startDate` is less than `endDate` + */ + private fun isEndDateLargeThanStartDate(): Boolean? { + return if (startDate != null && endDate != null) + startDate!! <= endDate!! + else null + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + /** + * Shows a filter dialog + */ + private fun showFilterDialog() { + val inflater = activity?.layoutInflater + val dialogView = inflater?.inflate(R.layout.layout_filter_dialog, null, false) + val llcheckBoxPeriod = dialogView?.findViewById(R.id.ll_row_checkbox) + val checkBoxPeriod: AppCompatCheckBox? = dialogView?.findViewById(R.id.cb_select) + val radioGroupFilter = dialogView?.findViewById(R.id.rg_date_filter) + tvStartDate = dialogView?.findViewById(R.id.tv_start_date) + tvEndDate = dialogView?.findViewById(R.id.tv_end_date) + tvStartDate?.isEnabled = false + tvEndDate?.isEnabled = false + + //setup listeners + tvStartDate?.setOnClickListener { startDatePick() } + tvEndDate?.setOnClickListener { endDatePick() } + llcheckBoxPeriod?.setOnClickListener { checkBoxPeriod?.isChecked = (checkBoxPeriod?.isChecked != true) } + checkBoxPeriod?.setOnCheckedChangeListener { _, isChecked -> + isCheckBoxPeriod = isChecked + if (!isChecked) { + isReady = false + radioGroupFilter?.clearCheck() + selectedRadioButtonId = -1 + } else { + if (selectedRadioButtonId == -1) { + val btn = dialogView.findViewById(R.id.rb_date) + btn.isChecked = true + } + } + } + radioGroupFilter?.setOnCheckedChangeListener { radioGroup, _ -> + isCheckBoxPeriod = true + selectedRadioButtonId = radioGroup.checkedRadioButtonId + when (radioGroup.checkedRadioButtonId) { + R.id.rb_four_weeks -> { + tvStartDate?.isEnabled = false + tvEndDate?.isEnabled = false + startDate = DateHelper.subtractWeeks(4) + endDate = System.currentTimeMillis() + isReady = true + } + R.id.rb_three_months -> { + tvStartDate?.isEnabled = false + tvEndDate?.isEnabled = false + startDate = DateHelper.subtractMonths(3) + endDate = System.currentTimeMillis() + isReady = true + } + R.id.rb_six_months -> { + tvStartDate?.isEnabled = false + tvEndDate?.isEnabled = false + startDate = DateHelper.subtractMonths(6) + endDate = System.currentTimeMillis() + isReady = true + } + R.id.rb_date -> { + tvStartDate?.isEnabled = true + tvEndDate?.isEnabled = false + } + } + } + + //restore prev state + checkBoxPeriod?.isChecked = isCheckBoxPeriod + if (selectedRadioButtonId != -1) { + val btn = dialogView?.findViewById(selectedRadioButtonId) + btn?.isChecked = true + } + val checkBoxRecyclerView: RecyclerView? = dialogView?.findViewById(R.id.recycler_view) + val layoutManager = LinearLayoutManager(activity) + layoutManager.orientation = LinearLayoutManager.VERTICAL + checkBoxRecyclerView?.layoutManager = layoutManager + checkBoxRecyclerView?.adapter = checkBoxAdapter + checkBoxAdapter?.statusList = statusList + MaterialDialog.Builder().init(activity) + .setTitle(R.string.savings_account_transaction) + .addView(dialogView) + .setPositiveButton(getString(R.string.filter), DialogInterface.OnClickListener { _, _ -> + if (checkBoxPeriod?.isChecked == true) { + if (!isReady) { + Toaster.show(rootView, getString(R.string.select_date)) + return@OnClickListener + } else if (isEndDateLargeThanStartDate() == false) { + Toaster.show(rootView, + getString(R.string.end_date_must_be_greater)) + return@OnClickListener + } + filter(startDate, endDate, checkBoxAdapter?.statusList) + } else { + filter(checkBoxAdapter?.statusList) + } + filterSavingsAccountTransactionsbyType(checkBoxAdapter?.statusList) + }) + .setNeutralButton(getString(R.string.clear_filters), + DialogInterface.OnClickListener { _, _ -> + transactionListAdapter + ?.setSavingAccountsTransactionList(transactionsList) + initializeFilterVariables() + } + ) + .setNegativeButton(R.string.cancel) + .createMaterialDialog() + .show() + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + inflater.inflate(R.menu.menu_saving_accounts_transaction, menu) + super.onCreateOptionsMenu(menu, inflater) + } + + /** + * Will filter `transactionsList` according to `startDate` and `endDate` + * + * @param startDate Starting date + * @param endDate Ending date + */ + private fun filter(startDate: Long?, endDate: Long?, statusModelList: List?) { + val dummyTransactionList = filterSavingsAccountTransactionsbyType(statusModelList) + savingAccountsTransactionPresenter?.filterTransactionList(dummyTransactionList, + startDate, endDate) + } + + /** + * Will filter `transactionsList` according to `startDate` and `endDate` + * + * @param statusModelList Status Model List + */ + private fun filter(statusModelList: List?) { + showFilteredList(filterSavingsAccountTransactionsbyType(statusModelList)) + } + + /** + * Will filter `transactionsList` according to `startDate` and `endDate` + * @param statusModelList Status Model List + */ + private fun filterSavingsAccountTransactionsbyType(statusModelList: List?): List? { + val filteredSavingsTransactions: MutableList? = ArrayList() + if (savingAccountsTransactionPresenter != null) + for (status in savingAccountsTransactionPresenter + ?.getCheckedStatus(statusModelList)!!) { + savingAccountsTransactionPresenter + ?.filterTranactionListbyType(transactionsList, status)?.let { filteredSavingsTransactions?.addAll(it) } + } + return filteredSavingsTransactions + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + R.id.menu_filter_savings_transactions -> showFilterDialog() + } + return true + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + savingAccountsTransactionPresenter?.detachView() + } + + companion object { + fun newInstance(savingsId: Long?): SavingAccountsTransactionFragment { + val fragment = SavingAccountsTransactionFragment() + val args = Bundle() + if (savingsId != null) args.putLong(Constants.SAVINGS_ID, savingsId) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountApplicationFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountApplicationFragment.java deleted file mode 100644 index 88899c6ecf..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountApplicationFragment.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* - * Created by saksham on 30/June/2018 - */ - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.Spinner; -import android.widget.TextView; -import android.widget.Toast; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload; -import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.templates.savings.ProductOptions; -import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate; -import org.mifos.mobile.presenters.SavingsAccountApplicationPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.SavingsAccountState; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.SavingsAccountApplicationView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.MFDatePicker; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -public class SavingsAccountApplicationFragment extends BaseFragment - implements SavingsAccountApplicationView { - - @BindView(R.id.sp_product_id) - Spinner spProductId; - - @BindView(R.id.tv_submission_date) - TextView tvSubmissionDate; - - @BindView(R.id.tv_client_name) - TextView tvClientName; - - @Inject - SavingsAccountApplicationPresenter presenter; - - @Inject - PreferencesHelper preferencesHelper; - - private View rootView; - private SavingsAccountState state; - private SavingsWithAssociations savingsWithAssociations; - private ArrayAdapter productIdAdapter; - private SavingsAccountTemplate template; - private List productOptions; - private List productIdList = new ArrayList<>(); - - public static SavingsAccountApplicationFragment newInstance( - SavingsAccountState state, SavingsWithAssociations savingsWithAssociations) { - SavingsAccountApplicationFragment fragment = new SavingsAccountApplicationFragment(); - Bundle bundle = new Bundle(); - bundle.putSerializable(Constants.SAVINGS_ACCOUNT_STATE, state); - bundle.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations); - fragment.setArguments(bundle); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - state = (SavingsAccountState) getArguments() - .getSerializable(Constants.SAVINGS_ACCOUNT_STATE); - savingsWithAssociations = getArguments().getParcelable(Constants.SAVINGS_ACCOUNTS); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_savings_account_application, container, - false); - ButterKnife.bind(this, rootView); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - - presenter.attachView(this); - presenter.loadSavingsAccountApplicationTemplate(preferencesHelper.getClientId(), state); - return rootView; - } - - @Override - public void showUserInterfaceSavingAccountApplication(SavingsAccountTemplate template) { - showUserInterface(template); - } - - @Override - public void showSavingsAccountApplicationSuccessfully() { - showMessage(getString(R.string.new_saving_account_created_successfully)); - getActivity().finish(); - } - - @Override - public void showUserInterfaceSavingAccountUpdate(SavingsAccountTemplate template) { - showUserInterface(template); - getActivity().setTitle(getString(R.string.string_savings_account, - getString(R.string.update))); - spProductId.setSelection(productIdAdapter.getPosition(savingsWithAssociations - .getSavingsProductName())); - } - - @Override - public void showSavingsAccountUpdateSuccessfully() { - showMessage(getString(R.string.saving_account_updated_successfully)); - getActivity().getSupportFragmentManager().popBackStack(); - } - - public void showUserInterface(SavingsAccountTemplate template) { - this.template = template; - productOptions = template.getProductOptions(); - for (ProductOptions item : productOptions) { - productIdList.add(item.getName()); - } - - tvClientName.setText(template.getClientName()); - - productIdAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, - productIdList); - productIdAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - spProductId.setAdapter(productIdAdapter); - - tvSubmissionDate.setText(MFDatePicker.getDatePickedAsString()); - } - - public void submitSavingsAccountApplication() { - SavingsAccountApplicationPayload payload = new SavingsAccountApplicationPayload(); - payload.setClientId(template.getClientId()); - payload.setProductId(productOptions.get(spProductId.getSelectedItemPosition()).getId()); - payload.setSubmittedOnDate(DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, - MFDatePicker.getDatePickedAsString())); - presenter.submitSavingsAccountApplication(payload); - } - - public void updateSavingAccount() { - SavingsAccountUpdatePayload payload = new SavingsAccountUpdatePayload(); - payload.setClientId(template.getClientId()); - payload.setProductId(productOptions.get(spProductId.getSelectedItemPosition()).getId()); - presenter.updateSavingsAccount(savingsWithAssociations.getAccountNo(), payload); - } - - @OnClick(R.id.btn_submit) - void onSubmit() { - if (state == SavingsAccountState.CREATE) { - submitSavingsAccountApplication(); - } else { - updateSavingAccount(); - } - } - - @Override - public void showError(String error) { - Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show(); - } - - @Override - public void showMessage(String message) { - Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); - } - - @Override - public void showProgress() { - showMifosProgressDialog(getString(R.string.progress_message_loading)); - } - - @Override - public void hideProgress() { - hideMifosProgressDialog(); - } - - @Override - public void onDestroy() { - super.onDestroy(); - hideProgress(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountApplicationFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountApplicationFragment.kt new file mode 100644 index 0000000000..6a318e9580 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountApplicationFragment.kt @@ -0,0 +1,185 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ArrayAdapter +import android.widget.Spinner +import android.widget.TextView +import android.widget.Toast + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.accounts.savings.SavingsAccountApplicationPayload +import org.mifos.mobile.models.accounts.savings.SavingsAccountUpdatePayload +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.templates.savings.ProductOptions +import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate +import org.mifos.mobile.presenters.SavingsAccountApplicationPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.SavingsAccountState +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.SavingsAccountApplicationView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DateHelper +import org.mifos.mobile.utils.MFDatePicker + +import java.util.* +import javax.inject.Inject + +/* +* Created by saksham on 30/June/2018 +*/ +class SavingsAccountApplicationFragment : BaseFragment(), SavingsAccountApplicationView { + + @kotlin.jvm.JvmField + @BindView(R.id.sp_product_id) + var spProductId: Spinner? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_submission_date) + var tvSubmissionDate: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_client_name) + var tvClientName: TextView? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: SavingsAccountApplicationPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + private var rootView: View? = null + private var state: SavingsAccountState? = null + private var savingsWithAssociations: SavingsWithAssociations? = null + private var productIdAdapter: ArrayAdapter? = null + private var template: SavingsAccountTemplate? = null + private var productOptions: List? = null + private val productIdList: MutableList = ArrayList() + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + state = arguments!! + .getSerializable(Constants.SAVINGS_ACCOUNT_STATE) as SavingsAccountState + savingsWithAssociations = arguments?.getParcelable(Constants.SAVINGS_ACCOUNTS) + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_savings_account_application, container, + false) + ButterKnife.bind(this, rootView!!) + (activity as BaseActivity?)?.activityComponent?.inject(this) + presenter?.attachView(this) + presenter?.loadSavingsAccountApplicationTemplate(preferencesHelper?.clientId, state) + return rootView + } + + override fun showUserInterfaceSavingAccountApplication(template: SavingsAccountTemplate?) { + showUserInterface(template) + } + + override fun showSavingsAccountApplicationSuccessfully() { + showMessage(getString(R.string.new_saving_account_created_successfully)) + activity?.finish() + } + + override fun showUserInterfaceSavingAccountUpdate(template: SavingsAccountTemplate?) { + showUserInterface(template) + activity?.title = getString(R.string.string_savings_account, + getString(R.string.update)) + productIdAdapter?.getPosition(savingsWithAssociations + ?.savingsProductName)?.let { spProductId?.setSelection(it) } + } + + override fun showSavingsAccountUpdateSuccessfully() { + showMessage(getString(R.string.saving_account_updated_successfully)) + activity?.supportFragmentManager?.popBackStack() + } + + fun showUserInterface(template: SavingsAccountTemplate?) { + this.template = template + productOptions = template?.productOptions + if (productOptions != null) + for ((_, name) in productOptions as ArrayList) { + productIdList.add(name) + } + tvClientName?.text = template?.clientName + productIdAdapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, + productIdList) + productIdAdapter?.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + spProductId?.adapter = productIdAdapter + tvSubmissionDate?.text = MFDatePicker.datePickedAsString + } + + private fun submitSavingsAccountApplication() { + val payload = SavingsAccountApplicationPayload() + payload.clientId = template?.clientId + payload.productId = spProductId?.selectedItemPosition?.let { productOptions?.get(it)?.id } + payload.submittedOnDate = DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, + MFDatePicker.datePickedAsString) + presenter?.submitSavingsAccountApplication(payload) + } + + private fun updateSavingAccount() { + val payload = SavingsAccountUpdatePayload() + payload.clientId = template?.clientId?.toLong() + payload.productId = spProductId?.selectedItemPosition?.let { productOptions?.get(it)?.id }?.toLong() + presenter?.updateSavingsAccount(savingsWithAssociations?.accountNo, payload) + } + + @OnClick(R.id.btn_submit) + fun onSubmit() { + if (state == SavingsAccountState.CREATE) { + submitSavingsAccountApplication() + } else { + updateSavingAccount() + } + } + + override fun showError(error: String?) { + Toast.makeText(context, error, Toast.LENGTH_SHORT).show() + } + + override fun showMessage(showMessage: String?) { + Toast.makeText(context, showMessage, Toast.LENGTH_SHORT).show() + } + + override fun showProgress() { + showMifosProgressDialog(getString(R.string.progress_message_loading)) + } + + override fun hideProgress() { + hideMifosProgressDialog() + } + + override fun onDestroy() { + super.onDestroy() + hideProgress() + presenter?.detachView() + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance( + state: SavingsAccountState?, savingsWithAssociations: SavingsWithAssociations? + ): SavingsAccountApplicationFragment { + val fragment = SavingsAccountApplicationFragment() + val bundle = Bundle() + bundle.putSerializable(Constants.SAVINGS_ACCOUNT_STATE, state) + bundle.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations) + fragment.arguments = bundle + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountWithdrawFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountWithdrawFragment.java deleted file mode 100644 index 05082ee80b..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountWithdrawFragment.java +++ /dev/null @@ -1,151 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* - * Created by saksham on 02/July/2018 - */ - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.google.android.material.textfield.TextInputLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.presenters.SavingsAccountWithdrawPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.SavingsAccountWithdrawView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.MFDatePicker; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -public class SavingsAccountWithdrawFragment extends BaseFragment - implements SavingsAccountWithdrawView { - - @BindView(R.id.tv_client_name) - TextView tvClientName; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_withdrawal_date) - TextView tvWithdrawalDate; - - @BindView(R.id.til_remark) - TextInputLayout tilRemark; - - @Inject - SavingsAccountWithdrawPresenter presenter; - - private View rootView; - private SavingsWithAssociations savingsWithAssociations; - private SavingsAccountWithdrawPayload payload; - - public static SavingsAccountWithdrawFragment newInstance( - SavingsWithAssociations savingsWithAssociations) { - SavingsAccountWithdrawFragment fragment = new SavingsAccountWithdrawFragment(); - - Bundle bundle = new Bundle(); - bundle.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations); - fragment.setArguments(bundle); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - savingsWithAssociations = getArguments().getParcelable(Constants.SAVINGS_ACCOUNTS); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_savings_account_withdraw_fragment, - container, false); - ButterKnife.bind(this, rootView); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - presenter.attachView(this); - showUserInterface(); - return rootView; - } - - @OnClick(R.id.btn_withdraw_savings_account) - void onWithdrawSavingsAccount() { - submitWithdrawSavingsAccount(); - } - - @Override - public void showUserInterface() { - getActivity().setTitle(getString(R.string.withdraw_savings_account)); - tvAccountNumber.setText(savingsWithAssociations.getAccountNo()); - tvClientName.setText(savingsWithAssociations.getClientName()); - tvWithdrawalDate.setText(MFDatePicker.getDatePickedAsString()); - } - - public boolean isFormIncomplete() { - boolean rv = false; - if (tilRemark.getEditText().getText().toString().trim().length() == 0) { - rv = true; - tilRemark.setError(getString(R.string.error_validation_blank, - getString(R.string.remark))); - } - return rv; - } - - public void submitWithdrawSavingsAccount() { - tilRemark.setErrorEnabled(false); - if (!isFormIncomplete()) { - payload = new SavingsAccountWithdrawPayload(); - payload.setNote(tilRemark.getEditText().getText().toString()); - payload.setWithdrawnOnDate(MFDatePicker.getDatePickedAsString()); - presenter.submitWithdrawSavingsAccount(savingsWithAssociations.getAccountNo(), payload); - } - } - - @Override - public void showSavingsAccountWithdrawSuccessfully() { - showMessage(getString(R.string.savings_account_withdraw_successful)); - getActivity().getSupportFragmentManager().popBackStack(); - } - - @Override - public void showMessage(String message) { - Toaster.show(rootView, message); - } - - @Override - public void showError(String error) { - Toaster.show(rootView, error); - } - - @Override - public void showProgress() { - showMifosProgressDialog(getString(R.string.progress_message_loading)); - - } - - @Override - public void hideProgress() { - hideMifosProgressDialog(); - } - - @Override - public void onDestroy() { - super.onDestroy(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountWithdrawFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountWithdrawFragment.kt new file mode 100644 index 0000000000..3d0a4f52ec --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsAccountWithdrawFragment.kt @@ -0,0 +1,141 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.google.android.material.textfield.TextInputLayout + +import org.mifos.mobile.R +import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.presenters.SavingsAccountWithdrawPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.SavingsAccountWithdrawView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.MFDatePicker +import org.mifos.mobile.utils.Toaster + +import javax.inject.Inject + +/* +* Created by saksham on 02/July/2018 +*/ +class SavingsAccountWithdrawFragment : BaseFragment(), SavingsAccountWithdrawView { + @kotlin.jvm.JvmField + @BindView(R.id.tv_client_name) + var tvClientName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_withdrawal_date) + var tvWithdrawalDate: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_remark) + var tilRemark: TextInputLayout? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: SavingsAccountWithdrawPresenter? = null + private var rootView: View? = null + private var savingsWithAssociations: SavingsWithAssociations? = null + private var payload: SavingsAccountWithdrawPayload? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + savingsWithAssociations = arguments?.getParcelable(Constants.SAVINGS_ACCOUNTS) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_savings_account_withdraw_fragment, + container, false) + ButterKnife.bind(this, rootView!!) + (activity as BaseActivity?)?.activityComponent?.inject(this) + presenter?.attachView(this) + showUserInterface() + return rootView + } + + @OnClick(R.id.btn_withdraw_savings_account) + fun onWithdrawSavingsAccount() { + submitWithdrawSavingsAccount() + } + + override fun showUserInterface() { + activity?.title = getString(R.string.withdraw_savings_account) + tvAccountNumber?.text = savingsWithAssociations?.accountNo + tvClientName?.text = savingsWithAssociations?.clientName + tvWithdrawalDate?.text = MFDatePicker.datePickedAsString + } + + private val isFormIncomplete: Boolean? + get() { + var rv = false + if (tilRemark?.editText?.text.toString().trim { it <= ' ' }.isEmpty()) { + rv = true + tilRemark?.error = getString(R.string.error_validation_blank, + getString(R.string.remark)) + } + return rv + } + + override fun submitWithdrawSavingsAccount() { + tilRemark?.isErrorEnabled = false + if (isFormIncomplete == false) { + payload = SavingsAccountWithdrawPayload() + payload?.note = tilRemark?.editText?.text.toString() + payload?.withdrawnOnDate = MFDatePicker.datePickedAsString + presenter?.submitWithdrawSavingsAccount(savingsWithAssociations?.accountNo, payload) + } + } + + override fun showSavingsAccountWithdrawSuccessfully() { + showMessage(getString(R.string.savings_account_withdraw_successful)) + activity?.supportFragmentManager?.popBackStack() + } + + override fun showMessage(message: String?) { + Toaster.show(rootView, message) + } + + override fun showError(error: String?) { + Toaster.show(rootView, error) + } + + override fun showProgress() { + showMifosProgressDialog(getString(R.string.progress_message_loading)) + } + + override fun hideProgress() { + hideMifosProgressDialog() + } + + override fun onDestroy() { + super.onDestroy() + presenter?.detachView() + } + + companion object { + fun newInstance( + savingsWithAssociations: SavingsWithAssociations?): SavingsAccountWithdrawFragment { + val fragment = SavingsAccountWithdrawFragment() + val bundle = Bundle() + bundle.putParcelable(Constants.SAVINGS_ACCOUNTS, savingsWithAssociations) + fragment.arguments = bundle + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsMakeTransferFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsMakeTransferFragment.java deleted file mode 100644 index 9f16e74446..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsMakeTransferFragment.java +++ /dev/null @@ -1,492 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatButton; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentTransaction; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.payload.AccountDetail; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.models.templates.account.AccountOption; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.presenters.SavingsMakeTransferPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.AccountsSpinnerAdapter; -import org.mifos.mobile.ui.enums.TransferType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.SavingsMakeTransferMvpView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.MFDatePicker; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.ProcessView; -import org.mifos.mobile.utils.Toaster; -import org.mifos.mobile.utils.Utils; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by Rajan Maurya on 10/03/17. - */ -public class SavingsMakeTransferFragment extends BaseFragment implements - SavingsMakeTransferMvpView, AdapterView.OnItemSelectedListener { - - @BindView(R.id.sp_pay_to) - Spinner spPayTo; - - @BindView(R.id.sp_pay_from) - Spinner spPayFrom; - - @BindView(R.id.et_amount) - EditText etAmount; - - @BindView(R.id.process_one) - ProcessView pvOne; - - @BindView(R.id.process_two) - ProcessView pvTwo; - - @BindView(R.id.process_three) - ProcessView pvThree; - - @BindView(R.id.process_four) - ProcessView pvFour; - - @BindView(R.id.btn_pay_to) - AppCompatButton btnPayTo; - - @BindView(R.id.btn_pay_from) - AppCompatButton btnPayFrom; - - @BindView(R.id.btn_amount) - AppCompatButton btnAmount; - - @BindView(R.id.ll_review) - LinearLayout llReview; - - @BindView(R.id.tv_select_pay_from) - TextView tvSelectPayFrom; - - @BindView(R.id.tv_select_amount) - TextView tvEnterAmount; - - @BindView(R.id.tv_enter_remark) - TextView tvEnterRemark; - - @BindView(R.id.et_remark) - EditText etRemark; - - @BindView(R.id.ll_make_transfer) - LinearLayout layoutMakeTransfer; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - SavingsMakeTransferPresenter savingsMakeTransferPresenter; - - View rootView; - - private List listPayTo = new ArrayList<>(); - private List listPayFrom = new ArrayList<>(); - - private AccountsSpinnerAdapter payToAdapter; - private AccountsSpinnerAdapter payFromAdapter; - - private TransferPayload transferPayload; - private String transferDate; - private AccountOption toAccountOption, fromAccountOption; - private AccountOptionsTemplate accountOptionsTemplate; - private String transferType, payTo, payFrom; - private long accountId; - private double outStandingBalance; - private boolean isLoanRepayment; - private SweetUIErrorHandler sweetUIErrorHandler; - - /** - * Provides an instance of {@link SavingsMakeTransferFragment}, use {@code transferType} as - * {@code Constants.TRANSFER_PAY_TO} when we want to deposit and - * {@code Constants.TRANSFER_PAY_FROM} when we want to make a transfer - * - * @param accountId Saving account Id - * @param transferType Type of transfer i.e. {@code Constants.TRANSFER_PAY_TO} or - * {@code Constants.TRANSFER_PAY_FROM} - * @return Instance of {@link SavingsMakeTransferFragment} - */ - public static SavingsMakeTransferFragment newInstance(long accountId, String transferType) { - SavingsMakeTransferFragment transferFragment = new SavingsMakeTransferFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.ACCOUNT_ID, accountId); - args.putString(Constants.TRANSFER_TYPE, transferType); - transferFragment.setArguments(args); - return transferFragment; - } - - public static SavingsMakeTransferFragment newInstance(long accountId, double outstandingBalance, - String transferType) { - SavingsMakeTransferFragment transferFragment = new SavingsMakeTransferFragment(); - Bundle args = new Bundle(); - args.putLong(Constants.ACCOUNT_ID, accountId); - args.putString(Constants.TRANSFER_TYPE, transferType); - args.putDouble(Constants.OUTSTANDING_BALANCE, outstandingBalance); - args.putBoolean(Constants.LOAN_REPAYMENT, true); - transferFragment.setArguments(args); - return transferFragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - accountId = getArguments().getLong(Constants.ACCOUNT_ID); - transferType = getArguments().getString(Constants.TRANSFER_TYPE); - - if (getArguments().getBoolean(Constants.LOAN_REPAYMENT, false)) { - isLoanRepayment = true; - outStandingBalance = getArguments().getDouble(Constants.OUTSTANDING_BALANCE); - } - } - setHasOptionsMenu(true); - } - - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_savings_make_transfer, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - setToolbarTitle(getString(R.string.transfer)); - ButterKnife.bind(this, rootView); - savingsMakeTransferPresenter.attachView(this); - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - showUserInterface(); - if (savedInstanceState == null) { - savingsMakeTransferPresenter.loanAccountTransferTemplate(); - } - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.TEMPLATE, accountOptionsTemplate); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showSavingsAccountTemplate((AccountOptionsTemplate) savedInstanceState. - getParcelable(Constants.TEMPLATE)); - } - } - - /** - * Checks validation of {@code etRemark} and then opens {@link TransferProcessFragment} for - * initiating the transfer - */ - @OnClick(R.id.btn_review_transfer) - void reviewTransfer() { - - if (etRemark.getText().toString().trim().equals("")) { - showToaster(getString(R.string.remark_is_mandatory)); - return; - } - - transferPayload = new TransferPayload(); - transferPayload.setFromAccountId(fromAccountOption.getAccountId()); - transferPayload.setFromClientId(fromAccountOption.getClientId()); - transferPayload.setFromAccountType(fromAccountOption.getAccountType().getId()); - transferPayload.setFromOfficeId(fromAccountOption.getOfficeId()); - transferPayload.setToOfficeId(toAccountOption.getOfficeId()); - transferPayload.setToAccountId(toAccountOption.getAccountId()); - transferPayload.setToClientId(toAccountOption.getClientId()); - transferPayload.setToAccountType(toAccountOption.getAccountType().getId()); - transferPayload.setTransferDate(transferDate); - transferPayload.setTransferAmount(Double.parseDouble(etAmount.getText().toString())); - transferPayload.setTransferDescription(etRemark.getText().toString()); - transferPayload.setFromAccountNumber(fromAccountOption.getAccountNo()); - transferPayload.setToAccountNumber(toAccountOption.getAccountNo()); - - ((BaseActivity) getActivity()).replaceFragment(TransferProcessFragment. - newInstance(transferPayload, TransferType.SELF), true, R.id.container); - } - - /** - * Cancels the transfer by poping current Fragment - */ - @OnClick(R.id.btn_cancel_transfer) - void cancelTransfer() { - getActivity().getSupportFragmentManager().popBackStack(); - } - - @OnClick(R.id.btn_try_again) - void onRetry() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(layoutMakeTransfer, layoutError); - savingsMakeTransferPresenter.loanAccountTransferTemplate(); - } else { - Toaster.show(rootView, getString(R.string.internet_not_connected)); - } - } - - /** - * Setting up basic components - */ - @Override - public void showUserInterface() { - pvOne.setCurrentActive(); - payFromAdapter = new AccountsSpinnerAdapter(getActivity(), R.layout.account_spinner_layout, - listPayFrom); - payFromAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice); - spPayFrom.setAdapter(payFromAdapter); - spPayFrom.setOnItemSelectedListener(this); - - payToAdapter = new AccountsSpinnerAdapter(getActivity(), R.layout.account_spinner_layout, - listPayTo); - payToAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice); - spPayTo.setAdapter(payToAdapter); - spPayTo.setOnItemSelectedListener(this); - transferDate = DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, - MFDatePicker.getDatePickedAsString()); - - if (isLoanRepayment) { - etAmount.setText(String.valueOf(outStandingBalance)); - etAmount.setFocusable(false); - } - - } - - /** - * Provides with {@code accountOptionsTemplate} fetched from server which is used to update - * {@code listPayFrom} and {@code listPayTo} - * - * @param accountOptionsTemplate Template for account transfer - */ - @Override - public void showSavingsAccountTemplate(AccountOptionsTemplate accountOptionsTemplate) { - this.accountOptionsTemplate = accountOptionsTemplate; - listPayFrom.clear(); - listPayFrom.addAll(savingsMakeTransferPresenter.getAccountNumbers( - accountOptionsTemplate.getFromAccountOptions(), true)); - listPayTo.clear(); - listPayTo.addAll(savingsMakeTransferPresenter.getAccountNumbers( - accountOptionsTemplate.getToAccountOptions(), false)); - payToAdapter.notifyDataSetChanged(); - payFromAdapter.notifyDataSetChanged(); - } - - /** - * Shows a {@link Snackbar} with {@code message} - * - * @param message String to be shown - */ - @Override - public void showToaster(String message) { - Toaster.show(rootView, message); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showError(String message) { - if (!Network.isConnected(getContext())) { - sweetUIErrorHandler.showSweetNoInternetUI(layoutMakeTransfer, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(message, layoutMakeTransfer, layoutError); - Toaster.show(rootView, message); - } - } - - @Override - public void showProgressDialog() { - showMifosProgressDialog(getString(R.string.making_transfer)); - } - - @Override - public void hideProgressDialog() { - hideMifosProgressDialog(); - } - - @Override - public void showProgress() { - layoutMakeTransfer.setVisibility(View.GONE); - showProgressBar(); - } - - @Override - public void hideProgress() { - layoutMakeTransfer.setVisibility(View.VISIBLE); - hideProgressBar(); - } - - /** - * Callback for {@code spPayFrom} and {@code spPayTo} - */ - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (parent.getId()) { - case R.id.sp_pay_to: - toAccountOption = accountOptionsTemplate.getToAccountOptions().get(position); - payTo = toAccountOption.getAccountNo(); - break; - case R.id.sp_pay_from: - fromAccountOption = accountOptionsTemplate.getFromAccountOptions().get(position); - payFrom = fromAccountOption.getAccountNo(); - break; - } - - switch (transferType) { - case Constants.TRANSFER_PAY_TO: - setToolbarTitle(getString(R.string.deposit)); - toAccountOption = savingsMakeTransferPresenter - .searchAccount(accountOptionsTemplate.getToAccountOptions(), accountId); - spPayTo.setSelection(accountOptionsTemplate.getToAccountOptions() - .indexOf(toAccountOption)); - spPayTo.setEnabled(false); - pvOne.setCurrentCompeleted(); - break; - case Constants.TRANSFER_PAY_FROM: - setToolbarTitle(getString(R.string.transfer)); - fromAccountOption = savingsMakeTransferPresenter - .searchAccount(accountOptionsTemplate.getFromAccountOptions(), accountId); - spPayFrom.setSelection(accountOptionsTemplate.getFromAccountOptions() - .indexOf(fromAccountOption)); - spPayFrom.setEnabled(false); - spPayFrom.setVisibility(View.VISIBLE); - tvSelectPayFrom.setVisibility(View.GONE); - pvTwo.setCurrentCompeleted(); - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - - /** - * Disables {@code spPayTo} {@link Spinner} and sets {@code pvOne} to completed and make - * {@code pvTwo} active - */ - @OnClick(R.id.btn_pay_to) - public void payToSelected() { - pvOne.setCurrentCompeleted(); - pvTwo.setCurrentActive(); - - btnPayTo.setVisibility(View.GONE); - tvSelectPayFrom.setVisibility(View.GONE); - btnPayFrom.setVisibility(View.VISIBLE); - spPayFrom.setVisibility(View.VISIBLE); - spPayTo.setEnabled(false); - } - - /** - * Checks validation of {@code spPayTo} {@link Spinner}.
- * Disables {@code spPayFrom} {@link Spinner} and sets {@code pvTwo} to completed and make - * {@code pvThree} active - */ - @OnClick(R.id.btn_pay_from) - public void payFromSelected() { - if (payTo.equals(payFrom)) { - showToaster(getString(R.string.error_same_account_transfer)); - return; - } - pvTwo.setCurrentCompeleted(); - pvThree.setCurrentActive(); - - btnPayFrom.setVisibility(View.GONE); - tvEnterAmount.setVisibility(View.GONE); - etAmount.setVisibility(View.VISIBLE); - btnAmount.setVisibility(View.VISIBLE); - spPayFrom.setEnabled(false); - } - - /** - * Checks validation of {@code etAmount} {@link EditText}.
- * Disables {@code etAmount} and sets {@code pvThree} to completed and make - * {@code pvFour} active - */ - @OnClick(R.id.btn_amount) - public void amountSet() { - - if (etAmount.getText().toString().equals("")) { - showToaster(getString(R.string.enter_amount)); - return; - } - - if (etAmount.getText().toString().equals(".")) { - showToaster(getString(R.string.invalid_amount)); - return; - } - - if (Double.parseDouble(etAmount.getText().toString()) == 0) { - showToaster(getString(R.string.amount_greater_than_zero)); - return; - } - - pvThree.setCurrentCompeleted(); - pvFour.setCurrentActive(); - - btnAmount.setVisibility(View.GONE); - tvEnterRemark.setVisibility(View.GONE); - etRemark.setVisibility(View.VISIBLE); - llReview.setVisibility(View.VISIBLE); - etAmount.setEnabled(false); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_transfer, menu); - Utils.setToolbarIconColor(getActivity(), menu, R.color.white); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == R.id.menu_refresh_transfer) { - FragmentTransaction transaction = getFragmentManager().beginTransaction(); - Fragment currFragment = getActivity().getSupportFragmentManager() - .findFragmentById(R.id.container); - transaction.detach(currFragment); - transaction.attach(currFragment); - transaction.commit(); - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - hideMifosProgressDialog(); - savingsMakeTransferPresenter.detachView(); - } -} - diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsMakeTransferFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsMakeTransferFragment.kt new file mode 100644 index 0000000000..130356dac4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/SavingsMakeTransferFragment.kt @@ -0,0 +1,463 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.os.Parcelable +import android.view.* +import android.widget.* +import android.widget.AdapterView.OnItemSelectedListener + +import androidx.appcompat.widget.AppCompatButton + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.payload.AccountDetail +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.models.templates.account.AccountOption +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.presenters.SavingsMakeTransferPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.AccountsSpinnerAdapter +import org.mifos.mobile.ui.enums.TransferType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.SavingsMakeTransferMvpView +import org.mifos.mobile.utils.* + +import java.util.* +import javax.inject.Inject + +/** + * Created by Rajan Maurya on 10/03/17. + */ +class SavingsMakeTransferFragment : BaseFragment(), SavingsMakeTransferMvpView, OnItemSelectedListener { + + @kotlin.jvm.JvmField + @BindView(R.id.sp_pay_to) + var spPayTo: Spinner? = null + + @kotlin.jvm.JvmField + @BindView(R.id.sp_pay_from) + var spPayFrom: Spinner? = null + + @kotlin.jvm.JvmField + @BindView(R.id.et_amount) + var etAmount: EditText? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_one) + var pvOne: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_two) + var pvTwo: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_three) + var pvThree: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_four) + var pvFour: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_pay_to) + var btnPayTo: AppCompatButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_pay_from) + var btnPayFrom: AppCompatButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_amount) + var btnAmount: AppCompatButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_review) + var llReview: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_select_pay_from) + var tvSelectPayFrom: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_select_amount) + var tvEnterAmount: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_enter_remark) + var tvEnterRemark: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.et_remark) + var etRemark: EditText? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_make_transfer) + var layoutMakeTransfer: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @Inject + var savingsMakeTransferPresenter: SavingsMakeTransferPresenter? = null + var rootView: View? = null + private val listPayTo: MutableList = ArrayList() + private val listPayFrom: MutableList = ArrayList() + private var payToAdapter: AccountsSpinnerAdapter? = null + private var payFromAdapter: AccountsSpinnerAdapter? = null + private var transferPayload: TransferPayload? = null + private var transferDate: String? = null + private var toAccountOption: AccountOption? = null + private var fromAccountOption: AccountOption? = null + private var accountOptionsTemplate: AccountOptionsTemplate? = null + private var transferType: String? = null + private var payTo: String? = null + private var payFrom: String? = null + private var accountId: Long? = 0 + private var outStandingBalance: Double? = 0.0 + private var isLoanRepayment = false + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + accountId = arguments?.getLong(Constants.ACCOUNT_ID) + transferType = arguments?.getString(Constants.TRANSFER_TYPE) + if (arguments?.getBoolean(Constants.LOAN_REPAYMENT, false) == true) { + isLoanRepayment = true + outStandingBalance = arguments?.getDouble(Constants.OUTSTANDING_BALANCE) + } + } + setHasOptionsMenu(true) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_savings_make_transfer, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + setToolbarTitle(getString(R.string.transfer)) + ButterKnife.bind(this, rootView!!) + savingsMakeTransferPresenter?.attachView(this) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + showUserInterface() + if (savedInstanceState == null) { + savingsMakeTransferPresenter?.loanAccountTransferTemplate() + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.TEMPLATE, accountOptionsTemplate) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showSavingsAccountTemplate(savedInstanceState.getParcelable(Constants.TEMPLATE) as AccountOptionsTemplate) + } + } + + /** + * Checks validation of `etRemark` and then opens [TransferProcessFragment] for + * initiating the transfer + */ + @OnClick(R.id.btn_review_transfer) + fun reviewTransfer() { + if (etRemark?.text.toString().trim { it <= ' ' } == "") { + showToaster(getString(R.string.remark_is_mandatory)) + return + } + transferPayload = TransferPayload() + transferPayload?.fromAccountId = fromAccountOption?.accountId + transferPayload?.fromClientId = fromAccountOption?.clientId + transferPayload?.fromAccountType = fromAccountOption?.accountType?.id + transferPayload?.fromOfficeId = fromAccountOption?.officeId + transferPayload?.toOfficeId = toAccountOption?.officeId + transferPayload?.toAccountId = toAccountOption?.accountId + transferPayload?.toClientId = toAccountOption?.clientId + transferPayload?.toAccountType = toAccountOption?.accountType?.id + transferPayload?.transferDate = transferDate + transferPayload?.transferAmount = etAmount?.text.toString().toDouble() + transferPayload?.transferDescription = etRemark?.text.toString() + transferPayload?.fromAccountNumber = fromAccountOption?.accountNo + transferPayload?.toAccountNumber = toAccountOption?.accountNo + (activity as BaseActivity?)?.replaceFragment(TransferProcessFragment.newInstance(transferPayload, TransferType.SELF), true, R.id.container) + } + + /** + * Cancels the transfer by poping current Fragment + */ + @OnClick(R.id.btn_cancel_transfer) + fun cancelTransfer() { + activity?.supportFragmentManager?.popBackStack() + } + + @OnClick(R.id.btn_try_again) + fun onRetry() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(layoutMakeTransfer, layoutError) + savingsMakeTransferPresenter?.loanAccountTransferTemplate() + } else { + Toaster.show(rootView, getString(R.string.internet_not_connected)) + } + } + + /** + * Setting up basic components + */ + override fun showUserInterface() { + pvOne?.setCurrentActive() + payFromAdapter = activity?.applicationContext?.let { + AccountsSpinnerAdapter(it, R.layout.account_spinner_layout, + listPayFrom) + } + payFromAdapter?.setDropDownViewResource(android.R.layout.select_dialog_singlechoice) + spPayFrom?.adapter = payFromAdapter + spPayFrom?.onItemSelectedListener = this + payToAdapter = activity?.applicationContext?.let { + AccountsSpinnerAdapter(it, R.layout.account_spinner_layout, + listPayTo) + } + payToAdapter?.setDropDownViewResource(android.R.layout.select_dialog_singlechoice) + spPayTo?.adapter = payToAdapter + spPayTo?.onItemSelectedListener = this + transferDate = DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, + MFDatePicker.datePickedAsString) + if (isLoanRepayment) { + etAmount?.setText(outStandingBalance.toString()) + etAmount?.isFocusable = false + } + } + + /** + * Provides with `accountOptionsTemplate` fetched from server which is used to update + * `listPayFrom` and `listPayTo` + * + * @param accountOptionsTemplate Template for account transfer + */ + override fun showSavingsAccountTemplate(accountOptionsTemplate: AccountOptionsTemplate?) { + this.accountOptionsTemplate = accountOptionsTemplate + listPayFrom.clear() + savingsMakeTransferPresenter?.getAccountNumbers( + accountOptionsTemplate?.fromAccountOptions, true)?.let { listPayFrom.addAll(it) } + listPayTo.clear() + savingsMakeTransferPresenter?.getAccountNumbers( + accountOptionsTemplate?.toAccountOptions, false)?.let { listPayTo.addAll(it) } + payToAdapter?.notifyDataSetChanged() + payFromAdapter?.notifyDataSetChanged() + } + + /** + * Shows a {@link Snackbar} with `message` + * + * @param message String to be shown + */ + override fun showToaster(message: String?) { + Toaster.show(rootView, message) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showError(message: String?) { + if (!Network.isConnected(context)) { + sweetUIErrorHandler?.showSweetNoInternetUI(layoutMakeTransfer, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(message, layoutMakeTransfer, layoutError) + Toaster.show(rootView, message) + } + } + + override fun showProgressDialog() { + showMifosProgressDialog(getString(R.string.making_transfer)) + } + + override fun hideProgressDialog() { + hideMifosProgressDialog() + } + + override fun showProgress() { + layoutMakeTransfer?.visibility = View.GONE + showProgressBar() + } + + override fun hideProgress() { + layoutMakeTransfer?.visibility = View.VISIBLE + hideProgressBar() + } + + /** + * Callback for `spPayFrom` and `spPayTo` + */ + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + when (parent?.id) { + R.id.sp_pay_to -> { + toAccountOption = accountOptionsTemplate?.toAccountOptions?.get(position) + payTo = toAccountOption?.accountNo + } + R.id.sp_pay_from -> { + fromAccountOption = accountOptionsTemplate?.fromAccountOptions?.get(position) + payFrom = fromAccountOption?.accountNo + } + } + when (transferType) { + Constants.TRANSFER_PAY_TO -> { + setToolbarTitle(getString(R.string.deposit)) + toAccountOption = savingsMakeTransferPresenter + ?.searchAccount(accountOptionsTemplate?.toAccountOptions, accountId) + spPayTo?.setSelection(accountOptionsTemplate?.toAccountOptions + ?.indexOf(toAccountOption)!!) + spPayTo?.isEnabled = false + pvOne?.setCurrentCompleted() + } + Constants.TRANSFER_PAY_FROM -> { + setToolbarTitle(getString(R.string.transfer)) + fromAccountOption = savingsMakeTransferPresenter + ?.searchAccount(accountOptionsTemplate?.fromAccountOptions, accountId) + spPayFrom?.setSelection(accountOptionsTemplate?.fromAccountOptions + ?.indexOf(fromAccountOption)!!) + spPayFrom?.isEnabled = false + spPayFrom?.visibility = View.VISIBLE + tvSelectPayFrom?.visibility = View.GONE + pvTwo?.setCurrentCompleted() + } + } + } + + override fun onNothingSelected(parent: AdapterView<*>?) {} + + /** + * Disables `spPayTo` [Spinner] and sets `pvOne` to completed and make + * `pvTwo` active + */ + @OnClick(R.id.btn_pay_to) + fun payToSelected() { + pvOne?.setCurrentCompleted() + pvTwo?.setCurrentActive() + btnPayTo?.visibility = View.GONE + tvSelectPayFrom?.visibility = View.GONE + btnPayFrom?.visibility = View.VISIBLE + spPayFrom?.visibility = View.VISIBLE + spPayTo?.isEnabled = false + } + + /** + * Checks validation of `spPayTo` [Spinner].

+ * Disables `spPayFrom` [Spinner] and sets `pvTwo` to completed and make + * `pvThree` active + */ + @OnClick(R.id.btn_pay_from) + fun payFromSelected() { + if (payTo == payFrom) { + showToaster(getString(R.string.error_same_account_transfer)) + return + } + pvTwo?.setCurrentCompleted() + pvThree?.setCurrentActive() + btnPayFrom?.visibility = View.GONE + tvEnterAmount?.visibility = View.GONE + etAmount?.visibility = View.VISIBLE + btnAmount?.visibility = View.VISIBLE + spPayFrom?.isEnabled = false + } + + /** + * Checks validation of `etAmount` [EditText].

+ * Disables `etAmount` and sets `pvThree` to completed and make + * `pvFour` active + */ + @OnClick(R.id.btn_amount) + fun amountSet() { + if (etAmount?.text.toString() == "") { + showToaster(getString(R.string.enter_amount)) + return + } + if (etAmount?.text.toString() == ".") { + showToaster(getString(R.string.invalid_amount)) + return + } + if (etAmount?.text.toString().toDouble() == 0.0) { + showToaster(getString(R.string.amount_greater_than_zero)) + return + } + pvThree?.setCurrentCompleted() + pvFour?.setCurrentActive() + btnAmount?.visibility = View.GONE + tvEnterRemark?.visibility = View.GONE + etRemark?.visibility = View.VISIBLE + llReview?.visibility = View.VISIBLE + etAmount?.isEnabled = false + } + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + super.onCreateOptionsMenu(menu, inflater) + inflater.inflate(R.menu.menu_transfer, menu) + Utils.setToolbarIconColor(activity, menu, R.color.white) + } + + override fun onOptionsItemSelected(item: MenuItem?): Boolean { + if (item?.itemId == R.id.menu_refresh_transfer) { + val transaction = fragmentManager?.beginTransaction() + val currFragment = activity?.supportFragmentManager + ?.findFragmentById(R.id.container) + if (currFragment != null) { + transaction?.detach(currFragment) + transaction?.attach(currFragment) + } + transaction?.commit() + } + return super.onOptionsItemSelected(item) + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + hideMifosProgressDialog() + savingsMakeTransferPresenter?.detachView() + } + + companion object { + /** + * Provides an instance of [SavingsMakeTransferFragment], use `transferType` as + * `Constants.TRANSFER_PAY_TO` when we want to deposit and + * `Constants.TRANSFER_PAY_FROM` when we want to make a transfer + * + * @param accountId Saving account Id + * @param transferType Type of transfer i.e. `Constants.TRANSFER_PAY_TO` or + * `Constants.TRANSFER_PAY_FROM` + * @return Instance of [SavingsMakeTransferFragment] + */ + fun newInstance(accountId: Long?, transferType: String?): SavingsMakeTransferFragment { + val transferFragment = SavingsMakeTransferFragment() + val args = Bundle() + if (accountId != null) args.putLong(Constants.ACCOUNT_ID, accountId) + args.putString(Constants.TRANSFER_TYPE, transferType) + transferFragment.arguments = args + return transferFragment + } + + fun newInstance( + accountId: Long?, outstandingBalance: Double?, + transferType: String? + ): SavingsMakeTransferFragment { + val transferFragment = SavingsMakeTransferFragment() + val args = Bundle() + if (accountId != null) args.putLong(Constants.ACCOUNT_ID, accountId) + args.putString(Constants.TRANSFER_TYPE, transferType) + if (outstandingBalance != null) args.putDouble(Constants.OUTSTANDING_BALANCE, outstandingBalance) + args.putBoolean(Constants.LOAN_REPAYMENT, true) + transferFragment.arguments = args + return transferFragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SettingsFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/SettingsFragment.java deleted file mode 100644 index aa75127bee..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/SettingsFragment.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Bundle; - -import org.mifos.mobile.R; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.utils.ConfigurationDialogFragmentCompat; -import org.mifos.mobile.utils.ConfigurationPreference; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.LanguageHelper; - -import androidx.fragment.app.DialogFragment; -import androidx.preference.ListPreference; -import androidx.preference.Preference; -import androidx.preference.PreferenceFragmentCompat; - -/** - * Created by dilpreet on 02/10/17. - */ - -public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences. - OnSharedPreferenceChangeListener { - - public static SettingsFragment newInstance() { - SettingsFragment fragment = new SettingsFragment(); - return fragment; - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.settings_preference); - } - - @Override - public void onResume() { - super.onResume(); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences(). - unregisterOnSharedPreferenceChangeListener(this); - } - - @Override - public void onDisplayPreferenceDialog(Preference preference) { - DialogFragment dialogFragment = null; - if (preference instanceof ConfigurationPreference) { - dialogFragment = new ConfigurationDialogFragmentCompat(); - Bundle bundle = new Bundle(1); - bundle.putString("key", preference.getKey()); - dialogFragment.setArguments(bundle); - } - - if (dialogFragment != null) { - dialogFragment.setTargetFragment(this, 0); - dialogFragment.show(this.getFragmentManager(), - "android.support.v7.preference.PreferenceFragment.DIALOG"); - } else { - super.onDisplayPreferenceDialog(preference); - } - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { - Preference preference = findPreference(s); - if (preference instanceof ListPreference) { - ListPreference listPreference = (ListPreference) preference; - LanguageHelper.setLocale(getContext(), listPreference.getValue()); - Intent intent = new Intent(getActivity(), getActivity().getClass()); - intent.putExtra(Constants.HAS_SETTINGS_CHANGED, true); - startActivity(intent); - getActivity().finish(); - } - } - - @Override - public boolean onPreferenceTreeClick(Preference preference) { - switch (preference.getKey()) { - case Constants.PASSWORD: - ((BaseActivity) getActivity()).replaceFragment(UpdatePasswordFragment - .newInstance(), true, R.id.container); - break; - } - return super.onPreferenceTreeClick(preference); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/SettingsFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/SettingsFragment.kt new file mode 100644 index 0000000000..ba8261b684 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/SettingsFragment.kt @@ -0,0 +1,77 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.content.SharedPreferences +import android.content.SharedPreferences.OnSharedPreferenceChangeListener +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import androidx.preference.ListPreference +import androidx.preference.Preference +import androidx.preference.PreferenceFragmentCompat +import org.mifos.mobile.R +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.utils.ConfigurationDialogFragmentCompat +import org.mifos.mobile.utils.ConfigurationPreference +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.LanguageHelper + +/** + * Created by dilpreet on 02/10/17. + */ +class SettingsFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener { + override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { + addPreferencesFromResource(R.xml.settings_preference) + } + + override fun onResume() { + super.onResume() + preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) + } + + override fun onPause() { + super.onPause() + preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) + } + + override fun onDisplayPreferenceDialog(preference: Preference) { + var dialogFragment: DialogFragment? = null + if (preference is ConfigurationPreference) { + dialogFragment = ConfigurationDialogFragmentCompat() + val bundle = Bundle(1) + bundle.putString("key", preference.getKey()) + dialogFragment.setArguments(bundle) + } + if (dialogFragment != null) { + dialogFragment.setTargetFragment(this, 0) + dialogFragment.show(this.fragmentManager, + "android.support.v7.preference.PreferenceFragment.DIALOG") + } else { + super.onDisplayPreferenceDialog(preference) + } + } + + override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, s: String) { + val preference = findPreference(s) + if (preference is ListPreference) { + LanguageHelper.setLocale(context, preference.value) + val intent = Intent(activity, activity?.javaClass) + intent.putExtra(Constants.HAS_SETTINGS_CHANGED, true) + startActivity(intent) + activity?.finish() + } + } + + override fun onPreferenceTreeClick(preference: Preference): Boolean { + when (preference.key) { + Constants.PASSWORD -> (activity as BaseActivity?)?.replaceFragment(UpdatePasswordFragment.newInstance(), true, R.id.container) + } + return super.onPreferenceTreeClick(preference) + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): SettingsFragment { + return SettingsFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/ThirdPartyTransferFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/ThirdPartyTransferFragment.java deleted file mode 100644 index d7a0a17579..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/ThirdPartyTransferFragment.java +++ /dev/null @@ -1,466 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.os.Bundle; -import android.os.Parcelable; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.Spinner; -import android.widget.TextView; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.beneficiary.BeneficiaryDetail; -import org.mifos.mobile.models.payload.AccountDetail; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.models.templates.account.AccountOption; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.presenters.ThirdPartyTransferPresenter; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.adapters.AccountsSpinnerAdapter; -import org.mifos.mobile.ui.adapters.BeneficiarySpinnerAdapter; -import org.mifos.mobile.ui.enums.TransferType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.ThirdPartyTransferView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.MFDatePicker; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.ProcessView; -import org.mifos.mobile.utils.Toaster; -import org.mifos.mobile.utils.Utils; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatButton; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentTransaction; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 21/6/17. - */ - -public class ThirdPartyTransferFragment extends BaseFragment implements ThirdPartyTransferView, - AdapterView.OnItemSelectedListener { - - @BindView(R.id.sp_beneficiary) - Spinner spBeneficiary; - - @BindView(R.id.sp_pay_from) - Spinner spPayFrom; - - @BindView(R.id.et_amount) - EditText etAmount; - - @BindView(R.id.et_remark) - EditText etRemark; - - @BindView(R.id.ll_make_transfer) - LinearLayout layoutMakeTransfer; - - @BindView(R.id.process_one) - ProcessView pvOne; - - @BindView(R.id.process_two) - ProcessView pvTwo; - - @BindView(R.id.process_three) - ProcessView pvThree; - - @BindView(R.id.process_four) - ProcessView pvFour; - - @BindView(R.id.btn_pay_to) - AppCompatButton btnPayTo; - - @BindView(R.id.btn_pay_from) - AppCompatButton btnPayFrom; - - @BindView(R.id.btn_amount) - AppCompatButton btnAmount; - - @BindView(R.id.btn_add_beneficiary) - AppCompatButton btnAddBeneficiary; - - @BindView(R.id.ll_review) - LinearLayout llReview; - - @BindView(R.id.tv_select_beneficary) - TextView tvSelectBeneficiary; - - @BindView(R.id.tv_select_amount) - TextView tvEnterAmount; - - @BindView(R.id.tv_enter_remark) - TextView tvEnterRemark; - - @BindView(R.id.tv_add_beneficiary_msg) - TextView tvAddBeneficiaryMsg; - - @BindView(R.id.layout_error) - View layoutError; - - @Inject - ThirdPartyTransferPresenter presenter; - - private List listBeneficiary = new ArrayList<>(); - private List listPayFrom = new ArrayList<>(); - private List beneficiaries; - private BeneficiarySpinnerAdapter beneficiaryAdapter; - private AccountsSpinnerAdapter payFromAdapter; - private AccountOption fromAccountOption; - private AccountOption beneficiaryAccountOption; - private AccountOptionsTemplate accountOptionsTemplate; - private String transferDate; - private View rootView; - private SweetUIErrorHandler sweetUIErrorHandler; - - public static ThirdPartyTransferFragment newInstance() { - ThirdPartyTransferFragment fragment = new ThirdPartyTransferFragment(); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - rootView = inflater.inflate(R.layout.fragment_third_party_transfer, container, false); - setToolbarTitle(getString(R.string.third_party_transfer)); - ButterKnife.bind(this, rootView); - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - showUserInterface(); - - presenter.attachView(this); - if (savedInstanceState == null) { - presenter.loadTransferTemplate(); - } - - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.TEMPLATE, accountOptionsTemplate); - outState.putParcelableArrayList(Constants.BENEFICIARY, new ArrayList( - beneficiaries)); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - showThirdPartyTransferTemplate((AccountOptionsTemplate) savedInstanceState. - getParcelable(Constants.TEMPLATE)); - List tempBeneficiaries = savedInstanceState.getParcelableArrayList( - Constants.BENEFICIARY); - showBeneficiaryList(tempBeneficiaries); - } - } - - /** - * Setting up basic components - */ - @Override - public void showUserInterface() { - payFromAdapter = new AccountsSpinnerAdapter(getActivity(), R.layout.account_spinner_layout, - listPayFrom); - payFromAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice); - spPayFrom.setAdapter(payFromAdapter); - spPayFrom.setOnItemSelectedListener(this); - - beneficiaryAdapter = new BeneficiarySpinnerAdapter(getActivity(), - R.layout.beneficiary_spinner_layout, listBeneficiary); - beneficiaryAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice); - spBeneficiary.setAdapter(beneficiaryAdapter); - spBeneficiary.setOnItemSelectedListener(this); - - transferDate = DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, - MFDatePicker.getDatePickedAsString()); - - pvOne.setCurrentActive(); - } - - /** - * Checks validation of {@code etRemark} and then opens {@link TransferProcessFragment} for - * initiating the transfer - */ - @OnClick(R.id.btn_review_transfer) - public void reviewTransfer() { - if (etAmount.getText().toString().equals("")) { - Toaster.show(rootView, getString(R.string.enter_amount)); - return; - } - - if (etAmount.getText().toString().equals(".")) { - Toaster.show(rootView, getString(R.string.invalid_amount)); - return; - } - - if (etRemark.getText().toString().trim().equals("")) { - Toaster.show(rootView, getString(R.string.remark_is_mandatory)); - return; - } - - if (spBeneficiary.getSelectedItem().toString(). - equals(spPayFrom.getSelectedItem().toString())) { - Toaster.show(rootView, getString(R.string.error_same_account_transfer)); - return; - } - - TransferPayload transferPayload = new TransferPayload(); - transferPayload.setFromAccountId(fromAccountOption.getAccountId()); - transferPayload.setFromClientId(fromAccountOption.getClientId()); - transferPayload.setFromAccountType(fromAccountOption.getAccountType().getId()); - transferPayload.setFromOfficeId(fromAccountOption.getOfficeId()); - transferPayload.setToOfficeId(beneficiaryAccountOption.getOfficeId()); - transferPayload.setToAccountId(beneficiaryAccountOption.getAccountId()); - transferPayload.setToClientId(beneficiaryAccountOption.getClientId()); - transferPayload.setToAccountType(beneficiaryAccountOption.getAccountType().getId()); - transferPayload.setTransferDate(transferDate); - transferPayload.setTransferAmount(Double.parseDouble(etAmount.getText().toString())); - transferPayload.setTransferDescription(etRemark.getText().toString()); - - ((BaseActivity) getActivity()).replaceFragment(TransferProcessFragment. - newInstance(transferPayload, TransferType.TPT), true, R.id.container); - - } - - /** - * Shows a {@link Snackbar} with {@code message} - * - * @param msg String to be shown - */ - @Override - public void showToaster(String msg) { - Toaster.show(rootView, msg); - } - - /** - * Provides with {@code accountOptionsTemplate} fetched from server which is used to update - * {@code listPayFrom} - * - * @param accountOptionsTemplate Template for account transfer - */ - @Override - public void showThirdPartyTransferTemplate(AccountOptionsTemplate accountOptionsTemplate) { - this.accountOptionsTemplate = accountOptionsTemplate; - listPayFrom.clear(); - listPayFrom.addAll(presenter.getAccountNumbersFromAccountOptions(accountOptionsTemplate. - getFromAccountOptions())); - payFromAdapter.notifyDataSetChanged(); - - } - - /** - * Provides with {@code beneficiaries} fetched from server which is used to update - * {@code listBeneficiary} - * - * @param beneficiaries List of {@link Beneficiary} linked with user's account - */ - @Override - public void showBeneficiaryList(List beneficiaries) { - this.beneficiaries = beneficiaries; - listBeneficiary.clear(); - listBeneficiary.addAll(presenter.getAccountNumbersFromBeneficiaries(beneficiaries)); - beneficiaryAdapter.notifyDataSetChanged(); - } - - - /** - * Disables {@code spPayFrom} {@link Spinner} and sets {@code pvOne} to completed and make - * {@code pvThree} pvTwo - */ - @OnClick(R.id.btn_pay_from) - public void payFromSelected() { - pvOne.setCurrentCompeleted(); - pvTwo.setCurrentActive(); - - btnPayFrom.setVisibility(View.GONE); - - tvSelectBeneficiary.setVisibility(View.GONE); - if (!listBeneficiary.isEmpty()) { - btnPayTo.setVisibility(View.VISIBLE); - spBeneficiary.setVisibility(View.VISIBLE); - spPayFrom.setEnabled(false); - } else { - tvAddBeneficiaryMsg.setVisibility(View.VISIBLE); - btnAddBeneficiary.setVisibility(View.VISIBLE); - } - } - - - /** - * Checks validation of {@code spBeneficiary} {@link Spinner}.
- * Disables {@code spBeneficiary} {@link Spinner} and sets {@code pvTwo} to completed and make - * {@code pvThree} active - */ - @OnClick(R.id.btn_pay_to) - public void payToSelected() { - if (spBeneficiary.getSelectedItem().toString().equals(spPayFrom.getSelectedItem(). - toString())) { - showToaster(getString(R.string.error_same_account_transfer)); - return; - } - pvTwo.setCurrentCompeleted(); - pvThree.setCurrentActive(); - - btnPayTo.setVisibility(View.GONE); - tvEnterAmount.setVisibility(View.GONE); - etAmount.setVisibility(View.VISIBLE); - btnAmount.setVisibility(View.VISIBLE); - spBeneficiary.setEnabled(false); - } - - /** - * Checks validation of {@code etAmount} {@link EditText}.
- * Disables {@code etAmount} and sets {@code pvThree} to completed and make - * {@code pvFour} active - */ - @OnClick(R.id.btn_amount) - public void amountSet() { - - if (etAmount.getText().toString().equals("")) { - showToaster(getString(R.string.enter_amount)); - return; - } - - if (etAmount.getText().toString().equals(".")) { - showToaster(getString(R.string.invalid_amount)); - return; - } - - if (Double.parseDouble(etAmount.getText().toString()) == 0) { - showToaster(getString(R.string.amount_greater_than_zero)); - return; - } - - pvThree.setCurrentCompeleted(); - pvFour.setCurrentActive(); - - btnAmount.setVisibility(View.GONE); - tvEnterRemark.setVisibility(View.GONE); - etRemark.setVisibility(View.VISIBLE); - llReview.setVisibility(View.VISIBLE); - etAmount.setEnabled(false); - } - - @OnClick(R.id.btn_cancel_transfer) - public void cancelTransfer() { - getActivity().getSupportFragmentManager().popBackStack(); - } - - @OnClick(R.id.btn_add_beneficiary) - public void addBeneficiary() { - ((BaseActivity) getActivity()).replaceFragment(BeneficiaryAddOptionsFragment.newInstance(), - true, R.id.container); - } - - @OnClick(R.id.btn_try_again) - public void onRetry() { - if (Network.isConnected(getContext())) { - sweetUIErrorHandler.hideSweetErrorLayoutUI(layoutMakeTransfer, layoutError); - presenter.loadTransferTemplate(); - } else { - Toaster.show(rootView, getString(R.string.internet_not_connected)); - } - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param msg Error message that tells the user about the problem. - */ - @Override - public void showError(String msg) { - if (!Network.isConnected(getContext())) { - sweetUIErrorHandler.showSweetNoInternetUI(layoutMakeTransfer, layoutError); - } else { - sweetUIErrorHandler.showSweetErrorUI(msg, layoutMakeTransfer, layoutError); - Toaster.show(rootView, msg); - } - } - - @Override - public void showProgress() { - layoutMakeTransfer.setVisibility(View.GONE); - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - layoutMakeTransfer.setVisibility(View.VISIBLE); - } - - /** - * Callback for {@code spPayFrom} and {@code spBeneficiary} - */ - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - switch (parent.getId()) { - case R.id.sp_beneficiary: - beneficiaryAccountOption = presenter.searchAccount(accountOptionsTemplate. - getFromAccountOptions(), beneficiaryAdapter.getItem(position)); - break; - case R.id.sp_pay_from: - fromAccountOption = accountOptionsTemplate.getFromAccountOptions().get(position); - break; - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_transfer, menu); - Utils.setToolbarIconColor(getActivity(), menu, R.color.white); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == R.id.menu_refresh_transfer) { - FragmentTransaction transaction = getFragmentManager().beginTransaction(); - Fragment currFragment = getActivity().getSupportFragmentManager() - .findFragmentById(R.id.container); - transaction.detach(currFragment); - transaction.attach(currFragment); - transaction.commit(); - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/ThirdPartyTransferFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/ThirdPartyTransferFragment.kt new file mode 100644 index 0000000000..04511a900d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/ThirdPartyTransferFragment.kt @@ -0,0 +1,421 @@ +package org.mifos.mobile.ui.fragments + +import android.os.Bundle +import android.os.Parcelable +import android.view.* +import android.widget.* +import android.widget.AdapterView.OnItemSelectedListener +import androidx.appcompat.widget.AppCompatButton + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler + +import org.mifos.mobile.R +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.beneficiary.BeneficiaryDetail +import org.mifos.mobile.models.payload.AccountDetail +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.models.templates.account.AccountOption +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.presenters.ThirdPartyTransferPresenter +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.adapters.AccountsSpinnerAdapter +import org.mifos.mobile.ui.adapters.BeneficiarySpinnerAdapter +import org.mifos.mobile.ui.enums.TransferType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.ThirdPartyTransferView +import org.mifos.mobile.utils.* + +import java.util.* +import javax.inject.Inject + +/** + * Created by dilpreet on 21/6/17. + */ +class ThirdPartyTransferFragment : BaseFragment(), ThirdPartyTransferView, OnItemSelectedListener { + + @kotlin.jvm.JvmField + @BindView(R.id.sp_beneficiary) + var spBeneficiary: Spinner? = null + + @kotlin.jvm.JvmField + @BindView(R.id.sp_pay_from) + var spPayFrom: Spinner? = null + + @kotlin.jvm.JvmField + @BindView(R.id.et_amount) + var etAmount: EditText? = null + + @kotlin.jvm.JvmField + @BindView(R.id.et_remark) + var etRemark: EditText? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_make_transfer) + var layoutMakeTransfer: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_one) + var pvOne: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_two) + var pvTwo: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_three) + var pvThree: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.process_four) + var pvFour: ProcessView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_pay_to) + var btnPayTo: AppCompatButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_pay_from) + var btnPayFrom: AppCompatButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_amount) + var btnAmount: AppCompatButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_add_beneficiary) + var btnAddBeneficiary: AppCompatButton? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_review) + var llReview: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_select_beneficary) + var tvSelectBeneficiary: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_select_amount) + var tvEnterAmount: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_enter_remark) + var tvEnterRemark: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_add_beneficiary_msg) + var tvAddBeneficiaryMsg: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: ThirdPartyTransferPresenter? = null + private val listBeneficiary: MutableList = ArrayList() + private val listPayFrom: MutableList = ArrayList() + private var beneficiaries: List? = null + private var beneficiaryAdapter: BeneficiarySpinnerAdapter? = null + private var payFromAdapter: AccountsSpinnerAdapter? = null + private var fromAccountOption: AccountOption? = null + private var beneficiaryAccountOption: AccountOption? = null + private var accountOptionsTemplate: AccountOptionsTemplate? = null + private var transferDate: String? = null + private var rootView: View? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + (activity as BaseActivity?)?.activityComponent?.inject(this) + rootView = inflater.inflate(R.layout.fragment_third_party_transfer, container, false) + setToolbarTitle(getString(R.string.third_party_transfer)) + if (rootView != null ) ButterKnife.bind(this, rootView!!) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + showUserInterface() + presenter?.attachView(this) + if (savedInstanceState == null) { + presenter?.loadTransferTemplate() + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.TEMPLATE, accountOptionsTemplate) + outState.putParcelableArrayList(Constants.BENEFICIARY, ArrayList( + beneficiaries)) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + showThirdPartyTransferTemplate(savedInstanceState.getParcelable(Constants.TEMPLATE) as AccountOptionsTemplate) + val tempBeneficiaries: List = savedInstanceState.getParcelableArrayList( + Constants.BENEFICIARY) + showBeneficiaryList(tempBeneficiaries) + } + } + + /** + * Setting up basic components + */ + override fun showUserInterface() { + payFromAdapter = activity?.applicationContext?.let { + AccountsSpinnerAdapter(it, R.layout.account_spinner_layout, + listPayFrom) + } + payFromAdapter?.setDropDownViewResource(android.R.layout.select_dialog_singlechoice) + spPayFrom?.adapter = payFromAdapter + spPayFrom?.onItemSelectedListener = this + beneficiaryAdapter = activity?.applicationContext?.let { + BeneficiarySpinnerAdapter(it, + R.layout.beneficiary_spinner_layout, listBeneficiary) + } + beneficiaryAdapter?.setDropDownViewResource(android.R.layout.select_dialog_singlechoice) + spBeneficiary?.adapter = beneficiaryAdapter + spBeneficiary?.onItemSelectedListener = this + transferDate = DateHelper.getSpecificFormat(DateHelper.FORMAT_dd_MMMM_yyyy, + MFDatePicker.datePickedAsString) + pvOne?.setCurrentActive() + } + + /** + * Checks validation of `etRemark` and then opens [TransferProcessFragment] for + * initiating the transfer + */ + @OnClick(R.id.btn_review_transfer) + fun reviewTransfer() { + if (etAmount?.text.toString() == "") { + Toaster.show(rootView, getString(R.string.enter_amount)) + return + } + if (etAmount?.text.toString() == ".") { + Toaster.show(rootView, getString(R.string.invalid_amount)) + return + } + if (etRemark?.text.toString().trim { it <= ' ' } == "") { + Toaster.show(rootView, getString(R.string.remark_is_mandatory)) + return + } + if (spBeneficiary?.selectedItem.toString() == spPayFrom?.selectedItem.toString()) { + Toaster.show(rootView, getString(R.string.error_same_account_transfer)) + return + } + val transferPayload = TransferPayload() + transferPayload.fromAccountId = fromAccountOption?.accountId + transferPayload.fromClientId = fromAccountOption?.clientId + transferPayload.fromAccountType = fromAccountOption?.accountType?.id + transferPayload.fromOfficeId = fromAccountOption?.officeId + transferPayload.toOfficeId = beneficiaryAccountOption?.officeId + transferPayload.toAccountId = beneficiaryAccountOption?.accountId + transferPayload.toClientId = beneficiaryAccountOption?.clientId + transferPayload.toAccountType = beneficiaryAccountOption?.accountType?.id + transferPayload.transferDate = transferDate + transferPayload.transferAmount = etAmount?.text.toString().toDouble() + transferPayload.transferDescription = etRemark?.text.toString() + (activity as BaseActivity?)?.replaceFragment(TransferProcessFragment.newInstance(transferPayload, TransferType.TPT), true, R.id.container) + } + + /** + * Shows a {@link Snackbar} with `message` + * + * @param msg String to be shown + */ + override fun showToaster(msg: String?) { + Toaster.show(rootView, msg) + } + + /** + * Provides with `accountOptionsTemplate` fetched from server which is used to update + * `listPayFrom` + * + * @param accountOptionsTemplate Template for account transfer + */ + override fun showThirdPartyTransferTemplate(accountOptionsTemplate: AccountOptionsTemplate?) { + this.accountOptionsTemplate = accountOptionsTemplate + listPayFrom.clear() + presenter?.getAccountNumbersFromAccountOptions(accountOptionsTemplate?.fromAccountOptions)?.let { listPayFrom.addAll(it) } + payFromAdapter?.notifyDataSetChanged() + } + + /** + * Provides with `beneficiaries` fetched from server which is used to update + * `listBeneficiary` + * + * @param beneficiaries List of [Beneficiary] linked with user's account + */ + override fun showBeneficiaryList(beneficiaries: List?) { + this.beneficiaries = beneficiaries + listBeneficiary.clear() + presenter?.getAccountNumbersFromBeneficiaries(beneficiaries)?.let { listBeneficiary.addAll(it) } + beneficiaryAdapter?.notifyDataSetChanged() + } + + /** + * Disables `spPayFrom` [Spinner] and sets `pvOne` to completed and make + * `pvThree` pvTwo + */ + @OnClick(R.id.btn_pay_from) + fun payFromSelected() { + pvOne?.setCurrentCompleted() + pvTwo?.setCurrentActive() + btnPayFrom?.visibility = View.GONE + tvSelectBeneficiary?.visibility = View.GONE + if (listBeneficiary.isNotEmpty()) { + btnPayTo?.visibility = View.VISIBLE + spBeneficiary?.visibility = View.VISIBLE + spPayFrom?.isEnabled = false + } else { + tvAddBeneficiaryMsg?.visibility = View.VISIBLE + btnAddBeneficiary?.visibility = View.VISIBLE + } + } + + /** + * Checks validation of `spBeneficiary` [Spinner].

+ * Disables `spBeneficiary` [Spinner] and sets `pvTwo` to completed and make + * `pvThree` active + */ + @OnClick(R.id.btn_pay_to) + fun payToSelected() { + if (spBeneficiary?.selectedItem.toString() == spPayFrom?.selectedItem.toString()) { + showToaster(getString(R.string.error_same_account_transfer)) + return + } + pvTwo?.setCurrentCompleted() + pvThree?.setCurrentActive() + btnPayTo?.visibility = View.GONE + tvEnterAmount?.visibility = View.GONE + etAmount?.visibility = View.VISIBLE + btnAmount?.visibility = View.VISIBLE + spBeneficiary?.isEnabled = false + } + + /** + * Checks validation of `etAmount` [EditText].

+ * Disables `etAmount` and sets `pvThree` to completed and make + * `pvFour` active + */ + @OnClick(R.id.btn_amount) + fun amountSet() { + if (etAmount?.text.toString() == "") { + showToaster(getString(R.string.enter_amount)) + return + } + if (etAmount?.text.toString() == ".") { + showToaster(getString(R.string.invalid_amount)) + return + } + if (etAmount?.text.toString().toDouble() == 0.0) { + showToaster(getString(R.string.amount_greater_than_zero)) + return + } + pvThree?.setCurrentCompleted() + pvFour?.setCurrentActive() + btnAmount?.visibility = View.GONE + tvEnterRemark?.visibility = View.GONE + etRemark?.visibility = View.VISIBLE + llReview?.visibility = View.VISIBLE + etAmount?.isEnabled = false + } + + @OnClick(R.id.btn_cancel_transfer) + fun cancelTransfer() { + activity?.supportFragmentManager?.popBackStack() + } + + @OnClick(R.id.btn_add_beneficiary) + fun addBeneficiary() { + (activity as BaseActivity?)?.replaceFragment(BeneficiaryAddOptionsFragment.newInstance(), + true, R.id.container) + } + + @OnClick(R.id.btn_try_again) + fun onRetry() { + if (Network.isConnected(context)) { + sweetUIErrorHandler?.hideSweetErrorLayoutUI(layoutMakeTransfer, layoutError) + presenter?.loadTransferTemplate() + } else { + Toaster.show(rootView, getString(R.string.internet_not_connected)) + } + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param msg Error message that tells the user about the problem. + */ + override fun showError(msg: String?) { + if (!Network.isConnected(context)) { + sweetUIErrorHandler?.showSweetNoInternetUI(layoutMakeTransfer, layoutError) + } else { + sweetUIErrorHandler?.showSweetErrorUI(msg, layoutMakeTransfer, layoutError) + Toaster.show(rootView, msg) + } + } + + override fun showProgress() { + layoutMakeTransfer?.visibility = View.GONE + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + layoutMakeTransfer?.visibility = View.VISIBLE + } + + /** + * Callback for `spPayFrom` and `spBeneficiary` + */ + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + when (parent?.id) { + R.id.sp_beneficiary -> beneficiaryAccountOption = + presenter?.searchAccount(accountOptionsTemplate?.fromAccountOptions, beneficiaryAdapter?.getItem(position)) + R.id.sp_pay_from -> fromAccountOption = + accountOptionsTemplate?.fromAccountOptions?.get(position) + } + } + + override fun onNothingSelected(parent: AdapterView<*>?) {} + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + super.onCreateOptionsMenu(menu, inflater) + inflater.inflate(R.menu.menu_transfer, menu) + Utils.setToolbarIconColor(activity, menu, R.color.white) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == R.id.menu_refresh_transfer) { + val transaction = fragmentManager?.beginTransaction() + val currFragment = activity?.supportFragmentManager + ?.findFragmentById(R.id.container) + if (currFragment!=null){ + transaction?.detach(currFragment) + transaction?.attach(currFragment) + } + transaction?.commit() + } + return super.onOptionsItemSelected(item) + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + presenter?.detachView() + } + + companion object { + fun newInstance(): ThirdPartyTransferFragment { + return ThirdPartyTransferFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/TransferProcessFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/TransferProcessFragment.java deleted file mode 100644 index 3aad65f2b8..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/TransferProcessFragment.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.graphics.drawable.Animatable; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.presenters.TransferProcessPresenter; -import org.mifos.mobile.ui.activities.SavingsAccountContainerActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.enums.TransferType; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.TransferProcessView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.CurrencyUtil; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatButton; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 1/7/17. - */ - -public class TransferProcessFragment extends BaseFragment implements TransferProcessView { - - @BindView(R.id.tv_amount) - TextView tvAmount; - - @BindView(R.id.tv_pay_to) - TextView tvPayTo; - - @BindView(R.id.tv_pay_from) - TextView tvPayFrom; - - @BindView(R.id.tv_date) - TextView tvDate; - - @BindView(R.id.tv_remark) - TextView tvRemark; - - @BindView(R.id.iv_success) - ImageView ivSuccess; - - @BindView(R.id.ll_transfer) - LinearLayout llTransfer; - - @BindView(R.id.btn_close) - AppCompatButton btnClose; - - @Inject - TransferProcessPresenter presenter; - - private View rootView; - private TransferPayload payload; - private TransferType transferType; - - /** - * Used for TPT Transfer and own Account Transfer.
- * Use {@code type} as TransferType.TPT for TPT and TransferType.SELF for self Account Transfer - * - * @param payload Transfer Information - * @param type enum of {@link TransferType} - * @return Instance of {@link TransferProcessFragment} - */ - public static TransferProcessFragment newInstance(TransferPayload payload, TransferType type) { - TransferProcessFragment fragment = new TransferProcessFragment(); - Bundle args = new Bundle(); - args.putParcelable(Constants.PAYLOAD, payload); - args.putSerializable(Constants.TRANSFER_TYPE, type); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getActivity() != null) { - payload = getArguments().getParcelable(Constants.PAYLOAD); - transferType = (TransferType) getArguments().getSerializable(Constants.TRANSFER_TYPE); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_transfer_process, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - setToolbarTitle(getString(R.string.transfer)); - - ButterKnife.bind(this, rootView); - presenter.attachView(this); - - tvAmount.setText(CurrencyUtil.formatCurrency(getActivity(), payload.getTransferAmount())); - tvPayFrom.setText(String.valueOf(payload.getFromAccountNumber())); - tvPayTo.setText(String.valueOf(payload.getToAccountNumber())); - tvDate.setText(payload.getTransferDate()); - tvRemark.setText(payload.getTransferDescription()); - - return rootView; - } - - /** - * Initiates a transfer depending upon {@code transferType} - */ - @OnClick(R.id.btn_start_transfer) - public void startTransfer() { - if (!Network.isConnected(getActivity())) { - Toaster.show(rootView, getString(R.string.internet_not_connected)); - return; - } - if (transferType == TransferType.SELF) { - presenter.makeSavingsTransfer(payload); - } else if (transferType == TransferType.TPT) { - presenter.makeTPTTransfer(payload); - } - } - - /** - * Cancels the Transfer and pops fragment - */ - @OnClick(R.id.btn_cancel_transfer) - public void cancelTransfer() { - Toaster.cancelTransfer(rootView, getString(R.string.cancel_transfer), - getString(R.string.yes), new View.OnClickListener() { - @Override - public void onClick(View view) { - getActivity().getSupportFragmentManager().popBackStack(); - getActivity().getSupportFragmentManager().popBackStack(); - } - }); - } - - /** - * Closes the transfer fragment - */ - @OnClick(R.id.btn_close) - public void closeClicked() { - getActivity().getSupportFragmentManager().popBackStack(); - getActivity().getSupportFragmentManager().popBackStack(); - } - - /** - * Shows a {@link Snackbar} on succesfull transfer of money - */ - @Override - public void showTransferredSuccessfully() { - Toaster.show(rootView, getString(R.string.transferred_successfully)); - ivSuccess.setVisibility(View.VISIBLE); - ((Animatable) ivSuccess.getDrawable()).start(); - btnClose.setVisibility(View.VISIBLE); - llTransfer.setVisibility(View.GONE); - SavingsAccountContainerActivity.transferSuccess = true; - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param msg Error message that tells the user about the problem. - */ - @Override - public void showError(String msg) { - Toaster.show(rootView, msg); - } - - @Override - public void showProgress() { - showMifosProgressDialog(getString(R.string.please_wait)); - } - - @Override - public void hideProgress() { - hideMifosProgressDialog(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/TransferProcessFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/TransferProcessFragment.kt new file mode 100644 index 0000000000..31c1e9dd25 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/TransferProcessFragment.kt @@ -0,0 +1,188 @@ +package org.mifos.mobile.ui.fragments + +import android.graphics.drawable.Animatable +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView + +import androidx.appcompat.widget.AppCompatButton + +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick + +import org.mifos.mobile.R +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.presenters.TransferProcessPresenter +import org.mifos.mobile.ui.activities.SavingsAccountContainerActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.enums.TransferType +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.TransferProcessView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.CurrencyUtil +import org.mifos.mobile.utils.Network +import org.mifos.mobile.utils.Toaster + +import javax.inject.Inject + +/** + * Created by dilpreet on 1/7/17. + */ +class TransferProcessFragment : BaseFragment(), TransferProcessView { + + @kotlin.jvm.JvmField + @BindView(R.id.tv_amount) + var tvAmount: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_pay_to) + var tvPayTo: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_pay_from) + var tvPayFrom: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_date) + var tvDate: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_remark) + var tvRemark: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_success) + var ivSuccess: ImageView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_transfer) + var llTransfer: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.btn_close) + var btnClose: AppCompatButton? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: TransferProcessPresenter? = null + private var rootView: View? = null + private var payload: TransferPayload? = null + private var transferType: TransferType? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (activity != null) { + payload = arguments?.getParcelable(Constants.PAYLOAD) + transferType = arguments?.getSerializable(Constants.TRANSFER_TYPE) as TransferType + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + rootView = inflater.inflate(R.layout.fragment_transfer_process, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + setToolbarTitle(getString(R.string.transfer)) + ButterKnife.bind(this, rootView!!) + presenter?.attachView(this) + tvAmount?.text = CurrencyUtil.formatCurrency(activity, payload?.transferAmount) + tvPayFrom?.text = payload?.fromAccountNumber.toString() + tvPayTo?.text = payload?.toAccountNumber.toString() + tvDate?.text = payload?.transferDate + tvRemark?.text = payload?.transferDescription + return rootView + } + + /** + * Initiates a transfer depending upon `transferType` + */ + @OnClick(R.id.btn_start_transfer) + fun startTransfer() { + if (!Network.isConnected(activity)) { + Toaster.show(rootView, getString(R.string.internet_not_connected)) + return + } + if (transferType == TransferType.SELF) { + presenter?.makeSavingsTransfer(payload) + } else if (transferType == TransferType.TPT) { + presenter?.makeTPTTransfer(payload) + } + } + + /** + * Cancels the Transfer and pops fragment + */ + @OnClick(R.id.btn_cancel_transfer) + fun cancelTransfer() { + Toaster.cancelTransfer(rootView, getString(R.string.cancel_transfer), + getString(R.string.yes), View.OnClickListener { + activity?.supportFragmentManager?.popBackStack() + activity?.supportFragmentManager?.popBackStack() + }) + } + + /** + * Closes the transfer fragment + */ + @OnClick(R.id.btn_close) + fun closeClicked() { + activity?.supportFragmentManager?.popBackStack() + activity?.supportFragmentManager?.popBackStack() + } + + /** + * Shows a {@link Snackbar} on succesfull transfer of money + */ + override fun showTransferredSuccessfully() { + Toaster.show(rootView, getString(R.string.transferred_successfully)) + ivSuccess?.visibility = View.VISIBLE + (ivSuccess?.drawable as Animatable).start() + btnClose?.visibility = View.VISIBLE + llTransfer?.visibility = View.GONE + SavingsAccountContainerActivity.transferSuccess = true + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param msg Error message that tells the user about the problem. + */ + override fun showError(msg: String?) { + Toaster.show(rootView, msg) + } + + override fun showProgress() { + showMifosProgressDialog(getString(R.string.please_wait)) + } + + override fun hideProgress() { + hideMifosProgressDialog() + } + + override fun onDestroyView() { + super.onDestroyView() + presenter?.detachView() + } + + companion object { + /** + * Used for TPT Transfer and own Account Transfer.

+ * Use `type` as TransferType.TPT for TPT and TransferType.SELF for self Account Transfer + * + * @param payload Transfer Information + * @param type enum of [TransferType] + * @return Instance of [TransferProcessFragment] + */ + fun newInstance(payload: TransferPayload?, type: TransferType?): TransferProcessFragment { + val fragment = TransferProcessFragment() + val args = Bundle() + args.putParcelable(Constants.PAYLOAD, payload) + args.putSerializable(Constants.TRANSFER_TYPE, type) + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/UpdatePasswordFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/UpdatePasswordFragment.java deleted file mode 100644 index 7aeb8068b1..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/UpdatePasswordFragment.java +++ /dev/null @@ -1,216 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -/* - * Created by saksham on 13/July/2018 - */ - -import android.content.Intent; -import android.os.Bundle; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.google.android.material.textfield.TextInputLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.UpdatePasswordPayload; -import org.mifos.mobile.presenters.UpdatePasswordPresenter; -import org.mifos.mobile.ui.activities.SettingsActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.UpdatePasswordView; -import org.mifos.mobile.utils.Network; -import org.mifos.mobile.utils.Toaster; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -public class UpdatePasswordFragment extends BaseFragment implements UpdatePasswordView, - TextWatcher, View.OnFocusChangeListener { - - @BindView(R.id.til_new_password) - TextInputLayout tilNewPassword; - - @BindView(R.id.til_confirm_new_password) - TextInputLayout tilConfirmNewPassword; - - @Inject - UpdatePasswordPresenter presenter; - - @Inject - PreferencesHelper preferencesHelper; - - private View rootView; - private UpdatePasswordPayload payload; - private boolean isFocusLostNewPassword = false; - private boolean isFocusLostConfirmPassword = false; - - public static UpdatePasswordFragment newInstance() { - return new UpdatePasswordFragment(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_update_password, container, false); - setToolbarTitle(getString(R.string.change_password)); - ButterKnife.bind(this, rootView); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - presenter.attachView(this); - - tilNewPassword.getEditText().addTextChangedListener(this); - tilConfirmNewPassword.getEditText().addTextChangedListener(this); - tilNewPassword.getEditText().setOnFocusChangeListener(this); - tilConfirmNewPassword.getEditText().setOnFocusChangeListener(this); - return rootView; - } - - @OnClick(R.id.btn_update_password) - void updatePassword() { - if (isFieldsCompleted()) { - presenter.updateAccountPassword(getUpdatePasswordPayload()); - } - } - - private boolean isFieldsCompleted() { - boolean rv = true; - String newPassword = tilNewPassword.getEditText().getText().toString().trim(); - String repeatPassword = tilConfirmNewPassword.getEditText().getText().toString().trim(); - - if (!checkNewPasswordFieldsComplete()) { - rv = false; - } - if (!checkConfirmPasswordFieldsComplete()) { - rv = false; - } - if (!newPassword.equals(repeatPassword)) { - Toaster.show(rootView, getString(R.string.error_password_not_match)); - rv = false; - } - return rv; - } - - private UpdatePasswordPayload getUpdatePasswordPayload() { - payload = new UpdatePasswordPayload(); - payload.setPassword(tilNewPassword.getEditText().getText().toString().trim()); - payload.setRepeatPassword(tilConfirmNewPassword.getEditText().getText().toString().trim()); - return payload; - } - - @Override - public void showError(String message) { - if (!Network.isConnected(getActivity())) { - message = getString(R.string.no_internet_connection); - } - Toaster.show(rootView, message); - } - - @Override - public void showPasswordUpdatedSuccessfully() { - Toast.makeText(getContext(), getString(R.string.string_changed_successfully, - getString(R.string.password)), Toast.LENGTH_SHORT).show(); - startActivity(new Intent(getContext(), SettingsActivity.class)); - } - - @Override - public void showProgress() { - showMifosProgressDialog(getString(R.string.progress_message_loading)); - } - - @Override - public void hideProgress() { - hideMifosProgressDialog(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - presenter.detachView(); - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (tilNewPassword.getEditText().hasFocus() && isFocusLostNewPassword) { - checkNewPasswordFieldsComplete(); - } - if (tilConfirmNewPassword.getEditText().hasFocus() && isFocusLostConfirmPassword) { - checkConfirmPasswordFieldsComplete(); - } - } - - @Override - public void afterTextChanged(Editable s) { - - } - - @Override - public void onFocusChange(View v, boolean hasFocus) { - if (v.getId() == R.id.et_new_password && !isFocusLostNewPassword && !hasFocus) { - checkNewPasswordFieldsComplete(); - isFocusLostNewPassword = true; - } - if (v.getId() == R.id.et_confirm_password && !isFocusLostConfirmPassword && !hasFocus) { - checkConfirmPasswordFieldsComplete(); - isFocusLostConfirmPassword = true; - } - } - - private boolean checkNewPasswordFieldsComplete() { - String newPassword = tilNewPassword.getEditText().getText().toString(); - isFocusLostNewPassword = true; - if (newPassword.isEmpty()) { - tilNewPassword.setError( - getString(R.string.error_validation_blank, - getString(R.string.new_password))); - return false; - } - if (newPassword.length() < 6) { - tilNewPassword.setError( - getString(R.string.error_validation_minimum_chars, - getString(R.string.new_password), - getResources().getInteger(R.integer.password_minimum_length))); - return false; - } - tilNewPassword.setErrorEnabled(false); - return true; - } - - private boolean checkConfirmPasswordFieldsComplete() { - String confirmPassword = tilConfirmNewPassword.getEditText().getText().toString(); - isFocusLostConfirmPassword = true; - if (confirmPassword.isEmpty()) { - tilConfirmNewPassword.setError( - getString(R.string.error_validation_blank, - getString(R.string.confirm_password))); - return false; - } - if (confirmPassword.length() < 6) { - tilConfirmNewPassword.setError( - getString(R.string.error_validation_minimum_chars, - getString(R.string.confirm_password), - getResources().getInteger(R.integer.password_minimum_length))); - return false; - } - tilConfirmNewPassword.setErrorEnabled(false); - return true; - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/UpdatePasswordFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/UpdatePasswordFragment.kt new file mode 100644 index 0000000000..ee290a308c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/UpdatePasswordFragment.kt @@ -0,0 +1,190 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.LayoutInflater +import android.view.View +import android.view.View.OnFocusChangeListener +import android.view.ViewGroup +import android.widget.Toast +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import com.google.android.material.textfield.TextInputLayout +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.UpdatePasswordPayload +import org.mifos.mobile.presenters.UpdatePasswordPresenter +import org.mifos.mobile.ui.activities.SettingsActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.UpdatePasswordView +import org.mifos.mobile.utils.Network +import org.mifos.mobile.utils.Toaster +import javax.inject.Inject + +/* +* Created by saksham on 13/July/2018 +*/ class UpdatePasswordFragment : BaseFragment(), UpdatePasswordView, TextWatcher, OnFocusChangeListener { + @kotlin.jvm.JvmField + @BindView(R.id.til_new_password) + var tilNewPassword: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_confirm_new_password) + var tilConfirmNewPassword: TextInputLayout? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: UpdatePasswordPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + private var rootView: View? = null + private var payload: UpdatePasswordPayload? = null + private var isFocusLostNewPassword = false + private var isFocusLostConfirmPassword = false + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_update_password, container, false) + setToolbarTitle(getString(R.string.change_password)) + ButterKnife.bind(this, rootView!!) + (activity as BaseActivity?)?.activityComponent?.inject(this) + presenter?.attachView(this) + tilNewPassword?.editText?.addTextChangedListener(this) + tilConfirmNewPassword?.editText?.addTextChangedListener(this) + tilNewPassword?.editText?.onFocusChangeListener = this + tilConfirmNewPassword?.editText?.onFocusChangeListener = this + return rootView + } + + @OnClick(R.id.btn_update_password) + fun updatePassword() { + if (isFieldsCompleted) { + presenter?.updateAccountPassword(updatePasswordPayload) + } + } + + private val isFieldsCompleted: Boolean + get() { + var rv = true + val newPassword = tilNewPassword?.editText?.text.toString().trim { it <= ' ' } + val repeatPassword = tilConfirmNewPassword?.editText?.text.toString().trim { it <= ' ' } + if (!checkNewPasswordFieldsComplete()) { + rv = false + } + if (!checkConfirmPasswordFieldsComplete()) { + rv = false + } + if (newPassword != repeatPassword) { + Toaster.show(rootView, getString(R.string.error_password_not_match)) + rv = false + } + return rv + } + private val updatePasswordPayload: UpdatePasswordPayload? + get() { + payload = UpdatePasswordPayload() + payload?.password = tilNewPassword?.editText?.text.toString().trim { it <= ' ' } + payload?.repeatPassword = tilConfirmNewPassword?.editText?.text.toString().trim { it <= ' ' } + return payload + } + + override fun showError(message: String?) { + var message = message + if (!Network.isConnected(activity)) { + message = getString(R.string.no_internet_connection) + } + Toaster.show(rootView, message) + } + + override fun showPasswordUpdatedSuccessfully() { + Toast.makeText(context, getString(R.string.string_changed_successfully, + getString(R.string.password)), Toast.LENGTH_SHORT).show() + startActivity(Intent(context, SettingsActivity::class.java)) + } + + override fun showProgress() { + showMifosProgressDialog(getString(R.string.progress_message_loading)) + } + + override fun hideProgress() { + hideMifosProgressDialog() + } + + override fun onDestroyView() { + super.onDestroyView() + presenter?.detachView() + } + + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + if (tilNewPassword?.editText?.hasFocus() == true && isFocusLostNewPassword) { + checkNewPasswordFieldsComplete() + } + if (tilConfirmNewPassword?.editText?.hasFocus() == true && isFocusLostConfirmPassword) { + checkConfirmPasswordFieldsComplete() + } + } + + override fun afterTextChanged(s: Editable) {} + override fun onFocusChange(v: View, hasFocus: Boolean) { + if (v.id == R.id.et_new_password && !isFocusLostNewPassword && !hasFocus) { + checkNewPasswordFieldsComplete() + isFocusLostNewPassword = true + } + if (v.id == R.id.et_confirm_password && !isFocusLostConfirmPassword && !hasFocus) { + checkConfirmPasswordFieldsComplete() + isFocusLostConfirmPassword = true + } + } + + private fun checkNewPasswordFieldsComplete(): Boolean { + val newPassword = tilNewPassword?.editText?.text.toString() + isFocusLostNewPassword = true + if (newPassword.isEmpty()) { + tilNewPassword?.error = getString(R.string.error_validation_blank, + getString(R.string.new_password)) + return false + } + if (newPassword.length < 6) { + tilNewPassword?.error = getString(R.string.error_validation_minimum_chars, + getString(R.string.new_password), + resources.getInteger(R.integer.password_minimum_length)) + return false + } + tilNewPassword?.isErrorEnabled = false + return true + } + + private fun checkConfirmPasswordFieldsComplete(): Boolean { + val confirmPassword = tilConfirmNewPassword?.editText?.text.toString() + isFocusLostConfirmPassword = true + if (confirmPassword.isEmpty()) { + tilConfirmNewPassword?.error = getString(R.string.error_validation_blank, + getString(R.string.confirm_password)) + return false + } + if (confirmPassword.length < 6) { + tilConfirmNewPassword?.error = getString(R.string.error_validation_minimum_chars, + getString(R.string.confirm_password), + resources.getInteger(R.integer.password_minimum_length)) + return false + } + tilConfirmNewPassword?.isErrorEnabled = false + return true + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): UpdatePasswordFragment { + return UpdatePasswordFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/UserProfileFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/UserProfileFragment.java deleted file mode 100644 index 6d24f409e1..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/UserProfileFragment.java +++ /dev/null @@ -1,287 +0,0 @@ -package org.mifos.mobile.ui.fragments; - -import android.content.Intent; -import android.graphics.Bitmap; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler; -import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.appbar.CollapsingToolbarLayout; -import com.google.android.material.floatingactionbutton.FloatingActionButton; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.client.Group; -import org.mifos.mobile.presenters.UserDetailsPresenter; -import org.mifos.mobile.ui.activities.EditUserDetailActivity; -import org.mifos.mobile.ui.activities.base.BaseActivity; -import org.mifos.mobile.ui.fragments.base.BaseFragment; -import org.mifos.mobile.ui.views.UserDetailsView; -import org.mifos.mobile.utils.Constants; -import org.mifos.mobile.utils.DateHelper; -import org.mifos.mobile.utils.TextDrawable; -import org.mifos.mobile.utils.Toaster; - -import java.util.List; - -import javax.inject.Inject; - -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import androidx.core.content.ContextCompat; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; - -/** - * Created by dilpreet on 10/7/17. - */ - -public class UserProfileFragment extends BaseFragment implements UserDetailsView { - - @BindView(R.id.iv_profile) - ImageView ivProfile; - - @BindView(R.id.iv_text_drawable) - ImageView ivTextDrawable; - - @BindView(R.id.app_bar_layout) - AppBarLayout appBarLayout; - - @BindView(R.id.collapsing_toolbar) - CollapsingToolbarLayout collapsingToolbarLayout; - - @BindView(R.id.tv_user_name) - TextView tvUsername; - - @BindView(R.id.tv_account_number) - TextView tvAccountNumber; - - @BindView(R.id.tv_activation_date) - TextView tvActivationDate; - - @BindView(R.id.tv_office_name) - TextView tvOfficeName; - - @BindView(R.id.tv_groups) - TextView tvGroups; - - @BindView(R.id.tv_client_type) - TextView tvClientType; - - @BindView(R.id.tv_client_classification) - TextView tvClientClassification; - - @BindView(R.id.tv_phone_number) - TextView tvPhoneNumber; - - @BindView(R.id.tv_dob) - TextView tvDOB; - - @BindView(R.id.tv_gender) - TextView tvGender; - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.layout_error) - View layoutError; - - @BindView(R.id.ll_user_profile) - LinearLayout llUserProfile; - - @BindView(R.id.fab_edit) - FloatingActionButton fabEdit; - - @Inject - UserDetailsPresenter presenter; - - @Inject - PreferencesHelper preferencesHelper; - - private View rootView; - private Bitmap userBitmap; - private Client client; - private SweetUIErrorHandler sweetUIErrorHandler; - - public static UserProfileFragment newInstance() { - UserProfileFragment fragment = new UserProfileFragment(); - return fragment; - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.fragment_user_profile, container, false); - ((BaseActivity) getActivity()).getActivityComponent().inject(this); - ButterKnife.bind(this, rootView); - presenter.attachView(this); - - ((BaseActivity) getActivity()).setSupportActionBar(toolbar); - ((BaseActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - collapsingToolbarLayout.setCollapsedTitleTextColor(ContextCompat.getColor(getActivity(), - R.color.white)); - collapsingToolbarLayout.setExpandedTitleColor(ContextCompat.getColor(getActivity(), - R.color.white)); - - sweetUIErrorHandler = new SweetUIErrorHandler(getActivity(), rootView); - if (savedInstanceState == null) { - presenter.getUserDetails(); - presenter.getUserImage(); - } - return rootView; - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putParcelable(Constants.USER_DETAILS, client); - } - - @Override - public void onActivityCreated(@Nullable Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - if (savedInstanceState != null) { - client = savedInstanceState.getParcelable(Constants.USER_DETAILS); - presenter.setUserProfile(preferencesHelper.getUserProfileImage()); - showUserDetails(client); - } - } - - /** - * Sets client basic details which are fetched from server - * - * @param client instance of {@link Client} which contains information about client - */ - @Override - public void showUserDetails(Client client) { - this.client = client; - tvUsername.setText(nullFieldCheck(getString(R.string.username), client.getDisplayName())); - tvAccountNumber.setText(nullFieldCheck(getString(R.string.account_number), - client.getAccountNo())); - tvActivationDate.setText(nullFieldCheck(getString(R.string.activation_date), - DateHelper.getDateAsString(client.getActivationDate()))); - tvOfficeName.setText(nullFieldCheck(getString(R.string.office_name), - client.getOfficeName())); - tvClientType.setText(nullFieldCheck(getString(R.string.client_type), - client.getClientType().getName())); - tvGroups.setText(nullFieldCheck(getString(R.string.groups), - getGroups(client.getGroups()))); - tvClientClassification.setText(nullFieldCheck(getString(R.string.client_classification), - client.getClientClassification().getName())); - tvPhoneNumber.setText(nullFieldCheck(getString(R.string.phone_number), - client.getMobileNo())); - if (client.getDobDate().size() != 3) { // no data entry in database for the client - tvDOB.setText(getString(R.string.no_dob_found)); - } else { - tvDOB.setText(DateHelper.getDateAsString(client.getDobDate())); - } - tvGender.setText(nullFieldCheck(getString(R.string.gender), client.getGender().getName())); - } - - private String nullFieldCheck(String field, String value) { - if (value == null) { - return getString(R.string.no) + getString(R.string.blank) + field + - getString(R.string.blank) + getString(R.string.found); - } - return value; - } - - /** - * Generate a string for groups which the client is part of. - * - * @param groups {@link List} of {@link Group} which client is a part of. - * @return Returns String of groups - */ - private String getGroups(List groups) { - if (groups.size() == 0) { - return getString( - R.string.not_assigned_with_any_group); // no groups entry in database for the - // client - } - - - StringBuilder builder = new StringBuilder(); - for (Group group : groups) { - builder.append(getString(R.string.string_and_string, group.getName(), " | ")); - } - return builder.toString().substring(0, builder.toString().length() - 2); - } - - /** - * Provides with client Image fetched from the server in {@code bitmap} - * - * @param bitmap User Image - */ - @Override - public void showUserImage(final Bitmap bitmap) { - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - userBitmap = bitmap; - if (userBitmap == null) { - final TextDrawable textDrawable = TextDrawable.builder() - .beginConfig() - .toUpperCase() - .endConfig() - .buildRound(preferencesHelper - .getClientName() - .substring(0, 1), - ContextCompat.getColor(getContext(), R.color.primary_dark)); - ivProfile.setVisibility(View.GONE); - ivTextDrawable.setVisibility(View.VISIBLE); - ivTextDrawable.setImageDrawable(textDrawable); - } else { - ivTextDrawable.setVisibility(View.GONE); - ivProfile.setVisibility(View.VISIBLE); - ivProfile.setImageBitmap(bitmap); - } - } - }); - } - - @OnClick(R.id.btn_change_password) - void changePassword() { - startActivity(new Intent(getContext(), EditUserDetailActivity.class)); - } - - /** - * It is called whenever any error occurs while executing a request - * - * @param message Error message that tells the user about the problem. - */ - @Override - public void showError(String message) { - Toaster.show(rootView, message); - sweetUIErrorHandler.showSweetCustomErrorUI(getString(R.string.error_fetching_user_profile), - R.drawable.ic_assignment_turned_in_black_24dp, appBarLayout, - layoutError); - fabEdit.setVisibility(View.GONE); - } - - @Override - public void showProgress() { - showProgressBar(); - } - - @Override - public void hideProgress() { - hideProgressBar(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - hideProgress(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/UserProfileFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/UserProfileFragment.kt new file mode 100644 index 0000000000..e9d6b04bd6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/UserProfileFragment.kt @@ -0,0 +1,284 @@ +package org.mifos.mobile.ui.fragments + +import android.content.Intent +import android.graphics.Bitmap +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.widget.Toolbar +import androidx.core.content.ContextCompat +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler +import com.google.android.material.appbar.AppBarLayout +import com.google.android.material.appbar.CollapsingToolbarLayout +import com.google.android.material.floatingactionbutton.FloatingActionButton +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.client.Group +import org.mifos.mobile.presenters.UserDetailsPresenter +import org.mifos.mobile.ui.activities.EditUserDetailActivity +import org.mifos.mobile.ui.activities.base.BaseActivity +import org.mifos.mobile.ui.fragments.base.BaseFragment +import org.mifos.mobile.ui.views.UserDetailsView +import org.mifos.mobile.utils.Constants +import org.mifos.mobile.utils.DateHelper +import org.mifos.mobile.utils.TextDrawable +import org.mifos.mobile.utils.Toaster +import javax.inject.Inject + +/** + * Created by dilpreet on 10/7/17. + */ +class UserProfileFragment : BaseFragment(), UserDetailsView { + @kotlin.jvm.JvmField + @BindView(R.id.iv_profile) + var ivProfile: ImageView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.iv_text_drawable) + var ivTextDrawable: ImageView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.app_bar_layout) + var appBarLayout: AppBarLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.collapsing_toolbar) + var collapsingToolbarLayout: CollapsingToolbarLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_user_name) + var tvUsername: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_account_number) + var tvAccountNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_activation_date) + var tvActivationDate: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_office_name) + var tvOfficeName: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_groups) + var tvGroups: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_client_type) + var tvClientType: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_client_classification) + var tvClientClassification: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_phone_number) + var tvPhoneNumber: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_dob) + var tvDOB: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.tv_gender) + var tvGender: TextView? = null + + @kotlin.jvm.JvmField + @BindView(R.id.toolbar) + var toolbar: Toolbar? = null + + @kotlin.jvm.JvmField + @BindView(R.id.layout_error) + var layoutError: View? = null + + @kotlin.jvm.JvmField + @BindView(R.id.ll_user_profile) + var llUserProfile: LinearLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.fab_edit) + var fabEdit: FloatingActionButton? = null + + @kotlin.jvm.JvmField + @Inject + var presenter: UserDetailsPresenter? = null + + @kotlin.jvm.JvmField + @Inject + var preferencesHelper: PreferencesHelper? = null + private lateinit var rootView: View + private var userBitmap: Bitmap? = null + private var client: Client? = null + private var sweetUIErrorHandler: SweetUIErrorHandler? = null + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + rootView = inflater.inflate(R.layout.fragment_user_profile, container, false) + (activity as BaseActivity?)?.activityComponent?.inject(this) + ButterKnife.bind(this, rootView) + presenter?.attachView(this) + (activity as BaseActivity?)?.setSupportActionBar(toolbar) + (activity as BaseActivity?)?.supportActionBar?.setDisplayHomeAsUpEnabled(true) + collapsingToolbarLayout?.setCollapsedTitleTextColor(ContextCompat.getColor(activity!!, + R.color.white)) + collapsingToolbarLayout?.setExpandedTitleColor(ContextCompat.getColor(activity!!, + R.color.white)) + sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView) + if (savedInstanceState == null) { + presenter?.userDetails + presenter?.userImage + } + return rootView + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(Constants.USER_DETAILS, client) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + if (savedInstanceState != null) { + client = savedInstanceState.getParcelable(Constants.USER_DETAILS) + presenter?.setUserProfile(preferencesHelper?.userProfileImage) + showUserDetails(client) + } + } + + /** + * Sets client basic details which are fetched from server + * + * @param client instance of [Client] which contains information about client + */ + override fun showUserDetails(client: Client?) { + this.client = client + tvUsername?.text = nullFieldCheck(getString(R.string.username), client?.displayName) + tvAccountNumber?.text = nullFieldCheck(getString(R.string.account_number), + client?.accountNo) + tvActivationDate?.text = nullFieldCheck(getString(R.string.activation_date), + DateHelper.getDateAsString(client?.activationDate)) + tvOfficeName?.text = nullFieldCheck(getString(R.string.office_name), + client?.officeName) + tvClientType?.text = nullFieldCheck(getString(R.string.client_type), + client?.clientType?.name) + tvGroups?.text = nullFieldCheck(getString(R.string.groups), + getGroups(client?.groups)) + tvClientClassification?.text = nullFieldCheck(getString(R.string.client_classification), + client?.clientClassification?.name) + tvPhoneNumber?.text = nullFieldCheck(getString(R.string.phone_number), + client?.mobileNo) + if (client?.dobDate?.size != 3) { // no data entry in database for the client + tvDOB?.text = getString(R.string.no_dob_found) + } else { + tvDOB?.text = DateHelper.getDateAsString(client.dobDate) + } + tvGender?.text = nullFieldCheck(getString(R.string.gender), client?.gender?.name) + } + + private fun nullFieldCheck(field: String, value: String?): String { + return value + ?: getString(R.string.no) + getString(R.string.blank) + field + + getString(R.string.blank) + getString(R.string.found) + } + + /** + * Generate a string for groups which the client is part of. + * + * @param groups [List] of [Group] which client is a part of. + * @return Returns String of groups + */ + private fun getGroups(groups: List?): String { + if (groups?.isEmpty() == true) { + return getString( + R.string.not_assigned_with_any_group) // no groups entry in database for the + // client + } + val builder = StringBuilder() + if (groups != null) + for ((_, _, name) in groups) { + builder.append(getString(R.string.string_and_string, name, " | ")) + } + return builder.toString().substring(0, builder.toString().length - 2) + } + + /** + * Provides with client Image fetched from the server in `bitmap` + * + * @param bitmap User Image + */ + override fun showUserImage(bitmap: Bitmap?) { + activity?.runOnUiThread { + userBitmap = bitmap + if (userBitmap == null) { + val textDrawable = TextDrawable.builder() + .beginConfig() + .toUpperCase() + .endConfig() + .buildRound( + (if (preferencesHelper?.clientName.isNullOrEmpty()) preferencesHelper + ?.userName + else preferencesHelper + ?.clientName) + ?.substring(0, 1), + ContextCompat.getColor(context!!, R.color.primary_dark)) + ivProfile?.visibility = View.GONE + ivTextDrawable?.visibility = View.VISIBLE + ivTextDrawable?.setImageDrawable(textDrawable) + } else { + ivTextDrawable?.visibility = View.GONE + ivProfile?.visibility = View.VISIBLE + ivProfile?.setImageBitmap(bitmap) + } + } + } + + @OnClick(R.id.btn_change_password) + fun changePassword() { + startActivity(Intent(context, EditUserDetailActivity::class.java)) + } + + /** + * It is called whenever any error occurs while executing a request + * + * @param message Error message that tells the user about the problem. + */ + override fun showError(message: String?) { + Toaster.show(rootView, message) + sweetUIErrorHandler?.showSweetCustomErrorUI(getString(R.string.error_fetching_user_profile), + R.drawable.ic_assignment_turned_in_black_24dp, appBarLayout, + layoutError) + fabEdit?.visibility = View.GONE + } + + override fun showProgress() { + showProgressBar() + } + + override fun hideProgress() { + hideProgressBar() + } + + override fun onDestroyView() { + super.onDestroyView() + hideProgress() + presenter?.detachView() + } + + companion object { + @kotlin.jvm.JvmStatic + fun newInstance(): UserProfileFragment { + return UserProfileFragment() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/base/BaseFragment.java b/app/src/main/java/org/mifos/mobile/ui/fragments/base/BaseFragment.java deleted file mode 100644 index b5da727bbf..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/fragments/base/BaseFragment.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.mifos.mobile.ui.fragments.base; - -import android.app.Activity; -import android.content.Context; -import android.os.Bundle; - -import org.mifos.mobile.ui.views.BaseActivityCallback; -import org.mifos.mobile.utils.LanguageHelper; -import org.mifos.mobile.utils.ProgressBarHandler; - -import androidx.fragment.app.Fragment; - -public class BaseFragment extends Fragment { - - private BaseActivityCallback callback; - private ProgressBarHandler progressBarHandler; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressBarHandler = new ProgressBarHandler(getActivity()); - } - - /** - * Used to show Progress bar. {@code callback} is implemented in - * {@link org.mifos.mobile.ui.activities.base.BaseActivity} - * @param message Message you want to display - */ - protected void showMifosProgressDialog(String message) { - if (callback != null) - callback.showProgressDialog(message); - } - - /** - * Used for hiding the progressbar. - */ - protected void hideMifosProgressDialog() { - if (callback != null) - callback.hideProgressDialog(); - } - - /** - * Used for setting title of Toolbar - * @param title String you want to display as title - */ - protected void setToolbarTitle(String title) { - callback.setToolbarTitle(title); - } - - /** - * Displays {@link ProgressBarHandler} - */ - protected void showProgressBar() { - progressBarHandler.show(); - } - - /** - * Hides {@link ProgressBarHandler} - */ - protected void hideProgressBar() { - progressBarHandler.hide(); - } - - @Override - public void onAttach(Context context) { - super.onAttach(LanguageHelper.onAttach(context)); - Activity activity = context instanceof Activity ? (Activity) context : null; - try { - callback = (BaseActivityCallback) activity; - } catch (ClassCastException e) { - throw new ClassCastException(activity.toString() - + " must implement BaseActivityCallback methods"); - } - } - - @Override - public void onDetach() { - super.onDetach(); - callback = null; - } - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/fragments/base/BaseFragment.kt b/app/src/main/java/org/mifos/mobile/ui/fragments/base/BaseFragment.kt new file mode 100644 index 0000000000..5869502d65 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/fragments/base/BaseFragment.kt @@ -0,0 +1,73 @@ +package org.mifos.mobile.ui.fragments.base + +import android.app.Activity +import android.content.Context +import android.os.Bundle +import androidx.fragment.app.Fragment + +import org.mifos.mobile.ui.views.BaseActivityCallback +import org.mifos.mobile.utils.LanguageHelper +import org.mifos.mobile.utils.ProgressBarHandler + +open class BaseFragment : Fragment() { + private var callback: BaseActivityCallback? = null + private var progressBarHandler: ProgressBarHandler? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + progressBarHandler = activity?.let { ProgressBarHandler(it) } + } + + /** + * Used to show Progress bar. `callback` is implemented in + * [org.mifos.mobile.ui.activities.base.BaseActivity] + * @param message Message you want to display + */ + protected fun showMifosProgressDialog(message: String?) { + if (callback != null) callback?.showProgressDialog(message) + } + + /** + * Used for hiding the progressbar. + */ + protected fun hideMifosProgressDialog() { + if (callback != null) callback?.hideProgressDialog() + } + + /** + * Used for setting title of Toolbar + * @param title String you want to display as title + */ + protected fun setToolbarTitle(title: String?) { + callback?.setToolbarTitle(title) + } + + /** + * Displays [ProgressBarHandler] + */ + protected fun showProgressBar() { + progressBarHandler?.show() + } + + /** + * Hides [ProgressBarHandler] + */ + protected fun hideProgressBar() { + progressBarHandler?.hide() + } + + override fun onAttach(context: Context) { + super.onAttach(LanguageHelper.onAttach(context)) + val activity = if (context is Activity) context else null + callback = try { + activity as BaseActivityCallback? + } catch (e: ClassCastException) { + throw ClassCastException(activity.toString() + + " must implement BaseActivityCallback methods") + } + } + + override fun onDetach() { + super.onDetach() + callback = null + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/AccountOverviewMvpView.java b/app/src/main/java/org/mifos/mobile/ui/views/AccountOverviewMvpView.java deleted file mode 100644 index 4ebc6a5072..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/AccountOverviewMvpView.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * @author Rajan Maurya - * On 16/10/17. - */ -public interface AccountOverviewMvpView extends MVPView { - - void showTotalLoanSavings(double totalLoan, double totalSavings); - - void showError(String message); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/AccountOverviewMvpView.kt b/app/src/main/java/org/mifos/mobile/ui/views/AccountOverviewMvpView.kt new file mode 100644 index 0000000000..968c0d9bb0 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/AccountOverviewMvpView.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * @author Rajan Maurya + * On 16/10/17. + */ +interface AccountOverviewMvpView : MVPView { + fun showTotalLoanSavings(totalLoan: Double?, totalSavings: Double?) + fun showError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/AccountsView.java b/app/src/main/java/org/mifos/mobile/ui/views/AccountsView.java deleted file mode 100644 index cb6787b4f3..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/AccountsView.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.models.accounts.share.ShareAccount; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; - -/** - * Created by Rajan Maurya on 23/10/16. - */ - -public interface AccountsView extends MVPView { - - void showLoanAccounts(List loanAccounts); - - void showSavingsAccounts(List savingAccounts); - - void showShareAccounts(List shareAccounts); - - void showError(String errorMessage); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/AccountsView.kt b/app/src/main/java/org/mifos/mobile/ui/views/AccountsView.kt new file mode 100644 index 0000000000..650c124ed9 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/AccountsView.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.models.accounts.share.ShareAccount +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by Rajan Maurya on 23/10/16. + */ +interface AccountsView : MVPView { + fun showLoanAccounts(loanAccounts: List?) + fun showSavingsAccounts(savingAccounts: List?) + fun showShareAccounts(shareAccounts: List?) + fun showError(errorMessage: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/AddGuarantorView.java b/app/src/main/java/org/mifos/mobile/ui/views/AddGuarantorView.java deleted file mode 100644 index a978fb884d..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/AddGuarantorView.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.ui.views; - -/* - * Created by saksham on 23/July/2018 - */ - -import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload; -import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload; -import org.mifos.mobile.ui.views.base.MVPView; - -public interface AddGuarantorView extends MVPView { - - void updatedSuccessfully(String message); - void submittedSuccessfully(String message, GuarantorApplicationPayload payload); - void showGuarantorUpdation(GuarantorTemplatePayload template); - void showGuarantorApplication(GuarantorTemplatePayload template); - void showError(String message); - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/AddGuarantorView.kt b/app/src/main/java/org/mifos/mobile/ui/views/AddGuarantorView.kt new file mode 100644 index 0000000000..4eee7332b2 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/AddGuarantorView.kt @@ -0,0 +1,15 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload +import org.mifos.mobile.models.guarantor.GuarantorTemplatePayload +import org.mifos.mobile.ui.views.base.MVPView + +/* +* Created by saksham on 23/July/2018 +*/ interface AddGuarantorView : MVPView { + fun updatedSuccessfully(message: String?) + fun submittedSuccessfully(message: String?, payload: GuarantorApplicationPayload?) + fun showGuarantorUpdation(template: GuarantorTemplatePayload?) + fun showGuarantorApplication(template: GuarantorTemplatePayload?) + fun showError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BaseActivityCallback.java b/app/src/main/java/org/mifos/mobile/ui/views/BaseActivityCallback.java deleted file mode 100644 index bb3b9ff191..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/BaseActivityCallback.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.mifos.mobile.ui.views; - -/** - * @author Rajan Maurya - */ -public interface BaseActivityCallback { - - void showProgressDialog(String message); - - void hideProgressDialog(); - - void setToolbarTitle(String title); -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BaseActivityCallback.kt b/app/src/main/java/org/mifos/mobile/ui/views/BaseActivityCallback.kt new file mode 100644 index 0000000000..9720cd8fa4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/BaseActivityCallback.kt @@ -0,0 +1,13 @@ +package org.mifos.mobile.ui.views + +/** + * @author Rajan Maurya + */ +interface BaseActivityCallback { + + fun showProgressDialog(message: String?) + + fun hideProgressDialog() + + fun setToolbarTitle(title: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiariesView.java b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiariesView.java deleted file mode 100644 index 9ddaffe826..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiariesView.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; - -/** - * Created by dilpreet on 14/6/17. - */ - -public interface BeneficiariesView extends MVPView { - - void showUserInterface(); - - void showError(String msg); - - void showBeneficiaryList(List beneficiaryList); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiariesView.kt b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiariesView.kt new file mode 100644 index 0000000000..f37bef6491 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiariesView.kt @@ -0,0 +1,13 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 14/6/17. + */ +interface BeneficiariesView : MVPView { + fun showUserInterface() + fun showError(msg: String?) + fun showBeneficiaryList(beneficiaryList: List?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryApplicationView.java b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryApplicationView.java deleted file mode 100644 index 799bb1def6..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryApplicationView.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 16/6/17. - */ - -public interface BeneficiaryApplicationView extends MVPView { - - void showUserInterface(); - - void showBeneficiaryTemplate(BeneficiaryTemplate beneficiaryTemplate); - - void showBeneficiaryCreatedSuccessfully(); - - void showBeneficiaryUpdatedSuccessfully(); - - void showError(String msg); - - void setVisibility(int state); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryApplicationView.kt b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryApplicationView.kt new file mode 100644 index 0000000000..2e198cfbdd --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryApplicationView.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 16/6/17. + */ +interface BeneficiaryApplicationView : MVPView { + fun showUserInterface() + fun showBeneficiaryTemplate(beneficiaryTemplate: BeneficiaryTemplate?) + fun showBeneficiaryCreatedSuccessfully() + fun showBeneficiaryUpdatedSuccessfully() + fun showError(msg: String?) + fun setVisibility(state: Int) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryDetailView.java b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryDetailView.java deleted file mode 100644 index 374ae3bfdc..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryDetailView.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 16/6/17. - */ - -public interface BeneficiaryDetailView extends MVPView { - - void showUserInterface(); - - void showBeneficiaryDeletedSuccessfully(); - - void showError(String msg); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryDetailView.kt b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryDetailView.kt new file mode 100644 index 0000000000..4622e58d0e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/BeneficiaryDetailView.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 16/6/17. + */ +interface BeneficiaryDetailView : MVPView { + fun showUserInterface() + fun showBeneficiaryDeletedSuccessfully() + fun showError(msg: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/ClientChargeView.java b/app/src/main/java/org/mifos/mobile/ui/views/ClientChargeView.kt similarity index 57% rename from app/src/main/java/org/mifos/mobile/ui/views/ClientChargeView.java rename to app/src/main/java/org/mifos/mobile/ui/views/ClientChargeView.kt index 962be12e71..775ae7826c 100644 --- a/app/src/main/java/org/mifos/mobile/ui/views/ClientChargeView.java +++ b/app/src/main/java/org/mifos/mobile/ui/views/ClientChargeView.kt @@ -1,29 +1,27 @@ -package org.mifos.mobile.ui.views; +package org.mifos.mobile.ui.views -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; +import org.mifos.mobile.models.Charge +import org.mifos.mobile.ui.views.base.MVPView /** * @author Vishwajeet * @since 17/8/16. */ -public interface ClientChargeView extends MVPView { +interface ClientChargeView : MVPView { /** * Should be called if there is any error from client side in loading the client charges * from server. * Reason for error should be mentioned clearly to the user. * * @param message Error message to display showing reason of failure in loading - * charges of a particular client. + * charges of a particular client. */ - void showErrorFetchingClientCharges(String message); + fun showErrorFetchingClientCharges(message: String?) /** * Use to display List of charges for the respective client. * * @param clientChargesList List containing charges of a particular client */ - void showClientCharges(List clientChargesList); -} + fun showClientCharges(clientChargesList: List?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/GuarantorDetailView.java b/app/src/main/java/org/mifos/mobile/ui/views/GuarantorDetailView.java deleted file mode 100644 index a89eed5446..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/GuarantorDetailView.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.mifos.mobile.ui.views; - -/* - * Created by saksham on 25/July/2018 - */ - -import org.mifos.mobile.ui.views.base.MVPView; - -public interface GuarantorDetailView extends MVPView { - void guarantorDeletedSuccessfully(String message); - void showError(String message); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/GuarantorDetailView.kt b/app/src/main/java/org/mifos/mobile/ui/views/GuarantorDetailView.kt new file mode 100644 index 0000000000..44c8461f2d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/GuarantorDetailView.kt @@ -0,0 +1,10 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/* +* Created by saksham on 25/July/2018 +*/ interface GuarantorDetailView : MVPView { + fun guarantorDeletedSuccessfully(message: String?) + fun showError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/GuarantorListView.java b/app/src/main/java/org/mifos/mobile/ui/views/GuarantorListView.java deleted file mode 100644 index eff95d7c36..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/GuarantorListView.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.mifos.mobile.ui.views; - -/* - * Created by saksham on 24/July/2018 - */ - -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; - -public interface GuarantorListView extends MVPView { - - void showGuarantorListSuccessfully(List list); - void showError(String message); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/GuarantorListView.kt b/app/src/main/java/org/mifos/mobile/ui/views/GuarantorListView.kt new file mode 100644 index 0000000000..8cf203c808 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/GuarantorListView.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.ui.views.base.MVPView + +/* +* Created by saksham on 24/July/2018 +*/ interface GuarantorListView : MVPView { + fun showGuarantorListSuccessfully(list: List?) + fun showError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/HelpView.java b/app/src/main/java/org/mifos/mobile/ui/views/HelpView.java deleted file mode 100644 index 6716b37a4f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/HelpView.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.FAQ; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.ArrayList; - -/** - * Created by dilpreet on 12/8/17. - */ - -public interface HelpView extends MVPView { - - void showFaq(ArrayList faqArrayList); - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/HelpView.kt b/app/src/main/java/org/mifos/mobile/ui/views/HelpView.kt new file mode 100644 index 0000000000..0e5ffb7cc3 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/HelpView.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.FAQ +import org.mifos.mobile.ui.views.base.MVPView +import java.util.* + +/** + * Created by dilpreet on 12/8/17. + */ +interface HelpView : MVPView { + fun showFaq(faqArrayList: ArrayList?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/HomeOldView.java b/app/src/main/java/org/mifos/mobile/ui/views/HomeOldView.java deleted file mode 100644 index 6afb29664c..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/HomeOldView.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.mifos.mobile.ui.views; - -import android.graphics.Bitmap; - -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 19/6/17. - */ - -public interface HomeOldView extends MVPView { - - void showUserInterface(); - - void showLoanAccountDetails(double totalLoanAmount); - - void showSavingAccountDetails(double totalSavingAmount); - - void showUserDetails(Client client); - - void showUserImage(Bitmap bitmap); - - void showNotificationCount(int count); - - void showError(String errorMessage); - -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/HomeOldView.kt b/app/src/main/java/org/mifos/mobile/ui/views/HomeOldView.kt new file mode 100644 index 0000000000..4fb8acf6b6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/HomeOldView.kt @@ -0,0 +1,18 @@ +package org.mifos.mobile.ui.views + +import android.graphics.Bitmap +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 19/6/17. + */ +interface HomeOldView : MVPView { + fun showUserInterface() + fun showLoanAccountDetails(totalLoanAmount: Double) + fun showSavingAccountDetails(totalSavingAmount: Double) + fun showUserDetails(client: Client?) + fun showUserImage(bitmap: Bitmap?) + fun showNotificationCount(count: Int) + fun showError(errorMessage: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/HomeView.java b/app/src/main/java/org/mifos/mobile/ui/views/HomeView.java deleted file mode 100644 index 925e89acc3..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/HomeView.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifos.mobile.ui.views; - -import android.graphics.Bitmap; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 19/6/17. - */ - -public interface HomeView extends MVPView { - - void showUserDetails(String userName); - - void showUserImageTextDrawable(); - - void showUserImage(Bitmap bitmap); - - void showNotificationCount(int count); - - void showError(String errorMessage); - - void showUserImageNotFound(); - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/HomeView.kt b/app/src/main/java/org/mifos/mobile/ui/views/HomeView.kt new file mode 100644 index 0000000000..92e7b918e9 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/HomeView.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.views + +import android.graphics.Bitmap +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 19/6/17. + */ +interface HomeView : MVPView { + fun showUserDetails(userName: String?) + fun showUserImageTextDrawable() + fun showUserImage(bitmap: Bitmap?) + fun showNotificationCount(count: Int) + fun showError(errorMessage: String?) + fun showUserImageNotFound() +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountWithdrawView.java b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountWithdrawView.java deleted file mode 100644 index 6693b9e59f..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountWithdrawView.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 7/6/17. - */ - -public interface LoanAccountWithdrawView extends MVPView { - - public void showLoanAccountWithdrawSuccess(); - - public void showLoanAccountWithdrawError(String message); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountWithdrawView.kt b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountWithdrawView.kt new file mode 100644 index 0000000000..079b574f0c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountWithdrawView.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 7/6/17. + */ +interface LoanAccountWithdrawView : MVPView { + fun showLoanAccountWithdrawSuccess() + fun showLoanAccountWithdrawError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsDetailView.java b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsDetailView.kt similarity index 62% rename from app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsDetailView.java rename to app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsDetailView.kt index ebd6dcfa64..505894fb57 100644 --- a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsDetailView.java +++ b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsDetailView.kt @@ -1,30 +1,31 @@ -package org.mifos.mobile.ui.views; +package org.mifos.mobile.ui.views -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.ui.views.base.MVPView; +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.ui.views.base.MVPView /** * @author Vishwajeet * @since 19/08/16 */ -public interface LoanAccountsDetailView extends MVPView { +interface LoanAccountsDetailView : MVPView { /** * Should be called when loan account object can successfully accessed * from the server to display loan account details on the screen. * * @param loanWithAssociations object containing details of each loan account, - * received from server. + * received from server. */ - void showLoanAccountsDetail(LoanWithAssociations loanWithAssociations); + fun showLoanAccountsDetail(loanWithAssociations: LoanWithAssociations?) /** * Should be called if there is any error from client side in getting * loan account object from server. - *

+ * + * * Reason for error should be mentioned clearly to the user. * * @param message Error message to display showing reason of failure in getting - * loan account object + * loan account object */ - void showErrorFetchingLoanAccountsDetail(String message); -} + fun showErrorFetchingLoanAccountsDetail(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsTransactionView.java b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsTransactionView.java deleted file mode 100644 index 20da98bb13..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsTransactionView.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 4/3/17. - */ - -public interface LoanAccountsTransactionView extends MVPView { - - void showUserInterface(); - - void showLoanTransactions(LoanWithAssociations loanWithAssociations); - - void showEmptyTransactions(LoanWithAssociations loanWithAssociations); - - void showErrorFetchingLoanAccountsDetail(String message); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsTransactionView.kt b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsTransactionView.kt new file mode 100644 index 0000000000..863289150e --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/LoanAccountsTransactionView.kt @@ -0,0 +1,14 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 4/3/17. + */ +interface LoanAccountsTransactionView : MVPView { + fun showUserInterface() + fun showLoanTransactions(loanWithAssociations: LoanWithAssociations?) + fun showEmptyTransactions(loanWithAssociations: LoanWithAssociations?) + fun showErrorFetchingLoanAccountsDetail(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanApplicationMvpView.java b/app/src/main/java/org/mifos/mobile/ui/views/LoanApplicationMvpView.java deleted file mode 100644 index 4fd4969d70..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/LoanApplicationMvpView.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.templates.loans.LoanTemplate; -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by Rajan Maurya on 06/03/17. - */ - -public interface LoanApplicationMvpView extends MVPView { - - void showUserInterface(); - - void showLoanTemplate(LoanTemplate loanTemplate); - - void showUpdateLoanTemplate(LoanTemplate loanTemplate); - - void showLoanTemplateByProduct(LoanTemplate loanTemplate); - - void showUpdateLoanTemplateByProduct(LoanTemplate loanTemplate); - - void showError(String message); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanApplicationMvpView.kt b/app/src/main/java/org/mifos/mobile/ui/views/LoanApplicationMvpView.kt new file mode 100644 index 0000000000..f80a4c5e30 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/LoanApplicationMvpView.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.templates.loans.LoanTemplate +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by Rajan Maurya on 06/03/17. + */ +interface LoanApplicationMvpView : MVPView { + fun showUserInterface() + fun showLoanTemplate(loanTemplate: LoanTemplate?) + fun showUpdateLoanTemplate(loanTemplate: LoanTemplate?) + fun showLoanTemplateByProduct(loanTemplate: LoanTemplate?) + fun showUpdateLoanTemplateByProduct(loanTemplate: LoanTemplate?) + fun showError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanRepaymentScheduleMvpView.java b/app/src/main/java/org/mifos/mobile/ui/views/LoanRepaymentScheduleMvpView.java deleted file mode 100644 index 89a4342538..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/LoanRepaymentScheduleMvpView.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by Rajan Maurya on 03/03/17. - */ - -public interface LoanRepaymentScheduleMvpView extends MVPView { - - void showUserInterface(); - - void showLoanRepaymentSchedule(LoanWithAssociations loanWithAssociations); - - void showEmptyRepaymentsSchedule(LoanWithAssociations loanWithAssociations); - - void showError(String message); -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoanRepaymentScheduleMvpView.kt b/app/src/main/java/org/mifos/mobile/ui/views/LoanRepaymentScheduleMvpView.kt new file mode 100644 index 0000000000..da8126878a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/LoanRepaymentScheduleMvpView.kt @@ -0,0 +1,14 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by Rajan Maurya on 03/03/17. + */ +interface LoanRepaymentScheduleMvpView : MVPView { + fun showUserInterface() + fun showLoanRepaymentSchedule(loanWithAssociations: LoanWithAssociations?) + fun showEmptyRepaymentsSchedule(loanWithAssociations: LoanWithAssociations?) + fun showError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/LoginView.java b/app/src/main/java/org/mifos/mobile/ui/views/LoginView.kt similarity index 61% rename from app/src/main/java/org/mifos/mobile/ui/views/LoginView.java rename to app/src/main/java/org/mifos/mobile/ui/views/LoginView.kt index 75ee3236df..b80ed363fa 100644 --- a/app/src/main/java/org/mifos/mobile/ui/views/LoginView.java +++ b/app/src/main/java/org/mifos/mobile/ui/views/LoginView.kt @@ -1,14 +1,12 @@ -package org.mifos.mobile.ui.views; +package org.mifos.mobile.ui.views -import org.mifos.mobile.ui.views.base.MVPView; +import org.mifos.mobile.ui.views.base.MVPView /** * @author Vishwajeet * @since 05/06/16 */ - -public interface LoginView extends MVPView { - +interface LoginView : MVPView { /** * Should be called when the user credentials are successfully * authenticated from the API. @@ -17,35 +15,30 @@ public interface LoginView extends MVPView { * * @param userName Username of the user that successfully logged in! */ - void onLoginSuccess(String userName); + fun onLoginSuccess(userName: String?) /** * Should be called when there is a problem with the user input that we * requested or with trying to authenticate the user from the API. * * The error could be of many types like - *

    - *
  • Invalid Login Credentials
  • - *
  • No network connection
  • - *
+ * + * * Invalid Login Credentials + * * No network connection + * * * The problem must be communicated back to the user clearly. * @param errorMessage Error message that tells the user about the problem. */ - void showMessage(String errorMessage); - - void showUsernameError(String error); - - void showPasswordError(String error); - - void clearUsernameError(); - - void clearPasswordError(); + fun showMessage(errorMessage: String?) + fun showUsernameError(error: String?) + fun showPasswordError(error: String?) + fun clearUsernameError() + fun clearPasswordError() /** * Should be called when the client is fetched successfully from API. * */ - void showPassCodeActivity(); - -} + fun showPassCodeActivity() +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/NotificationView.java b/app/src/main/java/org/mifos/mobile/ui/views/NotificationView.java deleted file mode 100644 index b11acdde3c..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/NotificationView.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; - -/** - * Created by dilpreet on 14/9/17. - */ - -public interface NotificationView extends MVPView { - - void showNotifications(List notifications); - - void showError(String msg); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/NotificationView.kt b/app/src/main/java/org/mifos/mobile/ui/views/NotificationView.kt new file mode 100644 index 0000000000..80ff89dfb5 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/NotificationView.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 14/9/17. + */ +interface NotificationView : MVPView { + fun showNotifications(notifications: List?) + fun showError(msg: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/QrCodeImportView.java b/app/src/main/java/org/mifos/mobile/ui/views/QrCodeImportView.java deleted file mode 100644 index 1f8a8aaa66..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/QrCodeImportView.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.mifos.mobile.ui.views; - -import com.google.zxing.Result; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by manishkumar on 19/05/18. - */ - -public interface QrCodeImportView extends MVPView { - - - void showErrorReadingQr(String message); - - void handleDecodedResult (Result result); - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/QrCodeImportView.kt b/app/src/main/java/org/mifos/mobile/ui/views/QrCodeImportView.kt new file mode 100644 index 0000000000..d28965ef3d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/QrCodeImportView.kt @@ -0,0 +1,12 @@ +package org.mifos.mobile.ui.views + +import com.google.zxing.Result +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by manishkumar on 19/05/18. + */ +interface QrCodeImportView : MVPView { + fun showErrorReadingQr(message: String?) + fun handleDecodedResult(result: Result?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/RecentTransactionsView.java b/app/src/main/java/org/mifos/mobile/ui/views/RecentTransactionsView.kt similarity index 56% rename from app/src/main/java/org/mifos/mobile/ui/views/RecentTransactionsView.java rename to app/src/main/java/org/mifos/mobile/ui/views/RecentTransactionsView.kt index a34b180d7f..e7ccfb9606 100644 --- a/app/src/main/java/org/mifos/mobile/ui/views/RecentTransactionsView.java +++ b/app/src/main/java/org/mifos/mobile/ui/views/RecentTransactionsView.kt @@ -1,22 +1,17 @@ -package org.mifos.mobile.ui.views; +package org.mifos.mobile.ui.views -import org.mifos.mobile.models.Transaction; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; +import org.mifos.mobile.models.Transaction +import org.mifos.mobile.ui.views.base.MVPView /** * @author Vishwajeet * @since 10/08/16 */ - -public interface RecentTransactionsView extends MVPView { - - +interface RecentTransactionsView : MVPView { /** * Use to setup basic UI elements like RecyclerView and SwipeToRefresh etc. */ - void showUserInterface(); + fun showUserInterface() /** * Should be called if there is any error from client side in loading the recent transactions @@ -24,32 +19,28 @@ public interface RecentTransactionsView extends MVPView { * Reason for error should be mentioned clearly to the user. * * @param message Error message to display showing reason of failure in loading recent - * transactions. + * transactions. */ - void showErrorFetchingRecentTransactions(String message); + fun showErrorFetchingRecentTransactions(message: String?) /** * Use to display List of recent transactions for the respective client. * * @param transactions List containing recent transactions of a particular client */ - void showRecentTransactions(List transactions); - - - void showLoadMoreRecentTransactions(List transactions); - - void resetUI(); - - void showMessage(String message); + fun showRecentTransactions(transactions: List?) + fun showLoadMoreRecentTransactions(transactions: List?) + fun resetUI() + fun showMessage(message: String?) /** * Use to indicate user that there is no transaction to show; */ - void showEmptyTransaction(); + fun showEmptyTransaction() /** * Use to show and hide the swipe Layout; * @param show Boolean */ - void showSwipeRefreshLayout(boolean show); -} + fun showSwipeRefreshLayout(show: Boolean) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/RegistrationVerificationView.java b/app/src/main/java/org/mifos/mobile/ui/views/RegistrationVerificationView.java deleted file mode 100644 index 624522f3a0..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/RegistrationVerificationView.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 31/7/17. - */ - -public interface RegistrationVerificationView extends MVPView { - - void showVerifiedSuccessfully(); - - void showError(String msg); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/RegistrationVerificationView.kt b/app/src/main/java/org/mifos/mobile/ui/views/RegistrationVerificationView.kt new file mode 100644 index 0000000000..540ba41a96 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/RegistrationVerificationView.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 31/7/17. + */ +interface RegistrationVerificationView : MVPView { + fun showVerifiedSuccessfully() + fun showError(msg: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/RegistrationView.java b/app/src/main/java/org/mifos/mobile/ui/views/RegistrationView.java deleted file mode 100644 index ef69e84729..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/RegistrationView.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 31/7/17. - */ - -public interface RegistrationView extends MVPView { - - void showRegisteredSuccessfully(); - - void showError(String msg); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/RegistrationView.kt b/app/src/main/java/org/mifos/mobile/ui/views/RegistrationView.kt new file mode 100644 index 0000000000..cd64fe7ddf --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/RegistrationView.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 31/7/17. + */ +interface RegistrationView : MVPView { + fun showRegisteredSuccessfully() + fun showError(msg: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsDetailView.java b/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsDetailView.kt similarity index 58% rename from app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsDetailView.java rename to app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsDetailView.kt index 46aa00e69c..76cb2b763d 100644 --- a/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsDetailView.java +++ b/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsDetailView.kt @@ -1,21 +1,21 @@ -package org.mifos.mobile.ui.views; +package org.mifos.mobile.ui.views -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.ui.views.base.MVPView; +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.ui.views.base.MVPView /** * @author Vishwajeet * @since 18/8/16. */ -public interface SavingAccountsDetailView extends MVPView { +interface SavingAccountsDetailView : MVPView { /** * Should be called when saving account object can successfully accessed * from the server to display saving account details on the screen. * * @param savingsWithAssociations object containing details of each saving account, - * received from server. + * received from server. */ - void showSavingAccountsDetail(SavingsWithAssociations savingsWithAssociations); + fun showSavingAccountsDetail(savingsWithAssociations: SavingsWithAssociations?) /** * Should be called if there is any error from client side in getting @@ -24,10 +24,8 @@ public interface SavingAccountsDetailView extends MVPView { * Reason for error should be mentioned clearly to the user. * * @param message Error message to display showing reason of failure in getting - * saving account object + * saving account object */ - void showErrorFetchingSavingAccountsDetail(String message); - - - void showAccountStatus(SavingsWithAssociations savingsWithAssociations); -} + fun showErrorFetchingSavingAccountsDetail(message: String?) + fun showAccountStatus(savingsWithAssociations: SavingsWithAssociations?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsTransactionView.java b/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsTransactionView.java deleted file mode 100644 index 20625a4f37..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsTransactionView.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.models.accounts.savings.Transactions; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; - -/** - * Created by dilpreet on 6/3/17. - */ - -public interface SavingAccountsTransactionView extends MVPView { - - void showUserInterface(); - - void showSavingAccountsDetail(SavingsWithAssociations savingsWithAssociations); - - void showErrorFetchingSavingAccountsDetail(String message); - - void showFilteredList(List list); - -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsTransactionView.kt b/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsTransactionView.kt new file mode 100644 index 0000000000..ea39c1ff8f --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/SavingAccountsTransactionView.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.models.accounts.savings.Transactions +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 6/3/17. + */ +interface SavingAccountsTransactionView : MVPView { + fun showUserInterface() + fun showSavingAccountsDetail(savingsWithAssociations: SavingsWithAssociations?) + fun showErrorFetchingSavingAccountsDetail(message: String?) + fun showFilteredList(list: List?) + fun showEmptyTransactions() +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountApplicationView.java b/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountApplicationView.java deleted file mode 100644 index 50d121f4e7..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountApplicationView.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.mifos.mobile.ui.views; - -/* - * Created by saksham on 30/June/2018 - */ - -import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate; -import org.mifos.mobile.ui.views.base.MVPView; - -public interface SavingsAccountApplicationView extends MVPView { - - void showUserInterfaceSavingAccountApplication(SavingsAccountTemplate template); - void showSavingsAccountApplicationSuccessfully(); - void showUserInterfaceSavingAccountUpdate(SavingsAccountTemplate template); - void showSavingsAccountUpdateSuccessfully(); - void showError(String error); - void showMessage(String showMessage); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountApplicationView.kt b/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountApplicationView.kt new file mode 100644 index 0000000000..ae73802198 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountApplicationView.kt @@ -0,0 +1,15 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.templates.savings.SavingsAccountTemplate +import org.mifos.mobile.ui.views.base.MVPView + +/* +* Created by saksham on 30/June/2018 +*/ interface SavingsAccountApplicationView : MVPView { + fun showUserInterfaceSavingAccountApplication(template: SavingsAccountTemplate?) + fun showSavingsAccountApplicationSuccessfully() + fun showUserInterfaceSavingAccountUpdate(template: SavingsAccountTemplate?) + fun showSavingsAccountUpdateSuccessfully() + fun showError(error: String?) + fun showMessage(showMessage: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountWithdrawView.java b/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountWithdrawView.java deleted file mode 100644 index d774c8a7bb..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountWithdrawView.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.mifos.mobile.ui.views; - -/* - * Created by saksham on 02/July/2018 - */ - -import org.mifos.mobile.ui.views.base.MVPView; - -public interface SavingsAccountWithdrawView extends MVPView { - - void showUserInterface(); - void submitWithdrawSavingsAccount(); - void showSavingsAccountWithdrawSuccessfully(); - void showMessage(String message); - void showError(String error); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountWithdrawView.kt b/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountWithdrawView.kt new file mode 100644 index 0000000000..08abc40ac2 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/SavingsAccountWithdrawView.kt @@ -0,0 +1,13 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/* +* Created by saksham on 02/July/2018 +*/ interface SavingsAccountWithdrawView : MVPView { + fun showUserInterface() + fun submitWithdrawSavingsAccount() + fun showSavingsAccountWithdrawSuccessfully() + fun showMessage(message: String?) + fun showError(error: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingsMakeTransferMvpView.java b/app/src/main/java/org/mifos/mobile/ui/views/SavingsMakeTransferMvpView.java deleted file mode 100644 index c1abf15845..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/SavingsMakeTransferMvpView.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by Rajan Maurya on 10/03/17. - */ - -public interface SavingsMakeTransferMvpView extends MVPView { - - void showUserInterface(); - - void showSavingsAccountTemplate(AccountOptionsTemplate accountOptionsTemplate); - - void showToaster(String message); - - void showError(String message); - - void showProgressDialog(); - - void hideProgressDialog(); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/SavingsMakeTransferMvpView.kt b/app/src/main/java/org/mifos/mobile/ui/views/SavingsMakeTransferMvpView.kt new file mode 100644 index 0000000000..8ff1790cf1 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/SavingsMakeTransferMvpView.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by Rajan Maurya on 10/03/17. + */ +interface SavingsMakeTransferMvpView : MVPView { + fun showUserInterface() + fun showSavingsAccountTemplate(accountOptionsTemplate: AccountOptionsTemplate?) + fun showToaster(message: String?) + fun showError(message: String?) + fun showProgressDialog() + fun hideProgressDialog() +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/ThirdPartyTransferView.java b/app/src/main/java/org/mifos/mobile/ui/views/ThirdPartyTransferView.java deleted file mode 100644 index 9e0c6119f9..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/ThirdPartyTransferView.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.ui.views.base.MVPView; - -import java.util.List; - -/** - * Created by dilpreet on 21/6/17. - */ - -public interface ThirdPartyTransferView extends MVPView { - - void showUserInterface(); - - void showToaster(String msg); - - void showThirdPartyTransferTemplate(AccountOptionsTemplate accountOptionsTemplate); - - void showBeneficiaryList(List beneficiaries); - - void showError(String msg); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/ThirdPartyTransferView.kt b/app/src/main/java/org/mifos/mobile/ui/views/ThirdPartyTransferView.kt new file mode 100644 index 0000000000..fb3481f1d8 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/ThirdPartyTransferView.kt @@ -0,0 +1,16 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 21/6/17. + */ +interface ThirdPartyTransferView : MVPView { + fun showUserInterface() + fun showToaster(msg: String?) + fun showThirdPartyTransferTemplate(accountOptionsTemplate: AccountOptionsTemplate?) + fun showBeneficiaryList(beneficiaries: List?) + fun showError(msg: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/TransferProcessView.java b/app/src/main/java/org/mifos/mobile/ui/views/TransferProcessView.java deleted file mode 100644 index 1db5dbd7f6..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/TransferProcessView.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.views; - -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by dilpreet on 1/7/17. - */ - -public interface TransferProcessView extends MVPView { - - void showTransferredSuccessfully(); - - void showError(String msg); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/TransferProcessView.kt b/app/src/main/java/org/mifos/mobile/ui/views/TransferProcessView.kt new file mode 100644 index 0000000000..73bf5a947a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/TransferProcessView.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by dilpreet on 1/7/17. + */ +interface TransferProcessView : MVPView { + fun showTransferredSuccessfully() + fun showError(msg: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/UpdatePasswordView.java b/app/src/main/java/org/mifos/mobile/ui/views/UpdatePasswordView.java deleted file mode 100644 index b80388501d..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/UpdatePasswordView.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.views; - -/* - * Created by saksham on 13/July/2018 - */ - -import org.mifos.mobile.ui.views.base.MVPView; - -public interface UpdatePasswordView extends MVPView { - - void showError(String message); - - void showPasswordUpdatedSuccessfully(); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/UpdatePasswordView.kt b/app/src/main/java/org/mifos/mobile/ui/views/UpdatePasswordView.kt new file mode 100644 index 0000000000..de94e1c69c --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/UpdatePasswordView.kt @@ -0,0 +1,10 @@ +package org.mifos.mobile.ui.views + +import org.mifos.mobile.ui.views.base.MVPView + +/* +* Created by saksham on 13/July/2018 +*/ interface UpdatePasswordView : MVPView { + fun showError(message: String?) + fun showPasswordUpdatedSuccessfully() +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/UserDetailsView.java b/app/src/main/java/org/mifos/mobile/ui/views/UserDetailsView.java deleted file mode 100644 index fed53cae41..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/UserDetailsView.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.mifos.mobile.ui.views; - -import android.graphics.Bitmap; - -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.ui.views.base.MVPView; - -/** - * Created by naman on 07/04/17. - */ - -public interface UserDetailsView extends MVPView { - - void showUserDetails(Client client); - - void showUserImage(Bitmap bitmap); - - void showError(String message); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/UserDetailsView.kt b/app/src/main/java/org/mifos/mobile/ui/views/UserDetailsView.kt new file mode 100644 index 0000000000..197f3c0833 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/UserDetailsView.kt @@ -0,0 +1,14 @@ +package org.mifos.mobile.ui.views + +import android.graphics.Bitmap +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.ui.views.base.MVPView + +/** + * Created by naman on 07/04/17. + */ +interface UserDetailsView : MVPView { + fun showUserDetails(client: Client?) + fun showUserImage(bitmap: Bitmap?) + fun showError(message: String?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/base/MVPView.java b/app/src/main/java/org/mifos/mobile/ui/views/base/MVPView.kt similarity index 82% rename from app/src/main/java/org/mifos/mobile/ui/views/base/MVPView.java rename to app/src/main/java/org/mifos/mobile/ui/views/base/MVPView.kt index 612dd139e4..1339529b9c 100644 --- a/app/src/main/java/org/mifos/mobile/ui/views/base/MVPView.java +++ b/app/src/main/java/org/mifos/mobile/ui/views/base/MVPView.kt @@ -1,11 +1,10 @@ -package org.mifos.mobile.ui.views.base; +package org.mifos.mobile.ui.views.base /** * @author ishan * @since 19/05/16 */ -public interface MVPView { - +interface MVPView { /** * Should be called when a time taking process starts and we want the user * to wait for the process to finish. The UI should gracefully display some @@ -15,11 +14,11 @@ public interface MVPView { * For example: a network request to the API is made for authenticating * the user. */ - void showProgress(); + fun showProgress() /** * Should be called when a time taking process ends and we have some result * for the user. */ - void hideProgress(); -} + fun hideProgress() +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/views/base/OnClickItem.java b/app/src/main/java/org/mifos/mobile/ui/views/base/OnClickItem.java deleted file mode 100644 index e5d63c137d..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/views/base/OnClickItem.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.views.base; - -import android.view.View; - -/** - * Created by Rajan Maurya on 23/02/17. - */ - -public interface OnClickItem { - - void onItemClick(View childView, int position); - - void onItemLongPress(View childView, int position); -} diff --git a/app/src/main/java/org/mifos/mobile/ui/views/base/OnClickItem.kt b/app/src/main/java/org/mifos/mobile/ui/views/base/OnClickItem.kt new file mode 100644 index 0000000000..5e5c3177af --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/views/base/OnClickItem.kt @@ -0,0 +1,11 @@ +package org.mifos.mobile.ui.views.base + +import android.view.View + +/** + * Created by Rajan Maurya on 23/02/17. + */ +interface OnClickItem { + fun onItemClick(childView: View?, position: Int) + fun onItemLongPress(childView: View?, position: Int) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeAppWidget.java b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeAppWidget.java deleted file mode 100644 index 287da434f4..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeAppWidget.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.mifos.mobile.ui.widgets; - -import android.annotation.TargetApi; -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.Context; -import android.content.Intent; -import android.os.Build; -import android.widget.RemoteViews; - -import org.mifos.mobile.R; - -import androidx.annotation.NonNull; - -/** - * Implementation of App Widget functionality. - */ -public class ChargeAppWidget extends AppWidgetProvider { - - static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, - int appWidgetId) { - RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.charge_app_widget); - - // Set up the collection - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - setRemoteAdapter(context, views); - } else { - setRemoteAdapterV11(context, views); - } - // Instruct the widget manager to update the widget - appWidgetManager.updateAppWidget(appWidgetId, views); - } - - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - // There may be multiple widgets active, so update all of them - for (int appWidgetId : appWidgetIds) { - updateAppWidget(context, appWidgetManager, appWidgetId); - } - super.onUpdate(context, appWidgetManager, appWidgetIds); - } - - @Override - public void onEnabled(Context context) { - // Enter relevant functionality for when the first widget is created - } - - @Override - public void onDisabled(Context context) { - // Enter relevant functionality for when the last widget is disabled - } - - /** - * Sets the remote adapter used to fill in the list items - * - * @param views RemoteViews to set the RemoteAdapter - */ - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - private static void setRemoteAdapter(Context context, @NonNull final RemoteViews views) { - views.setRemoteAdapter(R.id.lv_charges, new Intent(context, ChargeWidgetService.class)); - } - - /** - * Sets the remote adapter used to fill in the list items - * - * @param views RemoteViews to set the RemoteAdapter - */ - @SuppressWarnings("deprecation") - private static void setRemoteAdapterV11(Context context, @NonNull final RemoteViews views) { - views.setRemoteAdapter(0, R.id.lv_charges, new Intent(context, ChargeWidgetService.class)); - } -} - - - diff --git a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeAppWidget.kt b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeAppWidget.kt new file mode 100644 index 0000000000..34d1eb3695 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeAppWidget.kt @@ -0,0 +1,58 @@ +package org.mifos.mobile.ui.widgets + +import android.annotation.TargetApi +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProvider +import android.content.Context +import android.content.Intent +import android.os.Build +import android.widget.RemoteViews + +import org.mifos.mobile.R + +/** + * Implementation of App Widget functionality. + */ +class ChargeAppWidget : AppWidgetProvider() { + + override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { + // There may be multiple widgets active, so update all of them + for (appWidgetId in appWidgetIds) { + updateAppWidget(context, appWidgetManager, appWidgetId) + } + super.onUpdate(context, appWidgetManager, appWidgetIds) + } + + override fun onEnabled(context: Context) { + // Enter relevant functionality for when the first widget is created + } + + override fun onDisabled(context: Context) { + // Enter relevant functionality for when the last widget is disabled + } + + companion object { + fun updateAppWidget( + context: Context, appWidgetManager: AppWidgetManager, + appWidgetId: Int + ) { + val views = RemoteViews(context.packageName, R.layout.charge_app_widget) + + // Set up the collection + setRemoteAdapter(context, views) + // Instruct the widget manager to update the widget + appWidgetManager.updateAppWidget(appWidgetId, views) + } + + /** + * Sets the remote adapter used to fill in the list items + * + * @param views RemoteViews to set the RemoteAdapter + */ + @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) + private fun setRemoteAdapter(context: Context, views: RemoteViews) { + views.setRemoteAdapter(R.id.lv_charges, Intent(context, ChargeWidgetService::class.java)) + } + + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetDataProvider.java b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetDataProvider.java deleted file mode 100644 index 7abb3a757a..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetDataProvider.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.mifos.mobile.ui.widgets; - -import android.content.Context; -import android.content.Intent; -import android.widget.RemoteViews; -import android.widget.RemoteViewsService; -import android.widget.Toast; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.BaseApiManager; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.DatabaseHelper; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.injection.ApplicationContext; -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.presenters.ClientChargePresenter; -import org.mifos.mobile.ui.views.ClientChargeView; - -import java.util.ArrayList; -import java.util.List; - -/** - * ChargeWidgetDataProvider acts as the adapter for the collection view widget, - * providing RemoteViews to the widget in the getViewAt method. - */ -public class ChargeWidgetDataProvider implements RemoteViewsService.RemoteViewsFactory, - ClientChargeView { - - private static final String LOG_TAG = ChargeWidgetDataProvider.class.getSimpleName(); - - ClientChargePresenter chargePresenter; - - private Context context; - private List charges; - private final Object object; - - public ChargeWidgetDataProvider(@ApplicationContext Context context, Intent intent) { - this.context = context; - object = new Object(); - charges = new ArrayList<>(); - } - - @Override - public void onCreate() { - PreferencesHelper preferencesHelper = new PreferencesHelper(context); - BaseApiManager baseApiManager = new BaseApiManager(preferencesHelper); - DatabaseHelper databaseHelper = new DatabaseHelper(); - DataManager dataManager = new DataManager(preferencesHelper, baseApiManager, - databaseHelper); - chargePresenter = new ClientChargePresenter(dataManager, context); - chargePresenter.attachView(this); - } - - @Override - public void onDataSetChanged() { - //TODO Make ClientId Dynamic - chargePresenter.loadClientLocalCharges(); - synchronized (object) { - try { - // Calling wait() will block this thread until another thread - // calls notify() on the object. - object.wait(); - } catch (InterruptedException e) { - // Happens if someone interrupts your thread. - } - } - } - - @Override - public int getCount() { - return charges.size(); - } - - @Override - public RemoteViews getViewAt(int position) { - - Charge charge = charges.get(position); - - final int itemId = R.layout.item_widget_client_charge; - RemoteViews view = new RemoteViews(context.getPackageName(), itemId); - view.setTextViewText(R.id.tv_charge_name, charge.getName()); - view.setTextViewText(R.id.tv_charge_amount, String.valueOf(charge.getAmount())); - view.setImageViewResource(R.id.circle_status, R.drawable.ic_attach_money_black_24dp); - return view; - } - - @Override - public RemoteViews getLoadingView() { - return null; - } - - @Override - public int getViewTypeCount() { - return 1; - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public boolean hasStableIds() { - return false; - } - - @Override - public void showErrorFetchingClientCharges(String message) { - Toast.makeText(context, context.getString(R.string.error_client_charge_loading), - Toast.LENGTH_SHORT).show(); - } - - @Override - public void showClientCharges(List clientChargesList) { - charges = clientChargesList; - synchronized (object) { - object.notify(); - } - } - - @Override - public void showProgress() { - - } - - @Override - public void hideProgress() { - - } - - @Override - public void onDestroy() { - chargePresenter.detachView(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetDataProvider.kt b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetDataProvider.kt new file mode 100644 index 0000000000..5586a7e430 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetDataProvider.kt @@ -0,0 +1,116 @@ +package org.mifos.mobile.ui.widgets + +import android.content.Context +import android.widget.RemoteViews +import android.widget.RemoteViewsService.RemoteViewsFactory +import android.widget.Toast + +import org.mifos.mobile.R +import org.mifos.mobile.api.BaseApiManager +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.DatabaseHelper +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.injection.ApplicationContext +import org.mifos.mobile.models.Charge +import org.mifos.mobile.presenters.ClientChargePresenter +import org.mifos.mobile.ui.views.ClientChargeView + +import java.util.* +import java.util.concurrent.locks.ReentrantLock + +/** + * ChargeWidgetDataProvider acts as the adapter for the collection view widget, + * providing RemoteViews to the widget in the getViewAt method. + */ +class ChargeWidgetDataProvider(@param:ApplicationContext private val context: Context) : + RemoteViewsFactory, + ClientChargeView { + + private var chargePresenter: ClientChargePresenter? = null + private var charges: List? + private val `object`: ReentrantLock = ReentrantLock() + private val condition = `object`.newCondition() + + override fun onCreate() { + val preferencesHelper = PreferencesHelper(context) + val baseApiManager = BaseApiManager(preferencesHelper) + val databaseHelper = DatabaseHelper() + val dataManager = DataManager(preferencesHelper, baseApiManager, + databaseHelper) + chargePresenter = ClientChargePresenter(dataManager, context) + chargePresenter?.attachView(this) + } + + override fun onDataSetChanged() { + //TODO Make ClientId Dynamic + chargePresenter?.loadClientLocalCharges() + synchronized(`object`) { + try { + // Calling wait() will block this thread until another thread + // calls notify() on the object. + condition.await() + } catch (e: InterruptedException) { + // Happens if someone interrupts your thread. + } + } + } + + override fun getCount(): Int { + return if (charges != null) charges!!.size + else 0 + } + + override fun getViewAt(position: Int): RemoteViews { + val charge = charges?.get(position) + val itemId = R.layout.item_widget_client_charge + val view = RemoteViews(context.packageName, itemId) + view.setTextViewText(R.id.tv_charge_name, charge?.name) + view.setTextViewText(R.id.tv_charge_amount, charge?.amount.toString()) + view.setImageViewResource(R.id.circle_status, R.drawable.ic_attach_money_black_24dp) + return view + } + + override fun getLoadingView(): RemoteViews? { + return null + } + + override fun getViewTypeCount(): Int { + return 1 + } + + override fun getItemId(position: Int): Long { + return position.toLong() + } + + override fun hasStableIds(): Boolean { + return false + } + + override fun showErrorFetchingClientCharges(message: String?) { + Toast.makeText(context, context.getString(R.string.error_client_charge_loading), + Toast.LENGTH_SHORT).show() + } + + override fun showClientCharges(clientChargesList: List?) { + charges = clientChargesList + synchronized(`object`) { + condition.signal() + } + } + + override fun showProgress() {} + + override fun hideProgress() {} + + override fun onDestroy() { + chargePresenter?.detachView() + } + + companion object { + private val LOG_TAG = ChargeWidgetDataProvider::class.java.simpleName + } + + init { + charges = ArrayList() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetService.java b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetService.java deleted file mode 100644 index e2633122b7..0000000000 --- a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetService.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.mifos.mobile.ui.widgets; - -import android.content.Intent; -import android.widget.RemoteViewsService; - -/** - * ChargeWidgetService is the {@link RemoteViewsService} that will return our RemoteViewsFactory - */ -public class ChargeWidgetService extends RemoteViewsService { - @Override - public RemoteViewsFactory onGetViewFactory(Intent intent) { - return new ChargeWidgetDataProvider(this, intent); - } -} diff --git a/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetService.kt b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetService.kt new file mode 100644 index 0000000000..72b7afe1bb --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/ui/widgets/ChargeWidgetService.kt @@ -0,0 +1,14 @@ +package org.mifos.mobile.ui.widgets + +import android.content.Intent +import android.widget.RemoteViewsService + +/** + * ChargeWidgetService is the [RemoteViewsService] that will return our RemoteViewsFactory + */ +class ChargeWidgetService : RemoteViewsService() { + + override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { + return ChargeWidgetDataProvider(this) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/CheckSelfPermissionAndRequest.java b/app/src/main/java/org/mifos/mobile/utils/CheckSelfPermissionAndRequest.kt similarity index 51% rename from app/src/main/java/org/mifos/mobile/utils/CheckSelfPermissionAndRequest.java rename to app/src/main/java/org/mifos/mobile/utils/CheckSelfPermissionAndRequest.kt index f35fc646f3..13c1aea303 100644 --- a/app/src/main/java/org/mifos/mobile/utils/CheckSelfPermissionAndRequest.java +++ b/app/src/main/java/org/mifos/mobile/utils/CheckSelfPermissionAndRequest.kt @@ -1,29 +1,24 @@ -package org.mifos.mobile.utils; +package org.mifos.mobile.utils -import android.annotation.TargetApi; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.os.Build; -import android.provider.Settings; -import android.widget.Toast; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.local.PreferencesHelper; - -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; +import android.annotation.TargetApi +import android.content.Context +import android.content.DialogInterface +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.provider.Settings +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat +import org.mifos.mobile.R +import org.mifos.mobile.api.local.PreferencesHelper /** * Created by dilpreet on 14/7/17. */ - -public class CheckSelfPermissionAndRequest { - - +object CheckSelfPermissionAndRequest { /** * This Method Check the Permission is granted or not to the App. If the Permission granted, * returns true and If not permission denied then returns false. @@ -32,9 +27,10 @@ public class CheckSelfPermissionAndRequest { * @param permission Manifest.permission...Permission... * @return Boolean True or False. */ - public static Boolean checkSelfPermission(Context context, String permission) { - return ContextCompat.checkSelfPermission(context, permission) == - PackageManager.PERMISSION_GRANTED; + @JvmStatic + fun checkSelfPermission(context: Context?, permission: String?): Boolean { + return ContextCompat.checkSelfPermission(context!!, permission!!) == + PackageManager.PERMISSION_GRANTED } /** @@ -48,13 +44,15 @@ public static Boolean checkSelfPermission(Context context, String permission) { * you want to give this permission to app or not, If yes then click on Re-Try dialog button * and if not then click on Dialog button "I'M Sure", to not to give this permission to the * app. - *

+ * + * * And as user will click on "Re-Try" dialog button, he will be prompt with the with * permission dialog with "[-] never ask again" and have two options first one to click on * denied button again and put Un check the never ask check box. In this case, user will * prompt with permission dialog with "[-] never ask again" in the loop, whenever app ask * for that permission. - *

+ * + * * and If user will click on "[_/] never ask again" check box then permission dialog with * that permission will not prompt to the user. * 3. Third case will came. when user have denied to accept permission with never ask again. @@ -70,76 +68,65 @@ public static Boolean checkSelfPermission(Context context, String permission) { * @param messageNeverAskAgain Dialog Message Never Ask Again * @param permissionDeniedStatus Permission Denied Status */ + @JvmStatic @TargetApi(Build.VERSION_CODES.JELLY_BEAN) - public static void requestPermission(final AppCompatActivity activity, - final String permission, - final int permissionRequestCode, - final String dialogMessageRetry, - final String messageNeverAskAgain, - final String permissionDeniedStatus) { + fun requestPermission( + activity: AppCompatActivity, + permission: String, + permissionRequestCode: Int, + dialogMessageRetry: String?, + messageNeverAskAgain: String?, + permissionDeniedStatus: String? + ) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. - new MaterialDialog.Builder().init(activity) + MaterialDialog.Builder().init(activity) .setTitle(R.string.dialog_permission_denied) .setMessage(dialogMessageRetry) .setPositiveButton(R.string.dialog_action_re_try, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - ActivityCompat.requestPermissions(activity, new - String[]{permission}, - permissionRequestCode); - } + DialogInterface.OnClickListener { _, _ -> + ActivityCompat.requestPermissions(activity, arrayOf(permission), + permissionRequestCode) }) .setNegativeButton(R.string.dialog_action_i_am_sure) .createMaterialDialog() - .show(); + .show() } else { //Requesting Permission, first time to the device. - PreferencesHelper preferencesHelper = new PreferencesHelper(activity. - getApplicationContext()); - if (preferencesHelper.getBoolean(permissionDeniedStatus, true)) { - preferencesHelper.putBoolean(permissionDeniedStatus, false); - - ActivityCompat.requestPermissions(activity, new String[]{permission}, - permissionRequestCode); + val preferencesHelper = PreferencesHelper(activity.applicationContext) + if (preferencesHelper.getBoolean(permissionDeniedStatus, true) == true) { + preferencesHelper.putBoolean(permissionDeniedStatus, false) + ActivityCompat.requestPermissions(activity, arrayOf(permission), + permissionRequestCode) } else { //Requesting Permission, more the one time and opening the setting to change // the Permission in App Settings. - new MaterialDialog.Builder().init(activity) + MaterialDialog.Builder().init(activity) .setMessage(messageNeverAskAgain) .setNegativeButton(R.string.dialog_action_cancel) .setPositiveButton(R.string.dialog_action_app_settings, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - //Making the Intent to grant the permission - Intent intent = - new Intent(Settings - .ACTION_APPLICATION_DETAILS_SETTINGS); - Uri uri = Uri.fromParts(activity.getResources().getString( - R.string.package_name), activity.getPackageName() - , null); - intent.setData(uri); - PackageManager pm = activity.getPackageManager(); - if (intent.resolveActivity(pm) != null) { - activity.startActivityForResult(intent, - Constants.REQUEST_PERMISSION_SETTING); - } else { - Toast.makeText(activity, activity.getString( - R.string.msg_setting_activity_not_found) - , Toast.LENGTH_LONG).show(); - } + DialogInterface.OnClickListener { _, _ -> //Making the Intent to grant the permission + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + val uri = Uri.fromParts(activity.resources.getString( + R.string.package_name), activity.packageName, null) + intent.data = uri + val pm = activity.packageManager + if (intent.resolveActivity(pm) != null) { + activity.startActivityForResult(intent, + Constants.REQUEST_PERMISSION_SETTING) + } else { + Toast.makeText(activity, activity.getString( + R.string.msg_setting_activity_not_found), Toast.LENGTH_LONG).show() } }) .createMaterialDialog() - .show(); + .show() } } } -} +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/CircularImageView.java b/app/src/main/java/org/mifos/mobile/utils/CircularImageView.java deleted file mode 100644 index dcc0c29989..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/CircularImageView.java +++ /dev/null @@ -1,160 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.graphics.BitmapShader; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Shader; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.widget.ImageView; - -import org.mifos.mobile.R; - -public class CircularImageView extends ImageView { - private int borderWidth; - private int canvasSize; - private Bitmap image; - private Paint paint; - private Paint paintBorder; - - public CircularImageView(final Context context) { - this(context, null); - } - - public CircularImageView(Context context, AttributeSet attrs) { - super(context, attrs); - - // init paint - paint = new Paint(); - paint.setAntiAlias(true); - - paintBorder = new Paint(); - paintBorder.setAntiAlias(true); - - // load the styled attributes and set their properties - TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable - .CircularImageView); - - if (attributes.getBoolean(R.styleable.CircularImageView_border, true)) { - int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics() - .density + 0.5f); - setBorderWidth(attributes.getDimensionPixelOffset(R.styleable - .CircularImageView_border_width, defaultBorderSize)); - setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color - .WHITE)); - } - - if (attributes.getBoolean(R.styleable.CircularImageView_shadow, false)) - addShadow(); - } - - public void setBorderWidth(int borderWidth) { - this.borderWidth = borderWidth; - this.requestLayout(); - this.invalidate(); - } - - public void setBorderColor(int borderColor) { - if (paintBorder != null) - paintBorder.setColor(borderColor); - this.invalidate(); - } - - public void addShadow() { - setLayerType(LAYER_TYPE_SOFTWARE, paintBorder); - paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK); - } - - @Override - public void onDraw(Canvas canvas) { - // load the bitmap - image = drawableToBitmap(getDrawable()); - - // init shader - if (image != null) { - - canvasSize = canvas.getWidth(); - if (canvas.getHeight() < canvasSize) - canvasSize = canvas.getHeight(); - - BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, - canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); - paint.setShader(shader); - - // circleCenter is the x or y of the view's center - // radius is the radius in pixels of the cirle to be drawn - // paint contains the shader that will texture the shape - int circleCenter = (canvasSize - (borderWidth * 2)) / 2; - canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ( - (canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder); - canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ( - (canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint); - } - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int width = measureWidth(widthMeasureSpec); - int height = measureHeight(heightMeasureSpec); - setMeasuredDimension(width, height); - } - - private int measureWidth(int measureSpec) { - int result = 0; - int specMode = MeasureSpec.getMode(measureSpec); - int specSize = MeasureSpec.getSize(measureSpec); - - if (specMode == MeasureSpec.EXACTLY) { - // The parent has determined an exact size for the child. - result = specSize; - } else if (specMode == MeasureSpec.AT_MOST) { - // The child can be as large as it wants up to the specified size. - result = specSize; - } else { - // The parent has not imposed any constraint on the child. - result = canvasSize; - } - return result; - } - - private int measureHeight(int measureSpecHeight) { - int result = 0; - int specMode = MeasureSpec.getMode(measureSpecHeight); - int specSize = MeasureSpec.getSize(measureSpecHeight); - - if (specMode == MeasureSpec.EXACTLY) { - // We were told how big to be - result = specSize; - } else if (specMode == MeasureSpec.AT_MOST) { - // The child can be as large as it wants up to the specified size. - result = specSize; - } else { - // Measure the text (beware: ascent is a negative number) - result = canvasSize; - } - - return (result + 2); - } - - public Bitmap drawableToBitmap(Drawable drawable) { - if (drawable == null) { - return null; - } else if (drawable instanceof BitmapDrawable) { - return ((BitmapDrawable) drawable).getBitmap(); - } - Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable - .getIntrinsicHeight(), Bitmap.Config.ARGB_8888); - Bitmap bitmapScaled = Bitmap.createScaledBitmap(bitmap, bitmap.getHeight() / 5, bitmap - .getHeight() / 5, true); - Canvas canvas = new Canvas(bitmapScaled); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - drawable.draw(canvas); - return bitmapScaled; - } - -} diff --git a/app/src/main/java/org/mifos/mobile/utils/CircularImageView.kt b/app/src/main/java/org/mifos/mobile/utils/CircularImageView.kt new file mode 100644 index 0000000000..0264b658f3 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/CircularImageView.kt @@ -0,0 +1,123 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.graphics.* +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable +import android.util.AttributeSet +import android.view.View +import androidx.appcompat.widget.AppCompatImageView +import org.mifos.mobile.R + +class CircularImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : AppCompatImageView(context, attrs) { + private var borderWidth = 0 + private var canvasSize = 0 + private var image: Bitmap? = null + private val paint: Paint = Paint() + private val paintBorder: Paint? + private fun setBorderWidth(borderWidth: Int) { + this.borderWidth = borderWidth + requestLayout() + this.invalidate() + } + + private fun setBorderColor(borderColor: Int) { + if (paintBorder != null) paintBorder.color = borderColor + this.invalidate() + } + + private fun addShadow() { + setLayerType(View.LAYER_TYPE_SOFTWARE, paintBorder) + paintBorder?.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK) + } + + public override fun onDraw(canvas: Canvas) { + // load the bitmap + image = drawableToBitmap(drawable) + + // init shader + if (image != null) { + canvasSize = canvas.width + if (canvas.height < canvasSize) canvasSize = canvas.height + val shader = BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, + canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) + paint.shader = shader + + // circleCenter is the x or y of the view's center + // radius is the radius in pixels of the cirle to be drawn + // paint contains the shader that will texture the shape + val circleCenter = (canvasSize - borderWidth * 2) / 2 + canvas.drawCircle(circleCenter + borderWidth.toFloat(), circleCenter + borderWidth.toFloat(), (canvasSize - borderWidth * 2) / 2 + borderWidth - 4.0f, paintBorder) + canvas.drawCircle(circleCenter + borderWidth.toFloat(), circleCenter + borderWidth.toFloat(), (canvasSize - borderWidth * 2) / 2 - 4.0f, paint) + } + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = measureWidth(widthMeasureSpec) + val height = measureHeight(heightMeasureSpec) + setMeasuredDimension(width, height) + } + + private fun measureWidth(measureSpec: Int): Int { + var result = 0 + val specMode = MeasureSpec.getMode(measureSpec) + val specSize = MeasureSpec.getSize(measureSpec) + result = when (specMode) { + MeasureSpec.EXACTLY -> + specSize // The parent has determined an exact size for the child. + MeasureSpec.AT_MOST -> + specSize // The child can be as large as it wants up to the specified size. + else -> + canvasSize // The parent has not imposed any constraint on the child. + } + return result + } + + private fun measureHeight(measureSpecHeight: Int): Int { + var result = 0 + val specMode = MeasureSpec.getMode(measureSpecHeight) + val specSize = MeasureSpec.getSize(measureSpecHeight) + result = when (specMode) { + MeasureSpec.EXACTLY -> + specSize // We were told how big to be + MeasureSpec.AT_MOST -> + specSize // The child can be as large as it wants up to the specified size. + else -> + canvasSize // Measure the text (beware: ascent is a negative number) + } + return result + 2 + } + + private fun drawableToBitmap(drawable: Drawable?): Bitmap? { + if (drawable == null) { + return null + } else if (drawable is BitmapDrawable) { + return drawable.bitmap + } + val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable + .intrinsicHeight, Bitmap.Config.ARGB_8888) + val bitmapScaled = Bitmap.createScaledBitmap(bitmap, bitmap.height / 5, bitmap + .height / 5, true) + val canvas = Canvas(bitmapScaled) + drawable.setBounds(0, 0, canvas.width, canvas.height) + drawable.draw(canvas) + return bitmapScaled + } + + init { + + // init paint + paint.isAntiAlias = true + paintBorder = Paint() + paintBorder.isAntiAlias = true + + // load the styled attributes and set their properties + val attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView) + if (attributes.getBoolean(R.styleable.CircularImageView_border, true)) { + val defaultBorderSize = (4 * getContext().resources.displayMetrics.density + 0.5f).toInt() + setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize)) + setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE)) + } + if (attributes.getBoolean(R.styleable.CircularImageView_shadow, false)) addShadow() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ComparatorBasedOnId.java b/app/src/main/java/org/mifos/mobile/utils/ComparatorBasedOnId.java deleted file mode 100644 index 761aa40b32..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/ComparatorBasedOnId.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.mifos.mobile.utils; - -import org.mifos.mobile.models.accounts.Account; - -import java.util.Comparator; - -/** - * Created by dilpreet on 14/6/17. - */ - -public class ComparatorBasedOnId implements Comparator { - /** - * Compares {@link Account} based on their Id - * @param o1 the first object to be compared. - * @param o2 the second object to be compared. - * @return a negative integer, zero, or a positive integer as the - * first argument is less than, equal to, or greater than the - * second. - */ - @Override - public int compare(Account o1, Account o2) { - return Float.compare(o2.getId(), o1.getId()); - } -} - diff --git a/app/src/main/java/org/mifos/mobile/utils/ComparatorBasedOnId.kt b/app/src/main/java/org/mifos/mobile/utils/ComparatorBasedOnId.kt new file mode 100644 index 0000000000..1148f0b983 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/ComparatorBasedOnId.kt @@ -0,0 +1,22 @@ +package org.mifos.mobile.utils + +import org.mifos.mobile.models.accounts.Account + +/** + * Created by dilpreet on 14/6/17. + */ +open class ComparatorBasedOnId : Comparator { + /** + * Compares [Account] based on their Id + * @param o1 the first object to be compared. + * @param o2 the second object to be compared. + * @return a negative integer, zero, or a positive integer as the + * first argument is less than, equal to, or greater than the + * second. + */ + override fun compare(o1: Account?, o2: Account?): Int { + return if (o1 != null && o2 != null) + o2.id.toFloat().compareTo(o1.id.toFloat()) + else 0 + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ConfigurationDialogFragmentCompat.java b/app/src/main/java/org/mifos/mobile/utils/ConfigurationDialogFragmentCompat.java deleted file mode 100644 index 6d212151dd..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/ConfigurationDialogFragmentCompat.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.content.Intent; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.EditText; - -import com.google.android.material.textfield.TextInputLayout; - -import org.mifos.mobile.R; -import org.mifos.mobile.api.BaseApiManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.ui.activities.LoginActivity; - -import java.net.MalformedURLException; -import java.net.URL; - -import androidx.preference.DialogPreference; -import androidx.preference.Preference; -import androidx.preference.PreferenceDialogFragmentCompat; -import butterknife.BindView; -import butterknife.ButterKnife; - -/** - * Created by dilpreet on 11/03/18. - */ - -public class ConfigurationDialogFragmentCompat extends PreferenceDialogFragmentCompat implements - DialogPreference.TargetFragment, TextWatcher { - - @BindView(R.id.et_tenant) - EditText etTenant; - - @BindView(R.id.et_base_url) - EditText etBaseUrl; - - @BindView(R.id.til_tenant) - TextInputLayout tilTenant; - - @BindView(R.id.til_base_url) - TextInputLayout tilBaseUrl; - - private PreferencesHelper preferencesHelper; - - @Override - protected View onCreateDialogView(Context context) { - return LayoutInflater.from(context).inflate(R.layout.preference_configuration, null); - } - - @Override - protected void onBindDialogView(View view) { - super.onBindDialogView(view); - ButterKnife.bind(this, view); - preferencesHelper = new PreferencesHelper(getContext()); - - ConfigurationPreference preference = (ConfigurationPreference) getPreference(); - - etBaseUrl.setText(preference.getBaseUrl()); - etTenant.setText(preference.getTenant()); - - etBaseUrl.setSelection(etBaseUrl.getText().length()); - etTenant.addTextChangedListener(this); - etBaseUrl.addTextChangedListener(this); - } - - @Override - public void onDialogClosed(boolean positiveResult) { - if (positiveResult && !isFieldEmpty() && isUrlValid()) { - ConfigurationPreference preference = (ConfigurationPreference) getPreference(); - preference.updateConfigurations(etBaseUrl.getText().toString(), etTenant.getText(). - toString()); - - preferencesHelper.clear(); - String baseUrl = preferencesHelper.getBaseUrl(); - String tenant = preferencesHelper.getTenant(); - BaseApiManager.createService(baseUrl, tenant, ""); - - Intent loginIntent = new Intent(getActivity(), LoginActivity.class); - loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); - startActivity(loginIntent); - getActivity().finish(); - } - } - - @Override - public Preference findPreference(CharSequence key) { - return getPreference(); - } - - public boolean isFieldEmpty() { - if (etBaseUrl.getText().toString().trim().length() == 0) { - return true; - } - if (etTenant.getText().toString().trim().length() == 0) { - return true; - } - return false; - } - - public boolean isUrlValid() { - try { - new URL(etBaseUrl.getText().toString()); - return true; - } catch (MalformedURLException e) { - return false; - } - } - - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (s.toString().length() == 0) { - if (etBaseUrl.getText().toString().length() == 0) { - tilBaseUrl.setErrorEnabled(true); - tilBaseUrl.setError(getString(R.string.error_validation_blank, - getString(R.string.base_url))); - } - if (etTenant.getText().toString().length() == 0) { - tilTenant.setErrorEnabled(true); - tilTenant.setError(getString(R.string.error_validation_blank, - getString(R.string.tenant))); - } - } else { - if (etBaseUrl.getText().toString().length() != 0) { - tilBaseUrl.setErrorEnabled(false); - } - if (etTenant.getText().toString().length() != 0) { - tilTenant.setErrorEnabled(false); - } - } - } - - @Override - public void afterTextChanged(Editable s) { - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ConfigurationDialogFragmentCompat.kt b/app/src/main/java/org/mifos/mobile/utils/ConfigurationDialogFragmentCompat.kt new file mode 100644 index 0000000000..a9287044b9 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/ConfigurationDialogFragmentCompat.kt @@ -0,0 +1,117 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.content.Intent +import android.text.Editable +import android.text.TextWatcher +import android.view.LayoutInflater +import android.view.View +import android.widget.EditText +import androidx.preference.DialogPreference.TargetFragment +import androidx.preference.Preference +import androidx.preference.PreferenceDialogFragmentCompat +import butterknife.BindView +import butterknife.ButterKnife +import com.google.android.material.textfield.TextInputLayout +import org.mifos.mobile.R +import org.mifos.mobile.api.BaseApiManager.Companion.createService +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.ui.activities.LoginActivity +import java.net.MalformedURLException +import java.net.URL + +/** + * Created by dilpreet on 11/03/18. + */ +class ConfigurationDialogFragmentCompat : PreferenceDialogFragmentCompat(), TargetFragment, TextWatcher { + @kotlin.jvm.JvmField + @BindView(R.id.et_tenant) + var etTenant: EditText? = null + + @kotlin.jvm.JvmField + @BindView(R.id.et_base_url) + var etBaseUrl: EditText? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_tenant) + var tilTenant: TextInputLayout? = null + + @kotlin.jvm.JvmField + @BindView(R.id.til_base_url) + var tilBaseUrl: TextInputLayout? = null + private var preferencesHelper: PreferencesHelper? = null + override fun onCreateDialogView(context: Context): View { + return LayoutInflater.from(context).inflate(R.layout.preference_configuration, null) + } + + override fun onBindDialogView(view: View) { + super.onBindDialogView(view) + ButterKnife.bind(this, view) + preferencesHelper = PreferencesHelper(context) + val preference = preference as ConfigurationPreference + etBaseUrl?.setText(preference.baseUrl) + etTenant?.setText(preference.tenant) + etBaseUrl?.text?.length?.let { etBaseUrl?.setSelection(it) } + etTenant?.addTextChangedListener(this) + etBaseUrl?.addTextChangedListener(this) + } + + override fun onDialogClosed(positiveResult: Boolean) { + if (positiveResult && !isFieldEmpty && isUrlValid) { + val preference = preference as ConfigurationPreference + preference.updateConfigurations(etBaseUrl?.text.toString(), etTenant?.text.toString()) + preferencesHelper?.clear() + val baseUrl = preferencesHelper?.baseUrl + val tenant = preferencesHelper?.tenant + createService(baseUrl, tenant, "") + val loginIntent = Intent(activity, LoginActivity::class.java) + loginIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK + startActivity(loginIntent) + activity?.finish() + } + } + + override fun findPreference(key: CharSequence): Preference { + return preference + } + + val isFieldEmpty: Boolean + get() { + if (etBaseUrl?.text.toString().trim { it <= ' ' }.isEmpty()) { + return true + } + return etTenant?.text.toString().trim { it <= ' ' }.isEmpty() + } + val isUrlValid: Boolean + get() = try { + URL(etBaseUrl?.text.toString()) + true + } catch (e: MalformedURLException) { + false + } + + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + if (s.toString().isEmpty()) { + if (etBaseUrl?.text.toString().isEmpty()) { + tilBaseUrl?.isErrorEnabled = true + tilBaseUrl?.error = getString(R.string.error_validation_blank, + getString(R.string.base_url)) + } + if (etTenant?.text.toString().isEmpty()) { + tilTenant?.isErrorEnabled = true + tilTenant?.error = getString(R.string.error_validation_blank, + getString(R.string.tenant)) + } + } else { + if (etBaseUrl?.text.toString().length != 0) { + tilBaseUrl?.isErrorEnabled = false + } + if (etTenant?.text.toString().length != 0) { + tilTenant?.isErrorEnabled = false + } + } + } + + override fun afterTextChanged(s: Editable) {} +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ConfigurationPreference.java b/app/src/main/java/org/mifos/mobile/utils/ConfigurationPreference.java deleted file mode 100644 index dd83a10ab1..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/ConfigurationPreference.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.util.AttributeSet; - -import org.mifos.mobile.api.local.PreferencesHelper; - -import androidx.preference.DialogPreference; - -/** - * Created by dilpreet on 11/03/18. - */ - -public class ConfigurationPreference extends DialogPreference { - - private PreferencesHelper preferencesHelper; - - public ConfigurationPreference(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(); - } - - public ConfigurationPreference(Context context, AttributeSet attrs) { - super(context, attrs); - init(); - } - - public ConfigurationPreference(Context context) { - super(context); - init(); - } - - private void init() { - setPersistent(false); - preferencesHelper = new PreferencesHelper(getContext()); - } - - public String getBaseUrl() { - return preferencesHelper.getBaseUrl(); - } - - public void updateConfigurations(String baseUrl, String tenant) { - preferencesHelper.updateConfiguration(baseUrl, tenant); - } - - public String getTenant() { - return preferencesHelper.getTenant(); - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/ConfigurationPreference.kt b/app/src/main/java/org/mifos/mobile/utils/ConfigurationPreference.kt new file mode 100644 index 0000000000..4e3f4081e0 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/ConfigurationPreference.kt @@ -0,0 +1,40 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.util.AttributeSet +import androidx.preference.DialogPreference +import org.mifos.mobile.api.local.PreferencesHelper + +/** + * Created by dilpreet on 11/03/18. + */ +class ConfigurationPreference : DialogPreference { + private var preferencesHelper: PreferencesHelper? = null + + constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { + init() + } + + constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) { + init() + } + + constructor(context: Context?) : super(context) { + init() + } + + private fun init() { + isPersistent = false + preferencesHelper = PreferencesHelper(context) + } + + val baseUrl: String? + get() = preferencesHelper?.baseUrl + + fun updateConfigurations(baseUrl: String?, tenant: String?) { + preferencesHelper?.updateConfiguration(baseUrl, tenant) + } + + val tenant: String? + get() = preferencesHelper?.tenant +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/Constants.java b/app/src/main/java/org/mifos/mobile/utils/Constants.java deleted file mode 100644 index 2291ee0703..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/Constants.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.mifos.mobile.utils; - -/** - * @author Vishwajeet - * @since 21/06/16. - */ - -public class Constants { - - public static final String CLIENT_NAME = "clientName"; - - public static final String CLIENT_ID = "clientId"; - - public static final String ACCOUNT_ID = "accountId"; - - public static final String LOAN_ID = "loanId"; - - public static final String SAVINGS_ID = "savingsId"; - - public static final String BASIC = "Basic "; - - public static final String BACK_SLASH = "/"; - - public static final String SAVINGS_ACCOUNTS = "savingsAccounts"; - - public static final String LOAN_ACCOUNTS = "loanAccounts"; - - public static final String SHARE_ACCOUNTS = "shareAccounts"; - - public static final String RECURRING_ACCOUNTS = "recurringdepositaccounts"; - - public static final String ACCOUNT_TYPE = "accountType"; - - public static final String REPAYMENT_SCHEDULE = "repaymentSchedule"; - - public static final String TRANSACTIONS = "transactions"; - - public static final String DFRAG_DATE_PICKER = "Date Picker"; - - public static final String TRANSFER_TYPE = "transfer_type"; - - public static final String TRANSFER_QUICK = "transfer_quick"; - - public static final String TRANSFER_PAY_TO = "transfer_pay_to"; - - public static final String TRANSFER_PAY_FROM = "transfer_pay_from"; - - public static final String ACCOUNT_POSITION = "account_position"; - - public static final String BENEFICIARY = "beneficiary"; - - public static final String BENEFICIARY_STATE = "beneficiary_state"; - - public static final String LOAN_STATE = "loanType"; - - public static final String LOAN_ACCOUNT = "loanAccount"; - - public static final String PAYLOAD = "payload"; - - public static final int REQUEST_PERMISSION_SETTING = 254; - - public static final int PERMISSIONS_REQUEST_CAMERA = 1; - - public static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 2; - - public static final int PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 3; - - public static final int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 4; - - public static final String PERMISSIONS_CAMERA_STATUS = "camera_status"; - - public static final String PERMISSIONS_STORAGE_STATUS = "storage_status"; - - public static final String PERMISSIONS_READ_PHONE_STATE_STATUS = "read_phone_status"; - - public static final String INTIAL_LOGIN = "initial_login"; - - public static final String CHARGE_TYPE = "charge_type"; - - public static final String QR_DATA = "qrcode_data"; - - public static final String TEMPLATE = "template"; - - public static final String RECENT_TRANSACTIONS = "recent_transactions"; - - public static final String CHARGES = "charges"; - - public static final String HELP = "help"; - - public static final String USER_PROFILE = "user_profile"; - - public static final String USER_DETAILS = "user_details"; - - public static final String TOTAL_LOAN = "total_loan"; - - public static final String TOTAL_SAVINGS = "total_savings"; - - public static final String TOKEN = "token"; - - public static final String REGISTER_ON_SERVER = "RegisterOnServer"; - - public static final String NOTIFY_HOME_FRAGMENT = "NotifyHomeFragment"; - - public static final String QR_IMAGE_URI = "qr_image_uri"; - - public static final int GALLERY_QR_PICK = 1; - - public static final String FRAME_RECT = "FrameRect"; - - public static final String SOURCE_URI = "SourceUri"; - - public static final String GUARANTOR_DETAILS = "guarantorDetails"; - - public static final String GUARANTOR_STATE = "guarantorState"; - - public static final String INDEX = "index"; - - public static final String DATE_PICKER_TYPE = "datePickerType"; - - public static final String HAS_SETTINGS_CHANGED = "hasSettingsChanged"; - - public static final String PASSWORD = "Password"; - - public static final String SAVINGS_ACCOUNT_STATE = "savingsaccountstate"; - - public static final String OUTSTANDING_BALANCE = "outstanding_balance"; - - public static final String LOAN_REPAYMENT = "loan_repayment"; -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/Constants.kt b/app/src/main/java/org/mifos/mobile/utils/Constants.kt new file mode 100644 index 0000000000..bfa93d8db4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/Constants.kt @@ -0,0 +1,68 @@ +package org.mifos.mobile.utils + +/** + * @author Vishwajeet + * @since 21/06/16. + */ +object Constants { + const val CLIENT_NAME = "clientName" + const val CLIENT_ID = "clientId" + const val ACCOUNT_ID = "accountId" + const val LOAN_ID = "loanId" + const val SAVINGS_ID = "savingsId" + const val BASIC = "Basic " + const val BACK_SLASH = "/" + const val SAVINGS_ACCOUNTS = "savingsAccounts" + const val LOAN_ACCOUNTS = "loanAccounts" + const val SHARE_ACCOUNTS = "shareAccounts" + const val RECURRING_ACCOUNTS = "recurringdepositaccounts" + const val ACCOUNT_TYPE = "accountType" + const val REPAYMENT_SCHEDULE = "repaymentSchedule" + const val TRANSACTIONS = "transactions" + const val DFRAG_DATE_PICKER = "Date Picker" + const val TRANSFER_TYPE = "transfer_type" + const val TRANSFER_QUICK = "transfer_quick" + const val TRANSFER_PAY_TO = "transfer_pay_to" + const val TRANSFER_PAY_FROM = "transfer_pay_from" + const val ACCOUNT_POSITION = "account_position" + const val BENEFICIARY = "beneficiary" + const val BENEFICIARY_STATE = "beneficiary_state" + const val LOAN_STATE = "loanType" + const val LOAN_ACCOUNT = "loanAccount" + const val PAYLOAD = "payload" + const val REQUEST_PERMISSION_SETTING = 254 + const val PERMISSIONS_REQUEST_CAMERA = 1 + const val PERMISSIONS_REQUEST_READ_PHONE_STATE = 2 + const val PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 3 + const val PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 4 + const val PERMISSIONS_CAMERA_STATUS = "camera_status" + const val PERMISSIONS_STORAGE_STATUS = "storage_status" + const val PERMISSIONS_READ_PHONE_STATE_STATUS = "read_phone_status" + const val INTIAL_LOGIN = "initial_login" + const val CHARGE_TYPE = "charge_type" + const val QR_DATA = "qrcode_data" + const val TEMPLATE = "template" + const val RECENT_TRANSACTIONS = "recent_transactions" + const val CHARGES = "charges" + const val HELP = "help" + const val USER_PROFILE = "user_profile" + const val USER_DETAILS = "user_details" + const val TOTAL_LOAN = "total_loan" + const val TOTAL_SAVINGS = "total_savings" + const val TOKEN = "token" + const val REGISTER_ON_SERVER = "RegisterOnServer" + const val NOTIFY_HOME_FRAGMENT = "NotifyHomeFragment" + const val QR_IMAGE_URI = "qr_image_uri" + const val GALLERY_QR_PICK = 1 + const val FRAME_RECT = "FrameRect" + const val SOURCE_URI = "SourceUri" + const val GUARANTOR_DETAILS = "guarantorDetails" + const val GUARANTOR_STATE = "guarantorState" + const val INDEX = "index" + const val DATE_PICKER_TYPE = "datePickerType" + const val HAS_SETTINGS_CHANGED = "hasSettingsChanged" + const val PASSWORD = "Password" + const val SAVINGS_ACCOUNT_STATE = "savingsaccountstate" + const val OUTSTANDING_BALANCE = "outstanding_balance" + const val LOAN_REPAYMENT = "loan_repayment" +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/CurrencyUtil.java b/app/src/main/java/org/mifos/mobile/utils/CurrencyUtil.java deleted file mode 100644 index f58ea1124f..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/CurrencyUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.telephony.TelephonyManager; - -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -/** - * Created by dilpreet on 21/8/17. - */ - -public class CurrencyUtil { - - private static Locale defaultLocale = Locale.US; - - - public static String formatCurrency(Context context, String amt) { - return getDecimalFormatter(context).format(amt); - } - - public static String formatCurrency(Context context, long amt) { - return getDecimalFormatter(context).format(amt); - } - - public static String formatCurrency(Context context, double amt) { - return getDecimalFormatter(context).format(amt); - } - - - private static DecimalFormat getDecimalFormatter(Context context) { - DecimalFormat currencyFormatter; - Locale locale; - TelephonyManager tm = (TelephonyManager) context. - getSystemService(Context.TELEPHONY_SERVICE); - try { - locale = new Locale("en", tm.getNetworkCountryIso().toUpperCase()); - } catch (Exception e) { - locale = defaultLocale; - } - - try { - currencyFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale); - } catch (Exception e) { - currencyFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(defaultLocale); - } - DecimalFormatSymbols decimalFormatSymbols = currencyFormatter.getDecimalFormatSymbols(); - decimalFormatSymbols.setCurrencySymbol(""); - currencyFormatter.setDecimalFormatSymbols(decimalFormatSymbols); - return currencyFormatter; - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/CurrencyUtil.kt b/app/src/main/java/org/mifos/mobile/utils/CurrencyUtil.kt new file mode 100644 index 0000000000..d92e994c9d --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/CurrencyUtil.kt @@ -0,0 +1,47 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.telephony.TelephonyManager + +import java.text.DecimalFormat +import java.util.* + +/** + * Created by dilpreet on 21/8/17. + */ +object CurrencyUtil { + + private val defaultLocale = Locale.US + fun formatCurrency(context: Context, amt: String?): String { + return getDecimalFormatter(context).format(amt) + } + + fun formatCurrency(context: Context, amt: Long): String { + return getDecimalFormatter(context).format(amt) + } + + @kotlin.jvm.JvmStatic + fun formatCurrency(context: Context?, amt: Double?): String { + return getDecimalFormatter(context).format(amt) + } + + private fun getDecimalFormatter(context: Context?): DecimalFormat { + val currencyFormatter: DecimalFormat + val locale: Locale? + val tm = context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + locale = try { + Locale("en", tm.networkCountryIso.toUpperCase(Locale.ROOT)) + } catch (e: Exception) { + defaultLocale + } + currencyFormatter = try { + DecimalFormat.getCurrencyInstance(locale) as DecimalFormat + } catch (e: Exception) { + DecimalFormat.getCurrencyInstance(defaultLocale) as DecimalFormat + } + val decimalFormatSymbols = currencyFormatter.decimalFormatSymbols + decimalFormatSymbols.currencySymbol = "" + currencyFormatter.decimalFormatSymbols = decimalFormatSymbols + return currencyFormatter + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/DateHelper.java b/app/src/main/java/org/mifos/mobile/utils/DateHelper.java deleted file mode 100755 index 5014284e7b..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/DateHelper.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * This project is licensed under the open source MPL V2. - * See https://github.com/openMF/android-client/blob/master/LICENSE.md - */ - -package org.mifos.mobile.utils; - -import android.util.Log; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -/** - * Created by ishankhanna on 30/05/14. - *

This is a helper class that will be used to convert List Type Dates - * from MifosX into Simple Strings or Date Formats

- */ -public class DateHelper { - - public static final String LOG_TAG = DateHelper.class.getSimpleName(); - - public static final String FORMAT_dd_MMMM_yyyy = "dd MMMM yyyy"; - - public static List getCurrentDate(String dateFormat, String separator) { - List date = new ArrayList<>(); - - String s = new SimpleDateFormat(dateFormat, Locale.getDefault()).format(new Date()); - for (String str : s.split(separator)) { - date.add(Integer.parseInt(str)); - } - - return date; - } - - /** - * the result string uses the list given in a reverse order ([x, y, z] results in "z y x") - * - * @param integersOfDate [year-month-day] (ex [2016, 4, 14]) - * @return date in the format day month year (ex 14 Apr 2016) - */ - public static String getDateAsString(List integersOfDate) { - - StringBuilder stringBuilder = new StringBuilder(); - if (integersOfDate != null) { - stringBuilder.append(integersOfDate.get(2)) - .append(' ') - .append(getMonthName(integersOfDate.get(1))) - .append(' ') - .append(integersOfDate.get(0)); - } - return stringBuilder.toString(); - } - - public static String getDateAsString(List integersOfDate, String pattern) { - return DateHelper.getFormatConverter("dd MMM yyyy", - pattern, DateHelper.getDateAsString(integersOfDate)); - - } - - /** - * This Method converting the dd-MM-yyyy format type date string into dd MMMM yyyy - * - * @param format Final Format of date string - * @param dateString date string - * @return dd MMMM yyyy format date string. - */ - public static String getSpecificFormat(String format, String dateString) { - SimpleDateFormat pickerFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); - SimpleDateFormat finalFormat = new SimpleDateFormat(format, Locale.ENGLISH); - Date date = null; - try { - date = pickerFormat.parse(dateString); - } catch (ParseException e) { - Log.d(LOG_TAG, e.getLocalizedMessage()); - } - return finalFormat.format(date); - } - - public static String getFormatConverter(String currentFormat, String requiredFormat, - String dateString) { - SimpleDateFormat pickerFormat = new SimpleDateFormat(currentFormat, Locale.ENGLISH); - SimpleDateFormat finalFormat = new SimpleDateFormat(requiredFormat, Locale.ENGLISH); - Date date = null; - try { - date = pickerFormat.parse(dateString); - } catch (ParseException e) { - Log.d(LOG_TAG, e.getLocalizedMessage()); - } - return finalFormat.format(date); - } - - /** - * @param month an integer from 1 to 12 - * @return string representation of the month like Jan or Feb..etc - */ - public static String getMonthName(int month) { - String monthName = ""; - switch (month) { - case 1: - monthName = "Jan"; - break; - case 2: - monthName = "Feb"; - break; - case 3: - monthName = "Mar"; - break; - case 4: - monthName = "Apr"; - break; - case 5: - monthName = "May"; - break; - case 6: - monthName = "Jun"; - break; - case 7: - monthName = "Jul"; - break; - case 8: - monthName = "Aug"; - break; - case 9: - monthName = "Sep"; - break; - case 10: - monthName = "Oct"; - break; - case 11: - monthName = "Nov"; - break; - case 12: - monthName = "Dec"; - break; - } - return monthName; - } - - public static long getDateAsLongFromString(String dateStr, String pattern) { - SimpleDateFormat sdf = new SimpleDateFormat(pattern); - Date date = null; - - try { - date = sdf.parse(dateStr); - } catch (ParseException e) { - Log.d("TAG", e.getMessage()); - } - return date.getTime(); - } - - - public static long getDateAsLongFromList(List integersOfDate) { - String dateStr = getDateAsString(integersOfDate); - return getDateAsLongFromString(dateStr, "dd MMM yyyy"); - } - - public static long subtractWeeks(int number) { - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.WEEK_OF_YEAR, -number); - return calendar.getTimeInMillis(); - } - - - public static long subtractMonths(int number) { - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.MONTH, -number); - return calendar.getTimeInMillis(); - } - - public static String getDateAsStringFromLong(long timeInMillis) { - SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy"); - return sdf.format(new Date(timeInMillis)); - } - - public static String getDateAndTimeAsStringFromLong(long timeInMillis) { - SimpleDateFormat sdf = new SimpleDateFormat("HH:mm a dd MMM yyyy"); - return sdf.format(new Date(timeInMillis)); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/utils/DateHelper.kt b/app/src/main/java/org/mifos/mobile/utils/DateHelper.kt new file mode 100755 index 0000000000..23858f8480 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/DateHelper.kt @@ -0,0 +1,151 @@ +/* + * This project is licensed under the open source MPL V2. + * See https://github.com/openMF/android-client/blob/master/LICENSE.md + */ +package org.mifos.mobile.utils + +import android.util.Log + +import java.text.ParseException +import java.text.SimpleDateFormat +import java.util.* + +/** + * Created by ishankhanna on 30/05/14. + * + * This is a helper class that will be used to convert List Type Dates + * from MifosX into Simple Strings or Date Formats + */ +object DateHelper { + + val LOG_TAG: String? = DateHelper::class.java.simpleName + const val FORMAT_dd_MMMM_yyyy = "dd MMMM yyyy" + fun getCurrentDate(dateFormat: String?, separator: String): List { + val date: MutableList = ArrayList() + val s = SimpleDateFormat(dateFormat, Locale.getDefault()).format(Date()) + for (str in s.split(separator.toRegex()).toTypedArray()) { + date.add(str.toInt()) + } + return date + } + + /** + * the result string uses the list given in a reverse order ([x, y, z] results in "z y x") + * + * @param integersOfDate [year-month-day] (ex [2016, 4, 14]) + * @return date in the format day month year (ex 14 Apr 2016) + */ + fun getDateAsString(integersOfDate: List?): String { + val stringBuilder = StringBuilder() + if (integersOfDate != null) { + stringBuilder.append(integersOfDate[2]) + .append(' ') + .append(getMonthName(integersOfDate[1])) + .append(' ') + .append(integersOfDate[0]) + } + return stringBuilder.toString() + } + + fun getDateAsString(integersOfDate: List?, pattern: String?): String { + return getFormatConverter("dd MMM yyyy", + pattern, getDateAsString(integersOfDate)) + } + + /** + * This Method converting the dd-MM-yyyy format type date string into dd MMMM yyyy + * + * @param format Final Format of date string + * @param dateString date string + * @return dd MMMM yyyy format date string. + */ + fun getSpecificFormat(format: String?, dateString: String?): String { + val pickerFormat = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH) + val finalFormat = SimpleDateFormat(format, Locale.ENGLISH) + var date: Date? = null + try { + date = pickerFormat.parse(dateString) + } catch (e: ParseException) { + Log.d(LOG_TAG, e.localizedMessage) + } + return finalFormat.format(date) + } + + fun getFormatConverter( + currentFormat: String?, requiredFormat: String?, + dateString: String? + ): String { + val pickerFormat = SimpleDateFormat(currentFormat, Locale.ENGLISH) + val finalFormat = SimpleDateFormat(requiredFormat, Locale.ENGLISH) + var date: Date? = null + try { + date = pickerFormat.parse(dateString) + } catch (e: ParseException) { + Log.d(LOG_TAG, e.localizedMessage) + } + return finalFormat.format(date) + } + + /** + * @param month an integer from 1 to 12 + * @return string representation of the month like Jan or Feb..etc + */ + private fun getMonthName(month: Int?): String? { + var monthName = "" + when (month) { + 1 -> monthName = "Jan" + 2 -> monthName = "Feb" + 3 -> monthName = "Mar" + 4 -> monthName = "Apr" + 5 -> monthName = "May" + 6 -> monthName = "Jun" + 7 -> monthName = "Jul" + 8 -> monthName = "Aug" + 9 -> monthName = "Sep" + 10 -> monthName = "Oct" + 11 -> monthName = "Nov" + 12 -> monthName = "Dec" + } + return monthName + } + + fun getDateAsLongFromString(dateStr: String?, pattern: String?): Long? { + val sdf = SimpleDateFormat(pattern) + var date: Date? = null + try { + date = sdf.parse(dateStr) + } catch (e: ParseException) { + Log.d("TAG", e.message) + } + return date?.time + } + + @kotlin.jvm.JvmStatic + fun getDateAsLongFromList(integersOfDate: List?): Long? { + val dateStr = getDateAsString(integersOfDate) + return getDateAsLongFromString(dateStr, "dd MMM yyyy") + } + + fun subtractWeeks(number: Int): Long { + val calendar = Calendar.getInstance() + calendar.add(Calendar.WEEK_OF_YEAR, -number) + return calendar.timeInMillis + } + + fun subtractMonths(number: Int): Long { + val calendar = Calendar.getInstance() + calendar.add(Calendar.MONTH, -number) + return calendar.timeInMillis + } + + fun getDateAsStringFromLong(timeInMillis: Long?): String { + val sdf = SimpleDateFormat("dd MMM yyyy") + return sdf.format(timeInMillis?.let { Date(it) }) + } + + @kotlin.jvm.JvmStatic + fun getDateAndTimeAsStringFromLong(timeInMillis: Long?): String { + val sdf = SimpleDateFormat("HH:mm a dd MMM yyyy") + return sdf.format(timeInMillis?.let { Date(it) }) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/DatePick.java b/app/src/main/java/org/mifos/mobile/utils/DatePick.java deleted file mode 100644 index edb7eeacfb..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/DatePick.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.mifos.mobile.utils; - -/** - * Created by dilpreet on 6/3/17. - */ - -public enum DatePick { - START , - END -} diff --git a/app/src/main/java/org/mifos/mobile/utils/DatePick.kt b/app/src/main/java/org/mifos/mobile/utils/DatePick.kt new file mode 100644 index 0000000000..832d89cc44 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/DatePick.kt @@ -0,0 +1,8 @@ +package org.mifos.mobile.utils + +/** + * Created by dilpreet on 6/3/17. + */ +enum class DatePick { + START, END +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/DividerItemDecoration.java b/app/src/main/java/org/mifos/mobile/utils/DividerItemDecoration.java deleted file mode 100644 index 5ed401d426..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/DividerItemDecoration.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.view.View; - -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - -/** - * @author Vishwajeet - * @since 10/08/16 - */ -public class DividerItemDecoration extends RecyclerView.ItemDecoration { - - public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; - public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; - private static final int[] ATTRS = new int[]{android.R.attr.listDivider}; - private Drawable mDivider; - - private int mOrientation; - - public DividerItemDecoration(Context context, int orientation) { - final TypedArray a = context.obtainStyledAttributes(ATTRS); - mDivider = a.getDrawable(0); - a.recycle(); - setOrientation(orientation); - } - - public void setOrientation(int orientation) { - if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { - throw new IllegalArgumentException("invalid orientation"); - } - mOrientation = orientation; - } - - @Override - public void onDraw(Canvas c, RecyclerView parent) { - if (mOrientation == VERTICAL_LIST) { - drawVertical(c, parent); - } else { - drawHorizontal(c, parent); - } - } - - public void drawVertical(Canvas c, RecyclerView parent) { - final int left = parent.getPaddingLeft(); - final int right = parent.getWidth() - parent.getPaddingRight(); - - final int childCount = parent.getChildCount(); - for (int i = 0; i < childCount; i++) { - final View child = parent.getChildAt(i); - final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child - .getLayoutParams(); - final int top = child.getBottom() + params.bottomMargin; - final int bottom = top + mDivider.getIntrinsicHeight(); - mDivider.setBounds(left, top, right, bottom); - mDivider.draw(c); - } - } - - public void drawHorizontal(Canvas c, RecyclerView parent) { - final int top = parent.getPaddingTop(); - final int bottom = parent.getHeight() - parent.getPaddingBottom(); - - final int childCount = parent.getChildCount(); - for (int i = 0; i < childCount; i++) { - final View child = parent.getChildAt(i); - final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child - .getLayoutParams(); - final int left = child.getRight() + params.rightMargin; - final int right = left + mDivider.getIntrinsicHeight(); - mDivider.setBounds(left, top, right, bottom); - mDivider.draw(c); - } - } - - @Override - public void getItemOffsets(Rect outRect, View view, RecyclerView parent, - RecyclerView.State state) { - if (mOrientation == VERTICAL_LIST) { - outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); - } else { - outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/DividerItemDecoration.kt b/app/src/main/java/org/mifos/mobile/utils/DividerItemDecoration.kt new file mode 100644 index 0000000000..9c860f3025 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/DividerItemDecoration.kt @@ -0,0 +1,88 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Rect +import android.graphics.drawable.Drawable +import android.view.View + +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.RecyclerView.ItemDecoration + +/** + * @author Vishwajeet + * @since 10/08/16 + */ +class DividerItemDecoration(context: Context?, orientation: Int) : ItemDecoration() { + private var mDivider: Drawable? = null + private var mOrientation = 0 + private fun setOrientation(orientation: Int) { + require(!(orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST)) { "invalid orientation" } + mOrientation = orientation + } + + override fun onDraw(c: Canvas, parent: RecyclerView) { + if (mOrientation == VERTICAL_LIST) { + drawVertical(c, parent) + } else { + drawHorizontal(c, parent) + } + } + + private fun drawVertical(c: Canvas, parent: RecyclerView) { + val left = parent.paddingLeft + val right = parent.width - parent.paddingRight + val childCount = parent.childCount + for (i in 0 until childCount) { + val child = parent.getChildAt(i) + val params = child + .layoutParams as RecyclerView.LayoutParams + val top = child.bottom + params.bottomMargin + val bottom = top + if (mDivider != null) mDivider!!.intrinsicHeight else 0 + mDivider?.setBounds(left, top, right, bottom) + mDivider?.draw(c) + } + } + + private fun drawHorizontal(c: Canvas, parent: RecyclerView) { + val top = parent.paddingTop + val bottom = parent.height - parent.paddingBottom + val childCount = parent.childCount + for (i in 0 until childCount) { + val child = parent.getChildAt(i) + val params = child + .layoutParams as RecyclerView.LayoutParams + val left = child.right + params.rightMargin + val right = left + if (mDivider != null) mDivider!!.intrinsicHeight else 0 + mDivider?.setBounds(left, top, right, bottom) + mDivider?.draw(c) + } + } + + override fun getItemOffsets( + outRect: Rect, view: View, parent: RecyclerView, + state: RecyclerView.State + ) { + if (mOrientation == VERTICAL_LIST) { + outRect[0, 0, 0] = if (mDivider != null) mDivider!!.intrinsicHeight else 0 + } else { + outRect[0, 0, if (mDivider != null) mDivider!!.intrinsicWidth else 0] = 0 + } + } + + companion object { + const val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL + const val VERTICAL_LIST = LinearLayoutManager.VERTICAL + private val ATTRS = intArrayOf(android.R.attr.listDivider) + } + + init { + val a = context?.obtainStyledAttributes(ATTRS) + if (a != null) { + mDivider = a.getDrawable(0) + } + a?.recycle() + setOrientation(orientation) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/EndlessRecyclerViewScrollListener.java b/app/src/main/java/org/mifos/mobile/utils/EndlessRecyclerViewScrollListener.java deleted file mode 100644 index da17a49ac0..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/EndlessRecyclerViewScrollListener.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.mifos.mobile.utils; - -import androidx.recyclerview.widget.GridLayoutManager; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.recyclerview.widget.StaggeredGridLayoutManager; - -public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener { - // The minimum amount of items to have below your current scroll position - // before loading more. - private int visibleThreshold = 5; - // The current offset index of data you have loaded - private int currentPage = 0; - // The total number of items in the dataset after the last load - private int previousTotalItemCount = 0; - // True if we are still waiting for the last set of data to load. - private boolean loading = true; - // Sets the starting page index - private int startingPageIndex = 0; - - RecyclerView.LayoutManager mLayoutManager; - - public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) { - this.mLayoutManager = layoutManager; - } - - public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager) { - this.mLayoutManager = layoutManager; - visibleThreshold = visibleThreshold * layoutManager.getSpanCount(); - } - - public EndlessRecyclerViewScrollListener(StaggeredGridLayoutManager layoutManager) { - this.mLayoutManager = layoutManager; - visibleThreshold = visibleThreshold * layoutManager.getSpanCount(); - } - - public int getLastVisibleItem(int[] lastVisibleItemPositions) { - int maxSize = 0; - for (int i = 0; i < lastVisibleItemPositions.length; i++) { - if (i == 0) { - maxSize = lastVisibleItemPositions[i]; - } else if (lastVisibleItemPositions[i] > maxSize) { - maxSize = lastVisibleItemPositions[i]; - } - } - return maxSize; - } - - // This happens many times a second during a scroll, so be wary of the code you place here. - // We are given a few useful parameters to help us work out if we need to load some more data, - // but first we check if we are waiting for the previous load to finish. - @Override - public void onScrolled(RecyclerView view, int dx, int dy) { - int lastVisibleItemPosition = 0; - int totalItemCount = mLayoutManager.getItemCount(); - - if (mLayoutManager instanceof StaggeredGridLayoutManager) { - int[] lastVisibleItemPositions = - ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions( - null); - // get maximum element within the list - lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions); - } else if (mLayoutManager instanceof GridLayoutManager) { - lastVisibleItemPosition = - ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition(); - } else if (mLayoutManager instanceof LinearLayoutManager) { - lastVisibleItemPosition = - ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition(); - } - - // If the total item count is zero and the previous isn't, assume the - // list is invalidated and should be reset back to initial state - if (totalItemCount < previousTotalItemCount) { - this.currentPage = this.startingPageIndex; - this.previousTotalItemCount = totalItemCount; - if (totalItemCount == 0) { - this.loading = true; - } - } - // If it’s still loading, we check to see if the dataset count has - // changed, if so we conclude it has finished loading and update the current page - // number and total item count. - if (loading && (totalItemCount > previousTotalItemCount)) { - loading = false; - previousTotalItemCount = totalItemCount; - } - - // If it isn’t currently loading, we check to see if we have breached - // the visibleThreshold and need to reload more data. - // If we do need to reload some more data, we execute onLoadMore to fetch the data. - // threshold should reflect how many total columns there are too - if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) { - currentPage++; - onLoadMore(currentPage, totalItemCount, view); - loading = true; - } - } - - // Call this method whenever performing new searches - public void resetState() { - this.currentPage = this.startingPageIndex; - this.previousTotalItemCount = 0; - this.loading = true; - } - - // Defines the process for actually loading more data based on page - public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view); - -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/EndlessRecyclerViewScrollListener.kt b/app/src/main/java/org/mifos/mobile/utils/EndlessRecyclerViewScrollListener.kt new file mode 100644 index 0000000000..ae379bee30 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/EndlessRecyclerViewScrollListener.kt @@ -0,0 +1,106 @@ +package org.mifos.mobile.utils + +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.StaggeredGridLayoutManager + +abstract class EndlessRecyclerViewScrollListener : RecyclerView.OnScrollListener { + // The minimum amount of items to have below your current scroll position + // before loading more. + private var visibleThreshold = 5 + + // The current offset index of data you have loaded + private var currentPage = 0 + + // The total number of items in the dataset after the last load + private var previousTotalItemCount = 0 + + // True if we are still waiting for the last set of data to load. + private var loading = true + + // Sets the starting page index + private val startingPageIndex = 0 + var mLayoutManager: RecyclerView.LayoutManager + + constructor(layoutManager: LinearLayoutManager) { + mLayoutManager = layoutManager + } + + constructor(layoutManager: GridLayoutManager) { + mLayoutManager = layoutManager + visibleThreshold = visibleThreshold * layoutManager.spanCount + } + + constructor(layoutManager: StaggeredGridLayoutManager) { + mLayoutManager = layoutManager + visibleThreshold = visibleThreshold * layoutManager.spanCount + } + + fun getLastVisibleItem(lastVisibleItemPositions: IntArray): Int { + var maxSize = 0 + for (i in lastVisibleItemPositions.indices) { + if (i == 0) { + maxSize = lastVisibleItemPositions[i] + } else if (lastVisibleItemPositions[i] > maxSize) { + maxSize = lastVisibleItemPositions[i] + } + } + return maxSize + } + + // This happens many times a second during a scroll, so be wary of the code you place here. + // We are given a few useful parameters to help us work out if we need to load some more data, + // but first we check if we are waiting for the previous load to finish. + override fun onScrolled(view: RecyclerView, dx: Int, dy: Int) { + var lastVisibleItemPosition = 0 + val totalItemCount = mLayoutManager.itemCount + if (mLayoutManager is StaggeredGridLayoutManager) { + val lastVisibleItemPositions = (mLayoutManager as StaggeredGridLayoutManager).findLastVisibleItemPositions( + null) + // get maximum element within the list + lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions) + } else if (mLayoutManager is GridLayoutManager) { + lastVisibleItemPosition = (mLayoutManager as GridLayoutManager).findLastVisibleItemPosition() + } else if (mLayoutManager is LinearLayoutManager) { + lastVisibleItemPosition = (mLayoutManager as LinearLayoutManager).findLastVisibleItemPosition() + } + + // If the total item count is zero and the previous isn't, assume the + // list is invalidated and should be reset back to initial state + if (totalItemCount < previousTotalItemCount) { + currentPage = startingPageIndex + previousTotalItemCount = totalItemCount + if (totalItemCount == 0) { + loading = true + } + } + // If it’s still loading, we check to see if the dataset count has + // changed, if so we conclude it has finished loading and update the current page + // number and total item count. + if (loading && totalItemCount > previousTotalItemCount) { + loading = false + previousTotalItemCount = totalItemCount + } + + // If it isn’t currently loading, we check to see if we have breached + // the visibleThreshold and need to reload more data. + // If we do need to reload some more data, we execute onLoadMore to fetch the data. + // threshold should reflect how many total columns there are too + if (!loading && lastVisibleItemPosition + visibleThreshold > totalItemCount) { + currentPage++ + onLoadMore(currentPage, totalItemCount, view) + loading = true + } + } + + // Call this method whenever performing new searches + fun resetState() { + currentPage = startingPageIndex + previousTotalItemCount = 0 + loading = true + } + + // Defines the process for actually loading more data based on page + abstract fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/FaqDiffUtil.java b/app/src/main/java/org/mifos/mobile/utils/FaqDiffUtil.java deleted file mode 100644 index 093aa394de..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/FaqDiffUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.mifos.mobile.utils; - -import org.mifos.mobile.models.FAQ; - -import java.util.List; - -import androidx.recyclerview.widget.DiffUtil; - -/** - * Created by dilpreet on 12/8/17. - */ - -public class FaqDiffUtil extends DiffUtil.Callback { - - private List oldFaq; - private List newFaq; - - public FaqDiffUtil(List oldFaq, List newFaq) { - this.oldFaq = oldFaq; - this.newFaq = newFaq; - } - - @Override - public int getOldListSize() { - return oldFaq.size(); - } - - @Override - public int getNewListSize() { - return newFaq.size(); - } - - @Override - public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { - return oldFaq.get(oldItemPosition).getQuestion(). - compareTo(newFaq.get(newItemPosition).getAnswer()) == 0; - } - - @Override - public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { - return oldFaq.get(oldItemPosition).equals(newFaq.get(newItemPosition)); - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/FaqDiffUtil.kt b/app/src/main/java/org/mifos/mobile/utils/FaqDiffUtil.kt new file mode 100644 index 0000000000..245edb4af6 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/FaqDiffUtil.kt @@ -0,0 +1,27 @@ +package org.mifos.mobile.utils + +import androidx.recyclerview.widget.DiffUtil +import org.mifos.mobile.models.FAQ + +/** + * Created by dilpreet on 12/8/17. + */ +class FaqDiffUtil(private val oldFaq: ArrayList?, private val newFaq: ArrayList?) : DiffUtil.Callback() { + override fun getOldListSize(): Int { + return if (oldFaq?.size != null) oldFaq.size + else 0 + } + + override fun getNewListSize(): Int { + return if (newFaq?.size != null) newFaq.size + else 0 + } + + override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { + return newFaq?.get(newItemPosition)?.answer?.let { oldFaq?.get(oldItemPosition)?.question?.compareTo(it) } == 0 + } + + override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { + return oldFaq?.get(oldItemPosition) == newFaq?.get(newItemPosition) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ImageUtil.java b/app/src/main/java/org/mifos/mobile/utils/ImageUtil.java deleted file mode 100644 index a1711b58ba..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/ImageUtil.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.mifos.mobile.utils; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.util.Log; - -/** - * Created by dilpreet on 10/8/17. - */ - -public class ImageUtil { - /** - * Reference : https://developer.android.com/topic/performance/graphics/load-bitmap.html - * And for scaling : - * https://stackoverflow.com/questions/8722359/scale-rotate-bitmap-using-matrix-in-android/8722592#8722592 - */ - - private static ImageUtil instance; - - public static ImageUtil getInstance() { - if (instance == null) { - instance = new ImageUtil(); - } - return instance; - } - - //Default width and height - public Bitmap compressImage(byte[] decodedBytes) { - return compress(decodedBytes, 816.0f, 612.0f); - } - - public Bitmap compressImage(byte[] decodedBytes, float maxHeight, float maxWidth) { - return compress(decodedBytes, maxHeight, maxWidth); - } - - private Bitmap compress(byte[] decodedBytes, float maxHeight, float maxWidth) { - Bitmap scaledBitmap = null; - BitmapFactory.Options options = new BitmapFactory.Options(); - -// by setting this field as true, the actual bitmap pixels are not loaded in the memory. -// Just the bounds are loaded. If -// you try the use the bitmap here, you will get null. - options.inJustDecodeBounds = true; - Bitmap bmp = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length, options); - - int actualHeight = options.outHeight; - int actualWidth = options.outWidth; - - float imgRatio = actualWidth / actualHeight; - float maxRatio = maxWidth / maxHeight; - -// width and height values are set maintaining the aspect ratio of the image - - if (actualHeight > maxHeight || actualWidth > maxWidth) { - if (imgRatio < maxRatio) { - imgRatio = maxHeight / actualHeight; - actualWidth = (int) (imgRatio * actualWidth); - actualHeight = (int) maxHeight; - } else if (imgRatio > maxRatio) { - imgRatio = maxWidth / actualWidth; - actualHeight = (int) (imgRatio * actualHeight); - actualWidth = (int) maxWidth; - } else { - actualHeight = (int) maxHeight; - actualWidth = (int) maxWidth; - - } - } - -// setting inSampleSize value allows to load a scaled down version of the original image - - options.inSampleSize = - calculateInSampleSize(options, actualWidth, actualHeight); - -// inJustDecodeBounds set to false to load the actual bitmap - options.inJustDecodeBounds = false; - -// this options allow android to claim the bitmap memory if it runs low on memory - options.inPurgeable = true; - options.inInputShareable = true; - options.inTempStorage = new byte[16 * 1024]; - - try { - bmp = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length, options); - } catch (OutOfMemoryError exception) { - Log.e(ImageUtil.class.getName(), exception.toString()); - } - - try { - scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888); - } catch (OutOfMemoryError exception) { - Log.e(ImageUtil.class.getName(), exception.toString()); - } - - float ratioX = actualWidth / (float) options.outWidth; - float ratioY = actualHeight / (float) options.outHeight; - float middleX = actualWidth / 2.0f; - float middleY = actualHeight / 2.0f; - - Matrix scaleMatrix = new Matrix(); - scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); - - Canvas canvas = new Canvas(scaledBitmap); - canvas.setMatrix(scaleMatrix); - canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, - new Paint(Paint.FILTER_BITMAP_FLAG)); - - - scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, - scaledBitmap.getWidth(), scaledBitmap.getHeight(), null, - true); - - return scaledBitmap; - } - - private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { - int height = options.outHeight; - int width = options.outWidth; - int inSampleSize = 1; - - if (height > reqHeight || width > reqWidth) { - int heightRatio = Math.round((float) height / (float) reqHeight); - int widthRatio = Math.round((float) width / (float) reqWidth); - inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; - } - float totalPixels = width * height; - float totalReqPixelsCap = reqWidth * reqHeight * 2; - while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { - inSampleSize++; - } - - return inSampleSize; - } - -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ImageUtil.kt b/app/src/main/java/org/mifos/mobile/utils/ImageUtil.kt new file mode 100644 index 0000000000..4ab361e702 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/ImageUtil.kt @@ -0,0 +1,119 @@ +package org.mifos.mobile.utils + +import android.graphics.* +import android.util.Log + +/** + * Created by dilpreet on 10/8/17. + */ +class ImageUtil { + //Default width and height + fun compressImage(decodedBytes: ByteArray): Bitmap? { + return compress(decodedBytes, 816.0f, 612.0f) + } + + fun compressImage(decodedBytes: ByteArray, maxHeight: Float, maxWidth: Float): Bitmap? { + return compress(decodedBytes, maxHeight, maxWidth) + } + + private fun compress(decodedBytes: ByteArray, maxHeight: Float, maxWidth: Float): Bitmap? { + var scaledBitmap: Bitmap? = null + val options = BitmapFactory.Options() + +// by setting this field as true, the actual bitmap pixels are not loaded in the memory. +// Just the bounds are loaded. If +// you try the use the bitmap here, you will get null. + options.inJustDecodeBounds = true + var bmp = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size, options) + var actualHeight = options.outHeight + var actualWidth = options.outWidth + var imgRatio = actualWidth / actualHeight.toFloat() + val maxRatio = maxWidth / maxHeight + +// width and height values are set maintaining the aspect ratio of the image + if (actualHeight > maxHeight || actualWidth > maxWidth) { + if (imgRatio < maxRatio) { + imgRatio = maxHeight / actualHeight + actualWidth = (imgRatio * actualWidth).toInt() + actualHeight = maxHeight.toInt() + } else if (imgRatio > maxRatio) { + imgRatio = maxWidth / actualWidth + actualHeight = (imgRatio * actualHeight).toInt() + actualWidth = maxWidth.toInt() + } else { + actualHeight = maxHeight.toInt() + actualWidth = maxWidth.toInt() + } + } + +// setting inSampleSize value allows to load a scaled down version of the original image + options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight) + +// inJustDecodeBounds set to false to load the actual bitmap + options.inJustDecodeBounds = false + +// this options allow android to claim the bitmap memory if it runs low on memory + options.inPurgeable = true + options.inInputShareable = true + options.inTempStorage = ByteArray(16 * 1024) + try { + bmp = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size, options) + } catch (exception: OutOfMemoryError) { + Log.e(ImageUtil::class.java.name, exception.toString()) + } + try { + scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888) + } catch (exception: OutOfMemoryError) { + Log.e(ImageUtil::class.java.name, exception.toString()) + } + val ratioX = actualWidth / options.outWidth.toFloat() + val ratioY = actualHeight / options.outHeight.toFloat() + val middleX = actualWidth / 2.0f + val middleY = actualHeight / 2.0f + val scaleMatrix = Matrix() + scaleMatrix.setScale(ratioX, ratioY, middleX, middleY) + val canvas: Canvas? = Canvas(scaledBitmap) + canvas?.matrix = scaleMatrix + canvas?.drawBitmap(bmp, middleX - bmp.width / 2, middleY - bmp.height / 2, + Paint(Paint.FILTER_BITMAP_FLAG)) + if (scaledBitmap != null) + scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, + scaledBitmap.width, scaledBitmap.height, null, + true) + return scaledBitmap + } + + private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int { + val height = options.outHeight + val width = options.outWidth + var inSampleSize = 1 + if (height > reqHeight || width > reqWidth) { + val heightRatio = Math.round(height.toFloat() / reqHeight.toFloat()) + val widthRatio = Math.round(width.toFloat() / reqWidth.toFloat()) + inSampleSize = if (heightRatio < widthRatio) heightRatio else widthRatio + } + val totalPixels = width * height.toFloat() + val totalReqPixelsCap = reqWidth * reqHeight * 2.toFloat() + while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { + inSampleSize++ + } + return inSampleSize + } + + companion object { + /** + * Reference : https://developer.android.com/topic/performance/graphics/load-bitmap.html + * And for scaling : + * https://stackoverflow.com/questions/8722359/scale-rotate-bitmap-using-matrix-in-android/8722592#8722592 + */ + @kotlin.jvm.JvmStatic + var instance: ImageUtil? = null + get() { + if (field == null) { + field = ImageUtil() + } + return field + } + private set + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/LanguageHelper.java b/app/src/main/java/org/mifos/mobile/utils/LanguageHelper.java deleted file mode 100644 index 4796a1d282..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/LanguageHelper.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.mifos.mobile.utils; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.SharedPreferences; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.os.Build; - -import org.mifos.mobile.R; - -import java.util.Locale; - -import androidx.preference.PreferenceManager; - -/** - * Created by dilpreet on 02/10/17. - */ - -public class LanguageHelper { - //https://gunhansancar.com/change-language-programmatically-in-android/ - - public static Context onAttach(Context context) { - String lang = getPersistedData(context, Locale.getDefault().getLanguage()); - return setLocale(context, lang); - } - - public static Context onAttach(Context context, String defaultLanguage) { - String lang = getPersistedData(context, defaultLanguage); - return setLocale(context, lang); - } - - public static Context setLocale(Context context, String language) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - return updateResources(context, language); - } - - return updateResourcesLegacy(context, language); - } - - private static String getPersistedData(Context context, String defaultLanguage) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - return preferences.getString(context.getString(R.string.language_type), defaultLanguage); - } - - @TargetApi(Build.VERSION_CODES.N) - private static Context updateResources(Context context, String language) { - Locale locale = new Locale(language); - Locale.setDefault(locale); - - Configuration configuration = context.getResources().getConfiguration(); - configuration.setLocale(locale); - configuration.setLayoutDirection(locale); - - return context.createConfigurationContext(configuration); - } - - @SuppressWarnings("deprecation") - private static Context updateResourcesLegacy(Context context, String language) { - Locale locale = new Locale(language); - Locale.setDefault(locale); - - Resources resources = context.getResources(); - - Configuration configuration = resources.getConfiguration(); - configuration.locale = locale; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - configuration.setLayoutDirection(locale); - } - - resources.updateConfiguration(configuration, resources.getDisplayMetrics()); - - return context; - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/LanguageHelper.kt b/app/src/main/java/org/mifos/mobile/utils/LanguageHelper.kt new file mode 100644 index 0000000000..b85e606b72 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/LanguageHelper.kt @@ -0,0 +1,62 @@ +package org.mifos.mobile.utils + +import android.annotation.TargetApi +import android.content.Context +import android.os.Build + +import androidx.preference.PreferenceManager + +import org.mifos.mobile.R + +import java.util.* + +/** + * Created by dilpreet on 02/10/17. + */ +object LanguageHelper { + //https://gunhansancar.com/change-language-programmatically-in-android/ + fun onAttach(context: Context): Context? { + val lang = getPersistedData(context, Locale.getDefault().language) + return lang?.let { setLocale(context, it) } + } + + @kotlin.jvm.JvmStatic + fun onAttach(context: Context, defaultLanguage: String): Context? { + val lang = getPersistedData(context, defaultLanguage) + return lang?.let { setLocale(context, it) } + } + + fun setLocale(context: Context?, language: String): Context? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + updateResources(context!!, language) + } else updateResourcesLegacy(context, language) + } + + private fun getPersistedData(context: Context, defaultLanguage: String): String? { + val preferences = PreferenceManager.getDefaultSharedPreferences(context) + return preferences.getString(context.getString(R.string.language_type), defaultLanguage) + } + + @TargetApi(Build.VERSION_CODES.N) + private fun updateResources(context: Context, language: String): Context { + val locale = Locale(language) + Locale.setDefault(locale) + val configuration = context.resources.configuration + configuration.setLocale(locale) + configuration.setLayoutDirection(locale) + return context.createConfigurationContext(configuration) + } + + private fun updateResourcesLegacy(context: Context?, language: String): Context? { + val locale = Locale(language) + Locale.setDefault(locale) + val resources = context?.resources + val configuration = resources?.configuration + configuration?.locale = locale + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + configuration?.setLayoutDirection(locale) + } + resources?.updateConfiguration(configuration, resources.displayMetrics) + return context + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/MFDatePicker.java b/app/src/main/java/org/mifos/mobile/utils/MFDatePicker.java deleted file mode 100755 index 12fcce3c9b..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/MFDatePicker.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * This project is licensed under the open source MPL V2. - * See https://github.com/openMF/android-client/blob/master/LICENSE.md - */ - -package org.mifos.mobile.utils; - -import android.app.DatePickerDialog; -import android.app.Dialog; -import android.os.Bundle; -import android.text.format.DateFormat; -import android.widget.DatePicker; - -import org.mifos.mobile.R; - -import java.util.Calendar; -import java.util.Date; - -import androidx.fragment.app.DialogFragment; -import androidx.fragment.app.Fragment; - -/** - * Created by ishankhanna on 30/06/14. - */ -public class MFDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener { - - public static final String TAG = "MFDatePicker"; - static String dateSet; - static Calendar mCalendar; - private String startDateString; - private long startDate; - private int datePickerType = ALL_DAYS; - - /* Constants used to select which type of date picker is being called */ - public static final int PREVIOUS_DAYS = 1; // only past days - public static final int FUTURE_DAYS = 2; // only future days - public static final int ALL_DAYS = 3; // any day can be picked - - - static { - - mCalendar = Calendar.getInstance(); - dateSet = new StringBuilder() - .append(mCalendar.get(Calendar.DAY_OF_MONTH) < 10 ? - ("0" + mCalendar.get(Calendar.DAY_OF_MONTH)) - : mCalendar.get(Calendar.DAY_OF_MONTH)) - .append("-") - .append(mCalendar.get(Calendar.MONTH) + 1 < 10 ? - ("0" + (mCalendar.get(Calendar.MONTH) + 1)) - : mCalendar.get(Calendar.MONTH) + 1) - .append("-") - .append(mCalendar.get(Calendar.YEAR)) - .toString(); - } - - OnDatePickListener onDatePickListener; - - public MFDatePicker() { - - } - - public static MFDatePicker newInstance(Fragment fragment, int datePickerType, boolean active) { - MFDatePicker mfDatePicker = new MFDatePicker(); - - Bundle args = new Bundle(); - args.putInt(Constants.DATE_PICKER_TYPE, datePickerType); - - mfDatePicker.setArguments(args); - - mfDatePicker.onDatePickListener = (OnDatePickListener) fragment; - - if (!active) { - mCalendar = Calendar.getInstance(); - } - return mfDatePicker; - } - - public static String getDatePickedAsString() { - return dateSet; - } - - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - - DatePickerDialog dialog = new DatePickerDialog(getActivity(), - R.style.MaterialDatePickerTheme, - this, - mCalendar.get(Calendar.YEAR), - mCalendar.get(Calendar.MONTH), - mCalendar.get(Calendar.DAY_OF_MONTH)); - - Bundle args = getArguments(); - this.datePickerType = args.getInt(Constants.DATE_PICKER_TYPE, this.ALL_DAYS); - - switch (datePickerType) { - case FUTURE_DAYS: - dialog.getDatePicker().setMinDate(new Date().getTime()); - break; - - case PREVIOUS_DAYS: - dialog.getDatePicker().setMaxDate(new Date().getTime()); - break; - } - return dialog; - } - - @Override - public void onDateSet(DatePicker datePicker, int year, int month, int day) { - //TODO Fix Single digit problem that fails with the locale - Calendar calendar = mCalendar; - calendar.set(year, month, day); - Date date = calendar.getTime(); - onDatePickListener.onDatePicked(startDateString = DateFormat. - format("dd-MM-yyyy", date).toString()); - startDate = DateHelper.getDateAsLongFromString(startDateString, "dd-MM-yyyy"); - } - - public void setOnDatePickListener(OnDatePickListener onDatePickListener) { - this.onDatePickListener = onDatePickListener; - } - - public interface OnDatePickListener { - public void onDatePicked(String date); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/utils/MFDatePicker.kt b/app/src/main/java/org/mifos/mobile/utils/MFDatePicker.kt new file mode 100755 index 0000000000..a2d1df65a4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/MFDatePicker.kt @@ -0,0 +1,98 @@ +/* + * This project is licensed under the open source MPL V2. + * See https://github.com/openMF/android-client/blob/master/LICENSE.md + */ +package org.mifos.mobile.utils + +import android.app.DatePickerDialog +import android.app.DatePickerDialog.OnDateSetListener +import android.app.Dialog +import android.os.Bundle +import android.text.format.DateFormat +import android.widget.DatePicker +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.Fragment +import org.mifos.mobile.R +import java.util.* + +/** + * Created by ishankhanna on 30/06/14. + */ +class MFDatePicker : DialogFragment(), OnDateSetListener { + private var startDateString: String? = null + private var startDate: Long? = 0 + private var datePickerType: Int? = ALL_DAYS + + companion object { + const val TAG = "MFDatePicker" + var datePickedAsString: String? = null + var mCalendar: Calendar? = null + + /* Constants used to select which type of date picker is being called */ + const val PREVIOUS_DAYS = 1 // only past days + const val FUTURE_DAYS = 2 // only future days + const val ALL_DAYS = 3 // any day can be picked + fun newInstance(fragment: Fragment?, datePickerType: Int, active: Boolean): MFDatePicker { + val mfDatePicker = MFDatePicker() + val args = Bundle() + args.putInt(Constants.DATE_PICKER_TYPE, datePickerType) + mfDatePicker.arguments = args + mfDatePicker.onDatePickListener = fragment as OnDatePickListener? + if (!active) { + mCalendar = Calendar.getInstance() + } + return mfDatePicker + } + + init { + mCalendar = Calendar.getInstance() + datePickedAsString = StringBuilder() + .append(if (mCalendar?.get(Calendar.DAY_OF_MONTH) != null && + (mCalendar?.get(Calendar.DAY_OF_MONTH)!! < 10)) "0" + + mCalendar?.get(Calendar.DAY_OF_MONTH) + else mCalendar?.get(Calendar.DAY_OF_MONTH)) + .append("-") + .append(if (mCalendar?.get(Calendar.MONTH) != null && + (mCalendar?.get(Calendar.MONTH)!! + 1 < 10)) "0" + + (mCalendar?.get(Calendar.MONTH)!! + 1) + else mCalendar?.get(Calendar.MONTH)?.plus(1)) + .append("-") + .append(mCalendar?.get(Calendar.YEAR)) + .toString() + } + } + + private var onDatePickListener: OnDatePickListener? = null + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val dialog = DatePickerDialog(this.requireContext(), + R.style.MaterialDatePickerTheme, + this, + mCalendar?.get(Calendar.YEAR)!!, + mCalendar?.get(Calendar.MONTH)!!, + mCalendar?.get(Calendar.DAY_OF_MONTH)!!) + val args = arguments + datePickerType = args?.getInt(Constants.DATE_PICKER_TYPE, ALL_DAYS) + when (datePickerType) { + FUTURE_DAYS -> dialog.datePicker.minDate = Date().time + PREVIOUS_DAYS -> dialog.datePicker.maxDate = Date().time + } + return dialog + } + + override fun onDateSet(datePicker: DatePicker, year: Int, month: Int, day: Int) { + //TODO Fix Single digit problem that fails with the locale + val calendar = mCalendar + calendar!![year, month] = day + val date = calendar.time + onDatePickListener?.onDatePicked(DateFormat.format("dd-MM-yyyy", date).toString().also { startDateString = it }) + startDate = DateHelper.getDateAsLongFromString(startDateString, "dd-MM-yyyy") + } + + fun setOnDatePickListener(onDatePickListener: OnDatePickListener?) { + this.onDatePickListener = onDatePickListener + } + + interface OnDatePickListener { + fun onDatePicked(date: String?) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/MFErrorParser.java b/app/src/main/java/org/mifos/mobile/utils/MFErrorParser.java deleted file mode 100644 index 11f91704f7..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/MFErrorParser.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.mifos.mobile.utils; - -import com.google.gson.Gson; - -import org.mifos.mobile.models.mifoserror.MifosError; - -import io.reactivex.plugins.RxJavaPlugins; -import retrofit2.HttpException; - -public class MFErrorParser { - - public static final String LOG_TAG = "MFErrorParser"; - - private static Gson gson = new Gson(); - - public static MifosError parseError(String serverResponse) { - return gson.fromJson(serverResponse, MifosError.class); - } - - public static String errorMessage(Throwable throwableError) { - String errorMessage = ""; - try { - if (throwableError instanceof HttpException) { - errorMessage = ((HttpException) throwableError).response().errorBody().string(); - errorMessage = MFErrorParser.parseError(errorMessage).getErrors() - .get(0).getDefaultUserMessage(); - } - } catch (Throwable throwable) { - RxJavaPlugins.getErrorHandler(); - } - return errorMessage; - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/MFErrorParser.kt b/app/src/main/java/org/mifos/mobile/utils/MFErrorParser.kt new file mode 100644 index 0000000000..8764848958 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/MFErrorParser.kt @@ -0,0 +1,28 @@ +package org.mifos.mobile.utils + +import com.google.gson.Gson +import io.reactivex.plugins.RxJavaPlugins +import org.mifos.mobile.models.mifoserror.MifosError +import retrofit2.HttpException + +object MFErrorParser { + const val LOG_TAG = "MFErrorParser" + private val gson = Gson() + fun parseError(serverResponse: String?): MifosError { + return gson.fromJson(serverResponse, MifosError::class.java) + } + + @kotlin.jvm.JvmStatic + fun errorMessage(throwableError: Throwable?): String? { + var errorMessage: String? = "" + try { + if (throwableError is HttpException) { + errorMessage = throwableError.response().errorBody().string() + errorMessage = parseError(errorMessage).errors[0].defaultUserMessage + } + } catch (throwable: Throwable) { + RxJavaPlugins.getErrorHandler() + } + return errorMessage + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/MaterialDialog.java b/app/src/main/java/org/mifos/mobile/utils/MaterialDialog.java deleted file mode 100644 index 93fb53c3bb..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/MaterialDialog.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.content.DialogInterface; -import android.view.View; - -import org.mifos.mobile.R; - -import androidx.annotation.StringRes; -import androidx.appcompat.app.AlertDialog; -import androidx.core.content.ContextCompat; - -/** - * This Class is the Material Dialog Builder Class - * Created by Rajan Maurya on 03/08/16. - */ -public final class MaterialDialog { - - public static class Builder { - - private AlertDialog.Builder mMaterialDialogBuilder; - private Context context; - - //This is the Default Builder Initialization with Material Style - public Builder init(Context context) { - mMaterialDialogBuilder = - new AlertDialog.Builder(context, R.style.MaterialAlertDialogStyle); - this.context = context; - return this; - } - - //This method set the custom Material Style - public Builder init(Context context, int theme) { - mMaterialDialogBuilder = new AlertDialog.Builder(context, theme); - this.context = context; - return this; - } - - //This method set the String Title - public Builder setTitle(String title) { - mMaterialDialogBuilder.setTitle(title); - return this; - } - - //This Method set the String Resources to Title - public Builder setTitle(@StringRes int title) { - mMaterialDialogBuilder.setTitle(title); - return this; - } - - //This Method set the String Message - public Builder setMessage(String message) { - mMaterialDialogBuilder.setMessage(message); - return this; - } - - //This Method set the String Resources message - public Builder setMessage(@StringRes int message) { - mMaterialDialogBuilder.setMessage(message); - return this; - } - - //This Method set String Test to the Positive Button and set the Onclick null - public Builder setPositiveButton(String positiveText) { - mMaterialDialogBuilder.setPositiveButton(positiveText, null); - return this; - } - - //This Method Set the String Resources Text To Positive Button - public Builder setPositiveButton(@StringRes int positiveText) { - mMaterialDialogBuilder.setPositiveButton(positiveText, null); - return this; - } - - //This Method set the String Text to Positive Button and set the OnClick Event to it - public Builder setPositiveButton(String positiveText, - DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setPositiveButton(positiveText, listener); - return this; - } - - //This method set the String Resources text To Positive button and set the Onclick Event - public Builder setPositiveButton(@StringRes int positiveText, - DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setPositiveButton(positiveText, listener); - return this; - } - - //This Method the String Text to Negative Button and Set the onclick event to null - public Builder setNegativeButton(String negativeText) { - mMaterialDialogBuilder.setNegativeButton(negativeText, null); - return this; - } - - //This Method set the String Resources Text to Negative button - // and set the onclick event to null - public Builder setNegativeButton(@StringRes int negativeText) { - mMaterialDialogBuilder.setNegativeButton(negativeText, null); - return this; - } - - //This Method set String Text to Negative Button and - //Set the Onclick event - public Builder setNegativeButton(String negativeText, - DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setNegativeButton(negativeText, listener); - return this; - } - - //This method set String Resources Text to Negative Button and set Onclick Event - public Builder setNegativeButton(@StringRes int negativeText, - DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setNegativeButton(negativeText, listener); - return this; - } - - //This Method the String Text to Neutral Button and Set the onclick event to null - public Builder setNeutralButton(String neutralText) { - mMaterialDialogBuilder.setNeutralButton(neutralText, null); - return this; - } - - //This Method set the String Resources Text to Neutral button - // and set the onclick event to null - public Builder setNeutralButton(@StringRes int neutralText) { - mMaterialDialogBuilder.setNeutralButton(neutralText, null); - return this; - } - - //This Method set String Text to Neutral Button and - //Set the Onclick event - public Builder setNeutralButton(String neutralText, - DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setNeutralButton(neutralText, listener); - return this; - } - - //This method set String Resources Text to Neutral Button and set Onclick Event - public Builder setNeutralButton(@StringRes int neutralText, - DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setNeutralButton(neutralText, listener); - return this; - } - - public Builder setCancelable(Boolean cancelable) { - mMaterialDialogBuilder.setCancelable(cancelable); - return this; - } - - public Builder setItems(int items, DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setItems(items, listener); - return this; - } - - public Builder setItems(CharSequence[] items, DialogInterface.OnClickListener listener) { - mMaterialDialogBuilder.setItems(items, listener); - return this; - } - - public Builder addView(View view) { - mMaterialDialogBuilder.setView(view); - return this; - } - - //This Method Create the Final Material Dialog - public Builder createMaterialDialog() { - mMaterialDialogBuilder.create(); - return this; - } - - //This Method Show the Dialog - public Builder show() { - AlertDialog dialog = mMaterialDialogBuilder.show(); - dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, - R.color.accent)); - dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(context, - R.color.gray_dark)); - dialog.getButton(dialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(context, - R.color.black)); - return this; - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/MaterialDialog.kt b/app/src/main/java/org/mifos/mobile/utils/MaterialDialog.kt new file mode 100644 index 0000000000..3a6c846850 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/MaterialDialog.kt @@ -0,0 +1,194 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.content.DialogInterface +import android.view.View + +import androidx.annotation.StringRes +import androidx.appcompat.app.AlertDialog +import androidx.core.content.ContextCompat + +import org.mifos.mobile.R + +/** + * This Class is the Material Dialog Builder Class + * Created by Rajan Maurya on 03/08/16. + */ +class MaterialDialog { + + class Builder { + + private var mMaterialDialogBuilder: AlertDialog.Builder? = null + private var context: Context? = null + + //This is the Default Builder Initialization with Material Style + fun init(context: Context?): Builder { + mMaterialDialogBuilder = AlertDialog.Builder(context!!, R.style.MaterialAlertDialogStyle) + this.context = context + return this + } + + //This method set the custom Material Style + fun init(context: Context?, theme: Int): Builder { + mMaterialDialogBuilder = AlertDialog.Builder(context!!, theme) + this.context = context + return this + } + + //This method set the String Title + fun setTitle(title: String?): Builder { + mMaterialDialogBuilder?.setTitle(title) + return this + } + + //This Method set the String Resources to Title + fun setTitle(@StringRes title: Int): Builder { + mMaterialDialogBuilder?.setTitle(title) + return this + } + + //This Method set the String Message + fun setMessage(message: String?): Builder { + mMaterialDialogBuilder?.setMessage(message) + return this + } + + //This Method set the String Resources message + fun setMessage(@StringRes message: Int): Builder { + mMaterialDialogBuilder?.setMessage(message) + return this + } + + //This Method set String Test to the Positive Button and set the Onclick null + fun setPositiveButton(positiveText: String?): Builder { + mMaterialDialogBuilder?.setPositiveButton(positiveText, null) + return this + } + + //This Method Set the String Resources Text To Positive Button + fun setPositiveButton(@StringRes positiveText: Int): Builder { + mMaterialDialogBuilder?.setPositiveButton(positiveText, null) + return this + } + + //This Method set the String Text to Positive Button and set the OnClick Event to it + fun setPositiveButton( + positiveText: String?, + listener: DialogInterface.OnClickListener? + ): Builder { + mMaterialDialogBuilder?.setPositiveButton(positiveText, listener) + return this + } + + //This method set the String Resources text To Positive button and set the Onclick Event + fun setPositiveButton( + @StringRes positiveText: Int, + listener: DialogInterface.OnClickListener? + ): Builder { + mMaterialDialogBuilder?.setPositiveButton(positiveText, listener) + return this + } + + //This Method the String Text to Negative Button and Set the onclick event to null + fun setNegativeButton(negativeText: String?): Builder { + mMaterialDialogBuilder?.setNegativeButton(negativeText, null) + return this + } + + //This Method set the String Resources Text to Negative button + // and set the onclick event to null + fun setNegativeButton(@StringRes negativeText: Int): Builder { + mMaterialDialogBuilder?.setNegativeButton(negativeText, null) + return this + } + + //This Method set String Text to Negative Button and + //Set the Onclick event + fun setNegativeButton( + negativeText: String?, + listener: DialogInterface.OnClickListener? + ): Builder { + mMaterialDialogBuilder?.setNegativeButton(negativeText, listener) + return this + } + + //This method set String Resources Text to Negative Button and set Onclick Event + fun setNegativeButton( + @StringRes negativeText: Int, + listener: DialogInterface.OnClickListener? + ): Builder { + mMaterialDialogBuilder?.setNegativeButton(negativeText, listener) + return this + } + + //This Method the String Text to Neutral Button and Set the onclick event to null + fun setNeutralButton(neutralText: String?): Builder { + mMaterialDialogBuilder?.setNeutralButton(neutralText, null) + return this + } + + //This Method set the String Resources Text to Neutral button + // and set the onclick event to null + fun setNeutralButton(@StringRes neutralText: Int): Builder { + mMaterialDialogBuilder?.setNeutralButton(neutralText, null) + return this + } + + //This Method set String Text to Neutral Button and + //Set the Onclick event + fun setNeutralButton( + neutralText: String?, + listener: DialogInterface.OnClickListener? + ): Builder { + mMaterialDialogBuilder?.setNeutralButton(neutralText, listener) + return this + } + + //This method set String Resources Text to Neutral Button and set Onclick Event + fun setNeutralButton( + @StringRes neutralText: Int, + listener: DialogInterface.OnClickListener? + ): Builder { + mMaterialDialogBuilder?.setNeutralButton(neutralText, listener) + return this + } + + fun setCancelable(cancelable: Boolean?): Builder { + mMaterialDialogBuilder?.setCancelable(cancelable!!) + return this + } + + fun setItems(items: Int, listener: DialogInterface.OnClickListener?): Builder { + mMaterialDialogBuilder?.setItems(items, listener) + return this + } + + fun setItems(items: Array?, listener: DialogInterface.OnClickListener?): Builder { + mMaterialDialogBuilder?.setItems(items, listener) + return this + } + + fun addView(view: View?): Builder { + mMaterialDialogBuilder?.setView(view) + return this + } + + //This Method Create the Final Material Dialog + fun createMaterialDialog(): Builder { + mMaterialDialogBuilder?.create() + return this + } + + //This Method Show the Dialog + fun show(): Builder { + val dialog = mMaterialDialogBuilder?.show() + dialog?.getButton(DialogInterface.BUTTON_POSITIVE)?.setTextColor(ContextCompat.getColor(context!!, + R.color.accent)) + dialog?.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(ContextCompat.getColor(context!!, + R.color.gray_dark)) + dialog?.getButton(DialogInterface.BUTTON_NEUTRAL)?.setTextColor(ContextCompat.getColor(context!!, + R.color.black)) + return this + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/Network.java b/app/src/main/java/org/mifos/mobile/utils/Network.java deleted file mode 100644 index bdf1791140..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/Network.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.telephony.TelephonyManager; - -/** - * Created by rishabhkhanna on 07/03/17. - */ - -public class Network { - /** - * Get the network info - * - * @param context - * @return - */ - public static NetworkInfo getNetworkInfo(Context context) { - ConnectivityManager cm = (ConnectivityManager) - context.getSystemService(Context.CONNECTIVITY_SERVICE); - return cm.getActiveNetworkInfo(); - } - - /** - * Check if there is any connectivity - * - * @param context - * @return - */ - public static boolean isConnected(Context context) { - NetworkInfo info = Network.getNetworkInfo(context); - return (info != null && info.isConnected()); - } - - /** - * Check if there is any connectivity to a Wifi network - * - * @param context - * @param type - * @return - */ - public static boolean isConnectedWifi(Context context) { - NetworkInfo info = Network.getNetworkInfo(context); - return (info != null && info.isConnected() && - info.getType() == ConnectivityManager.TYPE_WIFI); - } - - /** - * Check if there is any connectivity to a mobile network - * - * @param context - * @param type - * @return - */ - public static boolean isConnectedMobile(Context context) { - NetworkInfo info = Network.getNetworkInfo(context); - return (info != null && info.isConnected() && - info.getType() == ConnectivityManager.TYPE_MOBILE); - } - - /** - * Check if there is fast connectivity - * - * @param context - * @return - */ - public static boolean isConnectedFast(Context context) { - NetworkInfo info = Network.getNetworkInfo(context); - return (info != null && info.isConnected() && - Network.isConnectionFast(info.getType(), info.getSubtype())); - } - - /** - * Check if the connection is fast - * - * @param type - * @param subType - * @return - */ - public static boolean isConnectionFast(int type, int subType) { - if (type == ConnectivityManager.TYPE_WIFI) { - return true; - } else if (type == ConnectivityManager.TYPE_MOBILE) { - switch (subType) { - case TelephonyManager.NETWORK_TYPE_1xRTT: - return false; // ~ 50-100 kbps - case TelephonyManager.NETWORK_TYPE_CDMA: - return false; // ~ 14-64 kbps - case TelephonyManager.NETWORK_TYPE_EDGE: - return false; // ~ 50-100 kbps - case TelephonyManager.NETWORK_TYPE_EVDO_0: - return true; // ~ 400-1000 kbps - case TelephonyManager.NETWORK_TYPE_EVDO_A: - return true; // ~ 600-1400 kbps - case TelephonyManager.NETWORK_TYPE_GPRS: - return false; // ~ 100 kbps - case TelephonyManager.NETWORK_TYPE_HSDPA: - return true; // ~ 2-14 Mbps - case TelephonyManager.NETWORK_TYPE_HSPA: - return true; // ~ 700-1700 kbps - case TelephonyManager.NETWORK_TYPE_HSUPA: - return true; // ~ 1-23 Mbps - case TelephonyManager.NETWORK_TYPE_UMTS: - return true; // ~ 400-7000 kbps - - /* Above API level 7, make sure to set android:targetSdkVersion - * to appropriate level to use these*/ - - case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 - return true; // ~ 1-2 Mbps - case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9 - return true; // ~ 5 Mbps - case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13 - return true; // ~ 10-20 Mbps - case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8 - return false; // ~25 kbps - case TelephonyManager.NETWORK_TYPE_LTE: // API level 11 - return true; // ~ 10+ Mbps - // Unknown - case TelephonyManager.NETWORK_TYPE_UNKNOWN: - default: - return false; - } - } else { - return false; - } - } - -} diff --git a/app/src/main/java/org/mifos/mobile/utils/Network.kt b/app/src/main/java/org/mifos/mobile/utils/Network.kt new file mode 100644 index 0000000000..01291dcae4 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/Network.kt @@ -0,0 +1,108 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkInfo +import android.telephony.TelephonyManager + +/** + * Created by rishabhkhanna on 07/03/17. + */ +object Network { + /** + * Get the network info + * + * @param context + * @return + */ + private fun getNetworkInfo(context: Context): NetworkInfo { + val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + return cm.activeNetworkInfo + } + + /** + * Check if there is any connectivity + * + * @param context + * @return + */ + @kotlin.jvm.JvmStatic + fun isConnected(context: Context?): Boolean { + val info = getNetworkInfo(context!!) + return info.isConnected + } + + /** + * Check if there is any connectivity to a Wifi network + * + * @param context + * @param type + * @return + */ + fun isConnectedWifi(context: Context): Boolean { + val info = getNetworkInfo(context) + return info.isConnected && info.type == ConnectivityManager.TYPE_WIFI + } + + /** + * Check if there is any connectivity to a mobile network + * + * @param context + * @param type + * @return + */ + fun isConnectedMobile(context: Context): Boolean { + val info = getNetworkInfo(context) + return info.isConnected && info.type == ConnectivityManager.TYPE_MOBILE + } + + /** + * Check if there is fast connectivity + * + * @param context + * @return + */ + fun isConnectedFast(context: Context): Boolean { + val info = getNetworkInfo(context) + return info.isConnected && isConnectionFast(info.type, info.subtype) + } + + /** + * Check if the connection is fast + * + * @param type + * @param subType + * @return + */ + private fun isConnectionFast(type: Int, subType: Int): Boolean { + return when (type) { + ConnectivityManager.TYPE_WIFI -> { + true + } + ConnectivityManager.TYPE_MOBILE -> { + when (subType) { + TelephonyManager.NETWORK_TYPE_1xRTT -> false // ~ 50-100 kbps + TelephonyManager.NETWORK_TYPE_CDMA -> false // ~ 14-64 kbps + TelephonyManager.NETWORK_TYPE_EDGE -> false // ~ 50-100 kbps + TelephonyManager.NETWORK_TYPE_EVDO_0 -> true // ~ 400-1000 kbps + TelephonyManager.NETWORK_TYPE_EVDO_A -> true // ~ 600-1400 kbps + TelephonyManager.NETWORK_TYPE_GPRS -> false // ~ 100 kbps + TelephonyManager.NETWORK_TYPE_HSDPA -> true // ~ 2-14 Mbps + TelephonyManager.NETWORK_TYPE_HSPA -> true // ~ 700-1700 kbps + TelephonyManager.NETWORK_TYPE_HSUPA -> true // ~ 1-23 Mbps + TelephonyManager.NETWORK_TYPE_UMTS -> true // ~ 400-7000 kbps + TelephonyManager.NETWORK_TYPE_EHRPD -> true // ~ 1-2 Mbps + TelephonyManager.NETWORK_TYPE_EVDO_B -> true // ~ 5 Mbps + TelephonyManager.NETWORK_TYPE_HSPAP -> true // ~ 10-20 Mbps + TelephonyManager.NETWORK_TYPE_IDEN -> false // ~25 kbps + TelephonyManager.NETWORK_TYPE_LTE -> true // ~ 10+ Mbps + TelephonyManager.NETWORK_TYPE_UNKNOWN -> false + else -> false + } + } + else -> { + false + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/NotificationComparator.java b/app/src/main/java/org/mifos/mobile/utils/NotificationComparator.java deleted file mode 100644 index 770e246e7e..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/NotificationComparator.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.mifos.mobile.utils; - -import org.mifos.mobile.models.notification.MifosNotification; - -import java.util.Comparator; - -/** - * Created by dilpreet on 14/9/17. - */ - -public class NotificationComparator implements Comparator { - @Override - public int compare(MifosNotification mifosNotification1, MifosNotification mifosNotification2) { - return mifosNotification2.getTimeStamp() < mifosNotification1.getTimeStamp() ? -1 : - mifosNotification1.getTimeStamp() > mifosNotification2.getTimeStamp() ? 1 : 0; - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/NotificationComparator.kt b/app/src/main/java/org/mifos/mobile/utils/NotificationComparator.kt new file mode 100644 index 0000000000..308283af06 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/NotificationComparator.kt @@ -0,0 +1,17 @@ +package org.mifos.mobile.utils + +import org.mifos.mobile.models.notification.MifosNotification +import java.util.* + +/** + * Created by dilpreet on 14/9/17. + */ +class NotificationComparator : Comparator { + override fun compare(mifosNotification1: MifosNotification, mifosNotification2: MifosNotification): Int { + return when { + mifosNotification2.timeStamp < mifosNotification1.timeStamp -> -1 + mifosNotification1.timeStamp > mifosNotification2.timeStamp -> 1 + else -> 0 + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/PasswordStrength.java b/app/src/main/java/org/mifos/mobile/utils/PasswordStrength.java deleted file mode 100644 index 11718ff9bb..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/PasswordStrength.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.mifos.mobile.utils; - -import android.graphics.Color; - -import org.mifos.mobile.R; - -public enum PasswordStrength { - - WEAK(R.string.password_strength_weak, Color.RED), - MEDIUM(R.string.password_strength_medium, Color.argb(255, 220, 185, 0)), - STRONG(R.string.password_strength_strong, Color.GREEN), - VERY_STRONG(R.string.password_strength_very_strong, Color.BLUE); - - //--------REQUIREMENTS-------- - static int REQUIRED_LENGTH = 8; - static int MAXIMUM_LENGTH = 15; - static boolean REQUIRE_SPECIAL_CHARACTERS = true; - static boolean REQUIRE_DIGITS = true; - static boolean REQUIRE_LOWER_CASE = true; - static boolean REQUIRE_UPPER_CASE = false; - - int resId; - int color; - - PasswordStrength(int resId, int color) { - this.resId = resId; - this.color = color; - } - - public CharSequence getText(android.content.Context ctx) { - return ctx.getText(resId); - } - - public int getColor() { - return color; - } - - public static PasswordStrength calculateStrength(String password) { - int currentScore = 0; - boolean sawUpper = false; - boolean sawLower = false; - boolean sawDigit = false; - boolean sawSpecial = false; - - - for (int i = 0; i < password.length(); i++) { - char c = password.charAt(i); - - if (!sawSpecial && !Character.isLetterOrDigit(c)) { - currentScore += 1; - sawSpecial = true; - } else { - if (!sawDigit && Character.isDigit(c)) { - currentScore += 1; - sawDigit = true; - } else { - if (!sawUpper || !sawLower) { - if (Character.isUpperCase(c)) { - sawUpper = true; - } else { - sawLower = true; - } - if (sawUpper && sawLower) - currentScore += 1; - } - } - } - } - - if (password.length() > REQUIRED_LENGTH) { - if ((REQUIRE_SPECIAL_CHARACTERS && !sawSpecial) - || (REQUIRE_UPPER_CASE && !sawUpper) - || (REQUIRE_LOWER_CASE && !sawLower) - || (REQUIRE_DIGITS && !sawDigit)) { - currentScore = 1; - } else { - currentScore = 2; - if (password.length() > MAXIMUM_LENGTH) { - currentScore = 3; - } - } - } else { - currentScore = 0; - } - - switch (currentScore) { - case 0: - return WEAK; - case 1: - return MEDIUM; - case 2: - return STRONG; - case 3: - return VERY_STRONG; - } - - return VERY_STRONG; - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/PasswordStrength.kt b/app/src/main/java/org/mifos/mobile/utils/PasswordStrength.kt new file mode 100644 index 0000000000..314738e739 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/PasswordStrength.kt @@ -0,0 +1,77 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.graphics.Color + +import org.mifos.mobile.R + +enum class PasswordStrength(private var resId: Int, var color: Int) { + + WEAK(R.string.password_strength_weak, Color.RED), + MEDIUM(R.string.password_strength_medium, Color.argb(255, 220, 185, 0)), + STRONG(R.string.password_strength_strong, Color.GREEN), + VERY_STRONG(R.string.password_strength_very_strong, Color.BLUE); + + fun getText(ctx: Context?): CharSequence? { + return ctx?.getText(resId) + } + + companion object { + //--------REQUIREMENTS-------- + private var REQUIRED_LENGTH = 8 + private var MAXIMUM_LENGTH = 15 + private var REQUIRE_SPECIAL_CHARACTERS = true + private var REQUIRE_DIGITS = true + private var REQUIRE_LOWER_CASE = true + private var REQUIRE_UPPER_CASE = false + fun calculateStrength(password: String): PasswordStrength { + var currentScore = 0 + var sawUpper = false + var sawLower = false + var sawDigit = false + var sawSpecial = false + for (element in password) { + if (!sawSpecial && !Character.isLetterOrDigit(element)) { + currentScore += 1 + sawSpecial = true + } else { + if (!sawDigit && Character.isDigit(element)) { + currentScore += 1 + sawDigit = true + } else { + if (!sawUpper || !sawLower) { + if (Character.isUpperCase(element)) { + sawUpper = true + } else { + sawLower = true + } + if (sawUpper && sawLower) currentScore += 1 + } + } + } + } + if (password.length > REQUIRED_LENGTH) { + if (REQUIRE_SPECIAL_CHARACTERS && !sawSpecial + || REQUIRE_UPPER_CASE && !sawUpper + || REQUIRE_LOWER_CASE && !sawLower + || REQUIRE_DIGITS && !sawDigit) { + currentScore = 1 + } else { + currentScore = 2 + if (password.length > MAXIMUM_LENGTH) { + currentScore = 3 + } + } + } else { + currentScore = 0 + } + when (currentScore) { + 0 -> return WEAK + 1 -> return MEDIUM + 2 -> return STRONG + 3 -> return VERY_STRONG + } + return VERY_STRONG + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ProcessView.java b/app/src/main/java/org/mifos/mobile/utils/ProcessView.java deleted file mode 100644 index 24f4237445..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/ProcessView.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.util.AttributeSet; -import android.view.View; - -import org.mifos.mobile.R; - -import androidx.core.content.ContextCompat; - -/** - * Created by dilpreet on 30/6/17. - */ - -public class ProcessView extends View { - - private String valueStr; - private Paint textPaint, backgroundPaint; - - public ProcessView(Context context) { - super(context, null); - } - - public ProcessView(Context context, AttributeSet attrs) { - super(context, attrs); - - TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProcessView); - valueStr = typedArray.getString(R.styleable.ProcessView_value); - - typedArray.recycle(); - - textPaint = new Paint(); - textPaint.setColor(getColorCompat(android.R.color.white)); - textPaint.setAntiAlias(true); - textPaint.setStyle(Paint.Style.FILL); - textPaint.setStrokeWidth(1); - textPaint.setTextSize(40f); - - backgroundPaint = new Paint(); - backgroundPaint.setColor(getColorCompat(R.color.gray_dark)); - backgroundPaint.setAntiAlias(true); - backgroundPaint.setStyle(Paint.Style.FILL); - - } - - @Override - protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - int xPos = (canvas.getWidth() / 2) - (int) (textPaint.measureText(String. - valueOf(valueStr)) / 2); - int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + - textPaint.ascent()) / 2)); - - int usableWidth = getWidth() - (getPaddingLeft() + getPaddingRight()); - int usableHeight = getHeight() - (getPaddingTop() + getPaddingBottom()); - - int radius = Math.min(usableWidth, usableHeight) / 2; - int cx = getPaddingLeft() + (usableWidth / 2); - int cy = getPaddingTop() + (usableHeight / 2); - - canvas.drawCircle(cx, cy, radius, backgroundPaint); - canvas.drawText(valueStr, xPos, yPos, textPaint); - } - - public void setCurrentActive() { - backgroundPaint.setColor(getColorCompat(R.color.primary)); - invalidate(); - } - - public void setCurrentCompeleted() { - backgroundPaint.setColor(getColorCompat(R.color.primary)); - valueStr = "\u2713"; - invalidate(); - } - - private int getColorCompat(int colorId) { - return ContextCompat.getColor(getContext(), colorId); - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/ProcessView.kt b/app/src/main/java/org/mifos/mobile/utils/ProcessView.kt new file mode 100644 index 0000000000..7947c9885a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/ProcessView.kt @@ -0,0 +1,63 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.util.AttributeSet +import android.view.View +import androidx.core.content.ContextCompat +import org.mifos.mobile.R + +/** + * Created by dilpreet on 30/6/17. + */ +class ProcessView : View { + private var valueStr: String? = null + private var textPaint: Paint? = null + private var backgroundPaint: Paint? = null + + constructor(context: Context?) : super(context, null) + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { + val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProcessView) + valueStr = typedArray.getString(R.styleable.ProcessView_value) + typedArray.recycle() + textPaint = Paint() + textPaint?.color = getColorCompat(android.R.color.white) + textPaint?.isAntiAlias = true + textPaint?.style = Paint.Style.FILL + textPaint?.strokeWidth = 1f + textPaint?.textSize = 40f + backgroundPaint = Paint() + backgroundPaint?.color = getColorCompat(R.color.gray_dark) + backgroundPaint?.isAntiAlias = true + backgroundPaint?.style = Paint.Style.FILL + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val xPos = canvas.width / 2 - (textPaint?.measureText(valueStr.toString())?.div(2))?.toInt()!! + val yPos = (canvas.height / 2 - ((textPaint?.descent()?.plus(textPaint?.ascent()!!))?.div(2))!!).toInt() + val usableWidth = width - (paddingLeft + paddingRight) + val usableHeight = height - (paddingTop + paddingBottom) + val radius = usableWidth.coerceAtMost(usableHeight) / 2 + val cx = paddingLeft + usableWidth / 2 + val cy = paddingTop + usableHeight / 2 + canvas.drawCircle(cx.toFloat(), cy.toFloat(), radius.toFloat(), backgroundPaint) + canvas.drawText(valueStr, xPos.toFloat(), yPos.toFloat(), textPaint) + } + + fun setCurrentActive() { + backgroundPaint?.color = getColorCompat(R.color.primary) + invalidate() + } + + fun setCurrentCompleted() { + backgroundPaint?.color = getColorCompat(R.color.primary) + valueStr = "\u2713" + invalidate() + } + + private fun getColorCompat(colorId: Int): Int { + return ContextCompat.getColor(context, colorId) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ProgressBarHandler.java b/app/src/main/java/org/mifos/mobile/utils/ProgressBarHandler.java deleted file mode 100644 index 2483af1312..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/ProgressBarHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.mifos.mobile.utils; - -import android.R.attr; -import android.R.id; -import android.app.Activity; -import android.content.Context; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ProgressBar; -import android.widget.RelativeLayout; -import android.widget.RelativeLayout.LayoutParams; - - -/** - * @author Rajan Maurya - */ -public class ProgressBarHandler { - - private ProgressBar mProgressBar; - private Context mContext; - - public ProgressBarHandler(Context context) { - mContext = context; - - ViewGroup layout = (ViewGroup) ((Activity) context).findViewById(id.content).getRootView(); - - mProgressBar = new ProgressBar(context, null, attr.progressBarStyleInverse); - mProgressBar.setIndeterminate(true); - - LayoutParams params = new - LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); - - RelativeLayout rl = new RelativeLayout(context); - - rl.setGravity(Gravity.CENTER); - rl.addView(mProgressBar); - - layout.addView(rl, params); - - hide(); - } - - public void show() { - mProgressBar.setVisibility(View.VISIBLE); - } - - public void hide() { - mProgressBar.setVisibility(View.INVISIBLE); - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/ProgressBarHandler.kt b/app/src/main/java/org/mifos/mobile/utils/ProgressBarHandler.kt new file mode 100644 index 0000000000..c6ddc6ca8b --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/ProgressBarHandler.kt @@ -0,0 +1,37 @@ +package org.mifos.mobile.utils + +import android.R.attr +import android.R.id +import android.app.Activity +import android.content.Context +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.ProgressBar +import android.widget.RelativeLayout + +/** + * @author Rajan Maurya + */ +class ProgressBarHandler(mContext: Context) { + private val mProgressBar: ProgressBar + fun show() { + mProgressBar.visibility = View.VISIBLE + } + + fun hide() { + mProgressBar.visibility = View.INVISIBLE + } + + init { + val layout = (mContext as Activity).findViewById(id.content).rootView as ViewGroup + mProgressBar = ProgressBar(mContext, null, attr.progressBarStyleInverse) + mProgressBar.isIndeterminate = true + val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT) + val rl = RelativeLayout(mContext) + rl.gravity = Gravity.CENTER + rl.addView(mProgressBar) + layout.addView(rl, params) + hide() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/QrCodeGenerator.java b/app/src/main/java/org/mifos/mobile/utils/QrCodeGenerator.java deleted file mode 100644 index f4e9575b9b..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/QrCodeGenerator.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.mifos.mobile.utils; - -import android.graphics.Bitmap; - -import com.google.gson.Gson; -import com.google.zxing.BarcodeFormat; -import com.google.zxing.MultiFormatWriter; -import com.google.zxing.WriterException; -import com.google.zxing.common.BitMatrix; - -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.templates.account.AccountType; - -import static android.graphics.Color.BLACK; -import static android.graphics.Color.WHITE; - -/** - * Created by dilpreet on 6/7/17. - */ - -public class QrCodeGenerator { - - /** - * Generate a QRCode which stores {@code str} in the form of {@link Bitmap} - * @param str Data which need to stored in QRCode - * @return Returns a {@link Bitmap} of QRCode - */ - public static Bitmap encodeAsBitmap(String str) { - BitMatrix result; - try { - result = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 200, 200, null); - } catch (IllegalArgumentException iae) { - return null; - } catch (WriterException e) { - return null; - } - - int width = result.getWidth(); - int height = result.getHeight(); - int[] pixels = new int[width * height]; - for (int y = 0; y < height; y++) { - int offset = y * width; - for (int x = 0; x < width; x++) { - pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; - } - } - - Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - bitmap.setPixels(pixels, 0, width, 0, 0, width, height); - return bitmap; - } - - /** - * Provides a string which contains json data for creating a {@link Beneficiary} - * @param accountNumber Account Number of client - * @param officeName Office Name of Client - * @param accountType {@link org.mifos.mobile.ui.enums.AccountType} i.e. SAVINGS or LOAN - * @return Returns a string with account details - */ - public static String getAccountDetailsInString(String accountNumber, String officeName, - org.mifos.mobile.ui.enums.AccountType - accountType) { - int accountId = -1; - if (accountType == org.mifos.mobile.ui.enums.AccountType.SAVINGS) { - accountId = 0; - } else if (accountType == org.mifos.mobile.ui.enums.AccountType.LOAN) { - accountId = 1; - } - - AccountType type = new AccountType(); - type.setId(accountId); - Beneficiary payload = new Beneficiary(); - payload.setAccountNumber(accountNumber); - payload.setAccountType(type); - payload.setOfficeName(officeName); - - Gson gson = new Gson(); - return gson.toJson(payload); - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/QrCodeGenerator.kt b/app/src/main/java/org/mifos/mobile/utils/QrCodeGenerator.kt new file mode 100644 index 0000000000..99128e8877 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/QrCodeGenerator.kt @@ -0,0 +1,71 @@ +package org.mifos.mobile.utils + +import android.graphics.Bitmap +import android.graphics.Color +import com.google.gson.Gson +import com.google.zxing.BarcodeFormat +import com.google.zxing.MultiFormatWriter +import com.google.zxing.WriterException +import com.google.zxing.common.BitMatrix +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.ui.enums.AccountType + +/** + * Created by dilpreet on 6/7/17. + */ +object QrCodeGenerator { + /** + * Generate a QRCode which stores `str` in the form of [Bitmap] + * @param str Data which need to stored in QRCode + * @return Returns a [Bitmap] of QRCode + */ + fun encodeAsBitmap(str: String?): Bitmap? { + val result: BitMatrix + result = try { + MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 200, 200, null) + } catch (iae: IllegalArgumentException) { + return null + } catch (e: WriterException) { + return null + } + val width = result.width + val height = result.height + val pixels = IntArray(width * height) + for (y in 0 until height) { + val offset = y * width + for (x in 0 until width) { + pixels[offset + x] = if (result[x, y]) Color.BLACK else Color.WHITE + } + } + val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + bitmap.setPixels(pixels, 0, width, 0, 0, width, height) + return bitmap + } + + /** + * Provides a string which contains json data for creating a [Beneficiary] + * @param accountNumber Account Number of client + * @param officeName Office Name of Client + * @param accountType [org.mifos.mobile.ui.enums.AccountType] i.e. SAVINGS or LOAN + * @return Returns a string with account details + */ + fun getAccountDetailsInString( + accountNumber: String?, officeName: String?, + accountType: AccountType + ): String { + var accountId = -1 + if (accountType === AccountType.SAVINGS) { + accountId = 0 + } else if (accountType === AccountType.LOAN) { + accountId = 1 + } + val type = org.mifos.mobile.models.templates.account.AccountType() + type.id = accountId + val payload = Beneficiary() + payload.accountNumber = accountNumber + payload.accountType = type + payload.officeName = officeName + val gson = Gson() + return gson.toJson(payload) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/RecyclerItemClickListener.java b/app/src/main/java/org/mifos/mobile/utils/RecyclerItemClickListener.java deleted file mode 100644 index 65fc1c980f..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/RecyclerItemClickListener.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; - -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.RecyclerView; - -/** - * Created by vjs3 on 20/6/16. - */ - -public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { - - protected OnItemClickListener listener; - - private GestureDetector gestureDetector; - - @Nullable - private View childView; - - private int childViewPosition; - - public RecyclerItemClickListener(Context context, OnItemClickListener listener) { - this.gestureDetector = new GestureDetector(context, new GestureListener()); - this.listener = listener; - } - - @Override - public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent event) { - childView = view.findChildViewUnder(event.getX(), event.getY()); - childViewPosition = view.getChildAdapterPosition(childView); - - return childView != null && gestureDetector.onTouchEvent(event); - } - - @Override - public void onTouchEvent(RecyclerView view, MotionEvent event) { - // Not needed. - } - - @Override - public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { - - } - - /** - * A click listener for items. - */ - public interface OnItemClickListener { - - /** - * Called when an item is clicked. - * - * @param childView View of the item that was clicked. - * @param position Position of the item that was clicked. - */ - void onItemClick(View childView, int position); - - /** - * Called when an item is long pressed. - * - * @param childView View of the item that was long pressed. - * @param position Position of the item that was long pressed. - */ - void onItemLongPress(View childView, int position); - - } - - /** - * A simple click listener whose methods can be overridden one by one. - */ - public abstract static class SimpleOnItemClickListener implements OnItemClickListener { - - /** - * Called when an item is clicked. The default implementation is a no-op. - * - * @param childView View of the item that was clicked. - * @param position Position of the item that was clicked. - */ - public void onItemClick(View childView, int position) { - // Do nothing. - } - - /** - * Called when an item is long pressed. The default implementation is a no-op. - * - * @param childView View of the item that was long pressed. - * @param position Position of the item that was long pressed. - */ - public void onItemLongPress(View childView, int position) { - // Do nothing. - } - - } - - protected class GestureListener extends GestureDetector.SimpleOnGestureListener { - - @Override - public boolean onSingleTapUp(MotionEvent event) { - if (childView != null) { - listener.onItemClick(childView, childViewPosition); - } - - return true; - } - - @Override - public void onLongPress(MotionEvent event) { - if (childView != null) { - listener.onItemLongPress(childView, childViewPosition); - } - } - - @Override - public boolean onDown(MotionEvent event) { - // Best practice to always return true here. - // http://developer.android.com/training/gestures/detector.html#detect - return true; - } - - } - -} diff --git a/app/src/main/java/org/mifos/mobile/utils/RecyclerItemClickListener.kt b/app/src/main/java/org/mifos/mobile/utils/RecyclerItemClickListener.kt new file mode 100644 index 0000000000..9a66f062a2 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/RecyclerItemClickListener.kt @@ -0,0 +1,102 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.view.GestureDetector +import android.view.GestureDetector.SimpleOnGestureListener +import android.view.MotionEvent +import android.view.View +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener + +/** + * Created by vjs3 on 20/6/16. + */ +class RecyclerItemClickListener(context: Context?, listener: OnItemClickListener) : OnItemTouchListener { + private var listener: OnItemClickListener + private val gestureDetector: GestureDetector + private var childView: View? = null + private var childViewPosition = 0 + override fun onInterceptTouchEvent(view: RecyclerView, event: MotionEvent): Boolean { + childView = view.findChildViewUnder(event.x, event.y) + if (childView!=null) childViewPosition = view.getChildAdapterPosition(childView!!) + return childView != null && gestureDetector.onTouchEvent(event) + } + + override fun onTouchEvent(view: RecyclerView, event: MotionEvent) { + // Not needed. + } + + override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {} + + /** + * A click listener for items. + */ + interface OnItemClickListener { + /** + * Called when an item is clicked. + * + * @param childView View of the item that was clicked. + * @param position Position of the item that was clicked. + */ + fun onItemClick(childView: View?, position: Int) + + /** + * Called when an item is long pressed. + * + * @param childView View of the item that was long pressed. + * @param position Position of the item that was long pressed. + */ + fun onItemLongPress(childView: View?, position: Int) + } + + /** + * A simple click listener whose methods can be overridden one by one. + */ + abstract class SimpleOnItemClickListener : OnItemClickListener { + /** + * Called when an item is clicked. The default implementation is a no-op. + * + * @param childView View of the item that was clicked. + * @param position Position of the item that was clicked. + */ + override fun onItemClick(childView: View?, position: Int) { + // Do nothing. + } + + /** + * Called when an item is long pressed. The default implementation is a no-op. + * + * @param childView View of the item that was long pressed. + * @param position Position of the item that was long pressed. + */ + override fun onItemLongPress(childView: View?, position: Int) { + // Do nothing. + } + } + + protected inner class GestureListener : SimpleOnGestureListener() { + override fun onSingleTapUp(event: MotionEvent): Boolean { + if (childView != null) { + listener.onItemClick(childView, childViewPosition) + } + return true + } + + override fun onLongPress(event: MotionEvent) { + if (childView != null) { + listener.onItemLongPress(childView, childViewPosition) + } + } + + override fun onDown(event: MotionEvent): Boolean { + // Best practice to always return true here. + // http://developer.android.com/training/gestures/detector.html#detect + return true + } + } + + init { + gestureDetector = GestureDetector(context, GestureListener()) + this.listener = listener + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/RxBus.kt b/app/src/main/java/org/mifos/mobile/utils/RxBus.kt index 0448d0c805..b065637d77 100644 --- a/app/src/main/java/org/mifos/mobile/utils/RxBus.kt +++ b/app/src/main/java/org/mifos/mobile/utils/RxBus.kt @@ -14,12 +14,12 @@ object RxBus { private val publisher = PublishSubject.create() @JvmStatic - fun publish(event: Any) { - publisher.onNext(event) + fun publish(event: Any?) { + if (event != null) publisher.onNext(event) } @JvmStatic - fun listen(eventType: Class): Observable { + fun listen(eventType: Class): Observable { return publisher.ofType(eventType) } diff --git a/app/src/main/java/org/mifos/mobile/utils/RxEvent.kt b/app/src/main/java/org/mifos/mobile/utils/RxEvent.kt index 8a2eca82d1..7814aabd9d 100644 --- a/app/src/main/java/org/mifos/mobile/utils/RxEvent.kt +++ b/app/src/main/java/org/mifos/mobile/utils/RxEvent.kt @@ -8,9 +8,9 @@ import org.mifos.mobile.models.guarantor.GuarantorApplicationPayload class RxEvent { - data class AddGuarantorEvent(var payload: GuarantorApplicationPayload, var index: Int) + data class AddGuarantorEvent(var payload: GuarantorApplicationPayload?, var index: Int?) - data class DeleteGuarantorEvent(var index: Int) + data class DeleteGuarantorEvent(var index: Int?) - data class UpdateGuarantorEvent(var payload: GuarantorApplicationPayload, var index: Int) + data class UpdateGuarantorEvent(var payload: GuarantorApplicationPayload?, var index: Int?) } diff --git a/app/src/main/java/org/mifos/mobile/utils/ScrollFabBehavior.java b/app/src/main/java/org/mifos/mobile/utils/ScrollFabBehavior.java deleted file mode 100644 index ea38d701bf..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/ScrollFabBehavior.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.View; - -import com.google.android.material.floatingactionbutton.FloatingActionButton; - -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.core.view.ViewCompat; - -/** - * Created by dilpreet on 23/8/17. - */ - -public class ScrollFabBehavior extends FloatingActionButton.Behavior { - - public ScrollFabBehavior(Context context, AttributeSet attrs) { - super(); - } - - @Override - public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, - FloatingActionButton child, View directTargetChild, - View target, int nestedScrollAxes) { - return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || - super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, - nestedScrollAxes); - } - - @Override - public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, - View target, int dxConsumed, int dyConsumed, int dxUnconsumed, - int dyUnconsumed) { - super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, - dyUnconsumed); - if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) { - // Reason to set fab visiblity as INVISIBLE : - // https://stackoverflow.com/a/41386278/4672688 - child.hide(new FloatingActionButton.OnVisibilityChangedListener() { - @Override - public void onHidden(FloatingActionButton fab) { - super.onHidden(fab); - fab.setVisibility(View.INVISIBLE); - } - }); - } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) { - child.show(); - } - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/ScrollFabBehavior.kt b/app/src/main/java/org/mifos/mobile/utils/ScrollFabBehavior.kt new file mode 100644 index 0000000000..222746b2cd --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/ScrollFabBehavior.kt @@ -0,0 +1,45 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.util.AttributeSet +import android.view.View +import androidx.coordinatorlayout.widget.CoordinatorLayout +import androidx.core.view.ViewCompat +import com.google.android.material.floatingactionbutton.FloatingActionButton +import com.google.android.material.floatingactionbutton.FloatingActionButton.OnVisibilityChangedListener + +/** + * Created by dilpreet on 23/8/17. + */ +class ScrollFabBehavior(context: Context?, attrs: AttributeSet?) : FloatingActionButton.Behavior() { + override fun onStartNestedScroll( + coordinatorLayout: CoordinatorLayout, + child: FloatingActionButton, directTargetChild: View, + target: View, nestedScrollAxes: Int + ): Boolean { + return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || + super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, + nestedScrollAxes) + } + + override fun onNestedScroll( + coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, + target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, + dyUnconsumed: Int + ) { + super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, + dyUnconsumed) + if (dyConsumed > 0 && child.visibility == View.VISIBLE) { + // Reason to set fab visiblity as INVISIBLE : + // https://stackoverflow.com/a/41386278/4672688 + child.hide(object : OnVisibilityChangedListener() { + override fun onHidden(fab: FloatingActionButton) { + super.onHidden(fab) + fab.visibility = View.INVISIBLE + } + }) + } else if (dyConsumed < 0 && child.visibility != View.VISIBLE) { + child.show() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/StatusUtils.java b/app/src/main/java/org/mifos/mobile/utils/StatusUtils.java deleted file mode 100644 index 7b6c752579..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/StatusUtils.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.CheckboxStatus; - -import java.util.ArrayList; -import java.util.List; - -import androidx.core.content.ContextCompat; - -/** - * Created by dilpreet on 3/7/17. - */ - -public class StatusUtils { - public static List getSavingsAccountStatusList(Context context) { - ArrayList arrayList = new ArrayList<>(); - arrayList.add(new CheckboxStatus(context.getString(R.string.active), ContextCompat. - getColor(context, R.color.deposit_green))); - arrayList.add(new CheckboxStatus(context.getString(R.string.approved), ContextCompat. - getColor(context, R.color.light_green))); - arrayList.add(new CheckboxStatus(context.getString(R.string.approval_pending), ContextCompat - .getColor(context, R.color.light_yellow))); - arrayList.add(new CheckboxStatus(context.getString(R.string.matured), ContextCompat. - getColor(context, R.color.red_light))); - arrayList.add(new CheckboxStatus(context.getString(R.string.closed), ContextCompat. - getColor(context, R.color.black))); - - return arrayList; - } - - public static List getLoanAccountStatusList(Context context) { - ArrayList arrayList = new ArrayList<>(); - arrayList.add(new CheckboxStatus(context.getString(R.string.in_arrears), ContextCompat. - getColor(context, R.color.red))); - arrayList.add(new CheckboxStatus(context.getString(R.string.active), ContextCompat. - getColor(context, R.color.deposit_green))); - arrayList.add(new CheckboxStatus(context.getString(R.string.waiting_for_disburse), - ContextCompat.getColor(context, R.color.blue))); - arrayList.add(new CheckboxStatus(context.getString(R.string.approval_pending), ContextCompat - .getColor(context, R.color.light_yellow))); - arrayList.add(new CheckboxStatus(context.getString(R.string.overpaid), ContextCompat. - getColor(context, R.color.purple))); - arrayList.add(new CheckboxStatus(context.getString(R.string.closed), ContextCompat. - getColor(context, R.color.black))); - arrayList.add(new CheckboxStatus(context.getString(R.string.withdrawn), ContextCompat. - getColor(context, R.color.gray_dark))); - - return arrayList; - } - - public static List getShareAccountStatusList(Context context) { - ArrayList arrayList = new ArrayList<>(); - arrayList.add(new CheckboxStatus(context.getString(R.string.active), ContextCompat. - getColor(context, R.color.deposit_green))); - arrayList.add(new CheckboxStatus(context.getString(R.string.approved), ContextCompat. - getColor(context, R.color.light_green))); - arrayList.add(new CheckboxStatus(context.getString(R.string.approval_pending), ContextCompat - .getColor(context, R.color.light_yellow))); - arrayList.add(new CheckboxStatus(context.getString(R.string.closed), ContextCompat. - getColor(context, R.color.light_blue))); - - return arrayList; - } - - public static List getSavingsAccountTransactionList(Context context) { - ArrayList arrayList = new ArrayList<>(); - arrayList.add(new CheckboxStatus(context.getString(R.string.deposit), ContextCompat - .getColor(context, R.color.deposit_green))); - arrayList.add(new CheckboxStatus(context.getString(R.string.dividend_payout), ContextCompat - .getColor(context, R.color.red_light))); - arrayList.add(new CheckboxStatus(context.getString(R.string.withdrawal), ContextCompat - .getColor(context, R.color.red_light))); - arrayList.add(new CheckboxStatus(context.getString(R.string.interest_posting), - ContextCompat.getColor(context, R.color.green_light))); - arrayList.add(new CheckboxStatus(context.getString(R.string.fee_deduction), ContextCompat - .getColor(context, R.color.red_light))); - arrayList.add(new CheckboxStatus(context.getString(R.string.withdrawal_transfer), - ContextCompat.getColor(context, R.color.red_light))); - arrayList.add(new CheckboxStatus(context.getString(R.string.rejected_transfer), - ContextCompat.getColor(context, R.color.green_light))); - arrayList.add(new CheckboxStatus(context.getString(R.string.overdraft_fee), ContextCompat - .getColor(context, R.color.red_light))); - - return arrayList; - - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/StatusUtils.kt b/app/src/main/java/org/mifos/mobile/utils/StatusUtils.kt new file mode 100644 index 0000000000..f856758682 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/StatusUtils.kt @@ -0,0 +1,71 @@ +package org.mifos.mobile.utils + +import android.content.Context +import androidx.core.content.ContextCompat + +import org.mifos.mobile.R +import org.mifos.mobile.models.CheckboxStatus + +import java.util.* + +/** + * Created by dilpreet on 3/7/17. + */ +object StatusUtils { + + fun getSavingsAccountStatusList(context: Context?): List { + val arrayList = ArrayList() + arrayList.add(CheckboxStatus(context?.getString(R.string.active), ContextCompat.getColor(context!!, R.color.deposit_green))) + arrayList.add(CheckboxStatus(context.getString(R.string.approved), ContextCompat.getColor(context, R.color.light_green))) + arrayList.add(CheckboxStatus(context.getString(R.string.approval_pending), ContextCompat + .getColor(context, R.color.light_yellow))) + arrayList.add(CheckboxStatus(context.getString(R.string.matured), ContextCompat.getColor(context, R.color.red_light))) + arrayList.add(CheckboxStatus(context.getString(R.string.closed), ContextCompat.getColor(context, R.color.black))) + return arrayList + } + + fun getLoanAccountStatusList(context: Context?): List { + val arrayList = ArrayList() + arrayList.add(CheckboxStatus(context?.getString(R.string.in_arrears), ContextCompat.getColor(context!!, R.color.red))) + arrayList.add(CheckboxStatus(context.getString(R.string.active), ContextCompat.getColor(context, R.color.deposit_green))) + arrayList.add(CheckboxStatus(context.getString(R.string.waiting_for_disburse), + ContextCompat.getColor(context, R.color.blue))) + arrayList.add(CheckboxStatus(context.getString(R.string.approval_pending), ContextCompat + .getColor(context, R.color.light_yellow))) + arrayList.add(CheckboxStatus(context.getString(R.string.overpaid), ContextCompat.getColor(context, R.color.purple))) + arrayList.add(CheckboxStatus(context.getString(R.string.closed), ContextCompat.getColor(context, R.color.black))) + arrayList.add(CheckboxStatus(context.getString(R.string.withdrawn), ContextCompat.getColor(context, R.color.gray_dark))) + return arrayList + } + + fun getShareAccountStatusList(context: Context?): List { + val arrayList = ArrayList() + arrayList.add(CheckboxStatus(context?.getString(R.string.active), ContextCompat.getColor(context!!, R.color.deposit_green))) + arrayList.add(CheckboxStatus(context.getString(R.string.approved), ContextCompat.getColor(context, R.color.light_green))) + arrayList.add(CheckboxStatus(context.getString(R.string.approval_pending), ContextCompat + .getColor(context, R.color.light_yellow))) + arrayList.add(CheckboxStatus(context.getString(R.string.closed), ContextCompat.getColor(context, R.color.light_blue))) + return arrayList + } + + fun getSavingsAccountTransactionList(context: Context?): List { + val arrayList = ArrayList() + arrayList.add(CheckboxStatus(context?.getString(R.string.deposit), ContextCompat + .getColor(context!!, R.color.deposit_green))) + arrayList.add(CheckboxStatus(context.getString(R.string.dividend_payout), ContextCompat + .getColor(context, R.color.red_light))) + arrayList.add(CheckboxStatus(context.getString(R.string.withdrawal), ContextCompat + .getColor(context, R.color.red_light))) + arrayList.add(CheckboxStatus(context.getString(R.string.interest_posting), + ContextCompat.getColor(context, R.color.green_light))) + arrayList.add(CheckboxStatus(context.getString(R.string.fee_deduction), ContextCompat + .getColor(context, R.color.red_light))) + arrayList.add(CheckboxStatus(context.getString(R.string.withdrawal_transfer), + ContextCompat.getColor(context, R.color.red_light))) + arrayList.add(CheckboxStatus(context.getString(R.string.rejected_transfer), + ContextCompat.getColor(context, R.color.green_light))) + arrayList.add(CheckboxStatus(context.getString(R.string.overdraft_fee), ContextCompat + .getColor(context, R.color.red_light))) + return arrayList + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/SymbolsUtils.java b/app/src/main/java/org/mifos/mobile/utils/SymbolsUtils.java deleted file mode 100644 index 99d34c60a5..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/SymbolsUtils.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.mifos.mobile.utils; - -/** - * Created by Rajan Maurya on 05/03/17. - */ - -public class SymbolsUtils { - - public static final String PERCENT = "%"; -} diff --git a/app/src/main/java/org/mifos/mobile/utils/SymbolsUtils.kt b/app/src/main/java/org/mifos/mobile/utils/SymbolsUtils.kt new file mode 100644 index 0000000000..dd17492cb1 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/SymbolsUtils.kt @@ -0,0 +1,8 @@ +package org.mifos.mobile.utils + +/** + * Created by Rajan Maurya on 05/03/17. + */ +object SymbolsUtils { + const val PERCENT = "%" +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/TextDrawable.java b/app/src/main/java/org/mifos/mobile/utils/TextDrawable.java deleted file mode 100644 index 9eb3193525..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/TextDrawable.java +++ /dev/null @@ -1,319 +0,0 @@ -package org.mifos.mobile.utils; - - -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.ColorFilter; -import android.graphics.Paint; -import android.graphics.PixelFormat; -import android.graphics.Rect; -import android.graphics.RectF; -import android.graphics.Typeface; -import android.graphics.drawable.ShapeDrawable; -import android.graphics.drawable.shapes.OvalShape; -import android.graphics.drawable.shapes.RectShape; -import android.graphics.drawable.shapes.RoundRectShape; - -public class TextDrawable extends ShapeDrawable { - - private final Paint textPaint; - private final Paint borderPaint; - private static final float SHADE_FACTOR = 0.9f; - private final String text; - private final int color; - private final RectShape shape; - private final int height; - private final int width; - private final int fontSize; - private final float radius; - private final int borderThickness; - - private TextDrawable(Builder builder) { - super(builder.shape); - - // shape properties - shape = builder.shape; - height = builder.iconHeight; - width = builder.iconWidth; - radius = builder.radius; - - // text and color - text = builder.iconToUpperCase ? builder.text.toUpperCase() : builder.text; - color = builder.color; - - // text paint settings - fontSize = builder.iconFontSize; - textPaint = new Paint(); - textPaint.setColor(builder.iconTextColor); - textPaint.setAntiAlias(true); - textPaint.setFakeBoldText(builder.isBold); - textPaint.setStyle(Paint.Style.FILL); - textPaint.setTypeface(builder.font); - textPaint.setTextAlign(Paint.Align.CENTER); - textPaint.setStrokeWidth(builder.borderThickness); - - // border paint settings - borderThickness = builder.borderThickness; - borderPaint = new Paint(); - borderPaint.setColor(getDarkerShade(color)); - borderPaint.setStyle(Paint.Style.STROKE); - borderPaint.setStrokeWidth(borderThickness); - - // drawable paint color - Paint paint = getPaint(); - paint.setColor(color); - - } - - private int getDarkerShade(int color) { - return Color.rgb((int) (SHADE_FACTOR * Color.red(color)), - (int) (SHADE_FACTOR * Color.green(color)), - (int) (SHADE_FACTOR * Color.blue(color))); - } - - @Override - public void draw(Canvas canvas) { - super.draw(canvas); - Rect r = getBounds(); - - - // draw border - if (borderThickness > 0) { - drawBorder(canvas); - } - - int count = canvas.save(); - canvas.translate(r.left, r.top); - - // draw text - int width = this.width < 0 ? r.width() : this.width; - int height = this.height < 0 ? r.height() : this.height; - int fontSize = this.fontSize < 0 ? (Math.min(width, height) / 2) : this.fontSize; - textPaint.setTextSize(fontSize); - canvas.drawText(text, width / 2, - height / 2 - ((textPaint.descent() + textPaint.ascent()) / 2), textPaint); - - canvas.restoreToCount(count); - - } - - private void drawBorder(Canvas canvas) { - RectF rect = new RectF(getBounds()); - rect.inset(borderThickness / 2, borderThickness / 2); - - if (shape instanceof OvalShape) { - canvas.drawOval(rect, borderPaint); - } else if (shape instanceof RoundRectShape) { - canvas.drawRoundRect(rect, radius, radius, borderPaint); - } else { - canvas.drawRect(rect, borderPaint); - } - } - - @Override - public void setAlpha(int alpha) { - textPaint.setAlpha(alpha); - } - - @Override - public void setColorFilter(ColorFilter cf) { - textPaint.setColorFilter(cf); - } - - @Override - public int getOpacity() { - return PixelFormat.TRANSLUCENT; - } - - @Override - public int getIntrinsicWidth() { - return width; - } - - @Override - public int getIntrinsicHeight() { - return height; - } - - public static IShapeBuilder builder() { - return new Builder(); - } - - public static class Builder implements IConfigBuilder, IShapeBuilder, IBuilder { - - private String text; - - private int color; - - private int borderThickness; - - private int iconWidth; - - private int iconHeight; - - private Typeface font; - - private RectShape shape; - - public int iconTextColor; - - private int iconFontSize; - - private boolean isBold; - - private boolean iconToUpperCase; - - public float radius; - - private Builder() { - text = ""; - color = Color.GRAY; - iconTextColor = Color.WHITE; - borderThickness = 0; - iconWidth = -1; - iconHeight = -1; - shape = new RectShape(); - font = Typeface.create("sans-serif-light", Typeface.NORMAL); - iconFontSize = -1; - isBold = false; - iconToUpperCase = false; - } - - public IConfigBuilder width(int width) { - this.iconWidth = width; - return this; - } - - public IConfigBuilder height(int height) { - this.iconHeight = height; - return this; - } - - public IConfigBuilder textColor(int color) { - this.iconTextColor = color; - return this; - } - - public IConfigBuilder withBorder(int thickness) { - this.borderThickness = thickness; - return this; - } - - public IConfigBuilder useFont(Typeface font) { - this.font = font; - return this; - } - - public IConfigBuilder fontSize(int size) { - this.iconFontSize = size; - return this; - } - - public IConfigBuilder bold() { - this.isBold = true; - return this; - } - - public IConfigBuilder toUpperCase() { - this.iconToUpperCase = true; - return this; - } - - @Override - public IConfigBuilder beginConfig() { - return this; - } - - @Override - public IShapeBuilder endConfig() { - return this; - } - - @Override - public IBuilder rect() { - this.shape = new RectShape(); - return this; - } - - @Override - public IBuilder round() { - this.shape = new OvalShape(); - return this; - } - - @Override - public IBuilder roundRect(int radius) { - this.radius = radius; - float[] radii = {radius, radius, radius, radius, radius, radius, radius, radius}; - this.shape = new RoundRectShape(radii, null, null); - return this; - } - - @Override - public TextDrawable buildRect(String text, int color) { - rect(); - return build(text, color); - } - - @Override - public TextDrawable buildRoundRect(String text, int color, int radius) { - roundRect(radius); - return build(text, color); - } - - @Override - public TextDrawable buildRound(String text, int color) { - round(); - return build(text, color); - } - - @Override - public TextDrawable build(String text, int color) { - this.color = color; - this.text = text; - return new TextDrawable(this); - } - } - - public interface IConfigBuilder { - IConfigBuilder width(int width); - - IConfigBuilder height(int height); - - IConfigBuilder textColor(int color); - - IConfigBuilder withBorder(int thickness); - - IConfigBuilder useFont(Typeface font); - - IConfigBuilder fontSize(int size); - - IConfigBuilder bold(); - - IConfigBuilder toUpperCase(); - - IShapeBuilder endConfig(); - } - - public static interface IBuilder { - - TextDrawable build(String text, int color); - } - - public static interface IShapeBuilder { - - IConfigBuilder beginConfig(); - - IBuilder rect(); - - IBuilder round(); - - IBuilder roundRect(int radius); - - TextDrawable buildRect(String text, int color); - - TextDrawable buildRoundRect(String text, int color, int radius); - - TextDrawable buildRound(String text, int color); - } -} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/TextDrawable.kt b/app/src/main/java/org/mifos/mobile/utils/TextDrawable.kt new file mode 100644 index 0000000000..686fccd78a --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/TextDrawable.kt @@ -0,0 +1,261 @@ +package org.mifos.mobile.utils + +import android.graphics.* +import android.graphics.drawable.ShapeDrawable +import android.graphics.drawable.shapes.OvalShape +import android.graphics.drawable.shapes.RectShape +import android.graphics.drawable.shapes.RoundRectShape +import java.util.* + +class TextDrawable private constructor(builder: Builder) : ShapeDrawable(builder.shape) { + private val textPaint: Paint + private val borderPaint: Paint + private val text: String + private val color: Int + private val shape: RectShape + private val height: Int + private val width: Int + private val fontSize: Int + private val radius: Float + private val borderThickness: Int + private fun getDarkerShade(color: Int): Int { + return Color.rgb((SHADE_FACTOR * Color.red(color)).toInt(), + (SHADE_FACTOR * Color.green(color)).toInt(), + (SHADE_FACTOR * Color.blue(color)).toInt()) + } + + override fun draw(canvas: Canvas) { + super.draw(canvas) + val r = bounds + + + // draw border + if (borderThickness > 0) { + drawBorder(canvas) + } + val count = canvas.save() + canvas.translate(r.left.toFloat(), r.top.toFloat()) + + // draw text + val width = if (width < 0) r.width() else width + val height = if (height < 0) r.height() else height + val fontSize = if (fontSize < 0) Math.min(width, height) / 2 else fontSize + textPaint.textSize = fontSize.toFloat() + canvas.drawText(text, width / 2.toFloat(), + height / 2 - (textPaint.descent() + textPaint.ascent()) / 2, textPaint) + canvas.restoreToCount(count) + } + + private fun drawBorder(canvas: Canvas) { + val rect = RectF(bounds) + rect.inset(borderThickness / 2.toFloat(), borderThickness / 2.toFloat()) + if (shape is OvalShape) { + canvas.drawOval(rect, borderPaint) + } else if (shape is RoundRectShape) { + canvas.drawRoundRect(rect, radius, radius, borderPaint) + } else { + canvas.drawRect(rect, borderPaint) + } + } + + override fun setAlpha(alpha: Int) { + textPaint.alpha = alpha + } + + override fun setColorFilter(cf: ColorFilter) { + textPaint.colorFilter = cf + } + + override fun getOpacity(): Int { + return PixelFormat.TRANSLUCENT + } + + override fun getIntrinsicWidth(): Int { + return width + } + + override fun getIntrinsicHeight(): Int { + return height + } + + class Builder : IConfigBuilder, IShapeBuilder, IBuilder { + var text = "" + var color: Int + var borderThickness: Int + var iconWidth: Int + var iconHeight: Int + var font: Typeface + var shape: RectShape + var iconTextColor: Int + var iconFontSize: Int + var isBold: Boolean + var iconToUpperCase: Boolean + var radius = 0f + override fun width(width: Int): IConfigBuilder { + iconWidth = width + return this + } + + override fun height(height: Int): IConfigBuilder { + iconHeight = height + return this + } + + override fun textColor(color: Int): IConfigBuilder { + iconTextColor = color + return this + } + + override fun withBorder(thickness: Int): IConfigBuilder { + borderThickness = thickness + return this + } + + override fun useFont(font: Typeface): IConfigBuilder { + this.font = font + return this + } + + override fun fontSize(size: Int): IConfigBuilder { + iconFontSize = size + return this + } + + override fun bold(): IConfigBuilder { + isBold = true + return this + } + + override fun toUpperCase(): IConfigBuilder { + iconToUpperCase = true + return this + } + + override fun beginConfig(): IConfigBuilder { + return this + } + + override fun endConfig(): IShapeBuilder { + return this + } + + override fun rect(): IBuilder { + shape = RectShape() + return this + } + + override fun round(): IBuilder { + shape = OvalShape() + return this + } + + override fun roundRect(radius: Int): IBuilder { + this.radius = radius.toFloat() + val radii = floatArrayOf(radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat(), radius.toFloat()) + shape = RoundRectShape(radii, null, null) + return this + } + + override fun buildRect(text: String, color: Int): TextDrawable { + rect() + return build(text, color) + } + + override fun buildRoundRect(text: String, color: Int, radius: Int): TextDrawable { + roundRect(radius) + return build(text, color) + } + + override fun buildRound(text: String?, color: Int): TextDrawable { + round() + return build(text!!, color) + } + + override fun build(text: String, color: Int): TextDrawable { + this.color = color + this.text = text + return TextDrawable(this) + } + + init { + color = Color.GRAY + iconTextColor = Color.WHITE + borderThickness = 0 + iconWidth = -1 + iconHeight = -1 + shape = RectShape() + font = Typeface.create("sans-serif-light", Typeface.NORMAL) + iconFontSize = -1 + isBold = false + iconToUpperCase = false + } + } + + interface IConfigBuilder { + fun width(width: Int): IConfigBuilder + fun height(height: Int): IConfigBuilder + fun textColor(color: Int): IConfigBuilder + fun withBorder(thickness: Int): IConfigBuilder + fun useFont(font: Typeface): IConfigBuilder + fun fontSize(size: Int): IConfigBuilder + fun bold(): IConfigBuilder + fun toUpperCase(): IConfigBuilder + fun endConfig(): IShapeBuilder + } + + interface IBuilder { + fun build(text: String, color: Int): TextDrawable + } + + interface IShapeBuilder { + fun beginConfig(): IConfigBuilder + fun rect(): IBuilder + fun round(): IBuilder + fun roundRect(radius: Int): IBuilder + fun buildRect(text: String, color: Int): TextDrawable + fun buildRoundRect(text: String, color: Int, radius: Int): TextDrawable + fun buildRound(text: String?, color: Int): TextDrawable + } + + companion object { + private const val SHADE_FACTOR = 0.9f + fun builder(): IShapeBuilder { + return Builder() + } + } + + init { + + // shape properties + shape = builder.shape + height = builder.iconHeight + width = builder.iconWidth + radius = builder.radius + + // text and color + text = if (builder.iconToUpperCase) builder.text.toUpperCase(Locale.ROOT) else builder.text + color = builder.color + + // text paint settings + fontSize = builder.iconFontSize + textPaint = Paint() + textPaint.color = builder.iconTextColor + textPaint.isAntiAlias = true + textPaint.isFakeBoldText = builder.isBold + textPaint.style = Paint.Style.FILL + textPaint.typeface = builder.font + textPaint.textAlign = Paint.Align.CENTER + textPaint.strokeWidth = builder.borderThickness.toFloat() + + // border paint settings + borderThickness = builder.borderThickness + borderPaint = Paint() + borderPaint.color = getDarkerShade(color) + borderPaint.style = Paint.Style.STROKE + borderPaint.strokeWidth = borderThickness.toFloat() + + // drawable paint color + val paint = paint + paint.color = color + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/Toaster.java b/app/src/main/java/org/mifos/mobile/utils/Toaster.java deleted file mode 100644 index 33ea8bc9f9..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/Toaster.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.graphics.Color; -import android.view.View; -import android.view.inputmethod.InputMethodManager; -import android.widget.TextView; - -import com.google.android.material.snackbar.Snackbar; - -import org.mifos.mobile.MifosSelfServiceApp; -import org.mifos.mobile.R; - -import java.util.ArrayList; - -public class Toaster { - - public static final int INDEFINITE = Snackbar.LENGTH_INDEFINITE; - public static final int LONG = Snackbar.LENGTH_LONG; - public static final int SHORT = Snackbar.LENGTH_SHORT; - private static ArrayList snackbarsQueue = new ArrayList<>(); - - public static void show(View view, String text, int duration) { - - InputMethodManager imm = (InputMethodManager) MifosSelfServiceApp.getContext(). - getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(view.getWindowToken(), 0); - - final Snackbar snackbar = Snackbar.make(view, text, duration); - View sbView = snackbar.getView(); - TextView textView = sbView.findViewById(R.id.snackbar_text); - textView.setTextColor(Color.WHITE); - textView.setTextSize(12); - snackbar.setAction("OK", new View.OnClickListener() { - @Override - public void onClick(View view) { - - } - }); - - snackbar.addCallback(new Snackbar.Callback() { - @Override - public void onShown(Snackbar sb) { - super.onShown(sb); - } - - @Override - public void onDismissed(Snackbar transientBottomBar, int event) { - - super.onDismissed(transientBottomBar, event); - - if (!snackbarsQueue.isEmpty()) { - - snackbarsQueue.remove(0); - - if (!snackbarsQueue.isEmpty()) { - - snackbarsQueue.get(0).show(); - } - } - } - }); - - snackbarsQueue.add(snackbar); - - if (!snackbarsQueue.get(0).isShown()) { - - snackbarsQueue.get(0).show(); - } - } - - public static void show(View view, int res, int duration) { - show(view, MifosSelfServiceApp.getContext().getResources().getString(res), duration); - } - - public static void cancelTransfer(View view, String text, String buttonText, - View.OnClickListener listener) { - final Snackbar snackbar = Snackbar.make(view, text, Snackbar.LENGTH_LONG); - snackbar.setAction(buttonText, listener); - snackbar.show(); - } - - public static void show(View view, String text) { - show(view, text, Snackbar.LENGTH_LONG); - } - - public static void show(View view, int res) { - show(view, MifosSelfServiceApp.getContext().getResources().getString(res)); - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/Toaster.kt b/app/src/main/java/org/mifos/mobile/utils/Toaster.kt new file mode 100644 index 0000000000..543c27c4c5 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/Toaster.kt @@ -0,0 +1,63 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.graphics.Color +import android.view.View +import android.view.inputmethod.InputMethodManager +import android.widget.TextView + +import com.google.android.material.snackbar.Snackbar +import org.mifos.mobile.MifosSelfServiceApp +import org.mifos.mobile.R +import java.util.* + +object Toaster { + + private val snackbarsQueue = ArrayList() + + @JvmOverloads + fun show(view: View?, text: String?, duration: Int = Snackbar.LENGTH_LONG) { + val imm = MifosSelfServiceApp.context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + imm.hideSoftInputFromWindow(view?.windowToken, 0) + val snackbar = Snackbar.make(view!!, text!!, duration) + val sbView = snackbar.view + val textView = sbView.findViewById(R.id.snackbar_text) + textView.setTextColor(Color.WHITE) + textView.textSize = 12f + snackbar.setAction("OK") { } + snackbar.addCallback(object : Snackbar.Callback() { + + override fun onDismissed(transientBottomBar: Snackbar, event: Int) { + super.onDismissed(transientBottomBar, event) + if (snackbarsQueue.isNotEmpty()) { + snackbarsQueue.removeAt(0) + if (snackbarsQueue.isNotEmpty()) { + snackbarsQueue[0].show() + } + } + } + }) + snackbarsQueue.add(snackbar) + if (!snackbarsQueue[0].isShown) { + snackbarsQueue[0].show() + } + } + + fun show(view: View, res: Int, duration: Int) { + show(view, MifosSelfServiceApp.context?.resources?.getString(res), duration) + } + + fun cancelTransfer( + view: View?, text: String?, buttonText: String?, + listener: View.OnClickListener? + ) { + val snackbar = Snackbar.make(view!!, text!!, Snackbar.LENGTH_LONG) + snackbar.setAction(buttonText, listener) + snackbar.show() + } + + + fun show(view: View?, res: Int) { + show(view, MifosSelfServiceApp.context?.resources?.getString(res)) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/Utils.java b/app/src/main/java/org/mifos/mobile/utils/Utils.java deleted file mode 100644 index 3d93c28529..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/Utils.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.mifos.mobile.utils; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.PorterDuff; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.LayerDrawable; -import android.net.Uri; -import android.util.Log; -import android.view.Menu; - -import org.mifos.mobile.R; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.text.DateFormatSymbols; - -import androidx.core.content.ContextCompat; -import androidx.core.content.FileProvider; - -/** - * Created by michaelsosnick on 12/12/16. - */ - -public class Utils { - public static String getMonth(int month) { - return new DateFormatSymbols().getMonths()[month - 1]; - } - - public static void setToolbarIconColor(Context context, Menu menu, int color) { - for (int i = 0; i < menu.size(); i++) { - Drawable drawable = menu.getItem(i).getIcon(); - if (drawable != null) { - drawable.mutate(); - drawable.setColorFilter( - ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN); - } - } - } - - public static LayerDrawable setCircularBackground(int colorId, Context context) { - Drawable color = new ColorDrawable(ContextCompat.getColor(context, colorId)); - Drawable image = ContextCompat.getDrawable(context, R.drawable.circular_background); - LayerDrawable ld = new LayerDrawable(new Drawable[]{image, color}); - return ld; - } - - - public static Uri getImageUri(Context context, Bitmap bitmap) { - try { - - File cachePath = new File(context.getCacheDir(), "images"); - cachePath.mkdirs(); - FileOutputStream stream = new FileOutputStream(cachePath + "/image.png"); - bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); - stream.close(); - } catch (IOException e) { - Log.d(Utils.class.getName(), e.toString()); - } - - File imagePath = new File(context.getCacheDir(), "images"); - File newFile = new File(imagePath, "image.png"); - - return FileProvider.getUriForFile(context, "org.mifos.mobilebanking.fileprovider", - newFile); - } - - public static String generateFormString(String[][] data) { - StringBuilder formString = new StringBuilder(); - formString.setLength(0); - for (String[] aData : data) { - formString.append(aData[0]).append(" : ").append(aData[1]).append('\n'); - } - return formString.toString(); - } - - public static String formatTransactionType(String type) { - StringBuilder builder = new StringBuilder(); - for (String str : type.toLowerCase().split("_")) { - builder.append(String.valueOf(str.charAt(0)).toUpperCase() + str.substring(1, - str.length()) + " "); - } - return builder.toString(); - } - -} diff --git a/app/src/main/java/org/mifos/mobile/utils/Utils.kt b/app/src/main/java/org/mifos/mobile/utils/Utils.kt new file mode 100644 index 0000000000..7c33d3c67f --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/Utils.kt @@ -0,0 +1,80 @@ +package org.mifos.mobile.utils + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.PorterDuff +import android.graphics.drawable.ColorDrawable +import android.graphics.drawable.Drawable +import android.graphics.drawable.LayerDrawable +import android.net.Uri +import android.util.Log +import android.view.Menu +import androidx.core.content.ContextCompat +import androidx.core.content.FileProvider +import org.mifos.mobile.R +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.text.DateFormatSymbols +import java.util.* + +/** + * Created by michaelsosnick on 12/12/16. + */ +object Utils { + fun getMonth(month: Int): String { + return DateFormatSymbols().months[month - 1] + } + + fun setToolbarIconColor(context: Context?, menu: Menu, color: Int) { + for (i in 0 until menu.size()) { + val drawable = menu.getItem(i).icon + if (drawable != null) { + drawable.mutate() + drawable.setColorFilter( + ContextCompat.getColor(context!!, color), PorterDuff.Mode.SRC_IN) + } + } + } + + fun setCircularBackground(colorId: Int, context: Context?): LayerDrawable { + val color: Drawable = ColorDrawable(ContextCompat.getColor(context!!, colorId)) + val image = ContextCompat.getDrawable(context, R.drawable.circular_background) + return LayerDrawable(arrayOf(image, color)) + } + + fun getImageUri(context: Context?, bitmap: Bitmap): Uri { + try { + val cachePath = File(context?.cacheDir, "images") + cachePath.mkdirs() + val stream = FileOutputStream("$cachePath/image.png") + bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) + stream.close() + } catch (e: IOException) { + Log.d(Utils::class.java.name, e.toString()) + } + val imagePath = File(context?.cacheDir, "images") + val newFile = File(imagePath, "image.png") + return FileProvider.getUriForFile(context!!, "org.mifos.mobilebanking.fileprovider", + newFile) + } + + fun generateFormString(data: Array>): String { + val formString = StringBuilder() + formString.setLength(0) + for (aData in data) { + formString.append(aData[0]).append(" : ").append(aData[1]).append('\n') + } + return formString.toString() + } + + @kotlin.jvm.JvmStatic + fun formatTransactionType(type: String?): String? { + val builder = StringBuilder() + for (str in type?.toLowerCase(Locale.ROOT)?.split("_".toRegex())?.toTypedArray()!!) { + builder.append(str[0].toString().toUpperCase(Locale.ROOT) + str.substring(1, + str.length) + " ") + } + return builder.toString() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/fcm/MifosFirebaseMessagingService.java b/app/src/main/java/org/mifos/mobile/utils/fcm/MifosFirebaseMessagingService.java deleted file mode 100644 index 6be6fd5200..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/fcm/MifosFirebaseMessagingService.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.mifos.mobile.utils.fcm; - -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.media.RingtoneManager; -import android.net.Uri; -import android.util.Log; - -import androidx.core.app.NotificationCompat; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import com.google.firebase.messaging.FirebaseMessagingService; -import com.google.firebase.messaging.RemoteMessage; - -import org.mifos.mobile.R; -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.ui.activities.HomeActivity; -import org.mifos.mobile.utils.Constants; - -import java.util.Map; - -public class MifosFirebaseMessagingService extends FirebaseMessagingService { - - private static final String TAG = MifosFirebaseMessagingService.class.getSimpleName(); - - // [START receive_message] - @Override - public void onMessageReceived(RemoteMessage remoteMessage) { - String from = remoteMessage.getFrom(); - Map data = remoteMessage.getData(); - - String message = data.get(getString(R.string.message)); - if (from.startsWith("/topics/")) { - // message received from some topic. - } else { - // normal downstream message. - } - - sendNotification(message); - Intent registrationComplete = new Intent(Constants.NOTIFY_HOME_FRAGMENT); - LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); - } - // [END receive_message] - - /** - * Create and show a simple notification containing the received FCM message. - * - * @param message FCM message received. - */ - private void sendNotification(String message) { - Intent intent = new Intent(this, HomeActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - intent.putExtra(getString(R.string.notification), true); - PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, - PendingIntent.FLAG_ONE_SHOT); - - Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); - NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) - .setSmallIcon(R.mipmap.mifos_icon) - .setContentTitle(getString(R.string.app_name)) - .setContentText(message) - .setAutoCancel(true) - .setSound(defaultSoundUri) - .setContentIntent(pendingIntent); - - NotificationManager notificationManager = - (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - - MifosNotification notification = new MifosNotification(); - notification.setMsg(message); - notification.setTimeStamp(System.currentTimeMillis()); - notification.setRead(false); - notification.save(); - - notificationManager.notify(0, notificationBuilder.build()); - } - - /** - * Called if InstanceID token is updated. This may occur if the security of - * the previous token had been compromised. Note that this is called when the InstanceID token - * is initially generated so this is where you would retrieve the token. - */ - @Override - public void onNewToken(String s) { - super.onNewToken(s); - Log.d(TAG, "Refreshed token: " + s); - Intent intent = new Intent(this, RegistrationIntentService.class); - startService(intent); - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/fcm/MifosFirebaseMessagingService.kt b/app/src/main/java/org/mifos/mobile/utils/fcm/MifosFirebaseMessagingService.kt new file mode 100644 index 0000000000..ef2283ce56 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/fcm/MifosFirebaseMessagingService.kt @@ -0,0 +1,92 @@ +/** + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.mifos.mobile.utils.fcm + +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.media.RingtoneManager +import android.util.Log +import androidx.core.app.NotificationCompat +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import com.google.firebase.messaging.FirebaseMessagingService +import com.google.firebase.messaging.RemoteMessage +import org.mifos.mobile.R +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.ui.activities.HomeActivity +import org.mifos.mobile.utils.Constants + +class MifosFirebaseMessagingService : FirebaseMessagingService() { + // [START receive_message] + override fun onMessageReceived(remoteMessage: RemoteMessage) { + val from = remoteMessage.from + val data = remoteMessage.data + val message = data[getString(R.string.message)] + if ((from?.startsWith("/topics/") == true)) { + // message received from some topic. + } else { + // normal downstream message. + } + sendNotification(message) + val registrationComplete = Intent(Constants.NOTIFY_HOME_FRAGMENT) + LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete) + } + // [END receive_message] + /** + * Create and show a simple notification containing the received FCM message. + * + * @param message FCM message received. + */ + private fun sendNotification(message: String?) { + val intent = Intent(this, HomeActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) + intent.putExtra(getString(R.string.notification), true) + val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, + PendingIntent.FLAG_ONE_SHOT) + val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) + val notificationBuilder = NotificationCompat.Builder(this) + .setSmallIcon(R.mipmap.mifos_icon) + .setContentTitle(getString(R.string.app_name)) + .setContentText(message) + .setAutoCancel(true) + .setSound(defaultSoundUri) + .setContentIntent(pendingIntent) + val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val notification = MifosNotification() + notification.msg = message + notification.timeStamp = System.currentTimeMillis() + notification.setRead(false) + notification.save() + notificationManager.notify(0, notificationBuilder.build()) + } + + /** + * Called if InstanceID token is updated. This may occur if the security of + * the previous token had been compromised. Note that this is called when the InstanceID token + * is initially generated so this is where you would retrieve the token. + */ + override fun onNewToken(s: String) { + super.onNewToken(s) + Log.d(TAG, "Refreshed token: $s") + val intent = Intent(this, RegistrationIntentService::class.java) + startService(intent) + } + + companion object { + private val TAG = MifosFirebaseMessagingService::class.java.simpleName + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/utils/fcm/RegistrationIntentService.java b/app/src/main/java/org/mifos/mobile/utils/fcm/RegistrationIntentService.java deleted file mode 100644 index df88b868f1..0000000000 --- a/app/src/main/java/org/mifos/mobile/utils/fcm/RegistrationIntentService.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.mifos.mobile.utils.fcm; - -import android.app.IntentService; -import android.content.Intent; -import android.util.Log; - -import androidx.annotation.NonNull; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import com.google.android.gms.tasks.OnCompleteListener; -import com.google.android.gms.tasks.Task; -import com.google.firebase.iid.FirebaseInstanceId; -import com.google.firebase.iid.InstanceIdResult; - -import org.mifos.mobile.utils.Constants; - - -public class RegistrationIntentService extends IntentService { - - private static final String TAG = "RegIntentService"; - - public RegistrationIntentService() { - super(TAG); - } - - @Override - protected void onHandleIntent(Intent intent) { - FirebaseInstanceId.getInstance().getInstanceId() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (!task.isSuccessful()) { - Log.w(TAG, "getInstanceId failed", task.getException()); - return; - } - - // Get new Instance ID token - String token = task.getResult().getToken(); - sendRegistrationToServer(token); - } - }); - } - - private void sendRegistrationToServer(String token) { - Intent registrationComplete = new Intent(Constants.REGISTER_ON_SERVER); - registrationComplete.putExtra(Constants.TOKEN, token); - LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); - } -} diff --git a/app/src/main/java/org/mifos/mobile/utils/fcm/RegistrationIntentService.kt b/app/src/main/java/org/mifos/mobile/utils/fcm/RegistrationIntentService.kt new file mode 100644 index 0000000000..cef5104e92 --- /dev/null +++ b/app/src/main/java/org/mifos/mobile/utils/fcm/RegistrationIntentService.kt @@ -0,0 +1,50 @@ +/** + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.mifos.mobile.utils.fcm + +import android.app.IntentService +import android.content.Intent +import android.util.Log +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import com.google.android.gms.tasks.OnCompleteListener +import com.google.firebase.iid.FirebaseInstanceId +import org.mifos.mobile.utils.Constants + +class RegistrationIntentService : IntentService(TAG) { + override fun onHandleIntent(intent: Intent) { + FirebaseInstanceId.getInstance().instanceId + .addOnCompleteListener(OnCompleteListener { task -> + if (!task.isSuccessful) { + Log.w(TAG, "getInstanceId failed", task.exception) + return@OnCompleteListener + } + + // Get new Instance ID token + val token = task.result?.token + sendRegistrationToServer(token) + }) + } + + private fun sendRegistrationToServer(token: String?) { + val registrationComplete = Intent(Constants.REGISTER_ON_SERVER) + registrationComplete.putExtra(Constants.TOKEN, token) + LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete) + } + + companion object { + private const val TAG = "RegIntentService" + } +} \ No newline at end of file diff --git a/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModel.kt b/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModel.kt index cabc1b6306..8725a662ab 100644 --- a/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModel.kt +++ b/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModel.kt @@ -8,7 +8,7 @@ import org.mifos.mobile.models.payload.LoansPayload import org.mifos.mobile.ui.enums.LoanState import javax.inject.Inject -class ReviewLoanApplicationViewModel @Inject constructor(var dataManager: DataManager) : ViewModel() { +class ReviewLoanApplicationViewModel @Inject constructor(var dataManager: DataManager?) : ViewModel() { private lateinit var loansPayload: LoansPayload private lateinit var loanState: LoanState @@ -49,13 +49,13 @@ class ReviewLoanApplicationViewModel @Inject constructor(var dataManager: DataMa fun getLoanState() = loanState - fun submitLoan(): Observable { + fun submitLoan(): Observable? { loansPayload.productName = null loansPayload.loanPurpose = null loansPayload.currency = null - if (loanState == LoanState.CREATE) - return dataManager.createLoansAccount(loansPayload) + return if (loanState == LoanState.CREATE) + dataManager?.createLoansAccount(loansPayload) else - return dataManager.updateLoanAccount(loanId, loansPayload) + dataManager?.updateLoanAccount(loanId, loansPayload) } } diff --git a/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModelFactory.kt b/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModelFactory.kt index 8e9e9298db..d7347bda83 100644 --- a/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModelFactory.kt +++ b/app/src/main/java/org/mifos/mobile/viewModels/ReviewLoanApplicationViewModelFactory.kt @@ -7,7 +7,7 @@ import org.mifos.mobile.injection.PerActivity import javax.inject.Inject @PerActivity -class ReviewLoanApplicationViewModelFactory @Inject constructor(private val dataManager: DataManager) +class ReviewLoanApplicationViewModelFactory @Inject constructor(private val dataManager: DataManager?) : ViewModelProvider.NewInstanceFactory() { override fun create(modelClass: Class): T { diff --git a/app/src/main/res/drawable-hdpi/ic_qrcode_scan_gray_dark.xml b/app/src/main/res/drawable-hdpi/ic_qrcode_scan_gray_dark.xml new file mode 100644 index 0000000000..d1797ea46e --- /dev/null +++ b/app/src/main/res/drawable-hdpi/ic_qrcode_scan_gray_dark.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_qrcode_scan.xml b/app/src/main/res/drawable/ic_qrcode_scan.xml index d1797ea46e..b8c098df4d 100644 --- a/app/src/main/res/drawable/ic_qrcode_scan.xml +++ b/app/src/main/res/drawable/ic_qrcode_scan.xml @@ -4,6 +4,6 @@ android:viewportWidth="24.0" android:viewportHeight="24.0"> diff --git a/app/src/main/res/layout/fragment_beneficiary_add_options.xml b/app/src/main/res/layout/fragment_beneficiary_add_options.xml index 67396a160a..5970c48b3f 100644 --- a/app/src/main/res/layout/fragment_beneficiary_add_options.xml +++ b/app/src/main/res/layout/fragment_beneficiary_add_options.xml @@ -79,7 +79,7 @@ + app:srcCompat="@drawable/ic_qrcode_scan_gray_dark"/> error(new - RuntimeException())); - - presenter.loadClientAccountDetails(); - - verify(mvpView).showProgress(); - verify(mvpView).hideProgress(); - verify(mvpView, never()).showTotalLoanSavings( - presenter.getLoanAccountDetails(accounts.getLoanAccounts()), - presenter.getSavingAccountDetails(accounts.getSavingsAccounts())); - verify(mvpView).showError(context.getString(R.string.error_fetching_accounts)); - } -} diff --git a/app/src/test/java/org/mifos/mobile/AccountOverviewPresenterTest.kt b/app/src/test/java/org/mifos/mobile/AccountOverviewPresenterTest.kt new file mode 100644 index 0000000000..c395176362 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/AccountOverviewPresenterTest.kt @@ -0,0 +1,81 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.presenters.AccountOverviewPresenter +import org.mifos.mobile.ui.views.AccountOverviewMvpView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by Chirag Gupta on 12/06/17. + */ +@RunWith(MockitoJUnitRunner::class) +class AccountOverviewPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var mvpView: AccountOverviewMvpView? = null + private var presenter: AccountOverviewPresenter? = null + private var accounts: ClientAccounts? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = AccountOverviewPresenter(context!!, dataManager!!) + presenter?.attachView(mvpView) + accounts = FakeRemoteDataSource.clientAccounts + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoadClientAccountDetails() { + Mockito.`when`(dataManager?.clientAccounts).thenReturn(Observable.just(accounts)) + presenter?.loadClientAccountDetails() + Mockito.verify(mvpView)?.showProgress() + Mockito.verify(mvpView)?.hideProgress() + Mockito.verify(mvpView)?.showTotalLoanSavings( + presenter?.getLoanAccountDetails(accounts?.loanAccounts), + presenter?.getSavingAccountDetails(accounts?.savingsAccounts)) + Mockito.verify(mvpView, Mockito.never())?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + @Test + fun testLoadClientAccountDetailsFail() { + Mockito.`when`(dataManager?.clientAccounts).thenReturn(Observable.error(RuntimeException())) + presenter?.loadClientAccountDetails() + Mockito.verify(mvpView)?.showProgress() + Mockito.verify(mvpView)?.hideProgress() + presenter?.getLoanAccountDetails(accounts?.loanAccounts)?.let { + Mockito.verify(mvpView, Mockito.never())?.showTotalLoanSavings( + it, + presenter?.getSavingAccountDetails(accounts?.savingsAccounts)!!) + } + Mockito.verify(mvpView)?.showError(context?.getString(R.string.error_fetching_accounts)) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/AccountsPresenterTest.java b/app/src/test/java/org/mifos/mobile/AccountsPresenterTest.java deleted file mode 100644 index 3f734441cc..0000000000 --- a/app/src/test/java/org/mifos/mobile/AccountsPresenterTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.client.ClientAccounts; -import org.mifos.mobile.presenters.AccountsPresenter; -import org.mifos.mobile.ui.views.AccountsView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mifos.mobile.utils.Constants; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 26/6/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class AccountsPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - AccountsView accountsView; - - private AccountsPresenter presenter; - private ClientAccounts accounts, savingsAccount, loanAccounts, shareAccounts; - - @Before - public void setUp() throws Exception { - presenter = new AccountsPresenter(context, dataManager); - presenter.attachView(accountsView); - - accounts = FakeRemoteDataSource.getClientAccounts(); - savingsAccount = FakeRemoteDataSource.getClientSavingsAccount(); - loanAccounts = FakeRemoteDataSource.getClientLoanAccount(); - shareAccounts = FakeRemoteDataSource.getClientShareAccount(); - - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testLoadClientAccounts() { - when(dataManager.getClientAccounts()).thenReturn(Observable.just(accounts)); - - presenter.loadClientAccounts(); - - verify(accountsView).showProgress(); - verify(accountsView).hideProgress(); - verify(accountsView).showSavingsAccounts(accounts.getSavingsAccounts()); - verify(accountsView).showLoanAccounts(accounts.getLoanAccounts()); - verify(accountsView).showShareAccounts(accounts.getShareAccounts()); - verify(accountsView, never()).showError(context.getString(R.string. - error_fetching_accounts)); - - } - - @Test - public void testLoadClientAccountsFail() { - when(dataManager.getClientAccounts()).thenReturn(Observable.error(new - RuntimeException())); - presenter.loadClientAccounts(); - - verify(accountsView).showProgress(); - verify(accountsView).hideProgress(); - verify(accountsView).showError(context.getString(R.string. - error_fetching_accounts)); - - } - - @Test - public void testLoadClientSavingsAccount() { - when(dataManager.getAccounts(Constants.SAVINGS_ACCOUNTS)). - thenReturn(Observable.just(savingsAccount)); - - presenter.loadAccounts(Constants.SAVINGS_ACCOUNTS); - - verify(accountsView).showProgress(); - verify(accountsView).hideProgress(); - verify(accountsView).showSavingsAccounts(savingsAccount.getSavingsAccounts()); - verify(accountsView, never()).showLoanAccounts(null); - verify(accountsView, never()).showShareAccounts(null); - verify(accountsView, never()).showError(context.getString(R.string. - error_fetching_accounts)); - - } - - @Test - public void testLoadClientLoanAccount() { - when(dataManager.getAccounts(Constants.LOAN_ACCOUNTS)). - thenReturn(Observable.just(loanAccounts)); - - presenter.loadAccounts(Constants.LOAN_ACCOUNTS); - - verify(accountsView).showProgress(); - verify(accountsView).hideProgress(); - verify(accountsView).showLoanAccounts(loanAccounts.getLoanAccounts()); - verify(accountsView, never()).showSavingsAccounts(null); - verify(accountsView, never()).showShareAccounts(null); - verify(accountsView, never()).showError(context.getString(R.string. - error_fetching_accounts)); - - } - - @Test - public void testLoadClientShareAccount() { - when(dataManager.getAccounts(Constants.SHARE_ACCOUNTS)). - thenReturn(Observable.just(shareAccounts)); - - presenter.loadAccounts(Constants.SHARE_ACCOUNTS); - - verify(accountsView).showProgress(); - verify(accountsView).hideProgress(); - verify(accountsView).showShareAccounts(shareAccounts.getShareAccounts()); - verify(accountsView, never()).showLoanAccounts(null); - verify(accountsView, never()).showSavingsAccounts(null); - verify(accountsView, never()).showError(context.getString(R.string. - error_fetching_accounts)); - - } - -} diff --git a/app/src/test/java/org/mifos/mobile/AccountsPresenterTest.kt b/app/src/test/java/org/mifos/mobile/AccountsPresenterTest.kt new file mode 100644 index 0000000000..f87fcc98b5 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/AccountsPresenterTest.kt @@ -0,0 +1,119 @@ +package org.mifos.mobile + +import android.content.Context +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.presenters.AccountsPresenter +import org.mifos.mobile.ui.views.AccountsView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mifos.mobile.utils.Constants + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 26/6/17. + */ +@RunWith(MockitoJUnitRunner::class) +class AccountsPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var accountsView: AccountsView? = null + private var presenter: AccountsPresenter? = null + private var accounts: ClientAccounts? = null + private var savingsAccount: ClientAccounts? = null + private var loanAccounts: ClientAccounts? = null + private var shareAccounts: ClientAccounts? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = AccountsPresenter(context!!, dataManager!!) + presenter?.attachView(accountsView) + accounts = FakeRemoteDataSource.clientAccounts + savingsAccount = FakeRemoteDataSource.clientSavingsAccount + loanAccounts = FakeRemoteDataSource.clientLoanAccount + shareAccounts = FakeRemoteDataSource.clientShareAccount + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoadClientAccounts() { + Mockito.`when`(dataManager?.clientAccounts).thenReturn(Observable.just(accounts)) + presenter?.loadClientAccounts() + Mockito.verify(accountsView)?.showProgress() + Mockito.verify(accountsView)?.hideProgress() + Mockito.verify(accountsView)?.showSavingsAccounts(accounts?.savingsAccounts) + Mockito.verify(accountsView)?.showLoanAccounts(accounts?.loanAccounts) + Mockito.verify(accountsView)?.showShareAccounts(accounts?.shareAccounts) + Mockito.verify(accountsView, Mockito.never())?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + @Test + fun testLoadClientAccountsFail() { + Mockito.`when`(dataManager?.clientAccounts).thenReturn(Observable.error(RuntimeException())) + presenter?.loadClientAccounts() + Mockito.verify(accountsView)?.showProgress() + Mockito.verify(accountsView)?.hideProgress() + Mockito.verify(accountsView)?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + @Test + fun testLoadClientSavingsAccount() { + Mockito.`when`(dataManager?.getAccounts(Constants.SAVINGS_ACCOUNTS)).thenReturn(Observable.just(savingsAccount)) + presenter?.loadAccounts(Constants.SAVINGS_ACCOUNTS) + Mockito.verify(accountsView)?.showProgress() + Mockito.verify(accountsView)?.hideProgress() + Mockito.verify(accountsView)?.showSavingsAccounts(savingsAccount?.savingsAccounts) + Mockito.verify(accountsView, Mockito.never())?.showLoanAccounts(null) + Mockito.verify(accountsView, Mockito.never())?.showShareAccounts(null) + Mockito.verify(accountsView, Mockito.never())?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + @Test + fun testLoadClientLoanAccount() { + Mockito.`when`(dataManager?.getAccounts(Constants.LOAN_ACCOUNTS)).thenReturn(Observable.just(loanAccounts)) + presenter?.loadAccounts(Constants.LOAN_ACCOUNTS) + Mockito.verify(accountsView)?.showProgress() + Mockito.verify(accountsView)?.hideProgress() + Mockito.verify(accountsView)?.showLoanAccounts(loanAccounts?.loanAccounts) + Mockito.verify(accountsView, Mockito.never())?.showSavingsAccounts(null) + Mockito.verify(accountsView, Mockito.never())?.showShareAccounts(null) + Mockito.verify(accountsView, Mockito.never())?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + @Test + fun testLoadClientShareAccount() { + Mockito.`when`(dataManager?.getAccounts(Constants.SHARE_ACCOUNTS)).thenReturn(Observable.just(shareAccounts)) + presenter?.loadAccounts(Constants.SHARE_ACCOUNTS) + Mockito.verify(accountsView)?.showProgress() + Mockito.verify(accountsView)?.hideProgress() + Mockito.verify(accountsView)?.showShareAccounts(shareAccounts?.shareAccounts) + Mockito.verify(accountsView, Mockito.never())?.showLoanAccounts(null) + Mockito.verify(accountsView, Mockito.never())?.showSavingsAccounts(null) + Mockito.verify(accountsView, Mockito.never())?.showError(context?.getString(R.string.error_fetching_accounts)) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/BeneficiaryApplicationPresenterTest.java b/app/src/test/java/org/mifos/mobile/BeneficiaryApplicationPresenterTest.java deleted file mode 100644 index 9174babd65..0000000000 --- a/app/src/test/java/org/mifos/mobile/BeneficiaryApplicationPresenterTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.beneficiary.BeneficiaryPayload; -import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload; -import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate; -import org.mifos.mobile.presenters.BeneficiaryApplicationPresenter; -import org.mifos.mobile.ui.views.BeneficiaryApplicationView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 12/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class BeneficiaryApplicationPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - BeneficiaryApplicationView view; - - @Mock - ResponseBody mockedResponseBody; - - private BeneficiaryUpdatePayload updatePayload; - private BeneficiaryPayload payload; - private BeneficiaryApplicationPresenter presenter; - private BeneficiaryTemplate beneficiaryTemplate; - - @Before - public void setUp() { - presenter = new BeneficiaryApplicationPresenter(dataManager, context); - presenter.attachView(view); - - beneficiaryTemplate = FakeRemoteDataSource.getBeneficiaryTemplate(); - payload = FakeRemoteDataSource.beneficiaryPayload(); - updatePayload = FakeRemoteDataSource.beneficiaryUpdatePayload(); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testShowBeneficiaryTemplate() { - when(dataManager.getBeneficiaryTemplate()).thenReturn(Observable.just(beneficiaryTemplate)); - - presenter.loadBeneficiaryTemplate(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showBeneficiaryTemplate(beneficiaryTemplate); - verify(view, never()).showError(context - .getString(R.string.error_fetching_beneficiary_template)); - } - - @Test - public void testShowBeneficiaryTemplateFails() { - when(dataManager.getBeneficiaryTemplate()).thenReturn(Observable.error - (new RuntimeException())); - - presenter.loadBeneficiaryTemplate(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context - .getString(R.string.error_fetching_beneficiary_template)); - verify(view, never()).showBeneficiaryTemplate(null); - } - - @Test - public void testCreateBeneficiary() { - when(dataManager.createBeneficiary(payload)).thenReturn(Observable. - just(mockedResponseBody)); - - presenter.createBeneficiary(payload); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showBeneficiaryCreatedSuccessfully(); - verify(view, never()).showError(context - .getString(R.string.error_creating_beneficiary)); - } - - @Test - public void testCreateBeneficiaryFails() { - when(dataManager.createBeneficiary(payload)).thenReturn(Observable.error(new - RuntimeException())); - - presenter.createBeneficiary(payload); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showBeneficiaryCreatedSuccessfully(); - verify(view).showError(context - .getString(R.string.error_creating_beneficiary)); - } - - @Test - public void testUpdateBeneficiary() { - when(dataManager.updateBeneficiary(1, updatePayload)).thenReturn(Observable. - just(mockedResponseBody)); - - presenter.updateBeneficiary(1, updatePayload); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showBeneficiaryUpdatedSuccessfully(); - verify(view, never()).showError(context - .getString(R.string.error_updating_beneficiary)); - } - - @Test - public void testUpdateBeneficiaryFails() { - when(dataManager.updateBeneficiary(1, updatePayload)).thenReturn(Observable. - error(new RuntimeException())); - - presenter.updateBeneficiary(1, updatePayload); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context - .getString(R.string.error_updating_beneficiary)); - verify(view, never()).showBeneficiaryUpdatedSuccessfully(); - } -} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/BeneficiaryApplicationPresenterTest.kt b/app/src/test/java/org/mifos/mobile/BeneficiaryApplicationPresenterTest.kt new file mode 100644 index 0000000000..a300974c6e --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/BeneficiaryApplicationPresenterTest.kt @@ -0,0 +1,128 @@ +package org.mifos.mobile + +import android.content.Context +import io.reactivex.Observable +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test + +import org.junit.runner.RunWith +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.beneficiary.BeneficiaryPayload +import org.mifos.mobile.models.beneficiary.BeneficiaryUpdatePayload +import org.mifos.mobile.models.templates.beneficiary.BeneficiaryTemplate +import org.mifos.mobile.presenters.BeneficiaryApplicationPresenter +import org.mifos.mobile.ui.views.BeneficiaryApplicationView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 12/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class BeneficiaryApplicationPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: BeneficiaryApplicationView? = null + + @Mock + var mockedResponseBody: ResponseBody? = null + private var updatePayload: BeneficiaryUpdatePayload? = null + private var payload: BeneficiaryPayload? = null + private var presenter: BeneficiaryApplicationPresenter? = null + private var beneficiaryTemplate: BeneficiaryTemplate? = null + + @Before + fun setUp() { + presenter = BeneficiaryApplicationPresenter(dataManager!!, context) + presenter?.attachView(view) + beneficiaryTemplate = FakeRemoteDataSource.beneficiaryTemplate + payload = FakeRemoteDataSource.beneficiaryPayload() + updatePayload = FakeRemoteDataSource.beneficiaryUpdatePayload() + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testShowBeneficiaryTemplate() { + Mockito.`when`(dataManager?.beneficiaryTemplate).thenReturn(Observable.just(beneficiaryTemplate)) + presenter?.loadBeneficiaryTemplate() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showBeneficiaryTemplate(beneficiaryTemplate) + Mockito.verify(view, Mockito.never())?.showError(context + ?.getString(R.string.error_fetching_beneficiary_template)) + } + + @Test + fun testShowBeneficiaryTemplateFails() { + Mockito.`when`(dataManager?.beneficiaryTemplate).thenReturn(Observable.error(RuntimeException())) + presenter?.loadBeneficiaryTemplate() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context + ?.getString(R.string.error_fetching_beneficiary_template)) + Mockito.verify(view, Mockito.never())?.showBeneficiaryTemplate(null) + } + + @Test + fun testCreateBeneficiary() { + Mockito.`when`(dataManager?.createBeneficiary(payload)).thenReturn(Observable.just(mockedResponseBody)) + presenter?.createBeneficiary(payload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showBeneficiaryCreatedSuccessfully() + Mockito.verify(view, Mockito.never())?.showError(context + ?.getString(R.string.error_creating_beneficiary)) + } + + @Test + fun testCreateBeneficiaryFails() { + Mockito.`when`(dataManager?.createBeneficiary(payload)).thenReturn(Observable.error(RuntimeException())) + presenter?.createBeneficiary(payload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showBeneficiaryCreatedSuccessfully() + Mockito.verify(view)?.showError(context + ?.getString(R.string.error_creating_beneficiary)) + } + + @Test + fun testUpdateBeneficiary() { + Mockito.`when`(dataManager?.updateBeneficiary(1, updatePayload)).thenReturn(Observable.just(mockedResponseBody)) + presenter?.updateBeneficiary(1, updatePayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showBeneficiaryUpdatedSuccessfully() + Mockito.verify(view, Mockito.never())?.showError(context + ?.getString(R.string.error_updating_beneficiary)) + } + + @Test + fun testUpdateBeneficiaryFails() { + Mockito.`when`(dataManager?.updateBeneficiary(1, updatePayload)).thenReturn(Observable.error(RuntimeException())) + presenter?.updateBeneficiary(1, updatePayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context + ?.getString(R.string.error_updating_beneficiary)) + Mockito.verify(view, Mockito.never())?.showBeneficiaryUpdatedSuccessfully() + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/BeneficiaryDetailPresenterTest.java b/app/src/test/java/org/mifos/mobile/BeneficiaryDetailPresenterTest.java deleted file mode 100644 index 8465923d0a..0000000000 --- a/app/src/test/java/org/mifos/mobile/BeneficiaryDetailPresenterTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.presenters.BeneficiaryDetailPresenter; -import org.mifos.mobile.ui.views.BeneficiaryDetailView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class BeneficiaryDetailPresenterTest { - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - BeneficiaryDetailView view; - - @Mock - ResponseBody mockedResponseBody; - - private BeneficiaryDetailPresenter presenter; - private long beneficiaryId = 1; - - @Before - public void setUp() { - presenter = new BeneficiaryDetailPresenter(dataManager, context); - presenter.attachView(view); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testDeleteBeneficiary() { - when(dataManager.deleteBeneficiary(beneficiaryId)).thenReturn(Observable. - just(mockedResponseBody)); - - presenter.deleteBeneficiary(beneficiaryId); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showBeneficiaryDeletedSuccessfully(); - verify(view, never()).showError(context.getString(R.string.error_deleting_beneficiary)); - } - - @Test - public void testDeleteBeneficiaryFails() { - when(dataManager.deleteBeneficiary(beneficiaryId)).thenReturn(Observable. - error(new RuntimeException())); - - presenter.deleteBeneficiary(beneficiaryId); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString(R.string.error_deleting_beneficiary)); - verify(view, never()).showBeneficiaryDeletedSuccessfully(); - } -} diff --git a/app/src/test/java/org/mifos/mobile/BeneficiaryDetailPresenterTest.kt b/app/src/test/java/org/mifos/mobile/BeneficiaryDetailPresenterTest.kt new file mode 100644 index 0000000000..cd5052d148 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/BeneficiaryDetailPresenterTest.kt @@ -0,0 +1,76 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.presenters.BeneficiaryDetailPresenter +import org.mifos.mobile.ui.views.BeneficiaryDetailView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class BeneficiaryDetailPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: BeneficiaryDetailView? = null + + @Mock + var mockedResponseBody: ResponseBody? = null + private var presenter: BeneficiaryDetailPresenter? = null + private val beneficiaryId: Long = 1 + + @Before + fun setUp() { + presenter = BeneficiaryDetailPresenter(dataManager!!, context) + presenter?.attachView(view) + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testDeleteBeneficiary() { + Mockito.`when`(dataManager?.deleteBeneficiary(beneficiaryId)).thenReturn(Observable.just(mockedResponseBody)) + presenter?.deleteBeneficiary(beneficiaryId) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showBeneficiaryDeletedSuccessfully() + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_deleting_beneficiary)) + } + + @Test + fun testDeleteBeneficiaryFails() { + Mockito.`when`(dataManager?.deleteBeneficiary(beneficiaryId)).thenReturn(Observable.error(RuntimeException())) + presenter?.deleteBeneficiary(beneficiaryId) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString(R.string.error_deleting_beneficiary)) + Mockito.verify(view, Mockito.never())?.showBeneficiaryDeletedSuccessfully() + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/BeneficiaryListPresenterTest.java b/app/src/test/java/org/mifos/mobile/BeneficiaryListPresenterTest.java deleted file mode 100644 index f6c8fe7bf0..0000000000 --- a/app/src/test/java/org/mifos/mobile/BeneficiaryListPresenterTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.presenters.BeneficiaryListPresenter; -import org.mifos.mobile.ui.views.BeneficiariesView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.List; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 27/6/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class BeneficiaryListPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - BeneficiariesView view; - - private BeneficiaryListPresenter presenter; - private List beneficiaryList; - - @Before - public void setUp() throws Exception { - presenter = new BeneficiaryListPresenter(dataManager, context); - presenter.attachView(view); - - beneficiaryList = FakeRemoteDataSource.getBeneficiaries(); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testLoadBeneficiaries() throws Exception { - when(dataManager.getBeneficiaryList()).thenReturn(Observable.just(beneficiaryList)); - - presenter.loadBeneficiaries(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showBeneficiaryList(beneficiaryList); - verify(view, never()).showError(context.getString(R.string.error_fetching_beneficiaries)); - } - - @Test - public void testLoadBeneficiariesFails() throws Exception { - when(dataManager.getBeneficiaryList()).thenReturn(Observable.>error(new - RuntimeException())); - - presenter.loadBeneficiaries(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString(R.string.error_fetching_beneficiaries)); - verify(view, never()).showBeneficiaryList(beneficiaryList); - } - -} diff --git a/app/src/test/java/org/mifos/mobile/BeneficiaryListPresenterTest.kt b/app/src/test/java/org/mifos/mobile/BeneficiaryListPresenterTest.kt new file mode 100644 index 0000000000..ce7e46a51e --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/BeneficiaryListPresenterTest.kt @@ -0,0 +1,77 @@ +package org.mifos.mobile + +import android.content.Context +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.presenters.BeneficiaryListPresenter +import org.mifos.mobile.ui.views.BeneficiariesView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 27/6/17. + */ +@RunWith(MockitoJUnitRunner::class) +class BeneficiaryListPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: BeneficiariesView? = null + private var presenter: BeneficiaryListPresenter? = null + private var beneficiaryList: List? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = BeneficiaryListPresenter(dataManager!!, context!!) + presenter?.attachView(view) + beneficiaryList = FakeRemoteDataSource.beneficiaries + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + @Throws(Exception::class) + fun testLoadBeneficiaries() { + Mockito.`when`(dataManager?.beneficiaryList).thenReturn(Observable.just(beneficiaryList)) + presenter?.loadBeneficiaries() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showBeneficiaryList(beneficiaryList) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_beneficiaries)) + } + + @Test + @Throws(Exception::class) + fun testLoadBeneficiariesFails() { + Mockito.`when`(dataManager?.beneficiaryList).thenReturn(Observable.error(RuntimeException())) + presenter?.loadBeneficiaries() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString(R.string.error_fetching_beneficiaries)) + Mockito.verify(view, Mockito.never())?.showBeneficiaryList(beneficiaryList) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/ClientChargePresenterTest.java b/app/src/test/java/org/mifos/mobile/ClientChargePresenterTest.java deleted file mode 100644 index fc556d1ab7..0000000000 --- a/app/src/test/java/org/mifos/mobile/ClientChargePresenterTest.java +++ /dev/null @@ -1,169 +0,0 @@ - -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.Charge; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.presenters.ClientChargePresenter; -import org.mifos.mobile.ui.views.ClientChargeView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.List; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by Chirag Gupta on 12/06/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class ClientChargePresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - ClientChargeView view; - - private ClientChargePresenter presenter; - private Page charge; - private List savingsCharge, loanCharge; - - @Before - public void setUp() throws Exception { - presenter = new ClientChargePresenter(dataManager, context); - presenter.attachView(view); - - charge = FakeRemoteDataSource.getCharge(); - savingsCharge = FakeRemoteDataSource.getSavingsCharge(); - loanCharge = FakeRemoteDataSource.getLoanCharge(); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testLoadClientCharges() { - when(dataManager.getClientCharges(1)).thenReturn(Observable.just(charge)); - - presenter.loadClientCharges(1); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showClientCharges(charge.getPageItems()); - verify(view, never()). - showErrorFetchingClientCharges(context. - getString(R.string.error_client_charge_loading)); - } - - @Test - public void testLoadClientChargesFails() { - when(dataManager.getClientCharges(1)). - thenReturn(Observable.>error(new RuntimeException())); - - presenter.loadClientCharges(1); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showClientCharges(charge.getPageItems()); - verify(view). - showErrorFetchingClientCharges( - context.getString(R.string.error_client_charge_loading)); - } - - @Test - public void testLoadLoanAccountCharges() { - when(dataManager.getLoanCharges(1)).thenReturn(Observable.just(loanCharge)); - - presenter.loadLoanAccountCharges(1); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showClientCharges(loanCharge); - verify(view, never()). - showErrorFetchingClientCharges( - context.getString(R.string.error_client_charge_loading)); - } - - @Test - public void testLoadLoanAccountChargesFails() { - when(dataManager.getLoanCharges(1)). - thenReturn(Observable.>error(new RuntimeException())); - - presenter.loadLoanAccountCharges(1); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showClientCharges(loanCharge); - verify(view). - showErrorFetchingClientCharges( - context.getString(R.string.error_client_charge_loading)); - } - - @Test - public void testLoadSavingsAccountCharges() { - when(dataManager.getSavingsCharges(1)).thenReturn(Observable.just(savingsCharge)); - - presenter.loadSavingsAccountCharges(1); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showClientCharges(savingsCharge); - verify(view, never()). - showErrorFetchingClientCharges( - context.getString(R.string.error_client_charge_loading)); - } - - @Test - public void testLoadSavingsAccountChargesFails() { - when(dataManager.getSavingsCharges(1)). - thenReturn(Observable.>error(new RuntimeException())); - - presenter.loadSavingsAccountCharges(1); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showClientCharges(savingsCharge); - verify(view). - showErrorFetchingClientCharges( - context.getString(R.string.error_client_charge_loading)); - } - - @Test - public void testLoadClientLocalCharges() { - when(dataManager.getClientLocalCharges()).thenReturn(Observable.just(charge)); - - presenter.loadClientLocalCharges(); - verify(view).showClientCharges(charge.getPageItems()); - verify(view, never()). - showErrorFetchingClientCharges( - context.getString(R.string.error_client_charge_loading)); - } - - @Test - public void testLoadClientLocalChargesFails() { - when(dataManager.getClientLocalCharges()). - thenReturn(Observable.>error(new RuntimeException())); - - presenter.loadClientLocalCharges(); - verify(view, never()).showClientCharges(charge.getPageItems()); - verify(view). - showErrorFetchingClientCharges( - context.getString(R.string.error_client_charge_loading)); - } -} diff --git a/app/src/test/java/org/mifos/mobile/ClientChargePresenterTest.kt b/app/src/test/java/org/mifos/mobile/ClientChargePresenterTest.kt new file mode 100644 index 0000000000..44844d201d --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/ClientChargePresenterTest.kt @@ -0,0 +1,144 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.Charge +import org.mifos.mobile.models.Page +import org.mifos.mobile.presenters.ClientChargePresenter +import org.mifos.mobile.ui.views.ClientChargeView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by Chirag Gupta on 12/06/17. + */ +@RunWith(MockitoJUnitRunner::class) +class ClientChargePresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: ClientChargeView? = null + private var presenter: ClientChargePresenter? = null + private var charge: Page? = null + private var savingsCharge: List? = null + private var loanCharge: List? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = ClientChargePresenter(dataManager, context) + presenter?.attachView(view) + charge = FakeRemoteDataSource.charge + savingsCharge = FakeRemoteDataSource.savingsCharge + loanCharge = FakeRemoteDataSource.loanCharge + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoadClientCharges() { + Mockito.`when`(dataManager?.getClientCharges(1)).thenReturn(Observable.just(charge)) + presenter?.loadClientCharges(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showClientCharges(charge?.pageItems) + Mockito.verify(view, Mockito.never())?.showErrorFetchingClientCharges(context?.getString(R.string.error_client_charge_loading)) + } + + @Test + fun testLoadClientChargesFails() { + Mockito.`when`(dataManager?.getClientCharges(1)).thenReturn(Observable.error(RuntimeException())) + presenter?.loadClientCharges(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showClientCharges(charge?.pageItems) + Mockito.verify(view)?.showErrorFetchingClientCharges( + context?.getString(R.string.error_client_charge_loading)) + } + + @Test + fun testLoadLoanAccountCharges() { + Mockito.`when`(dataManager?.getLoanCharges(1)).thenReturn(Observable.just(loanCharge)) + presenter?.loadLoanAccountCharges(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showClientCharges(loanCharge) + Mockito.verify(view, Mockito.never())?.showErrorFetchingClientCharges( + context?.getString(R.string.error_client_charge_loading)) + } + + @Test + fun testLoadLoanAccountChargesFails() { + Mockito.`when`(dataManager?.getLoanCharges(1)).thenReturn(Observable.error(RuntimeException())) + presenter?.loadLoanAccountCharges(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showClientCharges(loanCharge) + Mockito.verify(view)?.showErrorFetchingClientCharges( + context?.getString(R.string.error_client_charge_loading)) + } + + @Test + fun testLoadSavingsAccountCharges() { + Mockito.`when`(dataManager?.getSavingsCharges(1)).thenReturn(Observable.just(savingsCharge)) + presenter?.loadSavingsAccountCharges(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showClientCharges(savingsCharge) + Mockito.verify(view, Mockito.never())?.showErrorFetchingClientCharges( + context?.getString(R.string.error_client_charge_loading)) + } + + @Test + fun testLoadSavingsAccountChargesFails() { + Mockito.`when`(dataManager?.getSavingsCharges(1)).thenReturn(Observable.error(RuntimeException())) + presenter?.loadSavingsAccountCharges(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showClientCharges(savingsCharge) + Mockito.verify(view)?.showErrorFetchingClientCharges( + context?.getString(R.string.error_client_charge_loading)) + } + + @Test + fun testLoadClientLocalCharges() { + Mockito.`when`?>>(dataManager?.clientLocalCharges).thenReturn(Observable.just(charge)) + presenter?.loadClientLocalCharges() + Mockito.verify(view)?.showClientCharges(charge?.pageItems) + Mockito.verify(view, Mockito.never())?.showErrorFetchingClientCharges( + context?.getString(R.string.error_client_charge_loading)) + } + + @Test + fun testLoadClientLocalChargesFails() { + Mockito.`when`(dataManager?.clientLocalCharges).thenReturn(Observable.error(RuntimeException())) + presenter?.loadClientLocalCharges() + Mockito.verify(view, Mockito.never())?.showClientCharges(charge?.pageItems) + Mockito.verify(view)?.showErrorFetchingClientCharges( + context?.getString(R.string.error_client_charge_loading)) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/GuarantorDetailPresenterTest.java b/app/src/test/java/org/mifos/mobile/GuarantorDetailPresenterTest.java deleted file mode 100644 index 7fd12bd4d5..0000000000 --- a/app/src/test/java/org/mifos/mobile/GuarantorDetailPresenterTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.presenters.GuarantorDetailPresenter; -import org.mifos.mobile.ui.views.GuarantorDetailView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.IOException; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class GuarantorDetailPresenterTest { - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - GuarantorDetailView view; - - @Mock - ResponseBody responseBody; - - private GuarantorDetailPresenter presenter; - - @Before - public void setUp() throws Exception { - presenter = new GuarantorDetailPresenter(context, dataManager); - presenter.attachView(view); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testDeleteGuarantor() throws IOException { - long loanId = 1, guarantorId = 1; - when(dataManager.deleteGuarantor(loanId, guarantorId)) - .thenReturn(Observable.just(responseBody)); - presenter.deleteGuarantor(loanId, guarantorId); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).guarantorDeletedSuccessfully(responseBody.string()); - } - - @Test - public void testDeleteGuarantorOnError() throws IOException { - long loanId = 1, guarantorId = 1; - Exception exception = new Exception("ExceptionMessage"); - when(dataManager.deleteGuarantor(loanId, guarantorId)) - .thenReturn(Observable.error(exception)); - presenter.deleteGuarantor(loanId, guarantorId); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(exception.getMessage()); - } -} diff --git a/app/src/test/java/org/mifos/mobile/GuarantorDetailPresenterTest.kt b/app/src/test/java/org/mifos/mobile/GuarantorDetailPresenterTest.kt new file mode 100644 index 0000000000..20e1a8de64 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/GuarantorDetailPresenterTest.kt @@ -0,0 +1,84 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.presenters.GuarantorDetailPresenter +import org.mifos.mobile.ui.views.GuarantorDetailView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +import java.io.IOException + +@RunWith(MockitoJUnitRunner::class) +class GuarantorDetailPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: GuarantorDetailView? = null + + @Mock + var responseBody: ResponseBody? = null + private var presenter: GuarantorDetailPresenter? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = GuarantorDetailPresenter(context!!, dataManager!!) + presenter?.attachView(view) + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + @Throws(IOException::class) + fun testDeleteGuarantor() { + val loanId: Long = 1 + val guarantorId: Long = 1 + Mockito.`when`(dataManager?.deleteGuarantor(loanId, guarantorId)) + .thenReturn(Observable.just(responseBody)) + presenter?.deleteGuarantor(loanId, guarantorId) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.guarantorDeletedSuccessfully(responseBody?.string()) + } + + @Test + @Throws(IOException::class) + fun testDeleteGuarantorOnError() { + val loanId: Long = 1 + val guarantorId: Long = 1 + val exception = Exception("ExceptionMessage") + Mockito.`when`(dataManager?.deleteGuarantor(loanId, guarantorId)) + .thenReturn(Observable.error(exception)) + presenter?.deleteGuarantor(loanId, guarantorId) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(exception.message) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/GuarantorListPresenterTest.java b/app/src/test/java/org/mifos/mobile/GuarantorListPresenterTest.java deleted file mode 100644 index 8f84173380..0000000000 --- a/app/src/test/java/org/mifos/mobile/GuarantorListPresenterTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.guarantor.GuarantorPayload; -import org.mifos.mobile.presenters.GuarantorListPresenter; -import org.mifos.mobile.ui.views.GuarantorListView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.IOException; -import java.util.List; - -import io.reactivex.Observable; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class GuarantorListPresenterTest { - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - GuarantorListView view; - - private GuarantorListPresenter presenter; - List guarantorPayloadList; - - - @Before - public void setUp() throws Exception { - presenter = new GuarantorListPresenter(context, dataManager); - presenter.attachView(view); - guarantorPayloadList = FakeRemoteDataSource.getGuarantorsList(); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testGetGuarantorList() throws IOException { - long loanId = 1; - when(dataManager.getGuarantorList(loanId)) - .thenReturn(Observable.just(guarantorPayloadList)); - presenter.getGuarantorList(loanId); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showGuarantorListSuccessfully(guarantorPayloadList); - } - - @Test - public void testGetGuarantorListOnError() throws IOException { - long loanId = 1; - Exception exception = new Exception("ExceptionMessage"); - when(dataManager.getGuarantorList(loanId)) - .thenReturn(Observable.>error(exception)); - presenter.getGuarantorList(loanId); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(exception.getMessage()); - } -} diff --git a/app/src/test/java/org/mifos/mobile/GuarantorListPresenterTest.kt b/app/src/test/java/org/mifos/mobile/GuarantorListPresenterTest.kt new file mode 100644 index 0000000000..840822050c --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/GuarantorListPresenterTest.kt @@ -0,0 +1,80 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.guarantor.GuarantorPayload +import org.mifos.mobile.presenters.GuarantorListPresenter +import org.mifos.mobile.ui.views.GuarantorListView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +import java.io.IOException + +@RunWith(MockitoJUnitRunner::class) +class GuarantorListPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: GuarantorListView? = null + private var presenter: GuarantorListPresenter? = null + private var guarantorPayloadList: List? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = GuarantorListPresenter(context!!, dataManager!!) + presenter?.attachView(view) + guarantorPayloadList = FakeRemoteDataSource.guarantorsList + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + @Throws(IOException::class) + fun testGetGuarantorList() { + val loanId: Long = 1 + Mockito.`when`(dataManager?.getGuarantorList(loanId)) + .thenReturn(Observable.just(guarantorPayloadList)) + presenter?.getGuarantorList(loanId) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showGuarantorListSuccessfully(guarantorPayloadList) + } + + @Test + @Throws(IOException::class) + fun testGetGuarantorListOnError() { + val loanId: Long = 1 + val exception = Exception("ExceptionMessage") + Mockito.`when`(dataManager?.getGuarantorList(loanId)) + .thenReturn(Observable.error(exception)) + presenter?.getGuarantorList(loanId) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(exception.message) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/HomeOldPresenterTest.java b/app/src/test/java/org/mifos/mobile/HomeOldPresenterTest.java deleted file mode 100644 index d4ceca2565..0000000000 --- a/app/src/test/java/org/mifos/mobile/HomeOldPresenterTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.accounts.loan.LoanAccount; -import org.mifos.mobile.models.accounts.savings.SavingAccount; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.client.ClientAccounts; -import org.mifos.mobile.presenters.HomeOldPresenter; -import org.mifos.mobile.ui.views.HomeOldView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.List; - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class HomeOldPresenterTest { - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - HomeOldView view; - - @Mock - PreferencesHelper preferencesHelper; - - private HomeOldPresenter presenter; - private ClientAccounts clientAccounts; - private Client client; - - @Before - public void setUp() throws Exception { - presenter = new HomeOldPresenter(dataManager, context, preferencesHelper); - presenter.attachView(view); - clientAccounts = FakeRemoteDataSource.getClientAccounts(); - client = FakeRemoteDataSource.getCurrentClient(); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testLoadClientAccountDetails() { - when(dataManager.getClientAccounts()).thenReturn(Observable.just(clientAccounts)); - presenter.loadClientAccountDetails(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanAccountDetails(getLoanAccountDetails(clientAccounts - .getLoanAccounts())); - verify(view).showSavingAccountDetails(getSavingAccountDetails(clientAccounts - .getSavingsAccounts())); - verify(view, never()).showError(context.getString(R.string.error_fetching_accounts)); - } - - @Test - public void testLoadClientAccountDetailsFails() { - when(dataManager.getClientAccounts()) - .thenReturn(Observable.error(new Throwable())); - presenter.loadClientAccountDetails(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString(R.string.error_fetching_accounts)); - } - - @Test - public void testGetUserDetails() { - when(dataManager.getCurrentClient()) - .thenReturn(Observable.just(client)); - presenter.getUserDetails(); - verify(view).showUserDetails(client); - } - - @Test - public void testGetUserDetailsFails() { - when(dataManager.getCurrentClient()) - .thenReturn(Observable.error(new Throwable())); - presenter.getUserDetails(); - - verify(view).showError(context - .getString(R.string.error_client_not_found)); - } - -// @Test -// public void testGetUserImage() throws IOException { -// ResponseBody responseBody = ResponseBody.create(MediaType.parse("text/plain"), -// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+" + -// "9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ\n" + -// "bWFnZVJlYWR5ccllPAAAAJ1JREFUeNpi+P//PwMIA4E9EG8E4idQDGLbw+" + -// "WhiiqA+D8OXAFVAzbp\n" + -// "DxBvB2JLIGaGYkuoGEjOhhFIHAbij0BdPgxYACMj42ogJQpifwBiXSDeC8JIbt" + -// "4LxSC5DyxQjTeB\n" + -// "+BeaYb+Q5EBOAVutCzMJHUNNPADzzDokiYdAfAmJvwLkGeTgWQfyKZICS6hYBTwc0" + -// "QL8ORSjBDhA\n" + -// "gAEAOg13B6R/SAgAAAAASUVORK5CYII="); -// when(dataManager.getClientImage()) -// .thenReturn(Observable.just(responseBody)); -// presenter.getUserImage(); -// final String encodedString = responseBody.string(); -// final String pureBase64Encoded = -// encodedString.substring(encodedString.indexOf(',') + 1); -// verify(preferencesHelper).setUserProfileImage(pureBase64Encoded); -// verify(presenter).setUserProfile(pureBase64Encoded); -// } - - @Test - public void testGetUnreadNotificationsCount() { - int notificationCount = 10; - when(dataManager.getUnreadNotificationsCount()) - .thenReturn(Observable.just(notificationCount)); - presenter.getUnreadNotificationsCount(); - verify(view).showNotificationCount(notificationCount); - } - - @Test - public void testGetUnreadNotificationsCountOnError() { - when(dataManager.getUnreadNotificationsCount()) - .thenReturn(Observable.error(new Throwable())); - presenter.getUnreadNotificationsCount(); - verify(view).showNotificationCount(0); - } - - private double getLoanAccountDetails(List loanAccountList) { - double totalAmount = 0; - for (LoanAccount loanAccount : loanAccountList) { - totalAmount += loanAccount.getLoanBalance(); - } - return totalAmount; - } - - private double getSavingAccountDetails(List savingAccountList) { - double totalAmount = 0; - for (SavingAccount savingAccount : savingAccountList) { - totalAmount += savingAccount.getAccountBalance(); - } - return totalAmount; - } -} diff --git a/app/src/test/java/org/mifos/mobile/HomeOldPresenterTest.kt b/app/src/test/java/org/mifos/mobile/HomeOldPresenterTest.kt new file mode 100644 index 0000000000..861436762a --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/HomeOldPresenterTest.kt @@ -0,0 +1,156 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.accounts.loan.LoanAccount +import org.mifos.mobile.models.accounts.savings.SavingAccount +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.client.ClientAccounts +import org.mifos.mobile.presenters.HomeOldPresenter +import org.mifos.mobile.ui.views.HomeOldView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class HomeOldPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: HomeOldView? = null + + @Mock + var preferencesHelper: PreferencesHelper? = null + private var presenter: HomeOldPresenter? = null + private var clientAccounts: ClientAccounts? = null + private var client: Client? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = HomeOldPresenter(dataManager!!, context!!, preferencesHelper!!) + presenter?.attachView(view) + clientAccounts = FakeRemoteDataSource.clientAccounts + client = FakeRemoteDataSource.currentClient + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoadClientAccountDetails() { + Mockito.`when`(dataManager?.clientAccounts).thenReturn(Observable.just(clientAccounts)) + presenter?.loadClientAccountDetails() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + clientAccounts + ?.loanAccounts?.let { getLoanAccountDetails(it) }?.let { Mockito.verify(view)?.showLoanAccountDetails(it) } + Mockito.verify(view)?.showSavingAccountDetails(getSavingAccountDetails(clientAccounts + ?.savingsAccounts)) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + @Test + fun testLoadClientAccountDetailsFails() { + Mockito.`when`(dataManager?.clientAccounts) + .thenReturn(Observable.error(Throwable())) + presenter?.loadClientAccountDetails() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString(R.string.error_fetching_accounts)) + } + + @Test + fun testGetUserDetails() { + Mockito.`when`(dataManager?.currentClient) + .thenReturn(Observable.just(client)) + presenter?.userDetails + Mockito.verify(view)?.showUserDetails(client) + } + + @Test + fun testGetUserDetailsFails() { + Mockito.`when`(dataManager?.currentClient) + .thenReturn(Observable.error(Throwable())) + presenter?.userDetails + Mockito.verify(view)?.showError(context + ?.getString(R.string.error_client_not_found)) + } + + // @Test + // public void testGetUserImage() throws IOException { + // ResponseBody responseBody = ResponseBody.create(MediaType.parse("text/plain"), + // "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+" + + // "9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ\n" + + // "bWFnZVJlYWR5ccllPAAAAJ1JREFUeNpi+P//PwMIA4E9EG8E4idQDGLbw+" + + // "WhiiqA+D8OXAFVAzbp\n" + + // "DxBvB2JLIGaGYkuoGEjOhhFIHAbij0BdPgxYACMj42ogJQpifwBiXSDeC8JIbt" + + // "4LxSC5DyxQjTeB\n" + + // "+BeaYb+Q5EBOAVutCzMJHUNNPADzzDokiYdAfAmJvwLkGeTgWQfyKZICS6hYBTwc0" + + // "QL8ORSjBDhA\n" + + // "gAEAOg13B6R/SAgAAAAASUVORK5CYII="); + // when(dataManager.getClientImage()) + // .thenReturn(Observable.just(responseBody)); + // presenter.getUserImage(); + // final String encodedString = responseBody.string(); + // final String pureBase64Encoded = + // encodedString.substring(encodedString.indexOf(',') + 1); + // verify(preferencesHelper).setUserProfileImage(pureBase64Encoded); + // verify(presenter).setUserProfile(pureBase64Encoded); + // } + @Test + fun testGetUnreadNotificationsCount() { + val notificationCount = 10 + Mockito.`when`(dataManager?.unreadNotificationsCount) + .thenReturn(Observable.just(notificationCount)) + presenter?.unreadNotificationsCount + Mockito.verify(view)?.showNotificationCount(notificationCount) + } + + @Test + fun testGetUnreadNotificationsCountOnError() { + Mockito.`when`(dataManager?.unreadNotificationsCount) + .thenReturn(Observable.error(Throwable())) + presenter?.unreadNotificationsCount + Mockito.verify(view)?.showNotificationCount(0) + } + + private fun getLoanAccountDetails(loanAccountList: List): Double { + var totalAmount = 0.0 + for ((_, _, _, _, _, _, _, _, _, _, _, _, _, _, loanBalance) in loanAccountList) { + totalAmount += loanBalance + } + return totalAmount + } + + private fun getSavingAccountDetails(savingAccountList: List?): Double { + var totalAmount = 0.0 + for ((_, _, _, _, _, accountBalance) in savingAccountList!!) { + totalAmount += accountBalance + } + return totalAmount + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/LoanAccountDetailPresenterTest.java b/app/src/test/java/org/mifos/mobile/LoanAccountDetailPresenterTest.java deleted file mode 100644 index caef8117f8..0000000000 --- a/app/src/test/java/org/mifos/mobile/LoanAccountDetailPresenterTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.presenters.LoanAccountsDetailPresenter; -import org.mifos.mobile.ui.views.LoanAccountsDetailView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mifos.mobile.utils.Constants; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 27/6/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class LoanAccountDetailPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - LoanAccountsDetailView view; - - private LoanAccountsDetailPresenter presenter; - private LoanWithAssociations loanWithAssociations; - - @Before - public void setUp() throws Exception { - presenter = new LoanAccountsDetailPresenter(dataManager, context); - presenter.attachView(view); - - loanWithAssociations = FakeRemoteDataSource.getLoanAccountWithTransaction(); - } - - @Test - public void testLoadLoanAccountDetails() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 4)). - thenReturn(Observable.just(loanWithAssociations)); - - presenter.loadLoanAccountDetails(4); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanAccountsDetail(loanWithAssociations); - verify(view, never()).showErrorFetchingLoanAccountsDetail(context. - getString(R.string.error_loan_account_details_loading)); - } - - @Test - public void testLoadLoanAccountDetailsFails() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 4)). - thenReturn(Observable.error(new RuntimeException())); - - presenter.loadLoanAccountDetails(4); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showErrorFetchingLoanAccountsDetail(context. - getString(R.string.error_loan_account_details_loading)); - verify(view, never()).showLoanAccountsDetail(null); - } -} diff --git a/app/src/test/java/org/mifos/mobile/LoanAccountDetailPresenterTest.kt b/app/src/test/java/org/mifos/mobile/LoanAccountDetailPresenterTest.kt new file mode 100644 index 0000000000..5d30a292fd --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/LoanAccountDetailPresenterTest.kt @@ -0,0 +1,72 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.presenters.LoanAccountsDetailPresenter +import org.mifos.mobile.ui.views.LoanAccountsDetailView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mifos.mobile.utils.Constants + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 27/6/17. + */ +@RunWith(MockitoJUnitRunner::class) +class LoanAccountDetailPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: LoanAccountsDetailView? = null + private var presenter: LoanAccountsDetailPresenter? = null + private var loanWithAssociations: LoanWithAssociations? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = LoanAccountsDetailPresenter(dataManager!!, context) + presenter?.attachView(view) + loanWithAssociations = FakeRemoteDataSource.loanAccountWithTransaction + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetails() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 4)).thenReturn(Observable.just(loanWithAssociations)) + presenter?.loadLoanAccountDetails(4) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoanAccountsDetail(loanWithAssociations) + Mockito.verify(view, Mockito.never())?.showErrorFetchingLoanAccountsDetail(context?.getString(R.string.error_loan_account_details_loading)) + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetailsFails() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 4)).thenReturn(Observable.error(RuntimeException())) + presenter?.loadLoanAccountDetails(4) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showErrorFetchingLoanAccountsDetail(context?.getString(R.string.error_loan_account_details_loading)) + Mockito.verify(view, Mockito.never())?.showLoanAccountsDetail(null) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/LoanAccountWithdrawPresenterTest.java b/app/src/test/java/org/mifos/mobile/LoanAccountWithdrawPresenterTest.java deleted file mode 100644 index 498be71010..0000000000 --- a/app/src/test/java/org/mifos/mobile/LoanAccountWithdrawPresenterTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.accounts.loan.LoanWithdraw; -import org.mifos.mobile.presenters.LoanAccountWithdrawPresenter; -import org.mifos.mobile.ui.views.LoanAccountWithdrawView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class LoanAccountWithdrawPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - LoanAccountWithdrawView view; - - @Mock - LoanWithdraw loanWithdraw; - - @Mock - ResponseBody mockedResponseBody; - - private LoanAccountWithdrawPresenter presenter; - private long loanId = 1; - - @Before - public void setUp() { - presenter = new LoanAccountWithdrawPresenter(dataManager, context); - presenter.attachView(view); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testWithdrawLoanAccount() { - when(dataManager.withdrawLoanAccount(loanId, loanWithdraw)).thenReturn(Observable. - just(mockedResponseBody)); - - presenter.withdrawLoanAccount(loanId, loanWithdraw); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanAccountWithdrawSuccess(); - verify(view, never()).showLoanAccountWithdrawError(context.getString(R.string. - error_loan_account_withdraw)); - } - - @Test - public void testWithdrawLoanAccountFail() { - when(dataManager.withdrawLoanAccount(loanId, loanWithdraw)).thenReturn(Observable. - error(new RuntimeException())); - - presenter.withdrawLoanAccount(loanId, loanWithdraw); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanAccountWithdrawError(context.getString(R.string. - error_loan_account_withdraw)); - verify(view, never()).showLoanAccountWithdrawSuccess(); - } - -} diff --git a/app/src/test/java/org/mifos/mobile/LoanAccountWithdrawPresenterTest.kt b/app/src/test/java/org/mifos/mobile/LoanAccountWithdrawPresenterTest.kt new file mode 100644 index 0000000000..705f724261 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/LoanAccountWithdrawPresenterTest.kt @@ -0,0 +1,81 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.accounts.loan.LoanWithdraw +import org.mifos.mobile.presenters.LoanAccountWithdrawPresenter +import org.mifos.mobile.ui.views.LoanAccountWithdrawView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class LoanAccountWithdrawPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: LoanAccountWithdrawView? = null + + @Mock + var loanWithdraw: LoanWithdraw? = null + + @Mock + var mockedResponseBody: ResponseBody? = null + private var presenter: LoanAccountWithdrawPresenter? = null + private val loanId: Long = 1 + + @Before + fun setUp() { + presenter = LoanAccountWithdrawPresenter(dataManager!!, context) + presenter?.attachView(view) + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testWithdrawLoanAccount() { + Mockito.`when`(dataManager?.withdrawLoanAccount(loanId, loanWithdraw)).thenReturn(Observable.just(mockedResponseBody)) + presenter?.withdrawLoanAccount(loanId, loanWithdraw) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoanAccountWithdrawSuccess() + Mockito.verify(view, Mockito.never())?.showLoanAccountWithdrawError(context?.getString(R.string.error_loan_account_withdraw)) + } + + @Test + fun testWithdrawLoanAccountFail() { + Mockito.`when`(dataManager?.withdrawLoanAccount(loanId, loanWithdraw)).thenReturn(Observable.error(RuntimeException())) + presenter?.withdrawLoanAccount(loanId, loanWithdraw) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoanAccountWithdrawError(context?.getString(R.string.error_loan_account_withdraw)) + Mockito.verify(view, Mockito.never())?.showLoanAccountWithdrawSuccess() + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/LoanAccountsTransactionPresenterTest.java b/app/src/test/java/org/mifos/mobile/LoanAccountsTransactionPresenterTest.java deleted file mode 100644 index 5dc95fef91..0000000000 --- a/app/src/test/java/org/mifos/mobile/LoanAccountsTransactionPresenterTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.presenters.LoanAccountsTransactionPresenter; -import org.mifos.mobile.ui.views.LoanAccountsTransactionView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mifos.mobile.utils.Constants; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 27/6/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class LoanAccountsTransactionPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - LoanAccountsTransactionView view; - - private LoanAccountsTransactionPresenter presenter; - private LoanWithAssociations loanWithTransaction, loanWithEmptyTransactions; - - @Before - public void setUp() throws Exception { - presenter = new LoanAccountsTransactionPresenter(dataManager, context); - presenter.attachView(view); - - loanWithTransaction = FakeRemoteDataSource.getLoanAccountWithTransaction(); - loanWithEmptyTransactions = FakeRemoteDataSource.getLoanAccountWithEmptyTransaction(); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testLoadLoanAccountDetails() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.TRANSACTIONS, 29)). - thenReturn(Observable.just(loanWithTransaction)); - - presenter.loadLoanAccountDetails(29); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanTransactions(loanWithTransaction); - verify(view, never()).showEmptyTransactions(null); - verify(view, never()).showErrorFetchingLoanAccountsDetail(context. - getString(R.string.error_loan_account_details_loading)); - - } - - @Test - public void testLoadLoanAccountDetailsEmpty() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.TRANSACTIONS, 29)). - thenReturn(Observable.just(loanWithEmptyTransactions)); - - presenter.loadLoanAccountDetails(29); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showEmptyTransactions(loanWithEmptyTransactions); - verify(view, never()).showLoanTransactions(null); - verify(view, never()).showErrorFetchingLoanAccountsDetail(context. - getString(R.string.error_loan_account_details_loading)); - - } - - - @Test - public void testLoadLoanAccountDetailsFails() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.TRANSACTIONS, 29)). - thenReturn(Observable.error(new RuntimeException())); - - presenter.loadLoanAccountDetails(29); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showErrorFetchingLoanAccountsDetail(context. - getString(R.string.error_loan_account_details_loading)); - verify(view, never()).showEmptyTransactions(null); - verify(view, never()).showLoanTransactions(null); - - } -} diff --git a/app/src/test/java/org/mifos/mobile/LoanAccountsTransactionPresenterTest.kt b/app/src/test/java/org/mifos/mobile/LoanAccountsTransactionPresenterTest.kt new file mode 100644 index 0000000000..f67eebc8e7 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/LoanAccountsTransactionPresenterTest.kt @@ -0,0 +1,95 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.presenters.LoanAccountsTransactionPresenter +import org.mifos.mobile.ui.views.LoanAccountsTransactionView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mifos.mobile.utils.Constants + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 27/6/17. + */ +@RunWith(MockitoJUnitRunner::class) +class LoanAccountsTransactionPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: LoanAccountsTransactionView? = null + private var presenter: LoanAccountsTransactionPresenter? = null + private var loanWithTransaction: LoanWithAssociations? = null + private var loanWithEmptyTransactions: LoanWithAssociations? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = LoanAccountsTransactionPresenter(dataManager!!, context) + presenter?.attachView(view) + loanWithTransaction = FakeRemoteDataSource.loanAccountWithTransaction + loanWithEmptyTransactions = FakeRemoteDataSource.loanAccountWithEmptyTransaction + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetails() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.TRANSACTIONS, 29)).thenReturn(Observable.just(loanWithTransaction)) + presenter?.loadLoanAccountDetails(29) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoanTransactions(loanWithTransaction) + Mockito.verify(view, Mockito.never())?.showEmptyTransactions(null) + Mockito.verify(view, Mockito.never())?.showErrorFetchingLoanAccountsDetail(context?.getString(R.string.error_loan_account_details_loading)) + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetailsEmpty() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.TRANSACTIONS, 29)).thenReturn(Observable.just(loanWithEmptyTransactions)) + presenter?.loadLoanAccountDetails(29) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showEmptyTransactions(loanWithEmptyTransactions) + Mockito.verify(view, Mockito.never())?.showLoanTransactions(null) + Mockito.verify(view, Mockito.never())?.showErrorFetchingLoanAccountsDetail(context?.getString(R.string.error_loan_account_details_loading)) + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetailsFails() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.TRANSACTIONS, 29)).thenReturn(Observable.error(RuntimeException())) + presenter?.loadLoanAccountDetails(29) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showErrorFetchingLoanAccountsDetail(context?.getString(R.string.error_loan_account_details_loading)) + Mockito.verify(view, Mockito.never())?.showEmptyTransactions(null) + Mockito.verify(view, Mockito.never())?.showLoanTransactions(null) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/LoanApplicationPresenterTest.java b/app/src/test/java/org/mifos/mobile/LoanApplicationPresenterTest.java deleted file mode 100644 index a4d1c4d19d..0000000000 --- a/app/src/test/java/org/mifos/mobile/LoanApplicationPresenterTest.java +++ /dev/null @@ -1,175 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.payload.LoansPayload; -import org.mifos.mobile.models.templates.loans.LoanTemplate; -import org.mifos.mobile.presenters.LoanApplicationPresenter; -import org.mifos.mobile.ui.enums.LoanState; -import org.mifos.mobile.ui.views.LoanApplicationMvpView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 12/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class LoanApplicationPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - LoanApplicationMvpView view; - - @Mock - ResponseBody mockedResponseBody; - - private LoanApplicationPresenter presenter; - private LoanTemplate loanTemplate, loanTemplateWithProduct; - private LoansPayload loansPayload; - - @Before - public void setUp() { - presenter = new LoanApplicationPresenter(dataManager, context); - presenter.attachView(view); - - loanTemplate = FakeRemoteDataSource.getLoanTemplate(); - loanTemplateWithProduct = FakeRemoteDataSource.getLoanTemplateByTemplate(); - loansPayload = FakeRemoteDataSource.getLoansPayload(); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testLoadLoanApplicationTemplateNew() { - LoanState loanState = LoanState.CREATE; - when(dataManager.getLoanTemplate()).thenReturn(Observable.just(loanTemplate)); - - presenter.loadLoanApplicationTemplate(loanState); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanTemplate(loanTemplate); - verify(view, never()).showError(context.getString(R.string.error_fetching_template)); - } - - @Test - public void testLoadLoanApplicationTemplateUpdate() { - LoanState loanState = LoanState.UPDATE; - when(dataManager.getLoanTemplate()).thenReturn(Observable.just(loanTemplate)); - - presenter.loadLoanApplicationTemplate(loanState); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showUpdateLoanTemplate(loanTemplate); - verify(view, never()).showError(context.getString(R.string.error_fetching_template)); - } - - @Test - public void testLoadLoanApplicationTemplateFails() { - LoanState loanState = LoanState.CREATE; - when(dataManager.getLoanTemplate()).thenReturn(Observable.error(new - RuntimeException())); - - presenter.loadLoanApplicationTemplate(loanState); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString(R.string.error_fetching_template)); - verify(view, never()).showLoanTemplate(loanTemplate); - } - - @Test - public void testLoadLoanApplicationTemplateByProductNew() { - LoanState loanState = LoanState.CREATE; - when(dataManager.getLoanTemplateByProduct(1)).thenReturn(Observable. - just(loanTemplateWithProduct)); - - presenter.loadLoanApplicationTemplateByProduct(1, loanState); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanTemplateByProduct(loanTemplateWithProduct); - verify(view, never()).showError(context.getString(R.string.error_fetching_template)); - } - - @Test - public void testLoadLoanApplicationTemplateByProductUpdate() { - LoanState loanState = LoanState.UPDATE; - when(dataManager.getLoanTemplateByProduct(1)).thenReturn(Observable. - just(loanTemplateWithProduct)); - - presenter.loadLoanApplicationTemplateByProduct(1, loanState); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showUpdateLoanTemplateByProduct(loanTemplateWithProduct); - verify(view, never()).showError(context.getString(R.string.error_fetching_template)); - } - - @Test - public void testLoadLoanApplicationTemplateByProductFails() { - LoanState loanState = LoanState.CREATE; - when(dataManager.getLoanTemplateByProduct(1)).thenReturn(Observable.error(new - RuntimeException())); - - presenter.loadLoanApplicationTemplateByProduct(1, loanState); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString(R.string.error_fetching_template)); - verify(view, never()).showLoanTemplate(null); - } - -// @Test -// public void testCreateLoanAccount() { -// when(dataManager.createLoansAccount(loansPayload)).thenReturn(Observable. -// just(mockedResponseBody)); -// -// presenter.createLoansAccount(loansPayload); -// -// verify(view).showProgress(); -// verify(view).hideProgress(); -// verify(view).showLoanAccountCreatedSuccessfully(); -// -// } -// -// @Test -// public void testUpdateLoanAccount() { -// when(dataManager.updateLoanAccount(1, loansPayload)).thenReturn(Observable. -// just(mockedResponseBody)); -// -// presenter.updateLoanAccount(1, loansPayload); -// -// verify(view).showProgress(); -// verify(view).hideProgress(); -// verify(view).showLoanAccountUpdatedSuccessfully(); -// -// } - -} diff --git a/app/src/test/java/org/mifos/mobile/LoanApplicationPresenterTest.kt b/app/src/test/java/org/mifos/mobile/LoanApplicationPresenterTest.kt new file mode 100644 index 0000000000..cc7e2eb9a1 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/LoanApplicationPresenterTest.kt @@ -0,0 +1,155 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.payload.LoansPayload +import org.mifos.mobile.models.templates.loans.LoanTemplate +import org.mifos.mobile.presenters.LoanApplicationPresenter +import org.mifos.mobile.ui.enums.LoanState +import org.mifos.mobile.ui.views.LoanApplicationMvpView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 12/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class LoanApplicationPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: LoanApplicationMvpView? = null + + @Mock + var mockedResponseBody: ResponseBody? = null + private var presenter: LoanApplicationPresenter? = null + private var loanTemplate: LoanTemplate? = null + private var loanTemplateWithProduct: LoanTemplate? = null + private var loansPayload: LoansPayload? = null + + @Before + fun setUp() { + presenter = LoanApplicationPresenter(dataManager!!, context) + presenter?.attachView(view) + loanTemplate = FakeRemoteDataSource.loanTemplate + loanTemplateWithProduct = FakeRemoteDataSource.loanTemplateByTemplate + loansPayload = FakeRemoteDataSource.loansPayload + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoadLoanApplicationTemplateNew() { + val loanState = LoanState.CREATE + Mockito.`when`(dataManager?.loanTemplate).thenReturn(Observable.just(loanTemplate)) + presenter?.loadLoanApplicationTemplate(loanState) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoanTemplate(loanTemplate) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_template)) + } + + @Test + fun testLoadLoanApplicationTemplateUpdate() { + val loanState = LoanState.UPDATE + Mockito.`when`(dataManager?.loanTemplate).thenReturn(Observable.just(loanTemplate)) + presenter?.loadLoanApplicationTemplate(loanState) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showUpdateLoanTemplate(loanTemplate) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_template)) + } + + @Test + fun testLoadLoanApplicationTemplateFails() { + val loanState = LoanState.CREATE + Mockito.`when`(dataManager?.loanTemplate).thenReturn(Observable.error(RuntimeException())) + presenter?.loadLoanApplicationTemplate(loanState) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString(R.string.error_fetching_template)) + Mockito.verify(view, Mockito.never())?.showLoanTemplate(loanTemplate) + } + + @Test + fun testLoadLoanApplicationTemplateByProductNew() { + val loanState = LoanState.CREATE + Mockito.`when`(dataManager?.getLoanTemplateByProduct(1)).thenReturn(Observable.just(loanTemplateWithProduct)) + presenter?.loadLoanApplicationTemplateByProduct(1, loanState) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoanTemplateByProduct(loanTemplateWithProduct) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_template)) + } + + @Test + fun testLoadLoanApplicationTemplateByProductUpdate() { + val loanState = LoanState.UPDATE + Mockito.`when`(dataManager?.getLoanTemplateByProduct(1)).thenReturn(Observable.just(loanTemplateWithProduct)) + presenter?.loadLoanApplicationTemplateByProduct(1, loanState) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showUpdateLoanTemplateByProduct(loanTemplateWithProduct) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_template)) + } + + @Test + fun testLoadLoanApplicationTemplateByProductFails() { + val loanState = LoanState.CREATE + Mockito.`when`(dataManager?.getLoanTemplateByProduct(1)).thenReturn(Observable.error(RuntimeException())) + presenter?.loadLoanApplicationTemplateByProduct(1, loanState) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString(R.string.error_fetching_template)) + Mockito.verify(view, Mockito.never())?.showLoanTemplate(null) + } // @Test + // public void testCreateLoanAccount() { + // when(dataManager.createLoansAccount(loansPayload)).thenReturn(Observable. + // just(mockedResponseBody)); + // + // presenter.createLoansAccount(loansPayload); + // + // verify(view)?.showProgress(); + // verify(view)?.hideProgress(); + // verify(view)?.showLoanAccountCreatedSuccessfully(); + // + // } + // + // @Test + // public void testUpdateLoanAccount() { + // when(dataManager.updateLoanAccount(1, loansPayload)).thenReturn(Observable. + // just(mockedResponseBody)); + // + // presenter.updateLoanAccount(1, loansPayload); + // + // verify(view)?.showProgress(); + // verify(view)?.hideProgress(); + // verify(view)?.showLoanAccountUpdatedSuccessfully(); + // + // } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/LoanRepaymentSchedulePresenterTest.java b/app/src/test/java/org/mifos/mobile/LoanRepaymentSchedulePresenterTest.java deleted file mode 100644 index e5a31402e1..0000000000 --- a/app/src/test/java/org/mifos/mobile/LoanRepaymentSchedulePresenterTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.accounts.loan.LoanWithAssociations; -import org.mifos.mobile.presenters.LoanRepaymentSchedulePresenter; -import org.mifos.mobile.ui.views.LoanRepaymentScheduleMvpView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mifos.mobile.utils.Constants; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 27/6/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class LoanRepaymentSchedulePresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - LoanRepaymentScheduleMvpView view; - - private LoanRepaymentSchedulePresenter presenter; - private LoanWithAssociations loanWithRepaymentSchedule, loanWithEmptyRepaymentSchedule; - - @Before - public void setUp() throws Exception { - presenter = new LoanRepaymentSchedulePresenter(context, dataManager); - presenter.attachView(view); - - loanWithRepaymentSchedule = FakeRemoteDataSource.getLoanAccountRepaymentSchedule(); - loanWithEmptyRepaymentSchedule = FakeRemoteDataSource. - getLoanAccountEmptyRepaymentSchedule(); - - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testLoadLoanAccountDetails() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 29)). - thenReturn(Observable.just(loanWithRepaymentSchedule)); - - presenter.loanLoanWithAssociations(29); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoanRepaymentSchedule(loanWithRepaymentSchedule); - verify(view, never()).showEmptyRepaymentsSchedule(null); - verify(view, never()).showError(context. - getString(R.string.error_fetching_repayment_schedule)); - - } - - @Test - public void testLoadLoanAccountDetailsEmpty() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 29)). - thenReturn(Observable.just(loanWithEmptyRepaymentSchedule)); - - presenter.loanLoanWithAssociations(29); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showEmptyRepaymentsSchedule(loanWithEmptyRepaymentSchedule); - verify(view, never()).showLoanRepaymentSchedule(null); - verify(view, never()).showError(context. - getString(R.string.error_fetching_repayment_schedule)); - - } - - - @Test - public void testLoadLoanAccountDetailsFails() throws Exception { - when(dataManager.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 29)). - thenReturn(Observable.error(new RuntimeException())); - - presenter.loanLoanWithAssociations(29); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString(R.string.error_fetching_repayment_schedule)); - verify(view, never()).showEmptyRepaymentsSchedule(null); - verify(view, never()).showLoanRepaymentSchedule(null); - - } -} diff --git a/app/src/test/java/org/mifos/mobile/LoanRepaymentSchedulePresenterTest.kt b/app/src/test/java/org/mifos/mobile/LoanRepaymentSchedulePresenterTest.kt new file mode 100644 index 0000000000..c13087a3e2 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/LoanRepaymentSchedulePresenterTest.kt @@ -0,0 +1,95 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.accounts.loan.LoanWithAssociations +import org.mifos.mobile.presenters.LoanRepaymentSchedulePresenter +import org.mifos.mobile.ui.views.LoanRepaymentScheduleMvpView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mifos.mobile.utils.Constants + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 27/6/17. + */ +@RunWith(MockitoJUnitRunner::class) +class LoanRepaymentSchedulePresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: LoanRepaymentScheduleMvpView? = null + private var presenter: LoanRepaymentSchedulePresenter? = null + private var loanWithRepaymentSchedule: LoanWithAssociations? = null + private var loanWithEmptyRepaymentSchedule: LoanWithAssociations? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = LoanRepaymentSchedulePresenter(context, dataManager!!) + presenter?.attachView(view) + loanWithRepaymentSchedule = FakeRemoteDataSource.loanAccountRepaymentSchedule + loanWithEmptyRepaymentSchedule = FakeRemoteDataSource.loanAccountEmptyRepaymentSchedule + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetails() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 29)).thenReturn(Observable.just(loanWithRepaymentSchedule)) + presenter?.loanLoanWithAssociations(29) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoanRepaymentSchedule(loanWithRepaymentSchedule) + Mockito.verify(view, Mockito.never())?.showEmptyRepaymentsSchedule(null) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_repayment_schedule)) + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetailsEmpty() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 29)).thenReturn(Observable.just(loanWithEmptyRepaymentSchedule)) + presenter?.loanLoanWithAssociations(29) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showEmptyRepaymentsSchedule(loanWithEmptyRepaymentSchedule) + Mockito.verify(view, Mockito.never())?.showLoanRepaymentSchedule(null) + Mockito.verify(view, Mockito.never())?.showError(context?.getString(R.string.error_fetching_repayment_schedule)) + } + + @Test + @Throws(Exception::class) + fun testLoadLoanAccountDetailsFails() { + Mockito.`when`(dataManager?.getLoanWithAssociations(Constants.REPAYMENT_SCHEDULE, 29)).thenReturn(Observable.error(RuntimeException())) + presenter?.loanLoanWithAssociations(29) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString(R.string.error_fetching_repayment_schedule)) + Mockito.verify(view, Mockito.never())?.showEmptyRepaymentsSchedule(null) + Mockito.verify(view, Mockito.never())?.showLoanRepaymentSchedule(null) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/LoginPresenterTest.java b/app/src/test/java/org/mifos/mobile/LoginPresenterTest.java deleted file mode 100644 index 9a08bf8d99..0000000000 --- a/app/src/test/java/org/mifos/mobile/LoginPresenterTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.BaseURL; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.User; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.presenters.LoginPresenter; -import org.mifos.mobile.ui.views.LoginView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 27/6/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class LoginPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - PreferencesHelper mockHelper; - - @Mock - LoginView view; - - private LoginPresenter presenter; - private User user; - private Page clientPage, noClientPage; - - @Before - public void setUp() throws Exception { - - when(mockHelper.getBaseUrl()).thenReturn(BaseURL.PROTOCOL_HTTPS + BaseURL.API_ENDPOINT); - when(dataManager.getPreferencesHelper()).thenReturn(mockHelper); - - presenter = new LoginPresenter(dataManager, context); - presenter.attachView(view); - - user = FakeRemoteDataSource.getUser(); - clientPage = FakeRemoteDataSource.getClients(); - noClientPage = FakeRemoteDataSource.getNoClients(); - } - - @Test - public void testLogin() throws Exception { - when(dataManager.login("selfservice", "password")).thenReturn(Observable.just(user)); - - presenter.login("selfservice", "password"); - - verify(view).showProgress(); - verify(view).onLoginSuccess(user.getUsername()); - } - - @Test - public void testLoadClients() throws Exception { - long clientId = clientPage.getPageItems().get(0).getId(); - when(dataManager.getClients()).thenReturn(Observable.just(clientPage)); - - presenter.loadClient(); - - verify(view).hideProgress(); - verify(view).showPassCodeActivity(); - verify(view, never()).showMessage(context.getString(R.string.error_fetching_client)); - } - - @Test - public void testLoadNoClients() throws Exception { - long clientId = clientPage.getPageItems().get(0).getId(); - when(dataManager.getClients()).thenReturn(Observable.just(noClientPage)); - - presenter.loadClient(); - - verify(view).hideProgress(); - verify(view).showMessage(context.getString(R.string.error_client_not_found)); - verify(view, never()).showPassCodeActivity(); - } - - @Test - public void testLoadClientFails() throws Exception { - when(dataManager.getClients()).thenReturn(Observable.>error(RetrofitUtils. - get404Exception())); - - presenter.loadClient(); - - verify(view).hideProgress(); - verify(view).showMessage(context.getString(R.string.error_fetching_client)); - verify(view, never()).showPassCodeActivity(); - } - - @Test - public void testLoadClientUnauthorized() throws Exception { - when(dataManager.getClients()).thenReturn(Observable.>error(RetrofitUtils. - get401Exception())); - - presenter.loadClient(); - - verify(view).hideProgress(); - verify(view).showMessage(context.getString(R.string.unauthorized_client)); - verify(view, never()).showPassCodeActivity(); - } - @After - public void tearDown() throws Exception { - presenter.detachView(); - } -} diff --git a/app/src/test/java/org/mifos/mobile/LoginPresenterTest.kt b/app/src/test/java/org/mifos/mobile/LoginPresenterTest.kt new file mode 100644 index 0000000000..a77a69fddd --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/LoginPresenterTest.kt @@ -0,0 +1,123 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.BaseURL +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.Page +import org.mifos.mobile.models.User +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.payload.LoginPayload +import org.mifos.mobile.presenters.LoginPresenter +import org.mifos.mobile.ui.views.LoginView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 27/6/17. + */ +@RunWith(MockitoJUnitRunner::class) +class LoginPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var mockHelper: PreferencesHelper? = null + + @Mock + var view: LoginView? = null + private var presenter: LoginPresenter? = null + private var user: User? = null + private var clientPage: Page? = null + private var noClientPage: Page? = null + private var loginPayload: LoginPayload? = null + + @Before + @Throws(Exception::class) + fun setUp() { + Mockito.`when`(mockHelper?.baseUrl).thenReturn(BaseURL.PROTOCOL_HTTPS + BaseURL.API_ENDPOINT) + Mockito.`when`(dataManager?.preferencesHelper).thenReturn(mockHelper) + presenter = LoginPresenter(dataManager, context) + presenter?.attachView(view) + user = FakeRemoteDataSource.user + clientPage = FakeRemoteDataSource.clients + noClientPage = FakeRemoteDataSource.noClients + loginPayload = FakeRemoteDataSource.loginPayload + } + + @Test + @Throws(Exception::class) + fun testLogin() { + Mockito.`when`(dataManager?.login(loginPayload)).thenReturn(Observable.just(user)) + presenter?.login(loginPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.onLoginSuccess(user?.username) + } + + @Test + @Throws(Exception::class) + fun testLoadClients() { + val clientId = clientPage?.pageItems?.get(0)?.id?.toLong() + Mockito.`when`(dataManager?.clients).thenReturn(Observable.just(clientPage)) + presenter?.loadClient() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showPassCodeActivity() + Mockito.verify(view, Mockito.never())?.showMessage(context?.getString(R.string.error_fetching_client)) + } + + @Test + @Throws(Exception::class) + fun testLoadNoClients() { + val clientId = clientPage?.pageItems?.get(0)?.id?.toLong() + Mockito.`when`(dataManager?.clients).thenReturn(Observable.just(noClientPage)) + presenter?.loadClient() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showMessage(context?.getString(R.string.error_client_not_found)) + Mockito.verify(view, Mockito.never())?.showPassCodeActivity() + } + + @Test + @Throws(Exception::class) + fun testLoadClientFails() { + Mockito.`when`(dataManager?.clients).thenReturn(Observable.error(RetrofitUtils.get404Exception())) + presenter?.loadClient() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showMessage(context?.getString(R.string.error_fetching_client)) + Mockito.verify(view, Mockito.never())?.showPassCodeActivity() + } + + @Test + @Throws(Exception::class) + fun testLoadClientUnauthorized() { + Mockito.`when`(dataManager?.clients).thenReturn(Observable.error(RetrofitUtils.get401Exception())) + presenter?.loadClient() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showMessage(context?.getString(R.string.unauthorized_client)) + Mockito.verify(view, Mockito.never())?.showPassCodeActivity() + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/NotificationPresenterTest.java b/app/src/test/java/org/mifos/mobile/NotificationPresenterTest.java deleted file mode 100644 index 95c414ad75..0000000000 --- a/app/src/test/java/org/mifos/mobile/NotificationPresenterTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.notification.MifosNotification; -import org.mifos.mobile.presenters.NotificationPresenter; -import org.mifos.mobile.ui.views.NotificationView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.ArrayList; -import java.util.List; - -import io.reactivex.Observable; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class NotificationPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - NotificationView view; - - private NotificationPresenter presenter; - - @Before - public void setUp() throws Exception { - presenter = new NotificationPresenter(dataManager, context); - presenter.attachView(view); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testLoadNotifications() { - List list = new ArrayList<>(); - when(dataManager.getNotifications()) - .thenReturn(Observable.just(list)); - presenter.loadNotifications(); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showNotifications(list); - } - - @Test - public void testLoadNotificationsOnError() { - when(dataManager.getNotifications()) - .thenReturn(Observable.>error(new Throwable())); - presenter.loadNotifications(); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context - .getString(R.string.notification)); - } -} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/NotificationPresenterTest.kt b/app/src/test/java/org/mifos/mobile/NotificationPresenterTest.kt new file mode 100644 index 0000000000..b3a0da70f4 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/NotificationPresenterTest.kt @@ -0,0 +1,75 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.notification.MifosNotification +import org.mifos.mobile.presenters.NotificationPresenter +import org.mifos.mobile.ui.views.NotificationView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +import java.util.* + +@RunWith(MockitoJUnitRunner::class) +class NotificationPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: NotificationView? = null + private var presenter: NotificationPresenter? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = NotificationPresenter(dataManager!!, context!!) + presenter?.attachView(view) + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoadNotifications() { + val list: List = ArrayList() + Mockito.`when`?>?>(dataManager?.notifications) + .thenReturn(Observable.just(list)) + presenter?.loadNotifications() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showNotifications(list) + } + + @Test + fun testLoadNotificationsOnError() { + Mockito.`when`(dataManager?.notifications) + .thenReturn(Observable.error(Throwable())) + presenter?.loadNotifications() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context + ?.getString(R.string.notification)) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/RecentTransactionsPresenterTest.java b/app/src/test/java/org/mifos/mobile/RecentTransactionsPresenterTest.java deleted file mode 100644 index 23d73d081f..0000000000 --- a/app/src/test/java/org/mifos/mobile/RecentTransactionsPresenterTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.Page; -import org.mifos.mobile.models.Transaction; -import org.mifos.mobile.presenters.RecentTransactionsPresenter; -import org.mifos.mobile.ui.views.RecentTransactionsView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class RecentTransactionsPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - RecentTransactionsView view; - - private RecentTransactionsPresenter presenter; - private Page recentTransaction; - private int offset, limit = 50; - - @Before - public void setUp() { - presenter = new RecentTransactionsPresenter(dataManager, context); - presenter.attachView(view); - - recentTransaction = FakeRemoteDataSource.getTransactions(); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testLoadRecentTransactionsZeroOffset() { - offset = 0; - when(dataManager.getRecentTransactions(offset, limit)).thenReturn(Observable.just( - recentTransaction)); - - presenter.loadRecentTransactions(false, offset); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showRecentTransactions(recentTransaction.getPageItems()); - verify(view, never()).showErrorFetchingRecentTransactions(context.getString(R.string. - error_recent_transactions_loading)); - } - - @Test - public void testLoadRecentTransactionsWithOffset() { - offset = 10; - when(dataManager.getRecentTransactions(offset, limit)).thenReturn(Observable.just( - recentTransaction)); - - presenter.loadRecentTransactions(true, offset); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showLoadMoreRecentTransactions(recentTransaction.getPageItems()); - verify(view, never()).showErrorFetchingRecentTransactions(context.getString(R.string. - error_recent_transactions_loading)); - } - - @Test - public void testLoadRecentTransactionsWithZeroTransactions() { - offset = 0; - when(dataManager.getRecentTransactions(offset, limit)).thenReturn(Observable.just( - new Page())); - - presenter.loadRecentTransactions(false, offset); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showEmptyTransaction(); - verify(view, never()).showErrorFetchingRecentTransactions(context.getString(R.string. - error_recent_transactions_loading)); - } - - @Test - public void testLoadRecentTransactionsFails() { - offset = 0; - when(dataManager.getRecentTransactions(offset, limit)).thenReturn(Observable. - >error(new RuntimeException())); - - presenter.loadRecentTransactions(false, offset); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showErrorFetchingRecentTransactions(context.getString(R.string. - error_recent_transactions_loading)); - verify(view, never()).showEmptyTransaction(); - } - -} diff --git a/app/src/test/java/org/mifos/mobile/RecentTransactionsPresenterTest.kt b/app/src/test/java/org/mifos/mobile/RecentTransactionsPresenterTest.kt new file mode 100644 index 0000000000..634a0a49a8 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/RecentTransactionsPresenterTest.kt @@ -0,0 +1,104 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.Page +import org.mifos.mobile.models.Transaction +import org.mifos.mobile.presenters.RecentTransactionsPresenter +import org.mifos.mobile.ui.views.RecentTransactionsView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class RecentTransactionsPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: RecentTransactionsView? = null + private var presenter: RecentTransactionsPresenter? = null + private var recentTransaction: Page? = null + private var offset = 0 + private val limit = 50 + + @Before + fun setUp() { + presenter = RecentTransactionsPresenter(dataManager!!, context!!) + presenter?.attachView(view) + recentTransaction = FakeRemoteDataSource.transactions + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoadRecentTransactionsZeroOffset() { + offset = 0 + Mockito.`when`(dataManager?.getRecentTransactions(offset, limit)).thenReturn(Observable.just( + recentTransaction)) + presenter?.loadRecentTransactions(false, offset) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showRecentTransactions(recentTransaction?.pageItems) + Mockito.verify(view, Mockito.never())?.showErrorFetchingRecentTransactions(context?.getString(R.string.error_recent_transactions_loading)) + } + + @Test + fun testLoadRecentTransactionsWithOffset() { + offset = 10 + Mockito.`when`(dataManager?.getRecentTransactions(offset, limit)).thenReturn(Observable.just( + recentTransaction)) + presenter?.loadRecentTransactions(true, offset) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showLoadMoreRecentTransactions(recentTransaction?.pageItems) + Mockito.verify(view, Mockito.never())?.showErrorFetchingRecentTransactions(context?.getString(R.string.error_recent_transactions_loading)) + } + + @Test + fun testLoadRecentTransactionsWithZeroTransactions() { + offset = 0 + Mockito.`when`(dataManager?.getRecentTransactions(offset, limit)).thenReturn(Observable.just( + Page())) + presenter?.loadRecentTransactions(false, offset) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showEmptyTransaction() + Mockito.verify(view, Mockito.never())?.showErrorFetchingRecentTransactions(context?.getString(R.string.error_recent_transactions_loading)) + } + + @Test + fun testLoadRecentTransactionsFails() { + offset = 0 + Mockito.`when`(dataManager?.getRecentTransactions(offset, limit)).thenReturn(Observable.error(RuntimeException())) + presenter?.loadRecentTransactions(false, offset) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showErrorFetchingRecentTransactions(context?.getString(R.string.error_recent_transactions_loading)) + Mockito.verify(view, Mockito.never())?.showEmptyTransaction() + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/RegistrationPresenterTest.java b/app/src/test/java/org/mifos/mobile/RegistrationPresenterTest.java deleted file mode 100644 index 12ed658e37..0000000000 --- a/app/src/test/java/org/mifos/mobile/RegistrationPresenterTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.register.RegisterPayload; -import org.mifos.mobile.presenters.RegistrationPresenter; -import org.mifos.mobile.ui.views.RegistrationView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by Chirag Gupta on 11/29/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class RegistrationPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - RegistrationView view; - - @Mock - ResponseBody responseBody; - - private RegistrationPresenter presenter; - private RegisterPayload registerPayload; - - @Before - public void setUp() throws Exception { - presenter = new RegistrationPresenter(dataManager, context); - presenter.attachView(view); - - registerPayload = FakeRemoteDataSource.getRegisterPayload(); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testRegisterUser() throws Exception { - when(dataManager.registerUser(registerPayload)).thenReturn(Observable.just(responseBody)); - - presenter.registerUser(registerPayload); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showRegisteredSuccessfully(); - verify(view, never()).showError(""); - } - - @Test - public void testRegisterUserFails() throws Exception { - when(dataManager.registerUser(registerPayload)).thenReturn(Observable. - error(new RuntimeException())); - - presenter.registerUser(registerPayload); - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showRegisteredSuccessfully(); - verify(view).showError(""); - } -} - - - diff --git a/app/src/test/java/org/mifos/mobile/RegistrationPresenterTest.kt b/app/src/test/java/org/mifos/mobile/RegistrationPresenterTest.kt new file mode 100644 index 0000000000..e3ce98c5dc --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/RegistrationPresenterTest.kt @@ -0,0 +1,83 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.register.RegisterPayload +import org.mifos.mobile.presenters.RegistrationPresenter +import org.mifos.mobile.ui.views.RegistrationView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by Chirag Gupta on 11/29/17. + */ +@RunWith(MockitoJUnitRunner::class) +class RegistrationPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: RegistrationView? = null + + @Mock + var responseBody: ResponseBody? = null + private var presenter: RegistrationPresenter? = null + private var registerPayload: RegisterPayload? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = RegistrationPresenter(dataManager!!, context) + presenter?.attachView(view!!) + registerPayload = FakeRemoteDataSource.registerPayload + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + @Throws(Exception::class) + fun testRegisterUser() { + Mockito.`when`?>(dataManager?.registerUser(registerPayload)).thenReturn(Observable.just(responseBody)) + presenter?.registerUser(registerPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showRegisteredSuccessfully() + Mockito.verify(view, Mockito.never())?.showError("") + } + + @Test + @Throws(Exception::class) + fun testRegisterUserFails() { + Mockito.`when`(dataManager?.registerUser(registerPayload)).thenReturn(Observable.error(RuntimeException())) + presenter?.registerUser(registerPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showRegisteredSuccessfully() + Mockito.verify(view)?.showError("") + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/RegistrationVerificationPresenterTest.java b/app/src/test/java/org/mifos/mobile/RegistrationVerificationPresenterTest.java deleted file mode 100644 index 4fe5e0c064..0000000000 --- a/app/src/test/java/org/mifos/mobile/RegistrationVerificationPresenterTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.register.UserVerify; -import org.mifos.mobile.presenters.RegistrationVerificationPresenter; -import org.mifos.mobile.ui.views.RegistrationVerificationView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by Sean Kelly on 9/12/17. - */ - -@RunWith(MockitoJUnitRunner.class) -public class RegistrationVerificationPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - RegistrationVerificationView view; - - @Mock - ResponseBody responseBody; - - private RegistrationVerificationPresenter presenter; - private UserVerify userVerify; - - @Before - public void setUp() throws Exception { - presenter = new RegistrationVerificationPresenter(dataManager, context); - presenter.attachView(view); - - userVerify = FakeRemoteDataSource.getUserVerify(); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testVerifyUser() throws Exception { - when(dataManager.verifyUser(userVerify)).thenReturn(Observable.just(responseBody)); - - presenter.verifyUser(userVerify); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showVerifiedSuccessfully(); - verify(view, never()).showError(""); - } - - @Test - public void testVerifyUserFails() throws Exception { - when(dataManager.verifyUser(userVerify)).thenReturn(Observable.error(new - RuntimeException())); - - presenter.verifyUser(userVerify); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showVerifiedSuccessfully(); - verify(view).showError(""); - } - -} diff --git a/app/src/test/java/org/mifos/mobile/RegistrationVerificationPresenterTest.kt b/app/src/test/java/org/mifos/mobile/RegistrationVerificationPresenterTest.kt new file mode 100644 index 0000000000..d0bb780104 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/RegistrationVerificationPresenterTest.kt @@ -0,0 +1,83 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.register.UserVerify +import org.mifos.mobile.presenters.RegistrationVerificationPresenter +import org.mifos.mobile.ui.views.RegistrationVerificationView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by Sean Kelly on 9/12/17. + */ +@RunWith(MockitoJUnitRunner::class) +class RegistrationVerificationPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: RegistrationVerificationView? = null + + @Mock + var responseBody: ResponseBody? = null + private var presenter: RegistrationVerificationPresenter? = null + private var userVerify: UserVerify? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = RegistrationVerificationPresenter(dataManager!!, context!!) + presenter?.attachView(view) + userVerify = FakeRemoteDataSource.userVerify + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + @Throws(Exception::class) + fun testVerifyUser() { + Mockito.`when`?>(dataManager?.verifyUser(userVerify)).thenReturn(Observable.just(responseBody)) + presenter?.verifyUser(userVerify) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showVerifiedSuccessfully() + Mockito.verify(view, Mockito.never())?.showError("") + } + + @Test + @Throws(Exception::class) + fun testVerifyUserFails() { + Mockito.`when`(dataManager?.verifyUser(userVerify)).thenReturn(Observable.error(RuntimeException())) + presenter?.verifyUser(userVerify) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showVerifiedSuccessfully() + Mockito.verify(view)?.showError("") + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/SavingAccountDetailPresenterTest.java b/app/src/test/java/org/mifos/mobile/SavingAccountDetailPresenterTest.java deleted file mode 100644 index a1169ba2c1..0000000000 --- a/app/src/test/java/org/mifos/mobile/SavingAccountDetailPresenterTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.presenters.SavingAccountsDetailPresenter; -import org.mifos.mobile.ui.views.SavingAccountsDetailView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mifos.mobile.utils.Constants; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class SavingAccountDetailPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - SavingAccountsDetailView view; - - private SavingsWithAssociations savingsWithAssociations; - private SavingAccountsDetailPresenter presenter; - - @Before - public void setUp() { - - presenter = new SavingAccountsDetailPresenter(dataManager, context); - presenter.attachView(view); - - savingsWithAssociations = FakeRemoteDataSource.getSavingsWithAssociations(); - } - - @Test - public void testLoadSavingsWithAssociations() { - when(dataManager.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( - Observable.just(savingsWithAssociations)); - - presenter.loadSavingsWithAssociations(1); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showSavingAccountsDetail(savingsWithAssociations); - verify(view, never()).showErrorFetchingSavingAccountsDetail(context.getString(R.string. - error_saving_account_details_loading)); - } - - @Test - public void testLoadSavingsWithAssociationsFails() { - when(dataManager.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( - Observable.error(new RuntimeException())); - - presenter.loadSavingsWithAssociations(1); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showErrorFetchingSavingAccountsDetail(context.getString(R.string. - error_saving_account_details_loading)); - verify(view, never()).showSavingAccountsDetail(savingsWithAssociations); - } - -} diff --git a/app/src/test/java/org/mifos/mobile/SavingAccountDetailPresenterTest.kt b/app/src/test/java/org/mifos/mobile/SavingAccountDetailPresenterTest.kt new file mode 100644 index 0000000000..4edec34cea --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/SavingAccountDetailPresenterTest.kt @@ -0,0 +1,71 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.presenters.SavingAccountsDetailPresenter +import org.mifos.mobile.ui.views.SavingAccountsDetailView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mifos.mobile.utils.Constants + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class SavingAccountDetailPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: SavingAccountsDetailView? = null + private var savingsWithAssociations: SavingsWithAssociations? = null + private var presenter: SavingAccountsDetailPresenter? = null + + @Before + fun setUp() { + presenter = SavingAccountsDetailPresenter(dataManager!!, context) + presenter?.attachView(view) + savingsWithAssociations = FakeRemoteDataSource.savingsWithAssociations + } + + @Test + fun testLoadSavingsWithAssociations() { + Mockito.`when`(dataManager?.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( + Observable.just(savingsWithAssociations)) + presenter?.loadSavingsWithAssociations(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showSavingAccountsDetail(savingsWithAssociations) + Mockito.verify(view, Mockito.never())?.showErrorFetchingSavingAccountsDetail(context?.getString(R.string.error_saving_account_details_loading)) + } + + @Test + fun testLoadSavingsWithAssociationsFails() { + Mockito.`when`(dataManager?.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( + Observable.error(RuntimeException())) + presenter?.loadSavingsWithAssociations(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showErrorFetchingSavingAccountsDetail(context?.getString(R.string.error_saving_account_details_loading)) + Mockito.verify(view, Mockito.never())?.showSavingAccountsDetail(savingsWithAssociations) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/SavingAccountTransactionPresenterTest.java b/app/src/test/java/org/mifos/mobile/SavingAccountTransactionPresenterTest.java deleted file mode 100644 index b49672a917..0000000000 --- a/app/src/test/java/org/mifos/mobile/SavingAccountTransactionPresenterTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations; -import org.mifos.mobile.presenters.SavingAccountsTransactionPresenter; -import org.mifos.mobile.ui.views.SavingAccountsTransactionView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mifos.mobile.utils.Constants; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class SavingAccountTransactionPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - SavingAccountsTransactionView view; - - private SavingsWithAssociations savingsWithAssociations; - private SavingAccountsTransactionPresenter presenter; - - @Before - public void setUp() { - - presenter = new SavingAccountsTransactionPresenter(dataManager, context); - presenter.attachView(view); - - savingsWithAssociations = FakeRemoteDataSource.getSavingsWithAssociations(); - } - - @Test - public void testLoadSavingsWithAssociations() { - when(dataManager.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( - Observable.just(savingsWithAssociations)); - - presenter.loadSavingsWithAssociations(1); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showSavingAccountsDetail(savingsWithAssociations); - verify(view, never()).showErrorFetchingSavingAccountsDetail(context.getString(R.string. - error_saving_account_details_loading)); - } - - @Test - public void testLoadSavingsWithAssociationsFails() { - when(dataManager.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( - Observable.error(new RuntimeException())); - - presenter.loadSavingsWithAssociations(1); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showErrorFetchingSavingAccountsDetail(context.getString(R.string. - error_saving_account_details_loading)); - verify(view, never()).showSavingAccountsDetail(savingsWithAssociations); - } - -} diff --git a/app/src/test/java/org/mifos/mobile/SavingAccountTransactionPresenterTest.kt b/app/src/test/java/org/mifos/mobile/SavingAccountTransactionPresenterTest.kt new file mode 100644 index 0000000000..e00525bda7 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/SavingAccountTransactionPresenterTest.kt @@ -0,0 +1,71 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.accounts.savings.SavingsWithAssociations +import org.mifos.mobile.presenters.SavingAccountsTransactionPresenter +import org.mifos.mobile.ui.views.SavingAccountsTransactionView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mifos.mobile.utils.Constants + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class SavingAccountTransactionPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: SavingAccountsTransactionView? = null + private var savingsWithAssociations: SavingsWithAssociations? = null + private var presenter: SavingAccountsTransactionPresenter? = null + + @Before + fun setUp() { + presenter = SavingAccountsTransactionPresenter(dataManager!!, context) + presenter?.attachView(view) + savingsWithAssociations = FakeRemoteDataSource.savingsWithAssociations + } + + @Test + fun testLoadSavingsWithAssociations() { + Mockito.`when`(dataManager?.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( + Observable.just(savingsWithAssociations)) + presenter?.loadSavingsWithAssociations(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showSavingAccountsDetail(savingsWithAssociations) + Mockito.verify(view, Mockito.never())?.showErrorFetchingSavingAccountsDetail(context?.getString(R.string.error_saving_account_details_loading)) + } + + @Test + fun testLoadSavingsWithAssociationsFails() { + Mockito.`when`(dataManager?.getSavingsWithAssociations(1, Constants.TRANSACTIONS)).thenReturn( + Observable.error(RuntimeException())) + presenter?.loadSavingsWithAssociations(1) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showErrorFetchingSavingAccountsDetail(context?.getString(R.string.error_saving_account_details_loading)) + Mockito.verify(view, Mockito.never())?.showSavingAccountsDetail(savingsWithAssociations) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/SavingsAccountWithdrawPresenterTest.java b/app/src/test/java/org/mifos/mobile/SavingsAccountWithdrawPresenterTest.java deleted file mode 100644 index b4c9754cb2..0000000000 --- a/app/src/test/java/org/mifos/mobile/SavingsAccountWithdrawPresenterTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload; -import org.mifos.mobile.presenters.SavingsAccountWithdrawPresenter; -import org.mifos.mobile.ui.views.SavingsAccountWithdrawView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class SavingsAccountWithdrawPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - SavingsAccountWithdrawView view; - - private SavingsAccountWithdrawPresenter presenter; - - @Mock - SavingsAccountWithdrawPayload payload; - - @Mock - ResponseBody responseBody; - - @Before - public void setUp() throws Exception { - presenter = new SavingsAccountWithdrawPresenter(dataManager, context); - presenter.attachView(view); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testSubmitWithdrawSavingsAccount() { - String accountId = "1"; - when(dataManager.submitWithdrawSavingsAccount(accountId, payload)) - .thenReturn(Observable.just(responseBody)); - presenter.submitWithdrawSavingsAccount(accountId, payload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showSavingsAccountWithdrawSuccessfully(); - } - - @Test - public void testSubmitWithdrawSavingsAccountOnError() { - String accountId = "1"; - Exception exception = new Exception("message"); - when(dataManager.submitWithdrawSavingsAccount(accountId, payload)) - .thenReturn(Observable.error(exception)); - presenter.submitWithdrawSavingsAccount(accountId, payload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(exception.getMessage()); - } - -} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/SavingsAccountWithdrawPresenterTest.kt b/app/src/test/java/org/mifos/mobile/SavingsAccountWithdrawPresenterTest.kt new file mode 100644 index 0000000000..3c97dbde42 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/SavingsAccountWithdrawPresenterTest.kt @@ -0,0 +1,80 @@ +package org.mifos.mobile + +import android.content.Context +import io.reactivex.Observable +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.accounts.savings.SavingsAccountWithdrawPayload +import org.mifos.mobile.presenters.SavingsAccountWithdrawPresenter +import org.mifos.mobile.ui.views.SavingsAccountWithdrawView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class SavingsAccountWithdrawPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: SavingsAccountWithdrawView? = null + private var presenter: SavingsAccountWithdrawPresenter? = null + + @Mock + var payload: SavingsAccountWithdrawPayload? = null + + @Mock + var responseBody: ResponseBody? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = SavingsAccountWithdrawPresenter(dataManager!!, context!!) + presenter?.attachView(view) + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testSubmitWithdrawSavingsAccount() { + val accountId = "1" + Mockito.`when`(dataManager?.submitWithdrawSavingsAccount(accountId, payload)) + .thenReturn(Observable.just(responseBody)) + presenter?.submitWithdrawSavingsAccount(accountId, payload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showSavingsAccountWithdrawSuccessfully() + } + + @Test + fun testSubmitWithdrawSavingsAccountOnError() { + val accountId = "1" + val exception = Exception("message") + Mockito.`when`(dataManager?.submitWithdrawSavingsAccount(accountId, payload)) + .thenReturn(Observable.error(exception)) + presenter?.submitWithdrawSavingsAccount(accountId, payload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(exception.message) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/SavingsMakeTransferPresenterTest.java b/app/src/test/java/org/mifos/mobile/SavingsMakeTransferPresenterTest.java deleted file mode 100644 index d051ed7c9f..0000000000 --- a/app/src/test/java/org/mifos/mobile/SavingsMakeTransferPresenterTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.presenters.SavingsMakeTransferPresenter; -import org.mifos.mobile.ui.views.SavingsMakeTransferMvpView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class SavingsMakeTransferPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - SavingsMakeTransferMvpView view; - - private AccountOptionsTemplate accountOptionsTemplate; - private SavingsMakeTransferPresenter presenter; - - @Before - public void setUp() { - presenter = new SavingsMakeTransferPresenter(dataManager, context); - presenter.attachView(view); - - accountOptionsTemplate = FakeRemoteDataSource.getAccountOptionsTemplate(); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testLoanAccountTransferTemplate() { - when(dataManager.getAccountTransferTemplate()).thenReturn(Observable. - just(accountOptionsTemplate)); - - presenter.loanAccountTransferTemplate(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showSavingsAccountTemplate(accountOptionsTemplate); - verify(view, never()).showError(context.getString( - R.string.error_fetching_account_transfer_template)); - } - - @Test - public void testLoanAccountTransferTemplateFails() { - when(dataManager.getAccountTransferTemplate()).thenReturn(Observable. - error(new RuntimeException())); - - presenter.loanAccountTransferTemplate(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString( - R.string.error_fetching_account_transfer_template)); - verify(view, never()).showSavingsAccountTemplate(accountOptionsTemplate); - } -} diff --git a/app/src/test/java/org/mifos/mobile/SavingsMakeTransferPresenterTest.kt b/app/src/test/java/org/mifos/mobile/SavingsMakeTransferPresenterTest.kt new file mode 100644 index 0000000000..68c1b31d0f --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/SavingsMakeTransferPresenterTest.kt @@ -0,0 +1,76 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.presenters.SavingsMakeTransferPresenter +import org.mifos.mobile.ui.views.SavingsMakeTransferMvpView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class SavingsMakeTransferPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: SavingsMakeTransferMvpView? = null + private var accountOptionsTemplate: AccountOptionsTemplate? = null + private var presenter: SavingsMakeTransferPresenter? = null + + @Before + fun setUp() { + presenter = SavingsMakeTransferPresenter(dataManager!!, context) + presenter?.attachView(view) + accountOptionsTemplate = FakeRemoteDataSource.accountOptionsTemplate + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testLoanAccountTransferTemplate() { + Mockito.`when`(dataManager?.accountTransferTemplate).thenReturn(Observable.just(accountOptionsTemplate)) + presenter?.loanAccountTransferTemplate() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showSavingsAccountTemplate(accountOptionsTemplate) + Mockito.verify(view, Mockito.never())?.showError(context?.getString( + R.string.error_fetching_account_transfer_template)) + } + + @Test + fun testLoanAccountTransferTemplateFails() { + Mockito.`when`(dataManager?.accountTransferTemplate).thenReturn(Observable.error(RuntimeException())) + presenter?.loanAccountTransferTemplate() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString( + R.string.error_fetching_account_transfer_template)) + Mockito.verify(view, Mockito.never())?.showSavingsAccountTemplate(accountOptionsTemplate) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/ThirdPartyTransferPresenterTest.java b/app/src/test/java/org/mifos/mobile/ThirdPartyTransferPresenterTest.java deleted file mode 100644 index a0036229ad..0000000000 --- a/app/src/test/java/org/mifos/mobile/ThirdPartyTransferPresenterTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.beneficiary.Beneficiary; -import org.mifos.mobile.models.templates.account.AccountOptionsTemplate; -import org.mifos.mobile.presenters.ThirdPartyTransferPresenter; -import org.mifos.mobile.ui.views.ThirdPartyTransferView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.util.List; - - -import io.reactivex.Observable; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class ThirdPartyTransferPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - ThirdPartyTransferView view; - - private AccountOptionsTemplate accountOptionsTemplate; - private ThirdPartyTransferPresenter presenter; - private List beneficiaryList; - - @Before - public void setUp() { - presenter = new ThirdPartyTransferPresenter(dataManager, context); - presenter.attachView(view); - - accountOptionsTemplate = FakeRemoteDataSource.getAccountOptionsTemplate(); - beneficiaryList = FakeRemoteDataSource.getBeneficiaries(); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testTransferTemplate() { - when(dataManager.getThirdPartyTransferTemplate()).thenReturn(Observable. - just(accountOptionsTemplate)); - when(dataManager.getBeneficiaryList()).thenReturn(Observable. - just(beneficiaryList)); - - presenter.loadTransferTemplate(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showThirdPartyTransferTemplate(accountOptionsTemplate); - verify(view).showBeneficiaryList(beneficiaryList); - verify(view, never()).showError(context.getString( - R.string.error_fetching_account_transfer_template)); - } - - @Test - public void testTransferTemplateFails() { - when(dataManager.getThirdPartyTransferTemplate()).thenReturn(Observable. - error(new RuntimeException())); - when(dataManager.getBeneficiaryList()).thenReturn(Observable. - >error(new RuntimeException())); - - presenter.loadTransferTemplate(); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(context.getString( - R.string.error_fetching_account_transfer_template)); - verify(view, never()).showThirdPartyTransferTemplate(accountOptionsTemplate); - verify(view, never()).showBeneficiaryList(beneficiaryList); - } -} diff --git a/app/src/test/java/org/mifos/mobile/ThirdPartyTransferPresenterTest.kt b/app/src/test/java/org/mifos/mobile/ThirdPartyTransferPresenterTest.kt new file mode 100644 index 0000000000..dd9e11ad56 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/ThirdPartyTransferPresenterTest.kt @@ -0,0 +1,83 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.beneficiary.Beneficiary +import org.mifos.mobile.models.templates.account.AccountOptionsTemplate +import org.mifos.mobile.presenters.ThirdPartyTransferPresenter +import org.mifos.mobile.ui.views.ThirdPartyTransferView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class ThirdPartyTransferPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: ThirdPartyTransferView? = null + private var accountOptionsTemplate: AccountOptionsTemplate? = null + private var presenter: ThirdPartyTransferPresenter? = null + private var beneficiaryList: List? = null + + @Before + fun setUp() { + presenter = ThirdPartyTransferPresenter(dataManager!!, context!!) + presenter?.attachView(view) + accountOptionsTemplate = FakeRemoteDataSource.accountOptionsTemplate + beneficiaryList = FakeRemoteDataSource.beneficiaries + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testTransferTemplate() { + Mockito.`when`(dataManager?.thirdPartyTransferTemplate).thenReturn(Observable.just(accountOptionsTemplate)) + Mockito.`when`(dataManager?.beneficiaryList).thenReturn(Observable.just(beneficiaryList)) + presenter?.loadTransferTemplate() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showThirdPartyTransferTemplate(accountOptionsTemplate) + Mockito.verify(view)?.showBeneficiaryList(beneficiaryList) + Mockito.verify(view, Mockito.never())?.showError(context?.getString( + R.string.error_fetching_account_transfer_template)) + } + + @Test + fun testTransferTemplateFails() { + Mockito.`when`(dataManager?.thirdPartyTransferTemplate).thenReturn(Observable.error(RuntimeException())) + Mockito.`when`(dataManager?.beneficiaryList).thenReturn(Observable.error(RuntimeException())) + presenter?.loadTransferTemplate() + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(context?.getString( + R.string.error_fetching_account_transfer_template)) + Mockito.verify(view, Mockito.never())?.showThirdPartyTransferTemplate(accountOptionsTemplate) + Mockito.verify(view, Mockito.never())?.showBeneficiaryList(beneficiaryList) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/TransferProcessPresenterTest.java b/app/src/test/java/org/mifos/mobile/TransferProcessPresenterTest.java deleted file mode 100644 index 54cd54a55d..0000000000 --- a/app/src/test/java/org/mifos/mobile/TransferProcessPresenterTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.models.payload.TransferPayload; -import org.mifos.mobile.presenters.TransferProcessPresenter; -import org.mifos.mobile.ui.views.TransferProcessView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Created by dilpreet on 24/7/17. - */ -@RunWith(MockitoJUnitRunner.class) -public class TransferProcessPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - TransferProcessView view; - - @Mock - ResponseBody mockedResponseBody; - - private TransferProcessPresenter presenter; - private TransferPayload transferPayload; - - @Before - public void setUp() { - presenter = new TransferProcessPresenter(dataManager, context); - presenter.attachView(view); - - transferPayload = FakeRemoteDataSource.getTransferPayload(); - } - - @After - public void tearDown() { - presenter.detachView(); - } - - @Test - public void testMakeSavingsTransfer() { - when(dataManager.makeTransfer(transferPayload)).thenReturn(Observable. - just(mockedResponseBody)); - - presenter.makeSavingsTransfer(transferPayload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showTransferredSuccessfully(); - } - - @Test - public void testMakeSavingsTransferFails() { - when(dataManager.makeTransfer(transferPayload)).thenReturn(Observable. - error(new RuntimeException())); - - presenter.makeSavingsTransfer(transferPayload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showTransferredSuccessfully(); - } - - @Test - public void testMakeTPTTransfer() { - when(dataManager.makeThirdPartyTransfer(transferPayload)).thenReturn(Observable. - just(mockedResponseBody)); - - presenter.makeTPTTransfer(transferPayload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showTransferredSuccessfully(); - } - - @Test - public void testMakeTPTTransferFails() { - when(dataManager.makeThirdPartyTransfer(transferPayload)).thenReturn(Observable. - error(new RuntimeException())); - - presenter.makeTPTTransfer(transferPayload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view, never()).showTransferredSuccessfully(); - } -} diff --git a/app/src/test/java/org/mifos/mobile/TransferProcessPresenterTest.kt b/app/src/test/java/org/mifos/mobile/TransferProcessPresenterTest.kt new file mode 100644 index 0000000000..ad32065eaf --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/TransferProcessPresenterTest.kt @@ -0,0 +1,95 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.models.payload.TransferPayload +import org.mifos.mobile.presenters.TransferProcessPresenter +import org.mifos.mobile.ui.views.TransferProcessView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +/** + * Created by dilpreet on 24/7/17. + */ +@RunWith(MockitoJUnitRunner::class) +class TransferProcessPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: TransferProcessView? = null + + @Mock + var mockedResponseBody: ResponseBody? = null + private var presenter: TransferProcessPresenter? = null + private var transferPayload: TransferPayload? = null + + @Before + fun setUp() { + presenter = TransferProcessPresenter(dataManager!!, context!!) + presenter?.attachView(view) + transferPayload = FakeRemoteDataSource.transferPayload + } + + @After + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testMakeSavingsTransfer() { + Mockito.`when`(dataManager?.makeTransfer(transferPayload)).thenReturn(Observable.just(mockedResponseBody)) + presenter?.makeSavingsTransfer(transferPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showTransferredSuccessfully() + } + + @Test + fun testMakeSavingsTransferFails() { + Mockito.`when`(dataManager?.makeTransfer(transferPayload)).thenReturn(Observable.error(RuntimeException())) + presenter?.makeSavingsTransfer(transferPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showTransferredSuccessfully() + } + + @Test + fun testMakeTPTTransfer() { + Mockito.`when`?>(dataManager?.makeThirdPartyTransfer(transferPayload)).thenReturn(Observable.just(mockedResponseBody)) + presenter?.makeTPTTransfer(transferPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showTransferredSuccessfully() + } + + @Test + fun testMakeTPTTransferFails() { + Mockito.`when`(dataManager?.makeThirdPartyTransfer(transferPayload)).thenReturn(Observable.error(RuntimeException())) + presenter?.makeTPTTransfer(transferPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view, Mockito.never())?.showTransferredSuccessfully() + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/UpdatePasswordPresenterTest.java b/app/src/test/java/org/mifos/mobile/UpdatePasswordPresenterTest.java deleted file mode 100644 index e5cfc01eff..0000000000 --- a/app/src/test/java/org/mifos/mobile/UpdatePasswordPresenterTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.BaseURL; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.UpdatePasswordPayload; -import org.mifos.mobile.presenters.UpdatePasswordPresenter; -import org.mifos.mobile.ui.views.UpdatePasswordView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mifos.mobile.utils.MFErrorParser; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.Credentials; -import okhttp3.ResponseBody; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - - -@RunWith(MockitoJUnitRunner.class) -public class UpdatePasswordPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - UpdatePasswordView view; - - @Mock - PreferencesHelper preferencesHelper; - - @Mock - ResponseBody responseBody; - - private UpdatePasswordPayload passwordPayload; - private UpdatePasswordPresenter presenter; - - @Before - public void setUp() throws Exception { - when(preferencesHelper.getBaseUrl()) - .thenReturn(BaseURL.PROTOCOL_HTTPS + BaseURL.API_ENDPOINT); - presenter = new UpdatePasswordPresenter(context, dataManager, preferencesHelper); - passwordPayload = FakeRemoteDataSource.getUpdatePasswordPayload(); - presenter.attachView(view); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void updateAccountPassword() { - when(dataManager.updateAccountPassword(passwordPayload)) - .thenReturn(Observable.just(responseBody)); - presenter.updateAccountPassword(passwordPayload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showPasswordUpdatedSuccessfully(); - } - - @Test - public void updateAccountPasswordOnError() { - Exception exception = new Exception("message"); - when(dataManager.updateAccountPassword(passwordPayload)) - .thenReturn(Observable.error(exception)); - presenter.updateAccountPassword(passwordPayload); - - verify(view).showProgress(); - verify(view).hideProgress(); - verify(view).showError(MFErrorParser.errorMessage(exception)); - } - - @Test - public void updateAuthenticationToken() { - String password = "password"; - presenter.updateAuthenticationToken(password); - String authenticationToken = Credentials.basic(preferencesHelper.getUserName(), password); - - verify(preferencesHelper).saveToken(authenticationToken); - } -} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/UpdatePasswordPresenterTest.kt b/app/src/test/java/org/mifos/mobile/UpdatePasswordPresenterTest.kt new file mode 100644 index 0000000000..77d778e0d7 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/UpdatePasswordPresenterTest.kt @@ -0,0 +1,96 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.Credentials +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.BaseURL +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.UpdatePasswordPayload +import org.mifos.mobile.presenters.UpdatePasswordPresenter +import org.mifos.mobile.ui.views.UpdatePasswordView +import org.mifos.mobile.util.RxSchedulersOverrideRule +import org.mifos.mobile.utils.MFErrorParser.errorMessage + +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class UpdatePasswordPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: UpdatePasswordView? = null + + @Mock + var preferencesHelper: PreferencesHelper? = null + + @Mock + var responseBody: ResponseBody? = null + private var passwordPayload: UpdatePasswordPayload? = null + private var presenter: UpdatePasswordPresenter? = null + + @Before + @Throws(Exception::class) + fun setUp() { + Mockito.`when`(preferencesHelper?.baseUrl) + .thenReturn(BaseURL.PROTOCOL_HTTPS + BaseURL.API_ENDPOINT) + presenter = UpdatePasswordPresenter(context!!, dataManager!!, preferencesHelper!!) + passwordPayload = FakeRemoteDataSource.updatePasswordPayload + presenter?.attachView(view) + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun updateAccountPassword() { + Mockito.`when`?>(dataManager?.updateAccountPassword(passwordPayload)) + .thenReturn(Observable.just(responseBody)) + presenter?.updateAccountPassword(passwordPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showPasswordUpdatedSuccessfully() + } + + @Test + fun updateAccountPasswordOnError() { + val exception = Exception("message") + Mockito.`when`(dataManager?.updateAccountPassword(passwordPayload)) + .thenReturn(Observable.error(exception)) + presenter?.updateAccountPassword(passwordPayload) + Mockito.verify(view)?.showProgress() + Mockito.verify(view)?.hideProgress() + Mockito.verify(view)?.showError(errorMessage(exception)) + } + + @Test + fun updateAuthenticationToken() { + val password = "password" + presenter?.updateAuthenticationToken(password) + val authenticationToken = Credentials.basic(preferencesHelper?.userName, password) + Mockito.verify(preferencesHelper)?.saveToken(authenticationToken) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/UserDetailsPresenterTest.java b/app/src/test/java/org/mifos/mobile/UserDetailsPresenterTest.java deleted file mode 100644 index 929d72a033..0000000000 --- a/app/src/test/java/org/mifos/mobile/UserDetailsPresenterTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.mifos.mobile; - -import android.content.Context; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mifos.mobile.api.DataManager; -import org.mifos.mobile.api.local.PreferencesHelper; -import org.mifos.mobile.models.client.Client; -import org.mifos.mobile.models.notification.NotificationRegisterPayload; -import org.mifos.mobile.presenters.UserDetailsPresenter; -import org.mifos.mobile.ui.views.UserDetailsView; -import org.mifos.mobile.util.RxSchedulersOverrideRule; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import io.reactivex.Observable; -import okhttp3.ResponseBody; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class UserDetailsPresenterTest { - - @Rule - public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); - - @Mock - Context context; - - @Mock - DataManager dataManager; - - @Mock - UserDetailsView view; - - @Mock - PreferencesHelper preferencesHelper; - - @Mock - ResponseBody responseBody; - - private UserDetailsPresenter presenter; - private Client client; - - @Before - public void setUp() throws Exception { - presenter = new UserDetailsPresenter(context, dataManager, preferencesHelper); - client = FakeRemoteDataSource.getCurrentClient(); - presenter.attachView(view); - } - - @After - public void tearDown() throws Exception { - presenter.detachView(); - } - - @Test - public void testGetUserDetails() { - when(dataManager.getCurrentClient()) - .thenReturn(Observable.just(client)); - presenter.getUserDetails(); - verify(view).showUserDetails(client); - } - - @Test - public void testGetUserDetailsFails() { - when(dataManager.getCurrentClient()) - .thenReturn(Observable.error(new Throwable())); - presenter.getUserDetails(); - - verify(view).showError(context - .getString(R.string.error_client_not_found)); - } - - @Test - public void testRegisterNotification() { - String token = "1"; - when(dataManager.registerNotification(any(NotificationRegisterPayload.class))) - .thenReturn(Observable.just(responseBody)); - presenter.registerNotification(token); - - verify(preferencesHelper).setSentTokenToServer(true); - verify(preferencesHelper).saveGcmToken(token); - } -} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/UserDetailsPresenterTest.kt b/app/src/test/java/org/mifos/mobile/UserDetailsPresenterTest.kt new file mode 100644 index 0000000000..e2a09b4414 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/UserDetailsPresenterTest.kt @@ -0,0 +1,91 @@ +package org.mifos.mobile + +import android.content.Context + +import io.reactivex.Observable + +import okhttp3.ResponseBody + +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +import org.mifos.mobile.api.DataManager +import org.mifos.mobile.api.local.PreferencesHelper +import org.mifos.mobile.models.client.Client +import org.mifos.mobile.models.notification.NotificationRegisterPayload +import org.mifos.mobile.presenters.UserDetailsPresenter +import org.mifos.mobile.ui.views.UserDetailsView +import org.mifos.mobile.util.RxSchedulersOverrideRule + +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnitRunner + +@RunWith(MockitoJUnitRunner::class) +class UserDetailsPresenterTest { + @Rule + @JvmField + val mOverrideSchedulersRule = RxSchedulersOverrideRule() + + @Mock + var context: Context? = null + + @Mock + var dataManager: DataManager? = null + + @Mock + var view: UserDetailsView? = null + + @Mock + var preferencesHelper: PreferencesHelper? = null + + @Mock + var responseBody: ResponseBody? = null + private var presenter: UserDetailsPresenter? = null + private var client: Client? = null + + @Before + @Throws(Exception::class) + fun setUp() { + presenter = UserDetailsPresenter(context!!, dataManager!!, preferencesHelper!!) + client = FakeRemoteDataSource.currentClient + presenter?.attachView(view) + } + + @After + @Throws(Exception::class) + fun tearDown() { + presenter?.detachView() + } + + @Test + fun testGetUserDetails() { + Mockito.`when`(dataManager?.currentClient) + .thenReturn(Observable.just(client)) + presenter?.userDetails + Mockito.verify(view)?.showUserDetails(client) + } + + @Test + fun testGetUserDetailsFails() { + Mockito.`when`(dataManager?.currentClient) + .thenReturn(Observable.error(Throwable())) + presenter?.userDetails + Mockito.verify(view)?.showError(context + ?.getString(R.string.error_client_not_found)) + } + + @Test + fun testRegisterNotification() { + val token = "1" + Mockito.`when`?>(dataManager?.registerNotification(ArgumentMatchers.any(NotificationRegisterPayload::class.java))) + .thenReturn(Observable.just(responseBody)) + presenter?.registerNotification(token) + Mockito.verify(preferencesHelper)?.setSentTokenToServer(true) + Mockito.verify(preferencesHelper)?.saveGcmToken(token) + } +} \ No newline at end of file diff --git a/app/src/test/java/org/mifos/mobile/util/RxSchedulersOverrideRule.java b/app/src/test/java/org/mifos/mobile/util/RxSchedulersOverrideRule.java deleted file mode 100644 index b614117624..0000000000 --- a/app/src/test/java/org/mifos/mobile/util/RxSchedulersOverrideRule.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.mifos.mobile.util; - -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import java.util.concurrent.Callable; - -import io.reactivex.Scheduler; -import io.reactivex.android.plugins.RxAndroidPlugins; -import io.reactivex.functions.Function; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; - - -/** - * This rule registers SchedulerHooks for RxJava and RxAndroid to ensure that subscriptions - * always subscribeOn and observeOn Schedulers.immediate(). - * Warning, this rule will reset RxAndroidPlugins and RxJavaPlugins before and after each test so - * if the application code uses RxJava plugins this may affect the behaviour of the testing method. - */ -public class RxSchedulersOverrideRule implements TestRule { - - private final Scheduler SCHEDULER_INSTANCE = Schedulers.trampoline(); - - private Function schedulerFunction = - new Function() { - @Override - public Scheduler apply(Scheduler scheduler) throws Exception { - return SCHEDULER_INSTANCE; - } - }; - - private Function, Scheduler> schedulerFunctionLazy = - new Function, Scheduler>() { - @Override - public Scheduler apply(Callable schedulerCallable) throws Exception { - return SCHEDULER_INSTANCE; - } - }; - - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - RxAndroidPlugins.reset(); - RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerFunctionLazy); - - RxJavaPlugins.reset(); - RxJavaPlugins.setIoSchedulerHandler(schedulerFunction); - RxJavaPlugins.setNewThreadSchedulerHandler(schedulerFunction); - RxJavaPlugins.setComputationSchedulerHandler(schedulerFunction); - - base.evaluate(); - - RxAndroidPlugins.reset(); - RxJavaPlugins.reset(); - } - }; - } -} diff --git a/app/src/test/java/org/mifos/mobile/util/RxSchedulersOverrideRule.kt b/app/src/test/java/org/mifos/mobile/util/RxSchedulersOverrideRule.kt new file mode 100644 index 0000000000..06df157d83 --- /dev/null +++ b/app/src/test/java/org/mifos/mobile/util/RxSchedulersOverrideRule.kt @@ -0,0 +1,46 @@ +package org.mifos.mobile.util + +import io.reactivex.Scheduler +import io.reactivex.android.plugins.RxAndroidPlugins +import io.reactivex.functions.Function +import io.reactivex.plugins.RxJavaPlugins +import io.reactivex.schedulers.Schedulers + +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement +import java.util.concurrent.Callable + +/** + * This rule registers SchedulerHooks for RxJava and RxAndroid to ensure that subscriptions + * always subscribeOn and observeOn Schedulers.immediate(). + * Warning, this rule will reset RxAndroidPlugins and RxJavaPlugins before and after each test so + * if the application code uses RxJava plugins this may affect the behaviour of the testing method. + */ +class RxSchedulersOverrideRule : TestRule { + + private val SCHEDULER_INSTANCE = Schedulers.trampoline() + + private val schedulerFunction: Function = + Function { SCHEDULER_INSTANCE } + + private val schedulerFunctionLazy: Function?, Scheduler> = + Function?, Scheduler> { SCHEDULER_INSTANCE } + + override fun apply(base: Statement, description: Description): Statement { + return object : Statement() { + @Throws(Throwable::class) + override fun evaluate() { + RxAndroidPlugins.reset() + RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerFunctionLazy) + RxJavaPlugins.reset() + RxJavaPlugins.setIoSchedulerHandler(schedulerFunction) + RxJavaPlugins.setNewThreadSchedulerHandler(schedulerFunction) + RxJavaPlugins.setComputationSchedulerHandler(schedulerFunction) + base.evaluate() + RxAndroidPlugins.reset() + RxJavaPlugins.reset() + } + } + } +} \ No newline at end of file diff --git a/app/src/test/resources/login.json b/app/src/test/resources/login.json new file mode 100644 index 0000000000..a8611bc48b --- /dev/null +++ b/app/src/test/resources/login.json @@ -0,0 +1,4 @@ +{ + "username": "selfservice", + "password": "password" +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 0c762fa9d7..669c1a99e4 100644 --- a/build.gradle +++ b/build.gradle @@ -36,6 +36,7 @@ ext { targetSdkVersion = 28 compileSdkVersion = 28 buildToolsVersion = '28.0.3' + ndkVersion = '21.3.6528147' // App dependencies supportLibraryVersion = '1.0.0' @@ -64,5 +65,6 @@ ext { mifosPasscodeVersion = '0.3.0' cropviewVersion = '1.1.7' multiDexVersion = '2.0.1' + annotationLibraryVersion ='1.1.0' } diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000000..f45d8f110c --- /dev/null +++ b/renovate.json @@ -0,0 +1,5 @@ +{ + "extends": [ + "config:base" + ] +}