feat: 增加分级位置图标和社区分享
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-26 21:32:37 +08:00
parent 3cf0728b81
commit 4972d670ac
28 changed files with 1426 additions and 83 deletions

View File

@ -117,7 +117,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 11;
CURRENT_PROJECT_VERSION = 12;
GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";
@ -138,7 +138,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 11;
CURRENT_PROJECT_VERSION = 12;
GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";

View File

@ -0,0 +1,520 @@
import SwiftUI
private struct CommunityPost: Decodable, Identifiable {
let id: UUID
let title: String
let body: String
let author: String
let publishedAt: String
let average: Double?
let votes: Int
let myRating: Int?
var comments: Int
var ratingText: String {
if let average { return average.formatted(.number.precision(.fractionLength(1))) + " · \(votes) 人评分" }
return "暂无评分"
}
}
private struct FeedCursor: Decodable {
let rank: Int
let time: String
let id: UUID
}
private struct FeedResponse: Decodable {
let posts: [CommunityPost]
let next: FeedCursor?
}
private struct CommunityComment: Decodable, Identifiable {
let id: UUID
let body: String
let author: String
let mine: Bool
let createdAt: String
}
private struct CommentResponse: Decodable {
struct Cursor: Decodable { let time: String; let id: UUID }
let comments: [CommunityComment]
let next: Cursor?
}
private struct CommunityAPI {
let account: AtlasAccount
static let posts = "/api/community/posts"
func load<T: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> T {
var url = URLComponents()
url.path = path
if !query.isEmpty { url.queryItems = query }
return try JSONDecoder().decode(T.self, from: await account.request(url.string ?? path, timeout: 12))
}
func send<T: Encodable, R: Decodable>(_ path: String, method: String, _ body: T) async throws -> R {
let data = try await account.request(path, method: method, data: JSONEncoder().encode(body), timeout: 12)
return try JSONDecoder().decode(R.self, from: data)
}
}
struct CommunityFeedView: View {
let account: AtlasAccount
var source: InventoryStore? = nil
var mine = false
@State private var query = ""
@State private var posts: [CommunityPost] = []
@State private var next: FeedCursor?
@State private var loading = true
@State private var moreLoading = false
@State private var error: String?
@State private var requestID: UUID?
@State private var showingChooser = false
@State private var revision = 0
private var term: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }
var body: some View {
List {
if loading {
ProgressView("正在加载分享")
} else if posts.isEmpty && error == nil {
ContentUnavailableView(term.isEmpty ? "还没有分享" : "没找到相关分享",
systemImage: "bubble.left.and.bubble.right",
description: Text(mine ? "你公开的物品会显示在这里。" : "可以搜索公开物品,或发布自己的使用感受。"))
}
ForEach(posts) { post in
NavigationLink {
CommunityDetailView(account: account, postID: post.id)
} label: {
VStack(alignment: .leading, spacing: 9) {
Text(post.title).font(.headline)
Text(post.body).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
HStack(spacing: 12) {
Text(post.author).lineLimit(1)
Spacer(minLength: 0)
Label(post.ratingText, systemImage: "star")
Label(String(post.comments), systemImage: "bubble")
}
.font(.caption).foregroundStyle(.secondary)
}
.padding(.vertical, 5)
}
}
if let error {
Section {
Text(error).font(.footnote).foregroundStyle(.red)
Button("重试") { revision += 1 }
}
} else if next != nil {
Button(moreLoading ? "正在加载" : "更多分享") { Task { await load(append: true) } }
.disabled(moreLoading || loading)
}
}
.navigationTitle(mine ? "我公开的物品" : "社区")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $query, prompt: "搜公开物品和分享")
.toolbar {
if let source, source.space.role == "OWNER" && !mine {
ToolbarItem(placement: .topBarTrailing) {
Button { showingChooser = true } label: { Label("发布物品", systemImage: "square.and.pencil") }
}
}
}
.sheet(isPresented: $showingChooser) {
if let source { CommunityItemChooser(store: source) { revision += 1 } }
}
.task(id: "\(revision):\(source?.revision ?? 0):\(term)") { await load() }
.refreshable { await load() }
}
private func load(append: Bool = false) async {
let cursor = append ? next : nil
guard !append || (cursor != nil && !loading && !moreLoading) else { return }
let requested = term
let id = UUID()
requestID = id
error = nil
loading = !append
moreLoading = append
if !append { next = nil; posts = [] }
defer {
if requestID == id { loading = false; moreLoading = false }
}
do {
if !append && !requested.isEmpty { try await Task.sleep(for: .milliseconds(250)) }
var parameters = [URLQueryItem(name: "q", value: requested),
URLQueryItem(name: "mine", value: String(mine))]
if let cursor {
parameters += [.init(name: "rank", value: String(cursor.rank)),
.init(name: "time", value: cursor.time), .init(name: "before", value: cursor.id.uuidString)]
}
let result: FeedResponse = try await CommunityAPI(account: account).load(CommunityAPI.posts, query: parameters)
try Task.checkCancellation()
guard requestID == id, term == requested else { return }
let existing = Set(posts.map(\.id))
posts += result.posts.filter { !existing.contains($0.id) }
next = result.next
} catch where !Task.isCancelled && requestID == id { self.error = error.localizedDescription }
catch {}
}
}
private struct CommunityDetailView: View {
let account: AtlasAccount
let postID: UUID
@State private var post: CommunityPost?
@State private var comments: [CommunityComment] = []
@State private var next: CommentResponse.Cursor?
@State private var draft = ""
@State private var error: String?
@State private var busy = false
@FocusState private var typing: Bool
private var api: CommunityAPI { CommunityAPI(account: account) }
private var path: String { CommunityAPI.posts + "/\(postID)" }
var body: some View {
List {
if let post {
Section {
VStack(alignment: .leading, spacing: 10) {
Text(post.title).font(.title2.bold())
Text(post.author + " · " + String(post.publishedAt.prefix(10)))
.font(.footnote).foregroundStyle(.secondary)
Text(post.body).textSelection(.enabled)
}.padding(.vertical, 5)
}
Section("评分") {
Label(post.ratingText, systemImage: "star").foregroundStyle(.secondary)
Picker("我的评分", selection: Binding(get: { self.post?.myRating ?? 0 }, set: { stars in
Task { await rate(stars == 0 ? nil : stars) }
})) {
Text("未评分").tag(0)
ForEach(1...5, id: \.self) { Text("\($0) 星").tag($0) }
}.disabled(busy)
}
Section("评论") {
TextField("说说你的看法", text: $draft, axis: .vertical).focused($typing)
Button("发表评论") { typing = false; Task { await sendComment() } }
.disabled(busy || draft.utf16.count > 500 || draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
ForEach(comments) { comment in
VStack(alignment: .leading, spacing: 6) {
Text(comment.author).font(.subheadline.weight(.semibold))
Text(comment.body)
Text(comment.createdAt.prefix(10)).font(.caption).foregroundStyle(.secondary)
}
.swipeActions {
if comment.mine {
Button("删除", role: .destructive) { Task { await deleteComment(comment) } }
}
}
}
if next != nil {
Button("更多评论") { Task { await loadMore() } }.disabled(busy)
}
}
} else if error == nil {
ProgressView("正在打开分享")
}
if let error {
Section {
Text(error).font(.footnote).foregroundStyle(.red)
Button("重新加载") { Task { await load() } }
}
}
}
.navigationTitle("物品分享")
.navigationBarTitleDisplayMode(.inline)
.dismissibleKeyboard(active: typing) { typing = false }
.task { await load() }
.refreshable { await load() }
}
private func load() async {
await perform {
post = nil
comments = []
next = nil
let result: CommunityPost = try await api.load(path)
let listed: CommentResponse = try await api.load(path + "/comments")
try Task.checkCancellation()
post = result
comments = listed.comments
next = listed.next
}
}
private func loadMore() async {
guard let next else { return }
await perform {
let page: CommentResponse = try await api.load(path + "/comments", query: [
.init(name: "time", value: next.time), .init(name: "before", value: next.id.uuidString)
])
let existing = Set(comments.map(\.id))
comments += page.comments.filter { !existing.contains($0.id) }
self.next = page.next
}
}
private func sendComment() async {
struct Input: Encodable { let body: String }
let text = draft
await perform {
let comment: CommunityComment = try await api.send(path + "/comments", method: "POST", Input(body: text))
comments.insert(comment, at: 0)
post?.comments += 1
if draft == text { draft = "" }
}
}
private func deleteComment(_ comment: CommunityComment) async {
await perform {
_ = try await account.request(path + "/comments/\(comment.id)", method: "DELETE", timeout: 12)
comments.removeAll { $0.id == comment.id }
post?.comments -= 1
}
}
private func rate(_ stars: Int?) async {
struct Input: Encodable { let stars: Int? }
await perform {
post = try await api.send(path + "/rating", method: "PUT", Input(stars: stars))
}
}
private func perform(_ action: () async throws -> Void) async {
guard !busy else { return }
busy = true
error = nil
defer { busy = false }
do { try await action() }
catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
}
private struct CommunityItemChooser: View {
let store: InventoryStore
let onChange: () -> Void
@Environment(\.dismiss) private var dismiss
@State private var query = ""
@State private var items: [Item] = []
@State private var selected: Item?
@State private var loading = true
@State private var hasMore = false
@State private var error: String?
@State private var generation = UUID()
@State private var revision = 0
var body: some View {
NavigationStack {
List {
if loading && items.isEmpty { ProgressView("正在查找物品") }
ForEach(items) { item in
Button { selected = item } label: {
HStack {
Text(item.name).foregroundStyle(.primary)
Spacer()
if item.published == true {
Text("已公开").font(.caption).foregroundStyle(.secondary)
}
}
}
}
if let error {
Text(error).font(.footnote).foregroundStyle(.red)
Button("重新加载") { revision += 1 }
} else if !loading && items.isEmpty {
ContentUnavailableView("没有可选物品", systemImage: "archivebox")
} else if hasMore {
Button("更多物品") { Task { await load(append: true) } }.disabled(loading)
}
}
.navigationTitle("选择要分享的物品")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $query, prompt: "搜当前空间里的物品")
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("完成") { dismiss() } }
}
.task(id: "\(revision):\(query)") { await load() }
.sheet(item: $selected) { item in
PublicationEditor(store: store, item: item) {
revision += 1
onChange()
}
}
}
}
private func load(append: Bool = false) async {
guard !append || !loading else { return }
let id = UUID()
generation = id
let term = query
if !append { items = []; hasMore = false }
loading = true
error = nil
defer { if generation == id { loading = false } }
do {
if !append && !term.isEmpty { try await Task.sleep(for: .milliseconds(250)) }
let page = try await store.search(term, favorites: false, offset: append ? items.count : 0)
try Task.checkCancellation()
guard generation == id, query == term else { return }
items += page
hasMore = page.count == 50
} catch where !Task.isCancelled && generation == id { self.error = error.localizedDescription }
catch {}
}
}
struct CommunityPublicationSection: View {
let store: InventoryStore
let item: Item
@State private var editing = false
var body: some View {
if store.space.role == "OWNER" {
Section("社区分享") {
Button { editing = true } label: {
LabeledContent(item.published == true ? "管理分享" : "分享到社区",
value: item.published == true ? "已公开" : "私有")
}
}
.sheet(isPresented: $editing) { PublicationEditor(store: store, item: item) {} }
}
}
}
private struct PublicationEditor: View {
private struct Publication: Decodable {
let postId: UUID?
let title: String
let body: String
}
private struct Draft: Encodable {
var title: String
var body = ""
var isValid: Bool {
!title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && title.utf16.count <= 120
&& !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && body.utf16.count <= 2000
}
}
let store: InventoryStore
let item: Item
let onChange: () -> Void
@Environment(\.dismiss) private var dismiss
@FocusState private var typing: Bool
@State private var draft: Draft
@State private var publication: Publication?
@State private var busy = false
@State private var confirmingPublish = false
@State private var confirmingWithdrawal = false
@State private var error: String?
init(store: InventoryStore, item: Item, onChange: @escaping () -> Void) {
self.store = store
self.item = item
self.onChange = onChange
_draft = State(initialValue: Draft(title: String(item.name.prefix(120))))
}
private var path: String { store.itemPath(item.id) + "/publication" }
private var published: Bool { publication?.postId != nil }
var body: some View {
NavigationStack {
Form {
Section {
if publication != nil {
TextField("公开标题", text: $draft.title).focused($typing)
TextField("物品怎么样?写下你的使用感受", text: $draft.body, axis: .vertical)
.lineLimit(4...10).focused($typing)
} else if error == nil {
ProgressView("正在加载分享")
}
} footer: {
Text("登录用户可以看到这里填写的标题和内容。发出前请检查有没有住址、联系方式或其他私人信息。")
}
if let error {
Section {
Text(error).font(.footnote).foregroundStyle(.red)
if publication == nil { Button("重试") { Task { await load() } } }
}
}
if published {
Section {
Button("撤回分享", role: .destructive) { typing = false; confirmingWithdrawal = true }
.disabled(busy)
}
}
}
.navigationTitle(published ? "编辑社区分享" : "分享到社区")
.navigationBarTitleDisplayMode(.inline)
.dismissibleKeyboard(active: typing) { typing = false }
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() }.disabled(busy) }
ToolbarItem(placement: .confirmationAction) {
Button(published ? "保存" : "发布") {
typing = false
if published { Task { await save() } }
else { confirmingPublish = true }
}.disabled(publication == nil || busy || !draft.isValid)
}
}
.confirmationDialog("公开这条分享?", isPresented: $confirmingPublish, titleVisibility: .visible) {
Button("确认公开") { Task { await save() } }
} message: {
Text("这条分享会显示在社区和搜索结果中。")
}
.confirmationDialog("撤回这条分享?", isPresented: $confirmingWithdrawal, titleVisibility: .visible) {
Button("撤回", role: .destructive) { Task { await withdraw() } }
} message: {
Text("社区里的评论和评分也会删除。你的空间里会保留这件物品。")
}
.task { await load() }
}
.interactiveDismissDisabled(busy)
}
private func load() async {
await perform {
let response: Publication = try await store.get(path)
try Task.checkCancellation()
if response.postId != nil { draft = Draft(title: response.title, body: response.body) }
publication = response
}
}
private func save() async {
guard draft.isValid else { return }
await perform {
let _: Publication = try await store.send(path, method: "PUT", draft)
store.changed()
onChange()
dismiss()
}
}
private func withdraw() async {
await perform {
try await store.delete(path)
onChange()
dismiss()
}
}
private func perform(_ action: () async throws -> Void) async {
guard !busy else { return }
busy = true
error = nil
defer { busy = false }
do { try await action() }
catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
}

