item-atlas/apps/ios/ItemAtlas/IntakeView.swift

277 lines
14 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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] = [:]
@State private var operation: Operation?
@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 {
let name: String
let quantity: Int?
let action: String
let location: String?
}
private struct Operation: Decodable { let id: UUID; let status: String }
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("说句话,记下来") {
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" {
Text("\(candidate.name) · 跳过").foregroundStyle(.secondary)
} else {
VStack(alignment: .leading) {
Text("\(candidate.name) ×\(candidate.quantity ?? 1)")
if let hint = candidate.location, !hint.isEmpty {
Text("原话位置:\(hint)").font(.footnote).foregroundStyle(.secondary)
}
Picker("确认位置", selection: Binding(get: { selections[index] }, set: { selections[index] = $0 })) {
Text("不录入").tag(nil as UUID?)
ForEach(store.locations) { place in Text(place.path).tag(Optional(place.id)) }
}
}.disabled(operation != nil)
}
}
if !draft.candidates.isEmpty {
Button("确认保存") { Task { await submit(draft) } }
.disabled(busy || selections.isEmpty || operation != nil)
}
}
}
if let operation {
Section {
Text(statusText(operation.status))
if ["COMPLETED", "FAILED", "REJECTED"].contains(operation.status) {
Button("新的录入") { draft = nil; selections = [:]; text = ""; self.operation = nil }
} else if operation.status == "NEEDS_REVIEW" {
Button("重试交付") { Task { await retry(operation) } }.disabled(busy)
} else {
Button("刷新进度") { Task { await poll(operation) } }.disabled(busy)
}
}
}
if busy { ProgressView() }
if let error { Text(error).foregroundStyle(.red) }
}
.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("录入")
}
}
}
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()
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 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: [])
}
busy = true
defer { busy = false }
do {
let accepted: Operation = try await store.send(store.root + "/drafts/\(draft.id)/confirm",
Confirm(version: draft.version, items: items, automatic: automatic))
operation = accepted
await poll(accepted)
} catch {
if automatic { receipt = nil }
self.error = error.localizedDescription
}
}
private func retry(_ operation: Operation) async {
busy = true
defer { busy = false }
do {
let path = store.root + "/operations/\(operation.id)/retry"
let bytes = try await store.account.request(path, method: "POST")
let accepted = try JSONDecoder().decode(Operation.self, from: bytes)
self.operation = accepted
await poll(accepted)
} catch { self.error = error.localizedDescription }
}
private func poll(_ current: Operation) async {
busy = true
defer { busy = false }
error = nil
do {
for _ in 0..<12 {
let status: Operation = try await store.get(store.root + "/operations/\(current.id)")
operation = status
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))
}
} catch { self.error = error.localizedDescription }
}
private func statusText(_ status: String) -> String {
switch status {
case "COMPLETED": "物品已录入"
case "FAILED", "REJECTED": "录入失败,请核对空间权限与位置"
case "NEEDS_REVIEW": "录入结果待核对,可以重试交付"
default: "正在录入"
}
}
}