feat(android): 补上位置图标和物品价格编辑
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-30 18:48:41 +08:00
parent 1d6d600952
commit 8ca4b3bb79
9 changed files with 258 additions and 19 deletions

View File

@ -2,9 +2,9 @@
Android 8.0(API 26)及以上。使用 Kotlin、Jetpack Compose 和见物原生会话 API。应用分为找物、位置、社区和我的。用已有账号登录后可以新建或切换空间,按名称、别名或路径找物。录入可以暂时不填位置,移位也可以清空位置。
详情展示购入单价和移位记录,可以编辑名称、数量、别名和备注、设置关联、归档物品。个人收藏、星级和短评由账号各自保存。所有者可单独填写公开标题与正文并发布,社区支持搜索、查看作者、评论、打星和撤回。家中的存放路径、照片和备注仍按空间权限读取。
详情展示购入单价和移位记录,可以编辑名称、数量、别名、备注和物品图标,也可设置关联或归档。购入单价可留空或清除,按人民币分入库,修改时校验物品版本。个人收藏、星级和短评由账号各自保存。所有者可单独填写公开标题与正文并发布,社区支持搜索、查看作者、评论、打星和撤回。家中的存放路径、照片和备注仍按空间权限读取。
「位置」支持平铺排序及全屋、室内两级平面图。用模板新建或摆放已有位置,可以拖动到 10 厘米网格、修改宽深、旋转、撤回和重做。模型建议经预览和选择后进入本地编辑,点保存才更新后端。保存和排序都带版本冲突检查。三级及以下使用平铺。
「位置」支持平铺排序及全屋、室内两级平面图。用模板新建或摆放已有位置,可以拖动到 10 厘米网格、修改宽深、旋转、撤回和重做。模型建议经预览和选择后进入本地编辑,点保存才更新后端。保存和排序都带版本冲突检查。三级及以下使用平铺。进入位置后点图标可选本层图案或用该位置的照片缩略图,这项选择按账号保存。有写权限的成员可以修改位置名称和归档空位置。
添加物品可以转入智能录入。手工文字和通过系统本机识别转写的文字都能生成草稿。草稿中可以改名称和数量、换位置、清空位置,再确认保存。用返回的操作编号查询异步交付状态。语音在支持本机 SpeechRecognizer 的 Android 12 及以上设备可用,每次最多 25 秒。

View File

@ -15,8 +15,8 @@ android {
applicationId = "com.tutudog.itematlas"
minSdk = 26
targetSdk = 35
versionCode = 4
versionName = "0.1.3"
versionCode = 5
versionName = "0.1.4"
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

@ -0,0 +1,193 @@
package com.tutudog.itematlas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import java.math.BigDecimal
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
private val itemIcons = mapOf(
"BOX" to "▣ 通用", "CABLE" to "⌁ 线材", "BOOK" to "▤ 书籍", "TOOL" to "⚙ 工具",
"CLOTHING" to "◇ 衣物", "KEY" to "⚿ 钥匙", "HEADPHONES" to "♫ 耳机", "CAMERA" to "◉ 相机",
"COMPUTER" to "▰ 电脑", "GAME" to "✥ 游戏", "KITCHENWARE" to "◌ 厨具", "SPORT" to "◍ 运动",
"PET" to "❀ 宠物", "STATIONERY" to "✎ 文具", "MEDICINE" to "✚ 药品", "BOTTLE" to "♙ 瓶罐",
"WATCH" to "◷ 手表", "UMBRELLA" to "☂ 雨伞", "GLASSES" to "∞ 眼镜", "TOY" to "✦ 玩具",
)
private val roomIcons = mapOf(
"HOME" to "⌂ 房间", "LIVING_ROOM" to "▥ 客厅", "BEDROOM" to "◫ 卧室", "KITCHEN" to "◌ 厨房",
"BATHROOM" to "≋ 卫生间", "STUDY" to "▤ 书房", "BALCONY" to "☀ 阳台", "ENTRY" to "▯ 玄关",
"GARAGE" to "▣ 车库", "LAUNDRY" to "◉ 洗衣区", "FOLDER" to "◇ 其他区域",
)
private val storageIcons = mapOf(
"CABINET" to "▥ 柜子", "DRAWER" to "▱ 抽屉", "BOX" to "▣ 收纳盒", "BASKET" to "▨ 篮筐",
"DESK" to "▭ 桌面", "WARDROBE" to "▥ 衣柜", "SHELF" to "☷ 层架", "TV_STAND" to "▰ 电视柜",
"COUNTER" to "▔ 台面", "BOOKCASE" to "▤ 书柜", "TROLLEY" to "✥ 推车", "FRIDGE" to "▥ 冰箱",
"SHOE_CABINET" to "☰ 鞋柜", "TRAY" to "▱ 托盘", "BIN" to "◫ 收纳桶", "CASE" to "▣ 箱子",
"BAG" to "◇ 收纳袋", "DIVIDER" to "▥ 分隔", "POUCH" to "◇ 小袋", "TUBE" to "◌ 筒", "JAR" to "◉ 瓶罐",
"FOLDER" to "◇ 通用",
)
internal fun itemSymbol(icon: String): String = itemIcons[icon]?.substringBefore(' ') ?: "▣"
internal fun placeSymbol(place: Place): String =
(roomIcons + storageIcons)[place.displayIcon ?: place.icon]?.substringBefore(' ') ?: "◇"
internal fun priceInCents(value: String): Long? {
val clean = value.trim().replace(',', '.').replace(',', '.')
if (clean.isEmpty() || !Regex("""\d{1,11}(\.\d{1,2})?""").matches(clean)) return null
return clean.toBigDecimal().movePointRight(2).longValueExact().takeIf { it <= 9_990_000_000_000L }
}
internal fun priceText(cents: Long?): String = cents?.let { BigDecimal.valueOf(it, 2).toPlainString() }.orEmpty()
@Composable
internal fun AppearanceFields(
icon: String, price: String, enabled: Boolean, setIcon: (String) -> Unit, setPrice: (String) -> Unit,
) {
IconMenu("物品图标", itemIcons[icon].orEmpty(), itemIcons, enabled, setIcon)
val invalid = price.isNotBlank() && priceInCents(price) == null
OutlinedTextField(price, { setPrice(it.take(14)) }, Modifier.fillMaxWidth(), enabled = enabled,
singleLine = true, isError = invalid, label = { Text("购入单价(元,可选)") },
supportingText = { if (invalid) Text("输入 0 到 999 亿元,最多保留两位小数。") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal))
}
@Composable
private fun IconMenu(label: String, value: String, choices: Map<String, String>, enabled: Boolean, choose: (String) -> Unit) {
var expanded by remember { mutableStateOf(false) }
Box {
OutlinedButton(enabled = enabled, onClick = { expanded = true }) { Text("$label $value") }
DropdownMenu(expanded, onDismissRequest = { expanded = false }) {
choices.forEach { (id, title) ->
DropdownMenuItem(text = { Text(title) }, onClick = { expanded = false; choose(id) })
}
}
}
}
@Composable
internal fun LocationSettingsEntry(model: AtlasViewModel, space: Space, place: Place) {
key(space.id, place.id) {
var open by remember { mutableStateOf(false) }
val preview = place.iconPhotoId
if (preview != null) {
PhotoPreview(model, space, PhotoKind.Location, place.id, Photo(preview), true,
Modifier.size(44.dp).clickable(onClickLabel = "设置位置图标") { open = true })
} else {
OutlinedButton(onClick = { open = true },
modifier = Modifier.semantics { contentDescription = "设置位置图标" }) { Text(placeSymbol(place)) }
}
if (open) LocationSettings(model, space, place) { open = false }
}
}
@Composable
private fun LocationSettings(model: AtlasViewModel, space: Space, place: Place, close: () -> Unit) {
val scope = rememberCoroutineScope()
val icons = if (place.depth == 1) roomIcons else storageIcons
var name by remember { mutableStateOf(place.name) }
var photos by remember { mutableStateOf(emptyList<Photo>()) }
var busy by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
var confirmArchive by remember { mutableStateOf(false) }
fun run(task: suspend () -> Unit) {
if (busy) return
busy = true
error = null
scope.launch {
try { task() }
catch (failure: Exception) {
if (failure is CancellationException) throw failure
error = model.requestFailure(failure)
} finally { busy = false }
}
}
fun choose(presentation: PlacePresentation) = run {
model.api.presentation(space, place, presentation)
model.refreshLocations()
close()
}
LaunchedEffect(Unit) { run { photos = model.api.photos(space, PhotoKind.Location, place.id) } }
AlertDialog(onDismissRequest = { if (!busy) close() }, title = { Text("位置设置") },
text = {
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("第 ${place.depth} 级 · ${place.path}", style = MaterialTheme.typography.bodySmall)
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
if (space.writable) {
OutlinedTextField(name, { name = it.take(100) }, enabled = !busy, singleLine = true, label = { Text("位置名称") })
TextButton(enabled = !busy && name.isNotBlank() && name.trim() != place.name, onClick = {
run {
model.api.updateLocation(space, place, name.trim(), place.icon)
model.refreshLocations()
close()
}
}) { Text("保存名称") }
}
IconMenu("我的图标", icons[place.displayIcon ?: place.icon].orEmpty(), icons, !busy) {
choose(PlacePresentation(null, it))
}
if (photos.isNotEmpty()) {
Text("用位置照片作图标")
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
items(photos, key = Photo::id) { photo ->
PhotoPreview(model, space, PhotoKind.Location, place.id, photo, true,
Modifier.size(62.dp).clickable(enabled = !busy, onClickLabel = "选为位置图标") {
choose(PlacePresentation(photo.id, null))
})
}
}
}
TextButton(enabled = !busy, onClick = { choose(PlacePresentation(null, null)) }) { Text("恢复默认图标") }
if (space.writable) TextButton(enabled = !busy, onClick = { confirmArchive = true }) {
Text("归档位置", color = MaterialTheme.colorScheme.error)
}
}
}, confirmButton = { TextButton(enabled = !busy, onClick = close) { Text("关闭") } })
if (confirmArchive) AlertDialog(onDismissRequest = { confirmArchive = false }, title = { Text("归档这个位置?") },
text = { Text("有下级位置或存放物品时,请先处理这些内容。") },
confirmButton = { TextButton(onClick = {
confirmArchive = false
run {
model.api.archiveLocation(space, place)
model.openLocation(place.parentId)
model.refreshLocations()
close()
}
}) { Text("确认归档") } },
dismissButton = { TextButton(onClick = { confirmArchive = false }) { Text("取消") } })
}

View File

@ -31,6 +31,10 @@ data class Place(
val path: String,
val parentId: String? = null,
val sortRank: Int? = null,
val depth: Int = 1,
val icon: String = "FOLDER",
val displayIcon: String? = null,
val iconPhotoId: String? = null,
)
@Serializable
@ -44,6 +48,7 @@ data class Item(
val aliases: List<String> = emptyList(),
val version: Int,
val priceCents: Long? = null,
val icon: String = "BOX",
)
@Serializable
@ -67,8 +72,15 @@ data class ItemInput(
val locationId: String?,
val aliases: List<String>,
val notes: String,
val appearance: ItemAppearance? = null,
)
@Serializable
data class ItemAppearance(val icon: String, val priceCents: Long?)
@Serializable
data class PlacePresentation(val photoId: String?, val icon: String?)
class ApiError(val status: Int, message: String) : Exception(message)
class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
@ -85,7 +97,7 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
private data class SpaceInput(val name: String)
@Serializable
private data class PlaceInput(val name: String, val parentId: String?)
private data class PlaceInput(val name: String, val parentId: String?, val icon: String? = null)
@Serializable
private data class MoveInput(val locationId: String?, val version: Int)
@ -97,6 +109,7 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
val quantity: Int,
val aliases: List<String>,
val notes: String,
val appearance: ItemAppearance?,
)
@Serializable
@ -167,6 +180,16 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
suspend fun createLocation(space: Space, name: String, parentId: String?): Place =
json.decodeFromString(read(family(space, "locations"), "POST", json.encodeToString(PlaceInput(name, parentId))))
suspend fun updateLocation(space: Space, place: Place, name: String, icon: String): Place =
json.decodeFromString(read(family(space, "locations", place.id), "PUT", json.encodeToString(PlaceInput(name, place.parentId, icon))))
suspend fun presentation(space: Space, place: Place, choice: PlacePresentation): Place =
json.decodeFromString(read(family(space, "locations", place.id, "thumbnail"), "PUT", json.encodeToString(choice)))
suspend fun archiveLocation(space: Space, place: Place) {
read(family(space, "locations", place.id), "DELETE")
}
suspend fun loadOrder(space: Space, parentId: String?): LocationOrder {
val url = family(space, "locations", "order").newBuilder()
parentId?.let { url.addQueryParameter("parentId", it) }
@ -198,7 +221,7 @@ class AtlasApi(origin: String = BuildConfig.ATLAS_API_ORIGIN) {
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)
val change = ItemEdit(item.version, input.name, input.quantity, input.aliases, input.notes, input.appearance)
return json.decodeFromString(read(family(space, "items", item.id), "PUT", json.encodeToString(change)))
}

