Modern Apps git

← Modern-Apps.git

contacts: transfer contacts between accounts (#814)

Commit
5daedbc4fc4443c2bba0cf9e3b8641104b5a6b33
Author
vayun-mathur <[email protected]>
When
2026-10-14 21:13 UTC (1 month ago)
Parents
33a6336

Diff

contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.ktindex 5c221d5183..e600502a06 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt@@ -20,6 +20,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.contacts.R import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.data.isSimAccountType+import com.vayunmathur.contacts.ui.dialogs.MoveDialogHost import com.vayunmathur.contacts.util.ContactDetailsUiState import com.vayunmathur.contacts.util.ContactPlatforms import com.vayunmathur.contacts.util.ContactViewModel@@ -32,6 +33,7 @@ import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconEdit+import com.vayunmathur.library.ui.IconMove import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.IconStar import com.vayunmathur.library.ui.IconStarBorder@@ -98,6 +100,19 @@ fun ContactDetailsPage(         }     } +    var moveContactIds by remember(contactId) { mutableStateOf<List<Long>?>(null) }++    moveContactIds?.let { ids ->+        MoveDialogHost(+            viewModel = viewModel,+            contactIds = ids,+            onDismiss = { moveContactIds = null },+            // The moved contact no longer exists: pop before the re-sync+            // flips this page to "contact not found".+            onTransferred = onBack,+        )+    }+     ContactDetailsScreen(         state = ContactDetailsUiState(             contact = contact,@@ -112,6 +127,10 @@ fun ContactDetailsPage(              override fun confirmDeleteContact(contact: Contact) = onDelete() +            override fun moveContacts(contactIds: List<Long>) {+                moveContactIds = contactIds+            }+             override fun shareContacts(contacts: List<Contact>, filename: String) {                 shareContactsAsVcf(scope, context, contacts, filename, shareContactLabel)             }@@ -173,6 +192,9 @@ fun ContactDetailsScreen(             }) {                 IconShare()             }+            IconButton(onClick = { actions.moveContacts(listOf(contact.id)) }) {+                IconMove()+            }             IconButton(onClick = { actions.confirmDeleteContact(contact) }) {                 IconDelete()             }
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.ktindex 65e4340dd9..83a4acd085 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt@@ -15,7 +15,10 @@ import androidx.compose.foundation.lazy.LazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext@@ -25,6 +28,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.contacts.R import com.vayunmathur.contacts.Route import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.ui.dialogs.MoveDialogHost import com.vayunmathur.contacts.util.ContactListUiState import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.contacts.util.ContactsActions@@ -61,6 +65,15 @@ fun ContactList(      val last = backStack.last() +    var moveContactIds by remember { mutableStateOf<List<Long>?>(null) }+    moveContactIds?.let { ids ->+        MoveDialogHost(+            viewModel = viewModel,+            contactIds = ids,+            onDismiss = { moveContactIds = null },+        )+    }+     ContactListScreen(         state = ContactListUiState(             contacts = contacts,@@ -87,6 +100,10 @@ fun ContactList(                 backStack.add(Route.AddToGroupDialog(contactIds))             } +            override fun moveContacts(contactIds: List<Long>) {+                moveContactIds = contactIds+            }+             override fun shareContacts(contacts: List<Contact>, filename: String) {                 shareContactsAsVcf(scope, context, contacts, filename, resources.getString(R.string.share_contact))             }
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.ktindex 636f9207a8..23986305bd 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt@@ -42,6 +42,7 @@ import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconGroup+import com.vayunmathur.library.ui.IconMove import com.vayunmathur.library.ui.IconPerson import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.LazyListScaffold@@ -142,6 +143,11 @@ fun ContactListScreen(                         }) {                             IconGroup()                         }+                        IconButton(onClick = {+                            actions.moveContacts(selectedIds.toList())+                        }) {+                            IconMove()+                        }                         IconButton(onClick = {                             actions.shareContacts(contacts.filter { it.id in selectedIds }, "selected_contacts.vcf")                         }) {
contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.ktnew file mode 100644index 0000000000..5d0f1bd8dd--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.kt@@ -0,0 +1,100 @@+package com.vayunmathur.contacts.ui.dialogs++import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.data.isSimAccountType+import com.vayunmathur.contacts.util.ContactAccount+import com.vayunmathur.contacts.util.ContactViewModel+import com.vayunmathur.contacts.util.SimDroppedField+import com.vayunmathur.contacts.util.computeSimLoss+import com.vayunmathur.contacts.util.transferContacts+import com.vayunmathur.library.ui.rememberMessenger++/**+ * Hosts [MoveToAccountDialog] for [contactIds]: resolves source accounts and+ * SIM data-loss, runs the transfer, and reports the result via messenger.+ * [onTransferred] fires when at least one contact moved (before [onDismiss]).+ */+@Composable+fun MoveDialogHost(+    viewModel: ContactViewModel,+    contactIds: List<Long>,+    onDismiss: () -> Unit,+    onTransferred: () -> Unit = {},+) {+    val context = LocalContext.current+    val messenger = rememberMessenger()+    val accounts by viewModel.accounts.collectAsStateWithLifecycle()+    val simLabels by viewModel.simAccountLabels.collectAsStateWithLifecycle()+    val contacts by viewModel.contacts.collectAsStateWithLifecycle()++    val toMove = remember(contacts, contactIds) {+        contacts.filter { it.id in contactIds }+    }+    var selectedAccount by remember(contactIds) { mutableStateOf<ContactAccount?>(null) }++    val sourceAccounts = remember(toMove) {+        toMove.mapTo(mutableSetOf()) {+            ContactAccount(it.accountName.orEmpty(), it.accountType.orEmpty())+        }+    }+    val isSimDest = selectedAccount?.let { isSimAccountType(it.type) } == true+    val simLoss = remember(toMove, isSimDest) {+        if (!isSimDest) emptyList()+        else toMove.flatMapTo(mutableSetOf()) { computeSimLoss(it) }.toList()+    }++    MoveToAccountDialog(+        contactCount = toMove.size.coerceAtLeast(1),+        accounts = accounts,+        sourceAccounts = sourceAccounts,+        simLabels = simLabels,+        selectedAccount = selectedAccount,+        simLossLabels = simLoss.map { it.localized() },+        onSelectAccount = { selectedAccount = it },+        onClearSelection = { selectedAccount = null },+        onConfirm = {+            val dest = selectedAccount ?: return@MoveToAccountDialog+            val ids = toMove.map { it.id }.ifEmpty { contactIds }+            viewModel.transferContacts(ids, dest.name, dest.type) { moved, failed, _ ->+                // Resources (not composable stringResource): this callback runs+                // outside composition on the main thread.+                val message = when {+                    moved > 0 && failed == 0 ->+                        context.resources.getQuantityString(R.plurals.move_success, moved, moved)+                    moved > 0 ->+                        context.getString(R.string.move_partial_failure, moved, failed)+                    else -> context.getString(R.string.move_failed)+                }+                messenger.show(message)+                if (moved > 0) onTransferred()+                onDismiss()+            }+        },+        onDismiss = onDismiss,+    )+}++@Composable+private fun SimDroppedField.localized(): String = stringResource(+    when (this) {+        SimDroppedField.PHOTO -> R.string.move_dropped_photo+        SimDroppedField.EXTRA_PHONES -> R.string.move_dropped_extra_phones+        SimDroppedField.EXTRA_EMAILS -> R.string.move_dropped_extra_emails+        SimDroppedField.ADDRESSES -> R.string.move_dropped_addresses+        SimDroppedField.DATES -> R.string.move_dropped_dates+        SimDroppedField.ORGANIZATION -> R.string.move_dropped_organization+        SimDroppedField.NOTE -> R.string.move_dropped_note+        SimDroppedField.NICKNAME -> R.string.move_dropped_nickname+        SimDroppedField.GROUPS -> R.string.move_dropped_groups+        SimDroppedField.RINGTONE -> R.string.move_dropped_ringtone+        SimDroppedField.FAVORITE -> R.string.move_dropped_favorite+    }+)
contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.ktnew file mode 100644index 0000000000..e18d4beecd--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.kt@@ -0,0 +1,143 @@+package com.vayunmathur.contacts.ui.dialogs++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.data.isSimAccountType+import com.vayunmathur.contacts.util.ContactAccount+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.R as UiR++/**+ * Stateless move-to-account dialog: account picker first, then a SIM data-loss+ * warning when the destination is a SIM account that would drop fields.+ * Same-account destinations are shown disabled. Dropped-field labels come from+ * [simLossLabels], resolved by the caller from strings.+ */+@Composable+fun MoveToAccountDialog(+    contactCount: Int,+    accounts: List<ContactAccount>,+    sourceAccounts: Set<ContactAccount>,+    simLabels: Map<String, String> = emptyMap(),+    selectedAccount: ContactAccount?,+    simLossLabels: List<String> = emptyList(),+    onSelectAccount: (ContactAccount) -> Unit,+    onClearSelection: () -> Unit,+    onConfirm: () -> Unit,+    onDismiss: () -> Unit,+) {+    val destination = selectedAccount+    if (destination != null && isSimAccountType(destination.type) && simLossLabels.isNotEmpty()) {+        val simLabel = simLabels["${destination.type}|${destination.name}"]+            ?: destination.name.ifEmpty { stringResource(R.string.on_device) }+        val dropped = remember(simLossLabels) { simLossLabels.joinToString(", ") }+        // Plain AlertDialog rather than ConfirmDialog: ConfirmDialog invokes+        // onDismiss before onConfirm, and our back action clears the selection+        // the confirm callback needs.+        AlertDialog(+            onDismissRequest = onDismiss,+            title = { Text(stringResource(R.string.move_to_sim_warning_title)) },+            text = { Text(stringResource(R.string.move_to_sim_warning_body, simLabel, dropped)) },+            confirmButton = {+                TextButton(onClick = onConfirm) {+                    Text(+                        stringResource(R.string.move_anyway),+                        color = MaterialTheme.colorScheme.error,+                    )+                }+            },+            dismissButton = {+                // Back returns to the picker; tapping outside dismisses outright.+                TextButton(onClick = onClearSelection) {+                    Text(stringResource(UiR.string.back))+                }+            },+        )+        return+    }+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(stringResource(R.string.move_to_account)) },+        text = {+            Column(Modifier.fillMaxWidth().heightIn(max = 400.dp)) {+                Text(+                    pluralStringResource(R.plurals.move_to_account_subtitle, contactCount, contactCount),+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                LazyColumn(Modifier.fillMaxWidth()) {+                    items(accounts, key = { "${it.type}|${it.name}" }) { account ->+                        DestinationRow(+                            account = account,+                            simLabels = simLabels,+                            selected = destination == account,+                            enabled = account !in sourceAccounts,+                            onClick = { onSelectAccount(account) },+                        )+                    }+                }+            }+        },+        confirmButton = {+            TextButton(+                enabled = destination != null && destination !in sourceAccounts,+                onClick = onConfirm,+            ) {+                Text(stringResource(R.string.move))+            }+        },+        dismissButton = {+            TextButton(onClick = onDismiss) {+                Text(stringResource(UiR.string.cancel))+            }+        },+    )+}++@Composable+private fun DestinationRow(+    account: ContactAccount,+    simLabels: Map<String, String>,+    selected: Boolean,+    enabled: Boolean,+    onClick: () -> Unit,+) {+    val key = "${account.type}|${account.name}"+    val onDevice = stringResource(R.string.on_device)+    val label = simLabels[key] ?: account.name.ifEmpty { onDevice }+    val supporting = when {+        simLabels.containsKey(key) -> null+        account.type.isNotBlank() -> account.type+        else -> null+    }+    ListItem(+        content = {+            Text(+                label,+                color = if (enabled) MaterialTheme.colorScheme.onSurface+                else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),+            )+        },+        supportingContent = supporting?.let { { Text(it) } },+        trailingContent = if (selected) {+            { IconCheck() }+        } else null,+        modifier = if (enabled) Modifier.clickable(onClick = onClick) else Modifier,+    )+}
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.ktnew file mode 100644index 0000000000..679a4654e5--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt@@ -0,0 +1,229 @@+package com.vayunmathur.contacts.util++import android.app.Application+import androidx.lifecycle.viewModelScope+import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.data.ContactDetails+import com.vayunmathur.contacts.data.SimContactsDataSource+import com.vayunmathur.contacts.data.isSimAccountType+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** Fields a SIM move drops, for the warn-before-truncate dialog. */+enum class SimDroppedField {+    PHOTO,+    EXTRA_PHONES,+    EXTRA_EMAILS,+    ADDRESSES,+    DATES,+    ORGANIZATION,+    NOTE,+    NICKNAME,+    GROUPS,+    RINGTONE,+    FAVORITE,+}++data class TransferResult(val moved: Int, val failed: Int, val groupsDropped: Boolean)++/**+ * Pure helper: which fields of [contact] would not survive a move to a SIM+ * account (SIM ADN rows store only name + one phone + one email).+ */+fun computeSimLoss(contact: Contact): List<SimDroppedField> {+    val dropped = mutableListOf<SimDroppedField>()+    if (contact.details.photos.isNotEmpty()) dropped += SimDroppedField.PHOTO+    if (contact.details.phoneNumbers.size > 1) dropped += SimDroppedField.EXTRA_PHONES+    if (contact.details.emails.size > 1) dropped += SimDroppedField.EXTRA_EMAILS+    if (contact.details.addresses.isNotEmpty()) dropped += SimDroppedField.ADDRESSES+    if (contact.details.dates.isNotEmpty()) dropped += SimDroppedField.DATES+    if (contact.details.orgs.any { it.company.isNotBlank() }) dropped += SimDroppedField.ORGANIZATION+    if (contact.details.notes.any { it.content.isNotBlank() }) dropped += SimDroppedField.NOTE+    if (contact.details.nicknames.any { it.nickname.isNotBlank() }) dropped += SimDroppedField.NICKNAME+    if (contact.details.groups.isNotEmpty()) dropped += SimDroppedField.GROUPS+    if (contact.customRingtone != null) dropped += SimDroppedField.RINGTONE+    if (contact.isFavorite) dropped += SimDroppedField.FAVORITE+    return dropped+}++/**+ * MOVEs [contactIds] to ([destName], [destType]): copies each contact into the+ * destination with fresh data-row ids, then deletes the source only when the+ * insert succeeded. Sequential so SIM ADN insert ordering is deterministic.+ * [onResult] is invoked on the main thread.+ */+fun ContactViewModel.transferContacts(+    contactIds: List<Long>,+    destName: String,+    destType: String,+    onResult: ((moved: Int, failed: Int, groupsDropped: Boolean) -> Unit)? = null,+) {+    viewModelScope.launch {+        val result = withContext(Dispatchers.IO) { transferContactsInternal(contactIds, destName, destType) }+        loadAccounts()+        loadContacts()+        withContext(Dispatchers.Main) { onResult?.invoke(result.moved, result.failed, result.groupsDropped) }+    }+}++private suspend fun ContactViewModel.transferContactsInternal(+    contactIds: List<Long>,+    destName: String,+    destType: String,+): TransferResult {+    var moved = 0+    var failed = 0+    var groupsDropped = false+    for (id in contactIds) {+        val outcome = moveContactById(id, destName, destType)+        if (outcome == null) continue+        if (outcome.moved) {+            moved+++            if (outcome.groupsDropped) groupsDropped = true+        } else {+            failed+++        }+    }+    return TransferResult(moved, failed, groupsDropped)+}++/** Moves one contact by id. Null when the destination equals the source (skipped, not failed). */+private suspend fun ContactViewModel.moveContactById(+    id: Long,+    destName: String,+    destType: String,+): MoveOutcome? {+    val contact = findContact(id) ?: return MoveOutcome(false, false)+    if (isSameAccount(contact, destName, destType)) return null+    return moveOneContact(contact, destName, destType)+}++private fun isSameAccount(contact: Contact, destName: String, destType: String): Boolean =+    (contact.accountType.orEmpty() == destType) && (contact.accountName.orEmpty() == destName)++private data class MoveOutcome(val moved: Boolean, val groupsDropped: Boolean)++// Broad catch is deliberate: transfer crosses provider + SIM ADN writes and+// must report failure via the outcome rather than crashing the caller.+@Suppress("TooGenericExceptionCaught")+private suspend fun ContactViewModel.moveOneContact(+    contact: Contact,+    destName: String,+    destType: String,+): MoveOutcome {+    try {+        val fromSim = isSimAccountType(contact.accountType)+        val toSim = isSimAccountType(destType)+        val inserted = when {+            !fromSim && !toSim -> copyProviderToProvider(contact, destName, destType)+            !fromSim && toSim -> copyProviderToSim(contact, destName)+            fromSim && !toSim -> copySimToProvider(contact, destName, destType)+            else -> copySimToSim(contact, destName)+        }+        if (!inserted.ok) return MoveOutcome(false, false)+        deleteTransferSource(contact)+        return MoveOutcome(true, inserted.groupsDropped)+    } catch (e: Exception) {+        Log.error("ContactViewModel", "Error transferring contact ${contact.id}", e)+        return MoveOutcome(false, false)+    }+}++private data class InsertOutcome(val ok: Boolean, val groupsDropped: Boolean)++private suspend fun ContactViewModel.copyProviderToProvider(+    contact: Contact,+    destName: String,+    destType: String,+): InsertOutcome {+    val app = getApplication<Application>()+    val withGroups = contact.zeroedCopy(destName, destType)+    if (withGroups.save(app, withGroups.details, ContactDetails.empty())) {+        return InsertOutcome(true, false)+    }+    // Fallback: group row ids may not exist for the destination; retry without them.+    if (withGroups.details.groups.isEmpty()) return InsertOutcome(false, false)+    val withoutGroups = withGroups.copy(details = withGroups.details.copy(groups = emptyList()))+    val ok = withoutGroups.save(app, withoutGroups.details, ContactDetails.empty())+    return InsertOutcome(ok, ok)+}++private suspend fun ContactViewModel.copyProviderToSim(+    contact: Contact,+    destSubIdName: String,+): InsertOutcome {+    val app = getApplication<Application>()+    val subId = destSubIdName.toIntOrNull()+    val name = contact.name.value.trim().ifEmpty {+        contact.details.phoneNumbers.firstOrNull()?.number?.trim().orEmpty()+    }+    val number = contact.details.phoneNumbers.firstOrNull()?.number?.trim().orEmpty()+    val email = contact.details.emails.firstOrNull()?.address?.trim()?.takeIf { it.isNotEmpty() }+    if (name.isBlank() && number.isBlank()) return InsertOutcome(false, false)+    val ok = SimContactsDataSource.insertSimContact(app, name, number, email, subId)+    return InsertOutcome(ok, contact.details.groups.isNotEmpty() && ok)+}++private suspend fun ContactViewModel.copySimToProvider(+    contact: Contact,+    destName: String,+    destType: String,+): InsertOutcome {+    val app = getApplication<Application>()+    // Never leak the negative synthetic SIM id into the provider insert.+    val fresh = contact.zeroedCopy(destName, destType)+    val withoutGroups = fresh.copy(details = fresh.details.copy(groups = emptyList()))+    val ok = withoutGroups.save(app, withoutGroups.details, ContactDetails.empty())+    return InsertOutcome(ok, contact.details.groups.isNotEmpty() && ok)+}++private suspend fun ContactViewModel.copySimToSim(+    contact: Contact,+    destSubIdName: String,+): InsertOutcome {+    // Same truncated shape as provider->SIM; source SIM rows never carry the+    // richer fields, so no loss beyond what is already stored.+    return copyProviderToSim(contact, destSubIdName)+}++private suspend fun ContactViewModel.deleteTransferSource(contact: Contact) {+    val app = getApplication<Application>()+    if (isSimAccountType(contact.accountType)) {+        val sc = SimContactsDataSource.findBackingSimContact(app, contact)+        if (sc != null) {+            SimContactsDataSource.deleteSimContact(app, sc)+        }+    } else {+        // Fresh-read details so the delete path sees current rows.+        val fresh = runCatching { Contact.getContact(app, contact.id) }.getOrNull() ?: contact+        Contact.delete(app, fresh)+    }+    syncFromSystem()+}++/** Copy pointed at ([destName], [destType]) with id 0 and all data-row ids zeroed for insert. */+private fun Contact.zeroedCopy(destName: String, destType: String): Contact {+    val accountType = destType.ifEmpty { null }+    val accountName = if (accountType == null) null else destName.ifEmpty { null }+    return copy(+        id = 0,+        accountType = accountType,+        accountName = accountName,+        details = details.zeroed(),+    )+}++private fun ContactDetails.zeroed(): ContactDetails = copy(+    phoneNumbers = phoneNumbers.map { it.copy(id = 0) },+    emails = emails.map { it.copy(id = 0) },+    addresses = addresses.map { it.copy(id = 0) },+    dates = dates.map { it.copy(id = 0) },+    photos = photos.map { it.copy(id = 0) },+    names = names.map { it.copy(id = 0) },+    orgs = orgs.map { it.copy(id = 0) },+    notes = notes.map { it.copy(id = 0) },+    nicknames = nicknames.map { it.copy(id = 0) },+    groups = groups.map { it.copy(id = 0) },+)
contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.ktindex 78fc77ce0d..2e2d3ef46f 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactsUiContract.kt@@ -69,6 +69,9 @@ interface ContactsActions {     fun pickRingtone(contact: Contact) {}     fun addToGroup(contactIds: List<Long>) {} +    /** Opens the move-to-account flow for [contactIds] (details + multi-select entry points). */+    fun moveContacts(contactIds: List<Long>) {}+     /** Exports [contacts] to a VCF named [filename] and opens a share chooser. */     fun shareContacts(contacts: List<Contact>, filename: String) {}     fun selectTab(tab: ContactsTab) {}
contacts/src/main/res/values/strings.xml
diff --git a/contacts/src/main/res/values/strings.xml b/contacts/src/main/res/values/strings.xmlindex 3c1518f286..aa0e11b78a 100644--- a/contacts/src/main/res/values/strings.xml+++ b/contacts/src/main/res/values/strings.xml@@ -246,4 +246,42 @@     <string name="no_groups_yet">No groups yet</string>     <!-- Supporting text under no_groups_yet, pointing at the add button -->     <string name="no_groups_yet_message">Tap the add button to group contacts together.</string>++    <!-- Move contacts between accounts (#814) -->+    <!-- Dialog title and toolbar action for moving contacts to another account -->+    <string name="move_to_account">Move to account</string>+    <!-- Verb on the dialog confirm button: move the selected contacts to the chosen account -->+    <string name="move">Move</string>+    <!-- Dialog subtitle: pick the destination account. %1$d = number of selected contacts -->+    <plurals name="move_to_account_subtitle">+        <item quantity="one">Choose where to move <xliff:g id="count" example="1">%1$d</xliff:g> contact</item>+        <item quantity="other">Choose where to move <xliff:g id="count" example="3">%1$d</xliff:g> contacts</item>+    </plurals>+    <!-- Warning title when the destination is a SIM account that drops fields -->+    <string name="move_to_sim_warning_title">Some info won\'t fit on the SIM</string>+    <!-- Warning body when the destination is a SIM account. %1$s = SIM label, %2$s = dropped fields list -->+    <string name="move_to_sim_warning_body">Only name, phone, and email are kept on <xliff:g id="sim_label" example="SIM 1">%1$s</xliff:g>. These will be lost: <xliff:g id="dropped" example="photo, addresses">%2$s</xliff:g>.</string>+    <!-- Dropped-field labels for the SIM warning list -->+    <string name="move_dropped_photo">photo</string>+    <string name="move_dropped_extra_phones">extra phone numbers</string>+    <string name="move_dropped_extra_emails">extra email addresses</string>+    <string name="move_dropped_addresses">addresses</string>+    <string name="move_dropped_dates">dates</string>+    <string name="move_dropped_organization">organization</string>+    <string name="move_dropped_note">note</string>+    <string name="move_dropped_nickname">nickname</string>+    <string name="move_dropped_groups">groups</string>+    <string name="move_dropped_ringtone">ringtone</string>+    <string name="move_dropped_favorite">favorite</string>+    <!-- Confirm button label for the SIM warning: keep moving despite dropped fields -->+    <string name="move_anyway">Move anyway</string>+    <!-- Snackbar after a fully successful move. %1$d = number of moved contacts -->+    <plurals name="move_success">+        <item quantity="one"><xliff:g id="count" example="1">%1$d</xliff:g> contact moved</item>+        <item quantity="other"><xliff:g id="count" example="3">%1$d</xliff:g> contacts moved</item>+    </plurals>+    <!-- Snackbar when some contacts failed to move. %1$d = moved, %2$d = failed -->+    <string name="move_partial_failure"><xliff:g id="moved" example="2">%1$d</xliff:g> moved, <xliff:g id="failed" example="1">%2$d</xliff:g> failed</string>+    <!-- Snackbar when nothing moved -->+    <string name="move_failed">Move failed</string> </resources>
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 9206469d52..f41eebb9d9 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -1457,6 +1457,10 @@ fun IconSwapLanguages(modifier: Modifier = Modifier, tint: Color = LocalContentC fun IconSpeak(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.AutoMirrored.Filled.VolumeUp, "Speak", modifier, tint) +@Composable+fun IconMove(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.SwapHoriz, "Move", modifier, tint)+ // --- Calculator --- @Composable fun IconCalculate(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =