diff --git a/README.md b/README.md index 6ded73e..b3711be 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # 见物 · Item Atlas +> 于寻常处,见生活。 + 见物是一个家庭物品台账。它记录东西放在哪、搬动过几次,以及有哪些配件和关联物品。平时也可以顺手给自己喜欢、用得顺手的东西评个分。 ## 工程目录 diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index 0a0b440..91f050c 100644 --- a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj +++ b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj @@ -117,7 +117,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 17; + CURRENT_PROJECT_VERSION = 18; 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 = 17; + CURRENT_PROJECT_VERSION = 18; GENERATE_INFOPLIST_FILE = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; diff --git a/apps/ios/ItemAtlas/CommunityView.swift b/apps/ios/ItemAtlas/CommunityView.swift index 8c2a836..e0add81 100644 --- a/apps/ios/ItemAtlas/CommunityView.swift +++ b/apps/ios/ItemAtlas/CommunityView.swift @@ -5,6 +5,8 @@ private struct CommunityPost: Decodable, Identifiable { let title: String let body: String let author: String + let authorId: UUID? + let authorAvatar: ProfileAvatar? let publishedAt: String let average: Double? let votes: Int @@ -32,6 +34,8 @@ private struct CommunityComment: Decodable, Identifiable { let id: UUID let body: String let author: String + let authorId: UUID? + let authorAvatar: ProfileAvatar? let mine: Bool let createdAt: String } @@ -42,6 +46,38 @@ private struct CommentResponse: Decodable { let next: Cursor? } +private struct PublicCommunityProfile: Decodable { + let name: String + let avatar: ProfileAvatar + let publishedItems: Int64 + + static func path(_ id: UUID) -> String { "/api/community/people/\(id)" } +} + +private struct PublicAuthorLink: View { + let account: AtlasAccount + let name: String + let id: UUID? + let avatar: ProfileAvatar? + + var body: some View { + if let id { + NavigationLink { + CommunityFeedView(account: account, publicAuthor: id) + } label: { + HStack(spacing: 6) { + AvatarBadge(avatar: avatar ?? .person, size: 23) + Text(name).lineLimit(1) + } + } + .buttonStyle(.borderless) + .accessibilityLabel("查看" + name + "的主页") + } else { + Text(name).lineLimit(1) + } + } +} + private struct CommunityAPI { let account: AtlasAccount static let posts = "/api/community/posts" @@ -53,10 +89,11 @@ private struct CommunityAPI { return try JSONDecoder().decode(T.self, from: await account.request(url.string ?? path, timeout: 12)) } - static func feedPath(mine: Bool, term: String = "", after cursor: FeedCursor? = nil) -> String { + static func feedPath(mine: Bool, author: UUID? = nil, term: String = "", after cursor: FeedCursor? = nil) -> String { var url = URLComponents() url.path = posts url.queryItems = [.init(name: "q", value: term), .init(name: "mine", value: String(mine))] + if let author { url.queryItems?.append(.init(name: "authorId", value: author.uuidString)) } if let cursor { url.queryItems?.append(contentsOf: [.init(name: "rank", value: String(cursor.rank)), .init(name: "time", value: cursor.time), @@ -75,6 +112,7 @@ struct CommunityFeedView: View { let account: AtlasAccount var source: InventoryStore? = nil var mine = false + let publicAuthor: UUID? @State private var query = "" @State private var posts: [CommunityPost] @State private var next: FeedCursor? @@ -86,11 +124,16 @@ struct CommunityFeedView: View { @State private var showingChooser = false @State private var revision = 0 - init(account: AtlasAccount, source: InventoryStore? = nil, mine: Bool = false) { + @State private var publicProfile: PublicCommunityProfile? + @State private var profileError: String? + + init(account: AtlasAccount, source: InventoryStore? = nil, mine: Bool = false, publicAuthor: UUID? = nil) { self.account = account self.source = source self.mine = mine - let preview: FeedResponse? = account.cached(CommunityAPI.feedPath(mine: mine)) + self.publicAuthor = publicAuthor + _publicProfile = State(initialValue: publicAuthor.flatMap { account.cached(PublicCommunityProfile.path($0)) }) + let preview: FeedResponse? = account.cached(CommunityAPI.feedPath(mine: mine, author: publicAuthor)) _posts = State(initialValue: preview?.posts ?? []) _next = State(initialValue: preview?.next) _displayedTerm = State(initialValue: preview == nil ? nil : "") @@ -104,30 +147,38 @@ struct CommunityFeedView: View { var body: some View { List { + if publicAuthor != nil { profileHeader } if displayedTerm != term && error == nil { ProgressView("正在加载分享") } else if posts.isEmpty && error == nil { ContentUnavailableView(term.isEmpty ? "还没有分享" : "没找到相关分享", systemImage: "bubble.left.and.bubble.right", - description: Text(mine ? "你公开的物品会显示在这里。" : "可以搜索公开物品,或发布自己的使用感受。")) + description: Text(emptyDescription)) } ForEach(displayedTerm == term ? 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") + VStack(alignment: .leading, spacing: 10) { + NavigationLink { + CommunityDetailView(account: account, postID: post.id) + } label: { + VStack(alignment: .leading, spacing: 5) { + Text(post.title).font(.headline).foregroundStyle(.primary) + Text(post.body).font(.subheadline).foregroundStyle(.secondary).lineLimit(3) } - .font(.caption).foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) } - .padding(.vertical, 5) + .buttonStyle(.plain) + HStack(spacing: 10) { + if publicAuthor == nil { + PublicAuthorLink(account: account, name: post.author, id: post.authorId, avatar: post.authorAvatar) + } + 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 { @@ -139,9 +190,9 @@ struct CommunityFeedView: View { .disabled(moreLoading || updating) } } - .navigationTitle(mine ? "我公开的物品" : "社区") + .navigationTitle(publicAuthor != nil ? "社区主页" : (mine ? "我公开的物品" : "社区")) .navigationBarTitleDisplayMode(.inline) - .searchable(text: $query, prompt: "搜公开物品和分享") + .searchable(text: $query, prompt: publicAuthor == nil ? "搜公开物品和分享" : "搜此人的公开物品") .toolbar { if let source, source.space.role == "OWNER" && !mine { ToolbarItem(placement: .topBarTrailing) { @@ -153,7 +204,52 @@ struct CommunityFeedView: View { if let source { CommunityItemChooser(store: source) { revision += 1 } } } .task(id: "\(revision):\(source?.revision ?? 0):\(term)") { await load() } - .refreshable { await load(refresh: true) } + .task(id: publicAuthor) { await loadProfile() } + .refreshable { + async let header: Void = loadProfile(refresh: true) + await load(refresh: true) + await header + } + } + + private var emptyDescription: String { + if mine { return "你公开的物品会显示在这里。" } + if publicAuthor != nil { return "这个主页会显示对方的公开分享。" } + return "可以搜索公开物品,或发布自己的使用感受。" + } + + private var profileHeader: some View { + Section { + if let publicProfile { + HStack(spacing: 12) { + AvatarBadge(avatar: publicProfile.avatar, size: 50) + VStack(alignment: .leading, spacing: 4) { + Text(publicProfile.name).font(.headline) + Text("\(publicProfile.publishedItems) 件公开物品") + .font(.subheadline).foregroundStyle(.secondary) + } + } + .padding(.vertical, 6) + .accessibilityElement(children: .combine) + } else if let profileError { + Text(profileError).font(.footnote).foregroundStyle(.secondary) + Button("重载社区资料") { Task { await loadProfile(refresh: true) } } + } else { + ProgressView("正在加载社区资料") + } + } + } + + private func loadProfile(refresh: Bool = false) async { + guard let publicAuthor else { return } + do { + publicProfile = try await account.read(PublicCommunityProfile.path(publicAuthor), refresh: refresh) + profileError = nil + } catch is CancellationError { + } catch where !Task.isCancelled { + if (error as? AtlasError)?.resourceUnavailable == true { publicProfile = nil } + profileError = error.localizedDescription + } catch {} } private func load(append: Bool = false, refresh: Bool = false) async { @@ -166,7 +262,7 @@ struct CommunityFeedView: View { updating = !append moreLoading = append let firstPage = !append && requested.isEmpty - let path = CommunityAPI.feedPath(mine: mine, term: requested, after: cursor) + let path = CommunityAPI.feedPath(mine: mine, author: publicAuthor, term: requested, after: cursor) if firstPage, displayedTerm != requested, let preview: FeedResponse = account.cached(path) { posts = preview.posts next = preview.next @@ -211,7 +307,7 @@ struct CommunityFeedView: View { } } -private struct CommunityDetailView: View { +struct CommunityDetailView: View { let account: AtlasAccount let postID: UUID @State private var post: CommunityPost? @@ -241,27 +337,46 @@ private struct CommunityDetailView: View { Section { VStack(alignment: .leading, spacing: 10) { Text(post.title).font(.title2.bold()) - Text(post.author + " · " + String(post.publishedAt.prefix(10))) - .font(.footnote).foregroundStyle(.secondary) + HStack(spacing: 8) { + PublicAuthorLink(account: account, name: post.author, id: post.authorId, avatar: post.authorAvatar) + Text(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) + HStack(spacing: 3) { + ForEach(1...5, id: \.self) { stars in + Button { Task { await rate(stars) } } label: { + Image(systemName: stars <= (post.myRating ?? 0) ? "star.fill" : "star") + .font(.title3) + .foregroundStyle(Color.orange) + .frame(maxWidth: .infinity, minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .accessibilityLabel("评 \(stars) 星") + .accessibilityAddTraits(post.myRating == stars ? .isSelected : []) + } + } + .disabled(busy) + if post.myRating != nil { + Button("清除我的评分") { Task { await rate(nil) } }.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) + if comments.isEmpty && !busy { + Text("还没有评论").font(.subheadline).foregroundStyle(.secondary) + } ForEach(comments) { comment in VStack(alignment: .leading, spacing: 6) { - Text(comment.author).font(.subheadline.weight(.semibold)) + PublicAuthorLink(account: account, name: comment.author, id: comment.authorId, avatar: comment.authorAvatar) + .font(.subheadline.weight(.semibold)) Text(comment.body) Text(comment.createdAt.prefix(10)).font(.caption).foregroundStyle(.secondary) } @@ -446,11 +561,20 @@ struct CommunityPublicationSection: View { @State private var editing = false var body: some View { - if store.space.role == "OWNER" { + if store.space.role == "OWNER" || item.communityPostId != nil { Section("社区分享") { - Button { editing = true } label: { - LabeledContent(item.published == true ? "管理分享" : "分享到社区", - value: item.published == true ? "已公开" : "私有") + if let postId = item.communityPostId { + NavigationLink { + CommunityDetailView(account: store.account, postID: postId) + } label: { + Label("查看社区评论和评分", systemImage: "bubble.left.and.bubble.right") + } + } + if store.space.role == "OWNER" { + Button { editing = true } label: { + LabeledContent(item.published == true ? "管理分享" : "分享到社区", + value: item.published == true ? "已公开" : "私有") + } } } .sheet(isPresented: $editing) { PublicationEditor(store: store, item: item) {} } @@ -565,7 +689,7 @@ private struct PublicationEditor: View { guard draft.isValid else { return } await perform { let _: Publication = try await store.send(path, method: "PUT", draft) - store.changed() + store.changed(inventorySummaryChanged: true) onChange() dismiss() } diff --git a/apps/ios/ItemAtlas/Editors.swift b/apps/ios/ItemAtlas/Editors.swift index cd187e0..d44e0f6 100644 --- a/apps/ios/ItemAtlas/Editors.swift +++ b/apps/ios/ItemAtlas/Editors.swift @@ -55,7 +55,7 @@ struct ItemEditor: View { TextField("购入单价(元,可选)", text: $price).keyboardType(.decimalPad) .focused($focus, equals: .price) if !validPrice { - Text("请输入 0 到 99,999,999.99 元,最多两位小数。") + Text("单价允许 0 到 999 亿元,最多两位小数。") .font(.footnote).foregroundStyle(.secondary) } TextField("备注", text: $notes, axis: .vertical).focused($focus, equals: .notes) diff --git a/apps/ios/ItemAtlas/IntakeView.swift b/apps/ios/ItemAtlas/IntakeView.swift index 8a04d8d..338503e 100644 --- a/apps/ios/ItemAtlas/IntakeView.swift +++ b/apps/ios/ItemAtlas/IntakeView.swift @@ -386,7 +386,7 @@ struct IntakeView: View { let status: Operation = try await store.get(store.root + "/operations/\(current.id)") operation = status if status.status == "COMPLETED" { - store.changed() + store.changed(inventorySummaryChanged: true) return } if ["FAILED", "REJECTED", "NEEDS_REVIEW"].contains(status.status) { return } diff --git a/apps/ios/ItemAtlas/InventoryAppearance.swift b/apps/ios/ItemAtlas/InventoryAppearance.swift index 670c031..36c0028 100644 --- a/apps/ios/ItemAtlas/InventoryAppearance.swift +++ b/apps/ios/ItemAtlas/InventoryAppearance.swift @@ -185,6 +185,13 @@ struct SymbolPicker: View { } enum PurchasePrice { + static let maximumCents: Int64 = 9_990_000_000_000 + + static func totalDisplay(cents: String) -> String { + guard let amount = Decimal(string: cents, locale: Locale(identifier: "en_US_POSIX")) else { return "—" } + return (amount / 100).formatted(.currency(code: "CNY")) + } + static func cents(from text: String, decimalSeparator: String = Locale.current.decimalSeparator ?? ".") -> Int64? { let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines) .folding(options: .widthInsensitive, locale: .current) @@ -193,13 +200,14 @@ enum PurchasePrice { guard let whole = parts.first, parts.count <= 2 else { return nil } let fraction = parts.count == 2 ? parts[1] : "" guard !whole.isEmpty || !fraction.isEmpty, - whole.count <= 8, fraction.count <= 2, + whole.count <= 11, fraction.count <= 2, whole.utf8.allSatisfy({ (48...57).contains($0) }), fraction.utf8.allSatisfy({ (48...57).contains($0) }) else { return nil } let yuan = Int64(whole) ?? 0 let minor = (Int64(fraction) ?? 0) * (fraction.count == 1 ? 10 : 1) - return yuan * 100 + minor + let amount = yuan * 100 + minor + return amount <= maximumCents ? amount : nil } static func input(_ cents: Int64) -> String { diff --git a/apps/ios/ItemAtlas/InventoryStore.swift b/apps/ios/ItemAtlas/InventoryStore.swift index 845770a..781c156 100644 --- a/apps/ios/ItemAtlas/InventoryStore.swift +++ b/apps/ios/ItemAtlas/InventoryStore.swift @@ -35,10 +35,21 @@ struct Item: Decodable, Identifiable { var icon: String? = nil var priceCents: Int64? = nil var published: Bool? = nil + var communityPostId: UUID? = nil var locationLabel: String { locationPath.isEmpty ? "未设置位置" : locationPath } } +struct AccountInventorySummary: Decodable { + static let path = "/api/me/inventory-summary" + let activeItems: Int64 + let activeUnits: Int64 + let pricedItems: Int64 + let archivedItems: Int64 + let publishedItems: Int64 + let totalValueCents: String +} + struct ItemInput: Encodable { let name: String let quantity: Int @@ -173,14 +184,14 @@ final class InventoryStore { idempotencyKey: UUID? = nil) async throws -> R { let response = try await account.request(path, method: method, data: JSONEncoder().encode(value), idempotencyKey: idempotencyKey) - if path.hasSuffix("/publication") { account.invalidateReads("/api/community/posts") } + if path.hasSuffix("/publication") { account.invalidateReads("/api/community/") } return try JSONDecoder().decode(R.self, from: response) } func save(_ item: ItemInput, id: UUID? = nil, idempotencyKey: UUID? = nil) async throws -> Item { let created: Item = try await send(itemPath(id), method: id == nil ? "POST" : "PUT", item, idempotencyKey: idempotencyKey) - changed() + changed(inventorySummaryChanged: true) return created } @@ -241,7 +252,7 @@ final class InventoryStore { return try await account.request(path) } - func delete(_ path: String, affectsCommunity: Bool = false) async throws { + func delete(_ path: String, affectsCommunity: Bool = false, changesItemCount: Bool = false) async throws { _ = try await account.request(path, method: "DELETE") let resource = path.components(separatedBy: "?")[0] account.invalidateReads(resource, discard: true) @@ -249,12 +260,13 @@ final class InventoryStore { account.invalidateReads("/api/households", discard: true) } if resource == root || resource.hasSuffix("/publication") || affectsCommunity { - account.invalidateReads("/api/community/posts", discard: true) + account.invalidateReads("/api/community/", discard: true) } - changed() + changed(inventorySummaryChanged: changesItemCount || resource == root || resource.hasSuffix("/publication")) } - func changed() { + func changed(inventorySummaryChanged: Bool = false) { + if inventorySummaryChanged { account.invalidateReads(AccountInventorySummary.path) } account.invalidateReads(root + "/") revision += 1 } diff --git a/apps/ios/ItemAtlas/InventoryView.swift b/apps/ios/ItemAtlas/InventoryView.swift index 759828e..2c1d39d 100644 --- a/apps/ios/ItemAtlas/InventoryView.swift +++ b/apps/ios/ItemAtlas/InventoryView.swift @@ -381,7 +381,7 @@ struct ItemDetailView: View { busy = true defer { busy = false } do { - try await store.delete(store.itemPath(item.id) + "?version=\(item.version)", affectsCommunity: item.published == true) + try await store.delete(store.itemPath(item.id) + "?version=\(item.version)", affectsCommunity: item.published == true, changesItemCount: true) dismiss() } catch { self.error = error.localizedDescription } @@ -394,6 +394,14 @@ private struct PreferenceEditor: View { let saved: (ItemDetail) -> Void @State private var error: String? @State private var busy = false + @State private var note: String + + init(store: InventoryStore, detail: ItemDetail, saved: @escaping (ItemDetail) -> Void) { + self.store = store + self.detail = detail + self.saved = saved + _note = State(initialValue: detail.preference.note) + } var body: some View { Toggle("收藏", isOn: Binding(get: { detail.preference.favorite }, set: { value in @@ -409,10 +417,26 @@ private struct PreferenceEditor: View { Text("未评分").tag(0) ForEach(1...5, id: \.self) { Text("\($0) 分").tag($0) } }.disabled(busy) + TextField("写下自己的使用感受", text: $note, axis: .vertical) + .lineLimit(2...4) + .disabled(busy) + .onChange(of: detail.preference.note) { _, updated in note = updated } + if note.trimmingCharacters(in: .whitespacesAndNewlines) != detail.preference.note { + Button("保存个人短评") { + var preference = detail.preference + preference.note = note + Task { await save(preference) } + } + .disabled(busy || note.utf16.count > 500) + } + if note.utf16.count > 500 { + Text("短评最多 500 字。").font(.footnote).foregroundStyle(.secondary) + } if let error { Text(error).foregroundStyle(.red) } } private func save(_ preference: ItemDetail.Preference) async { + guard !busy else { return } busy = true defer { busy = false } do { diff --git a/apps/ios/ItemAtlas/ItemAtlasApp.swift b/apps/ios/ItemAtlas/ItemAtlasApp.swift index 37c53bc..3c93f9d 100644 --- a/apps/ios/ItemAtlas/ItemAtlasApp.swift +++ b/apps/ios/ItemAtlas/ItemAtlasApp.swift @@ -202,6 +202,25 @@ private struct SpaceTabs: View { } var body: some View { + VStack(spacing: 0) { + tabs + .frame(maxWidth: .infinity, maxHeight: .infinity) + if !keyboardVisible { navigationBar } + } + .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in + keyboardVisible = true + } + .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in + keyboardVisible = false + } + .sheet(item: $intake) { request in + NavigationStack { IntakeView(store: store, initialLocation: request.location) } + .presentationDragIndicator(.visible) + } + .task { await store.warm() } + } + + private var tabs: some View { TabView(selection: $page) { InventoryView(store: store, switcher: switcher, onIntake: { openIntake() }) .toolbar(.hidden, for: .tabBar) @@ -225,20 +244,6 @@ private struct SpaceTabs: View { .tag(Page.profile) } .toolbar(.hidden, for: .tabBar) - .safeAreaInset(edge: .bottom, spacing: 0) { - if !keyboardVisible { navigationBar } - } - .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in - keyboardVisible = true - } - .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in - keyboardVisible = false - } - .sheet(item: $intake) { request in - NavigationStack { IntakeView(store: store, initialLocation: request.location) } - .presentationDragIndicator(.visible) - } - .task { await store.warm() } } private var navigationBar: some View { @@ -248,9 +253,9 @@ private struct SpaceTabs: View { if store.canWrite { Button { openIntake() } label: { Image(systemName: "plus") - .font(.system(size: 24, weight: .semibold)) + .font(.system(size: 27, weight: .semibold)) .foregroundStyle(.white) - .frame(width: 52, height: 52) + .frame(width: 60, height: 60) .background(Color.atlasBlue, in: Circle()) } .buttonStyle(.plain) @@ -272,7 +277,8 @@ private struct SpaceTabs: View { private func tabButton(_ destination: Page) -> some View { Button { page = destination } label: { VStack(spacing: 4) { - Image(systemName: destination.symbol).font(.system(size: 19, weight: .medium)) + tabGlyph(destination, selected: page == destination) + .frame(width: 28, height: 26) .accessibilityHidden(true) Text(destination.title).font(.caption2.weight(page == destination ? .semibold : .medium)) } @@ -284,12 +290,41 @@ private struct SpaceTabs: View { .accessibilityAddTraits(page == destination ? .isSelected : []) } + @ViewBuilder + private func tabGlyph(_ destination: Page, selected: Bool) -> some View { + if destination == .inventory { + SearchTabGlyph(selected: selected).frame(width: 24, height: 24) + } else { + Image(systemName: selected ? destination.symbol + ".fill" : destination.symbol) + .font(.system(size: destination == .profile ? 24 : 21, weight: .medium)) + } + } + private func openIntake(_ location: Place? = nil) { guard store.canWrite else { return } intake = IntakeRequest(location: location) } } +private struct SearchTabGlyph: View { + let selected: Bool + + var body: some View { + Canvas { context, size in + let scale = size.width / 24 + let lens = Path(ellipseIn: CGRect(x: 2.5 * scale, y: 2.5 * scale, width: 14 * scale, height: 14 * scale)) + let stroke = StrokeStyle(lineWidth: 2 * scale, lineCap: .round) + let color = GraphicsContext.Shading.foreground + var handle = Path() + handle.move(to: CGPoint(x: 14.8 * scale, y: 14.8 * scale)) + handle.addLine(to: CGPoint(x: 21 * scale, y: 21 * scale)) + if selected { context.fill(lens, with: color) } + context.stroke(lens, with: color, style: stroke) + context.stroke(handle, with: color, style: stroke) + } + } +} + private struct SpaceEditor: View { let account: AtlasAccount let joining: Bool diff --git a/apps/ios/ItemAtlas/MyView.swift b/apps/ios/ItemAtlas/MyView.swift index 2d1fecf..ac29e37 100644 --- a/apps/ios/ItemAtlas/MyView.swift +++ b/apps/ios/ItemAtlas/MyView.swift @@ -15,7 +15,7 @@ private struct AccountProfile: Decodable { } } -private enum ProfileAvatar: String, CaseIterable, Codable, Identifiable { +enum ProfileAvatar: String, CaseIterable, Codable, Identifiable { case person = "PERSON" case cat = "CAT" case leaf = "LEAF" @@ -59,7 +59,7 @@ private enum ProfileAvatar: String, CaseIterable, Codable, Identifiable { } } -private struct AvatarBadge: View { +struct AvatarBadge: View { let avatar: ProfileAvatar let size: CGFloat @@ -81,6 +81,8 @@ struct MyView: View { @State private var profile: AccountProfile? @State private var profileError: String? + @State private var inventory: AccountInventorySummary? + @State private var inventoryError: String? @State private var showingProfile = false @State private var confirmingSignOut = false @@ -89,6 +91,7 @@ struct MyView: View { self.store = store self.openSpaces = openSpaces _profile = State(initialValue: account.cached("/api/me/profile")) + _inventory = State(initialValue: account.cached(AccountInventorySummary.path)) } var body: some View { @@ -125,6 +128,8 @@ struct MyView: View { } } + overview + Section("空间") { if let store { NavigationLink { @@ -169,7 +174,12 @@ struct MyView: View { .navigationTitle("我的") .navigationBarTitleDisplayMode(.inline) .task { await loadProfile() } - .refreshable { await loadProfile(refresh: true) } + .task(id: store?.revision ?? 0) { await loadInventory() } + .refreshable { + async let profile: Void = loadProfile(refresh: true) + await loadInventory(refresh: true) + await profile + } .sheet(isPresented: $showingProfile) { if let profile { ProfileEditor(account: account, profile: profile) { self.profile = $0 } @@ -180,6 +190,48 @@ struct MyView: View { } } + private var overview: some View { + Section { + if let inventory { + VStack(alignment: .leading, spacing: 4) { + Text("购入总额").font(.subheadline).foregroundStyle(.secondary) + if inventory.pricedItems > 0 { + Text(PurchasePrice.totalDisplay(cents: inventory.totalValueCents)) + .font(.title2.weight(.semibold)) + .monospacedDigit() + .minimumScaleFactor(0.6) + } else { + Text("暂无已填写的价格").font(.headline) + } + } + .accessibilityElement(children: .combine) + LabeledContent("在册物品", value: "\(inventory.activeUnits) 件 · \(inventory.activeItems) 条记录") + LabeledContent("已公开", value: "\(inventory.publishedItems) 件") + LabeledContent("已删除", value: "\(inventory.archivedItems) 条") + } else if inventoryError == nil { + ProgressView("正在加载物品概览") + } + if let inventoryError { + Text(inventoryError).font(.footnote).foregroundStyle(.secondary) + Button("重新加载概览") { Task { await loadInventory(refresh: true) } } + } + } header: { + Text("物品概览") + } footer: { + Text("统计你拥有的空间。购入总额按已填写单价的在册物品计算。") + } + } + + private func loadInventory(refresh: Bool = false) async { + do { + inventory = try await account.read(AccountInventorySummary.path, refresh: refresh) + inventoryError = nil + } catch is CancellationError { + } catch where !Task.isCancelled { + inventoryError = "暂时无法加载物品概览。" + } catch {} + } + private func loadProfile(refresh: Bool = false) async { do { profile = try await account.read("/api/me/profile", refresh: refresh) @@ -268,6 +320,7 @@ private struct ProfileEditor: View { do { let data = try await account.request("/api/me/profile", method: "PUT", data: JSONEncoder().encode(update), timeout: 12) account.invalidateReads("/api/me/profile", discard: true) + account.invalidateReads("/api/community/") saved(try JSONDecoder().decode(AccountProfile.self, from: data)) dismiss() } catch { self.error = error.localizedDescription } diff --git a/apps/ios/ItemAtlas/WelcomeView.swift b/apps/ios/ItemAtlas/WelcomeView.swift index 85ed739..2202cb3 100644 --- a/apps/ios/ItemAtlas/WelcomeView.swift +++ b/apps/ios/ItemAtlas/WelcomeView.swift @@ -31,8 +31,14 @@ struct WelcomeView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: 18) { - EntryBrand(prominent: true) - .frame(maxWidth: .infinity, alignment: .center) + VStack(spacing: 9) { + EntryBrand(prominent: true) + Text("于寻常处,见生活。") + .font(.system(.title3, design: .serif).weight(.medium)) + .foregroundStyle(.primary.opacity(0.78)) + .multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity) scene featureExamples } diff --git a/backend/gateway/src/main/resources/application.yml b/backend/gateway/src/main/resources/application.yml index cd78f63..22e6675 100644 --- a/backend/gateway/src/main/resources/application.yml +++ b/backend/gateway/src/main/resources/application.yml @@ -36,13 +36,13 @@ spring: order: -1 uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081} predicates: - - Path=/api/community/posts,/api/community/posts/** + - Path=/api/community/posts,/api/community/posts/**,/api/community/people/* filters: - RequestSize=16KB - id: inventory uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081} predicates: - - Path=/api/me/profile,/api/households,/api/households/**,/api/admin/** + - Path=/api/me/profile,/api/me/inventory-summary,/api/households,/api/households/**,/api/admin/** filters: - RequestSize=64KB server: diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileController.java index babcece..c9d89b5 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileController.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileController.java @@ -12,25 +12,30 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController -@RequestMapping("/api/me/profile") +@RequestMapping("/api/me") class AccountProfileController { private final AccountProfileService service; AccountProfileController(AccountProfileService service) { this.service = service; } - @GetMapping + @GetMapping("/profile") ResponseEntity get(Authentication user) { return ResponseEntity.ok().cacheControl(CacheControl.noStore()) .body(service.get(user.getName(), loginName(user))); } - @PutMapping + @PutMapping("/profile") ResponseEntity save(Authentication user, @Valid @RequestBody AccountProfileService.Update update) { return ResponseEntity.ok().cacheControl(CacheControl.noStore()) .body(service.save(user.getName(), loginName(user), update)); } + @GetMapping("/inventory-summary") + ResponseEntity summary(Authentication user) { + return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(service.inventorySummary(user.getName())); + } + private static String loginName(Authentication user) { if (user instanceof JwtAuthenticationToken token) { return token.getToken().getClaimAsString("preferred_username"); diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileService.java index 247a6db..ea3b630 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileService.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/AccountProfileService.java @@ -30,6 +30,17 @@ class AccountProfileService { .single(); } + InventorySummary inventorySummary(String subject) { + return db.sql(""" + SELECT active_items,active_units,priced_items,archived_items,published_items,total_value_cents + FROM account_inventory_stats WHERE subject=:subject + """).param("subject", subject) + .query((rs, row) -> new InventorySummary(rs.getLong("active_items"), rs.getLong("active_units"), + rs.getLong("priced_items"), rs.getLong("archived_items"), rs.getLong("published_items"), + rs.getBigDecimal("total_value_cents").toPlainString())) + .optional().orElse(new InventorySummary(0, 0, 0, 0, 0, "0")); + } + @Transactional Profile save(String subject, String loginName, Update update) { db.sql(""" @@ -45,6 +56,9 @@ class AccountProfileService { enum Avatar { PERSON, CAT, LEAF, MOON, MOUNTAIN, SPARK } + record InventorySummary(long activeItems, long activeUnits, long pricedItems, long archivedItems, + long publishedItems, String totalValueCents) {} + record Profile(String username, String nickname, String signature, Avatar avatar) {} record Update( diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityController.java index cf90be9..15fb52f 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityController.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityController.java @@ -25,8 +25,14 @@ class CommunityController { ResponseEntity 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)); + @RequestParam(required = false) Instant time, @RequestParam(required = false) UUID before, + @RequestParam(required = false) UUID authorId) { + return fresh(service.feed(user.getName(), q, mine, authorId, limit, rank, time, before)); + } + + @GetMapping("/api/community/people/{id}") + ResponseEntity profile(@PathVariable UUID id) { + return fresh(service.publicProfile(id)); } @GetMapping(COMMUNITY + "/{id}") diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityService.java index af20309..3188b04 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityService.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/CommunityService.java @@ -22,11 +22,12 @@ import org.springframework.web.server.ResponseStatusException; 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, + COALESCE(NULLIF(profile.nickname,''),'见物用户') AS author,identity.public_id AS author_id, + COALESCE(profile.avatar,'PERSON') AS author_avatar,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 + JOIN community_identity identity ON identity.subject=p.author_subject LEFT JOIN account_profile profile ON profile.subject=p.author_subject CROSS JOIN LATERAL ( SELECT avg(stars) AS average,count(*) AS votes, @@ -34,14 +35,23 @@ class CommunityService { FROM community_rating WHERE post_id=p.id ) r """; + private static final String COMMENT_FIELDS = """ + SELECT c.id,c.body,c.created_at,c.subject=:viewer AS mine, + COALESCE(NULLIF(profile.nickname,''),'见物用户') AS author,identity.public_id AS author_id, + COALESCE(profile.avatar,'PERSON') AS author_avatar + FROM community_comment c + JOIN community_identity identity ON identity.subject=c.subject + LEFT JOIN account_profile profile ON profile.subject=c.subject + WHERE c.post_id=:post + """; private static final RowMapper 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.getObject("author_id", UUID.class), rs.getString("author_avatar"), 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 = (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()); + rs.getObject("author_id", UUID.class), rs.getString("author_avatar"), rs.getBoolean("mine"), rs.getObject("created_at", OffsetDateTime.class).toInstant()); private final JdbcClient db; private final HouseholdAccess access; @@ -50,7 +60,7 @@ class CommunityService { this.access = access; } - Feed feed(String viewer, String query, boolean mine, int limit, Integer rank, Instant time, UUID before) { + Feed feed(String viewer, String query, boolean mine, UUID authorId, int limit, Integer rank, Instant time, UUID before) { if ((time == null) != (before == null) || (time == null) != (rank == null)) { throw new ResponseStatusException(BAD_REQUEST, "分页参数不完整"); } @@ -61,16 +71,19 @@ class CommunityService { 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 author = authorId == null ? "" : + " AND author_subject=(SELECT subject FROM community_identity WHERE public_id=:authorId)"; 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 + FROM community_post WHERE (NOT :mine OR author_subject=:viewer)%s%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") + """.formatted(score, author, 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 (authorId != null) { sql.param("authorId", authorId); } if (before != null) { sql.param("rank", rank).param("time", OffsetDateTime.ofInstant(time, ZoneOffset.UTC)).param("before", before); } @@ -84,6 +97,20 @@ class CommunityService { return new Feed(rows.stream().limit(limit).map(ScoredPost::post).toList(), next); } + PublicProfile publicProfile(UUID id) { + return db.sql(""" + SELECT identity.public_id,COALESCE(NULLIF(p.nickname,''),'见物用户') AS name, + COALESCE(p.avatar,'PERSON') AS avatar,COALESCE(stats.published_items,0) AS published_items + FROM community_identity identity + LEFT JOIN account_profile p ON p.subject=identity.subject + LEFT JOIN account_inventory_stats stats ON stats.subject=identity.subject + WHERE identity.public_id=:id + """).param("id", id) + .query((rs, row) -> new PublicProfile(rs.getObject("public_id", UUID.class), rs.getString("name"), + rs.getString("avatar"), rs.getLong("published_items"))) + .optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "社区资料不存在")); + } + Post post(UUID id, String viewer) { return db.sql(""" WITH page AS ( @@ -130,12 +157,7 @@ class CommunityService { } 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") + var query = db.sql(COMMENT_FIELDS + 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(); @@ -152,12 +174,13 @@ class CommunityService { 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(""" + UUID id = UUID.randomUUID(); + 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(); + """).param("post", post).param("id", id).param("viewer", actor) + .param("body", input.body().strip()).update(); + return db.sql(COMMENT_FIELDS + " AND c.id=:id") + .param("post", post).param("id", id).param("viewer", actor).query(COMMENT).single(); } @Transactional @@ -201,12 +224,14 @@ class CommunityService { 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, + record PublicProfile(UUID id, String name, String avatar, long publishedItems) {} + record Post(UUID id, String title, String body, String author, UUID authorId, String authorAvatar, + 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 posts, Cursor next) {} record CommentInput(@NotBlank @Size(max = 500) String body) {} - record Comment(UUID id, String body, String author, boolean mine, Instant createdAt) {} + record Comment(UUID id, String body, String author, UUID authorId, String authorAvatar, boolean mine, Instant createdAt) {} record CommentCursor(Instant time, UUID id) {} record Comments(List comments, CommentCursor next) {} record Rating(@Min(1) @Max(5) Integer stars) {} diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java index f4261a9..2ce7798 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java @@ -28,10 +28,10 @@ final class InventoryDtos { 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 Appearance(@NotNull ItemIcon icon, @Min(0) @Max(9_990_000_000_000L) Long priceCents) {} record Item(UUID id, String name, int quantity, String notes, UUID locationId, String locationPath, int version, List aliases, UUID coverPhotoId, - ItemIcon icon, Long priceCents, boolean published) {} + ItemIcon icon, Long priceCents, boolean published, UUID communityPostId) {} record ItemInput(@NotBlank @Size(max = 150) String name, @Min(1) @Max(9999) int quantity, @Size(max = 1500) String notes, UUID locationId, diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java index 3b3a0e6..6bb2d47 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java @@ -28,7 +28,7 @@ class InventoryService { 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.getBoolean("published")); + rs.getObject("price_cents", Long.class), rs.getBoolean("published"), rs.getObject("post_id", UUID.class)); private static final String SELECT_LOCATIONS = """ SELECT p.*,l.icon,cardinality(p.ancestors) AS depth,thumb.photo_id AS icon_photo_id, COALESCE(thumb.icon,l.icon) AS display_icon, @@ -61,13 +61,14 @@ class InventoryService { """; private static final String SELECT_ITEMS = """ SELECT i.*, COALESCE(p.path, '') AS path, - EXISTS (SELECT FROM community_post post WHERE (post.household_id,post.item_id)=(i.household_id,i.id)) AS published, + (post.id IS NOT NULL) AS published, post.id AS post_id, 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) ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id FROM item i LEFT JOIN paths p ON p.household_id=i.household_id AND p.id=i.location_id + LEFT JOIN community_post post ON (post.household_id,post.item_id)=(i.household_id,i.id) %s WHERE i.household_id=:household AND i.archived_at IS NULL """; diff --git a/backend/inventory-service/src/main/resources/db/migration/V14__account_inventory_stats.sql b/backend/inventory-service/src/main/resources/db/migration/V14__account_inventory_stats.sql new file mode 100644 index 0000000..b50671a --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V14__account_inventory_stats.sql @@ -0,0 +1,101 @@ +ALTER TABLE item DROP CONSTRAINT item_price_cents_check; +ALTER TABLE item ADD CONSTRAINT item_price_cents_check CHECK (price_cents BETWEEN 0 AND 9990000000000); + +LOCK TABLE community_post IN SHARE ROW EXCLUSIVE MODE; + +CREATE UNIQUE INDEX household_one_owner ON household_member(household_id) WHERE role='OWNER'; + +CREATE TABLE account_inventory_stats ( + subject text PRIMARY KEY, + active_items bigint NOT NULL DEFAULT 0 CHECK (active_items >= 0), + active_units bigint NOT NULL DEFAULT 0 CHECK (active_units >= 0), + priced_items bigint NOT NULL DEFAULT 0 CHECK (priced_items >= 0 AND priced_items <= active_items), + archived_items bigint NOT NULL DEFAULT 0 CHECK (archived_items >= 0), + published_items bigint NOT NULL DEFAULT 0 CHECK (published_items >= 0), + total_value_cents numeric(38,0) NOT NULL DEFAULT 0 CHECK (total_value_cents >= 0) +); + +WITH inventory AS ( + SELECT m.subject, + count(*) FILTER (WHERE i.archived_at IS NULL) AS active_items, + coalesce(sum(i.quantity) FILTER (WHERE i.archived_at IS NULL), 0) AS active_units, + count(i.price_cents) FILTER (WHERE i.archived_at IS NULL) AS priced_items, + count(*) FILTER (WHERE i.archived_at IS NOT NULL) AS archived_items, + coalesce(sum(i.price_cents::numeric * i.quantity) FILTER (WHERE i.archived_at IS NULL), 0) AS total_value_cents + FROM item i + JOIN household_member m ON m.household_id=i.household_id AND m.role='OWNER' + GROUP BY m.subject +), published AS ( + SELECT author_subject AS subject, count(*) AS published_items FROM community_post GROUP BY author_subject +) +INSERT INTO account_inventory_stats(subject,active_items,active_units,priced_items,archived_items,published_items,total_value_cents) +SELECT subject,coalesce(active_items,0),coalesce(active_units,0),coalesce(priced_items,0), + coalesce(archived_items,0),coalesce(published_items,0),coalesce(total_value_cents,0) +FROM inventory FULL JOIN published USING(subject); + +CREATE FUNCTION maintain_account_item_stats() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + owner_subject text; + active_delta bigint := 0; + units_delta bigint := 0; + priced_delta bigint := 0; + archived_delta bigint := 0; + value_delta numeric := 0; +BEGIN + SELECT subject INTO owner_subject FROM household_member + WHERE household_id=(CASE WHEN TG_OP='DELETE' THEN OLD.household_id ELSE NEW.household_id END) AND role='OWNER'; + IF owner_subject IS NULL THEN RETURN NULL; END IF; + + IF TG_OP <> 'INSERT' THEN + IF OLD.archived_at IS NULL THEN + active_delta := -1; + units_delta := -OLD.quantity; + IF OLD.price_cents IS NOT NULL THEN + priced_delta := -1; + value_delta := -OLD.price_cents::numeric * OLD.quantity; + END IF; + ELSE + archived_delta := -1; + END IF; + END IF; + IF TG_OP <> 'DELETE' THEN + IF NEW.archived_at IS NULL THEN + active_delta := active_delta + 1; + units_delta := units_delta + NEW.quantity; + IF NEW.price_cents IS NOT NULL THEN + priced_delta := priced_delta + 1; + value_delta := value_delta + NEW.price_cents::numeric * NEW.quantity; + END IF; + ELSE + archived_delta := archived_delta + 1; + END IF; + END IF; + + IF (active_delta,units_delta,priced_delta,archived_delta,value_delta) <> (0,0,0,0,0) THEN + INSERT INTO account_inventory_stats(subject) VALUES (owner_subject) ON CONFLICT DO NOTHING; + UPDATE account_inventory_stats SET active_items=active_items+active_delta, active_units=active_units+units_delta, + priced_items=priced_items+priced_delta, archived_items=archived_items+archived_delta, + total_value_cents=total_value_cents+value_delta + WHERE subject=owner_subject; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER item_account_stats + AFTER INSERT OR DELETE OR UPDATE OF quantity,price_cents,archived_at ON item + FOR EACH ROW EXECUTE FUNCTION maintain_account_item_stats(); + +CREATE FUNCTION maintain_account_publication_count() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + publisher text := CASE WHEN TG_OP='DELETE' THEN OLD.author_subject ELSE NEW.author_subject END; + delta integer := CASE WHEN TG_OP='DELETE' THEN -1 ELSE 1 END; +BEGIN + INSERT INTO account_inventory_stats(subject) VALUES (publisher) ON CONFLICT DO NOTHING; + UPDATE account_inventory_stats SET published_items=published_items+delta WHERE subject=publisher; + RETURN NULL; +END; +$$; + +CREATE TRIGGER community_post_account_stats AFTER INSERT OR DELETE ON community_post + FOR EACH ROW EXECUTE FUNCTION maintain_account_publication_count(); diff --git a/backend/inventory-service/src/main/resources/db/migration/V15__community_public_profile.sql b/backend/inventory-service/src/main/resources/db/migration/V15__community_public_profile.sql new file mode 100644 index 0000000..6567165 --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V15__community_public_profile.sql @@ -0,0 +1,28 @@ +LOCK TABLE community_post,community_comment IN SHARE ROW EXCLUSIVE MODE; + +CREATE TABLE community_identity ( + subject text PRIMARY KEY, + public_id uuid NOT NULL UNIQUE DEFAULT gen_random_uuid() +); + +INSERT INTO community_identity(subject) +SELECT author_subject FROM community_post +UNION +SELECT subject FROM community_comment; + +CREATE FUNCTION register_community_identity() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_TABLE_NAME='community_post' THEN + INSERT INTO community_identity(subject) VALUES (NEW.author_subject) ON CONFLICT DO NOTHING; + ELSE + INSERT INTO community_identity(subject) VALUES (NEW.subject) ON CONFLICT DO NOTHING; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER community_post_register_author BEFORE INSERT ON community_post + FOR EACH ROW EXECUTE FUNCTION register_community_identity(); + +CREATE TRIGGER community_comment_register_author BEFORE INSERT ON community_comment + FOR EACH ROW EXECUTE FUNCTION register_community_identity(); diff --git a/backend/tests/ios_experience_smoke.py b/backend/tests/ios_experience_smoke.py index 1ea4e0f..6b7801b 100644 --- a/backend/tests/ios_experience_smoke.py +++ b/backend/tests/ios_experience_smoke.py @@ -9,6 +9,7 @@ from smoke import RUN, await_operation, call, ready def verify(): ready() verify_profiles() + verify_inventory_summary() space = call("POST", "/api/households", {"name": "见物体验 " + RUN}, status=201) root = "/api/households/" + space["id"] try: @@ -42,6 +43,63 @@ def verify_profiles(): print("PASS private editable profile, account display and input validation", flush=True) +def verify_inventory_summary(): + summary = "/api/me/inventory-summary" + call("GET", summary, user=None, status=401) + before = call("GET", summary) + viewer_summary = call("GET", summary, user="viewer") + roots = ["/api/households/" + call("POST", "/api/households", {"name": "物品统计 " + RUN}, status=201)["id"] + for _ in range(2)] + maximum = 9_990_000_000_000 + + def check(items, units, priced, archived, published, cents): + current = call("GET", summary) + for key, delta in zip(("activeItems", "activeUnits", "pricedItems", "archivedItems", "publishedItems"), + (items, units, priced, archived, published)): + assert current[key] == before[key] + delta, (key, current[key], before[key], delta) + assert current["totalValueCents"] == str(int(before["totalValueCents"]) + cents), current + assert call("GET", summary, user="viewer") == viewer_summary + + def create_at(root): + return call("POST", root + "/items", {"name": "待整理设备", "quantity": 2, + "appearance": {"icon": "BOX", "priceCents": maximum}}, status=201) + + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + first, second = pool.map(create_at, roots) + check(2, 4, 2, 0, 0, maximum * 4) + call("POST", roots[0] + "/items", {"name": "超额测试", "quantity": 1, + "appearance": {"icon": "BOX", "priceCents": maximum + 1}}, status=400) + note = call("POST", roots[0] + "/items", {"name": "未填价格的物品", "quantity": 1}, status=201) + check(3, 5, 2, 0, 0, maximum * 4) + + path = roots[0] + "/items/" + first["id"] + update = {"name": first["name"], "quantity": 3, "version": first["version"], + "appearance": {"icon": "BOX", "priceCents": 8888}} + edited = call("PUT", path, update) + check(3, 6, 2, 0, 0, maximum * 2 + 3 * 8888) + + publication = path + "/publication" + draft = {"title": "测试分享", "body": "体验记录"} + assert call("PUT", publication, draft) == call("PUT", publication, draft) + check(3, 6, 2, 0, 1, maximum * 2 + 3 * 8888) + call("DELETE", publication, status=204) + check(3, 6, 2, 0, 0, maximum * 2 + 3 * 8888) + call("PUT", publication, draft) + + call("DELETE", path + "?version=" + str(edited["version"]), status=204) + check(2, 3, 1, 1, 0, maximum * 2) + call("DELETE", roots[1], status=202) + roots.pop() + check(1, 1, 0, 1, 0, 0) + assert note["priceCents"] is None and second["priceCents"] == maximum + finally: + for root in roots: + call("DELETE", root, status=202) + check(0, 0, 0, 0, 0, 0) + print("PASS private persisted owner totals, concurrent spaces, price cap, publication, archive and deletion", flush=True) + + def verify_search_and_voice(root): def location(name, parent=None): return call("POST", root + "/locations", {"name": name, "parentId": parent}, status=201)["id"] @@ -228,9 +286,18 @@ def verify_community(root): 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", + assert set(result) == {"id", "title", "body", "author", "authorId", "authorAvatar", "mine", "publishedAt", "average", "votes", "myRating", "comments"} assert result["title"] == term and result["body"] == draft["body"] and result["mine"] is False + profile_path = "/api/community/people/" + result["authorId"] + call("GET", profile_path, user=None, status=401) + call("GET", "/api/community/people/" + str(uuid4()), user="other", status=404) + assert call("GET", profile_path, user="other") == { + "id": result["authorId"], "name": result["author"], "avatar": result["authorAvatar"], "publishedItems": 2 + } + authors_posts = call("GET", posts + "?" + urlencode({"authorId": result["authorId"]}), user="other") + assert {row["id"] for row in authors_posts["posts"]} == {result["id"], weaker} + assert call("GET", root + "/items/" + item["id"])["item"]["communityPostId"] == result["id"] 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") @@ -254,6 +321,8 @@ def verify_community(root): comments = address + "/comments" first = call("POST", comments, {"body": "请问续航怎么样?"}, user="other", status=201) + commenter = call("GET", "/api/community/people/" + first["authorId"], user="viewer") + assert commenter["id"] != result["authorId"] and commenter["publishedItems"] == 0 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"]] @@ -269,7 +338,9 @@ def verify_community(root): 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 + private = call("GET", root + "/items/" + item["id"])["item"] + assert private["published"] is False and private["communityPostId"] is None + assert call("GET", profile_path, user="other")["publishedItems"] == 1 again = call("PUT", publication(item), draft)["postId"] assert again != sharing["postId"] diff --git a/docs/architecture/account-profile.md b/docs/architecture/account-profile.md index f96ac48..2a4ba78 100644 --- a/docs/architecture/account-profile.md +++ b/docs/architecture/account-profile.md @@ -1,4 +1,4 @@ -# 账号资料与收藏 +# 账号资料、物品概览与收藏 iOS 的「我的」显示账号资料、当前空间、收藏和退出入口。个人资料跨空间,收藏仍按当前空间和个人账号筛选。 @@ -10,10 +10,18 @@ iOS 的「我的」显示账号资料、当前空间、收藏和退出入口。 Flyway V8 新增 `account_profile`,主键是账号的 subject。资料同空间成员表分开,一份资料可在各空间显示。更新使用 PostgreSQL 的主键冲突更新,在同一个事务中返回保存结果。现有登录会话和物品数据保持兼容,回退应用时可以保留新增表。 +## 物品概览 + +`GET /api/me/inventory-summary` 根据已验证的当前账号读取 `account_inventory_stats` 主键。个人统计覆盖该账号拥有的空间,共享空间的编辑者和查看者不重复累计。返回在册记录数、数量合计、已填价格记录数、已删除记录数、公开物品数和人民币分表示的购入总额。清除一个物品的价格后,它仍计入在册记录和件数。没有记录时返回零。整空间删除后,空间内的在册和已删除记录都从统计中扣除。 + +购入总额是每条在册物品的单价乘数量相加,金额用 PostgreSQL `numeric(38,0)`,API 用十进制字符串传输。单件单价的上限为 999 亿元,最小单位为分。移动、备注、照片和收藏不会修改金额。账号身份、签名和概览为私有数据。 + +Flyway V14 在原表数据上回填统计,物品新增、价格或数量变化、归档、物理删除时由数据库触发器按差量更新。发布、撤回和级联清理同步更新公开数。触发器和业务写入使用同一事务,账号主键行上的原子加减处理跨空间并发。查询概览只读统计记录。当前空间所有者不可转让,数据库约束每个空间最多一名所有者。实现所有权转移时,需在交接事务内迁移汇总数据。 + ## 收藏加载 收藏复用物品列表 API 的 `favorites=true` 参数。数据库同时匹配当前空间、账号和物品。iOS 在实际显示的导航页启动请求。切换搜索词或列表刷新会使旧请求失效,失败后结束加载并提供重试。 ## 验收 -`backend/tests/ios_experience_smoke.py` 检查未登录访问、不同账号资料隔离、保存回读、输入验证、空收藏和有收藏的返回。客户端覆盖 [TC-28 与 TC-29](../testing/cases.md)。 +`backend/tests/ios_experience_smoke.py` 检查未登录访问、账号隔离、资料保存、个人统计并发更新、金额上限及删除回退。客户端覆盖 [TC-28 与 TC-29](../testing/cases.md)。 diff --git a/docs/architecture/community.md b/docs/architecture/community.md index a5050b3..5bc6e45 100644 --- a/docs/architecture/community.md +++ b/docs/architecture/community.md @@ -4,7 +4,7 @@ 社区和家庭物品都由 `inventory-service` 管理。一个物品可以有一条社区分享。数据库用 `community_post` 保存单独填写的标题和正文,通过空间与物品的复合外键关联。查不到分享记录时,物品是私有的。修改家里的名称、备注或价格时,已经发布的标题和正文原样保留。 -空间所有者从物品详情或社区入口发起发布,确认后才写入。社区接口允许已登录账号访问,成员关系仍只用于家庭接口。公开响应使用单独的 DTO,返回帖子地址、标题、正文、昵称、发布时间、评分和评论数。位置树、家庭标识、源物品标识、购买信息、备注和照片留在家庭接口。昵称为空时显示「见物用户」。内容由用户输入,发布表单提醒先检查个人信息。 +空间所有者从物品详情或社区入口发起发布,确认后才写入。社区接口允许已登录账号访问,成员关系仍只用于家庭接口。公开响应使用单独的 DTO,返回帖子地址、标题、正文、作者公开标识、头像、昵称、发布时间、评分和评论数。位置树、家庭标识、源物品标识、购买信息、备注和照片留在家庭接口。昵称为空时显示「见物用户」。内容由用户输入,发布表单提醒先检查个人信息。 ```mermaid flowchart LR @@ -21,6 +21,12 @@ flowchart LR 每位账号在每个帖子下有一个 1–5 星的评分,重复提交会更新同一行,也可以清除。列表先取出当前页,再统计其中帖子的评分和评论。评论每条最多 500 字,按时间和评论 ID 分页,评论者可删除自己的评论。发表时锁住帖子并检查账号在该帖的一分钟内已有评论,达到八条时返回 429。当前聚合和评论都按数据库事务处理,压测时应分别观察热门帖的并发写入和列表读延迟。 +## 社区主页 + +`GET /api/community/people/{id}` 返回独立的公开标识、昵称、内置头像和公开物品数量。公开标识是随机 UUID,与登录名和内部账号编号分开。Flyway V15 回填已有发布者和评论者,新发布或评论时自动分配。昵称为空时显示「见物用户」,签名和物品统计留在个人账号接口。通过 `/api/community/posts?authorId={id}` 获取对方的公开分享,复用同一套查询与游标。 + +家庭物品详情会在已公开时返回社区帖子 ID,当前空间的成员可以据此查看公开评价。私人短评继续以物品和账号为键保存。社区评分和评论只关联公开帖子,撤回时一起清理。 + ## 数据撤回与发布 撤回时在同一事务删除帖子以及评分和评论,原物品仍在空间。归档物品由数据库触发器撤回,删除整个空间由外键清理帖子。原分享地址随后返回 404。再次发布会生成新地址。社区读取使用 `Cache-Control: no-store`,网关限制请求体为 16 KiB。物品列表的 `published` 由现有分享记录计算,避免再维护一份状态。 diff --git a/docs/architecture/inventory-appearance.md b/docs/architecture/inventory-appearance.md index 6b36d39..bf964a7 100644 --- a/docs/architecture/inventory-appearance.md +++ b/docs/architecture/inventory-appearance.md @@ -4,7 +4,7 @@ Flyway V9 给位置与物品增加各自的图标标识,由 API 枚举和 PostgreSQL 约束校验。已有位置默认用文件夹,已有物品默认用箱子。修改空间默认位置图标和名称沿用原来的空间写权限。 -物品的 `appearance` 包含 `icon` 和可空的 `priceCents`。购入单价按人民币分存为整数,范围是 0 到 99,999,999.99 元。旧客户端省略 `appearance` 时保留现有字段。新版传入该对象且价格为空时清空单价。物品编辑沿用现有版本号校验。 +物品的 `appearance` 包含 `icon` 和可空的 `priceCents`。购入单价按人民币分存为整数,范围是 0 到 999 亿元。旧客户端省略 `appearance` 时保留现有字段。新版传入该对象且价格为空时清空单价。物品编辑沿用现有版本号校验。 ## 个人位置图标 diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md index 58c5c5f..2dda494 100644 --- a/docs/product/ios-experience.md +++ b/docs/product/ios-experience.md @@ -2,7 +2,7 @@ ## 首页 -见物标识在顶部居中。照片下方用三张示例卡介绍 AI 智能录入、智能找物和社区。底部可以进入自己的空间。首次使用时可以新建空空间,或在空间列表里接受家人的邀请。 +见物标识和品牌语「于寻常处,见生活。」在顶部居中显示。照片下方用三张示例卡介绍 AI 智能录入、智能找物和社区。底部可以进入自己的空间。首次使用时可以新建空空间,或在空间列表里接受家人的邀请。 ## 录入 @@ -18,6 +18,8 @@ 顶部的一行显示头像、账号或昵称、签名。点这一行可修改头像、昵称和签名,保存后跟随账号。首版头像从六个内置图案中选择。 +物品概览汇总你拥有的空间,显示在册件数、已公开和已删除的条数。购入总额是已填写单价的在册物品按数量合计。金额和私有统计只在自己的「我的」显示。 + 下面是当前空间、空间设置和切换空间。收藏在「我的收藏」里,按当前空间显示。切换空间后可以查看该空间的收藏。收藏列表为空时直接显示空状态,加载出错可以重试。退出登录放在页面底部。 找物页右上角显示当前空间。点开可看到可访问的空间和当前选中项,也可以进入完整的「我的空间」列表。 @@ -52,4 +54,4 @@ 物品建好后默认只在空间里。空间所有者可从物品详情的「分享到社区」或社区右上角「发布物品」选一件,单独写标题和使用感受。社区首版分享文字,已经上传到家里的照片仍按空间权限查看。 -登录后可浏览、搜索公开分享、打 1–5 星及发表评论。撤回后,帖子及其评分、评论从社区删除。物品仍在空间。家里的一件物品需要管理存放位置时,可建立相应的位置节点。例如用来放物品的架子,先按位置管理。首版没有双重身份和物品转位置操作。 +登录后可浏览、搜索公开分享、点星评分及发表评论。点帖子或评论里的头像和昵称,可查看该用户的社区主页及公开物品。已公开的物品可从自己的物品详情进入社区评论和评分。个人短评保存在自己的物品评价中。撤回后,帖子及其评分、评论从社区删除。物品仍在空间。家里的一件物品需要管理存放位置时,可建立相应的位置节点。例如用来放物品的架子,先按位置管理。首版没有双重身份和物品转位置操作。 diff --git a/docs/testing/cases.md b/docs/testing/cases.md index cae6c34..b8a3980 100644 --- a/docs/testing/cases.md +++ b/docs/testing/cases.md @@ -46,5 +46,8 @@ R01–R10 对应[需求与验收](../product/requirements.md)。实现和当前 | TC-40 iOS 会话缓存隔离 | R01 | 加载空间 A 的数据,切到空间 B,再退出并换另一个账号。 | 家庭数据按所在空间读取,旧账号的内存快照已经清除。 | | TC-41 无位置物品 | R03、R06 | 手动保存留空位置的物品。智能草稿中同时保存一件有位置和一件无位置的物品。按名称找物,并对无位置的物品设置、清除位置。 | 物品均可保存和搜索。位置调整保留历史,旧版本请求返回冲突。 | | TC-42 智能匹配位置 | R06 | 在两个房间建同名抽屉。分别录入明确路径、同名抽屉和没有提位置的描述。在草稿里点叉号。 | 完整路径优先,同名只在当前房间唯一时预选。没提位置时使用当前房间。清除后仍能保存。 | +| TC-43 导航栏与删除位置 | R02 | 在 iPhone 打开房间详情并滑到列表末尾,再检查四个底栏入口的选中状态。 | 删除位置可完整显示和点击。四个图标的视觉大小一致,当前选中项为实心,中央加号仍进入录入页。 | +| TC-44 购入总额和记录数 | R03 | 同一所有者在两个空间并发录入,修改一件物品的数量和单价,发布、撤回并删除物品,再删除其所在空间。用另一账号查自己的概览。 | 每步统计与物品状态一致,已删除物品从金额扣除,超上限单价被拒绝,查询只读取当前账号的汇总。 | +| TC-45 社区资料和评价 | R08、R10 | 从帖子和评论点进不同作者主页,查公开物品。从已公开物品的详情进入社区评价,改星并发表评论。 | 公开主页只显示昵称、头像和公开物品及数量。个人短评和购入总额仅当前账号可见。 | [测试与演示计划](plan.md) diff --git a/docs/ui/ios-welcome.md b/docs/ui/ios-welcome.md index 9b8c0c4..89b69d1 100644 --- a/docs/ui/ios-welcome.md +++ b/docs/ui/ios-welcome.md @@ -18,7 +18,7 @@ ## 首次打开 -见物标识在屏幕安全区顶部居中。三个功能卡使用同色图标。照片用横幅构图,下方三张示例卡依次介绍功能。登录入口贴近底部安全区。 [首页主图](../../apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/WelcomeTray.jpg) +见物标识和品牌语「于寻常处,见生活。」在屏幕安全区顶部居中排列。三个功能卡使用同色图标。照片用横幅构图,下方三张示例卡依次介绍功能。登录入口贴近底部安全区。 [首页主图](../../apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/WelcomeTray.jpg) | 示例 | 内容 | | --- | --- |