View File

@ -246,9 +246,9 @@ class AtlasViewModel : ViewModel() {
refreshLocations()
}
fun create(name: String, quantity: String, location: Place?, aliases: String, notes: String) {
fun create(name: String, quantity: String, location: Place?, aliases: String, notes: String, appearance: ItemAppearance? = null) {
val space = mutable.value.space?.takeIf { it.writable } ?: return
val input = itemInput(name, quantity, location?.id, aliases.split(',', ',', '、'), notes) ?: return
val input = itemInput(name, quantity, location?.id, aliases.split(',', ',', '、'), notes, appearance) ?: return
if (pendingItem != input) {
pendingItem = input
pendingKey = UUID.randomUUID().toString()
@ -260,7 +260,8 @@ class AtlasViewModel : ViewModel() {
}
}
private fun itemInput(name: String, quantity: String, location: String?, aliases: List<String>, notes: String): ItemInput? {
private fun itemInput(name: String, quantity: String, location: String?, aliases: List<String>, notes: String,
appearance: ItemAppearance?): 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 ||
@ -268,7 +269,7 @@ class AtlasViewModel : ViewModel() {
mutable.update { it.copy(error = "请检查名称、数量、别名和备注的长度。") }
return null
}
return ItemInput(name.trim(), count, location, names, notes)
return ItemInput(name.trim(), count, location, names, notes, appearance)
}
fun startEdit() {
@ -277,10 +278,10 @@ class AtlasViewModel : ViewModel() {
mutable.update { it.copy(screen = Screen.Edit, writeConflict = false, error = null) }
}
fun edit(name: String, quantity: String, aliases: List<String>, notes: String) {
fun edit(name: String, quantity: String, aliases: List<String>, notes: String, appearance: ItemAppearance? = null) {
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
val input = itemInput(name, quantity, item.locationId, aliases, notes, appearance) ?: return
writeItem { api.edit(space, item, input) }
}

View File

@ -144,7 +144,10 @@ private fun LocationItems(state: AtlasState, model: AtlasViewModel) {
}
}
}
if (active != null) Text(active.path, style = MaterialTheme.typography.titleLarge)
if (active != null) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
state.space?.let { LocationSettingsEntry(model, it, active) }
Text(active.path, style = MaterialTheme.typography.titleLarge)
}
state.space?.let { space ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (active == null || active.parentId == null) LocationPlanEntry(model, space, active)
@ -158,6 +161,7 @@ private fun LocationItems(state: AtlasState, model: AtlasViewModel) {
items(children, key = { "place/${it.id}" }) { place ->
Row(Modifier.fillMaxWidth().clickable(enabled = !state.busy) { model.openLocation(place.id) }
.padding(vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) {
Text(placeSymbol(place), Modifier.padding(end = 10.dp), color = MaterialTheme.colorScheme.primary)
Text(place.name, Modifier.weight(1f), style = MaterialTheme.typography.titleMedium)
Text("›", color = MaterialTheme.colorScheme.onSurfaceVariant)
}

View File

@ -271,7 +271,7 @@ private fun PhotoGallery(
}
@Composable
private fun PhotoPreview(
internal fun PhotoPreview(
model: AtlasViewModel, space: Space, kind: PhotoKind, id: String, photo: Photo,
thumbnail: Boolean, modifier: Modifier,
) {

View File

@ -214,6 +214,12 @@ private fun LocationPlan(model: AtlasViewModel, space: Space, place: Place?, dis
selected = null
})
}
if (current != null && !dirty && base.locations.any { it.id == current.id }) {
TextButton(enabled = !busy, onClick = {
dismiss()
model.openLocation(current.id)
}) { Text("查看这个位置") }
}
if (painted.isNotEmpty()) {
HorizontalDivider()
Text("图上的位置", style = MaterialTheme.typography.titleMedium)

View File

@ -159,7 +159,10 @@ private fun Detail(state: AtlasState, model: AtlasViewModel, modifier: Modifier)
Form(modifier) {
Status(state)
val item = state.selected ?: return@Form
Text(item.name, style = MaterialTheme.typography.headlineMedium)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(itemSymbol(item.icon), color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.headlineMedium)
Text(item.name, style = MaterialTheme.typography.headlineMedium)
}
DetailLine("位置", item.displayPlace())
DetailLine("数量", item.quantity.toString())
item.priceCents?.let {
@ -228,6 +231,8 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier
var quantity by rememberSaveable { mutableStateOf("1") }
var aliases by rememberSaveable { mutableStateOf("") }
var notes by rememberSaveable { mutableStateOf("") }
var icon by rememberSaveable { mutableStateOf("BOX") }
var price by rememberSaveable { mutableStateOf("") }
var placeId by rememberSaveable {
mutableStateOf(state.locationId.takeIf { state.tab == InventoryTab.Locations })
}
@ -241,9 +246,11 @@ private fun AddItem(state: AtlasState, model: AtlasViewModel, modifier: Modifier
OutlinedTextField(aliases, { aliases = it }, Modifier.fillMaxWidth(), enabled = !state.busy,
label = { Text("别名,可用逗号分隔") })
ItemNotes(notes, { notes = it }, !state.busy)
AppearanceFields(icon, price, !state.busy, { icon = it }, { price = it })
Status(state)
Button(onClick = { model.create(title, quantity, place, aliases, notes) },
enabled = title.isNotBlank() && !state.busy && (placeId == null || place != null),
val cents = priceInCents(price)
Button(onClick = { model.create(title, quantity, place, aliases, notes, ItemAppearance(icon, cents)) },
enabled = title.isNotBlank() && !state.busy && (placeId == null || place != null) && (price.isBlank() || cents != null),
modifier = Modifier.fillMaxWidth()) { Text("保存物品") }
}
}
@ -255,6 +262,8 @@ private fun EditItem(state: AtlasState, model: AtlasViewModel, modifier: Modifie
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) }
var icon by rememberSaveable(item.id, item.version) { mutableStateOf(item.icon) }
var price by rememberSaveable(item.id, item.version) { mutableStateOf(priceText(item.priceCents)) }
val enabled = !state.busy && !state.writeConflict
Form(modifier) {
ItemNameAndQuantity(title, { title = it }, quantity, { quantity = it }, enabled)
@ -274,9 +283,12 @@ private fun EditItem(state: AtlasState, model: AtlasViewModel, modifier: Modifie
TextButton(onClick = { aliases = ArrayList(aliases).apply { add("") } }, enabled = enabled) { Text("添加别名") }
}
ItemNotes(notes, { notes = it }, enabled)
AppearanceFields(icon, price, enabled, { icon = it }, { price = it })
WriteStatus(state, model)
Button(onClick = { model.edit(title, quantity, aliases, notes) },
enabled = enabled && title.isNotBlank(), modifier = Modifier.fillMaxWidth()) { Text("保存修改") }
val cents = priceInCents(price)
Button(onClick = { model.edit(title, quantity, aliases, notes, ItemAppearance(icon, cents)) },
enabled = enabled && title.isNotBlank() && (price.isBlank() || cents != null),
modifier = Modifier.fillMaxWidth()) { Text("保存修改") }
}
}