import SwiftUI struct IntakeView: View { let store: InventoryStore var initialLocation: Place? = nil @Environment(\.scenePhase) private var scenePhase @Environment(\.dismiss) private var dismiss @AppStorage("atlas.voice.recording-mode") private var recordingMode: RecordingMode = .tap @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 showingHelp = false private enum RecordingMode: String { case tap, hold } private struct Draft: Decodable { let id: UUID let originalText: String let candidates: [Candidate] let status: 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] } private var canParse: Bool { !busy && voice.phase == .idle && operation == nil && text.utf16.count <= 4000 && !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } var body: some View { ScrollViewReader { scroll in ScrollView { VStack(alignment: .leading, spacing: 14) { if let initialLocation { Label(initialLocation.path, systemImage: "mappin") .font(.subheadline).foregroundStyle(.secondary) .accessibilityLabel("默认位置," + initialLocation.path) } smartCard manualEntry if voice.phase == .idle && operation == nil { inputCard if let draft { reviewCard(draft).id(draft.id) } } if let operation { operationCard(operation) } if let error { Text(error).font(.callout).foregroundStyle(.red) } } .frame(maxWidth: 560) .padding(16) .frame(maxWidth: .infinity) } .onChange(of: draft?.id) { _, id in if let id { withAnimation { scroll.scrollTo(id, anchor: .top) } } } } .background(Color(uiColor: .systemGroupedBackground)) .scrollDismissesKeyboard(.interactively) .dismissibleKeyboard(active: typing) { typing = false } .navigationTitle("录入物品") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() }.disabled(busy) } ToolbarItem(placement: .topBarTrailing) { Button { showingHelp = true } label: { Label("录入说明", systemImage: "questionmark.circle") } .disabled(voice.phase != .idle) } } .interactiveDismissDisabled(busy || voice.phase != .idle) .sensoryFeedback(.start, trigger: voice.phase) { _, phase in phase == .recording } .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 = [:] } } .sheet(isPresented: $showingHelp) { help } .sheet(isPresented: $showingAdd) { ItemEditor(store: store, initialLocation: initialLocation?.id) } } private var smartCard: some View { VStack(alignment: .leading, spacing: 12) { HStack(alignment: .firstTextBaseline) { Text("智能录入").font(.title3.weight(.semibold)) .accessibilityAddTraits(.isHeader) Spacer() Menu { Picker("录音方式", selection: $recordingMode) { Text("点按开始,再点结束").tag(RecordingMode.tap) Text("按住录音,松手结束").tag(RecordingMode.hold) } } label: { Label(recordingMode == .hold ? "按住说" : "点按录音", systemImage: "chevron.up.chevron.down") .font(.subheadline.weight(.medium)) } .accessibilityLabel("录音方式") .accessibilityValue(recordingMode == .hold ? "按住说" : "点按录音") .disabled(voice.phase != .idle) } Text("说出要记的物品,例如「记录两根数据线」。") .font(.subheadline).foregroundStyle(.secondary) voiceButton if voice.phase == .recording || voice.phase == .finishing { ProgressView(value: Double(voice.elapsedSeconds), total: Double(VoiceCapture.maximumDuration)) { Text("\(voice.elapsedSeconds) / \(VoiceCapture.maximumDuration) 秒") .font(.caption.monospacedDigit()) } } if !voice.transcript.isEmpty { Text(voice.transcript).font(.callout) .frame(maxWidth: .infinity, alignment: .leading) } if let error = voice.error { Text(error).font(.footnote).foregroundStyle(.secondary) } } .padding(16) .background(Color.atlasBlue.opacity(0.10), in: .rect(cornerRadius: 20)) } private var manualEntry: some View { Button { showingAdd = true } label: { HStack(spacing: 13) { Image(systemName: "square.and.pencil") .font(.headline) .foregroundStyle(Color.atlasBlue) .frame(width: 36, height: 36) .background(Color.atlasBlue.opacity(0.10), in: .rect(cornerRadius: 10)) .accessibilityHidden(true) VStack(alignment: .leading, spacing: 3) { Text("手动添加").font(.headline).foregroundStyle(.primary) Text("填写名称、照片和备注").font(.subheadline).foregroundStyle(.secondary) } Spacer() Image(systemName: "chevron.right").font(.footnote.weight(.semibold)) .foregroundStyle(.tertiary).accessibilityHidden(true) } .frame(maxWidth: .infinity, alignment: .leading) .padding(14) .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16)) .contentShape(.rect(cornerRadius: 16)) } .buttonStyle(.plain) .accessibilityIdentifier("intake.manual") .disabled(voice.phase != .idle || busy) } private var inputCard: some View { VStack(alignment: .leading, spacing: 10) { Text("物品描述").font(.headline).accessibilityAddTraits(.isHeader) TextField("录音文字会显示在这里,也可以直接输入", text: $text, axis: .vertical) .lineLimit(3...7) .focused($typing) .accessibilityLabel("物品描述") .disabled(busy) if text.utf16.count > 4000 { Text("最多 4,000 字,可以分开整理。").font(.footnote).foregroundStyle(.secondary) } if !text.isEmpty && draft == nil { Button("整理成物品草稿") { typing = false; Task { await parse() } }.disabled(!canParse) } if busy && draft == nil { ProgressView("正在整理") } } .padding(16) .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16)) } private func reviewCard(_ draft: Draft) -> some View { VStack(alignment: .leading, spacing: 12) { Text("核对物品").font(.headline).accessibilityAddTraits(.isHeader) if draft.candidates.isEmpty { Text(draft.status == "MODEL_UNAVAILABLE" ? "AI 暂不可用,可以重试或手动添加。" : "这段话还没整理出物品,可以修改原话或用 AI 整理。") .font(.callout).foregroundStyle(.secondary) Button("用 AI 整理") { typing = false; Task { await parse(source: "MODEL") } } .disabled(!canParse) } ForEach(draft.candidates.indices, id: \.self) { index in let candidate = draft.candidates[index] if candidate.action == "SKIP" { Text("\(candidate.name) · 跳过").font(.callout).foregroundStyle(.secondary) } else { VStack(alignment: .leading, spacing: 4) { Text("\(candidate.name) ×\(candidate.quantity ?? 1)").font(.subheadline.weight(.semibold)) if let hint = candidate.location, !hint.isEmpty, selections[index] == nil { Text("原话位置 · " + hint).font(.footnote).foregroundStyle(.secondary) } LocationPicker(store: store, selection: Binding(get: { selections[index] }, set: { selections[index] = $0 }), title: "存放位置", allowsClearing: true) } .padding(12) .background(Color(uiColor: .systemGroupedBackground), in: .rect(cornerRadius: 12)) } } if draft.candidates.contains(where: { $0.action != "SKIP" }) { Button { typing = false; Task { await submit(draft) } } label: { Text("保存物品").frame(maxWidth: .infinity).padding(.vertical, 4) } .buttonStyle(.borderedProminent) .disabled(busy) } if busy { ProgressView(draft.candidates.isEmpty ? "正在整理" : "正在保存") } } .padding(16) .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16)) } private func operationCard(_ operation: Operation) -> some View { VStack(alignment: .leading, spacing: 10) { Text(statusText(operation.status)).font(.headline) if busy { ProgressView() } else if operation.status == "COMPLETED" { Button("继续录入") { reset(clearText: true) } } else if ["FAILED", "REJECTED"].contains(operation.status) { Button("返回核对") { reset(clearText: false) } } else if operation.status == "NEEDS_REVIEW" { Button("重试交付") { Task { await retry(operation) } } } else { Button("刷新进度") { Task { await poll(operation) } } } } .frame(maxWidth: .infinity, alignment: .leading) .padding(16) .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16)) } private var help: some View { NavigationStack { List { Section("智能录入") { Text("1. 点按开始录音,或者选择按住录音。") Text("2. 看到录音状态再说。一次最多 25 秒,可以停顿。") Text("3. 说完松手或再次点按。可以修改转写,也可以直接打字。") Text("4. 核对物品后保存。位置可以调整、清除或留空。") } Section("手动添加") { Text("填写名称就能录入单件物品。需要时再加位置、照片或备注。") } } .navigationTitle("怎么录入") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .confirmationAction) { Button("完成") { showingHelp = false } } } } } private var voiceEnabled: Bool { !busy && operation == nil && voice.phase != .finishing } @ViewBuilder private var voiceButton: some View { if recordingMode == .tap { Button(action: toggleRecording) { recordingLabel } .buttonStyle(.plain) .disabled(!voiceEnabled) } else { recordingLabel .accessibilityHidden(true) .overlay { HoldRecordingControl(label: recordingTitle, enabled: voiceEnabled, onPress: beginRecording, onRelease: { voice.stop() }, onAccessibilityActivate: toggleRecording) } } } private var recordingTitle: String { switch voice.phase { case .idle: recordingMode == .hold ? "按住说" : "开始录音" case .preparing: "麦克风准备中" case .recording: recordingMode == .hold ? "松手结束" : "结束录音" case .finishing: "正在转写" } } private var recordingLabel: some View { Label(recordingTitle, systemImage: voice.phase == .recording ? "waveform" : "mic.fill") .font(.headline) .frame(maxWidth: .infinity, minHeight: 54) .foregroundStyle(.white) .background(voice.phase == .recording ? Color.atlasNavy : Color.atlasBlue, in: .rect(cornerRadius: 14)) .opacity(voiceEnabled ? 1 : 0.55) .contentShape(Rectangle()) } private func toggleRecording() { if voice.phase == .idle { beginRecording() } else { voice.stop() } } private func beginRecording() { guard voiceEnabled, voice.phase == .idle else { return } typing = false voice.start(context: store.locations.map(\.name)) { phrase, complete in let previous = text.trimmingCharacters(in: .whitespacesAndNewlines) text = previous.isEmpty ? phrase : previous + "\n" + phrase if complete { Task { await parse() } } } } private func parse(source: String = "VOICE") async { guard canParse else { return } let original = text busy = true defer { busy = false } error = nil do { try await store.refreshLocations() let result: Draft = try await store.send(store.root + "/drafts", ["text": original, "source": source]) guard text == original else { return } draft = result selections = Dictionary(uniqueKeysWithValues: result.candidates.enumerated().compactMap { index, candidate in guard candidate.action != "SKIP", let place = IntakeLocationMatcher.match(candidate.location, locations: store.locations, defaultID: initialLocation?.id) else { return nil } return (index, place) }) } catch { self.error = error.localizedDescription } } private func submit(_ draft: Draft) async { guard draft.originalText == text, !busy, operation == nil, voice.phase == .idle else { return } let items = draft.candidates.enumerated().compactMap { index, candidate -> ItemInput? in guard candidate.action != "SKIP" else { return nil } return ItemInput(name: candidate.name, quantity: candidate.quantity ?? 1, notes: "", locationId: selections[index], aliases: []) } guard !items.isEmpty else { return } 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)) operation = accepted await poll(accepted) } catch { self.error = error.localizedDescription } } private func reset(clearText: Bool) { if clearText { text = "" } draft = nil selections = [:] operation = nil error = nil } 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(inventorySummaryChanged: true) 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: "正在录入" } } }