feat(android): 支持编辑物品和查看移位记录
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
continuous-integration/drone Build is passing Details

This commit is contained in:
dongjf 2026-11-29 10:02:53 +08:00
parent 565d37ccf7
commit 247278a4a9
5 changed files with 215 additions and 37 deletions

View File

@ -2,6 +2,8 @@
Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原生会话 API。用已有账号登录后,可新建或切换空间、按名称和别名找物、查看详情、手动添加物品和移位。录入可以不选位置,移位也可以清空位置。只读空间仅显示查询功能。
详情展示购入单价和移位记录。可以编辑名称、数量、别名和备注,存放位置由移位操作管理。编辑过程中若其他端先更新了同一物品,服务端会根据物品版本返回 409。用户确认载入最新内容后,可以基于新版本重新修改。
会话令牌只在应用进程内使用,续期由 API 客户端处理。应用被完全关闭后需要重新登录。应用不预置物品、账号或凭据。
## 构建和安装
@ -18,6 +20,6 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
## 验收
登录后切换空间,输入名称或别名并打开详情。分别尝试在有位置和无位置时录入,再移动到另一个位置或清空位置。用只读成员检查物品写入口,用网络中断检查失败提示,退出后确认页面清空。首版测试范围为账号、空间与物品,拍照、语音、社区及平面图随后接入。
登录后切换空间,输入名称或别名并打开详情。分别尝试在有位置和无位置时录入,再移动到另一个位置或清空位置,核对详情中的移位记录。两端同时打开同一件物品,用一端保存后再在另一端提交,检查冲突提示及重新载入。用只读成员检查物品写入口,用网络中断检查失败提示,退出后确认页面清空。拍照、语音、社区及平面图随后接入。
[客户端架构](../../docs/architecture/clients.md) · [Android 构建](https://developer.android.com/build/building-cmdline)

View File

@ -15,8 +15,8 @@ android {
applicationId = "com.tutudog.itematlas"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
versionCode = 2
versionName = "0.1.1"
val apiOrigin = providers.gradleProperty("ATLAS_API_ORIGIN").orElse("https://api-atlas.tutudog.com").get()
require(Regex("https://[A-Za-z0-9.-]+(:[0-9]+)?").matches(apiOrigin)) { "ATLAS_API_ORIGIN must be an HTTPS origin" }

View File

@ -35,10 +35,14 @@ data class Item(
val locationPath: String = "",
val aliases: List<String> = emptyList(),
val version: Int,
val priceCents: Long? = null,
)
@Serializable
data class ItemDetail(val item: Item)
data class Movement(val fromPath: String, val toPath: String, val movedAt: String)
@Serializable
data class ItemDetail(val item: Item, val moves: List<Movement> = emptyList())
@Serializable
data class ItemInput(
@ -67,6 +71,15 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
@Serializable
private data class MoveInput(val locationId: String?, val version: Int)
@Serializable
private data class ItemEdit(
val version: Int,
val name: String,
val quantity: Int,
val aliases: List<String>,
val notes: String,
)
@Serializable
private data class Problem(val detail: String? = null, val message: String? = null)
@ -114,6 +127,11 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
suspend fun create(space: Space, input: ItemInput, key: String): Item =
json.decodeFromString(read(family(space, "items"), "POST", json.encodeToString(input), key))
suspend fun edit(space: Space, item: Item, input: ItemInput): Item {
val change = ItemEdit(item.version, input.name, input.quantity, input.aliases, input.notes)
return json.decodeFromString(read(family(space, "items", item.id), "PUT", json.encodeToString(change)))
}
suspend fun move(space: Space, item: Item, position: Place?): Item =
json.decodeFromString(read(family(space, "items", item.id, "moves"), "POST",
json.encodeToString(MoveInput(position?.id, item.version))))

View File

@ -12,7 +12,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
enum class Screen { SignIn, Inventory, Detail, Add, Move }
enum class Screen { SignIn, Inventory, Detail, Add, Edit, Move }
data class AtlasState(
val screen: Screen = Screen.SignIn,
@ -21,6 +21,8 @@ data class AtlasState(
val places: List<Place> = emptyList(),
val items: List<Item> = emptyList(),
val selected: Item? = null,
val recentMoves: List<Movement>? = null,
val writeConflict: Boolean = false,
val query: String = "",
val nextOffset: Int = 0,
val hasMore: Boolean = false,
@ -73,7 +75,8 @@ class AtlasViewModel : ViewModel() {
detailJob?.cancel()
mutable.update {
it.copy(space = space, places = emptyList(), items = emptyList(), selected = null,
query = "", hasMore = false, nextOffset = 0, error = null, screen = Screen.Inventory)
query = "", hasMore = false, nextOffset = 0, recentMoves = null, writeConflict = false,
error = null, screen = Screen.Inventory)
}
search()
locations()
@ -132,17 +135,19 @@ class AtlasViewModel : ViewModel() {
fun open(item: Item) {
val space = mutable.value.space ?: return
detailJob?.cancel()
mutable.update { it.copy(screen = Screen.Detail, selected = item, error = null) }
mutable.update {
it.copy(screen = Screen.Detail, selected = item, recentMoves = null, writeConflict = false, error = null)
}
detailJob = viewModelScope.launch {
try {
val detail = api.detail(space, item.id)
if (mutable.value.selected?.id == item.id && mutable.value.space?.id == space.id) {
mutable.update { it.copy(selected = detail.item) }
mutable.update { it.copy(selected = detail.item, recentMoves = detail.moves) }
}
} catch (failure: Exception) {
if (failure is CancellationException) throw failure
if (failure is ApiError && failure.status in setOf(403, 404)) {
mutable.update { it.copy(selected = null) }
mutable.update { it.copy(selected = null, recentMoves = null) }
}
handle(failure)
}
@ -159,27 +164,78 @@ class AtlasViewModel : ViewModel() {
fun create(name: String, quantity: String, location: Place?, aliases: String, notes: String) {
val space = mutable.value.space?.takeIf { it.writable } ?: return
val count = quantity.toIntOrNull()
val names = aliases.split(',', ',', '、').map(String::trim).filter(String::isNotEmpty).distinct()
if (name.trim().length !in 1..150 || count == null || count !in 1..9999 ||
notes.length > 1500 || names.size > 20 || names.any { it.length > 80 }) {
mutable.update { it.copy(error = "请检查名称、数量、别名和备注的长度。") }
return
}
val input = ItemInput(name.trim(), count, location?.id, names, notes)
val input = itemInput(name, quantity, location?.id, aliases.split(',', ',', '、'), notes) ?: return
if (pendingItem != input) {
pendingItem = input
pendingKey = UUID.randomUUID().toString()
}
action {
val item = api.create(space, input, pendingKey)
mutable.update { it.copy(screen = Screen.Detail, selected = item, query = "", items = emptyList()) }
mutable.update { it.copy(query = "", items = emptyList()) }
open(item)
}
}
private fun itemInput(name: String, quantity: String, location: String?, aliases: List<String>, notes: String): ItemInput? {
val count = quantity.toIntOrNull()
val names = aliases.map(String::trim).filter(String::isNotEmpty).distinct()
if (name.trim().length !in 1..150 || count == null || count !in 1..9999 ||
notes.length > 1500 || names.size > 20 || names.any { it.length > 80 }) {
mutable.update { it.copy(error = "请检查名称、数量、别名和备注的长度。") }
return null
}
return ItemInput(name.trim(), count, location, names, notes)
}
fun startEdit() {
if (mutable.value.space?.writable != true || mutable.value.selected == null) return
detailJob?.cancel()
mutable.update { it.copy(screen = Screen.Edit, writeConflict = false, error = null) }
}
fun edit(name: String, quantity: String, aliases: List<String>, notes: String) {
val space = mutable.value.space?.takeIf { it.writable } ?: return
val item = mutable.value.selected ?: return
val input = itemInput(name, quantity, item.locationId, aliases, notes) ?: return
writeItem { api.edit(space, item, input) }
}
private fun writeItem(change: suspend () -> Item) {
if (mutable.value.writeConflict) return
action {
try {
open(change())
} catch (failure: ApiError) {
if (failure.status != 409) throw failure
mutable.update {
it.copy(writeConflict = true, error = "这件物品刚被更新。载入最新内容后再修改。")
}
}
}
}
fun reloadWriteSnapshot() {
val space = mutable.value.space ?: return
val item = mutable.value.selected ?: return
action {
try {
val latest = api.detail(space, item.id)
mutable.update { it.copy(selected = latest.item, recentMoves = latest.moves, writeConflict = false) }
} catch (failure: ApiError) {
if (failure.status == 403 || failure.status == 404) {
mutable.update {
it.copy(screen = Screen.Detail, selected = null, recentMoves = null, writeConflict = false)
}
}
throw failure
}
}
}
fun startMove() {
if (mutable.value.space?.writable != true || mutable.value.selected == null) return
mutable.update { it.copy(screen = Screen.Move, error = null) }
detailJob?.cancel()
mutable.update { it.copy(screen = Screen.Move, writeConflict = false, error = null) }
locations()
}
@ -187,20 +243,21 @@ class AtlasViewModel : ViewModel() {
val space = mutable.value.space?.takeIf { it.writable } ?: return
val item = mutable.value.selected ?: return
if (position?.id == item.locationId) return
action {
val moved = api.move(space, item, position)
mutable.update { it.copy(screen = Screen.Detail, selected = moved) }
}
writeItem { api.move(space, item, position) }
}
fun back() {
if (mutable.value.busy) return
detailJob?.cancel()
val from = mutable.value.screen
if (from == Screen.Edit || from == Screen.Move) {
mutable.value.selected?.let(::open)
return
}
mutable.update {
when (from) {
Screen.Move -> it.copy(screen = Screen.Detail, error = null)
Screen.Detail, Screen.Add -> it.copy(screen = Screen.Inventory, selected = null, error = null)
Screen.Detail, Screen.Add -> it.copy(screen = Screen.Inventory, selected = null,
recentMoves = null, writeConflict = false, error = null)
else -> it
}
}

View File

@ -60,6 +60,13 @@ import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import java.math.BigDecimal
import java.text.NumberFormat
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.util.Locale
class MainActivity : ComponentActivity() {
private val model by viewModels<AtlasViewModel>()
@ -82,13 +89,14 @@ class MainActivity : ComponentActivity() {
@Composable
private fun AtlasApp(model: AtlasViewModel) {
val state by model.state.collectAsState()
val child = state.screen in listOf(Screen.Detail, Screen.Add, Screen.Move)
val child = state.screen != Screen.SignIn && state.screen != Screen.Inventory
BackHandler(child, model::back)
Scaffold(topBar = {
if (state.screen != Screen.SignIn) {
val title = when (state.screen) {
Screen.Detail -> "物品详情"
Screen.Add -> "添加物品"
Screen.Edit -> "编辑物品"
Screen.Move -> "移动物品"
else -> "见物"
}
@ -109,6 +117,7 @@ private fun AtlasApp(model: AtlasViewModel) {
Screen.Inventory -> Inventory(state, model, content)
Screen.Detail -> Detail(state, model, content)
Screen.Add -> AddItem(state, model, content)
Screen.Edit -> EditItem(state, model, content)
Screen.Move -> MoveItem(state, model, content)
}
}
@ -248,14 +257,51 @@ private fun Detail(state: AtlasState, model: AtlasViewModel, modifier: Modifier)
Text(item.name, style = MaterialTheme.typography.headlineMedium)
DetailLine("位置", item.displayPlace())
DetailLine("数量", item.quantity.toString())
item.priceCents?.let {
DetailLine("购入单价", NumberFormat.getCurrencyInstance(Locale.CHINA).format(BigDecimal.valueOf(it, 2)))
}
if (item.aliases.isNotEmpty()) DetailLine("别名", item.aliases.joinToString("、"))
if (item.notes.isNotBlank()) DetailLine("备注", item.notes)
if (state.space?.writable == true) {
OutlinedButton(onClick = model::startMove, enabled = !state.busy) { Text("移动物品") }
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
OutlinedButton(onClick = model::startEdit, enabled = !state.busy) { Text("编辑物品") }
OutlinedButton(onClick = model::startMove, enabled = !state.busy) { Text("移动物品") }
}
}
HorizontalDivider()
Text("移位记录", style = MaterialTheme.typography.titleMedium)
val moves = state.recentMoves
when {
moves == null && state.error != null -> {
TextButton(onClick = { model.open(item) }) { Text("重新加载记录") }
}
moves == null -> LinearProgressIndicator(Modifier.fillMaxWidth())
moves.isEmpty() -> Text("还没有移位记录", color = MaterialTheme.colorScheme.onSurfaceVariant)
else -> moves.forEach { move -> MovementEntry(move) }
}
}
}
@Composable
private fun MovementEntry(move: Movement) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
val from = move.fromPath.ifBlank { "未设置位置" }
val to = move.toPath.ifBlank { "未设置位置" }
Text("$from → $to", style = MaterialTheme.typography.bodyMedium)
Text(displayMoveTime(move.movedAt), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
HorizontalDivider(Modifier.padding(top = 6.dp))
}
}
private val movementTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.CHINA)
private fun displayMoveTime(value: String): String = try {
OffsetDateTime.parse(value).atZoneSameInstant(ZoneId.systemDefault()).format(movementTime)
} catch (_: DateTimeParseException) {
value
}
@Composable
private fun DetailLine(label: String, value: String) {
Column(Modifier.fillMaxWidth().padding(vertical = 4.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
@ -273,15 +319,11 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier
var placeId by rememberSaveable { mutableStateOf<String?>(null) }
val place = state.places.firstOrNull { it.id == placeId }
Form(modifier) {
OutlinedTextField(title, { title = it.take(150) }, Modifier.fillMaxWidth(), enabled = !state.busy,
label = { Text("名称") }, singleLine = true)
OutlinedTextField(quantity, { quantity = it.filter(Char::isDigit).take(4) }, Modifier.fillMaxWidth(), enabled = !state.busy,
label = { Text("数量") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, !state.busy)
PlacePicker(state.places, place?.path ?: "未设置位置", !state.busy) { placeId = it?.id }
OutlinedTextField(aliases, { aliases = it }, Modifier.fillMaxWidth(), enabled = !state.busy,
label = { Text("别名,可用逗号分隔") })
OutlinedTextField(notes, { notes = it.take(1500) }, Modifier.fillMaxWidth(), enabled = !state.busy,
label = { Text("备注") }, minLines = 2)
ItemNotes(notes, { notes = it }, !state.busy)
Status(state)
Button(onClick = { model.create(title, quantity, place, aliases, notes) },
enabled = title.isNotBlank() && !state.busy && (placeId == null || place != null),
@ -289,25 +331,84 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier
}
}
@Composable
private fun EditItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier) {
val item = state.selected ?: return
var title by rememberSaveable(item.id, item.version) { mutableStateOf(item.name) }
var quantity by rememberSaveable(item.id, item.version) { mutableStateOf(item.quantity.toString()) }
var aliases by rememberSaveable(item.id, item.version) { mutableStateOf(ArrayList(item.aliases)) }
var notes by rememberSaveable(item.id, item.version) { mutableStateOf(item.notes) }
val enabled = !state.busy && !state.writeConflict
Form(modifier) {
ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, enabled)
aliases.forEachIndexed { index, alias ->
OutlinedTextField(
alias, { value -> aliases = ArrayList(aliases).apply { set(index, value.take(80)) } },
Modifier.fillMaxWidth(), enabled = enabled,
label = { Text("别名 ${index + 1}") },
trailingIcon = {
TextButton(onClick = { aliases = ArrayList(aliases).apply { removeAt(index) } }, enabled = enabled) {
Text("移除")
}
},
)
}
if (aliases.size < 20) {
TextButton(onClick = { aliases = ArrayList(aliases).apply { add("") } }, enabled = enabled) { Text("添加别名") }
}
ItemNotes(notes, { notes = it }, enabled)
WriteStatus(state, model)
Button(onClick = { model.edit(title, quantity, aliases, notes) },
enabled = enabled && title.isNotBlank(), modifier = Modifier.fillMaxWidth()) { Text("保存修改") }
}
}
@Composable
private fun ItemNameAndQuantity(
name: String, onName: (String) -> Unit, quantity: String, onQuantity: (String) -> Unit, enabled: Boolean,
) {
OutlinedTextField(name, { onName(it.take(150)) }, Modifier.fillMaxWidth(), enabled = enabled,
label = { Text("名称") }, singleLine = true)
OutlinedTextField(quantity, { onQuantity(it.filter(Char::isDigit).take(4)) }, Modifier.fillMaxWidth(), enabled = enabled,
label = { Text("数量") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
}
@Composable
private fun ItemNotes(notes: String, onChange: (String) -> Unit, enabled: Boolean) {
OutlinedTextField(notes, { onChange(it.take(1500)) }, Modifier.fillMaxWidth(), enabled = enabled,
label = { Text("备注") }, minLines = 2)
}
@Composable
private fun MoveItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier) {
val item = state.selected ?: return
var placeId by rememberSaveable(item.id) { mutableStateOf(item.locationId) }
var placeId by rememberSaveable(item.id, item.version) { mutableStateOf(item.locationId) }
val place = state.places.firstOrNull { it.id == placeId }
val enabled = !state.busy && !state.writeConflict
Form(modifier) {
Text(item.name, style = MaterialTheme.typography.titleLarge)
DetailLine("当前位置", item.displayPlace())
val pickedLabel = place?.path ?: if (placeId == item.locationId) item.displayPlace() else "未设置位置"
PlacePicker(state.places, pickedLabel, !state.busy) { placeId = it?.id }
Status(state)
PlacePicker(state.places, pickedLabel, enabled) { placeId = it?.id }
WriteStatus(state, model)
Button(
onClick = { model.move(place) },
enabled = !state.busy && placeId != item.locationId && (placeId == null || place != null),
enabled = enabled && placeId != item.locationId && (placeId == null || place != null),
modifier = Modifier.fillMaxWidth(),
) { Text("确认移位") }
}
}
@Composable
private fun WriteStatus(state: AtlasState, model: AtlasViewModel) {
Status(state)
if (state.writeConflict) {
OutlinedButton(onClick = model::reloadWriteSnapshot, enabled = !state.busy, modifier = Modifier.fillMaxWidth()) {
Text("放弃本次修改,载入最新内容")
}
}
}
@Composable
private fun PlacePicker(places: List<Place>, label: String, enabled: Boolean, onSelect: (Place?) -> Unit) {
var showPicker by remember { mutableStateOf(false) }