diff --git a/apps/ios/AppInfo.plist b/apps/ios/AppInfo.plist index ceb3d8f..0b5d491 100644 --- a/apps/ios/AppInfo.plist +++ b/apps/ios/AppInfo.plist @@ -6,5 +6,9 @@ $(ATLAS_API_BASE_URL) AtlasOIDCIssuer $(ATLAS_OIDC_ISSUER) + NSMicrophoneUsageDescription + 用于录入物品时接收你说的话。 + NSSpeechRecognitionUsageDescription + 用于在此设备上把整理时说的话转成文字。 diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index 77a9372..63e383a 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 = 4; + CURRENT_PROJECT_VERSION = 5; 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 = 4; + CURRENT_PROJECT_VERSION = 5; GENERATE_INFOPLIST_FILE = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; diff --git a/apps/ios/ItemAtlas/Account.swift b/apps/ios/ItemAtlas/Account.swift index f63de32..712a4be 100644 --- a/apps/ios/ItemAtlas/Account.swift +++ b/apps/ios/ItemAtlas/Account.swift @@ -84,6 +84,17 @@ final class AtlasAccount { private var refreshTask: Task? private var generation = UUID() + var preferenceScope: String? { + guard let segment = tokens?.grant.access_token.split(separator: ".").dropFirst().first, + let issuer = configuration?.issuer else { return nil } + let payload = segment.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + let padding = String(repeating: "=", count: (4 - payload.count % 4) % 4) + guard let data = Data(base64Encoded: payload + padding), + let claims = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let subject = claims["sub"] as? String, !subject.isEmpty else { return nil } + return issuer.absoluteString + "/" + subject + } + init() { let config = URLSessionConfiguration.ephemeral config.urlCache = nil diff --git a/apps/ios/ItemAtlas/Assets.xcassets/WelcomeDrawer.imageset/Contents.json b/apps/ios/ItemAtlas/Assets.xcassets/WelcomeDrawer.imageset/Contents.json deleted file mode 100644 index 8687f3a..0000000 --- a/apps/ios/ItemAtlas/Assets.xcassets/WelcomeDrawer.imageset/Contents.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "images" : [ - { - "filename" : "WelcomeDrawer.jpg", - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/apps/ios/ItemAtlas/Assets.xcassets/WelcomeDrawer.imageset/WelcomeDrawer.jpg b/apps/ios/ItemAtlas/Assets.xcassets/WelcomeDrawer.imageset/WelcomeDrawer.jpg deleted file mode 100644 index e46ebfc..0000000 Binary files a/apps/ios/ItemAtlas/Assets.xcassets/WelcomeDrawer.imageset/WelcomeDrawer.jpg and /dev/null differ diff --git a/apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/Contents.json b/apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/Contents.json new file mode 100644 index 0000000..bd77734 --- /dev/null +++ b/apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [{ "filename" : "WelcomeTray.jpg", "idiom" : "universal" }], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/WelcomeTray.jpg b/apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/WelcomeTray.jpg new file mode 100644 index 0000000..4f5e97c Binary files /dev/null and b/apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/WelcomeTray.jpg differ diff --git a/apps/ios/ItemAtlas/IntakeView.swift b/apps/ios/ItemAtlas/IntakeView.swift index 3fb0a6c..c455652 100644 --- a/apps/ios/ItemAtlas/IntakeView.swift +++ b/apps/ios/ItemAtlas/IntakeView.swift @@ -2,7 +2,10 @@ import SwiftUI struct IntakeView: View { let store: InventoryStore + @Environment(\.scenePhase) private var scenePhase + @AppStorage private var automaticSave: Bool @FocusState private var typing: Bool + @State private var voice = VoiceCapture() @State private var text = "" @State private var draft: Draft? @State private var selections: [Int: UUID] = [:] @@ -10,10 +13,22 @@ struct IntakeView: View { @State private var busy = false @State private var showingAdd = false @State private var error: String? + @State private var receipt: String? + @State private var showingReceipt = false + @State private var showingVoiceReview = false + + init(store: InventoryStore) { + self.store = store + let scope = store.account.preferenceScope ?? "unavailable" + _automaticSave = AppStorage(wrappedValue: false, "atlas.voice-auto-save." + scope) + } private struct Draft: Decodable { let id: UUID + let originalText: String let candidates: [Candidate] + let status: String + let source: String? let version: Int } private struct Candidate: Decodable { @@ -23,20 +38,43 @@ struct IntakeView: View { let location: String? } private struct Operation: Decodable { let id: UUID; let status: String } - private struct Confirm: Encodable { let version: Int; let items: [ItemInput] } + private struct Confirm: Encodable { let version: Int; let items: [ItemInput]; let automatic: Bool } + + private var canParse: Bool { + !busy && voice.phase == .idle && operation == nil && text.count <= 4000 && + !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } var body: some View { NavigationStack { if store.canWrite { Form { Button { showingAdd = true } label: { Label("手工记一件", systemImage: "plus") } - Section("批量录入") { - TextEditor(text: $text).frame(minHeight: 120).focused($typing).accessibilityLabel("整理原话") - Button("生成草稿") { typing = false; Task { await parse() } } - .disabled(busy || operation != nil || text.count > 4000 || text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + Section("说句话,记下来") { + voiceButton + if !voice.transcript.isEmpty { + Text(voice.transcript).foregroundStyle(.secondary) + } + if let error = voice.error { Text(error).font(.footnote).foregroundStyle(.secondary) } + TextEditor(text: $text).frame(minHeight: 96).focused($typing).accessibilityLabel("整理原话") + .disabled(busy || voice.phase != .idle || operation != nil) + Button("提取物品") { typing = false; Task { await parse(source: "VOICE") } }.disabled(!canParse) + Button("用 AI 整理") { typing = false; Task { await parse(source: "MODEL") } }.disabled(!canParse) + if store.account.preferenceScope != nil { + DisclosureGroup("语音设置") { + Toggle("清楚的一句话自动保存", isOn: $automaticSave) + Text("仅自动保存一件物品,位置需匹配完整路径。").font(.footnote).foregroundStyle(.secondary) + } + } } if let draft { Section("核对物品和位置") { + if draft.candidates.isEmpty { + Text(draft.status == "MODEL_UNAVAILABLE" + ? "模型暂不可用,原话已保留。" + : "这句话需要再核对。可以改文字、手工录入,或用 AI 整理。") + .font(.footnote).foregroundStyle(.secondary) + } ForEach(draft.candidates.indices, id: \.self) { index in let candidate = draft.candidates[index] if candidate.action == "SKIP" { @@ -54,8 +92,10 @@ struct IntakeView: View { }.disabled(operation != nil) } } - Button("确认录入") { Task { await submit(draft) } } - .disabled(busy || selections.isEmpty || operation != nil) + if !draft.candidates.isEmpty { + Button("确认保存") { Task { await submit(draft) } } + .disabled(busy || selections.isEmpty || operation != nil) + } } } if let operation { @@ -75,6 +115,32 @@ struct IntakeView: View { } .dismissibleKeyboard(active: typing) { typing = false } .navigationTitle("录入") + .onDisappear { voice.cancel() } + .onChange(of: scenePhase) { _, phase in + if phase == .background { voice.cancel() } + } + .onChange(of: text) { _, updated in + if operation == nil && draft?.originalText != updated { + draft = nil + selections = [:] + } + } + .alert("已存入", isPresented: $showingReceipt) { + Button("知道了", role: .cancel) { receipt = nil } + } message: { + Text(receipt ?? "") + } + .confirmationDialog("核对这条录入", isPresented: $showingVoiceReview, titleVisibility: .visible) { + Button("确认保存") { + if let draft { Task { await submit(draft) } } + } + Button("返回编辑", role: .cancel) {} + } message: { + if let item = draft?.candidates.first, + let place = store.locations.first(where: { $0.id == selections[0] }) { + Text("\(item.name) ×\(item.quantity ?? 1)\n\(place.path)") + } + } .sheet(isPresented: $showingAdd) { ItemEditor(store: store) } } else { ContentUnavailableView("当前空间只有查看权限", systemImage: "lock").navigationTitle("录入") @@ -82,18 +148,75 @@ struct IntakeView: View { } } - private func parse() async { + private var voiceButton: some View { + Button { + if voice.phase == .recording { + voice.stop() + } else { + typing = false + let hadText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + Task { + await voice.start(context: store.locations.map(\.name)) { phrase, final in + text = hadText ? text + "\n" + phrase : phrase + let canSave = final && !hadText && automaticSave && store.account.preferenceScope != nil + if text.count <= 4000 { + Task { await parse(source: "VOICE", fromVoice: true, automatically: canSave) } + } + } + } + } + } label: { + switch voice.phase { + case .idle: Label("开始录音", systemImage: "mic.fill") + case .preparing: Label("准备麦克风…", systemImage: "mic") + case .recording: Label("说完了", systemImage: "stop.circle.fill") + case .finishing: Label("正在转写…", systemImage: "waveform") + } + } + .disabled(busy || operation != nil || voice.phase == .preparing || voice.phase == .finishing) + } + + private func parse(source: String, fromVoice: Bool = false, automatically: Bool = false) async { busy = true defer { busy = false } error = nil do { try await store.refreshLocations() - draft = try await store.send(store.root + "/drafts", ["text": text]) - selections = [:] + let result: Draft = try await store.send(store.root + "/drafts", ["text": text, "source": source]) + draft = result + selections = Dictionary(uniqueKeysWithValues: result.candidates.enumerated().compactMap { index, candidate in + guard candidate.action != "SKIP", let place = suggestedPlace(candidate.location) else { return nil } + return (index, place.id) + }) + if automatically, result.source == "VOICE", result.candidates.count == 1, + let candidate = result.candidates.first, candidate.action == "RECORD", + let place = suggestedPlace(candidate.location, fullPathOnly: true), place.id == selections[0] { + receipt = "\(candidate.name) ×\(candidate.quantity ?? 1)\n\(place.path)" + await submit(result, automatic: true) + } else if fromVoice && result.candidates.count == 1 && selections[0] != nil { + showingVoiceReview = true + } } catch { self.error = error.localizedDescription } } - private func submit(_ draft: Draft) async { + private func suggestedPlace(_ original: String?, fullPathOnly: Bool = false) -> Place? { + guard let original else { return nil } + func key(_ value: String) -> String { + value.folding(options: [.caseInsensitive, .widthInsensitive], locale: Locale(identifier: "zh-CN")) + .filter { !$0.isWhitespace && $0 != "/" } + } + let hint = key(original) + guard !hint.isEmpty else { return nil } + let spoken = hint.hasSuffix("了") ? String(hint.dropLast()) : hint + let exact = store.locations.filter { key($0.path) == hint } + let matches = exact.isEmpty ? store.locations.filter { key($0.path) == spoken } : exact + if !matches.isEmpty { return matches.count == 1 ? matches.first : nil } + if fullPathOnly { return nil } + let names = store.locations.filter { key($0.name) == hint || key($0.name) == spoken } + return names.count == 1 ? names.first : nil + } + + private func submit(_ draft: Draft, automatic: Bool = false) async { let items = draft.candidates.enumerated().compactMap { index, candidate -> ItemInput? in guard let location = selections[index], candidate.action != "SKIP" else { return nil } return ItemInput(name: candidate.name, quantity: candidate.quantity ?? 1, notes: "", locationId: location, aliases: []) @@ -102,10 +225,13 @@ struct IntakeView: View { defer { busy = false } do { let accepted: Operation = try await store.send(store.root + "/drafts/\(draft.id)/confirm", - Confirm(version: draft.version, items: items)) + Confirm(version: draft.version, items: items, automatic: automatic)) operation = accepted await poll(accepted) - } catch { self.error = error.localizedDescription } + } catch { + if automatic { receipt = nil } + self.error = error.localizedDescription + } } private func retry(_ operation: Operation) async { @@ -128,7 +254,11 @@ struct IntakeView: View { for _ in 0..<12 { let status: Operation = try await store.get(store.root + "/operations/\(current.id)") operation = status - if status.status == "COMPLETED" { store.changed(); return } + if status.status == "COMPLETED" { + store.changed() + showingReceipt = receipt != nil + return + } if ["FAILED", "REJECTED", "NEEDS_REVIEW"].contains(status.status) { return } try await Task.sleep(for: .seconds(1)) } diff --git a/apps/ios/ItemAtlas/InventoryView.swift b/apps/ios/ItemAtlas/InventoryView.swift index 77eeee4..5d1f854 100644 --- a/apps/ios/ItemAtlas/InventoryView.swift +++ b/apps/ios/ItemAtlas/InventoryView.swift @@ -3,6 +3,7 @@ import SwiftUI struct InventoryView: View { let store: InventoryStore var favoritesOnly = false + @Environment(\.colorScheme) private var colorScheme @State private var query = "" @FocusState private var searching: Bool @@ -10,16 +11,18 @@ struct InventoryView: View { NavigationStack { VStack(spacing: 0) { VStack(alignment: .leading, spacing: 14) { - HStack(spacing: 7) { - Image("BrandMark").resizable().frame(width: 24, height: 24).clipShape(.rect(cornerRadius: 6)) - .accessibilityHidden(true) - Text("见物").font(.subheadline.weight(.semibold)) + HStack(alignment: .firstTextBaseline, spacing: 12) { + Text(favoritesOnly ? "收藏" : "找物").font(.largeTitle.bold()) + .accessibilityAddTraits(.isHeader) + .layoutPriority(1) Spacer() - Text(store.space.name).font(.caption).lineLimit(1) + Label(store.space.name, systemImage: "house") + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) } - Text(favoritesOnly ? "我的收藏" : "找东西").font(.largeTitle.bold()).accessibilityAddTraits(.isHeader) HStack(spacing: 10) { - Image(systemName: "magnifyingglass").accessibilityHidden(true) + Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true) TextField("搜物品、别名或位置", text: $query) .focused($searching).submitLabel(.search).onSubmit { searching = false } .textInputAutocapitalization(.never) @@ -32,12 +35,12 @@ struct InventoryView: View { .accessibilityLabel("收起键盘") } } - .padding(12) - .foregroundStyle(Color.atlasNavy) - .environment(\.colorScheme, .light) - .background(.white, in: RoundedRectangle(cornerRadius: 10)) + .padding(.horizontal, 12) + .frame(minHeight: 46) + .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 13)) } - .padding(18).foregroundStyle(.white).background(Color.atlasNavy) + .padding(18) + .background(Color.entryBackground(for: colorScheme)) List { ItemsSection(store: store, query: query, favorites: favoritesOnly) } .listStyle(.plain).scrollDismissesKeyboard(.interactively) } diff --git a/apps/ios/ItemAtlas/ItemAtlasApp.swift b/apps/ios/ItemAtlas/ItemAtlasApp.swift index 5540e77..c2f6375 100644 --- a/apps/ios/ItemAtlas/ItemAtlasApp.swift +++ b/apps/ios/ItemAtlas/ItemAtlasApp.swift @@ -28,6 +28,8 @@ private struct SpacesView: View { @State private var showingJoin = false @State private var loaded = false @State private var error: String? + @State private var invitations: [ReceivedSpaceInvitation] = [] + @State private var updatingInvitation = false var body: some View { Group { @@ -38,22 +40,44 @@ private struct SpacesView: View { NavigationStack { List { if !loaded && error == nil { ProgressView("正在加载空间") } - if loaded && spaces.isEmpty { - ContentUnavailableView("还没有空间", systemImage: "house", description: Text("新建自己的空间,或用邀请码加入家人的空间。")) + if loaded && spaces.isEmpty && invitations.isEmpty { + ContentUnavailableView("还没有空间", systemImage: "house", description: Text("建一个自己的空间,或等家人邀请你。")) } if let error { Text(error).foregroundStyle(.red) } + if !invitations.isEmpty { + Section("待接受的邀请") { + ForEach(invitations) { invitation in + VStack(alignment: .leading, spacing: 8) { + Text(invitation.spaceName).font(.headline) + Text(invitation.role == "EDITOR" ? "可查看和整理物品" : "可查看物品") + .font(.subheadline).foregroundStyle(.secondary) + HStack(spacing: 18) { + Button("接受") { Task { await update(invitation, accepting: true) } } + Button("忽略") { Task { await update(invitation, accepting: false) } } + .foregroundStyle(.secondary) + } + .buttonStyle(.borderless) + .disabled(updatingInvitation) + } + } + } + } ForEach(spaces) { space in Button { selected = space } label: { Label(space.name, systemImage: "house") } } Button("新建空间") { showingCreate = true }.disabled(!loaded) - Button("使用邀请码") { showingJoin = true }.disabled(!loaded) } .task { await load(chooseSingle: !loaded) } .refreshable { await load() } .navigationTitle("我的空间") .toolbar { ToolbarItem(placement: .topBarTrailing) { - Button("退出登录") { Task { await account.signOut() } } + Menu { + Button("使用邀请码") { showingJoin = true } + Button("退出登录", role: .destructive) { Task { await account.signOut() } } + } label: { + Label("更多", systemImage: "ellipsis.circle") + } } } .sheet(isPresented: $showingCreate) { @@ -74,10 +98,32 @@ private struct SpacesView: View { spaces = try JSONDecoder().decode([Space].self, from: bytes) loaded = true error = nil - if chooseSingle && spaces.count == 1 { selected = spaces[0] } + let inbox = try await account.request("/api/households/direct-invitations") + try Task.checkCancellation() + invitations = try JSONDecoder().decode([ReceivedSpaceInvitation].self, from: inbox) + if chooseSingle && spaces.count == 1 && invitations.isEmpty { selected = spaces[0] } } catch where !Task.isCancelled { self.error = error.localizedDescription } catch {} } + + private func update(_ invitation: ReceivedSpaceInvitation, accepting: Bool) async { + guard !updatingInvitation else { return } + updatingInvitation = true + defer { updatingInvitation = false } + error = nil + let path = "/api/households/direct-invitations/" + invitation.id.uuidString + do { + if accepting { + let response = try await account.request(path + "/accept", method: "POST") + let space = try JSONDecoder().decode(Space.self, from: response) + if !spaces.contains(where: { $0.id == space.id }) { spaces.append(space) } + selected = space + } else { + _ = try await account.request(path, method: "DELETE") + } + invitations.removeAll { $0.id == invitation.id } + } catch { self.error = error.localizedDescription } + } } private struct SpaceTabs: View { @@ -152,6 +198,7 @@ private struct SpaceSettings: View { let store: InventoryStore let openSpaces: () -> Void @State private var confirming = false + @State private var showingInvite = false @State private var busy = false @State private var error: String? @@ -159,9 +206,13 @@ private struct SpaceSettings: View { NavigationStack { List { LabeledContent("当前空间", value: store.space.name) - ShareLink(item: store.space.id.uuidString) { Label("分享空间 ID", systemImage: "square.and.arrow.up") } Button("切换空间", action: openSpaces).disabled(busy) if store.space.role == "OWNER" { + Section("成员") { + Button { showingInvite = true } label: { + Label("邀请成员", systemImage: "person.badge.plus") + } + } Section { Button("删除空间", role: .destructive) { confirming = true }.disabled(busy) } @@ -170,6 +221,7 @@ private struct SpaceSettings: View { if let error { Text(error).foregroundStyle(.red) } } .navigationTitle("空间") + .sheet(isPresented: $showingInvite) { SpaceInvitationView(store: store) } .confirmationDialog("删除「\(store.space.name)」?", isPresented: $confirming, titleVisibility: .visible) { Button("删除空间和图片", role: .destructive) { Task { diff --git a/apps/ios/ItemAtlas/SpaceInvitations.swift b/apps/ios/ItemAtlas/SpaceInvitations.swift new file mode 100644 index 0000000..1a4c2d9 --- /dev/null +++ b/apps/ios/ItemAtlas/SpaceInvitations.swift @@ -0,0 +1,99 @@ +import SwiftUI + +struct ReceivedSpaceInvitation: Decodable, Identifiable { + let id: UUID + let spaceName: String + let role: String +} + +struct SpaceInvitationView: View { + let store: InventoryStore + @Environment(\.dismiss) private var dismiss + @FocusState private var editing: Bool + @State private var username = "" + @State private var role = "VIEWER" + @State private var sent: [SentInvitation] = [] + @State private var busy = false + @State private var notice: String? + @State private var error: String? + + private struct SentInvitation: Decodable, Identifiable { + let id: UUID + let username: String + let role: String + } + + private var endpoint: String { store.root + "/direct-invitations" } + private var recipient: String { username.trimmingCharacters(in: .whitespacesAndNewlines) } + + var body: some View { + NavigationStack { + Form { + Section { + TextField("对方的见物账号", text: $username) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .focused($editing) + Picker("加入后的权限", selection: $role) { + Text("查看").tag("VIEWER") + Text("查看和整理").tag("EDITOR") + } + Button("发送邀请") { editing = false; Task { await send() } } + .disabled(recipient.isEmpty || recipient.count > 64 || busy) + if let notice { Text(notice).font(.footnote).foregroundStyle(.secondary) } + if let error { Text(error).font(.footnote).foregroundStyle(.red) } + } + if !sent.isEmpty { + Section("待对方接受") { + ForEach(sent) { invitation in + LabeledContent(invitation.username, value: invitation.role == "EDITOR" ? "可整理" : "可查看") + .swipeActions { + Button("撤销", role: .destructive) { Task { await revoke(invitation) } } + .disabled(busy) + } + } + } + } + } + .dismissibleKeyboard(active: editing) { editing = false } + .navigationTitle("邀请成员") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { Button("完成") { dismiss() }.disabled(busy) } + } + .task { await load() } + } + } + + private func load() async { + do { sent = try await store.get(endpoint) } + catch where !Task.isCancelled { self.error = error.localizedDescription } + catch {} + } + + private func send() async { + guard !busy else { return } + busy = true + defer { busy = false } + error = nil + notice = nil + do { + let body = try JSONEncoder().encode(["username": recipient, "role": role]) + _ = try await store.account.request(endpoint, method: "POST", data: body) + username = "" + notice = "已提交。可接受的邀请会显示在对方的空间列表。" + await load() + } catch { self.error = error.localizedDescription } + } + + private func revoke(_ invitation: SentInvitation) async { + guard !busy else { return } + busy = true + defer { busy = false } + error = nil + do { + _ = try await store.account.request(endpoint + "/" + invitation.id.uuidString, method: "DELETE") + await load() + } catch { self.error = error.localizedDescription } + } +} diff --git a/apps/ios/ItemAtlas/VoiceCapture.swift b/apps/ios/ItemAtlas/VoiceCapture.swift new file mode 100644 index 0000000..1d605b7 --- /dev/null +++ b/apps/ios/ItemAtlas/VoiceCapture.swift @@ -0,0 +1,159 @@ +import AVFoundation +import Observation +import Speech + +@MainActor +@Observable +final class VoiceCapture { + enum Phase { case idle, preparing, recording, finishing } + + private(set) var phase: Phase = .idle + private(set) var transcript = "" + private(set) var error: String? + private let engine = AVAudioEngine() + private let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "zh-CN")) + private var request: SFSpeechAudioBufferRecognitionRequest? + private var recognition: SFSpeechRecognitionTask? + private var timer: Task? + private var sessionID: UUID? + private var tapInstalled = false + private var audioActive = false + private var completion: ((String, Bool) -> Void)? + + func start(context: [String], completion: @escaping (String, Bool) -> Void) async { + guard phase == .idle else { return } + let id = UUID() + sessionID = id + error = nil + transcript = "" + phase = .preparing + let microphone = await AVAudioApplication.requestRecordPermission() + guard sessionID == id else { return } + guard microphone else { + fail("麦克风权限已关闭。可以在系统设置中开启,或直接打字。") + return + } + let authorized = await withCheckedContinuation { continuation in + SFSpeechRecognizer.requestAuthorization { status in continuation.resume(returning: status == .authorized) } + } + guard sessionID == id else { return } + guard authorized else { + fail("语音识别权限已关闭。可以在系统设置中开启,或直接打字。") + return + } + guard let recognizer, recognizer.supportsOnDeviceRecognition, recognizer.isAvailable else { + fail("这台设备暂时无法在本机转写普通话。可以改用键盘听写或直接打字。") + return + } + + do { + let audio = AVAudioSession.sharedInstance() + try audio.setCategory(.record, mode: .measurement) + try audio.setActive(true) + audioActive = true + let input = engine.inputNode + let format = input.outputFormat(forBus: 0) + guard format.sampleRate > 0, format.channelCount > 0 else { + fail("当前没有可录音的麦克风。") + return + } + let request = SFSpeechAudioBufferRecognitionRequest() + request.requiresOnDeviceRecognition = true + request.shouldReportPartialResults = true + request.taskHint = .dictation + request.contextualStrings = Array(context.prefix(60)) + self.request = request + self.completion = completion + let sink = BufferSink(request) + input.installTap(onBus: 0, bufferSize: 1024, format: format) { @Sendable buffer, _ in + sink.append(buffer) + } + tapInstalled = true + recognition = recognizer.recognitionTask(with: request) { @Sendable [weak self] result, failure in + let text = result?.bestTranscription.formattedString + let final = result?.isFinal == true + let failed = failure != nil + Task { @MainActor in + self?.received(id: id, text: text, isFinal: final, failed: failed) + } + } + engine.prepare() + try engine.start() + phase = .recording + timer = Task { [weak self] in + try? await Task.sleep(for: .seconds(25)) + if !Task.isCancelled { self?.stop() } + } + } catch { + fail("麦克风暂时无法使用。") + } + } + + func stop() { + guard phase == .recording else { return } + phase = .finishing + stopMicrophone() + request?.endAudio() + timer?.cancel() + timer = Task { [weak self] in + try? await Task.sleep(for: .seconds(2)) + if !Task.isCancelled { self?.finish(final: false) } + } + } + + func cancel() { + stopMicrophone() + recognition?.cancel() + recognition = nil + request = nil + timer?.cancel() + timer = nil + completion = nil + sessionID = nil + phase = .idle + transcript = "" + if audioActive { + try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) + audioActive = false + } + } + + private func received(id: UUID, text: String?, isFinal: Bool, failed: Bool) { + guard sessionID == id else { return } + if let text, !text.isEmpty { transcript = text } + if isFinal || failed { finish(final: isFinal && !failed) } + } + + private func stopMicrophone() { + engine.stop() + if tapInstalled { + engine.inputNode.removeTap(onBus: 0) + tapInstalled = false + } + } + + private func finish(final: Bool) { + let text = transcript.trimmingCharacters(in: .whitespacesAndNewlines) + let callback = completion + cancel() + if text.isEmpty { + error = "没有听清。可以再录一遍,或直接输入。" + } else { + callback?(text, final) + } + } + + private func fail(_ message: String) { + cancel() + error = message + } + + // Apple's recognition request receives buffers on the audio thread. + private final class BufferSink: @unchecked Sendable { + private let request: SFSpeechAudioBufferRecognitionRequest + + init(_ request: SFSpeechAudioBufferRecognitionRequest) { self.request = request } + + func append(_ buffer: AVAudioPCMBuffer) { request.append(buffer) } + } +} diff --git a/apps/ios/ItemAtlas/WelcomeView.swift b/apps/ios/ItemAtlas/WelcomeView.swift index ae28f63..997719c 100644 --- a/apps/ios/ItemAtlas/WelcomeView.swift +++ b/apps/ios/ItemAtlas/WelcomeView.swift @@ -22,78 +22,32 @@ extension Color { struct WelcomeView: View { let account: AtlasAccount @Environment(\.colorScheme) private var colorScheme - @ScaledMetric(relativeTo: .largeTitle) private var headlineSize = 38.0 - @State private var showingGuide = false - - private var canvas: Color { - .entryBackground(for: colorScheme) - } + @Environment(\.dynamicTypeSize) private var dynamicType + @ScaledMetric(relativeTo: .largeTitle) private var headlineSize = 41.0 var body: some View { ScrollView { - VStack(alignment: .leading, spacing: 22) { + VStack(alignment: .leading, spacing: 19) { EntryBrand() - - VStack(alignment: .leading, spacing: 9) { - Text("放在哪里,\n一找就知道。") - .font(.system(size: headlineSize, weight: .bold)) - .accessibilityAddTraits(.isHeader) - Text("记下家里的东西和位置,下次需要时,搜一下就能找到。") - .font(.subheadline) - .foregroundStyle(.primary.opacity(0.72)) - } - - Color.atlasBlue.opacity(0.08) - .aspectRatio(1.9, contentMode: .fit) - .overlay { - GeometryReader { geometry in - Image("WelcomeDrawer") - .resizable() - .scaledToFill() - .frame(width: geometry.size.width, height: geometry.size.height) - } - } - .clipShape(.rect(cornerRadius: 21)) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 13) { - WelcomeFeature(symbol: "magnifyingglass", title: "搜名字就能找", - detail: "从房间到抽屉,顺着位置就能拿到。") - Divider().padding(.leading, 50) - WelcomeFeature(symbol: "square.and.pencil", title: "一次记几件", - detail: "把整理时记下的话变成草稿,核对后再保存。") - Divider().padding(.leading, 50) - WelcomeFeature(symbol: "person.2", title: "和家人一起找", - detail: "用邀请码加入同一个空间。") - } + if dynamicType.isAccessibilitySize { headline } + scene + Text("说一句「数据线放在书房抽屉」,见物帮你记下。") + .font(.body) + .foregroundStyle(.primary.opacity(0.77)) + .lineSpacing(4) } - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: 472, alignment: .leading) - .padding(.horizontal, 24) - .padding(.top, 12) - .padding(.bottom, 20) + .frame(maxWidth: 460, alignment: .leading) + .padding(.horizontal, 23) + .padding(.vertical, 12) .frame(maxWidth: .infinity) } .safeAreaInset(edge: .bottom, spacing: 0) { - actions - } - .background(canvas.ignoresSafeArea()) - .toolbar(.hidden, for: .navigationBar) - .sheet(isPresented: $showingGuide) { - WelcomeGuide() - } - } - - private var actions: some View { - VStack(spacing: 5) { NavigationLink { SignInView(account: account) } label: { HStack(spacing: 9) { - Text("登录我的空间") - Image(systemName: "arrow.right") - .font(.subheadline.weight(.semibold)) - .accessibilityHidden(true) + Text("进入我的空间") + Image(systemName: "arrow.right").accessibilityHidden(true) } .font(.body.weight(.semibold)) .frame(maxWidth: .infinity, minHeight: 29) @@ -101,70 +55,45 @@ struct WelcomeView: View { .buttonStyle(.borderedProminent) .buttonBorderShape(.roundedRectangle(radius: 15)) .controlSize(.large) - Button("看看怎么用") { showingGuide = true } - .font(.subheadline.weight(.semibold)) - .frame(minHeight: 44) + .frame(maxWidth: 460) + .padding(.horizontal, 23) + .padding(.vertical, 12) + .frame(maxWidth: .infinity) + .foregroundStyle(.white) + .background(Color.entryBackground(for: colorScheme)) } - .frame(maxWidth: 472) - .padding(.horizontal, 24) - .padding(.top, 10) - .frame(maxWidth: .infinity) - .background(canvas) - .overlay(alignment: .top) { Divider() } - } -} - -private struct WelcomeFeature: View { - let symbol: String - let title: String - let detail: String - @Environment(\.colorScheme) private var colorScheme - - private var iconColor: Color { - colorScheme == .dark ? Color(red: 0.58, green: 0.67, blue: 1) : .atlasBlue + .background(Color.entryBackground(for: colorScheme).ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) } - var body: some View { - HStack(alignment: .top, spacing: 12) { - Image(systemName: symbol) - .font(.system(size: 17, weight: .medium)) - .foregroundStyle(iconColor) - .frame(width: 38, height: 38) - .background(iconColor.opacity(0.12), in: .rect(cornerRadius: 12)) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 3) { - Text(title).font(.subheadline.weight(.semibold)) - Text(detail).font(.footnote).foregroundStyle(.primary.opacity(0.72)) - } - } - .accessibilityElement(children: .combine) + private var headline: some View { + Text("家里有的,\n心里有数。") + .font(.system(size: headlineSize, weight: .semibold)) + .accessibilityAddTraits(.isHeader) } -} -private struct WelcomeGuide: View { - @Environment(\.dismiss) private var dismiss - - var body: some View { - NavigationStack { - ScrollView { - VStack(alignment: .leading, spacing: 24) { - WelcomeFeature(symbol: "tray", title: "整理时记下位置", - detail: "给常用物品写下名称和位置。一次整理了好几件,也可以先生成草稿,再逐件核对。") - WelcomeFeature(symbol: "magnifyingglass", title: "需要时搜一下", - detail: "可以搜物品的名字,也可以搜平时的叫法。结果会显示它放在哪个房间、哪层柜子。") - WelcomeFeature(symbol: "person.2", title: "跟家人用同一个空间", - detail: "登录后可以新建自己的空间,也可以用邀请码加入家人的空间。") - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(24) - } - .navigationTitle("怎么用见物") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("完成") { dismiss() } + private var scene: some View { + Color.atlasNavy + .aspectRatio(0.94, contentMode: .fit) + .overlay { + GeometryReader { proxy in + Image("WelcomeTray") + .resizable() + .scaledToFill() + .frame(width: proxy.size.width, height: proxy.size.height) + .accessibilityHidden(true) } } - } + .overlay(alignment: .topLeading) { + if !dynamicType.isAccessibilitySize { + LinearGradient(colors: [.black.opacity(0.42), .clear], startPoint: .top, endPoint: .center) + .accessibilityHidden(true) + headline + .foregroundStyle(.white) + .padding(.horizontal, 23) + .padding(.top, 23) + } + } + .clipShape(.rect(cornerRadius: 25)) } } diff --git a/apps/ios/README.md b/apps/ios/README.md index 9eacd21..c67432e 100644 --- a/apps/ios/README.md +++ b/apps/ios/README.md @@ -4,7 +4,7 @@ ## 登录与空间 -未登录时展示首页和使用说明,两者都可以离线查看。点「登录我的空间」进入 SwiftUI 表单,表单内输入账号密码、查看登录进度和处理错误。返回后清除密码。登录成功才加载用户的空间。 [首页与登录设计稿](../../docs/ui/ios-welcome.md) +未登录时展示可离线查看的首页。点「进入我的空间」进入 SwiftUI 表单,表单内输入账号密码、查看登录进度和处理错误。返回后清除密码。登录字段已标记为系统的用户名和密码类型,已登录会话由钥匙串保存。 [首页与登录设计稿](../../docs/ui/ios-welcome.md) · [Apple 密码自动填充](https://developer.apple.com/documentation/security/password-autofill) 新登录通过 `POST /api/session/login`。App 把会话凭证保存在设备钥匙串,服务端按账号和空间返回物品、位置与收藏。首次登录可新建或通过邀请码加入空间,新空间显示空状态。升级后原 Keycloak 登录会话仍可刷新,退出后的再次登录走原生表单。 @@ -14,6 +14,8 @@ 找物、收藏、位置、手工录入和批量草稿使用项目 API。搜索和编辑表单可以手动收起键盘,表单也支持下滑收起。照片从系统照片选择器导入,支持平移、调整放大比例与方形剪裁,按最长边 1600 像素压缩为 JPEG。客户端最多接受 30 MiB 来源文件,上传上限为 5 MiB,每件最多六张。列表使用服务端生成的缩略图。 +录入页支持普通话本机转写。说完后可核对和修改原话,规则优先,模型由用户选择。语音自动保存默认关闭。同一个账号的设置只作用于当前设备。家庭邀请用对方的见物账号发出,接收者在空间列表接受。 [语音、搜索和家庭邀请](../../docs/architecture/mobile-capture-and-search.md) + ## 构建 ```sh diff --git a/backend/README.md b/backend/README.md index 37b4dd6..1a6cbea 100644 --- a/backend/README.md +++ b/backend/README.md @@ -42,3 +42,4 @@ Compose 的 `local` profile 带 `owner`、`viewer`、`other` 三个演示用户 - 家庭建档使用 `POST /api/households`,请求体为 `{"name":"家庭名称"}`,可传 `displayName`。创建者在同一事务成为 OWNER。用返回的 `Location` 查询家庭详情。受邀者登录后使用 `POST /api/households/invitations/redeem` 兑换。 - 录入状态进入 `NEEDS_REVIEW` 后,草稿创建者可调用 `POST /api/households/{household}/operations/{operation}/retry`。返回 `202` 时继续查询同一操作号。当前操作最多支持启动一次额外恢复窗口。 - 业务覆盖、受限的功能和实际复现命令见 [后端验收](../docs/testing/backend-readiness.md) 与 [部署和监控](../docs/deployment/observability.md)。 +- [iOS 语音、检索和邀请](../docs/architecture/mobile-capture-and-search.md) 说明草稿来源、权重、按账号邀请和 Flyway 迁移。CI 在独立数据库上执行 `ios_experience_smoke.py`。 diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java index 40fe9bc..69ecd8d 100644 --- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java +++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java @@ -33,14 +33,17 @@ class DraftService { this.propagator = propagator; } - Draft create(UUID household, String actor, String text) { + Draft create(UUID household, String actor, DraftInput input) { UUID id = UUID.randomUUID(); + DraftSource source = input.source() == null ? DraftSource.MODEL : input.source(); db.sql(""" - INSERT INTO draft(id,household_id,subject,original_text,status) - VALUES (:id,:household,:actor,:text,'GENERATING') - """).param("id", id).param("household", household).param("actor", actor).param("text", text).update(); + INSERT INTO draft(id,household_id,subject,original_text,status,source) + VALUES (:id,:household,:actor,:text,'GENERATING',:source) + """).param("id", id).param("household", household).param("actor", actor) + .param("text", input.text()).param("source", source.name()).update(); try { - String candidates = json.writeValueAsString(model.generate(text).items()); + var items = source == DraftSource.VOICE ? VoiceDraft.parse(input.text()) : model.generate(input.text()).items(); + String candidates = json.writeValueAsString(items); db.sql("UPDATE draft SET status='READY',candidates=cast(:data AS jsonb) WHERE id=:id") .param("id", id).param("data", candidates).update(); } catch (DraftModel.ModelUnavailable ex) { @@ -51,18 +54,19 @@ class DraftService { Draft get(UUID household, String actor, UUID id) { return db.sql(""" - SELECT id,original_text,candidates,status,version, + SELECT id,original_text,candidates,status,version,source, status='GENERATING' AND created_at < now() - interval '2 minutes' AS expired FROM draft WHERE id=:id AND household_id=:household AND subject=:actor """).param("id", id).param("household", household).param("actor", actor) .query((rs, row) -> new Draft(rs.getObject(1, UUID.class), rs.getString(2), json.readValue(rs.getString(3), new TypeReference>() {}), - rs.getBoolean("expired") ? "MODEL_UNAVAILABLE" : rs.getString(4), rs.getInt(5))) + rs.getBoolean("expired") ? "MODEL_UNAVAILABLE" : rs.getString(4), rs.getInt(5), + DraftSource.valueOf(rs.getString("source")))) .optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "草稿不存在")); } @Transactional - Operation confirm(UUID household, String actor, UUID id, Confirm input) { + Operation confirm(UUID household, String actor, UUID id, Confirm input, List places) { db.sql(""" SELECT id FROM draft WHERE id=:id AND household_id=:household AND subject=:actor FOR UPDATE """).param("id", id).param("household", household).param("actor", actor).query(UUID.class).optional() @@ -76,8 +80,12 @@ class DraftService { if (draft.version() != input.version() || !List.of("READY", "MODEL_UNAVAILABLE").contains(draft.status())) { throw new ResponseStatusException(CONFLICT, "草稿状态已变化,请刷新"); } + String expectedPath = Boolean.TRUE.equals(input.automatic()) + ? VoiceDraft.verifiedPlace(draft, input, places).map(Place::path) + .orElseThrow(() -> new ResponseStatusException(CONFLICT, "请手动确认物品和位置")) + : null; UUID operation = UUID.randomUUID(); - var payload = new Delivery(household, actor, input.items()); + var payload = new Delivery(household, actor, input.items(), expectedPath); db.sql(""" INSERT INTO confirm_operation(id,draft_id,draft_version,payload,trace_parent) VALUES (:operation,:id,:version,cast(:payload AS jsonb),:traceParent) diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java index 221dafa..0c6305f 100644 --- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java +++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java @@ -31,7 +31,7 @@ class IntakeController { ResponseEntity create(@PathVariable UUID household, @RequestHeader(HttpHeaders.AUTHORIZATION) String auth, Principal principal, @Valid @RequestBody DraftInput input) { inventory.checkAccess(household, auth, true); - var draft = drafts.create(household, principal.getName(), input.text()); + var draft = drafts.create(household, principal.getName(), input); return ResponseEntity.created(url(household, "drafts", draft.id())).body(draft); } @@ -47,7 +47,8 @@ class IntakeController { @RequestHeader(HttpHeaders.AUTHORIZATION) String auth, @Valid @RequestBody Confirm input) { inventory.checkAccess(household, auth, true); - var operation = drafts.confirm(household, principal.getName(), id, input); + var places = Boolean.TRUE.equals(input.automatic()) ? inventory.places(household, auth) : List.of(); + var operation = drafts.confirm(household, principal.getName(), id, input, places); return ResponseEntity.accepted().location(url(household, "operations", operation.id())).body(operation); } diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeDtos.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeDtos.java index 6fb20fd..8fecb8a 100644 --- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeDtos.java +++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeDtos.java @@ -7,17 +7,20 @@ import java.util.UUID; final class IntakeDtos { record Provider(String id, String name, String status, String model) {} - record DraftInput(@NotBlank @Size(max = 4000) String text) {} + enum DraftSource { MODEL, VOICE } + record DraftInput(@NotBlank @Size(max = 4000) String text, DraftSource source) {} record Candidate(@NotBlank @Size(max = 150) String name, @Min(1) @Max(9999) Integer quantity, @NotNull Action action, @Size(max = 300) String location) {} enum Action { RECORD, SKIP, REVIEW } record Candidates(@NotEmpty @Size(max = 30) List<@NotNull @Valid Candidate> items) {} - record Draft(UUID id, String originalText, List candidates, String status, int version) {} + record Draft(UUID id, String originalText, List candidates, String status, int version, DraftSource source) {} + record Place(UUID id, String path) {} record ItemInput(@NotBlank @Size(max = 150) String name, @Min(1) @Max(9999) int quantity, @Size(max = 1500) String notes, @NotNull UUID locationId, @Size(max = 20) List<@NotBlank @Size(max = 80) String> aliases) {} - record Confirm(@NotNull @Min(0) Integer version, @NotEmpty @Size(max = 30) List<@NotNull @Valid ItemInput> items) {} + record Confirm(@NotNull @Min(0) Integer version, @NotEmpty @Size(max = 30) List<@NotNull @Valid ItemInput> items, + Boolean automatic) {} record Operation(UUID id, String status) {} - record Delivery(UUID householdId, String actor, List items) {} + record Delivery(UUID householdId, String actor, List items, String expectedLocationPath) {} record DeliveryResult(String outcome) {} } diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/InventoryClient.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/InventoryClient.java index 147fb89..bedb181 100644 --- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/InventoryClient.java +++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/InventoryClient.java @@ -56,6 +56,17 @@ class InventoryClient { private record Membership(UUID id, String role) {} + java.util.List places(UUID household, String authorization) { + try { + Place[] response = membership.get().uri("/api/households/{id}/locations", household) + .header(HttpHeaders.AUTHORIZATION, authorization).retrieve().body(Place[].class); + if (response != null) return Arrays.asList(response); + } catch (RestClientException ex) { + throw new ResponseStatusException(SERVICE_UNAVAILABLE, "位置暂时无法核对"); + } + throw new ResponseStatusException(SERVICE_UNAVAILABLE, "位置响应为空"); + } + static RestClient.Builder setup(RestClient.Builder builder, String url) { var factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(Duration.ofSeconds(2)); diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/VoiceDraft.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/VoiceDraft.java new file mode 100644 index 0000000..30e345b --- /dev/null +++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/VoiceDraft.java @@ -0,0 +1,70 @@ +package com.tutudog.itematlas.intake; + +import static com.tutudog.itematlas.intake.IntakeDtos.*; + +import java.text.Normalizer; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; + +final class VoiceDraft { + private static final Pattern COMMAND = Pattern.compile( + "(?:我(?:刚刚|刚才|现在|刚)?\\s*)?(?:把|将)?\\s*(.+?)\\s*(?:放到|放在|放进|收进)\\s*(.+)"); + private static final Pattern UNCERTAIN = Pattern.compile( + "[、,,;;。!?!?\\n]|不(?:要|用|必|会|能|想|放|把|是|确定)|没(?:有|把|将|放)|别(?:把|放|收)|可能|好像|应该|或者|如果|然后|还有|一起|打算|想把|准备|哪里|哪儿|吗"); + private static final Pattern QUANTITY = Pattern.compile( + "([1-9][0-9]{0,3}|[一二两三四五六七八九十])[个根件条只套把张本双盒支]\\s*(.+)"); + private static final Pattern NUMBER_START = Pattern.compile("^[0-9零一二两三四五六七八九十百千万半].*"); + private static final Pattern EXTRA_QUANTITY = Pattern.compile("[0-9一二两三四五六七八九十][个根件条只套把张本双盒支]"); + private static final Map NUMBERS = Map.ofEntries( + Map.entry("一", 1), Map.entry("二", 2), Map.entry("两", 2), Map.entry("三", 3), Map.entry("四", 4), + Map.entry("五", 5), Map.entry("六", 6), Map.entry("七", 7), Map.entry("八", 8), Map.entry("九", 9), Map.entry("十", 10)); + + private VoiceDraft() {} + + static List parse(String original) { + String text = Normalizer.normalize(original, Normalizer.Form.NFKC).strip().replaceFirst("[。.!!]+$", ""); + if (text.length() > 120 || UNCERTAIN.matcher(text).find()) return List.of(); + var command = COMMAND.matcher(text); + if (!command.matches()) return List.of(); + String name = command.group(1).strip().replaceFirst("^(?:那个|这个)", "").strip(); + String location = command.group(2).strip(); + if (name.isEmpty() || location.isEmpty() || name.contains("和") || name.contains("跟") + || COMMAND.matcher(location).matches()) return List.of(); + var quantity = QUANTITY.matcher(name); + int count = 1; + if (quantity.matches()) { + String value = quantity.group(1); + count = NUMBERS.containsKey(value) ? NUMBERS.get(value) : Integer.parseInt(value); + name = quantity.group(2).strip(); + } else if (NUMBER_START.matcher(name).matches()) { + return List.of(); + } + if (EXTRA_QUANTITY.matcher(name).find()) return List.of(); + return List.of(new Candidate(name, count, Action.RECORD, location)); + } + + static Optional verifiedPlace(Draft draft, Confirm input, List places) { + if (draft.source() != DraftSource.VOICE || draft.candidates().size() != 1 || input.items().size() != 1) { + return Optional.empty(); + } + var candidate = draft.candidates().getFirst(); + var item = input.items().getFirst(); + if (candidate.action() != Action.RECORD || !candidate.name().equals(item.name()) || candidate.quantity() == null + || candidate.quantity() != item.quantity()) return Optional.empty(); + String location = pathKey(candidate.location()); + var exact = places.stream().filter(p -> pathKey(p.path()).equals(location)).toList(); + if (exact.isEmpty() && location.endsWith("了")) { + String spoken = location.substring(0, location.length() - 1); + exact = places.stream().filter(p -> pathKey(p.path()).equals(spoken)).toList(); + } + return exact.size() == 1 && exact.getFirst().id().equals(item.locationId()) + ? Optional.of(exact.getFirst()) : Optional.empty(); + } + + private static String pathKey(String path) { + return Normalizer.normalize(path, Normalizer.Form.NFKC).toLowerCase(Locale.ROOT).replaceAll("[/\\s]", ""); + } +} diff --git a/backend/intake-service/src/main/resources/db/migration/V3__draft_source.sql b/backend/intake-service/src/main/resources/db/migration/V3__draft_source.sql new file mode 100644 index 0000000..5c274b4 --- /dev/null +++ b/backend/intake-service/src/main/resources/db/migration/V3__draft_source.sql @@ -0,0 +1,2 @@ +ALTER TABLE draft ADD COLUMN source text NOT NULL DEFAULT 'MODEL' + CHECK (source IN ('MODEL', 'VOICE')); diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdController.java index e254db1..594e812 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdController.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdController.java @@ -90,4 +90,38 @@ class HouseholdController { Household redeem(Principal user, @RequestBody @Valid RedeemInput input) { return service.redeem(user.getName(), input); } + + @GetMapping(ROOT + "/direct-invitations") + List receivedInvitations(Principal user) { + return service.receivedInvitations(user.getName()); + } + + @PostMapping(ROOT + "/direct-invitations/{id}/accept") + Household acceptInvitation(@PathVariable UUID id, Principal user) { + return service.acceptInvitation(id, user.getName()); + } + + @DeleteMapping(ROOT + "/direct-invitations/{id}") + ResponseEntity declineInvitation(@PathVariable UUID id, Principal user) { + service.declineInvitation(id, user.getName()); + return ResponseEntity.noContent().build(); + } + + @GetMapping(FAMILY + "/direct-invitations") + List sentInvitations(@PathVariable UUID household, Principal user) { + return service.sentInvitations(household, user.getName()); + } + + @PostMapping(FAMILY + "/direct-invitations") + ResponseEntity sendInvitation(@PathVariable UUID household, Principal user, + @RequestBody @Valid AddressedInvitation input) { + service.sendInvitation(household, user.getName(), input); + return ResponseEntity.accepted().build(); + } + + @DeleteMapping(FAMILY + "/direct-invitations/{id}") + ResponseEntity cancelDirectInvitation(@PathVariable UUID household, @PathVariable UUID id, Principal user) { + service.cancelDirectInvitation(household, id, user.getName()); + return ResponseEntity.noContent().build(); + } } diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdDtos.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdDtos.java index 7f44359..459a44a 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdDtos.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdDtos.java @@ -16,6 +16,9 @@ final class HouseholdDtos { record Member(UUID id, String displayName, String role) {} record Invitation(UUID id, MemberRole role, OffsetDateTime expiresAt) {} record CreatedInvitation(UUID id, MemberRole role, OffsetDateTime expiresAt, String code) {} + record AddressedInvitation(@NotBlank @Size(max = 64) String username, @NotNull MemberRole role) {} + record ReceivedInvitation(UUID id, String spaceName, String role, OffsetDateTime expiresAt) {} + record SentInvitation(UUID id, String username, String role, OffsetDateTime expiresAt) {} record RedeemInput(@NotBlank @Pattern(regexp = "[A-Za-z0-9_-]{43}") String code, @NotBlank @Size(max = 80) String displayName) {} } diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java index 384c959..430f925 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java @@ -10,6 +10,7 @@ import java.security.SecureRandom; import java.time.OffsetDateTime; import java.util.Base64; import java.util.List; +import java.util.Locale; import java.util.UUID; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.simple.JdbcClient; @@ -212,6 +213,117 @@ class HouseholdService { .param("name", displayName).query(UUID.class).single(); } + List receivedInvitations(String actor) { + return db.sql(""" + SELECT d.id,h.name,d.role,d.expires_at FROM household_direct_invitation d + JOIN household h ON h.id=d.household_id + WHERE d.recipient_subject=:actor AND d.expires_at>now() + AND d.closed_at IS NULL AND d.accepted_member_id IS NULL + AND NOT EXISTS (SELECT FROM household_member m + WHERE m.household_id=h.id AND m.subject=:actor) + ORDER BY d.expires_at,d.id LIMIT 100 + """).param("actor", actor).query((rs, row) -> new ReceivedInvitation( + rs.getObject(1, UUID.class), rs.getString(2), rs.getString(3), + rs.getObject(4, OffsetDateTime.class))).list(); + } + + List sentInvitations(UUID household, String actor) { + access.requireOwner(access.role(household, actor)); + return db.sql(""" + SELECT d.id,a.username,d.role,d.expires_at FROM household_direct_invitation d + JOIN native_account a ON a.subject=d.recipient_subject + WHERE d.household_id=:household AND d.expires_at>now() + AND d.closed_at IS NULL AND d.accepted_member_id IS NULL + ORDER BY d.expires_at,d.id + """).param("household", household).query((rs, row) -> new SentInvitation( + rs.getObject(1, UUID.class), rs.getString(2), rs.getString(3), + rs.getObject(4, OffsetDateTime.class))).list(); + } + + @Transactional + void sendInvitation(UUID household, String actor, AddressedInvitation input) { + access.requireOwner(access.lockMember(household, actor)); + db.sql(""" + DELETE FROM household_direct_invitation WHERE household_id=:household + AND expires_atnow() AND closed_at IS NULL AND accepted_member_id IS NULL + """).param("household", household).query(Integer.class).single(); + if (pending >= MAX_ACTIVE_INVITATIONS) { + throw new ResponseStatusException(CONFLICT, "待接受的邀请已达上限"); + } + db.sql(""" + INSERT INTO household_invite_budget(actor,day,used) VALUES (:actor,CURRENT_DATE,1) + ON CONFLICT (actor) DO UPDATE SET day=excluded.day, + used=CASE WHEN household_invite_budget.day=excluded.day THEN household_invite_budget.used+1 ELSE 1 END + WHERE household_invite_budget.day<>excluded.day OR household_invite_budget.used<20 + RETURNING used + """).param("actor", actor).query(Integer.class).optional() + .orElseThrow(() -> new ResponseStatusException(TOO_MANY_REQUESTS, "今天的邀请已达上限")); + // Keep the send response the same for a missing account, an existing member or a duplicate. + db.sql(""" + INSERT INTO household_direct_invitation (id,household_id,recipient_subject,role,expires_at) + SELECT :id,:household,a.subject,:role,now()+interval '24 hours' FROM native_account a + WHERE a.username=:username AND a.enabled AND NOT EXISTS (SELECT FROM household_member m + WHERE m.household_id=:household AND m.subject=a.subject) + ON CONFLICT (household_id,recipient_subject) DO UPDATE SET + id=excluded.id,role=excluded.role,expires_at=excluded.expires_at, + closed_at=NULL,accepted_member_id=NULL + WHERE household_direct_invitation.expires_at<=now() + """).param("id", UUID.randomUUID()).param("household", household) + .param("role", input.role().name()).param("username", input.username().strip().toLowerCase(Locale.ROOT)) + .update(); + } + + @Transactional + Household acceptInvitation(UUID id, String actor) { + UUID household = db.sql("SELECT household_id FROM household_direct_invitation WHERE id=:id AND recipient_subject=:actor") + .param("id", id).param("actor", actor).query(UUID.class).optional() + .orElseThrow(HouseholdService::inviteUnavailable); + String name = db.sql("SELECT name FROM household WHERE id=:household FOR UPDATE") + .param("household", household).query(String.class).optional().orElseThrow(HouseholdService::inviteUnavailable); + var invitation = db.sql(""" + SELECT d.role,d.accepted_member_id,a.username + FROM household_direct_invitation d JOIN native_account a ON a.subject=d.recipient_subject + WHERE d.id=:id AND d.recipient_subject=:actor AND d.closed_at IS NULL AND a.enabled + AND (d.expires_at>now() OR d.accepted_member_id IS NOT NULL) + FOR UPDATE OF d + """).param("id", id).param("actor", actor).query((rs, row) -> new DirectAcceptance( + rs.getString(1), rs.getObject(2, UUID.class), rs.getString(3))).optional() + .orElseThrow(HouseholdService::inviteUnavailable); + var member = db.sql(""" + SELECT member_id,display_name,role FROM household_member WHERE household_id=:household AND subject=:actor + """).param("household", household).param("actor", actor).query(MEMBER).optional().orElse(null); + if (invitation.memberId() != null) { + if (member == null || !member.id().equals(invitation.memberId())) throw inviteUnavailable(); + return new Household(household, name, member.role()); + } + UUID membership = member == null ? addMember(household, actor, invitation.username(), invitation.role()) : member.id(); + db.sql("UPDATE household_direct_invitation SET accepted_member_id=:member WHERE id=:id") + .param("member", membership).param("id", id).update(); + return new Household(household, name, member == null ? invitation.role() : member.role()); + } + + void declineInvitation(UUID id, String actor) { + db.sql(""" + UPDATE household_direct_invitation SET closed_at=now() + WHERE id=:id AND recipient_subject=:actor AND closed_at IS NULL AND accepted_member_id IS NULL + """).param("id", id).param("actor", actor).update(); + } + + @Transactional + void cancelDirectInvitation(UUID household, UUID id, String actor) { + access.requireOwner(access.lockMember(household, actor)); + db.sql(""" + UPDATE household_direct_invitation SET closed_at=now() + WHERE id=:id AND household_id=:household AND closed_at IS NULL AND accepted_member_id IS NULL + """).param("id", id).param("household", household).update(); + } + + private record DirectAcceptance(String role, UUID memberId, String username) {} + private String editableSubject(UUID household, UUID memberId) { return db.sql(""" SELECT subject,role FROM household_member WHERE household_id=:household AND member_id=:id 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 a49466a..4bfde2f 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 @@ -31,6 +31,7 @@ final class InventoryDtos { record Preference(boolean favorite, @Min(1) @Max(5) Integer rating, @Size(max = 500) String note) {} record Detail(Item item, List moves, List relations, Preference preference) {} record Delivery(@NotNull UUID householdId, @NotBlank String actor, - @NotEmpty @Size(max = 30) List<@NotNull @Valid ItemInput> items) {} + @NotEmpty @Size(max = 30) List<@NotNull @Valid ItemInput> items, + @Size(max = 600) String expectedLocationPath) {} record DeliveryResult(String outcome) {} } 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 b58b0c3..ca0968c 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 @@ -25,13 +25,33 @@ 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)); + private static final String SCOPED_PATHS = "WITH paths AS (SELECT * FROM location_paths(:household))\n"; + private static final String SEARCH_HITS = """ + , hits AS ( + SELECT id, max(score) AS score FROM ( + SELECT id, CASE WHEN lower(name)=lower(:term) THEN 100 + WHEN lower(name) LIKE lower(:prefix) THEN 80 ELSE 60 END AS score + FROM item + WHERE household_id=:household AND archived_at IS NULL AND lower(name) LIKE lower(:pattern) + UNION ALL + SELECT item_id, CASE WHEN lower(alias)=lower(:term) THEN 90 + WHEN lower(alias) LIKE lower(:prefix) THEN 70 ELSE 50 END + FROM item_alias WHERE household_id=:household AND lower(alias) LIKE lower(:pattern) + UNION ALL + SELECT i.id, 30 FROM paths p JOIN item i + ON (i.household_id,i.location_id)=(p.household_id,p.id) + WHERE i.archived_at IS NULL AND lower(p.path) LIKE lower(:pattern) + ) matches GROUP BY id + ) + """; private static final String SELECT_ITEMS = """ SELECT i.*, p.path, 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 JOIN location_path p ON p.household_id=i.household_id AND p.id=i.location_id + FROM item i JOIN paths p ON p.household_id=i.household_id AND p.id=i.location_id + %s WHERE i.household_id=:household AND i.archived_at IS NULL """; private final JdbcClient db; @@ -44,7 +64,7 @@ class InventoryService { List locations(UUID household, String actor) { access.role(household, actor); - return db.sql("SELECT * FROM location_path WHERE household_id=:household ORDER BY path,id") + return db.sql("SELECT * FROM location_paths(:household) ORDER BY path,id") .param("household", household).query(LOCATION).list(); } @@ -54,7 +74,7 @@ class InventoryService { } private Location location(UUID household, UUID id) { - return db.sql("SELECT * FROM location_path WHERE household_id=:household AND id=:id") + return db.sql("SELECT * FROM location_paths(:household) WHERE id=:id") .param("household", household).param("id", id).query(LOCATION).optional() .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "位置不存在")); } @@ -66,7 +86,7 @@ class InventoryService { if (parent != null) { location(household, parent); if (id != null && db.sql(""" - SELECT :id = ANY(ancestors) FROM location_path WHERE household_id=:household AND id=:parent + SELECT :id = ANY(ancestors) FROM location_paths(:household) WHERE id=:parent """).param("id", id).param("parent", parent).param("household", household) .query(Boolean.class).single()) { throw new ResponseStatusException(CONFLICT, "不能移动到自己或子位置"); @@ -101,22 +121,28 @@ class InventoryService { List items(UUID household, String actor, String q, int limit, int offset, boolean favorites, UUID location) { access.role(household, actor); - return db.sql(SELECT_ITEMS + """ - AND (strpos(lower(i.name),lower(:q)) > 0 OR strpos(lower(p.path),lower(:q)) > 0 - OR EXISTS (SELECT FROM item_alias a WHERE a.household_id=i.household_id - AND a.item_id=i.id AND strpos(lower(a.alias),lower(:q)) > 0)) + String term = q.strip(); + boolean searching = !term.isEmpty(); + var query = db.sql(SCOPED_PATHS + (searching ? SEARCH_HITS : "") + + SELECT_ITEMS.formatted(searching ? "JOIN hits ON hits.id=i.id" : "") + """ AND (NOT :favorites OR EXISTS (SELECT FROM item_preference pref WHERE (pref.household_id,pref.item_id)=(i.household_id,i.id) AND pref.subject=:actor AND pref.favorite)) AND (CAST(:location AS uuid) IS NULL OR i.location_id=:location) - ORDER BY lower(i.name),i.id LIMIT :limit OFFSET :offset - """).param("household", household).param("q", q.strip()).param("limit", limit) - .param("offset", offset).param("favorites", favorites).param("actor", actor) - .param("location", location, Types.OTHER).query(ITEM).list(); + ORDER BY %s lower(i.name),i.id LIMIT :limit OFFSET :offset + """.formatted(searching ? "hits.score DESC," : "")) + .param("household", household).param("limit", limit).param("offset", offset) + .param("favorites", favorites).param("actor", actor).param("location", location, Types.OTHER); + if (searching) { + String escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_"); + query.param("term", term).param("prefix", escaped + "%").param("pattern", "%" + escaped + "%"); + } + return query.query(ITEM).list(); } private Item item(UUID household, UUID id) { - return db.sql(SELECT_ITEMS + " AND i.id=:id").param("household", household).param("id", id) + return db.sql(SCOPED_PATHS + SELECT_ITEMS.formatted("") + " AND i.id=:id") + .param("household", household).param("id", id) .query(ITEM).optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在")); } @@ -131,7 +157,7 @@ class InventoryService { var relations = db.sql(""" SELECT r.related_id,i.name,p.path,r.kind FROM item_relation r JOIN item i ON (i.household_id,i.id)=(r.household_id,r.related_id) - JOIN location_path p ON (p.household_id,p.id)=(i.household_id,i.location_id) + JOIN location_paths(:household) p ON (p.household_id,p.id)=(i.household_id,i.location_id) WHERE r.household_id=:household AND r.item_id=:id AND i.archived_at IS NULL ORDER BY i.name,i.id """).param("household", household).param("id", id).query((rs, row) -> new Relation( rs.getObject(1, UUID.class), rs.getString(2), rs.getString(3), @@ -267,7 +293,12 @@ class InventoryService { } try { access.requireWrite(household, delivery.actor()); - for (ItemInput input : delivery.items()) { location(household, input.locationId()); } + for (ItemInput input : delivery.items()) { + var place = location(household, input.locationId()); + if (delivery.expectedLocationPath() != null && !delivery.expectedLocationPath().equals(place.path())) { + throw new ResponseStatusException(CONFLICT, "录入位置已变化"); + } + } } catch (ResponseStatusException rejected) { db.sql("UPDATE delivered_operation SET outcome='REJECTED' WHERE id=:id") .param("id", operation).update(); diff --git a/backend/inventory-service/src/main/resources/db/migration/V6__search_indexes.sql b/backend/inventory-service/src/main/resources/db/migration/V6__search_indexes.sql new file mode 100644 index 0000000..7817715 --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V6__search_indexes.sql @@ -0,0 +1,22 @@ +CREATE EXTENSION IF NOT EXISTS pg_trgm; + +CREATE INDEX item_active_name_trgm ON item USING gin (lower(name) gin_trgm_ops) + WHERE archived_at IS NULL; +CREATE INDEX item_alias_text_trgm ON item_alias USING gin (lower(alias) gin_trgm_ops); + +CREATE FUNCTION location_paths(space_id uuid) +RETURNS TABLE (household_id uuid, id uuid, parent_id uuid, name text, path text, ancestors uuid[]) +LANGUAGE sql STABLE AS $$ + WITH RECURSIVE paths AS ( + SELECT l.household_id, l.id, l.parent_id, l.name, l.name AS path, ARRAY[l.id] AS ancestors + FROM location l + WHERE l.household_id = space_id AND l.parent_id IS NULL AND l.archived_at IS NULL + UNION ALL + SELECT child.household_id, child.id, child.parent_id, child.name, + paths.path || ' / ' || child.name, paths.ancestors || child.id + FROM location child JOIN paths + ON child.household_id = paths.household_id AND child.parent_id = paths.id + WHERE child.archived_at IS NULL AND NOT child.id = ANY(paths.ancestors) + ) + SELECT * FROM paths +$$; diff --git a/backend/inventory-service/src/main/resources/db/migration/V7__direct_invitations.sql b/backend/inventory-service/src/main/resources/db/migration/V7__direct_invitations.sql new file mode 100644 index 0000000..0aa434e --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V7__direct_invitations.sql @@ -0,0 +1,21 @@ +CREATE TABLE household_direct_invitation ( + id uuid PRIMARY KEY, + household_id uuid NOT NULL REFERENCES household(id) ON DELETE CASCADE, + recipient_subject text NOT NULL REFERENCES native_account(subject) ON DELETE CASCADE, + role text NOT NULL CHECK (role IN ('EDITOR', 'VIEWER')), + expires_at timestamptz NOT NULL, + closed_at timestamptz, + accepted_member_id uuid, + UNIQUE (household_id, recipient_subject), + CHECK (closed_at IS NULL OR accepted_member_id IS NULL) +); + +CREATE INDEX household_direct_invitation_inbox + ON household_direct_invitation(recipient_subject, expires_at) + WHERE closed_at IS NULL AND accepted_member_id IS NULL; + +CREATE TABLE household_invite_budget ( + actor text PRIMARY KEY, + day date NOT NULL, + used integer NOT NULL CHECK (used BETWEEN 1 AND 20) +); diff --git a/backend/tests/ios_experience_smoke.py b/backend/tests/ios_experience_smoke.py new file mode 100644 index 0000000..d9ea789 --- /dev/null +++ b/backend/tests/ios_experience_smoke.py @@ -0,0 +1,93 @@ +"""Validate iOS workflows in a disposable environment with a native_account row for viewer.""" +import concurrent.futures +from urllib.parse import urlencode + +from smoke import RUN, await_operation, call, ready + + +def verify(): + ready() + space = call("POST", "/api/households", {"name": "见物体验 " + RUN}, status=201) + root = "/api/households/" + space["id"] + try: + verify_search_and_voice(root) + verify_direct_invitations(root) + finally: + call("DELETE", root, status=202) + + +def verify_search_and_voice(root): + def location(name, parent=None): + return call("POST", root + "/locations", {"name": name, "parentId": parent}, status=201)["id"] + + room = location("书房") + drawer = location("右抽屉", room) + entry = location("玄关") + duplicate = location("右抽屉", entry) + + def item(name, place, aliases=None, quantity=1): + return {"name": name, "quantity": quantity, "locationId": place, "notes": "", "aliases": aliases or []} + + exact = call("POST", root + "/items", item("数据线", drawer), status=201)["id"] + alias = call("POST", root + "/items", item("充电配件", drawer, ["数据线"]), status=201)["id"] + prefix = call("POST", root + "/items", item("数据线收纳包", duplicate), status=201)["id"] + contains = call("POST", root + "/items", item("旧数据线备用", drawer), status=201)["id"] + percent = call("POST", root + "/items", item("标签%尺寸", entry), status=201)["id"] + + def search(term): + return [row["id"] for row in call("GET", root + "/items?" + urlencode({"q": term}))] + + assert search("数据线") == [exact, alias, prefix, contains] + assert set(search("书房 / 右抽屉")) == {exact, alias, contains} + assert search("%") == [percent] + call("GET", root + "/items?" + urlencode({"q": "数据线"}), user="other", status=404) + print("PASS scoped weighted name/alias/path search and literal wildcard", flush=True) + + def draft(text): + result = call("POST", root + "/drafts", {"text": text, "source": "VOICE"}, status=201) + assert result["status"] == "READY" and result["source"] == "VOICE" + return result + + for text in ("我没把钥匙放在书房右抽屉", "钥匙好像放在书房右抽屉", "两根线一个转接头放在书房右抽屉"): + assert draft(text)["candidates"] == [] + note = draft("我刚把两根转接线放在书房右抽屉了。") + assert note["candidates"] == [{"name": "转接线", "quantity": 2, "action": "RECORD", "location": "书房右抽屉了"}] + confirm = root + "/drafts/" + note["id"] + "/confirm" + payload = {"version": note["version"], "items": [item("转接线", duplicate, quantity=2)], "automatic": True} + call("POST", confirm, payload, status=409) + payload["items"][0]["locationId"] = drawer + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + operations = list(pool.map(lambda _: call("POST", confirm, payload, status=202), range(2))) + assert operations[0]["id"] == operations[1]["id"] + await_operation(root + "/operations/" + operations[0]["id"], "COMPLETED") + assert len(search("转接线")) == 1 + print("PASS voice rules, automatic location guard and one outbox delivery", flush=True) + + +def verify_direct_invitations(root): + sent = root + "/direct-invitations" + inbox = "/api/households/direct-invitations" + call("POST", sent, {"username": "unknown-" + RUN, "role": "VIEWER"}, status=202) + assert call("GET", sent) == [] + call("GET", root + "/items", user="viewer", status=404) + call("POST", sent, {"username": "ViEwEr", "role": "VIEWER"}, status=202) + call("POST", sent, {"username": "viewer", "role": "EDITOR"}, status=202) + outgoing, = call("GET", sent) + assert outgoing["username"] == "viewer" and outgoing["role"] == "VIEWER" + received, = [row for row in call("GET", inbox, user="viewer") if row["id"] == outgoing["id"]] + assert received["role"] == "VIEWER" + assert not any(row["id"] == outgoing["id"] for row in call("GET", inbox, user="other")) + accept = inbox + "/" + outgoing["id"] + "/accept" + call("POST", accept, user="other", status=404) + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(lambda _: call("POST", accept, user="viewer"), range(2))) + assert results[0] == results[1] and results[0]["role"] == "VIEWER" + call("GET", root + "/items", user="viewer") + call("POST", root + "/drafts", {"text": "数据线放在书房右抽屉", "source": "VOICE"}, user="viewer", status=403) + call("POST", sent, {"username": "other", "role": "EDITOR"}, user="viewer", status=403) + assert call("GET", sent) == [] + print("PASS addressed invitations, private inbox, atomic acceptance and role checks", flush=True) + + +if __name__ == "__main__": + verify() diff --git a/deploy/local/ci-smoke.sh b/deploy/local/ci-smoke.sh index 9fb472e..5cc5de8 100755 --- a/deploy/local/ci-smoke.sh +++ b/deploy/local/ci-smoke.sh @@ -32,3 +32,11 @@ if ! python3 backend/tests/smoke.py; then tail -80 /tmp/atlas-inventory.log /tmp/atlas-intake.log /tmp/atlas-gateway.log exit 1 fi +psql "$ATLAS_SMOKE_INVENTORY_DSN" -v ON_ERROR_STOP=1 <<'SQL' +INSERT INTO native_account(username, subject, password_hash) +VALUES ('viewer', 'viewer', 'ci-basic-auth-fixture'); +SQL +if ! python3 backend/tests/ios_experience_smoke.py; then + tail -80 /tmp/atlas-inventory.log /tmp/atlas-intake.log /tmp/atlas-gateway.log + exit 1 +fi diff --git a/docs/README.md b/docs/README.md index 17bc591..cecba56 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,8 +2,8 @@ | 阶段 | 内容 | | --- | --- | -| 产品 | [调研](product/research.md)、[产品设计](product/overview.md)、[需求与验收](product/requirements.md) | +| 产品 | [调研](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/ai-providers.md)、[可观测性](architecture/observability.md)、[两级缓存](architecture/cache.md) | +| 架构 | [系统架构](architecture/system.md)、[客户端选型](architecture/clients.md)、[语音、搜索和邀请](architecture/mobile-capture-and-search.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) | diff --git a/docs/architecture/mobile-capture-and-search.md b/docs/architecture/mobile-capture-and-search.md new file mode 100644 index 0000000..be30e2a --- /dev/null +++ b/docs/architecture/mobile-capture-and-search.md @@ -0,0 +1,56 @@ +# iOS 录入、检索和家庭邀请 + +## 录音到物品 + +```mermaid +flowchart LR + I[iPhone 麦克风] --> S[Apple 本机转写] + S --> E[可编辑的原话] + E --> D[录入服务规则提取] + E --> A[用户选择 AI 整理] + A --> O[家庭内网 Ollama] + D --> C[核对草稿] + O --> C + C --> W[幂等确认和 Outbox] + W --> P[物品服务事务写入] +``` + +iOS 只启动支持本机转写的普通话识别,麦克风采集最长 25 秒,结束后将转写文字交给录入服务。拒绝权限、设备不支持或听不清时仍可打字。音频在内存中处理。识别中的字可即时看见,结束后原话可编辑。 [Apple 语音识别](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest) + +`POST /api/households/{space}/drafts` 的 `source=VOICE` 调用规则,只识别一条明确的放置命令以及有限的数量表达。遇到否定、不确定、多件物品或超出语法的句子,返回空候选,保留原话。用户选择「用 AI 整理」才发起 `source=MODEL` 请求。旧客户端缺省字段时继续走模型。模型已有关闭思考、结构化校验、超时与单实例并发限制。 + +默认经确认后写入。开启本机账号级自动保存后,App 只对最终转写的单一候选提交 `automatic=true`。录入服务重新校验草稿来源、物品、数量和所在空间中唯一的完整位置路径。只说「右抽屉」时,即使可预填唯一的同名叶子,也保留确认步骤。部分转写、需要模型的文本和冲突候选保留确认。规则匹配表示句式和位置符合条件,语音误听仍可能,需要时经过界面修正。 + +确认操作复用已部署的 `draft_id + draft_version` 唯一键和 Outbox。物品服务事务内核对当前角色和位置,自动写入还会核对提交时记录的完整路径,位置被移走或改名时拒绝投递。投递重试仍使用同一操作号。完成才显示「已存入」。排错先核对用户角色、草稿来源和完整位置,再按操作号查日志与 Outbox 指标。音频、转写原话和空间名称不进入指标标签。 + +## 检索和权重 + +先校验空间成员身份。位置路径从当前空间根节点向下计算,名称和别名都先按空间过滤,归档物品不进结果。匹配保留字面量,用户键入 `%`、`_` 或反斜杠时按原字符查找。多个字段同时命中只取最高分,分页保持分数、名称和 ID 的顺序。空查询保持名称排序。 + +| 命中 | 分数 | +| --- | ---: | +| 完整名称 | 100 | +| 完整别名 | 90 | +| 名称前缀 | 80 | +| 别名前缀 | 70 | +| 名称包含 | 60 | +| 别名包含 | 50 | +| 位置路径 | 30 | + +PostgreSQL `pg_trgm` 给活跃物品名称和别名提供 GIN 索引,短中文词仍按空间匹配。选取执行计划由数据库决定,短词或小空间用空间索引过滤后扫描也合理。物品提交后直接可搜,查询与空间权限使用同一个数据库状态。 [PostgreSQL pg_trgm](https://www.postgresql.org/docs/17/pgtrgm.html) + +2026-11-26 在工作 Mac 使用合成数据验收。401 个空间共 104,000 件物品,目标空间 4,000 件。预热后用 6 个并发客户端,经网关交替查询「数据线」「HDMI」「线」,120 次请求每次取 20 条。API P50 约 209 毫秒,P95 约 267 毫秒。该结果包含本机 HTTP、鉴权和结果组装,现场网络与真实名称分布需另测。 + +当前部署用一个 SSD PostgreSQL。先按空间大小和查询长度观察网关、物品接口的 P95,再用真实类别和同音词样本检查命中。压测时分别覆盖小空间、单大空间、多空间并发和两字词。需要中文分词、拼写容错、复杂召回,或索引压测达到 PostgreSQL 的资源边界时,再用相同样本对比 Elasticsearch 的字段权重和 BM25。引入时保留 PostgreSQL 为主库,用 Outbox 增量同步并支持重建索引,服务端继续验证空间访问权限。 [Elastic 相关性调优](https://www.elastic.co/docs/troubleshoot/elasticsearch/troubleshooting-search-relevance) + +## 按账号邀请 + +所有者按完整见物账号提交,服务端只匹配启用的原生账号。公开接口无模糊账号搜索。发送端每天最多 20 次,空间最多 20 个活跃邀请。发送返回 202,发出的有效邀请可以由发送方查看和撤销,邀请只在对应接收者的收件列表出现。收到邀请本身不会获得物品权限。 + +接受时锁住空间,检查当事账号、状态与有效期,再在同一 PostgreSQL 事务写成员和接受记录。重复接受返回同一成员,撤销和接受并发时最多产生一个有效结果。设为查看者后仍由原有角色规则限制写入。旧邀请码继续支持已发送的邀请。手机号查找、好友关系和入群申请需要独立的隐私、验证和反滥用设计。 + +## 部署与验收 + +物品库 Flyway V6 安装 `pg_trgm`、搜索索引和按空间取路径的函数,V7 建邀请及额度表。录入库 V3 为草稿加来源。扩展随 PostgreSQL 镜像提供,部署账号需要目标数据库的 `CREATE` 权限。索引迁移会消耗 CPU、磁盘并占用写入时间,大库按实测安排发布窗口。部署前备份,先在隔离环境迁移并跑 `backend/tests/ios_experience_smoke.py`,然后核对公网版本与手机签名包。部署继续使用现有网关、PostgreSQL、Ollama 与 Helm 配置。 [后端发布与回退](../deployment/backend-release.md) + +回退旧镜像时保留新增的索引、表和列,先验证旧版客户端和草稿路径。新版 iOS 的邀请与语音规则依赖对应的服务版本,演示前配套核对。 diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md new file mode 100644 index 0000000..77dda73 --- /dev/null +++ b/docs/product/ios-experience.md @@ -0,0 +1,19 @@ +# 见物 iOS 日常使用 + +## 首页 + +入口用「家里有的,心里有数。」和一张家里随手放东西的场景画。用一句实话演示见物的用途,例如「数据线放在书房抽屉」。下方直接进入自己的空间。首次使用时可以新建空空间,或在空间列表里接受家人的邀请。 + +## 一句话录入 + +在录入页点麦克风,说完点停止。转写文字留在输入框,可直接修改。系统先从一句话取出物品、数量和位置,给用户看实际准备保存的内容。默认核对后保存。选择自动保存时,只直接提交规则能完整解析的一件物品,且位置必须对应当前空间内唯一的完整路径。保存成功提示「已存入」,点「知道了」收起。 + +含否定、不确定位置、多个物品或者无法匹配位置的原话交给用户核对。可以改文字、选位置、手工记一件,或明确点「用 AI 整理」。这几步保存共用现有物品确认操作,重复提交只交付一次。 + +## 家庭邀请 + +空间所有者输入对方的见物账号并选择角色。对方在「我的空间」看到邀请,接受后才获得访问权限。单独用手机号查找需要可验证的手机号和防枚举机制,首版按用户已知的见物账号精确发送。现有码仍可兑换。 + +## 找物 + +搜索框接收名称、别名和位置。完整名称优先于完整别名,再排前缀、包含和位置。结果优先露出位置路径。录入或改名后,搜索直接读到数据库提交的结果。 diff --git a/docs/product/requirements.md b/docs/product/requirements.md index 7343906..dadcd39 100644 --- a/docs/product/requirements.md +++ b/docs/product/requirements.md @@ -7,7 +7,7 @@ | R01 | 家庭和角色 | 登录后按当前账号展示空间。新空间显示空状态。两户数据互相隔离。所有者可签发和撤销邀请、调整普通成员角色及移除成员。两人同时兑换同一邀请时只有一人加入。查看者可找物,降权或移除后用原登录凭据也只能执行当前权限允许的请求。 | | R02 | 多层位置 | 可以建立房间、柜子、收纳盒。同名位置显示完整路径。禁止把上级移动到子节点下,有活动物品或下级的位置归档前须先处理关联。 | | R03 | 物品和移位 | 可以新增、修改、移位和归档物品。移位后同时查到当前和原来的位置,用旧版本写入时提示冲突。 | -| R04 | 搜索 | 可以按名称、别名和位置找物。结果带完整位置路径。 | +| R04 | 搜索 | 可以按名称、别名和位置找物。完整名称优先于完整别名和部分匹配,结果带完整位置路径。 | | R05 | 物品关联 | 可以关联同一家庭里的配件、同类或常一起使用的物品。详情显示关联物品的位置。 | | R06 | 批量草稿 | 同一句能拆成多条,处理数量、否定和不确定的位置。确认后可以查处理状态,同一次确认只写入一次。 | | R07 | 模型状态 | 模型待配置或不可用时显示对应状态,原始输入保留,可继续手工录入。云端调用由用户选择。 | @@ -16,7 +16,9 @@ ## 质量要求 -- iOS 首次打开可浏览产品首页和使用说明。账号密码在 App 内提交,成功后请求账号空间。登录页可返回首页,连接失败可重试。 +- iOS 首次打开可查看产品首页。账号密码在 App 内提交,成功后请求账号空间。登录页可返回首页,连接失败可重试。 +- 家庭支持按见物账号发送邀请。接收者确认后才获得指定空间的角色。 +- iOS 录音优先本机转写,明确的一句话由规则提取。默认确认后保存,自动保存只适用于验证通过的单件物品与完整位置。 - 不确定的提交结果可通过操作状态查询。确认失败时留下可恢复的草稿。 - 用带名称、别名、位置和数量的演示数据验证,有实际运行结果后再填写命中率、耗时和人工修正数。 - 备份恢复后核对物品、位置、历史和关系。演示使用独立数据。 diff --git a/docs/testing/cases.md b/docs/testing/cases.md index f2a444b..74fa552 100644 --- a/docs/testing/cases.md +++ b/docs/testing/cases.md @@ -23,8 +23,11 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前 | TC-17 照片裁剪和图片限制 | R09 | 选一张长图裁剪上传,分别读取清晰大图和缩略图。尝试上传超限或伪装格式的文件。 | 列表显示小图、详情显示裁剪结果,超限或不合法的图片被拒绝。 | | TC-18 删除及 OSS 清理 | R09 | 分别删除照片、物品和空间,另用后台删除有图片的空间。暂停对象存储再恢复。 | 访问立即失效,原图和缩略图最终都被删掉。存储故障期间可观察到重试。 | | TC-19 iOS 收起键盘 | 质量 | 在搜索、物品备注和批量录入分别输入中文,使用「收起键盘」。 | 键盘收起,已输入文字保留。 | -| TC-20 iOS 原生登录页 | R01 | 在未登录状态打开 App,查看并关闭使用说明。点「登录我的空间」,切换密码显隐,再返回。 | 原生导航打开表单,输入和错误都在 App 内。返回后清除密码,空间入口仍需登录。 | +| TC-20 iOS 原生登录页 | R01 | 在未登录状态打开 App。点「进入我的空间」,切换密码显隐,再返回。 | 原生导航打开表单,输入和错误都在 App 内。返回后清除密码,空间入口仍需登录。 | | TC-21 iOS 登录失败和重试 | R01 | 在原生表单提交错误密码,再断网提交。恢复网络,用正确账号密码继续。 | 表单分别提示凭据错误和网络失败,提交中禁止重复登录,恢复后显示当前账号空间。 | | TC-22 原生会话与权限 | R01 | 新会话查空间与模型提供方,尝试管理 API。刷新后用旧令牌重试,再退出。 | 两个业务服务都接受有效会话。普通账号无法访问管理 API。刷新令牌只用一次,退出后不可续期。 | +| TC-23 搜索评分与空间 | R04 | 同一空间创建完整名称、别名、前缀和包含同一词的物品。另测查询位置、百分号及从其他账号查该空间。 | 结果按得分排序,位置可搜,百分号按字面匹配,跨空间读取被拒绝。 | +| TC-24 语音和自动保存 | R06 | 点麦克风说「我把两根转接线放在书房右抽屉」。分别关闭和开启自动保存,再测试「好像」和同名抽屉。 | 完整路径唯一时按设置确认或自动保存,成功才弹出回执。否定、模糊位置、只转写部分等情况保留手动核对。 | +| TC-25 按账号邀请 | R01 | 所有者邀请查看者,另一个账号尝试读取和接受。被邀请者同时接受两次,并尝试写入。 | 只有本人看到邀请并加入,两次接受返回同一成员,查看者不能写入。 | [测试与演示计划](plan.md) diff --git a/docs/ui/ios-welcome.md b/docs/ui/ios-welcome.md index ab9e385..c0e5560 100644 --- a/docs/ui/ios-welcome.md +++ b/docs/ui/ios-welcome.md @@ -8,44 +8,38 @@ | 页面 | 布局与交互 | | --- | --- | -| 欢迎 | 一张家里的抽屉照片和找物、批量记录、家庭共享的用途。主入口进入原生登录,使用说明离线可看。 | +| 欢迎 | 生活场景和标题放在同一画面,下方用一句口语演示录入。主入口进入原生登录。 | | 登录 | 系统返回按钮、小品牌行、大标题和两个带明确标签的原生输入框。密码默认隐藏,可切换显示。 | | 找物与收藏 | 搜索框贴近标题,缩略图左对齐,物品名和完整位置路径置于同一行组。保留可见的空结果和清除搜索动作。 | | 详情 | 标题、照片、完整位置路径依次展示。移位和编辑靠近位置,按角色展示可用动作。 | | 位置和录入 | 位置按房间、柜子、收纳盒逐层打开。录入先输入再核对草稿,保留原话、重试和手工录入。 | -方向稿属于视觉参考,稿里的物品只用于说明设计。当前改版先完成原生登录,其余业务页按这一套层级逐页更新。 +方向稿用于说明主要页面结构。首页以下面最新的文案和主图为准。 ## 首次打开 -打开见物,先说明它能帮人找回家里的东西。首页从上到下放小号品牌标识、标题、收纳场景照片和三条用途。底部是「登录我的空间」和「看看怎么用」。首页和使用说明可以在离线时打开。 +首页上方是见物标识。光线偏暖的玄关照片占主要空间,标题放在照片留出的深色区域。照片下方用一句实际的录入场景说明用途。底部保留单个主入口。 [首页主图](../../apps/ios/ItemAtlas/Assets.xcassets/WelcomeTray.imageset/WelcomeTray.jpg) ```text 见物 - 放在哪里, - 一找就知道。 - 记下家里的东西和位置,下次需要时,搜一下就能找到。 + [ 家里有的, ] + [ 心里有数。 ] + [ 玄关托盘里的物品 ] - [ 家里拉开的抽屉 ] + 说一句「数据线放在书房抽屉」,见物帮你记下。 - 搜名字就能找 显示物品放在哪一层 - 一次记几件 整理好草稿再确认 - 和家人一起找 用邀请码加入同一个空间 - - [ 登录我的空间 ] - 看看怎么用 + [ 进入我的空间 ] ``` -- 点「看看怎么用」打开原生说明页,介绍记录位置、搜索别名和邀请家人。关掉后回到首页。 -- 登录前的场景照片和使用说明是产品介绍。用户确认账号后才加载空间。新账号可新建或通过邀请码加入,空空间按空状态显示。 -- 背景用浅暖灰,按钮和图标沿用见物的蓝色。图片裁切保留抽屉主体。深色模式使用系统背景,标题、说明和按钮随 Dynamic Type 调整。小屏和大字号允许向下滚动。 +- 登录后才加载空间。新账号可新建空空间,或在空间列表接受邀请。 +- 深色模式跟随系统。辅助字号下标题移至照片上方,避免文字遮住物品,小屏可滚动。 ## 登录过程 | 状态 | 用户看到的内容 | | --- | --- | -| 点「登录我的空间」 | 在当前 SwiftUI 导航栈推入原生登录页,系统返回键回到欢迎页。 | +| 点「进入我的空间」 | 在当前 SwiftUI 导航栈推入原生登录页,系统返回键回到欢迎页。 | | 输入账号和密码 | 键盘 Next 进入密码框,支持系统密码填充和切换密码显隐。 | | 提交 | 键盘收起,按钮显示「正在登录…」并禁止重复请求。成功后显示当前账号的空间。 | | 连接或验证失败 | 错误在表单内显示,允许修正后重试。 |