View File

@ -137,7 +137,8 @@ struct ItemEditor: View {
}
private var photoSection: some View {
Section("照片") {
let pickerTitle = photo == nil ? "选择照片" : "更换待上传照片"
return Section("照片") {
if let photo, let preview = UIImage(data: photo) {
Image(uiImage: preview)
.resizable().scaledToFit()
@ -153,7 +154,7 @@ struct ItemEditor: View {
}
if savedItem == nil {
PhotosPicker(selection: $photoSelection, matching: .images, preferredItemEncoding: .current) {
Label(photo == nil ? "选择照片" : "更换待上传照片", systemImage: "photo.badge.plus")
Label(pickerTitle, systemImage: "photo.badge.plus")
}
.disabled(busy || loadingPhoto)
}

View File

@ -5,13 +5,49 @@ struct InventorySymbol: Identifiable {
let title: String
let image: String
static let locations: [Self] = [
.init(id: "FOLDER", title: "默认", image: "folder.fill"),
private static let folder = Self(id: "FOLDER", title: "默认", image: "folder.fill")
private static let rooms: [Self] = [
folder,
.init(id: "HOME", title: "房间", image: "house.fill"),
.init(id: "DESK", title: "书桌", image: "desktopcomputer"),
.init(id: "LIVING_ROOM", title: "客厅", image: "sofa.fill"),
.init(id: "BEDROOM", title: "卧室", image: "bed.double.fill"),
.init(id: "KITCHEN", title: "厨房", image: "cooktop.fill"),
.init(id: "BATHROOM", title: "浴室", image: "bathtub.fill"),
.init(id: "STUDY", title: "书房", image: "books.vertical.fill"),
.init(id: "BALCONY", title: "阳台", image: "sun.max.fill"),
.init(id: "ENTRY", title: "玄关", image: "door.left.hand.open"),
.init(id: "GARAGE", title: "车库", image: "car.fill"),
.init(id: "LAUNDRY", title: "洗衣房", image: "washer.fill")
]
private static let furniture: [Self] = [
folder,
.init(id: "CABINET", title: "柜子", image: "cabinet.fill"),
.init(id: "WARDROBE", title: "衣柜", image: "hanger"),
.init(id: "SHELF", title: "置物架", image: "squareshape.split.3x3"),
.init(id: "DESK", title: "书桌", image: "desktopcomputer"),
.init(id: "TV_STAND", title: "电视柜", image: "tv.fill"),
.init(id: "COUNTER", title: "台面", image: "rectangle.grid.1x2.fill"),
.init(id: "BOOKCASE", title: "书柜", image: "books.vertical"),
.init(id: "TROLLEY", title: "推车", image: "cart.fill"),
.init(id: "FRIDGE", title: "冰箱", image: "refrigerator.fill"),
.init(id: "SHOE_CABINET", title: "鞋柜", image: "shoe.fill")
]
private static let containers: [Self] = [
folder,
.init(id: "DRAWER", title: "抽屉", image: "tray.fill"),
.init(id: "BASKET", title: "收纳篮", image: "basket.fill")
.init(id: "BASKET", title: "收纳篮", image: "basket.fill"),
.init(id: "TRAY", title: "托盘", image: "tray"),
.init(id: "BIN", title: "收纳桶", image: "archivebox"),
.init(id: "CASE", title: "收纳箱", image: "case.fill"),
.init(id: "BAG", title: "袋子", image: "bag.fill"),
.init(id: "BOX", title: "小盒", image: "shippingbox"),
.init(id: "DIVIDER", title: "格子", image: "square.grid.2x2.fill"),
.init(id: "POUCH", title: "小包", image: "wallet.bifold.fill"),
.init(id: "TUBE", title: "筒", image: "cylinder.fill"),
.init(id: "JAR", title: "罐子", image: "mug.fill")
]
static let items: [Self] = [
@ -20,15 +56,97 @@ struct InventorySymbol: Identifiable {
.init(id: "BOOK", title: "书本", image: "book.closed.fill"),
.init(id: "TOOL", title: "工具", image: "wrench.and.screwdriver.fill"),
.init(id: "CLOTHING", title: "衣物", image: "tshirt.fill"),
.init(id: "KEY", title: "钥匙", image: "key.fill")
.init(id: "KEY", title: "钥匙", image: "key.fill"),
.init(id: "HEADPHONES", title: "耳机", image: "headphones"),
.init(id: "CAMERA", title: "相机", image: "camera.fill"),
.init(id: "COMPUTER", title: "电脑", image: "laptopcomputer"),
.init(id: "GAME", title: "游戏", image: "gamecontroller.fill"),
.init(id: "KITCHENWARE", title: "餐厨", image: "fork.knife"),
.init(id: "SPORT", title: "运动", image: "basketball.fill"),
.init(id: "PET", title: "宠物", image: "pawprint.fill"),
.init(id: "STATIONERY", title: "文具", image: "pencil"),
.init(id: "MEDICINE", title: "药品", image: "pills.fill"),
.init(id: "BOTTLE", title: "水杯", image: "waterbottle.fill"),
.init(id: "WATCH", title: "手表", image: "watchface.applewatch.case"),
.init(id: "UMBRELLA", title: "雨伞", image: "umbrella.fill"),
.init(id: "GLASSES", title: "眼镜", image: "eyeglasses"),
.init(id: "TOY", title: "玩具", image: "teddybear.fill")
]
static func location(_ value: String?) -> Self { resolve(value, in: locations) }
static func location(_ value: String?) -> Self {
(rooms + furniture + containers).first { $0.id == value } ?? folder
}
static func item(_ value: String?) -> Self { resolve(value, in: items) }
static func palette(level: LocationLevel, including current: String?) -> [Self] {
let options = switch level {
case .room: rooms
case .furniture: furniture
case .container, .nested: containers
}
guard let current, !options.contains(where: { $0.id == current }) else { return options }
let old = location(current)
return old.id == current ? options + [old] : options
}
private static func resolve(_ value: String?, in symbols: [Self]) -> Self {
symbols.first { $0.id == value } ?? symbols[0]
static func item(_ value: String?) -> Self {
items.first { $0.id == value } ?? items[0]
}
}
enum LocationLevel {
case room, furniture, container, nested
init(depth: Int) {
self = switch depth {
case ...1: .room
case 2: .furniture
case 3: .container
default: .nested
}
}
var title: String {
switch self {
case .room: "一级 · 房间和区域"
case .furniture: "二级 · 家具和收纳区"
case .container: "三级 · 抽屉和容器"
case .nested: "内层容器"
}
}
var tint: Color {
switch self {
case .room: .indigo
case .furniture: .blue
case .container: .orange
case .nested: .secondary
}
}
}
struct LocationMark: View {
let store: InventoryStore
let place: Place
var size: CGFloat = 31
var body: some View {
let tint = LocationLevel(depth: place.levelDepth).tint
let symbol = InventorySymbol.location(place.displayIcon ?? place.icon).image
Group {
if let photo = place.iconPhotoId {
PhotoImage(store: store, target: .location(place.id), photo: photo, thumbnail: true,
placeholderSymbol: symbol, placeholderTint: tint)
} else {
Image(systemName: symbol)
.font(.subheadline.weight(.medium))
.foregroundStyle(tint)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(tint.opacity(0.10))
}
}
.frame(width: size, height: size)
.clipShape(.rect(cornerRadius: 8))
.accessibilityHidden(true)
}
}
@ -36,9 +154,10 @@ struct SymbolPicker: View {
let symbols: [InventorySymbol]
let color: Color
@Binding var selection: String
@ScaledMetric(relativeTo: .caption) private var cellWidth = 56.0
var body: some View {
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 12) {
LazyVGrid(columns: [GridItem(.adaptive(minimum: cellWidth, maximum: 120), spacing: 8)], spacing: 12) {
ForEach(symbols) { symbol in
let selected = selection == symbol.id
Button { selection = symbol.id } label: {

View File

@ -15,6 +15,11 @@ struct Place: Decodable, Identifiable {
let path: String
var icon: String? = nil
var coverPhotoId: UUID? = nil
var iconPhotoId: UUID? = nil
var displayIcon: String? = nil
var depth: Int? = nil
var levelDepth: Int { depth ?? (parentId == nil ? 1 : path.components(separatedBy: " / ").count) }
}
struct Item: Decodable, Identifiable {
@ -29,6 +34,7 @@ struct Item: Decodable, Identifiable {
let coverPhotoId: UUID?
var icon: String? = nil
var priceCents: Int64? = nil
var published: Bool? = nil
}
struct ItemInput: Encodable {
@ -87,7 +93,7 @@ enum PhotoTarget: Hashable {
var title: String {
switch self {
case .item: "物品照片"
case .location: "位置照片"
case .location: "详情照片"
}
}
}
@ -141,18 +147,36 @@ final class InventoryStore {
return created
}
struct LocationDisplay: Encodable {
var photoId: UUID? = nil
var icon: String? = nil
}
func saveLocation(name: String, parent: UUID?, icon: String, id: UUID?) async throws -> UUID {
struct Input: Encodable { let name: String; let parentId: UUID?; let icon: String }
struct Input: Encodable {
let name: String
let parentId: UUID?
let icon: String
}
let address = root + "/locations" + (id.map { "/\($0)" } ?? "")
let place: Place = try await send(address, method: id == nil ? "POST" : "PUT",
Input(name: name, parentId: parent, icon: icon))
updateLocation(place)
return place.id
}
func saveLocationDisplay(_ selection: LocationDisplay, location: UUID) async throws {
let place: Place = try await send(root + "/locations/\(location)/thumbnail", method: "PUT", selection)
updateLocation(place)
}
private func updateLocation(_ place: Place) {
if let index = locations.firstIndex(where: { $0.id == place.id }) {
locations[index] = place
} else {
locations.append(place)
}
changed()
return place.id
}
func itemPath(_ id: UUID?) -> String {

View File

@ -268,6 +268,7 @@ struct ItemDetailView: View {
if !detail.item.notes.isEmpty { Text(detail.item.notes) }
}
PhotoGallery(store: store, target: .item(itemID))
CommunityPublicationSection(store: store, item: detail.item)
Section("我的评价") { PreferenceEditor(store: store, detail: detail, saved: { self.detail = $0 }) }
if !detail.relations.isEmpty {
Section("关联物品") {
@ -301,6 +302,8 @@ struct ItemDetailView: View {
.sheet(isPresented: $showingEdit) { ItemEditor(store: store, existing: detail.item) }
.confirmationDialog("删除「\(detail.item.name)」?", isPresented: $confirmingDelete, titleVisibility: .visible) {
Button("删除物品和图片", role: .destructive) { Task { await archive(detail.item) } }
} message: {
if detail.item.published == true { Text("社区分享及其评论、评分也会删除。") }
}
} else if let error {
ContentUnavailableView { Label("加载失败", systemImage: "exclamationmark.circle") }

View File

@ -27,6 +27,7 @@ private struct SpacesView: View {
@State private var showingCreate = false
@State private var showingJoin = false
@State private var showingMyProfile = false
@State private var showingCommunity = false
@State private var loaded = false
@State private var error: String?
@State private var invitations: [ReceivedSpaceInvitation] = []
@ -74,11 +75,19 @@ private struct SpacesView: View {
.navigationTitle("我的空间")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button { showingCommunity = true } label: {
Label("社区", systemImage: "bubble.left.and.bubble.right")
}
}
ToolbarItemGroup(placement: .topBarTrailing) {
Button { showingJoin = true } label: { Label("使用邀请码", systemImage: "person.badge.plus") }
Button { showingMyProfile = true } label: { Label("我的", systemImage: "person.crop.circle") }
}
}
.sheet(isPresented: $showingCommunity) {
NavigationStack { CommunityFeedView(account: account) }
}
.sheet(isPresented: $showingMyProfile) {
NavigationStack { MyView(account: account, openSpaces: { showingMyProfile = false }) }
}
@ -153,6 +162,9 @@ private struct SpaceTabs: View {
InventoryView(store: store, switcher: switcher).tabItem { Label("找物", systemImage: "magnifyingglass") }
LocationView(store: store).tabItem { Label("位置", systemImage: "square.stack") }
IntakeView(store: store).tabItem { Label("录入", systemImage: "square.and.pencil") }
NavigationStack {
CommunityFeedView(account: store.account, source: store)
}.tabItem { Label("社区", systemImage: "bubble.left.and.bubble.right") }
NavigationStack {
MyView(account: store.account, store: store, openSpaces: openSpaces)
}.tabItem { Label("我的", systemImage: "person.crop.circle") }

View File

@ -27,7 +27,7 @@ struct LocationPicker: View {
.accessibilityLabel(title)
.accessibilityValue(path ?? "未选择")
.sheet(isPresented: $showingPicker) {
LocationSelection(places: store.locations, selected: selection, allowsClearing: allowsClearing) { chosen in
LocationSelection(store: store, places: store.locations, selected: selection, allowsClearing: allowsClearing) { chosen in
selection = chosen
showingPicker = false
}
@ -69,6 +69,7 @@ struct LocationTree {
}
struct LocationSelection: View {
let store: InventoryStore
let places: [Place]
let selected: UUID?
let allowsClearing: Bool
@ -103,7 +104,7 @@ struct LocationSelection: View {
ContentUnavailableView("还没有位置", systemImage: "folder",
description: Text("请先在「位置」里新建一个存放位置。"))
} else if query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
Section("房间和区域") {
Section(LocationLevel.room.title) {
children(tree.children(of: nil), tree: tree)
}
} else {
@ -126,12 +127,12 @@ struct LocationSelection: View {
List {
Section {
Button { pick(parent.id) } label: {
row("选这个位置", detail: parent.path, symbol: "location",
row("选这个位置", detail: parent.path, place: parent,
checked: selected == parent.id)
}
.buttonStyle(.plain)
}
Section("子位置") {
Section(LocationLevel(depth: parent.levelDepth + 1).title) {
children(tree.children(of: parent.id), tree: tree)
}
}
@ -145,7 +146,7 @@ struct LocationSelection: View {
choice(place)
} else {
NavigationLink(value: place.id) {
row(place.name, detail: nil, symbol: InventorySymbol.location(place.icon).image, checked: selected == place.id)
row(place.name, detail: nil, place: place, checked: selected == place.id)
}
}
}
@ -153,15 +154,15 @@ struct LocationSelection: View {
private func choice(_ place: Place, showsPath: Bool = false) -> some View {
Button { pick(place.id) } label: {
row(place.name, detail: showsPath ? place.path : nil, symbol: InventorySymbol.location(place.icon).image,
row(place.name, detail: showsPath ? place.path : nil, place: place,
checked: selected == place.id)
}
.buttonStyle(.plain)
}
private func row(_ title: String, detail: String?, symbol: String, checked: Bool) -> some View {
private func row(_ title: String, detail: String?, place: Place, checked: Bool) -> some View {
HStack(spacing: 11) {
Image(systemName: symbol).foregroundStyle(Color.atlasBlue).accessibilityHidden(true)
LocationMark(store: store, place: place)
VStack(alignment: .leading, spacing: 4) {
Text(title).foregroundStyle(.primary)
if let detail { Text(detail).font(.footnote).foregroundStyle(.secondary) }

View File

@ -14,6 +14,7 @@ private struct LocationContents: View {
@State private var items = ItemListResults()
@State private var addingLocation = false
@State private var editingLocation = false
@State private var editingAppearance = false
@State private var confirmingDelete = false
@State private var error: String?
@State private var retry = 0
@ -27,30 +28,34 @@ private struct LocationContents: View {
var body: some View {
List {
if let location {
Label(location.path, systemImage: InventorySymbol.location(location.icon).image)
.foregroundStyle(.secondary)
Section {
HStack(spacing: 11) {
LocationMark(store: store, place: location, size: 38)
VStack(alignment: .leading, spacing: 4) {
Text(location.path).font(.subheadline)
Text(LocationLevel(depth: location.levelDepth).title)
.font(.caption).foregroundStyle(.secondary)
}
}
Button { editingAppearance = true } label: {
Label("图标与缩略图", systemImage: "square.on.square")
}
.disabled(busy)
}
PhotoGallery(store: store, target: .location(location.id))
}
Section(location == nil ? "房间和区域" : "子位置") {
Section(LocationLevel(depth: (location?.levelDepth ?? 0) + 1).title) {
ForEach(store.locations.filter { $0.parentId == location?.id }) { child in
NavigationLink { LocationContents(store: store, initialLocation: child) } label: {
HStack(spacing: 12) {
Label(child.name, systemImage: InventorySymbol.location(child.icon).image)
if let cover = child.coverPhotoId {
Spacer(minLength: 0)
PhotoImage(store: store, target: .location(child.id), photo: cover, thumbnail: true,
placeholderSymbol: InventorySymbol.location(child.icon).image,
placeholderTint: .atlasBlue)
.frame(width: 38, height: 38)
.clipShape(.rect(cornerRadius: 7))
.accessibilityHidden(true)
}
HStack(spacing: 11) {
LocationMark(store: store, place: child)
Text(child.name)
}
}
}
if store.canWrite {
Button { addingLocation = true } label: {
Label(location == nil ? "新建位置" : "新建子位置", systemImage: "plus")
Label(location == nil ? "新建房间或区域" : "新建子位置", systemImage: "plus")
}
}
}
@ -85,6 +90,11 @@ private struct LocationContents: View {
PlaceEditor(store: store, existing: location) { _ in retry += 1 }
}
}
.sheet(isPresented: $editingAppearance) {
if let location {
PlaceEditor(store: store, existing: location, personal: true) { _ in }
}
}
.confirmationDialog("删除这个位置?", isPresented: $confirmingDelete, titleVisibility: .visible) {
Button("删除位置", role: .destructive) {
guard let location else { return }
@ -106,35 +116,88 @@ struct PlaceEditor: View {
let store: InventoryStore
let parent: UUID?
let existing: Place?
let personal: Bool
let saved: (UUID) -> Void
@Environment(\.dismiss) private var dismiss
@FocusState private var focused: Bool
@State private var name: String
@State private var icon: String
@State private var iconPhoto: UUID?
@State private var defaultDisplay: Bool
@State private var photos: [Photo] = []
@State private var error: String?
@State private var busy = false
init(store: InventoryStore, parent: UUID? = nil, existing: Place? = nil,
saved: @escaping (UUID) -> Void) {
personal: Bool = false, saved: @escaping (UUID) -> Void) {
self.store = store
self.parent = parent
self.existing = existing
self.personal = personal
self.saved = saved
_name = State(initialValue: existing?.name ?? "")
_icon = State(initialValue: InventorySymbol.location(existing?.icon).id)
_icon = State(initialValue: InventorySymbol.location(personal ? existing?.displayIcon : existing?.icon).id)
_iconPhoto = State(initialValue: personal ? existing?.iconPhotoId : nil)
_defaultDisplay = State(initialValue: personal && existing?.displayIcon == existing?.icon && existing?.iconPhotoId == nil)
}
private var level: LocationLevel {
LocationLevel(depth: existing?.levelDepth ?? ((store.locations.first { $0.id == parent }?.levelDepth ?? 0) + 1))
}
private var title: String {
if existing != nil { return "编辑位置" }
return parent == nil ? "新建位置" : "新建子位置"
if existing != nil { return personal ? "图标与缩略图" : "编辑位置" }
return parent == nil ? "新建房间或区域" : "新建子位置"
}
var body: some View {
NavigationStack {
Form {
TextField("名称", text: $name).focused($focused)
Section("位置图标") {
SymbolPicker(symbols: InventorySymbol.locations, color: .atlasBlue, selection: $icon)
if !personal {
TextField("名称", text: $name).focused($focused)
}
Section(level.title) {
SymbolPicker(symbols: InventorySymbol.palette(level: level, including: icon),
color: level.tint, selection: Binding(
get: { iconPhoto == nil && !defaultDisplay ? icon : "" },
set: { icon = $0; iconPhoto = nil; defaultDisplay = false }
))
if personal {
Button("使用空间默认图标") {
iconPhoto = nil
defaultDisplay = true
}
}
}
if personal, let existing, !photos.isEmpty {
Section {
ScrollView(.horizontal) {
HStack(spacing: 11) {
ForEach(photos) { photo in
Button {
iconPhoto = photo.id
defaultDisplay = false
} label: {
PhotoImage(store: store, target: .location(existing.id), photo: photo.id,
thumbnail: true, placeholderTint: level.tint)
.frame(width: 44, height: 44)
.clipShape(.rect(cornerRadius: 7))
.overlay {
RoundedRectangle(cornerRadius: 7)
.strokeBorder(iconPhoto == photo.id ? level.tint : .clear, lineWidth: 2)
}
}
.buttonStyle(.plain)
.accessibilityLabel("选为我的缩略图")
.accessibilityAddTraits(iconPhoto == photo.id ? .isSelected : [])
}
}
}
} header: {
Text("我的照片缩略图")
} footer: {
Text("只影响你看到的位置列表图标。")
}
}
if let error { Text(error).foregroundStyle(.red) }
}
@ -146,21 +209,34 @@ struct PlaceEditor: View {
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) }
ToolbarItem(placement: .confirmationAction) {
Button("保存") { focused = false; Task { await save() } }
.disabled(busy || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
.disabled(busy || (!personal && name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))
}
}
}
.interactiveDismissDisabled(busy)
.task {
guard personal, let existing else { return }
do { photos = try await store.get(store.root + PhotoTarget.location(existing.id).path) }
catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
}
private func save() async {
guard !busy else { return }
busy = true
error = nil
defer { busy = false }
do {
let id = try await store.saveLocation(name: name, parent: existing?.parentId ?? parent,
icon: icon, id: existing?.id)
saved(id)
if personal, let existing {
let personalIcon = defaultDisplay || iconPhoto != nil ? nil : icon
try await store.saveLocationDisplay(.init(photoId: iconPhoto, icon: personalIcon), location: existing.id)
saved(existing.id)
} else {
let id = try await store.saveLocation(name: name, parent: existing?.parentId ?? parent,
icon: icon, id: existing?.id)
saved(id)
}
dismiss()
} catch { self.error = error.localizedDescription }
}

View File

@ -138,8 +138,13 @@ struct MyView: View {
}
}
if let store {
Section {
Section {
NavigationLink {
CommunityFeedView(account: account, mine: true)
} label: {
Label("我公开的物品", systemImage: "bubble.left")
}
if let store {
NavigationLink {
ItemListView(store: store, favoritesOnly: true)
} label: {

View File

@ -32,6 +32,13 @@ spring:
- Path=/api/households/{householdId}/items/{itemId}/photos,/api/households/{householdId}/locations/{locationId}/photos
filters:
- RequestSize=6MB
- id: community
order: -1
uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081}
predicates:
- Path=/api/community/posts,/api/community/posts/**
filters:
- RequestSize=16KB
- id: inventory
uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081}
predicates:

View File

@ -0,0 +1,80 @@
package com.tutudog.itematlas.inventory;
import static com.tutudog.itematlas.inventory.CommunityService.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
import java.security.Principal;
import java.time.Instant;
import java.util.UUID;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
class CommunityController {
private static final String COMMUNITY = "/api/community/posts";
private static final String PUBLICATION = "/api/households/{household}/items/{item}/publication";
private final CommunityService service;
CommunityController(CommunityService service) { this.service = service; }
@GetMapping(COMMUNITY)
ResponseEntity<Feed> feed(Principal user, @RequestParam(defaultValue = "") @Size(max = 120) String q,
@RequestParam(defaultValue = "false") boolean mine, @RequestParam(defaultValue = "20") @Min(1) @Max(50) int limit,
@RequestParam(required = false) @Min(0) @Max(100) Integer rank,
@RequestParam(required = false) Instant time, @RequestParam(required = false) UUID before) {
return fresh(service.feed(user.getName(), q, mine, limit, rank, time, before));
}
@GetMapping(COMMUNITY + "/{id}")
ResponseEntity<Post> post(Principal user, @PathVariable UUID id) {
return fresh(service.post(id, user.getName()));
}
@GetMapping(PUBLICATION)
ResponseEntity<Publication> publication(Principal user, @PathVariable UUID household, @PathVariable UUID item) {
return fresh(service.publication(household, item, user.getName()));
}
@PutMapping(PUBLICATION)
ResponseEntity<Publication> publish(Principal user, @PathVariable UUID household, @PathVariable UUID item,
@RequestBody @Valid Publish input) {
return fresh(service.publish(household, item, user.getName(), input));
}
@DeleteMapping(PUBLICATION)
ResponseEntity<Void> withdraw(Principal user, @PathVariable UUID household, @PathVariable UUID item) {
service.withdraw(household, item, user.getName());
return ResponseEntity.noContent().build();
}
@GetMapping(COMMUNITY + "/{id}/comments")
ResponseEntity<Comments> comments(Principal user, @PathVariable UUID id,
@RequestParam(defaultValue = "20") @Min(1) @Max(50) int limit,
@RequestParam(required = false) Instant time, @RequestParam(required = false) UUID before) {
return fresh(service.comments(id, user.getName(), limit, time, before));
}
@PostMapping(COMMUNITY + "/{id}/comments")
ResponseEntity<Comment> comment(Principal user, @PathVariable UUID id, @RequestBody @Valid CommentInput input) {
return ResponseEntity.status(201).cacheControl(CacheControl.noStore()).body(service.comment(id, user.getName(), input));
}
@DeleteMapping(COMMUNITY + "/{id}/comments/{comment}")
ResponseEntity<Void> deleteComment(Principal user, @PathVariable UUID id, @PathVariable UUID comment) {
service.deleteComment(id, comment, user.getName());
return ResponseEntity.noContent().build();
}
@PutMapping(COMMUNITY + "/{id}/rating")
ResponseEntity<Post> rate(Principal user, @PathVariable UUID id, @RequestBody @Valid Rating input) {
return fresh(service.rate(id, user.getName(), input));
}
private static <T> ResponseEntity<T> fresh(T value) {
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(value);
}
}

View File

@ -0,0 +1,213 @@
package com.tutudog.itematlas.inventory;
import static org.springframework.http.HttpStatus.*;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.sql.Types;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
@Service
class CommunityService {
private static final String POST_FIELDS = """
SELECT p.id,p.title,p.body,p.published_at,p.score,
COALESCE(NULLIF(profile.nickname,''),'见物用户') AS author,
p.author_subject=:viewer AS mine,
round(r.average,1) AS average,r.votes,r.my_rating,
(SELECT count(*) FROM community_comment c WHERE c.post_id=p.id) AS comments
FROM page p
LEFT JOIN account_profile profile ON profile.subject=p.author_subject
CROSS JOIN LATERAL (
SELECT avg(stars) AS average,count(*) AS votes,
max(stars) FILTER (WHERE subject=:viewer) AS my_rating
FROM community_rating WHERE post_id=p.id
) r
""";
private static final RowMapper<ScoredPost> POST = (rs, row) -> new ScoredPost(new Post(
rs.getObject("id", UUID.class), rs.getString("title"), rs.getString("body"), rs.getString("author"),
rs.getBoolean("mine"), rs.getObject("published_at", OffsetDateTime.class).toInstant(),
rs.getBigDecimal("average"), rs.getLong("votes"), rs.getObject("my_rating", Integer.class), rs.getLong("comments")),
rs.getInt("score"));
private static final RowMapper<Comment> COMMENT = (rs, row) -> new Comment(
rs.getObject("id", UUID.class), rs.getString("body"), rs.getString("author"),
rs.getBoolean("mine"), rs.getObject("created_at", OffsetDateTime.class).toInstant());
private final JdbcClient db;
private final HouseholdAccess access;
CommunityService(JdbcClient db, HouseholdAccess access) {
this.db = db;
this.access = access;
}
Feed feed(String viewer, String query, boolean mine, int limit, Integer rank, Instant time, UUID before) {
if ((time == null) != (before == null) || (time == null) != (rank == null)) {
throw new ResponseStatusException(BAD_REQUEST, "分页参数不完整");
}
String term = query.strip();
boolean searching = !term.isEmpty();
String score = searching ? """
CASE WHEN lower(title)=lower(:term) THEN 100 WHEN lower(title) LIKE lower(:prefix) THEN 80
WHEN lower(title) LIKE lower(:pattern) THEN 60 ELSE 20 END
""" : "0";
String matches = searching ? " AND (lower(title) LIKE lower(:pattern) OR lower(body) LIKE lower(:pattern))" : "";
String cursor = before == null ? "" : " WHERE (score,published_at,id)<(:rank,:time,:before)";
var sql = db.sql("""
WITH ranked AS (
SELECT id,title,left(body,220) AS body,author_subject,published_at,%s AS score
FROM community_post WHERE (NOT :mine OR author_subject=:viewer)%s
), page AS (
SELECT * FROM ranked%s ORDER BY score DESC,published_at DESC,id DESC LIMIT :limit
)
""".formatted(score, matches, cursor) + POST_FIELDS + " ORDER BY p.score DESC,p.published_at DESC,p.id DESC")
.param("viewer", viewer).param("mine", mine).param("limit", limit + 1);
if (before != null) {
sql.param("rank", rank).param("time", OffsetDateTime.ofInstant(time, ZoneOffset.UTC)).param("before", before);
}
if (searching) {
String escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
sql.param("term", term).param("prefix", escaped + "%").param("pattern", "%" + escaped + "%");
}
var rows = sql.query(POST).list();
var last = rows.size() > limit ? rows.get(limit - 1) : null;
var next = last == null ? null : new Cursor(last.score(), last.post().publishedAt(), last.post().id());
return new Feed(rows.stream().limit(limit).map(ScoredPost::post).toList(), next);
}
Post post(UUID id, String viewer) {
return db.sql("""
WITH page AS (
SELECT id,title,body,author_subject,published_at,0 AS score FROM community_post WHERE id=:id
)
""" + POST_FIELDS).param("id", id).param("viewer", viewer).query(POST).optional()
.map(ScoredPost::post).orElseThrow(CommunityService::missing);
}
Publication publication(UUID household, UUID item, String actor) {
access.requireOwner(access.role(household, actor));
requireItem(household, item);
return db.sql("SELECT id,title,body FROM community_post WHERE household_id=:house AND item_id=:item")
.param("house", household).param("item", item)
.query((rs, row) -> new Publication(rs.getObject(1, UUID.class), rs.getString(2), rs.getString(3)))
.optional().orElse(new Publication(null, "", ""));
}
@Transactional
Publication publish(UUID household, UUID item, String actor, Publish input) {
access.requireOwner(access.lockMember(household, actor));
requireItem(household, item);
return db.sql("""
INSERT INTO community_post(id,household_id,item_id,author_subject,title,body)
VALUES (:id,:house,:item,:actor,:title,:body)
ON CONFLICT (household_id,item_id) DO UPDATE SET title=excluded.title,body=excluded.body
RETURNING id,title,body
""").param("id", UUID.randomUUID()).param("house", household).param("item", item)
.param("actor", actor).param("title", input.title().strip()).param("body", input.body().strip())
.query((rs, row) -> new Publication(rs.getObject(1, UUID.class), rs.getString(2), rs.getString(3))).single();
}
@Transactional
void withdraw(UUID household, UUID item, String actor) {
access.requireOwner(access.lockMember(household, actor));
requireItem(household, item);
db.sql("DELETE FROM community_post WHERE household_id=:house AND item_id=:item")
.param("house", household).param("item", item).update();
}
Comments comments(UUID post, String viewer, int limit, Instant time, UUID before) {
if ((time == null) != (before == null)) {
throw new ResponseStatusException(BAD_REQUEST, "分页参数不完整");
}
requirePost(post, "");
String cursor = before == null ? "" : " AND (c.created_at,c.id)<(:time,:before)";
var query = db.sql("""
SELECT c.id,c.body,c.created_at,c.subject=:viewer AS mine,
COALESCE(NULLIF(profile.nickname,''),'见物用户') AS author
FROM community_comment c LEFT JOIN account_profile profile ON profile.subject=c.subject
WHERE c.post_id=:post
""" + cursor + " ORDER BY c.created_at DESC,c.id DESC LIMIT :limit")
.param("viewer", viewer).param("post", post).param("limit", limit + 1);
if (before != null) { query.param("time", OffsetDateTime.ofInstant(time, ZoneOffset.UTC)).param("before", before); }
var rows = query.query(COMMENT).list();
var last = rows.size() > limit ? rows.get(limit - 1) : null;
return new Comments(rows.stream().limit(limit).toList(),
last == null ? null : new CommentCursor(last.createdAt(), last.id()));
}
@Transactional
Comment comment(UUID post, String actor, CommentInput input) {
requirePost(post, " FOR UPDATE");
long recent = db.sql("""
SELECT count(*) FROM community_comment
WHERE post_id=:post AND subject=:actor AND created_at>now()-interval '1 minute'
""").param("post", post).param("actor", actor).query(Long.class).single();
if (recent >= 8) { throw new ResponseStatusException(TOO_MANY_REQUESTS, "评论过于频繁,请稍后再试"); }
return db.sql("""
INSERT INTO community_comment(post_id,id,subject,body) VALUES (:post,:id,:viewer,:body)
RETURNING id,body,created_at,true AS mine,
COALESCE((SELECT NULLIF(nickname,'') FROM account_profile WHERE subject=:viewer),'见物用户') AS author
""").param("post", post).param("id", UUID.randomUUID()).param("viewer", actor)
.param("body", input.body().strip()).query(COMMENT).single();
}
@Transactional
void deleteComment(UUID post, UUID id, String actor) {
requirePost(post, " FOR KEY SHARE");
int changed = db.sql("DELETE FROM community_comment WHERE post_id=:post AND id=:id AND subject=:actor")
.param("post", post).param("id", id).param("actor", actor).update();
if (changed == 0) { throw new ResponseStatusException(NOT_FOUND, "评论不存在"); }
}
@Transactional
Post rate(UUID post, String actor, Rating input) {
requirePost(post, " FOR KEY SHARE");
if (input.stars() == null) {
db.sql("DELETE FROM community_rating WHERE post_id=:post AND subject=:actor")
.param("post", post).param("actor", actor).update();
} else {
db.sql("""
INSERT INTO community_rating(post_id,subject,stars) VALUES (:post,:actor,:stars)
ON CONFLICT (post_id,subject) DO UPDATE SET stars=excluded.stars
""").param("post", post).param("actor", actor).param("stars", input.stars(), Types.SMALLINT).update();
}
return post(post, actor);
}
private void requireItem(UUID household, UUID item) {
db.sql("SELECT id FROM item WHERE household_id=:house AND id=:item AND archived_at IS NULL")
.param("house", household).param("item", item).query(UUID.class).optional()
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在"));
}
private void requirePost(UUID post, String lock) {
db.sql("SELECT id FROM community_post WHERE id=:id" + lock)
.param("id", post).query(UUID.class).optional().orElseThrow(CommunityService::missing);
}
private static ResponseStatusException missing() {
return new ResponseStatusException(NOT_FOUND, "这条分享已下架或不存在");
}
private record ScoredPost(Post post, int score) {}
record Publish(@NotBlank @Size(max = 120) String title, @NotBlank @Size(max = 2000) String body) {}
record Publication(UUID postId, String title, String body) {}
record Post(UUID id, String title, String body, String author, boolean mine, Instant publishedAt,
java.math.BigDecimal average, long votes, Integer myRating, long comments) {}
record Cursor(int rank, Instant time, UUID id) {}
record Feed(List<Post> posts, Cursor next) {}
record CommentInput(@NotBlank @Size(max = 500) String body) {}
record Comment(UUID id, String body, String author, boolean mine, Instant createdAt) {}
record CommentCursor(Instant time, UUID id) {}
record Comments(List<Comment> comments, CommentCursor next) {}
record Rating(@Min(1) @Max(5) Integer stars) {}
}

View File

@ -43,6 +43,12 @@ class InventoryController {
return service.saveLocation(household, user.getName(), id, input);
}
@PutMapping(FAMILY + "/locations/{id}/thumbnail")
Location updateThumbnail(@PathVariable UUID household, @PathVariable UUID id, Principal user,
@RequestBody ThumbnailSelection selection) {
return service.updateThumbnail(household, id, user.getName(), selection);
}
@DeleteMapping(FAMILY + "/locations/{id}")
ResponseEntity<Void> archiveLocation(@PathVariable UUID household, @PathVariable UUID id, Principal user) {
service.archiveLocation(household, user.getName(), id);

View File

@ -12,15 +12,25 @@ import java.util.List;
import java.util.UUID;
final class InventoryDtos {
enum LocationIcon { FOLDER, HOME, DESK, CABINET, DRAWER, BASKET }
enum ItemIcon { BOX, CABLE, BOOK, TOOL, CLOTHING, KEY }
enum LocationIcon {
FOLDER, HOME, DESK, CABINET, DRAWER, BASKET,
LIVING_ROOM, BEDROOM, KITCHEN, BATHROOM, STUDY, BALCONY, ENTRY, GARAGE, LAUNDRY,
WARDROBE, SHELF, TV_STAND, COUNTER, BOOKCASE, TROLLEY, FRIDGE, SHOE_CABINET,
TRAY, BIN, CASE, BAG, BOX, DIVIDER, POUCH, TUBE, JAR
}
enum ItemIcon {
BOX, CABLE, BOOK, TOOL, CLOTHING, KEY, HEADPHONES, CAMERA, COMPUTER, GAME,
KITCHENWARE, SPORT, PET, STATIONERY, MEDICINE, BOTTLE, WATCH, UMBRELLA, GLASSES, TOY
}
record Location(UUID id, UUID parentId, String name, String path, LocationIcon icon, UUID coverPhotoId) {}
record Location(UUID id, UUID parentId, String name, String path, LocationIcon icon, UUID coverPhotoId,
UUID iconPhotoId, LocationIcon displayIcon, int depth) {}
record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId, LocationIcon icon) {}
record ThumbnailSelection(UUID photoId, LocationIcon icon) {}
record Appearance(@NotNull ItemIcon icon, @Min(0) @Max(9_999_999_999L) Long priceCents) {}
record Item(UUID id, String name, int quantity, String notes, UUID locationId,
String locationPath, int version, List<String> aliases, UUID coverPhotoId,
ItemIcon icon, Long priceCents) {}
ItemIcon icon, Long priceCents, boolean published) {}
record ItemInput(@NotBlank @Size(max = 150) String name,
@Min(1) @Max(9999) int quantity, @Size(max = 1500) String notes,
@NotNull UUID locationId,

View File

@ -20,20 +20,24 @@ class InventoryService {
private static final RowMapper<Location> LOCATION = (rs, row) -> new Location(
rs.getObject("id", UUID.class), rs.getObject("parent_id", UUID.class),
rs.getString("name"), rs.getString("path"), LocationIcon.valueOf(rs.getString("icon")),
rs.getObject("cover_photo_id", UUID.class));
rs.getObject("cover_photo_id", UUID.class), rs.getObject("icon_photo_id", UUID.class),
LocationIcon.valueOf(rs.getString("display_icon")), rs.getInt("depth"));
private static final RowMapper<Item> ITEM = (rs, row) -> new Item(
rs.getObject("id", UUID.class), rs.getString("name"), rs.getInt("quantity"),
rs.getString("notes"), rs.getObject("location_id", UUID.class), rs.getString("path"),
rs.getInt("version"), Arrays.asList((String[]) rs.getArray("aliases").getArray()),
rs.getObject("cover_photo_id", UUID.class), ItemIcon.valueOf(rs.getString("icon")),
rs.getObject("price_cents", Long.class));
rs.getObject("price_cents", Long.class), rs.getBoolean("published"));
private static final String SELECT_LOCATIONS = """
SELECT p.*,l.icon,
SELECT p.*,l.icon,cardinality(p.ancestors) AS depth,thumb.photo_id AS icon_photo_id,
COALESCE(thumb.icon,l.icon) AS display_icon,
(SELECT photo.id FROM location_photo photo
WHERE (photo.household_id,photo.location_id)=(p.household_id,p.id)
ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id
FROM location_paths(:household) p
JOIN location l ON (l.household_id,l.id)=(p.household_id,p.id)
LEFT JOIN location_thumbnail_preference thumb
ON (thumb.household_id,thumb.location_id)=(p.household_id,p.id) AND thumb.subject=:actor
""";
private static final String SCOPED_PATHS = "WITH paths AS (SELECT * FROM location_paths(:household))\n";
private static final String SEARCH_HITS = """
@ -55,7 +59,9 @@ class InventoryService {
)
""";
private static final String SELECT_ITEMS = """
SELECT i.*, p.path, ARRAY(SELECT a.alias FROM item_alias a
SELECT i.*, p.path,
EXISTS (SELECT FROM community_post post WHERE (post.household_id,post.item_id)=(i.household_id,i.id)) AS published,
ARRAY(SELECT a.alias FROM item_alias a
WHERE a.household_id=i.household_id AND a.item_id=i.id ORDER BY a.alias) AS aliases,
(SELECT photo.id FROM item_photo photo
WHERE (photo.household_id,photo.item_id)=(i.household_id,i.id)
@ -75,17 +81,21 @@ class InventoryService {
List<Location> locations(UUID household, String actor) {
access.role(household, actor);
return db.sql(SELECT_LOCATIONS + " ORDER BY p.path,p.id")
.param("household", household).query(LOCATION).list();
.param("household", household).param("actor", actor).query(LOCATION).list();
}
Location location(UUID household, String actor, UUID id) {
access.role(household, actor);
return location(household, id);
return locationFor(household, id, actor);
}
private Location location(UUID household, UUID id) {
return locationFor(household, id, null);
}
private Location locationFor(UUID household, UUID id, String actor) {
return db.sql(SELECT_LOCATIONS + " WHERE p.id=:id")
.param("household", household).param("id", id).query(LOCATION).optional()
.param("household", household).param("id", id).param("actor", actor, Types.VARCHAR).query(LOCATION).optional()
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "位置不存在"));
}
@ -119,7 +129,37 @@ class InventoryService {
} catch (DuplicateKeyException ex) {
throw new ResponseStatusException(CONFLICT, "当前层级已有同名位置");
}
return location(household, target);
return locationFor(household, target, actor);
}
@Transactional
Location updateThumbnail(UUID household, UUID id, String actor, ThumbnailSelection selection) {
access.lockMember(household, actor);
location(household, id);
pickLocationThumbnail(household, id, actor, selection);
return locationFor(household, id, actor);
}
private void pickLocationThumbnail(UUID household, UUID id, String actor, ThumbnailSelection selection) {
UUID photo = selection.photoId();
LocationIcon icon = selection.icon();
if (photo != null && icon != null) { throw new ResponseStatusException(BAD_REQUEST, "请选择图标或照片中的一种"); }
if (photo == null && icon == null) {
db.sql("DELETE FROM location_thumbnail_preference WHERE household_id=:house AND location_id=:id AND subject=:actor")
.param("house", household).param("id", id).param("actor", actor).update();
return;
}
if (photo != null && !db.sql("""
SELECT EXISTS (SELECT FROM location_photo WHERE household_id=:house AND location_id=:id AND id=:photo)
""").param("house", household).param("id", id).param("photo", photo).query(Boolean.class).single()) {
throw new ResponseStatusException(NOT_FOUND, "位置照片不存在");
}
db.sql("""
INSERT INTO location_thumbnail_preference(household_id,location_id,subject,photo_id,icon)
VALUES (:house,:id,:actor,:photo,:icon)
ON CONFLICT (household_id,location_id,subject) DO UPDATE SET photo_id=excluded.photo_id,icon=excluded.icon
""").param("house", household).param("id", id).param("actor", actor).param("photo", photo, Types.OTHER)
.param("icon", icon == null ? null : icon.name(), Types.VARCHAR).update();
}
@Transactional

View File

@ -0,0 +1,32 @@
ALTER TABLE location DROP CONSTRAINT location_icon_check;
ALTER TABLE location ADD CONSTRAINT location_icon_check CHECK (icon IN (
'FOLDER','HOME','DESK','CABINET','DRAWER','BASKET',
'LIVING_ROOM','BEDROOM','KITCHEN','BATHROOM','STUDY','BALCONY','ENTRY','GARAGE','LAUNDRY',
'WARDROBE','SHELF','TV_STAND','COUNTER','BOOKCASE','TROLLEY','FRIDGE','SHOE_CABINET',
'TRAY','BIN','CASE','BAG','BOX','DIVIDER','POUCH','TUBE','JAR'
));
ALTER TABLE item DROP CONSTRAINT item_icon_check;
ALTER TABLE item ADD CONSTRAINT item_icon_check CHECK (icon IN (
'BOX','CABLE','BOOK','TOOL','CLOTHING','KEY','HEADPHONES','CAMERA','COMPUTER','GAME',
'KITCHENWARE','SPORT','PET','STATIONERY','MEDICINE','BOTTLE','WATCH','UMBRELLA','GLASSES','TOY'
));
ALTER TABLE location_photo ADD CONSTRAINT location_photo_parent_id UNIQUE (household_id, location_id, id);
CREATE TABLE location_thumbnail_preference (
household_id uuid NOT NULL,
location_id uuid NOT NULL,
subject text NOT NULL,
photo_id uuid,
icon varchar(16),
CHECK ((photo_id IS NULL) <> (icon IS NULL)),
PRIMARY KEY (household_id, location_id, subject),
FOREIGN KEY (household_id, location_id) REFERENCES location(household_id, id) ON DELETE CASCADE,
FOREIGN KEY (household_id, subject) REFERENCES household_member(household_id, subject) ON DELETE CASCADE,
FOREIGN KEY (household_id, location_id, photo_id)
REFERENCES location_photo(household_id, location_id, id) ON DELETE CASCADE
);
CREATE INDEX location_thumbnail_photo ON location_thumbnail_preference(household_id, location_id, photo_id);
CREATE INDEX location_thumbnail_member ON location_thumbnail_preference(household_id, subject);

View File

@ -0,0 +1,46 @@
CREATE TABLE community_post (
id uuid PRIMARY KEY,
household_id uuid NOT NULL,
item_id uuid NOT NULL,
author_subject text NOT NULL,
title varchar(120) NOT NULL CHECK (btrim(title) <> ''),
body varchar(2000) NOT NULL CHECK (btrim(body) <> ''),
published_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (household_id, item_id),
FOREIGN KEY (household_id, item_id) REFERENCES item(household_id, id) ON DELETE CASCADE
);
CREATE INDEX community_post_latest ON community_post(published_at DESC, id DESC);
CREATE INDEX community_post_author ON community_post(author_subject, published_at DESC, id DESC);
CREATE INDEX community_post_title_search ON community_post USING gin (lower(title) gin_trgm_ops);
CREATE INDEX community_post_body_search ON community_post USING gin (lower(body) gin_trgm_ops);
CREATE TABLE community_rating (
post_id uuid NOT NULL REFERENCES community_post(id) ON DELETE CASCADE,
subject text NOT NULL,
stars smallint NOT NULL CHECK (stars BETWEEN 1 AND 5),
PRIMARY KEY (post_id, subject)
);
CREATE TABLE community_comment (
post_id uuid NOT NULL REFERENCES community_post(id) ON DELETE CASCADE,
id uuid NOT NULL,
subject text NOT NULL,
body varchar(500) NOT NULL CHECK (btrim(body) <> ''),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (post_id, id)
);
CREATE INDEX community_comment_recent ON community_comment(post_id, created_at DESC, id DESC);
CREATE INDEX community_comment_sender ON community_comment(post_id, subject, created_at DESC);
CREATE FUNCTION withdraw_archived_item_posts() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
DELETE FROM community_post WHERE household_id=NEW.household_id AND item_id=NEW.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER item_archive_community_cleanup AFTER UPDATE OF archived_at ON item
FOR EACH ROW WHEN (OLD.archived_at IS NULL AND NEW.archived_at IS NOT NULL)
EXECUTE FUNCTION withdraw_archived_item_posts();

View File

@ -15,6 +15,7 @@ def verify():
verify_inventory_appearance(root)
verify_search_and_voice(root)
verify_direct_invitations(root)
verify_community(root)
finally:
call("DELETE", root, status=202)
@ -149,5 +150,89 @@ def verify_direct_invitations(root):
print("PASS addressed invitations, private inbox, atomic acceptance and role checks", flush=True)
def verify_community(root):
room = call("POST", root + "/locations", {"name": "测试住址" + RUN, "icon": "BEDROOM"}, status=201)
posts = "/api/community/posts"
term = "社区相机" + RUN
def create(name):
return call("POST", root + "/items", {
"name": name, "quantity": 1, "locationId": room["id"], "notes": "仅家庭可见" + RUN,
"appearance": {"icon": "CAMERA", "priceCents": 12800},
}, status=201)
def publication(item):
return root + "/items/" + item["id"] + "/publication"
item, second = create("家庭相机" + RUN), create("旧设备" + RUN)
assert item["published"] is False
assert call("GET", publication(item))["postId"] is None
call("GET", posts, user=None, status=401)
call("GET", posts + "?limit=0", status=400)
call("GET", posts + "?rank=2", status=400)
assert call("GET", posts + "?" + urlencode({"q": term}), user="other")["posts"] == []
draft = {"title": term, "body": "外出拍照携带方便。" * 32}
call("PUT", publication(item), draft, user="viewer", status=403)
call("PUT", publication(item), draft, user="other", status=404)
call("PUT", publication(item), dict(draft, body=" "), status=400)
sharing = call("PUT", publication(item), draft)
assert call("PUT", publication(item), draft) == sharing
weaker = call("PUT", publication(second), {"title": "另一份使用体会", "body": term})["postId"]
address = posts + "/" + sharing["postId"]
assert call("GET", root + "/items/" + item["id"])["item"]["published"] is True
result = call("GET", address, user="other")
assert set(result) == {"id", "title", "body", "author", "mine", "publishedAt",
"average", "votes", "myRating", "comments"}
assert result["title"] == term and result["body"] == draft["body"] and result["mine"] is False
assert not any(value in str(result) for value in (item["id"], item["name"], room["id"], room["name"], item["notes"]))
query = {"q": term, "limit": 1}
first = call("GET", posts + "?" + urlencode(query), user="other")
only, = first["posts"]
assert only["id"] == result["id"] and len(only["body"]) == 220
cursor = first["next"]
query.update(rank=cursor["rank"], time=cursor["time"], before=cursor["id"])
assert [row["id"] for row in call("GET", posts + "?" + urlencode(query), user="other")["posts"]] == [weaker]
assert not call("GET", posts + "?mine=true", user="other")["posts"]
assert result["id"] in {post["id"] for post in call("GET", posts + "?mine=true")["posts"]}
assert not call("GET", posts + "?" + urlencode({"q": room["name"]}))["posts"]
assert not call("GET", root + "/items?" + urlencode({"q": term}))
rating = address + "/rating"
call("PUT", rating, {"stars": 6}, user="other", status=400)
assert call("PUT", rating, {"stars": 4}, user="other")["votes"] == 1
updated = call("PUT", rating, {"stars": 5}, user="other")
assert updated["votes"] == 1 and updated["average"] == 5 and updated["myRating"] == 5
assert call("GET", address)["myRating"] is None
assert call("PUT", rating, {}, user="other")["votes"] == 0
comments = address + "/comments"
first = call("POST", comments, {"body": "请问续航怎么样?"}, user="other", status=201)
second_comment = call("POST", comments, {"body": "一天没问题。"}, status=201)
last = call("GET", comments + "?limit=1", user="other")
assert [row["id"] for row in last["comments"]] == [second_comment["id"]]
cursor = last["next"]
rest, = call("GET", comments + "?" + urlencode({"time": cursor["time"], "before": cursor["id"]}),
user="other")["comments"]
assert rest["id"] == first["id"] and rest["mine"] is True
call("DELETE", comments + "/" + first["id"], status=404)
call("DELETE", comments + "/" + first["id"], user="other", status=204)
assert call("GET", address)["comments"] == 1
call("PUT", rating, {"stars": 5}, user="other")
call("DELETE", publication(item), status=204)
call("GET", address, user="other", status=404)
call("GET", comments, user="other", status=404)
call("PUT", rating, {"stars": 1}, user="other", status=404)
assert call("GET", root + "/items/" + item["id"])["item"]["published"] is False
again = call("PUT", publication(item), draft)["postId"]
assert again != sharing["postId"]
assert call("GET", posts + "/" + again)["votes"] == 0
assert call("GET", posts + "/" + again + "/comments")["comments"] == []
call("DELETE", root + "/items/" + item["id"] + "?version=" + str(item["version"]), status=204)
call("GET", posts + "/" + again, user="other", status=404)
print("PASS private by default, public field boundary, ranked search, cursor, ratings, comments and withdrawal", flush=True)
if __name__ == "__main__":
verify()

View File

@ -71,7 +71,9 @@ def verify_location_photos(house, space, jpeg):
child = call("POST", space + "/locations", {"name": "收纳柜", "parentId": room}, status=201)["id"]
location = f"{space}/locations/{child}"
photos = location + "/photos"
assert call("GET", photos) == [] and call("GET", location)["coverPhotoId"] is None
initial = call("GET", location)
assert call("GET", photos) == [] and initial["coverPhotoId"] is None
assert initial["depth"] == 2 and call("GET", f"{space}/locations/{room}")["depth"] == 1
upload(photos, jpeg, user="viewer", status=403)
call("GET", photos, user="other", status=404)
upload(photos, b"x" * (6 * 1024 * 1024), status=413)
@ -82,6 +84,17 @@ def verify_location_photos(house, space, jpeg):
first = receipts[0]["id"]
second = json.loads(upload(photos, jpeg))["id"]
assert call("GET", location)["coverPhotoId"] == first
assert call("GET", location)["iconPhotoId"] is None
display = location + "/thumbnail"
call("PUT", display, {"photoId": first}, user="other", status=404)
call("PUT", f"{space}/locations/{room}/thumbnail", {"photoId": first}, status=404)
call("PUT", display, {"photoId": first, "icon": "CABINET"}, status=400)
assert call("PUT", display, {"photoId": first})["iconPhotoId"] == first
assert call("GET", location, user="viewer")["iconPhotoId"] is None
personal = call("PUT", display, {"icon": "CABINET"}, user="viewer")
assert personal["displayIcon"] == "CABINET" and personal["icon"] == "FOLDER"
assert call("GET", location)["displayIcon"] == "FOLDER"
assert call("PUT", display, {"photoId": second}, user="viewer")["iconPhotoId"] == second
asset = f"{photos}/{first}"
full = response(make_request("GET", asset, None, "owner"), 200)
thumb = response(make_request("GET", asset + "?thumbnail=true", None, "viewer"), 200)
@ -91,7 +104,10 @@ def verify_location_photos(house, space, jpeg):
call("DELETE", asset, user="viewer", status=403)
call("DELETE", asset, status=202)
await_absence(house, child, first, "locations")
assert call("GET", location)["coverPhotoId"] == second
fallback = call("GET", location)
assert fallback["coverPhotoId"] == second and fallback["iconPhotoId"] is None and fallback["displayIcon"] == "FOLDER"
assert call("GET", location, user="viewer")["iconPhotoId"] == second
assert call("PUT", display, {}, user="viewer")["iconPhotoId"] is None
call("DELETE", location, status=204)
call("GET", photos, status=404)
await_absence(house, child, second, "locations")

View File

@ -4,6 +4,6 @@
| --- | --- |
| 产品 | [调研](product/research.md)、[产品设计](product/overview.md)、[需求与验收](product/requirements.md)、[iOS 日常使用](product/ios-experience.md) |
| UI | [界面设计与走查](ui/README.md)、[低保真原型](ui/wireframes.md) |
| 架构 | [系统架构](architecture/system.md)、[客户端选型](architecture/clients.md)、[语音、搜索和邀请](architecture/mobile-capture-and-search.md)、[模型接入](architecture/ai-providers.md)、[可观测性](architecture/observability.md)、[两级缓存](architecture/cache.md) |
| 架构 | [系统架构](architecture/system.md)、[客户端选型](architecture/clients.md)、[语音、搜索和邀请](architecture/mobile-capture-and-search.md)、[位置图标](architecture/inventory-appearance.md)、[社区](architecture/community.md)、[模型接入](architecture/ai-providers.md)、[可观测性](architecture/observability.md)、[两级缓存](architecture/cache.md) |
| 部署 | [部署架构、域名与发布](deployment/overview.md)、[预发布环境搭建](deployment/staging-bootstrap.md)、[监控安装](deployment/observability.md)、[登录与图片](deployment/identity-and-media.md) |
| 测试 | [测试与演示计划](testing/plan.md)、[测试用例](testing/cases.md)、[后端验收](testing/backend-readiness.md) |

View File

@ -0,0 +1,28 @@
# 社区与公开物品
## 发布边界
社区和家庭物品都由 `inventory-service` 管理。一个物品可以有一条社区分享。数据库用 `community_post` 保存单独填写的标题和正文,通过空间与物品的复合外键关联。查不到分享记录时,物品是私有的。修改家里的名称、备注或价格时,已经发布的标题和正文原样保留。
空间所有者从物品详情或社区入口发起发布,确认后才写入。社区接口允许已登录账号访问,成员关系仍只用于家庭接口。公开响应使用单独的 DTO,返回帖子地址、标题、正文、昵称、发布时间、评分和评论数。位置树、家庭标识、源物品标识、购买信息、备注和照片留在家庭接口。昵称为空时显示「见物用户」。内容由用户输入,发布表单提醒先检查个人信息。
```mermaid
flowchart LR
App["iOS"] --> Gateway["API 网关"]
Gateway --> Inventory["物品服务"]
Inventory --> Home["家庭物品、位置和私有照片"]
Inventory --> Community["公开帖子、评分与评论"]
Home -->|"所有者确认发布"| Community
```
## 搜索、评论和评分
`GET /api/community/posts` 读取分享,`mine=true` 按当前账号筛选发布记录。搜索依次排完整标题、标题前缀、标题包含和正文包含。列表按命中分数、发布时间及帖子 ID 倒序翻页,摘要读前 220 字。详情读完整正文。查询词按字面匹配,PostgreSQL `pg_trgm` 索引覆盖标题和正文。含短搜索词的查询可能由 PostgreSQL 选择扫描,容量评估时也要纳入。家庭「找物」继续使用另一套按空间限定的查询。
每位账号在每个帖子下有一个 1–5 星的评分,重复提交会更新同一行,也可以清除。列表先取出当前页,再统计其中帖子的评分和评论。评论每条最多 500 字,按时间和评论 ID 分页,评论者可删除自己的评论。发表时锁住帖子并检查账号在该帖的一分钟内已有评论,达到八条时返回 429。当前聚合和评论都按数据库事务处理,压测时应分别观察热门帖的并发写入和列表读延迟。
## 数据撤回与发布
撤回时在同一事务删除帖子以及评分和评论,原物品仍在空间。归档物品由数据库触发器撤回,删除整个空间由外键清理帖子。原分享地址随后返回 404。再次发布会生成新地址。社区读取使用 `Cache-Control: no-store`,网关限制请求体为 16 KiB。物品列表的 `published` 由现有分享记录计算,避免再维护一份状态。
物品库 Flyway V12 安装社区表、索引和清理触发器。网关与物品服务要一同更新并通过就绪探针,之后交付使用该接口的 iOS 构建。验证使用隔离 PostgreSQL,覆盖默认私有、交叉账号访问、评分更新、搜索分页和撤回。公网预览发布时用已有账号做只读检查。 [后端发布](../deployment/backend-release.md) · [测试用例](../testing/cases.md)

View File

@ -1,12 +1,18 @@
# 位置图标、物品单价与首张照片
# 位置图标、个人缩略图与物品资料
## 字段和权限
Flyway V9 给位置与物品增加各自的图标标识,由 API 枚举和 PostgreSQL 约束校验。已有位置默认用文件夹,已有物品默认用箱子。位置详情与列表读取同一图标。位置层级由空间内的复合外键约束,编辑图标和名称沿用原来的空间写权限。
Flyway V9 给位置与物品增加各自的图标标识,由 API 枚举和 PostgreSQL 约束校验。已有位置默认用文件夹,已有物品默认用箱子。修改空间默认位置图标和名称沿用原来的空间写权限。
物品的 `appearance` 包含 `icon` 和可空的 `priceCents`。购入单价按人民币分存为整数,范围是 0 到 99,999,999.99 元。旧客户端省略 `appearance` 时保留现有字段。新版传入该对象且价格为空时清空单价。物品编辑沿用现有版本号校验。
## 首张照片
## 个人位置图标
Flyway V11 扩充图标并增加 `location_thumbnail_preference`。位置层级通过位置树的祖先数计算,位置列表和详情同时返回空间的默认 `icon`、当前账号的 `displayIcon` 和可空的 `iconPhotoId`。
`PUT /api/households/{householdId}/locations/{locationId}/thumbnail` 允许当前空间成员传一个预设 `icon` 或一张 `photoId`。空对象清除个人选择。数据库按空间、位置和账号存这一条选择。复合外键确保照片属于当前的位置,成员移除、选用的照片删除或位置记录物理删除时,外键清理相应的个人设置。位置归档后,其设置不再返回。照片正文和缩略图仍走原有授权下载接口。
## 首张物品照片
iOS 从相册读图,裁剪后的 JPEG 保留在编辑表单,保存时先创建物品,再按物品 ID 调用原照片接口。照片服务继续生成展示图和缩略图,存放在私有桶的 `households/{spaceId}/items/{itemId}/{photoId}/`。删除沿用对象清理队列。
@ -16,4 +22,4 @@ iOS 从相册读图,裁剪后的 JPEG 保留在编辑表单,保存时先创
在隔离 PostgreSQL 上运行 `backend/tests/ios_experience_smoke.py`,检查主子位置图标、购入价格、旧客户端兼容和并发创建。用独立 Garage 桶运行 `backend/tests/media_smoke.py`,检查并发重试、缩略图、大小限制、查看权限与对象清理。
部署前备份物品库。先升级物品服务并确认 Flyway V9,通过公网读取与真机验收后再交付 iOS。回退旧镜像时保留新增字段和索引。 [后端发布流程](../deployment/backend-release.md)
部署前备份物品库。先升级物品服务并确认 Flyway V11 和 V12,通过公网读取后再交付 iOS。旧镜像只识别原有的图标枚举。开始写入新图标后,发布故障优先用兼容新版枚举的镜像修复。 [后端发布流程](../deployment/backend-release.md)

View File

@ -11,7 +11,7 @@
| 服务 | 管什么 | 相关需求 |
| --- | --- | --- |
| `gateway` | Spring Cloud Gateway 提供 API 路由、请求体大小限制和物品读请求的版本分流。 | R01 |
| `inventory-service` | 家庭建档和成员权限、物品、位置、移动历史、别名搜索、关联、收藏和个人评分。 | R01、R02、R03、R04、R05、R08 |
| `inventory-service` | 家庭建档和成员权限、物品、位置、移动历史、别名搜索、关联、收藏、个人评分和[社区分享](community.md)。 | R01、R02、R03、R04、R05、R08 |
| `intake-service` | 批量草稿、模型提供方状态、本地模型、录入任务和执行结果。 | R06、R07 |
H5、PC 和管理后台规划为独立 Web 入口。网关转发业务请求,两个服务分别验证 Token,并检查家庭归属、角色和数据状态。跨服务的确认请求须带服务身份和原操作人,写入前由物品服务重新核对权限。 [客户端与后台](clients.md)
@ -35,7 +35,7 @@ Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。正式部署
| 收藏和评分 | 按用户和物品唯一保存,用户可以改分、取消收藏或清除短评。 |
| 草稿 | 保存输入、候选项和确认状态。同一草稿版本只接受一份确认任务。 |
业务路径放在 `/api/households/{householdId}` 下。`/items`、`/locations`、`/items/{id}/moves` 和 `/items/{id}/preference` 走物品服务。`/drafts`、`/drafts/{id}/confirm` 和 `/operations/{id}` 走录入服务。模型状态走 `/api/model-providers`,后台管理预留独立的 `/api/admin` 前缀。内部投递路径只允许服务访问。
业务路径放在 `/api/households/{householdId}` 下。`/items`、`/locations`、`/items/{id}/moves` 和 `/items/{id}/preference` 走物品服务。`/drafts`、`/drafts/{id}/confirm` 和 `/operations/{id}` 走录入服务。社区走 `/api/community/posts`,公开标题和正文来自独立社区表。模型状态走 `/api/model-providers`,后台管理预留独立的 `/api/admin` 前缀。内部投递路径只允许服务访问。
## 草稿确认与分布式一致性

View File

@ -16,17 +16,19 @@
下面是当前空间、空间设置和切换空间。收藏在「我的收藏」里,按当前空间显示。切换空间后可以查看该空间的收藏。收藏列表为空时直接显示空状态,加载出错可以重试。退出登录放在页面底部。
找物、位置、录入、我的使用同一套紧凑导航栏。录入页右上角的问号保留四步说明。
底部依次是找物、位置、录入、社区、我的。录入页右上角的问号保留四步说明。
找物页右上角显示当前空间。点开可看到可访问的空间和当前选中项,也可以进入完整的「我的空间」列表。
## 位置图标和物品信息
打开房间、区域或子位置,点右上角「编辑」即可修改名称和图标。新建时也能选图标,位置列表和选位置页面会同步显示。
空间下面第一级是房间和区域,用靛蓝色的房间图标。再往里是蓝色的家具和收纳区、橙色的抽屉和容器。第四级起统一显示为内层容器。列表有层级文字,设备字号较大时,图标选择器会减少每行的个数。
位置详情的「位置照片」可以拍照或从相册选图,裁剪确认后上传。已有照片可点开查看和删除,列表用第一张照片做缩略图。删除位置时,其照片随位置清理。
打开任一级位置,点「图标与缩略图」可选择自己的图标。有详情照片时,也可以挑其中一张当作列表小图。右上角「编辑」可以改名称和空间默认图标。团队成员可各自选择显示样式。
添加或编辑物品时,可以填写可选的购入单价、选择物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。
位置详情的「详情照片」支持拍照、相册和裁剪。删掉用作个人图标的那张照片后,位置会恢复空间默认图标。删除位置时,其照片随位置清理。
添加或编辑物品时,可以填写可选的购入单价、选择绿色物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。
## 选存放位置
@ -41,3 +43,9 @@
## 找物
搜索框接收名称、别名和位置。完整名称优先于完整别名,再排前缀、包含和位置。结果优先露出位置路径。录入或改名后,搜索直接读到数据库提交的结果。
## 社区
物品建好后默认只在空间里。空间所有者可从物品详情的「分享到社区」或社区右上角「发布物品」选一件,单独写标题和使用感受。社区首版分享文字,已经上传到家里的照片仍按空间权限查看。
登录后可浏览、搜索公开分享、打 1–5 星及发表评论。撤回后,帖子及其评分、评论从社区删除。物品仍在空间。家里的一件物品需要管理存放位置时,可建立相应的位置节点。例如用来放物品的架子,先按位置管理。首版没有双重身份和物品转位置操作。

View File

@ -13,12 +13,13 @@
| 关联 | 在详情里把硬盘和数据线、吸尘器和刷头之类的物品连起来,可从当前物品直接查看配件。 |
| 收藏和评分 | 每人可以收藏、用 1–5 星记录使用感受,补一句短评,也可以清除。个人评价不影响家庭物品的位置和管理权限。 |
| 家庭范围 | 所有者管理成员,编辑成员录入或移位,查看成员可以找物。首版用两户演示数据验证权限。 |
| 社区分享 | 所有者可挑一件物品,写使用感受并公开。已登录用户能搜索、评论和打星。存放位置和家中照片继续在空间里查看。 |
| 模型辅助 | 本地模型作为默认选项,云端由用户选择。草稿能逐条改位置、跳过或确认。 |
H5、PC 网页和管理后台是首批界面。iOS 和 Android 已纳入整体设计,按各自平台安排页面和功能。后台负责管理和运行状态。微信小程序暂不纳入。 [客户端设计](../architecture/clients.md)
## 后续方向
家庭邀请、共享扩展、拍照识物、公开物品评价和推荐逐步安排。用户公开分享时只选择愿意分享的物品介绍或使用体验。等有足够的公开评价或互动,再比较按类别推荐和协同过滤的效果。
后续可继续做共享扩展和拍照识物。公开内容积累到有足够的互动后,再比较按类别推荐和协同过滤的效果。
[需求与验收](requirements.md) · [UI 设计](../ui/README.md)

View File

@ -5,14 +5,15 @@
| 编号 | 需求 | 验收 |
| --- | --- | --- |
| R01 | 家庭和角色 | 登录后按当前账号展示空间。新空间显示空状态。两户数据互相隔离。所有者可签发和撤销邀请、调整普通成员角色及移除成员。两人同时兑换同一邀请时只有一人加入。查看者可找物,降权或移除后用原登录凭据也只能执行当前权限允许的请求。 |
| R02 | 多层位置 | 可以建立房间、柜子、收纳盒。同名位置显示完整路径。禁止把上级移动到子节点下,有活动物品或下级的位置归档前须先处理关联。 |
| R02 | 多层位置 | 可以建立房间、柜子、收纳盒。同名位置显示完整路径。禁止把上级移动到子节点下,有活动物品或下级的位置归档前须先处理关联。前三级位置有层级文字和对应的图标组,第四级起采用相同的内层样式。 |
| R03 | 物品和移位 | 可以新增、修改、移位和归档物品。移位后同时查到当前和原来的位置,用旧版本写入时提示冲突。 |
| R04 | 搜索 | 可以按名称、别名和位置找物。完整名称优先于完整别名和部分匹配,结果带完整位置路径。 |
| R05 | 物品关联 | 可以关联同一家庭里的配件、同类或常一起使用的物品。详情显示关联物品的位置。 |
| R06 | 批量草稿 | 同一句能拆成多条,处理数量、否定和不确定的位置。确认后可以查处理状态,同一次确认只写入一次。 |
| R07 | 模型状态 | 模型待配置或不可用时显示对应状态,原始输入保留,可继续手工录入。云端调用由用户选择。 |
| R08 | 收藏和评分 | 可收藏、评 1–5 星或写短评,支持修改和清除。每件物品的个人评价按用户独立保存。 |
| R09 | 物品照片 | 选择照片并在上传前剪裁,每件最多六张。列表加载缩略图,详情可看大图。查看权限与物品一致,删除图片、物品或空间后同步登记两份文件的清理。 |
| R09 | 物品和位置照片 | 选择照片并在上传前剪裁,每件最多六张。列表加载缩略图,详情可看大图。查看权限与物品一致,删除图片、物品或空间后同步登记两份文件的清理。 |
| R10 | 社区分享 | 新建物品默认私有。空间所有者确认发布后,任一已登录账号可搜分享、评论和打星。社区只展示独立填写的标题和正文。撤回或归档物品后,帖子、评分及评论退出社区。 |
## 质量要求

View File

@ -1,6 +1,6 @@
# 首版测试用例
R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前可执行范围见[后端验收清单](backend-readiness.md)。
R01–R10 对应[需求与验收](../product/requirements.md)。实现和当前可执行范围见[后端验收清单](backend-readiness.md)。
| 用例 | 需求 | 准备与操作 | 预期结果 |
| --- | --- | --- | --- |
@ -37,6 +37,9 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前
| TC-31 分级选位置 | R02 | 建两个带同名收纳盒的分支,其中一个有三级。从录音草稿、添加物品和移位分别打开位置选择,逐级找一次,再用完整路径搜索。 | 叶子和上级节点都能选。搜索显示完整路径,选好后返回原表单,取消时保留原选择。 |
| TC-32 编辑位置与物品图标 | R02 | 为房间和子位置选择图标,再编辑子位置名称。新建物品并选择另一套物品图标。 | 位置层级保持正确,列表和选择页显示最新图标。无封面照片的物品显示物品图标。 |
| TC-33 购入单价与新建照片 | R09 | 添加物品,输入 39.99 元并选相册照片裁剪。模拟上传中断后重试。随后清空购入单价。 | 价格按分精确保存。照片可单独重试,只保留一件物品和一张照片,详情可读取原图和缩略图。清空后详情收起价格项。 |
| TC-34 位置照片与清理 | R09 | 进入房间和子位置,分别拍照和选相册图,裁剪后上传。查看原图和缩略图,删除首图、归档空位置,再删除整个空间。 | 图标保留,缩略图随首图更新。查看者可看,编辑者可上传。删除相应记录后,两份对象都从桶中清理。 |
| TC-34 位置照片与清理 | R09 | 进入房间和子位置,分别拍照和选相册图,裁剪后上传。查看原图和缩略图,删除首图、归档空位置,再删除整个空间。 | 新照片出现在详情照片区。查看者可看,编辑者可上传。删除相应记录后,两份对象都从桶中清理。 |
| TC-35 位置层级与个人图标 | R02、R09 | 建空间下五级位置。两个账号为同一个位置分别选择照片和预设图标。随后删除被选中的照片。 | 前三级与内层分组清楚。两人分别看到自己的设置。照片删除后,使用该照片的账号恢复空间默认,另一账号的图标保留。 |
| TC-36 社区发布与搜索 | R10 | 新建物品后用另一账号搜索。所有者填写公开标题和描述后发布,分别搜索公开标题和私人位置名。 | 新建物品私有。发布后其他已登录账号可读,完整标题优先。家里的位置、物品记录和照片不随分享公开。 |
| TC-37 社区互动与撤回 | R10 | 连续修改评分、发表和删除自己的评论。撤回分享,再重新发布并归档源物品。 | 同一账号在同一个帖子只计一次评分。撤回后原地址失效,重新发布没有旧互动,物品归档后新地址失效。 |
[测试与演示计划](plan.md)