Skip to content

Commit

Permalink
Add "delete account" button in settings
Browse files Browse the repository at this point in the history
  • Loading branch information
onyxvd committed Sep 19, 2024
1 parent c68d3a4 commit 09e9ec3
Show file tree
Hide file tree
Showing 7 changed files with 155 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.google.gson.JsonObject;

import org.bspb.smartbirds.pro.backend.dto.BaseResponse;
import org.bspb.smartbirds.pro.backend.dto.CheckSessionRequest;
import org.bspb.smartbirds.pro.backend.dto.DownloadsResponse;
import org.bspb.smartbirds.pro.backend.dto.FileId;
Expand All @@ -17,11 +18,13 @@
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Part;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;

Expand Down Expand Up @@ -96,4 +99,7 @@ public interface SmartBirdsApi {

@POST("bats")
Call<UploadFormResponse> createBat(@Body JsonObject request);

@DELETE("user/{id}")
Call<BaseResponse> deleteUser(@Path("id") long id);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.bspb.smartbirds.pro.backend.dto;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class BaseResponse {

@Expose
@SerializedName("error")
public String error;

@Expose
@SerializedName("success")
public boolean success;

@Override
public String toString() {
final StringBuffer sb = new StringBuffer("BaseResponse{");
sb.append("error='").append(error).append('\'');
sb.append(", success=").append(success);
sb.append('}');
return sb.toString();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package org.bspb.smartbirds.pro.ui.fragment

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.preference.ListPreference
import androidx.preference.MultiSelectListPreference
import androidx.preference.Preference
Expand All @@ -10,13 +12,21 @@ import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.google.gson.reflect.TypeToken
import org.bspb.smartbirds.pro.R
import org.bspb.smartbirds.pro.backend.Backend
import org.bspb.smartbirds.pro.backend.dto.BaseResponse
import org.bspb.smartbirds.pro.backend.dto.MapLayerItem
import org.bspb.smartbirds.pro.prefs.SmartBirdsPrefs
import org.bspb.smartbirds.pro.prefs.UserPrefs
import org.bspb.smartbirds.pro.tools.DBExporter
import org.bspb.smartbirds.pro.tools.SBGsonParser
import org.bspb.smartbirds.pro.ui.MainActivity
import org.bspb.smartbirds.pro.ui.map.MapProvider
import org.bspb.smartbirds.pro.utils.KmlUtils
import org.bspb.smartbirds.pro.utils.debugLog
import org.bspb.smartbirds.pro.utils.showAlert
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class SettingsFragment : PreferenceFragmentCompat() {
Expand All @@ -26,7 +36,12 @@ class SettingsFragment : PreferenceFragmentCompat() {
private var exportPreference: Preference? = null
private var showKmlPreference: SwitchPreferenceCompat? = null
private var importedKmlPreference: Preference? = null
private var deleteAccountPreference: Preference? = null

private var prefs: SmartBirdsPrefs? = null
private var userPrefs: UserPrefs? = null

private val backend: Backend by lazy { Backend.getInstance() }

private val pickKml = registerForActivityResult(ActivityResultContracts.GetContent()) {
it ?: return@registerForActivityResult
Expand All @@ -41,6 +56,7 @@ class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings, rootKey)
prefs = SmartBirdsPrefs(requireContext())
userPrefs = UserPrefs(requireContext())
initPreferences()
updateMapType(MapProvider.ProviderType.valueOf(providerPreference?.value as String))
}
Expand All @@ -50,6 +66,7 @@ class SettingsFragment : PreferenceFragmentCompat() {
mapTypePreference = findPreference("mapType")
enabledFormsPreference = findPreference("formsEnabled")
exportPreference = findPreference("exportDB")
deleteAccountPreference = findPreference("deleteAccount")

providerPreference?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener() { _: Preference, newValue: Any ->
Expand Down Expand Up @@ -93,6 +110,12 @@ class SettingsFragment : PreferenceFragmentCompat() {
return@setOnPreferenceClickListener true
}

deleteAccountPreference?.onPreferenceClickListener =
Preference.OnPreferenceClickListener { _: Preference ->
showDeleteAccountConfirmation()
return@OnPreferenceClickListener true
}

updateImportedKmlPreference()
initMapLayersSettings()
}
Expand Down Expand Up @@ -152,4 +175,53 @@ class SettingsFragment : PreferenceFragmentCompat() {
mapTypePreference?.isEnabled = true
}
}

private fun showDeleteAccountConfirmation() {
debugLog("Show delete account confirmation")
AlertDialog.Builder(requireContext())
.setView(R.layout.dialog_delete_account)
.setPositiveButton(R.string.dialog_delete_account_btn_yes) { _, _ ->
deleteAccount()
}
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.show()
}

private fun deleteAccount() {
userPrefs?.getUserId() ?: return

val loadingDialog = LoadingDialog.newInstance(getString(R.string.deleting_account_progress))
loadingDialog.show(parentFragmentManager, "deleting")

backend.api().deleteUser(userPrefs!!.getUserId().toLong())
.enqueue(object : Callback<BaseResponse> {
override fun onResponse(
call: Call<BaseResponse>,
response: Response<BaseResponse>,
) {
loadingDialog.dismiss()
if (response.isSuccessful && response.body()?.success == true) {
userPrefs?.clear()
startActivity(Intent(context, MainActivity::class.java))
} else {
showDeleteAccountError()
}

}

override fun onFailure(call: Call<BaseResponse>, error: Throwable) {
loadingDialog.dismiss()
debugLog("Delete account failed ${error.message}")
}
})
}

private fun showDeleteAccountError() {
context?.showAlert(
R.string.delete_account_dialog_title,
R.string.delete_account_dialog_error_message,
null,
null
)
}
}
37 changes: 37 additions & 0 deletions app/src/main/res/layout/dialog_delete_account.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:padding="?dialogPreferredPadding"
android:layout_height="match_parent">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/delete_account_dialog_title"
android:textAppearance="@android:style/TextAppearance.DialogWindowTitle" />

<LinearLayout
android:id="@+id/confirmation_message_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:text="@string/delete_account_dialog_confirmation_message"
android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/holo_red_dark"
android:paddingTop="10dp"
android:text="@string/delete_account_dialog_confirmation_warning_message"
android:textAppearance="@android:style/TextAppearance.DeviceDefault.Small" />
</LinearLayout>

</LinearLayout>
2 changes: 2 additions & 0 deletions app/src/main/res/values-bg/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,8 @@
<string name="settings_category_advanced">"Допълнителни"</string>
<string name="settings_export_db">"Експорт на Базата данни"</string>
<string name="settings_export_db_summary">"Експортиране на Базата данни в Downloads."</string>
<string name="settings_delete_account">"Изтриване на профил"</string>
<string name="settings_delete_account_summary">"Тази операция ще изтрие потребителският ви профил и всички данни свързани с него. Операцията е необратима!"</string>
<string name="settings_enabled_forms_alert_title">"Внимание"</string>
<string name="settings_enabled_forms_alert_message">"Трябва да изберете поне една активна форма за наблюдение."</string>
<string name="export_db_dialog_title_success">"Успех"</string>
Expand Down
8 changes: 8 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,8 @@ Do you really want to cancel the monitoring?"</string>
<string name="settings_category_advanced">"Advanced"</string>
<string name="settings_export_db">"Export DB"</string>
<string name="settings_export_db_summary">"Export the DB in Downloads."</string>
<string name="settings_delete_account">"Delete account"</string>
<string name="settings_delete_account_summary">"This operation will delete your account and all related data. It cannot be undone! "</string>
<string name="settings_enabled_forms_alert_title">"Warning"</string>
<string name="settings_enabled_forms_alert_message">"You have to select at least one active monitoring form."</string>
<string name="export_db_dialog_title_success">"Success"</string>
Expand Down Expand Up @@ -503,4 +505,10 @@ Do you really want to cancel the monitoring?"</string>
<string name="settings_show_current_location_circle">"Current location zone"</string>
<string name="notifications_permission_rationale">"Notification permission is required for starting a monitoring"</string>
<string name="monitoring_fish_total_length">"Total length (TL) class, cm"</string>
<string name="delete_account_dialog_title">Delete account</string>
<string name="delete_account_dialog_confirmation_message">Are you sure you want to delete your account?</string>
<string name="delete_account_dialog_confirmation_warning_message">Warning: This action cannot be undone.</string>
<string name="delete_account_dialog_error_message">Failed to delete account</string>
<string name="deleting_account_progress">Deleting account...</string>
<string name="dialog_delete_account_btn_yes">Yes, delete account.</string>
</resources>
6 changes: 6 additions & 0 deletions app/src/main/res/xml/settings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,12 @@
app:key="exportDB"
app:summary="@string/settings_export_db_summary"
app:title="@string/settings_export_db" />

<Preference
app:iconSpaceReserved="false"
app:key="deleteAccount"
app:summary="@string/settings_delete_account_summary"
app:title="@string/settings_delete_account" />
</PreferenceCategory>

</PreferenceScreen>

0 comments on commit 09e9ec3

Please sign in to comment.