Compare commits

..

2 Commits

Author SHA1 Message Date
dongjf 247278a4a9 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
2026-11-29 10:02:53 +08:00
dongjf 565d37ccf7 perf(inventory): 优化物品首屏和移位记录查询 2026-11-29 10:02:53 +08:00
9 changed files with 331 additions and 52 deletions

View File

@ -2,6 +2,8 @@
Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原生会话 API。用已有账号登录后,可新建或切换空间、按名称和别名找物、查看详情、手动添加物品和移位。录入可以不选位置,移位也可以清空位置。只读空间仅显示查询功能。 Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原生会话 API。用已有账号登录后,可新建或切换空间、按名称和别名找物、查看详情、手动添加物品和移位。录入可以不选位置,移位也可以清空位置。只读空间仅显示查询功能。
详情展示购入单价和移位记录。可以编辑名称、数量、别名和备注,存放位置由移位操作管理。编辑过程中若其他端先更新了同一物品,服务端会根据物品版本返回 409。用户确认载入最新内容后,可以基于新版本重新修改。
会话令牌只在应用进程内使用,续期由 API 客户端处理。应用被完全关闭后需要重新登录。应用不预置物品、账号或凭据。 会话令牌只在应用进程内使用,续期由 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) [客户端架构](../../docs/architecture/clients.md) · [Android 构建](https://developer.android.com/build/building-cmdline)

View File

@ -15,8 +15,8 @@ android {
applicationId = "com.tutudog.itematlas" applicationId = "com.tutudog.itematlas"
minSdk = 26 minSdk = 26
targetSdk = 35 targetSdk = 35
versionCode = 1 versionCode = 2
versionName = "0.1.0" versionName = "0.1.1"
val apiOrigin = providers.gradleProperty("ATLAS_API_ORIGIN").orElse("https://api-atlas.tutudog.com").get() 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" } 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 locationPath: String = "",
val aliases: List<String> = emptyList(), val aliases: List<String> = emptyList(),
val version: Int, val version: Int,
val priceCents: Long? = null,
) )
@Serializable @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 @Serializable
data class ItemInput( data class ItemInput(
@ -67,6 +71,15 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
@Serializable @Serializable
private data class MoveInput(val locationId: String?, val version: Int) 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 @Serializable
private data class Problem(val detail: String? = null, val message: String? = null) 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 = suspend fun create(space: Space, input: ItemInput, key: String): Item =
json.decodeFromString(read(family(space, "items"), "POST", json.encodeToString(input), key)) 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 = suspend fun move(space: Space, item: Item, position: Place?): Item =
json.decodeFromString(read(family(space, "items", item.id, "moves"), "POST", json.decodeFromString(read(family(space, "items", item.id, "moves"), "POST",
json.encodeToString(MoveInput(position?.id, item.version)))) 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.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
enum class Screen { SignIn, Inventory, Detail, Add, Move } enum class Screen { SignIn, Inventory, Detail, Add, Edit, Move }
data class AtlasState( data class AtlasState(
val screen: Screen = Screen.SignIn, val screen: Screen = Screen.SignIn,
@ -21,6 +21,8 @@ data class AtlasState(
val places: List<Place> = emptyList(), val places: List<Place> = emptyList(),
val items: List<Item> = emptyList(), val items: List<Item> = emptyList(),
val selected: Item? = null, val selected: Item? = null,
val recentMoves: List<Movement>? = null,
val writeConflict: Boolean = false,
val query: String = "", val query: String = "",
val nextOffset: Int = 0, val nextOffset: Int = 0,
val hasMore: Boolean = false, val hasMore: Boolean = false,
@ -73,7 +75,8 @@ class AtlasViewModel : ViewModel() {
detailJob?.cancel() detailJob?.cancel()
mutable.update { mutable.update {
it.copy(space = space, places = emptyList(), items = emptyList(), selected = null, 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() search()
locations() locations()
@ -132,17 +135,19 @@ class AtlasViewModel : ViewModel() {
fun open(item: Item) { fun open(item: Item) {
val space = mutable.value.space ?: return val space = mutable.value.space ?: return
detailJob?.cancel() 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 { detailJob = viewModelScope.launch {
try { try {
val detail = api.detail(space, item.id) val detail = api.detail(space, item.id)
if (mutable.value.selected?.id == item.id && mutable.value.space?.id == space.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) { } catch (failure: Exception) {
if (failure is CancellationException) throw failure if (failure is CancellationException) throw failure
if (failure is ApiError && failure.status in setOf(403, 404)) { 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) handle(failure)
} }
@ -159,27 +164,78 @@ class AtlasViewModel : ViewModel() {
fun create(name: String, quantity: String, location: Place?, aliases: String, notes: String) { fun create(name: String, quantity: String, location: Place?, aliases: String, notes: String) {
val space = mutable.value.space?.takeIf { it.writable } ?: return val space = mutable.value.space?.takeIf { it.writable } ?: return
val count = quantity.toIntOrNull() val input = itemInput(name, quantity, location?.id, aliases.split(',', ',', '、'), notes) ?: return
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)
if (pendingItem != input) { if (pendingItem != input) {
pendingItem = input pendingItem = input
pendingKey = UUID.randomUUID().toString() pendingKey = UUID.randomUUID().toString()
} }
action { action {
val item = api.create(space, input, pendingKey) 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() { fun startMove() {
if (mutable.value.space?.writable != true || mutable.value.selected == null) return 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() locations()
} }
@ -187,20 +243,21 @@ class AtlasViewModel : ViewModel() {
val space = mutable.value.space?.takeIf { it.writable } ?: return val space = mutable.value.space?.takeIf { it.writable } ?: return
val item = mutable.value.selected ?: return val item = mutable.value.selected ?: return
if (position?.id == item.locationId) return if (position?.id == item.locationId) return
action { writeItem { api.move(space, item, position) }
val moved = api.move(space, item, position)
mutable.update { it.copy(screen = Screen.Detail, selected = moved) }
}
} }
fun back() { fun back() {
if (mutable.value.busy) return if (mutable.value.busy) return
detailJob?.cancel() detailJob?.cancel()
val from = mutable.value.screen val from = mutable.value.screen
if (from == Screen.Edit || from == Screen.Move) {
mutable.value.selected?.let(::open)
return
}
mutable.update { mutable.update {
when (from) { when (from) {
Screen.Move -> it.copy(screen = Screen.Detail, error = null) Screen.Detail, Screen.Add -> it.copy(screen = Screen.Inventory, selected = null,
Screen.Detail, Screen.Add -> it.copy(screen = Screen.Inventory, selected = null, error = null) recentMoves = null, writeConflict = false, error = null)
else -> it 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.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp 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() { class MainActivity : ComponentActivity() {
private val model by viewModels<AtlasViewModel>() private val model by viewModels<AtlasViewModel>()
@ -82,13 +89,14 @@ class MainActivity : ComponentActivity() {
@Composable @Composable
private fun AtlasApp(model: AtlasViewModel) { private fun AtlasApp(model: AtlasViewModel) {
val state by model.state.collectAsState() 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) BackHandler(child, model::back)
Scaffold(topBar = { Scaffold(topBar = {
if (state.screen != Screen.SignIn) { if (state.screen != Screen.SignIn) {
val title = when (state.screen) { val title = when (state.screen) {
Screen.Detail -> "物品详情" Screen.Detail -> "物品详情"
Screen.Add -> "添加物品" Screen.Add -> "添加物品"
Screen.Edit -> "编辑物品"
Screen.Move -> "移动物品" Screen.Move -> "移动物品"
else -> "见物" else -> "见物"
} }
@ -109,6 +117,7 @@ private fun AtlasApp(model: AtlasViewModel) {
Screen.Inventory -> Inventory(state, model, content) Screen.Inventory -> Inventory(state, model, content)
Screen.Detail -> Detail(state, model, content) Screen.Detail -> Detail(state, model, content)
Screen.Add -> AddItem(state, model, content) Screen.Add -> AddItem(state, model, content)
Screen.Edit -> EditItem(state, model, content)
Screen.Move -> MoveItem(state, model, content) Screen.Move -> MoveItem(state, model, content)
} }
} }
@ -248,12 +257,49 @@ private fun Detail(state: AtlasState, model: AtlasViewModel, modifier: Modifier)
Text(item.name, style = MaterialTheme.typography.headlineMedium) Text(item.name, style = MaterialTheme.typography.headlineMedium)
DetailLine("位置", item.displayPlace()) DetailLine("位置", item.displayPlace())
DetailLine("数量", item.quantity.toString()) 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.aliases.isNotEmpty()) DetailLine("别名", item.aliases.joinToString("、"))
if (item.notes.isNotBlank()) DetailLine("备注", item.notes) if (item.notes.isNotBlank()) DetailLine("备注", item.notes)
if (state.space?.writable == true) { if (state.space?.writable == true) {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
OutlinedButton(onClick = model::startEdit, enabled = !state.busy) { Text("编辑物品") }
OutlinedButton(onClick = model::startMove, 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 @Composable
@ -273,15 +319,11 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier
var placeId by rememberSaveable { mutableStateOf<String?>(null) } var placeId by rememberSaveable { mutableStateOf<String?>(null) }
val place = state.places.firstOrNull { it.id == placeId } val place = state.places.firstOrNull { it.id == placeId }
Form(modifier) { Form(modifier) {
OutlinedTextField(title, { title = it.take(150) }, Modifier.fillMaxWidth(), enabled = !state.busy, ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, !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))
PlacePicker(state.places, place?.path ?: "未设置位置", !state.busy) { placeId = it?.id } PlacePicker(state.places, place?.path ?: "未设置位置", !state.busy) { placeId = it?.id }
OutlinedTextField(aliases, { aliases = it }, Modifier.fillMaxWidth(), enabled = !state.busy, OutlinedTextField(aliases, { aliases = it }, Modifier.fillMaxWidth(), enabled = !state.busy,
label = { Text("别名,可用逗号分隔") }) label = { Text("别名,可用逗号分隔") })
OutlinedTextField(notes, { notes = it.take(1500) }, Modifier.fillMaxWidth(), enabled = !state.busy, ItemNotes(notes, { notes = it }, !state.busy)
label = { Text("备注") }, minLines = 2)
Status(state) Status(state)
Button(onClick = { model.create(title, quantity, place, aliases, notes) }, Button(onClick = { model.create(title, quantity, place, aliases, notes) },
enabled = title.isNotBlank() && !state.busy && (placeId == null || place != null), 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 @Composable
private fun MoveItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier) { private fun MoveItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier) {
val item = state.selected ?: return 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 place = state.places.firstOrNull { it.id == placeId }
val enabled = !state.busy && !state.writeConflict
Form(modifier) { Form(modifier) {
Text(item.name, style = MaterialTheme.typography.titleLarge) Text(item.name, style = MaterialTheme.typography.titleLarge)
DetailLine("当前位置", item.displayPlace()) DetailLine("当前位置", item.displayPlace())
val pickedLabel = place?.path ?: if (placeId == item.locationId) item.displayPlace() else "未设置位置" val pickedLabel = place?.path ?: if (placeId == item.locationId) item.displayPlace() else "未设置位置"
PlacePicker(state.places, pickedLabel, !state.busy) { placeId = it?.id } PlacePicker(state.places, pickedLabel, enabled) { placeId = it?.id }
Status(state) WriteStatus(state, model)
Button( Button(
onClick = { model.move(place) }, 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(), modifier = Modifier.fillMaxWidth(),
) { Text("确认移位") } ) { 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 @Composable
private fun PlacePicker(places: List<Place>, label: String, enabled: Boolean, onSelect: (Place?) -> Unit) { private fun PlacePicker(places: List<Place>, label: String, enabled: Boolean, onSelect: (Place?) -> Unit) {
var showPicker by remember { mutableStateOf(false) } var showPicker by remember { mutableStateOf(false) }

View File

@ -18,6 +18,7 @@ import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.JdbcClient; import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ResponseStatusException;
@ -65,7 +66,7 @@ class InventoryService {
) matches GROUP BY id ) matches GROUP BY id
) )
"""; """;
private static final String SELECT_ITEMS = """ private static final String ITEM_COLUMNS = """
SELECT i.*, COALESCE(p.path, '') AS path, SELECT i.*, COALESCE(p.path, '') AS path,
(post.id IS NOT NULL) AS published, post.id AS post_id, (post.id IS NOT NULL) AS published, post.id AS post_id,
ARRAY(SELECT a.alias FROM item_alias a ARRAY(SELECT a.alias FROM item_alias a
@ -73,10 +74,10 @@ class InventoryService {
(SELECT photo.id FROM item_photo photo (SELECT photo.id FROM item_photo photo
WHERE (photo.household_id,photo.item_id)=(i.household_id,i.id) WHERE (photo.household_id,photo.item_id)=(i.household_id,i.id)
ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id
FROM item i LEFT JOIN paths p ON p.household_id=i.household_id AND p.id=i.location_id """;
private static final String ITEM_DECORATIONS = """
LEFT JOIN paths p ON p.household_id=i.household_id AND p.id=i.location_id
LEFT JOIN community_post post ON (post.household_id,post.item_id)=(i.household_id,i.id) LEFT JOIN community_post post ON (post.household_id,post.item_id)=(i.household_id,i.id)
%s
WHERE i.household_id=:household AND i.archived_at IS NULL
"""; """;
private final JdbcClient db; private final JdbcClient db;
private final HouseholdAccess access; private final HouseholdAccess access;
@ -275,14 +276,22 @@ class InventoryService {
? "AND i.location_id IN (SELECT id FROM paths WHERE :location = ANY(ancestors))" ? "AND i.location_id IN (SELECT id FROM paths WHERE :location = ANY(ancestors))"
: "AND i.location_id = :location"; : "AND i.location_id = :location";
} }
var query = db.sql(SCOPED_PATHS + (searching ? SEARCH_HITS : "") String order = searching ? "score DESC,lower(i.name),i.id" : "lower(i.name),i.id";
+ SELECT_ITEMS.formatted(searching ? "JOIN hits ON hits.id=i.id" : "") + """ // Select a page before reading aliases, cover photos and publication details.
var query = db.sql(SCOPED_PATHS + (searching ? SEARCH_HITS : "") + """
, page AS MATERIALIZED (
SELECT i.*%s FROM item i
%s
WHERE i.household_id=:household AND i.archived_at IS NULL
AND (NOT :favorites OR EXISTS (SELECT FROM item_preference pref AND (NOT :favorites OR EXISTS (SELECT FROM item_preference pref
WHERE (pref.household_id,pref.item_id)=(i.household_id,i.id) WHERE (pref.household_id,pref.item_id)=(i.household_id,i.id)
AND pref.subject=:actor AND pref.favorite)) AND pref.subject=:actor AND pref.favorite))
%s %s
ORDER BY %s lower(i.name),i.id LIMIT :limit OFFSET :offset ORDER BY %s LIMIT :limit OFFSET :offset
""".formatted(locationFilter, searching ? "hits.score DESC," : "")) )
""".formatted(searching ? ",hits.score" : "", searching ? "JOIN hits ON hits.id=i.id" : "",
locationFilter, order)
+ ITEM_COLUMNS + "FROM page i\n" + ITEM_DECORATIONS + "ORDER BY " + order)
.param("household", household).param("limit", limit).param("offset", offset) .param("household", household).param("limit", limit).param("offset", offset)
.param("favorites", favorites).param("actor", actor); .param("favorites", favorites).param("actor", actor);
if (location != null) { if (location != null) {
@ -296,11 +305,15 @@ class InventoryService {
} }
private Item item(UUID household, UUID id) { private Item item(UUID household, UUID id) {
return db.sql(SCOPED_PATHS + SELECT_ITEMS.formatted("") + " AND i.id=:id") return db.sql(SCOPED_PATHS + ITEM_COLUMNS + "FROM item i\n" + ITEM_DECORATIONS + """
WHERE i.household_id=:household AND i.archived_at IS NULL AND i.id=:id
""")
.param("household", household).param("id", id) .param("household", household).param("id", id)
.query(ITEM).optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在")); .query(ITEM).optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在"));
} }
// A concurrent move can change the item and its history between these queries.
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
Detail detail(UUID household, String actor, UUID id) { Detail detail(UUID household, String actor, UUID id) {
access.role(household, actor); access.role(household, actor);
Item item = item(household, id); Item item = item(household, id);

View File

@ -0,0 +1,4 @@
CREATE INDEX item_active_name_order ON item(household_id, lower(name), id)
WHERE archived_at IS NULL;
CREATE INDEX item_move_recent ON item_move(household_id, item_id, id DESC);

View File

@ -1,8 +1,10 @@
"""Validate iOS workflows in a disposable environment with a native_account row for viewer.""" """Validate iOS workflows in a disposable environment with a native_account row for viewer."""
import concurrent.futures import concurrent.futures
import os import os
import subprocess
import time
from urllib.parse import urlencode from urllib.parse import urlencode
from uuid import uuid4 from uuid import UUID, uuid4
from smoke import RUN, await_operation, call, ready from smoke import RUN, await_operation, call, ready
@ -17,6 +19,8 @@ def verify():
verify_inventory_appearance(root) verify_inventory_appearance(root)
verify_search_and_voice(root) verify_search_and_voice(root)
verify_optional_locations(root) verify_optional_locations(root)
if dsn := os.environ.get("ATLAS_SMOKE_INVENTORY_DSN"):
verify_detail_snapshot(root, dsn)
verify_direct_invitations(root) verify_direct_invitations(root)
verify_location_order(root) verify_location_order(root)
verify_location_layout(root) verify_location_layout(root)
@ -129,6 +133,15 @@ def verify_search_and_voice(root):
return [row["id"] for row in call("GET", root + "/items?" + urlencode({"q": term}))] return [row["id"] for row in call("GET", root + "/items?" + urlencode({"q": term}))]
assert search("数据线") == [exact, alias, prefix, contains] assert search("数据线") == [exact, alias, prefix, contains]
paged = [
call("GET", root + "/items?" + urlencode({"q": "数据线", "limit": 1, "offset": offset}))
for offset in range(5)
]
assert [[item["id"] for item in page] for page in paged] == [[exact], [alias], [prefix], [contains], []]
matches = call("GET", root + "/items?" + urlencode(
{"q": "数据线", "location": room, "includeDescendants": "true", "favorites": "true", "limit": 1}
))
assert len(matches) == 1 and matches[0]["id"] == exact and matches[0]["locationPath"] == "书房 / 右抽屉"
assert set(search("书房 / 右抽屉")) == {exact, alias, contains} assert set(search("书房 / 右抽屉")) == {exact, alias, contains}
assert search("%") == [percent] assert search("%") == [percent]
call("GET", root + "/items?" + urlencode({"q": "数据线"}), user="other", status=404) call("GET", root + "/items?" + urlencode({"q": "数据线"}), user="other", status=404)
@ -212,6 +225,14 @@ def verify_optional_locations(root):
latest, initial = call("GET", address)["moves"] latest, initial = call("GET", address)["moves"]
assert (initial["fromPath"], initial["toPath"]) == ("", place["name"]) assert (initial["fromPath"], initial["toPath"]) == ("", place["name"])
assert (latest["fromPath"], latest["toPath"]) == (place["name"], "") assert (latest["fromPath"], latest["toPath"]) == (place["name"], "")
edit = {"name": manual["name"], "quantity": 2, "notes": "补记数量",
"aliases": ["照明,备用", "手电"], "version": moved["version"]}
call("PUT", address, edit, status=409)
revised = call("PUT", address, dict(edit, version=cleared["version"]))
detail = call("GET", address)
assert detail["item"] == revised and revised["locationId"] is None
assert revised["quantity"] == 2 and sorted(revised["aliases"]) == sorted(edit["aliases"])
assert detail["moves"] == [latest, initial]
name = "录入无位置手表 " + RUN name = "录入无位置手表 " + RUN
draft = call("POST", root + "/drafts", {"text": "记录两只手表", "source": "VOICE"}, status=201) draft = call("POST", root + "/drafts", {"text": "记录两只手表", "source": "VOICE"}, status=201)
@ -228,10 +249,58 @@ def verify_optional_locations(root):
assert actual["locationId"] is None and actual["locationPath"] == "" assert actual["locationId"] is None and actual["locationPath"] == ""
with_location, = call("GET", items + "?" + urlencode({"q": payload["items"][1]["name"]})) with_location, = call("GET", items + "?" + urlencode({"q": payload["items"][1]["name"]}))
assert with_location["locationId"] == place["id"] assert with_location["locationId"] == place["id"]
call("DELETE", address + "?version=" + str(cleared["version"]), status=204) call("DELETE", address + "?version=" + str(revised["version"]), status=204)
print("PASS unset positions in manual creation, search, links, move history and mixed draft confirmation", flush=True) print("PASS unset positions in manual creation, search, links, move history and mixed draft confirmation", flush=True)
def verify_detail_snapshot(root, dsn):
room = call("POST", root + "/locations", {"name": "并发测试柜"}, status=201)
item = call("POST", root + "/items", {"name": "并发测试钥匙", "quantity": 1}, status=201)
detail_path = root + "/items/" + item["id"]
space_id, room_id, item_id = UUID(root.rsplit("/", 1)[1]), UUID(room["id"]), UUID(item["id"])
psql = ["psql", dsn, "-XAtq", "-v", "ON_ERROR_STOP=1"]
waiting_lock = """
SELECT EXISTS (SELECT FROM pg_locks WHERE relation='item_move'::regclass
AND database=(SELECT oid FROM pg_database WHERE datname=current_database())
AND mode='AccessShareLock' AND NOT granted);
"""
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
with subprocess.Popen(psql, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as writer:
writer.stdin.write("BEGIN; LOCK TABLE item_move IN ACCESS EXCLUSIVE MODE; SELECT 'locked';\n")
writer.stdin.flush()
assert writer.stdout.readline().strip() == "locked"
detail = pool.submit(call, "GET", detail_path)
try:
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
probe = subprocess.run(psql, input=waiting_lock, text=True,
capture_output=True, timeout=4, check=True)
if probe.stdout.strip() == "t":
break
time.sleep(0.05)
else:
raise AssertionError("Detail read did not reach the history query")
# Commit a move after the detail request has already read the item.
writer.stdin.write(f"""
UPDATE item SET location_id='{room_id}',version=1
WHERE household_id='{space_id}' AND id='{item_id}';
INSERT INTO item_move(household_id,item_id,from_path,to_path)
VALUES ('{space_id}','{item_id}','','并发测试柜');
COMMIT;
""")
writer.stdin.flush()
finally:
writer.stdin.close()
assert writer.wait(timeout=5) == 0
older = detail.result(timeout=10)
assert older["item"]["version"] == 0 and older["moves"] == []
latest = call("GET", detail_path)
assert latest["item"]["version"] == 1 and latest["item"]["locationId"] == str(room_id)
assert [move["toPath"] for move in latest["moves"]] == ["并发测试柜"]
print("PASS detail snapshot stays consistent while a move commits", flush=True)
def verify_direct_invitations(root): def verify_direct_invitations(root):
sent = root + "/direct-invitations" sent = root + "/direct-invitations"
inbox = "/api/households/direct-invitations" inbox = "/api/households/direct-invitations"

View File

@ -47,6 +47,21 @@ PostgreSQL `pg_trgm` 给活跃物品名称和别名提供 GIN 索引,短中文
当前部署用一个 SSD PostgreSQL。先按空间大小和查询长度观察网关、物品接口的 P95,再用真实类别和同音词样本检查命中。压测时分别覆盖小空间、单大空间、多空间并发和两字词。需要中文分词、拼写容错、复杂召回,或索引压测达到 PostgreSQL 的资源边界时,再用相同样本对比 Elasticsearch 的字段权重和 BM25。引入时保留 PostgreSQL 为主库,用 Outbox 增量同步并支持重建索引,服务端继续验证空间访问权限。 [Elastic 相关性调优](https://www.elastic.co/docs/troubleshoot/elasticsearch/troubleshooting-search-relevance) 当前部署用一个 SSD PostgreSQL。先按空间大小和查询长度观察网关、物品接口的 P95,再用真实类别和同音词样本检查命中。压测时分别覆盖小空间、单大空间、多空间并发和两字词。需要中文分词、拼写容错、复杂召回,或索引压测达到 PostgreSQL 的资源边界时,再用相同样本对比 Elasticsearch 的字段权重和 BM25。引入时保留 PostgreSQL 为主库,用 Outbox 增量同步并支持重建索引,服务端继续验证空间访问权限。 [Elastic 相关性调优](https://www.elastic.co/docs/troubleshoot/elasticsearch/troubleshooting-search-relevance)
### 物品首屏和移位记录
列表先筛选空间、归档状态、关键词、位置和收藏,再按原顺序取当前页。别名、封面、完整位置路径和发布状态在分页之后组装。空关键词的首屏可以利用 `item_active_name_order` 的空间、名称和 ID 顺序。详情中的移位记录使用 `item_move_recent`,按空间和物品定位后取最近 100 条。 [PostgreSQL 索引与排序](https://www.postgresql.org/docs/17/indexes-ordering.html)
详情的物品、移位、关联和个人评价在同一只读 `REPEATABLE READ` 事务中返回。并发移位提交时,一个请求内显示同一数据库快照。编辑和移位仍使用物品版本校验,旧版本提交返回 409。 [PostgreSQL 事务隔离](https://www.postgresql.org/docs/17/transaction-iso.html#XACT-REPEATABLE-READ)
2026-11-29 使用本机 PostgreSQL 17.12、同一空间 32,000 件物品、210 个位置和 80,000 条移位记录对比。先执行 `ANALYZE`,再用 `EXPLAIN (ANALYZE, BUFFERS)` 各执行五次,取执行计划中 `Execution Time` 的中位数。首屏 30 条记录的内容和顺序逐条一致。 [PostgreSQL 执行计划](https://www.postgresql.org/docs/17/using-explain.html)
| 查询 | 优化前 | 优化后 | 访问的共享缓冲块数 |
| --- | ---: | ---: | ---: |
| 空关键词首屏 30 条 | 34.227 ms | 0.422 ms | 551 → 83 |
| 单件物品的最近移位(该物品有 2 条) | 2.829 ms | 0.019 ms | 991 → 4 |
Flyway V18 增加两个索引。本次数据规模下额外占用约 6.6 MiB。写入活跃物品或移位时会维护对应索引。正式迁移前按环境的表规模评估建索引期间的写入等待。回退服务可保留这两个索引。
## 按账号邀请 ## 按账号邀请
所有者按完整见物账号提交,服务端只匹配启用的原生账号。公开接口无模糊账号搜索。发送端每天最多 20 次,空间最多 20 个活跃邀请。发送返回 202,发出的有效邀请可以由发送方查看和撤销,邀请只在对应接收者的收件列表出现。收到邀请本身不会获得物品权限。 所有者按完整见物账号提交,服务端只匹配启用的原生账号。公开接口无模糊账号搜索。发送端每天最多 20 次,空间最多 20 个活跃邀请。发送返回 202,发出的有效邀请可以由发送方查看和撤销,邀请只在对应接收者的收件列表出现。收到邀请本身不会获得物品权限。