diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index f70ad06..9878911 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 = 22; + CURRENT_PROJECT_VERSION = 23; 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 = 22; + CURRENT_PROJECT_VERSION = 23; GENERATE_INFOPLIST_FILE = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; diff --git a/apps/ios/ItemAtlas/LocationFloorDrawing.swift b/apps/ios/ItemAtlas/LocationFloorDrawing.swift new file mode 100644 index 0000000..0676462 --- /dev/null +++ b/apps/ios/ItemAtlas/LocationFloorDrawing.swift @@ -0,0 +1,246 @@ +import SwiftUI + +struct LocationPlanCanvas: View { + let width: Int + let depth: Int + let locations: [LayoutLocation] + let selected: UUID? + let editing: Bool + let open: (UUID) -> Void + var change: ((UUID, LocationGeometry) -> Void)? = nil + + var body: some View { + GeometryReader { proxy in + let scale = max(0.001, min((proxy.size.width - 20) / CGFloat(width), (proxy.size.height - 20) / CGFloat(depth))) + let board = CGSize(width: CGFloat(width) * scale, height: CGFloat(depth) * scale) + ZStack { + RoundedRectangle(cornerRadius: 8).fill(Color(uiColor: .secondarySystemGroupedBackground)) + ZStack(alignment: .topLeading) { + PlanGrid() + ForEach(locations) { place in + if let geometry = place.geometry { + PlanTile(place: place, geometry: geometry, scale: scale, + selected: selected == place.id, editing: editing, + open: { open(place.id) }, change: { change?(place.id, $0) }) + .zIndex(geometry.template.kind == .furniture ? (selected == place.id ? 3 : 2) : (selected == place.id ? 1 : 0)) + } + } + } + .frame(width: board.width, height: board.height) + .overlay { Rectangle().strokeBorder(.secondary.opacity(0.2), lineWidth: 1).allowsHitTesting(false) } + if locations.isEmpty { + Text("摆放位置后会显示在这里") + .font(.footnote).foregroundStyle(.secondary).allowsHitTesting(false) + } + } + .clipped() + } + .frame(height: editing ? 330 : 275) + .accessibilityElement(children: .contain) + .accessibilityLabel("位置俯视图") + .accessibilityIdentifier("location.floor.canvas") + } +} + +private struct PlanGrid: View { + var body: some View { + Canvas { context, size in + var lines = Path() + for x in stride(from: CGFloat(0), through: size.width, by: 14) { + lines.move(to: CGPoint(x: x, y: 0)) + lines.addLine(to: CGPoint(x: x, y: size.height)) + } + for y in stride(from: CGFloat(0), through: size.height, by: 14) { + lines.move(to: CGPoint(x: 0, y: y)) + lines.addLine(to: CGPoint(x: size.width, y: y)) + } + context.stroke(lines, with: .color(.secondary.opacity(0.13)), lineWidth: 1) + } + .allowsHitTesting(false) + .accessibilityHidden(true) + } +} + +private struct PlanTile: View { + let place: LayoutLocation + let geometry: LocationGeometry + let scale: CGFloat + let selected: Bool + let editing: Bool + let open: () -> Void + let change: (LocationGeometry) -> Void + @GestureState private var move = CGSize.zero + @GestureState private var resize = CGSize.zero + + private var width: CGFloat { max(4, CGFloat(geometry.widthMm) * scale + resize.width) } + private var depth: CGFloat { max(4, CGFloat(geometry.depthMm) * scale + resize.height) } + + var body: some View { + ZStack(alignment: .topLeading) { + let tile = LocationFloorArt(template: geometry.template, rotation: geometry.rotation) + .overlay(alignment: geometry.template.kind == .room ? .topLeading : .bottom) { + if width > 29 && depth > 17 { + Text(place.name) + .font(.caption2.weight(.semibold)) + .lineLimit(1) + .padding(.horizontal, 4).padding(.vertical, 2) + .background(.regularMaterial, in: .rect(cornerRadius: 4)) + .padding(2) + .allowsHitTesting(false) + } + } + .frame(width: width, height: depth) + .overlay { + if selected { RoundedRectangle(cornerRadius: 4).stroke(Color.atlasBlue, lineWidth: 2) } + } + .contentShape(Rectangle()) + if editing { + tile + .onTapGesture(perform: open) + .highPriorityGesture(DragGesture(minimumDistance: 4, coordinateSpace: .global) + .updating($move) { value, state, _ in state = value.translation } + .onEnded { value in + var edited = geometry + edited.xMm += millimeters(value.translation.width) + edited.yMm += millimeters(value.translation.height) + change(edited) + }) + .accessibilityAddTraits(.isButton) + .accessibilityAction { open() } + } else { + Button(action: open) { tile }.buttonStyle(.plain) + } + if selected && editing { + Circle() + .fill(Color.atlasBlue) + .overlay { Circle().strokeBorder(.white, lineWidth: 2) } + .frame(width: 15, height: 15) + .frame(width: 40, height: 40) + .contentShape(Rectangle()) + .highPriorityGesture(DragGesture(minimumDistance: 3, coordinateSpace: .global) + .updating($resize) { value, state, _ in state = value.translation } + .onEnded { value in + var edited = geometry + edited.widthMm += millimeters(value.translation.width) + edited.depthMm += millimeters(value.translation.height) + change(edited) + }) + .position(x: width, y: depth) + .accessibilityHidden(true) + } + } + .frame(width: width, height: depth, alignment: .topLeading) + .position(x: CGFloat(geometry.xMm) * scale + width / 2 + move.width, + y: CGFloat(geometry.yMm) * scale + depth / 2 + move.height) + .accessibilityLabel(place.name) + } + + private func millimeters(_ points: CGFloat) -> Int { + Int((points / scale / 100).rounded()) * 100 + } +} + +struct LocationFloorArt: View { + let template: LocationTemplate + let rotation: Int + @Environment(\.colorScheme) private var scheme + + private struct Piece { + let x: CGFloat + let y: CGFloat + let w: CGFloat + let h: CGFloat + let color: Color + let radius: CGFloat + + init(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat, _ color: Color, _ radius: CGFloat = 5) { + self.x = x; self.y = y; self.w = w; self.h = h + self.color = color; self.radius = radius + } + } + + private let sage = Color(red: 0.55, green: 0.66, blue: 0.54) + private let pale = Color(red: 0.77, green: 0.82, blue: 0.64) + private let tan = Color(red: 0.85, green: 0.69, blue: 0.53) + private let cream = Color(red: 0.97, green: 0.91, blue: 0.78) + private let wood = Color(red: 0.65, green: 0.43, blue: 0.34) + private let slate = Color(red: 0.33, green: 0.40, blue: 0.47) + + var body: some View { + if template.kind == .furniture { + GeometryReader { proxy in + let sideways = rotation % 180 != 0 + let width = sideways ? proxy.size.height : proxy.size.width + let height = sideways ? proxy.size.width : proxy.size.height + furnishing.frame(width: width, height: height) + .rotationEffect(.degrees(Double(rotation))) + .position(x: proxy.size.width / 2, y: proxy.size.height / 2) + } + } else { + room + } + } + + private var room: some View { + let tint = template == .bathroom || template == .kitchen || template == .balcony ? Color.teal : Color.brown + return RoundedRectangle(cornerRadius: 4) + .fill(tint.opacity(scheme == .dark ? 0.26 : 0.16)) + .overlay { + RoundedRectangle(cornerRadius: 4) + .strokeBorder(tint.opacity(0.76), style: StrokeStyle(lineWidth: template.kind == .room ? 1.6 : 1, dash: template.kind == .area ? [4, 3] : [])) + } + } + + private var furnishing: some View { + Canvas { context, size in + let shapes = pieces + let left = (shapes.map(\.x).min() ?? 0) - 2 + let top = (shapes.map(\.y).min() ?? 0) - 2 + let right = (shapes.map { $0.x + $0.w }.max() ?? 100) + 2 + let bottom = (shapes.map { $0.y + $0.h }.max() ?? 70) + 2 + let sx = size.width / (right - left), sy = size.height / (bottom - top) + for part in shapes { + let rect = CGRect(x: (part.x - left) * sx, y: (part.y - top) * sy, + width: part.w * sx, height: part.h * sy) + let path = Path(roundedRect: rect, cornerRadius: part.radius * min(sx, sy)) + context.fill(path, with: .color(part.color)) + context.stroke(path, with: .color(.black.opacity(0.4)), lineWidth: min(1.3, max(0.45, min(sx, sy)))) + } + } + .allowsHitTesting(false) + } + + private var pieces: [Piece] { + switch template { + case .sofa: + [.init(4,6,105,39,sage,10), .init(74,30,35,38,sage,9), + .init(15,16,25,20,pale), .init(41,16,25,20,pale), .init(67,16,25,20,pale), + .init(80,37,22,23,pale), .init(97,13,12,48,sage)] + case .bed: + [.init(17,4,74,86,tan,8), .init(21,9,66,12,wood), + .init(24,16,28,17,cream), .init(56,16,28,17,cream), + .init(22,35,64,49,cream,7), .init(22,65,64,19,sage)] + case .tvStand: + [.init(5,12,106,47,tan,7), .init(32,22,51,9,slate), .init(11,11,94,14,slate), + .init(12,39,28,13,cream), .init(44,39,28,13,cream), .init(76,39,27,13,cream)] + case .wardrobe: + [.init(5,10,104,48,wood), .init(10,15,22,38,tan), .init(34,15,22,38,tan), + .init(58,15,22,38,tan), .init(82,15,22,38,tan), + .init(26,29,3,10,slate), .init(39,29,3,10,slate), .init(74,29,3,10,slate), .init(86,29,3,10,slate)] + case .bookcase: + [.init(6,7,102,49,wood), .init(13,13,88,36,cream), .init(41,13,4,36,wood,2), + .init(71,13,4,36,wood,2), .init(19,23,8,23,sage), .init(28,26,9,20,slate), + .init(49,17,8,29,wood), .init(58,23,8,23,sage), .init(82,22,13,24,slate)] + case .shelf: + [.init(5,12,107,46,sage), .init(12,18,21,34,pale), .init(36,18,21,34,pale), + .init(60,18,21,34,pale), .init(84,18,21,34,pale)] + case .desk: + [.init(5,10,106,55,wood,7), .init(10,14,96,44,tan), + .init(25,22,22,24,cream), .init(62,22,31,20,slate), .init(72,42,11,7,slate)] + case .table: + [.init(3,3,58,58,wood,29), .init(6,5,52,52,tan,26)] + default: + [.init(20,7,66,60,tan,9), .init(22,9,62,20,cream,7), .init(43,45,20,8,wood,4)] + } + } +} diff --git a/apps/ios/ItemAtlas/LocationLayout.swift b/apps/ios/ItemAtlas/LocationLayout.swift new file mode 100644 index 0000000..97c06f7 --- /dev/null +++ b/apps/ios/ItemAtlas/LocationLayout.swift @@ -0,0 +1,502 @@ +import SwiftUI + +enum LocationTemplate: String, CaseIterable, Codable, Identifiable { + case livingRoom = "LIVING_ROOM", bedroom = "BEDROOM", study = "STUDY", kitchen = "KITCHEN" + case bathroom = "BATHROOM", room = "ROOM", entry = "ENTRY", balcony = "BALCONY", area = "AREA" + case sofa = "SOFA", bed = "BED", desk = "DESK", tvStand = "TV_STAND", wardrobe = "WARDROBE" + case bookcase = "BOOKCASE", shelf = "SHELF", table = "TABLE", storageBox = "STORAGE_BOX" + + var id: String { rawValue } + + var name: String { + switch self { + case .livingRoom: "客厅" + case .bedroom: "卧室" + case .study: "书房" + case .kitchen: "厨房" + case .bathroom: "卫生间" + case .room: "房间" + case .entry: "玄关" + case .balcony: "阳台" + case .area: "开放区域" + case .sofa: "转角沙发" + case .bed: "床" + case .desk: "书桌" + case .tvStand: "电视柜" + case .wardrobe: "衣柜" + case .bookcase: "书架" + case .shelf: "层架" + case .table: "边几" + case .storageBox: "收纳箱" + } + } + + enum Kind { case room, area, furniture } + + var kind: Kind { + switch self { + case .livingRoom, .bedroom, .study, .kitchen, .bathroom, .room: .room + case .entry, .balcony, .area: .area + default: .furniture + } + } + + var dimensions: (width: Int, depth: Int) { + switch self { + case .livingRoom: (4000, 3400) + case .bedroom, .study, .room: (3000, 2800) + case .kitchen: (2600, 2400) + case .bathroom: (2100, 1900) + case .entry, .balcony, .area: (2200, 1500) + case .sofa: (2300, 1400) + case .bed: (1600, 2100) + case .desk, .tvStand: (1400, 620) + case .wardrobe: (1600, 650) + case .bookcase, .shelf: (1100, 450) + case .table: (600, 600) + case .storageBox: (500, 450) + } + } + + static func suggested(for slot: LayoutLocation, isRoot: Bool) -> Self { + if slot.name.contains("沙发") { return .sofa } + if let known = LocationTemplate(rawValue: slot.icon), isRoot || known.kind != .room { return known } + return isRoot ? .room : .storageBox + } +} + +struct LocationGeometry: Codable, Equatable { + var template: LocationTemplate + var xMm: Int + var yMm: Int + var widthMm: Int + var depthMm: Int + var rotation = 0 + + var right: Int { xMm + widthMm } + var bottom: Int { yMm + depthMm } + + func overlaps(_ other: Self) -> Bool { + xMm < other.right && other.xMm < right && yMm < other.bottom && other.yMm < bottom + } +} + +struct LayoutLocation: Decodable, Identifiable, Equatable { + let id: UUID + let name: String + let icon: String + var geometry: LocationGeometry? +} + +struct LocationLayoutSnapshot: Decodable { + let version: UUID + let widthMm: Int + let depthMm: Int + let locations: [LayoutLocation] +} + +struct LocationPlacement: Encodable { + let id: UUID + let newName: String? + let geometry: LocationGeometry +} + +extension InventoryStore { + func locationLayout(parent: UUID?, refresh: Bool = false) async throws -> LocationLayoutSnapshot { + let query = parent.map { "?parentId=\($0)" } ?? "" + return try await account.read(root + "/location-layout" + query, refresh: refresh) + } + + func saveLocationLayout(parent: UUID?, version: UUID, placements: [LocationPlacement]) async throws -> LocationLayoutSnapshot { + struct Input: Encodable { + let parentId: UUID? + let version: UUID + let placements: [LocationPlacement] + } + let snapshot: LocationLayoutSnapshot = try await send(root + "/location-layout", method: "PUT", + Input(parentId: parent, version: version, placements: placements)) + changed() + return snapshot + } +} + +struct LocationPlanSection: View { + let store: InventoryStore + let parent: Place? + let open: (UUID) -> Void + @State private var snapshot: LocationLayoutSnapshot? + @State private var error: String? + @State private var editing = false + + var body: some View { + Section { + if let snapshot { + let placed = snapshot.locations.filter { $0.geometry != nil } + if placed.isEmpty { + ContentUnavailableView("还没有摆放位置", systemImage: "square.dashed", + description: Text(store.canWrite ? "可以摆放已有位置,或用模板新建。" : "空间成员摆放后会显示在这里。")) + } else { + LocationPlanCanvas(width: snapshot.widthMm, depth: snapshot.depthMm, locations: placed, + selected: nil, editing: false, open: open) + DisclosureGroup("图上的位置") { + ForEach(placed) { place in + Button(place.name) { open(place.id) }.buttonStyle(.borderless) + } + } + } + let unplaced = snapshot.locations.filter { $0.geometry == nil } + if !unplaced.isEmpty { + DisclosureGroup("未摆放 \(unplaced.count) 处") { + ForEach(unplaced) { place in + Button(place.name) { open(place.id) }.buttonStyle(.borderless) + } + } + } + if store.canWrite { + Button { editing = true } label: { Label("编辑布局", systemImage: "square.and.pencil") } + } + } else if error == nil { + ProgressView("正在读取俯视图") + } + if let error { + Text(error).font(.footnote).foregroundStyle(.secondary) + Button("重新读取") { Task { await load(refresh: true) } } + } + } header: { + LocationLevelHeading(level: parent == nil ? .room : .furniture) + } + .task(id: store.revision) { await load() } + .sheet(isPresented: $editing) { + if let snapshot { + LocationPlanEditor(store: store, parent: parent, snapshot: snapshot) { saved in + self.snapshot = saved + } + } + } + } + + private func load(refresh: Bool = false) async { + do { + snapshot = try await store.locationLayout(parent: parent?.id, refresh: refresh) + error = nil + } catch where !Task.isCancelled { + if (error as? AtlasError)?.resourceUnavailable == true { snapshot = nil } + self.error = error.localizedDescription + } catch {} + } +} + +private struct LocationPlanEditor: View { + let store: InventoryStore + let parent: Place? + let onSave: (LocationLayoutSnapshot) -> Void + @Environment(\.dismiss) private var dismiss + @State private var snapshot: LocationLayoutSnapshot + @State private var locations: [LayoutLocation] + @State private var selection: UUID? + @State private var choosingTemplate = false + @State private var saving = false + @State private var error: String? + @State private var conflicted = false + @State private var confirmingReload = false + @FocusState private var dimensionField: String? + + init(store: InventoryStore, parent: Place?, snapshot: LocationLayoutSnapshot, + onSave: @escaping (LocationLayoutSnapshot) -> Void) { + self.store = store + self.parent = parent + self.onSave = onSave + _snapshot = State(initialValue: snapshot) + _locations = State(initialValue: snapshot.locations) + } + + private var placed: [LayoutLocation] { locations.filter { $0.geometry != nil } } + private var unplaced: [LayoutLocation] { locations.filter { $0.geometry == nil } } + + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + if let parent { Text(parent.path).font(.subheadline).foregroundStyle(.secondary) } + LocationPlanCanvas(width: snapshot.widthMm, depth: snapshot.depthMm, locations: placed, + selected: selection, editing: true, open: { selection = $0 }, change: change) + if let selection, let place = locations.first(where: { $0.id == selection }), let geometry = place.geometry { + controls(for: place, geometry: geometry) + } + HStack { + if !unplaced.isEmpty { + Menu { + ForEach(unplaced) { place in + Button(place.name) { placeExisting(place) } + } + } label: { Label("摆放已有位置", systemImage: "square.dashed") } + } + Button { choosingTemplate = true } label: { + Label("添加模板", systemImage: "plus") + } + } + .buttonStyle(.bordered) + if let error { + Text(error).font(.footnote).foregroundStyle(.red).accessibilityAddTraits(.updatesFrequently) + if conflicted { Button("加载最新布局") { confirmingReload = true } } + } + } + .padding(16) + .frame(maxWidth: 600) + .frame(maxWidth: .infinity) + } + .background(Color(uiColor: .systemGroupedBackground)) + .dismissibleKeyboard(active: dimensionField != nil) { dimensionField = nil } + .disabled(saving) + .navigationTitle("编辑布局") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("取消") { dismiss() }.disabled(saving) + } + ToolbarItem(placement: .confirmationAction) { + Button("保存") { + dimensionField = nil + Task { await save() } + } + .disabled(saving || locations == snapshot.locations) + } + } + .sheet(isPresented: $choosingTemplate) { + LocationTemplatePicker(isRoot: parent == nil, names: Set(locations.map(\.name)), add: add) + } + .confirmationDialog("重新加载最新布局?", isPresented: $confirmingReload, titleVisibility: .visible) { + Button("重新加载", role: .destructive) { Task { await reload() } } + } message: { Text("重新加载会舍弃本次未保存的调整。") } + } + .interactiveDismissDisabled(saving || locations != snapshot.locations) + } + + private func controls(for place: LayoutLocation, geometry: LocationGeometry) -> some View { + VStack(alignment: .leading, spacing: 10) { + HStack(alignment: .firstTextBaseline) { + Text(place.name).font(.headline) + Spacer() + Menu { + ForEach(LocationTemplate.allCases.filter { parent == nil || $0.kind != .room }) { template in + Button(template.name) { + var updated = geometry + updated.template = template + change(place.id, updated) + } + } + } label: { + Label(geometry.template.name, systemImage: "chevron.down") + .font(.subheadline) + } + .accessibilityLabel("更换模板,当前为" + geometry.template.name) + } + Grid(horizontalSpacing: 10, verticalSpacing: 6) { + GridRow { + measurement("宽度", at: \.widthMm, in: place.id, value: geometry.widthMm) + measurement("深度", at: \.depthMm, in: place.id, value: geometry.depthMm) + } + GridRow { + measurement("横向位置", at: \.xMm, in: place.id, value: geometry.xMm) + measurement("纵向位置", at: \.yMm, in: place.id, value: geometry.yMm) + } + } + HStack { + Button("旋转 90°", systemImage: "rotate.right") { + var turned = geometry + turned.widthMm = geometry.depthMm + turned.depthMm = geometry.widthMm + turned.rotation = (geometry.rotation + 90) % 360 + guard turned.widthMm <= snapshot.widthMm && turned.depthMm <= snapshot.depthMm else { + error = "旋转后超出画布。请先缩小尺寸。" + return + } + change(place.id, turned) + } + Spacer() + Button("移出俯视图", role: .destructive) { remove(place.id) } + } + .font(.subheadline) + } + .padding(14) + .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 14)) + } + + private func measurement(_ label: String, at key: WritableKeyPath, + in id: UUID, value: Int) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(label + "(厘米)").font(.caption).foregroundStyle(.secondary) + TextField(label, value: Binding(get: { value / 10 }, set: { number in + guard let current = locations.first(where: { $0.id == id })?.geometry else { return } + var updated = current + updated[keyPath: key] = min(2400, max(0, number)) * 10 + change(id, updated) + }), format: .number.grouping(.never)) + .keyboardType(.numberPad) + .textFieldStyle(.roundedBorder) + .focused($dimensionField, equals: label) + .accessibilityLabel(label + ",厘米") + } + } + + private func change(_ id: UUID, _ proposed: LocationGeometry) { + guard let index = locations.firstIndex(where: { $0.id == id }) else { return } + var geometry = proposed + geometry.widthMm = min(snapshot.widthMm, max(100, geometry.widthMm)) + geometry.depthMm = min(snapshot.depthMm, max(100, geometry.depthMm)) + geometry.xMm = min(snapshot.widthMm - geometry.widthMm, max(0, geometry.xMm)) + geometry.yMm = min(snapshot.depthMm - geometry.depthMm, max(0, geometry.yMm)) + locations[index].geometry = geometry + selection = id + if !conflicted { error = nil } + } + + private func placeExisting(_ place: LayoutLocation) { + let template = LocationTemplate.suggested(for: place, isRoot: parent == nil) + if let geometry = suggestedPlacement(template) { change(place.id, geometry) } + } + + private func add(_ template: LocationTemplate, _ name: String) { + guard let geometry = suggestedPlacement(template) else { return } + let id = UUID() + locations.append(.init(id: id, name: name, icon: template.rawValue, geometry: geometry)) + selection = id + } + + private func suggestedPlacement(_ template: LocationTemplate) -> LocationGeometry? { + let preferred = template.dimensions + let geometries = placed.compactMap(\.geometry) + let occupied = geometries.filter { geometry in + template.kind == .room ? geometry.template.kind == .room : geometry.template.kind == template.kind + } + for divisor in [1, 2] { + let width = min(snapshot.widthMm, max(100, preferred.width / divisor)) + let depth = min(snapshot.depthMm, max(100, preferred.depth / divisor)) + for y in stride(from: 0, through: snapshot.depthMm - depth, by: 200) { + for x in stride(from: 0, through: snapshot.widthMm - width, by: 200) { + let geometry = LocationGeometry(template: template, xMm: x, yMm: y, widthMm: width, depthMm: depth) + if !occupied.contains(where: { geometry.overlaps($0) }) { return geometry } + } + } + } + error = "画布没有足够空位。请先调整已有的位置。" + return nil + } + + private func remove(_ id: UUID) { + guard let index = locations.firstIndex(where: { $0.id == id }) else { return } + if snapshot.locations.contains(where: { $0.id == id }) { locations[index].geometry = nil } + else { locations.remove(at: index) } + selection = nil + } + + private func save() async { + guard !saving else { return } + saving = true + error = nil + defer { saving = false } + let existing = Set(snapshot.locations.map(\.id)) + let request = locations.compactMap { place in + place.geometry.map { LocationPlacement(id: place.id, newName: existing.contains(place.id) ? nil : place.name, geometry: $0) } + } + do { + let updated = try await store.saveLocationLayout(parent: parent?.id, version: snapshot.version, placements: request) + onSave(updated) + dismiss() + } catch { + self.error = error.localizedDescription + conflicted = (error as? AtlasError)?.status == 409 + } + } + + private func reload() async { + do { + let updated = try await store.locationLayout(parent: parent?.id, refresh: true) + snapshot = updated + locations = updated.locations + selection = nil + error = nil + conflicted = false + } catch { self.error = error.localizedDescription } + } +} + +private struct LocationTemplatePicker: View { + let isRoot: Bool + let names: Set + let add: (LocationTemplate, String) -> Void + @Environment(\.dismiss) private var dismiss + @State private var template: LocationTemplate? + @State private var name = "" + @FocusState private var focused: Bool + + private var trimmed: String { name.trimmingCharacters(in: .whitespacesAndNewlines) } + private var available: [LocationTemplate] { + LocationTemplate.allCases.filter { isRoot || $0.kind != .room } + } + + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 14) { + if template != nil { + TextField("位置名称", text: $name) + .textFieldStyle(.roundedBorder) + .focused($focused) + if names.contains(trimmed) { + Text("当前层级已有同名位置。").font(.footnote).foregroundStyle(.secondary) + } + } + LazyVGrid(columns: [GridItem(.adaptive(minimum: 88), spacing: 8)], spacing: 8) { + ForEach(available) { choice in + Button { + focused = false + template = choice + name = availableName(choice.name) + } label: { + VStack(spacing: 5) { + LocationFloorArt(template: choice, rotation: 0) + .frame(width: 57, height: 40) + .accessibilityHidden(true) + Text(choice.name).font(.subheadline).foregroundStyle(.primary) + } + .padding(8) + .frame(maxWidth: .infinity, minHeight: 79) + .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 10)) + .overlay { + if choice == template { RoundedRectangle(cornerRadius: 10).stroke(Color.atlasBlue, lineWidth: 2) } + } + } + .buttonStyle(.plain) + .accessibilityAddTraits(choice == template ? .isSelected : []) + } + } + } + .padding(16) + } + .background(Color(uiColor: .systemGroupedBackground)) + .dismissibleKeyboard(active: focused) { focused = false } + .navigationTitle("添加模板") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("摆放") { + if let template { add(template, trimmed); dismiss() } + } + .disabled(template == nil || trimmed.isEmpty || trimmed.utf16.count > 100 || names.contains(trimmed)) + } + } + } + } + + private func availableName(_ title: String) -> String { + var unique = title + var suffix = 2 + while names.contains(unique) { + unique = "\(title) \(suffix)" + suffix += 1 + } + return unique + } +} diff --git a/apps/ios/ItemAtlas/LocationView.swift b/apps/ios/ItemAtlas/LocationView.swift index ffdc6e7..b5c6f3a 100644 --- a/apps/ios/ItemAtlas/LocationView.swift +++ b/apps/ios/ItemAtlas/LocationView.swift @@ -14,15 +14,20 @@ private struct LocationContents: View { let initialLocation: Place? let onIntake: (Place?) -> Void @Environment(\.dismiss) private var dismiss + @AppStorage("atlas.location-view.overview") private var overviewMode: DisplayMode = .flat + @AppStorage("atlas.location-view.inside") private var insideMode: DisplayMode = .flat @State private var items: ItemListResults @State private var addingLocation = false @State private var editingLocation = false @State private var editingAppearance = false @State private var sortingLocations = false + @State private var openedFromPlan: UUID? @State private var confirmingDelete = false @State private var error: String? @State private var busy = false + private enum DisplayMode: String { case flat, floorPlan } + init(store: InventoryStore, initialLocation: Place?, onIntake: @escaping (Place?) -> Void) { self.store = store self.initialLocation = initialLocation @@ -41,6 +46,9 @@ private struct LocationContents: View { Place.displayOrder(store.locations.filter { $0.parentId == location?.id }) } + private var hasPlan: Bool { initialLocation == nil || location?.levelDepth == 1 } + private var displayMode: Binding { initialLocation == nil ? $overviewMode : $insideMode } + var body: some View { Group { if store.locationAccessLost || (initialLocation != nil && store.locationsReady && location == nil) { @@ -65,32 +73,20 @@ private struct LocationContents: View { if !store.locationsReady && error == nil { ProgressView("正在加载位置") } - Section { - ForEach(children) { child in - NavigationLink { LocationContents(store: store, initialLocation: child, onIntake: onIntake) } label: { - HStack(spacing: 11) { - LocationMark(store: store, place: child) - Text(child.name) - } + if hasPlan { + Section { + Picker("位置显示", selection: displayMode) { + Text("平铺").tag(DisplayMode.flat) + Text("俯视图").tag(DisplayMode.floorPlan) } + .pickerStyle(.segmented) + .accessibilityIdentifier("location.view.mode") } - if store.canWrite { - Button { addingLocation = true } label: { - Label(location == nil ? "新建房间或区域" : "新建子位置", systemImage: "plus") - } - } - } header: { - HStack { - LocationLevelHeading(level: LocationLevel(depth: (location?.levelDepth ?? 0) + 1)) - if store.canWrite && children.count > 1 { - Spacer() - Button("排序") { sortingLocations = true } - .buttonStyle(.borderless) - .font(.subheadline.weight(.semibold)) - .frame(minHeight: 44) - } - } - .textCase(nil) + } + if hasPlan && displayMode.wrappedValue == .floorPlan { + LocationPlanSection(store: store, parent: location, open: openPlanLocation) + } else { + flatLocations } if let location { ItemsSection(store: store, results: items, location: location.id, onIntake: { onIntake(location) }) @@ -101,6 +97,11 @@ private struct LocationContents: View { Button("重试") { Task { await reloadLocations(refresh: true) } } } } + .navigationDestination(item: $openedFromPlan) { id in + if let place = store.locations.first(where: { $0.id == id }) { + LocationContents(store: store, initialLocation: place, onIntake: onIntake) + } + } .toolbar { if location != nil && store.canWrite { ToolbarItem(placement: .topBarTrailing) { @@ -148,6 +149,50 @@ private struct LocationContents: View { } message: { Text("请先清空物品和子位置。删除这个位置时,里面的照片会一起删除。") } } + private var flatLocations: some View { + Section { + ForEach(children) { child in + NavigationLink { LocationContents(store: store, initialLocation: child, onIntake: onIntake) } label: { + HStack(spacing: 11) { + LocationMark(store: store, place: child) + Text(child.name) + } + } + } + if store.canWrite { + Button { addingLocation = true } label: { + Label(location == nil ? "新建房间或区域" : "新建子位置", systemImage: "plus") + } + } + } header: { + HStack { + LocationLevelHeading(level: LocationLevel(depth: (location?.levelDepth ?? 0) + 1)) + if store.canWrite && children.count > 1 { + Spacer() + Button("排序") { sortingLocations = true } + .buttonStyle(.borderless) + .font(.subheadline.weight(.semibold)) + .frame(minHeight: 44) + } + } + .textCase(nil) + } + } + + private func openPlanLocation(_ id: UUID) { + if children.contains(where: { $0.id == id }) { + openedFromPlan = id + } else { + Task { + do { + try await store.refreshLocations(refresh: true) + guard children.contains(where: { $0.id == id }) else { throw AtlasError("位置已有变化,请刷新后再查看。") } + openedFromPlan = id + } catch { self.error = error.localizedDescription } + } + } + } + private func locationOverview(_ location: Place) -> some View { VStack(alignment: .leading, spacing: 12) { HStack(spacing: 12) { diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java index 6fe5dfc..fbb94fc 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java @@ -17,8 +17,12 @@ import org.springframework.web.bind.annotation.*; class InventoryController { private static final String FAMILY = "/api/households/{household}"; private final InventoryService service; + private final LocationLayoutService layouts; - InventoryController(InventoryService service) { this.service = service; } + InventoryController(InventoryService service, LocationLayoutService layouts) { + this.service = service; + this.layouts = layouts; + } @GetMapping(FAMILY + "/locations") List locations(@PathVariable UUID household, Principal user) { @@ -37,6 +41,18 @@ class InventoryController { return service.saveLocationOrder(household, user.getName(), input); } + @GetMapping(FAMILY + "/location-layout") + LocationLayout.Snapshot locationLayout(@PathVariable UUID household, Principal user, + @RequestParam(required = false) UUID parentId) { + return layouts.get(household, user.getName(), parentId); + } + + @PutMapping(FAMILY + "/location-layout") + LocationLayout.Snapshot saveLocationLayout(@PathVariable UUID household, Principal user, + @RequestBody @Valid LocationLayout.Save input) { + return layouts.save(household, user.getName(), input); + } + @PostMapping(FAMILY + "/locations") ResponseEntity createLocation(@PathVariable UUID household, Principal user, @RequestBody @Valid LocationInput input) { 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 ecf5521..6a33106 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 @@ -159,6 +159,16 @@ class InventoryService { @Transactional Location saveLocation(UUID household, String actor, UUID id, LocationInput input) { access.requireWrite(household, actor); + return writeLocation(household, actor, id, null, input); + } + + @Transactional + Location createMappedLocation(UUID household, String actor, UUID id, LocationInput input) { + access.requireWrite(household, actor); + return writeLocation(household, actor, null, id, input); + } + + private Location writeLocation(UUID household, String actor, UUID id, UUID creationId, LocationInput input) { UUID parent = input.parentId(); if (parent != null) { location(household, parent); @@ -170,8 +180,9 @@ class InventoryService { } } Location existing = id == null ? null : location(household, id); - UUID target = existing == null ? UUID.randomUUID() : existing.id(); - Integer rank = existing != null && Objects.equals(existing.parentId(), parent) ? existing.sortRank() + UUID target = existing == null ? Objects.requireNonNullElseGet(creationId, UUID::randomUUID) : existing.id(); + boolean sameParent = existing != null && Objects.equals(existing.parentId(), parent); + Integer rank = sameParent ? existing.sortRank() : db.sql(""" SELECT max(sort_rank)+1 FROM location WHERE household_id=:household AND parent_id IS NOT DISTINCT FROM :parent AND archived_at IS NULL @@ -194,6 +205,13 @@ class InventoryService { } catch (DuplicateKeyException ex) { throw new ResponseStatusException(CONFLICT, "当前层级已有同名位置"); } + if (existing != null && !sameParent) { + db.sql(""" + DELETE FROM location_geometry g USING location_paths(:household) p + WHERE g.household_id=:household AND g.location_id=p.id + AND (p.id=:id OR cardinality(p.ancestors)>2) + """).param("household", household).param("id", target).update(); + } return locationFor(household, target, actor); } @@ -239,6 +257,8 @@ class InventoryService { if (occupied) { throw new ResponseStatusException(CONFLICT, "位置还有物品或子位置"); } db.sql("UPDATE location SET archived_at=now() WHERE household_id=:household AND id=:id") .param("household", household).param("id", id).update(); + db.sql("DELETE FROM location_geometry WHERE household_id=:household AND location_id=:id") + .param("household", household).param("id", id).update(); } List items(UUID household, String actor, String q, int limit, int offset, boolean favorites, UUID location) { diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/LocationLayout.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/LocationLayout.java new file mode 100644 index 0000000..f16ff88 --- /dev/null +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/LocationLayout.java @@ -0,0 +1,45 @@ +package com.tutudog.itematlas.inventory; + +import static com.tutudog.itematlas.inventory.InventoryDtos.LocationIcon; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.util.List; +import java.util.UUID; + +final class LocationLayout { + enum Template { + LIVING_ROOM(LocationIcon.LIVING_ROOM, true), BEDROOM(LocationIcon.BEDROOM, true), + STUDY(LocationIcon.STUDY, true), KITCHEN(LocationIcon.KITCHEN, true), + BATHROOM(LocationIcon.BATHROOM, true), ROOM(LocationIcon.HOME, true), + ENTRY(LocationIcon.ENTRY), BALCONY(LocationIcon.BALCONY), AREA(LocationIcon.FOLDER), + SOFA(LocationIcon.LIVING_ROOM), BED(LocationIcon.BEDROOM), DESK(LocationIcon.DESK), + TV_STAND(LocationIcon.TV_STAND), WARDROBE(LocationIcon.WARDROBE), + BOOKCASE(LocationIcon.BOOKCASE), SHELF(LocationIcon.SHELF), TABLE(LocationIcon.DESK), + STORAGE_BOX(LocationIcon.BOX); + + final LocationIcon icon; + final boolean room; + + Template(LocationIcon icon) { this(icon, false); } + Template(LocationIcon icon, boolean room) { this.icon = icon; this.room = room; } + } + + record Geometry(@NotNull Template template, @Min(0) @Max(24000) int xMm, @Min(0) @Max(24000) int yMm, + @Min(100) @Max(24000) int widthMm, @Min(100) @Max(24000) int depthMm, + @Min(0) @Max(270) int rotation) { + int right() { return xMm + widthMm; } + int bottom() { return yMm + depthMm; } + boolean turnedSideways() { return rotation % 180 != 0; } + } + + record Slot(UUID id, String name, LocationIcon icon, Geometry geometry) {} + record Snapshot(UUID version, int widthMm, int depthMm, List locations) {} + record Placement(@NotNull UUID id, @Size(max=100) String newName, @NotNull @Valid Geometry geometry) {} + record Save(UUID parentId, @NotNull UUID version, @NotNull List<@NotNull @Valid Placement> placements) {} + + private LocationLayout() {} +} diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/LocationLayoutService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/LocationLayoutService.java new file mode 100644 index 0000000..09bcd08 --- /dev/null +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/LocationLayoutService.java @@ -0,0 +1,192 @@ +package com.tutudog.itematlas.inventory; + +import static com.tutudog.itematlas.inventory.InventoryDtos.*; +import static com.tutudog.itematlas.inventory.LocationLayout.*; +import static org.springframework.http.HttpStatus.*; + +import java.nio.charset.StandardCharsets; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +@Service +class LocationLayoutService { + private record Bounds(int width, int depth) { + boolean fits(Geometry geometry) { return geometry.right() <= width && geometry.bottom() <= depth; } + } + + private final JdbcClient db; + private final HouseholdAccess access; + private final InventoryService inventory; + + LocationLayoutService(JdbcClient db, HouseholdAccess access, InventoryService inventory) { + this.db = db; + this.access = access; + this.inventory = inventory; + } + + @Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) + Snapshot get(UUID household, String actor, UUID parent) { + access.role(household, actor); + return snapshot(household, actor, parent); + } + + @Transactional + Snapshot save(UUID household, String actor, Save input) { + // Location and layout writes share the same household lock. + access.requireWrite(household, actor); + Snapshot current = snapshot(household, actor, input.parentId()); + var requested = new LinkedHashMap(); + for (Placement placement : input.placements()) { + if (requested.putIfAbsent(placement.id(), placement) != null) { + throw new ResponseStatusException(BAD_REQUEST, "同一位置在布局里重复出现"); + } + } + var slots = current.locations().stream().collect(Collectors.toMap(Slot::id, Function.identity())); + if (matchesSavedLayout(current, requested, slots)) { return current; } + if (!current.version().equals(input.version())) { + throw new ResponseStatusException(CONFLICT, "布局已有更新,请加载最新布局后再编辑"); + } + validate(household, input.parentId(), current, requested, slots); + for (Slot previous : current.locations()) { + if (previous.geometry() != null && !requested.containsKey(previous.id())) { + db.sql("DELETE FROM location_geometry WHERE household_id=:household AND location_id=:id") + .param("household", household).param("id", previous.id()).update(); + } + } + for (Placement entry : requested.values()) { + Slot previous = slots.get(entry.id()); + Geometry shape = entry.geometry(); + if (previous == null) { + inventory.createMappedLocation(household, actor, entry.id(), + new LocationInput(entry.newName().strip(), input.parentId(), shape.template().icon)); + } + if (previous == null || !Objects.equals(previous.geometry(), shape)) { upsert(household, entry); } + } + return snapshot(household, actor, input.parentId()); + } + + private Snapshot snapshot(UUID household, String actor, UUID parent) { + if (parent != null && inventory.location(household, actor, parent).depth() != 1) { + throw new ResponseStatusException(BAD_REQUEST, "俯视图只支持一级和二级位置"); + } + List slots = db.sql(""" + SELECT l.id,l.name,l.icon,g.template,g.x_mm,g.y_mm,g.width_mm,g.depth_mm,g.rotation + FROM location l LEFT JOIN location_geometry g + ON (g.household_id,g.location_id)=(l.household_id,l.id) + WHERE l.household_id=:household AND l.parent_id IS NOT DISTINCT FROM :parent AND l.archived_at IS NULL + ORDER BY l.id + """).param("household", household).param("parent", parent, Types.OTHER) + .query((row, index) -> new Slot(row.getObject("id", UUID.class), row.getString("name"), + LocationIcon.valueOf(row.getString("icon")), geometry(row))).list(); + Bounds bounds = bounds(household, parent, slots); + var version = new StringBuilder().append(bounds).append('|'); + slots.forEach(slot -> version.append(slot.id()).append('/').append(slot.geometry()).append('|')); + return new Snapshot(UUID.nameUUIDFromBytes(version.toString().getBytes(StandardCharsets.UTF_8)), + bounds.width(), bounds.depth(), slots); + } + + private Bounds bounds(UUID household, UUID parent, List slots) { + if (parent == null) { return new Bounds(12000, 9000); } + var declared = db.sql(""" + SELECT template,x_mm,y_mm,width_mm,depth_mm,rotation FROM location_geometry + WHERE household_id=:household AND location_id=:id + """).param("household", household).param("id", parent).query((row, index) -> geometry(row)).optional(); + if (declared.isPresent()) { return interior(declared.get()); } + // A previously drawn room can be removed from the overview while keeping its own furniture layout. + int width = 5000, depth = 3750; + for (Slot slot : slots) { + if (slot.geometry() == null) { continue; } + width = Math.max(width, slot.geometry().right()); + depth = Math.max(depth, slot.geometry().bottom()); + } + return new Bounds(width, depth); + } + + private static Bounds interior(Geometry geometry) { + return geometry.turnedSideways() ? new Bounds(geometry.depthMm(), geometry.widthMm()) + : new Bounds(geometry.widthMm(), geometry.depthMm()); + } + + private static Geometry geometry(ResultSet row) throws SQLException { + String template = row.getString("template"); + return template == null ? null : new Geometry(Template.valueOf(template), + row.getInt("x_mm"), row.getInt("y_mm"), row.getInt("width_mm"), row.getInt("depth_mm"), row.getInt("rotation")); + } + + private static boolean matchesSavedLayout(Snapshot current, Map requested, Map slots) { + long placed = current.locations().stream().filter(slot -> slot.geometry() != null).count(); + return placed == requested.size() && requested.values().stream().allMatch(entry -> { + Slot slot = slots.get(entry.id()); + return slot != null && entry.geometry().equals(slot.geometry()) + && (entry.newName() == null || entry.newName().strip().equals(slot.name())); + }); + } + + private void validate(UUID household, UUID parent, Snapshot current, Map requested, + Map slots) { + var canvas = new Bounds(current.widthMm(), current.depthMm()); + for (Placement entry : requested.values()) { + Slot previous = slots.get(entry.id()); + String name = entry.newName(); + if (previous == null && (name == null || name.isBlank()) + || previous != null && name != null && !name.strip().equals(previous.name())) { + throw new ResponseStatusException(BAD_REQUEST, "布局的位置不属于当前层级,或新位置名称无效"); + } + Geometry shape = entry.geometry(); + if (shape.rotation() % 90 != 0 || !canvas.fits(shape) || parent != null && shape.template().room) { + throw new ResponseStatusException(BAD_REQUEST, "位置尺寸、朝向或模板超出当前画布"); + } + if (parent == null && previous != null && !Objects.equals(previous.geometry(), shape)) { + validateInterior(household, entry.id(), interior(shape)); + } + } + var rooms = requested.values().stream().map(Placement::geometry).filter(g -> g.template().room).toList(); + for (int i = 0; i < rooms.size(); i++) { + for (int j = i + 1; j < rooms.size(); j++) { + Geometry a = rooms.get(i), b = rooms.get(j); + if (a.xMm() < b.right() && b.xMm() < a.right() && a.yMm() < b.bottom() && b.yMm() < a.bottom()) { + throw new ResponseStatusException(CONFLICT, "两个房间的边界重叠,请移动或调整大小"); + } + } + } + } + + private void validateInterior(UUID household, UUID id, Bounds interior) { + boolean outside = db.sql(""" + SELECT EXISTS (SELECT FROM location l JOIN location_geometry g + ON (g.household_id,g.location_id)=(l.household_id,l.id) + WHERE l.household_id=:household AND l.parent_id=:id AND l.archived_at IS NULL + AND (g.x_mm+g.width_mm>:width OR g.y_mm+g.depth_mm>:depth)) + """).param("household", household).param("id", id).param("width", interior.width()) + .param("depth", interior.depth()).query(Boolean.class).single(); + if (outside) { + throw new ResponseStatusException(CONFLICT, "有二级位置超出调整后的尺寸,请先调整内部摆放"); + } + } + + private void upsert(UUID household, Placement entry) { + Geometry shape = entry.geometry(); + db.sql(""" + INSERT INTO location_geometry(household_id,location_id,template,x_mm,y_mm,width_mm,depth_mm,rotation) + VALUES (:household,:id,:template,:x,:y,:width,:depth,:rotation) + ON CONFLICT (household_id,location_id) DO UPDATE SET template=excluded.template, + x_mm=excluded.x_mm,y_mm=excluded.y_mm,width_mm=excluded.width_mm,depth_mm=excluded.depth_mm, + rotation=excluded.rotation + """).param("household", household).param("id", entry.id()).param("template", shape.template().name()) + .param("x", shape.xMm()).param("y", shape.yMm()).param("width", shape.widthMm()) + .param("depth", shape.depthMm()).param("rotation", shape.rotation()).update(); + } +} diff --git a/backend/inventory-service/src/main/resources/db/migration/V17__location_geometry.sql b/backend/inventory-service/src/main/resources/db/migration/V17__location_geometry.sql new file mode 100644 index 0000000..998412b --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V17__location_geometry.sql @@ -0,0 +1,12 @@ +CREATE TABLE location_geometry ( + household_id uuid NOT NULL, + location_id uuid NOT NULL, + template varchar(24) NOT NULL, + x_mm integer NOT NULL CHECK (x_mm BETWEEN 0 AND 24000), + y_mm integer NOT NULL CHECK (y_mm BETWEEN 0 AND 24000), + width_mm integer NOT NULL CHECK (width_mm BETWEEN 100 AND 24000), + depth_mm integer NOT NULL CHECK (depth_mm BETWEEN 100 AND 24000), + rotation smallint NOT NULL CHECK (rotation IN (0,90,180,270)), + PRIMARY KEY (household_id, location_id), + FOREIGN KEY (household_id, location_id) REFERENCES location(household_id, id) ON DELETE CASCADE +); diff --git a/backend/tests/ios_experience_smoke.py b/backend/tests/ios_experience_smoke.py index 2e206a8..92f01eb 100644 --- a/backend/tests/ios_experience_smoke.py +++ b/backend/tests/ios_experience_smoke.py @@ -18,6 +18,7 @@ def verify(): verify_optional_locations(root) verify_direct_invitations(root) verify_location_order(root) + verify_location_layout(root) verify_community(root) finally: call("DELETE", root, status=202) @@ -301,6 +302,56 @@ def verify_location_order(root): print("PASS persisted sibling order, append, scoped roles, stale edits and idempotent retry", flush=True) +def verify_location_layout(root): + location_path = root + "/locations" + layout_path = root + "/location-layout" + + def shape(template, x, y, w, h, rotation=0): + return {"template": template, "xMm": x, "yMm": y, "widthMm": w, "depthMm": h, "rotation": rotation} + + def entry(id, geometry, name=None): + return {"id": id, "geometry": geometry, "newName": name} + + def content(point, placements, parent=None): + return {"version": point["version"], "parentId": parent, "placements": placements} + + room = call("POST", location_path, {"name": "布局客厅"}, status=201)["id"] + first = call("GET", layout_path, user="viewer") + assert any(p["id"] == room and p["geometry"] is None for p in first["locations"]) + call("GET", layout_path, user="other", status=404) + sofa_id = str(uuid4()) + closed = entry(room, shape("LIVING_ROOM", 200, 300, 4000, 3600)) + sofa = entry(sofa_id, shape("SOFA", 500, 700, 1500, 800), "测试沙发") + request = content(first, [closed, sofa]) + call("PUT", layout_path, request, user="viewer", status=403) + call("PUT", layout_path, content(first, [closed, entry(str(uuid4()), shape("ROOM", 300, 500, 2100, 1900), "重叠房间")]), status=409) + call("PUT", layout_path, content(first, [entry(room, shape("ROOM", 11800, 300, 4000, 3600))]), status=400) + assert call("GET", layout_path) == first + saved = call("PUT", layout_path, request) + assert saved == call("GET", layout_path) == call("PUT", layout_path, request) + assert call("GET", location_path + "/" + sofa_id)["parentId"] is None + call("PUT", layout_path, content(first, []), status=409) + + inner_path = layout_path + "?" + urlencode({"parentId": room}) + inner = call("GET", inner_path) + assert (inner["widthMm"], inner["depthMm"], inner["locations"]) == (4000, 3600, []) + cabinet = entry(str(uuid4()), shape("WARDROBE", 2200, 900, 1500, 650), "布局衣柜") + call("PUT", layout_path, content(inner, [entry(sofa_id, sofa["geometry"])], room), status=400) + nested = call("PUT", layout_path, content(inner, [cabinet], room)) + assert nested == call("GET", inner_path) + call("GET", layout_path + "?" + urlencode({"parentId": cabinet["id"]}), status=400) + too_small = entry(room, shape("LIVING_ROOM", 100, 100, 2000, 1700)) + call("PUT", layout_path, content(saved, [too_small, sofa]), status=409) + turned = entry(room, shape("LIVING_ROOM", 200, 300, 3600, 4000, 90)) + rotated = call("PUT", layout_path, content(saved, [turned, sofa])) + assert call("GET", inner_path)["widthMm"] == 4000 + + removed = call("PUT", layout_path, content(rotated, [turned])) + assert any(p["id"] == sofa_id and p["geometry"] is None for p in removed["locations"]) + assert call("GET", location_path + "/" + sofa_id)["name"] == "测试沙发" + print("PASS two-level floor plans, shared positions, atomic creation, bounds, overlap, roles and retry", flush=True) + + def verify_community(root): room = call("POST", root + "/locations", {"name": "测试住址" + RUN, "icon": "BEDROOM"}, status=201) posts = "/api/community/posts" diff --git a/docs/architecture/location-layout.md b/docs/architecture/location-layout.md index d0c1248..b0e1482 100644 --- a/docs/architecture/location-layout.md +++ b/docs/architecture/location-layout.md @@ -8,31 +8,19 @@ - `PUT /api/households/{household}/locations/order` 接收 `parentId`、读取时的 `version` 和排序后的完整 `ids`。服务复用家庭写入事务锁,确认空间写权限、同级活动位置集合和版本后,一次写入 `location.sort_rank`。旧版本有变更时返回 `409`。顺序已经一致时可以安全重试。 - Flyway V16 增加可空的 `sort_rank`。从未排序的老数据保留原有顺序。某层保存过自定义顺序后,新建或移入的位置追加到队尾。选择位置的树和 iOS 平铺列表读取相同的排名。 -## 俯视图和建模草稿的数据设计 +## 俯视图 -- `location_layout_scope` 以 `household_id` 和 `parent_location_id` 定位一组兄弟位置。根层的父 ID 为空,联合唯一约束使用 `NULLS NOT DISTINCT`。记录画布范围和 `revision`。三级以下可只保存排序。 -- `location_presentation` 以 `household_id` 和 `location_id` 关联原位置。保存可空的 `mold_key`、`x_mm`、`y_mm`、`width_mm`、`depth_mm`、`rotation`。几何字段整体为空表示未摆放,同级排序沿用 `location.sort_rank`。模板键用白名单。原有图标及个人照片缩略图继续沿用。 -- 历史位置无需批量猜尺寸或坐标。有手动顺序时按顺序显示,其余使用既有的路径和 ID 顺序。新增位置追加到队尾。已设顺序的同级节点在刷新后仍稳定可读。 -- 缩放和平移只改变客户端视图。保存以整数毫米为单位,画布默认按 10 厘米吸附。模板给估算尺寸,明确度量可通过数值输入覆盖。朝向按 90° 存储并计算实际占用边界。 -- 家具可以叠放在房间轮廓内,开放区域也可用虚线描在大房间里。两个封闭房间之间的明显重叠显示冲突。缩小一级位置前检查已有二级家具是否会超出范围,提示定位到对应家具调整。 +Flyway V17 创建 `location_geometry`。每条记录以 `household_id` 和 `location_id` 关联现有位置,保存模板、左上角坐标、宽深和 90° 的朝向。没有记录时显示为未摆放。把位置移出俯视图只删除几何记录。 -## API 和一致性 +空间总图使用 12 × 9 米画布。一级位置已有尺寸时,其内部画布取旋转前的宽深。未摆放的一级位置从 5 × 3.75 米开始,并覆盖已有二级家具的范围。拖动和拉角默认按 10 厘米吸附,面板可用厘米输入。房间边界不能相互重叠,独立沙发可以画在房间轮廓内。缩小房间时,后端核对已摆放的二级位置是否仍在范围内。 | 请求 | 契约 | | --- | --- | -| `GET /api/households/{household}/location-layout` | 可传 `parentId`。返回画布、版本、同级位置的排序和坐标。仅空间的有效成员可读。 | -| `PUT /api/households/{household}/location-layout` | 提交同级 `parentId`、读到的版本、调整后的几何数据或完整排序 ID。手动添加模板可一并提交待新建位置,同一事务创建和落图。成功返回新版本。 | -| `POST /api/households/{household}/location-layout-drafts` | 生成当前范围的布局草稿,接收文字、模型选择和布局版本。使用草稿 ID 查询生成结果。 | -| `POST /api/households/{household}/location-layout/apply-draft` | 由有写权限的成员确认草稿。明确哪些条目绑定现有位置、哪些要新建。临时 ID 只用于一次确认,创建和落图在同一事务完成。 | +| `GET /api/households/{household}/location-layout` | `parentId` 为空时读取空间总图。指定一级位置时读取该位置的二级布局。返回画布范围、版本、当前同级位置和各自几何。 | +| `PUT /api/households/{household}/location-layout` | 提交 `parentId`、读取的版本和本次画布上的全部位置。已有位置使用原 ID,新模板带客户端生成的 ID 和名称。保存会一次提交新位置及布局。 | -保存前重新校验角色、位置归属和层级。排序请求只接收当前活动兄弟节点的完整排列。写事务锁住目标范围,把版本和坐标检查、排序写入一起提交。影响父子两个布局时按固定顺序取锁。任一版本过期返回 `409`,客户端保留编辑内容,待重新载入核对后再提交。 +读取使用一致的数据库快照。写入和位置变更共用家庭事务锁,并校验写权限、层级、坐标和当前版本。同样的保存操作可以重试。旧版本提交会提示重新加载。位置归档或移动到新上级时清理原先的摆放,已超出二级的子位置回到平铺。原有同级排序和物品归属仍通过位置树保存。 -位置归档或换上级时,在原操作的事务内清理原布局关联和排序。位置移到新上级时进入新组队尾,待用户摆放。普通拖拽保留原业务归属。网络超时后先查最新版本或草稿确认结果。确认凭据绑定用户、空间和范围,重复请求返回已提交结果。批量提交失败时事务回滚。 +## AI 建模规划 -## 建模草稿 - -`intake-service` 复用现有录音文本及模型路由,新增位置布局的结构化输出。输入携带当前布局范围的层级、允许使用的模板键、必要的同级位置名及引用、用户描述和已有布局版本。默认使用本地模型,云端沿用显式选择和额度限制。 - -模型给出名称、模板、明确尺寸、方位关系以及哪些信息缺失。服务端查出现有位置,校验模板和层级,用确定性的边界检查与排布逻辑计算坐标。没有唯一解的项留作待确认。用户审核后提交到库存服务。输入只使用当前范围必要的名称和尺寸,提示词与用户描述留在受控数据路径。 - -服务端集成测试覆盖跨空间 ID、只读成员、并发修改、未知模板、越界、同名歧义、确认重试和存量位置兼容。 +录音或文字在 `intake-service` 生成结构化布局草稿。默认走本地模型,云模型沿用现有选择和预算限制。模型给出模板、尺寸与相对方位,服务端用当前画布和有效位置约束输出。用户审核、微调后再通过库存服务保存。提示词和描述不会进入普通请求日志。 diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md index e0951a6..2911639 100644 --- a/docs/product/ios-experience.md +++ b/docs/product/ios-experience.md @@ -34,6 +34,8 @@ 同一级有两处或以上位置时,空间所有者和编辑者可点标题旁的「排序」,拖动后保存。其他成员刷新后看到同一个顺序,选位置时也沿用这个顺序。如果同时有人修改了列表,排序页会保留当前编辑,提示加载最新顺序。 +在「位置」页切换「俯视图」,再点「编辑布局」。可摆放已有位置,或从卡通模板新建沙发、房间或柜子。拖动物件和右下角手柄,或在下方输入位置和尺寸,调整后点保存。点画面上的一级位置进入它的详情,一级详情里的切换栏控制二级布局。三级及以下使用平铺。 + 添加或编辑物品时,可以填写可选的购入单价、选择绿色物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。 ## 选存放位置 diff --git a/docs/product/requirements.md b/docs/product/requirements.md index 4eed8e5..bb7b4d7 100644 --- a/docs/product/requirements.md +++ b/docs/product/requirements.md @@ -14,7 +14,8 @@ | R08 | 收藏和评分 | 可收藏、评 1–5 星或写短评,支持修改和清除。每件物品的个人评价按用户独立保存。 | | R09 | 物品和位置照片 | 选择照片并在上传前剪裁,每件最多六张。列表加载缩略图,详情可看大图。查看权限与物品一致,删除图片、物品或空间后同步登记两份文件的清理。 | | R10 | 社区分享 | 新建物品默认私有。空间所有者确认发布后,任一已登录账号可搜分享、评论和打星。社区只展示独立填写的标题和正文。撤回或归档物品后,帖子、评分及评论退出社区。 | -| R11 | 位置布局(设计中) | 一级和二级可切换俯视图与平铺。按模板创建位置,编辑坐标、宽深及可用朝向。同级平铺可排序,三级及以下保留平铺。已有位置可加入画布。语音和文字能生成可编辑、待确认的布局草稿。保存前校验空间、权限与版本。 | +| R11 | 位置布局 | 一级和二级可切换俯视图与平铺。按模板创建位置,编辑坐标、宽深及朝向。同级平铺可排序,三级及以下保留平铺。已有位置可加入画布。保存前校验空间、权限与版本。 | +| R12 | AI 建模(规划) | 语音和文字可生成可编辑、待确认的布局草稿。用户核对后应用,模型失败时保留原文和现有布局。 | ## 质量要求 diff --git a/docs/testing/cases.md b/docs/testing/cases.md index 138f820..056ed17 100644 --- a/docs/testing/cases.md +++ b/docs/testing/cases.md @@ -57,6 +57,6 @@ R01–R10 对应[需求与验收](../product/requirements.md)。实现和当前 | --- | --- | --- | --- | | TC-47 布局与排序 | R11 | 用有老位置的空间切换俯视图和平铺。放入已有客厅,添加一级沙发,拖动改尺寸。进入客厅摆放电视柜,再进电视柜。切回平铺排序并重新登录。 | 存量位置和物品关联保持。一级、二级可浏览和编辑俯视。三级只平铺。同级排序在刷新后保留,图上位置独立。 | | TC-48 布局权限与冲突 | R01、R11 | 两位可写成员同时编辑同一张图,先后保存。以只读成员尝试修改,再提交另一空间的位置 ID。 | 成员可以查看允许的布局。旧版本提示冲突并保留本地编辑。越权写入被拒绝,也不会留下部分变化。 | -| TC-49 AI 布局草稿 | R07、R11 | 用语音或文字描述新增区域、移动家具及有歧义的同名位置。核对后应用,同一请求重复提交。模拟模型不可用。 | 预览标出变化及待确认的条目。确认后布局原子更新,重复提交不会创建重复位置。模型不可用时原话仍可编辑,手动布局可继续。 | +| TC-49 AI 布局草稿 | R07、R12 | 用语音或文字描述新增区域、移动家具及有歧义的同名位置。核对后应用,同一请求重复提交。模拟模型不可用。 | 预览标出变化及待确认的条目。确认后布局原子更新,重复提交不会创建重复位置。模型不可用时原话仍可编辑,手动布局可继续。 | [测试与演示计划](plan.md) diff --git a/docs/ui/ios/location-layout.md b/docs/ui/ios/location-layout.md index 7bc8a14..4d4fe50 100644 --- a/docs/ui/ios/location-layout.md +++ b/docs/ui/ios/location-layout.md @@ -32,7 +32,7 @@ 查看时突出房间边界和家具形状。进入编辑才显示网格、选中轮廓和手柄。「添加模板」用插画预览,可按房间、区域和家具选择。名称和选中状态独立渲染,家具转动时标签继续正向可读。 [早期材质探索](location-models/README.md) -## 用描述生成草稿 +## 用描述生成草稿(规划) 从任一张一级或二级画布进入「AI 建模」,用语音转文字,或用键盘写一段。也可以使用系统输入法的手写文字。例如「客厅下面是玄关,右侧是书房」或「电视柜贴上边,书架放右侧」。提交前能改转写。