From 31efe8cd8699b3e1772058770c83605c4a51da48 Mon Sep 17 00:00:00 2001 From: dongjf <1+dongjf@noreply.git.tutudog.com> Date: Thu, 26 Nov 2026 20:30:55 +0800 Subject: [PATCH] =?UTF-8?q?feat(ios):=20=E5=A2=9E=E5=8A=A0=E4=BD=8D?= =?UTF-8?q?=E7=BD=AE=E5=9B=BE=E6=A0=87=E3=80=81=E7=89=A9=E5=93=81=E5=8D=95?= =?UTF-8?q?=E4=BB=B7=E5=92=8C=E9=A6=96=E5=BC=A0=E7=85=A7=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/ios/ItemAtlas.xcodeproj/project.pbxproj | 4 +- apps/ios/ItemAtlas/Account.swift | 4 +- apps/ios/ItemAtlas/Editors.swift | 127 ++++++++++++++++-- apps/ios/ItemAtlas/InventoryAppearance.swift | 95 +++++++++++++ apps/ios/ItemAtlas/InventoryStore.swift | 39 ++++-- apps/ios/ItemAtlas/InventoryView.swift | 6 +- apps/ios/ItemAtlas/ItemPhotos.swift | 11 +- apps/ios/ItemAtlas/LocationPicker.swift | 4 +- apps/ios/ItemAtlas/LocationView.swift | 77 +++++++++-- .../inventory/InventoryController.java | 5 +- .../itematlas/inventory/InventoryDtos.java | 15 ++- .../itematlas/inventory/InventoryService.java | 58 +++++--- .../itematlas/inventory/PhotoController.java | 5 +- .../itematlas/inventory/PhotoService.java | 24 +++- .../db/migration/V9__inventory_appearance.sql | 22 +++ backend/tests/ios_experience_smoke.py | 34 +++++ backend/tests/media_smoke.py | 13 +- backend/tests/smoke.py | 4 +- docs/architecture/inventory-appearance.md | 19 +++ docs/product/ios-experience.md | 6 + docs/testing/cases.md | 2 + 21 files changed, 499 insertions(+), 75 deletions(-) create mode 100644 apps/ios/ItemAtlas/InventoryAppearance.swift create mode 100644 backend/inventory-service/src/main/resources/db/migration/V9__inventory_appearance.sql create mode 100644 docs/architecture/inventory-appearance.md diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index 45931e0..c646606 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 = 9; + CURRENT_PROJECT_VERSION = 10; 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 = 9; + CURRENT_PROJECT_VERSION = 10; 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 a407b10..b7376d9 100644 --- a/apps/ios/ItemAtlas/Account.swift +++ b/apps/ios/ItemAtlas/Account.swift @@ -141,7 +141,8 @@ final class AtlasAccount { } func request(_ path: String, method: String = "GET", data: Data? = nil, - contentType: String = "application/json", timeout: TimeInterval? = nil) async throws -> Data { + contentType: String = "application/json", timeout: TimeInterval? = nil, + idempotencyKey: UUID? = nil) async throws -> Data { guard let configuration, let url = URL(string: path, relativeTo: configuration.api)?.absoluteURL, Self.sameOrigin(url, configuration.api), path.hasPrefix("/api/") else { throw AtlasError("接口地址无效。") @@ -151,6 +152,7 @@ final class AtlasAccount { request.httpMethod = method if let timeout { request.timeoutInterval = timeout } request.httpBody = data + if let idempotencyKey { request.setValue(idempotencyKey.uuidString, forHTTPHeaderField: "Idempotency-Key") } if data != nil { request.setValue(contentType, forHTTPHeaderField: "Content-Type") } let access = try await accessToken(configuration) guard requestGeneration == generation else { throw CancellationError() } diff --git a/apps/ios/ItemAtlas/Editors.swift b/apps/ios/ItemAtlas/Editors.swift index feea2d5..9f04595 100644 --- a/apps/ios/ItemAtlas/Editors.swift +++ b/apps/ios/ItemAtlas/Editors.swift @@ -1,3 +1,4 @@ +import PhotosUI import SwiftUI struct ItemEditor: View { @@ -10,23 +11,61 @@ struct ItemEditor: View { @State private var aliases = "" @State private var quantity = 1 @State private var notes = "" + @State private var price = "" + @State private var icon = "BOX" @State private var locationID: UUID? @State private var showingAddLocation = false @State private var loadingLocations = true + @State private var initialized = false @State private var error: String? @State private var busy = false - private enum Field { case name, aliases, notes } + @State private var photoSelection: PhotosPickerItem? + @State private var loadingPhoto = false + @State private var crop: CropSource? + @State private var photo: Data? + @State private var photoKey = UUID() + @State private var createKey = UUID() + @State private var savedItem: Item? + + private enum Field { case name, aliases, price, notes } + + private var canSave: Bool { + !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && locationID != nil && validPrice && + !busy && !loadingPhoto + } + + private var validPrice: Bool { + price.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || PurchasePrice.cents(from: price) != nil + } var body: some View { NavigationStack { Form { + if savedItem != nil { + Section { + Text("物品已保存,照片可以重试上传。") + Button("稍后添加照片") { dismiss() }.disabled(busy) + } + } Section("物品") { TextField("名称", text: $name).focused($focus, equals: .name) TextField("别名,用逗号隔开", text: $aliases).focused($focus, equals: .aliases) Stepper("数量:\(quantity)", value: $quantity, in: 1...9999) + TextField("购入单价(元,可选)", text: $price).keyboardType(.decimalPad) + .focused($focus, equals: .price) + if !validPrice { + Text("请输入 0 到 99,999,999.99 元,最多两位小数。") + .font(.footnote).foregroundStyle(.secondary) + } TextField("备注", text: $notes, axis: .vertical).focused($focus, equals: .notes) } + .disabled(busy || savedItem != nil) + photoSection + Section("图标") { + SymbolPicker(symbols: InventorySymbol.items, color: .teal, selection: $icon) + } + .disabled(busy || savedItem != nil) if existing == nil { Section("放在哪") { LocationPicker(store: store, selection: $locationID) @@ -34,44 +73,114 @@ struct ItemEditor: View { Button("新建位置") { focus = nil; showingAddLocation = true } } } + .disabled(busy || savedItem != nil) } if let error { Text(error).foregroundStyle(.red) } } .dismissibleKeyboard(active: focus != nil) { focus = nil } .navigationTitle(existing == nil ? "添加物品" : "编辑物品") + .navigationBarTitleDisplayMode(.inline) .toolbar { - ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) } + ToolbarItem(placement: .cancellationAction) { + Button(savedItem == nil ? "取消" : "关闭") { dismiss() }.disabled(busy) + } ToolbarItem(placement: .confirmationAction) { - Button("保存") { focus = nil; Task { await save() } } - .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || locationID == nil || busy) + Button(savedItem == nil ? "保存" : "重试上传") { focus = nil; Task { await save() } } + .disabled(!canSave) } } .sheet(isPresented: $showingAddLocation) { PlaceEditor(store: store) { locationID = $0 } } + .sheet(item: $crop) { source in + CropEditor(source: source, actionTitle: "使用照片") { jpeg in + photo = jpeg + photoKey = UUID() + } + } } .interactiveDismissDisabled(busy) .task { + guard !initialized else { return } + initialized = true name = existing?.name ?? "" aliases = existing?.aliases.joined(separator: "、") ?? "" quantity = existing?.quantity ?? 1 notes = existing?.notes ?? "" + price = existing?.priceCents.map(PurchasePrice.input) ?? "" + icon = InventorySymbol.item(existing?.icon).id locationID = existing?.locationId ?? initialLocation do { if existing == nil { try await store.refreshLocations() } } catch { self.error = error.localizedDescription } loadingLocations = false } + .task(id: photoSelection) { + guard let selection = photoSelection else { return } + loadingPhoto = true + defer { + if photoSelection == selection { + loadingPhoto = false + photoSelection = nil + } + } + do { + guard let source = try await selection.loadTransferable(type: CropSource.self) else { + throw AtlasError("这张照片无法打开,请重新选择。") + } + try Task.checkCancellation() + focus = nil + error = nil + crop = source + } catch where !Task.isCancelled { self.error = error.localizedDescription } + catch {} + } + } + + private var photoSection: some View { + Section("照片") { + if let photo, let preview = UIImage(data: photo) { + Image(uiImage: preview) + .resizable().scaledToFit() + .frame(maxHeight: 130) + .clipShape(.rect(cornerRadius: 10)) + .accessibilityLabel("待上传照片") + if savedItem == nil { + Button("移除待上传照片", role: .destructive) { self.photo = nil }.disabled(busy) + } + } else if let existing, let cover = existing.coverPhotoId { + PhotoImage(store: store, item: existing.id, photo: cover, thumbnail: true) + .frame(width: 82, height: 82).clipShape(.rect(cornerRadius: 10)) + } + if savedItem == nil { + PhotosPicker(selection: $photoSelection, matching: .images, preferredItemEncoding: .current) { + Label(photo == nil ? "选择照片" : "更换待上传照片", systemImage: "photo.badge.plus") + } + .disabled(busy || loadingPhoto) + } + if busy && photo != nil { ProgressView("正在保存") } + if loadingPhoto { ProgressView("读取照片") } + } } private func save() async { - guard let locationID else { return } - let aliasList = aliases.split(whereSeparator: { ",,、".contains($0) }) - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } + guard canSave, let locationID else { return } busy = true + error = nil defer { busy = false } do { - _ = try await store.save(ItemInput(name: name, quantity: quantity, notes: notes, locationId: locationID, - aliases: aliasList, version: existing?.version), id: existing?.id) + let item: Item + if let savedItem { + item = savedItem + } else { + let aliasList = aliases.split(whereSeparator: { ",,、".contains($0) }) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } + let input = ItemInput(name: name, quantity: quantity, notes: notes, locationId: locationID, + aliases: aliasList, version: existing?.version, + appearance: .init(icon: icon, priceCents: PurchasePrice.cents(from: price))) + item = try await store.save(input, id: existing?.id, idempotencyKey: existing == nil ? createKey : nil) + savedItem = item + } + if let photo { try await store.upload(photo, item: item.id, idempotencyKey: photoKey) } dismiss() } catch { self.error = error.localizedDescription } } diff --git a/apps/ios/ItemAtlas/InventoryAppearance.swift b/apps/ios/ItemAtlas/InventoryAppearance.swift new file mode 100644 index 0000000..9a1ab55 --- /dev/null +++ b/apps/ios/ItemAtlas/InventoryAppearance.swift @@ -0,0 +1,95 @@ +import SwiftUI + +struct InventorySymbol: Identifiable { + let id: String + let title: String + let image: String + + static let locations: [Self] = [ + .init(id: "FOLDER", title: "默认", image: "folder.fill"), + .init(id: "HOME", title: "房间", image: "house.fill"), + .init(id: "DESK", title: "书桌", image: "desktopcomputer"), + .init(id: "CABINET", title: "柜子", image: "cabinet.fill"), + .init(id: "DRAWER", title: "抽屉", image: "tray.fill"), + .init(id: "BASKET", title: "收纳篮", image: "basket.fill") + ] + + static let items: [Self] = [ + .init(id: "BOX", title: "默认", image: "shippingbox.fill"), + .init(id: "CABLE", title: "线材", image: "cable.connector"), + .init(id: "BOOK", title: "书本", image: "book.closed.fill"), + .init(id: "TOOL", title: "工具", image: "wrench.and.screwdriver.fill"), + .init(id: "CLOTHING", title: "衣物", image: "tshirt.fill"), + .init(id: "KEY", title: "钥匙", image: "key.fill") + ] + + static func location(_ value: String?) -> Self { resolve(value, in: locations) } + + static func item(_ value: String?) -> Self { resolve(value, in: items) } + + private static func resolve(_ value: String?, in symbols: [Self]) -> Self { + symbols.first { $0.id == value } ?? symbols[0] + } +} + +struct SymbolPicker: View { + let symbols: [InventorySymbol] + let color: Color + @Binding var selection: String + + var body: some View { + LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 12) { + ForEach(symbols) { symbol in + let selected = selection == symbol.id + Button { selection = symbol.id } label: { + VStack(spacing: 5) { + Image(systemName: symbol.image) + .font(.title3) + .frame(width: 42, height: 38) + .foregroundStyle(color) + .background(color.opacity(selected ? 0.15 : 0.06), in: .rect(cornerRadius: 10)) + .overlay { + RoundedRectangle(cornerRadius: 10) + .strokeBorder(selected ? color : .clear, lineWidth: 1.5) + } + .accessibilityHidden(true) + Text(symbol.title).font(.caption).foregroundStyle(.primary) + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.plain) + .accessibilityAddTraits(selected ? .isSelected : []) + } + } + .padding(.vertical, 6) + } +} + +enum PurchasePrice { + static func cents(from text: String, decimalSeparator: String = Locale.current.decimalSeparator ?? ".") -> Int64? { + let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines) + .folding(options: .widthInsensitive, locale: .current) + .replacingOccurrences(of: decimalSeparator, with: ".") + let parts = normalized.split(separator: ".", omittingEmptySubsequences: false) + guard let whole = parts.first, parts.count <= 2 else { return nil } + let fraction = parts.count == 2 ? parts[1] : "" + guard !whole.isEmpty || !fraction.isEmpty, + whole.count <= 8, fraction.count <= 2, + whole.allSatisfy({ $0 >= "0" && $0 <= "9" }), + fraction.allSatisfy({ $0 >= "0" && $0 <= "9" }) + else { return nil } + let yuan = Int64(whole) ?? 0 + let minor = (Int64(fraction) ?? 0) * (fraction.count == 1 ? 10 : 1) + return yuan * 100 + minor + } + + static func input(_ cents: Int64) -> String { + let fraction = cents % 100 + let separator = Locale.current.decimalSeparator ?? "." + return "\(cents / 100)\(separator)\(fraction < 10 ? "0" : "")\(fraction)" + } + + static func display(_ cents: Int64) -> String { + (Decimal(cents) / 100).formatted(.currency(code: "CNY")) + } +} diff --git a/apps/ios/ItemAtlas/InventoryStore.swift b/apps/ios/ItemAtlas/InventoryStore.swift index a11ffd0..04e3adc 100644 --- a/apps/ios/ItemAtlas/InventoryStore.swift +++ b/apps/ios/ItemAtlas/InventoryStore.swift @@ -13,6 +13,7 @@ struct Place: Decodable, Identifiable { let parentId: UUID? let name: String let path: String + var icon: String? = nil } struct Item: Decodable, Identifiable { @@ -25,6 +26,8 @@ struct Item: Decodable, Identifiable { let version: Int let aliases: [String] let coverPhotoId: UUID? + var icon: String? = nil + var priceCents: Int64? = nil } struct ItemInput: Encodable { @@ -34,6 +37,12 @@ struct ItemInput: Encodable { let locationId: UUID let aliases: [String] var version: Int? = nil + var appearance: Appearance? = nil + + struct Appearance: Encodable { + let icon: String + let priceCents: Int64? + } } struct ItemDetail: Decodable { @@ -96,22 +105,30 @@ final class InventoryStore { try JSONDecoder().decode(T.self, from: await account.request(path)) } - func send(_ path: String, method: String = "POST", _ value: T) async throws -> R { - let response = try await account.request(path, method: method, data: JSONEncoder().encode(value)) + func send(_ path: String, method: String = "POST", _ value: T, + idempotencyKey: UUID? = nil) async throws -> R { + let response = try await account.request(path, method: method, data: JSONEncoder().encode(value), + idempotencyKey: idempotencyKey) return try JSONDecoder().decode(R.self, from: response) } - func save(_ item: ItemInput, id: UUID? = nil) async throws -> Item { - let created: Item = try await send(itemPath(id), method: id == nil ? "POST" : "PUT", item) + func save(_ item: ItemInput, id: UUID? = nil, idempotencyKey: UUID? = nil) async throws -> Item { + let created: Item = try await send(itemPath(id), method: id == nil ? "POST" : "PUT", item, + idempotencyKey: idempotencyKey) changed() return created } - func saveLocation(name: String, parent: UUID?) async throws -> UUID { - struct Input: Encodable { let name: String; let parentId: UUID? } - let place: Place = try await send(root + "/locations", Input(name: name, parentId: parent)) - locations.removeAll { $0.id == place.id } - locations.append(place) + func saveLocation(name: String, parent: UUID?, icon: String, id: UUID?) async throws -> UUID { + struct Input: Encodable { let name: String; let parentId: UUID?; let icon: String } + let address = root + "/locations" + (id.map { "/\($0)" } ?? "") + let place: Place = try await send(address, method: id == nil ? "POST" : "PUT", + Input(name: name, parentId: parent, icon: icon)) + if let index = locations.firstIndex(where: { $0.id == place.id }) { + locations[index] = place + } else { + locations.append(place) + } changed() return place.id } @@ -120,14 +137,14 @@ final class InventoryStore { root + "/items" + (id.map { "/\($0)" } ?? "") } - func upload(_ image: Data, item: UUID) async throws { + func upload(_ image: Data, item: UUID, idempotencyKey: UUID? = nil) async throws { guard image.count <= 5 * 1024 * 1024 else { throw AtlasError("图片不能超过 5 MiB。") } let boundary = UUID().uuidString var payload = Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"image\"; filename=\"photo.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n".utf8) payload.append(image) payload.append(Data("\r\n--\(boundary)--\r\n".utf8)) _ = try await account.request(itemPath(item) + "/photos", method: "POST", data: payload, - contentType: "multipart/form-data; boundary=\(boundary)") + contentType: "multipart/form-data; boundary=\(boundary)", idempotencyKey: idempotencyKey) changed() } diff --git a/apps/ios/ItemAtlas/InventoryView.swift b/apps/ios/ItemAtlas/InventoryView.swift index c989351..35b3707 100644 --- a/apps/ios/ItemAtlas/InventoryView.swift +++ b/apps/ios/ItemAtlas/InventoryView.swift @@ -199,7 +199,8 @@ struct ItemsSection: View { ForEach(results.rows) { item in NavigationLink { ItemDetailView(store: store, itemID: item.id) } label: { HStack(spacing: 12) { - PhotoImage(store: store, item: item.id, photo: item.coverPhotoId, thumbnail: true) + PhotoImage(store: store, item: item.id, photo: item.coverPhotoId, thumbnail: true, + placeholderSymbol: InventorySymbol.item(item.icon).image) .frame(width: 46, height: 46).clipShape(.rect(cornerRadius: 8)).accessibilityHidden(true) VStack(alignment: .leading, spacing: 3) { Text(item.name).font(.headline) @@ -260,6 +261,9 @@ struct ItemDetailView: View { } Section("物品信息") { LabeledContent("数量", value: "\(detail.item.quantity)") + if let price = detail.item.priceCents { + LabeledContent("购入单价", value: PurchasePrice.display(price)) + } if !detail.item.aliases.isEmpty { LabeledContent("别名", value: detail.item.aliases.joined(separator: "、")) } if !detail.item.notes.isEmpty { Text(detail.item.notes) } } diff --git a/apps/ios/ItemAtlas/ItemPhotos.swift b/apps/ios/ItemAtlas/ItemPhotos.swift index c368402..28eae0c 100644 --- a/apps/ios/ItemAtlas/ItemPhotos.swift +++ b/apps/ios/ItemAtlas/ItemPhotos.swift @@ -8,6 +8,7 @@ struct PhotoImage: View { let item: UUID let photo: UUID? let thumbnail: Bool + var placeholderSymbol = "shippingbox.fill" @State private var image: UIImage? @State private var error = false @State private var retry = 0 @@ -25,7 +26,8 @@ struct PhotoImage: View { } else if !thumbnail, error { Button("重新加载图片") { retry += 1 } } else { - Image(systemName: error ? "photo" : "archivebox").foregroundStyle(Color.atlasBlue) + Image(systemName: error ? "photo" : placeholderSymbol) + .foregroundStyle(error ? Color.secondary : Color.teal) } } .frame(width: geometry.size.width, height: geometry.size.height) @@ -112,7 +114,7 @@ struct ItemPhotos: View { } } -private struct CropSource: Transferable, Identifiable { +struct CropSource: Transferable, Identifiable { let id = UUID() let image: CGImage @@ -131,8 +133,9 @@ private struct CropSource: Transferable, Identifiable { } } -private struct CropEditor: View { +struct CropEditor: View { let source: CropSource + var actionTitle = "上传" let save: (Data) async throws -> Void @Environment(\.dismiss) private var dismiss @State private var zoom: Double = 1 @@ -176,7 +179,7 @@ private struct CropEditor: View { .toolbar { ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) } ToolbarItem(placement: .confirmationAction) { - Button("上传") { Task { await upload() } }.disabled(busy || side <= 1) + Button(actionTitle) { Task { await upload() } }.disabled(busy || side <= 1) } } } diff --git a/apps/ios/ItemAtlas/LocationPicker.swift b/apps/ios/ItemAtlas/LocationPicker.swift index 47f5e7c..1aa2887 100644 --- a/apps/ios/ItemAtlas/LocationPicker.swift +++ b/apps/ios/ItemAtlas/LocationPicker.swift @@ -145,7 +145,7 @@ struct LocationSelection: View { choice(place) } else { NavigationLink(value: place.id) { - row(place.name, detail: nil, symbol: "folder", checked: selected == place.id) + row(place.name, detail: nil, symbol: InventorySymbol.location(place.icon).image, checked: selected == place.id) } } } @@ -153,7 +153,7 @@ struct LocationSelection: View { private func choice(_ place: Place, showsPath: Bool = false) -> some View { Button { pick(place.id) } label: { - row(place.name, detail: showsPath ? place.path : nil, symbol: "folder", + row(place.name, detail: showsPath ? place.path : nil, symbol: InventorySymbol.location(place.icon).image, checked: selected == place.id) } .buttonStyle(.plain) diff --git a/apps/ios/ItemAtlas/LocationView.swift b/apps/ios/ItemAtlas/LocationView.swift index 745f36d..254e87d 100644 --- a/apps/ios/ItemAtlas/LocationView.swift +++ b/apps/ios/ItemAtlas/LocationView.swift @@ -3,32 +3,42 @@ import SwiftUI struct LocationView: View { let store: InventoryStore var body: some View { - NavigationStack { LocationContents(store: store, location: nil) } + NavigationStack { LocationContents(store: store, initialLocation: nil) } } } private struct LocationContents: View { let store: InventoryStore - let location: Place? + let initialLocation: Place? @Environment(\.dismiss) private var dismiss @State private var items = ItemListResults() + @State private var addingLocation = false @State private var editingLocation = false @State private var confirmingDelete = false @State private var error: String? @State private var retry = 0 @State private var busy = false + private var location: Place? { + guard let initialLocation else { return nil } + return store.locations.first { $0.id == initialLocation.id } ?? initialLocation + } + var body: some View { List { - if let location { Text(location.path).foregroundStyle(.secondary) } + if let location { + Label(location.path, systemImage: InventorySymbol.location(location.icon).image) + .foregroundStyle(.secondary) + } Section(location == nil ? "房间和区域" : "子位置") { ForEach(store.locations.filter { $0.parentId == location?.id }) { child in - NavigationLink { LocationContents(store: store, location: child) } label: { - Label(child.name, systemImage: "folder") + NavigationLink { LocationContents(store: store, initialLocation: child) } label: { + Label(child.name, systemImage: InventorySymbol.location(child.icon).image) + .labelStyle(.titleAndIcon) } } if store.canWrite { - Button { editingLocation = true } label: { + Button { addingLocation = true } label: { Label(location == nil ? "新建位置" : "新建子位置", systemImage: "plus") } } @@ -41,6 +51,13 @@ private struct LocationContents: View { } .navigationTitle(location?.name ?? "位置") .navigationBarTitleDisplayMode(.inline) + .toolbar { + if location != nil && store.canWrite { + ToolbarItem(placement: .topBarTrailing) { + Button("编辑") { editingLocation = true }.disabled(busy) + } + } + } .task(id: items.loadID(query: "", revision: store.revision)) { if let location { await items.load(store: store, location: location.id) } } @@ -48,7 +65,14 @@ private struct LocationContents: View { do { try await store.refreshLocations(); error = nil } catch { self.error = error.localizedDescription } } - .sheet(isPresented: $editingLocation) { PlaceEditor(store: store, parent: location?.id) { _ in } } + .sheet(isPresented: $addingLocation) { + PlaceEditor(store: store, parent: location?.id) { _ in } + } + .sheet(isPresented: $editingLocation) { + if let location { + PlaceEditor(store: store, existing: location) { _ in retry += 1 } + } + } .confirmationDialog("删除这个位置?", isPresented: $confirmingDelete, titleVisibility: .visible) { Button("删除位置", role: .destructive) { guard let location else { return } @@ -68,26 +92,48 @@ private struct LocationContents: View { struct PlaceEditor: View { let store: InventoryStore - var parent: UUID? = nil + let parent: UUID? + let existing: Place? let saved: (UUID) -> Void @Environment(\.dismiss) private var dismiss @FocusState private var focused: Bool - @State private var name = "" + @State private var name: String + @State private var icon: String @State private var error: String? @State private var busy = false + init(store: InventoryStore, parent: UUID? = nil, existing: Place? = nil, + saved: @escaping (UUID) -> Void) { + self.store = store + self.parent = parent + self.existing = existing + self.saved = saved + _name = State(initialValue: existing?.name ?? "") + _icon = State(initialValue: InventorySymbol.location(existing?.icon).id) + } + + private var title: String { + if existing != nil { return "编辑位置" } + return parent == nil ? "新建位置" : "新建子位置" + } + var body: some View { NavigationStack { Form { TextField("名称", text: $name).focused($focused) + Section("位置图标") { + SymbolPicker(symbols: InventorySymbol.locations, color: .atlasBlue, selection: $icon) + } if let error { Text(error).foregroundStyle(.red) } } + .disabled(busy) .dismissibleKeyboard(active: focused) { focused = false } - .navigationTitle(parent == nil ? "新建位置" : "新建子位置") + .navigationTitle(title) + .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) } ToolbarItem(placement: .confirmationAction) { - Button("保存") { Task { await save() } } + Button("保存") { focused = false; Task { await save() } } .disabled(busy || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } @@ -96,9 +142,14 @@ struct PlaceEditor: View { } private func save() async { + guard !busy else { return } busy = true defer { busy = false } - do { saved(try await store.saveLocation(name: name, parent: parent)); dismiss() } - catch { self.error = error.localizedDescription } + do { + let id = try await store.saveLocation(name: name, parent: existing?.parentId ?? parent, + icon: icon, id: existing?.id) + saved(id) + dismiss() + } catch { self.error = error.localizedDescription } } } 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 a26feae..90ffe0e 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 @@ -60,8 +60,9 @@ class InventoryController { } @PostMapping(FAMILY + "/items") - ResponseEntity create(@PathVariable UUID household, Principal user, @Valid @RequestBody ItemInput input) { - var item = service.create(household, user.getName(), input); + ResponseEntity create(@PathVariable UUID household, Principal user, @Valid @RequestBody ItemInput input, + @RequestHeader(value = "Idempotency-Key", required = false) UUID requestKey) { + var item = service.create(household, user.getName(), input, requestKey); return ResponseEntity.created(uri(household, "items", item.id())).body(item); } 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 4bfde2f..717121a 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 @@ -12,17 +12,22 @@ import java.util.List; import java.util.UUID; final class InventoryDtos { - record Location(UUID id, UUID parentId, String name, String path) {} - record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId) {} + enum LocationIcon { FOLDER, HOME, DESK, CABINET, DRAWER, BASKET } + enum ItemIcon { BOX, CABLE, BOOK, TOOL, CLOTHING, KEY } + + record Location(UUID id, UUID parentId, String name, String path, LocationIcon icon) {} + record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId, LocationIcon icon) {} + record Appearance(@NotNull ItemIcon icon, @Min(0) @Max(9_999_999_999L) Long priceCents) {} record Item(UUID id, String name, int quantity, String notes, UUID locationId, - String locationPath, int version, List aliases, UUID coverPhotoId) {} + String locationPath, int version, List aliases, UUID coverPhotoId, + ItemIcon icon, Long priceCents) {} 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) {} + @Size(max = 20) List<@NotBlank @Size(max = 80) String> aliases, @Valid Appearance appearance) {} record ItemEdit(@NotNull @Min(0) Integer version, @NotBlank @Size(max = 150) String name, @Min(1) @Max(9999) int quantity, @Size(max = 1500) String notes, - @Size(max = 20) List<@NotBlank @Size(max = 80) String> aliases) {} + @Size(max = 20) List<@NotBlank @Size(max = 80) String> aliases, @Valid Appearance appearance) {} record MoveInput(@NotNull UUID locationId, @NotNull @Min(0) Integer version) {} record Move(String fromPath, String toPath, OffsetDateTime movedAt) {} enum RelationKind { ACCESSORY, SIMILAR, TOGETHER } 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 ca0968c..27b56bc 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 @@ -19,12 +19,17 @@ import org.springframework.web.server.ResponseStatusException; class InventoryService { private static final RowMapper LOCATION = (rs, row) -> new Location( rs.getObject("id", UUID.class), rs.getObject("parent_id", UUID.class), - rs.getString("name"), rs.getString("path")); + rs.getString("name"), rs.getString("path"), LocationIcon.valueOf(rs.getString("icon"))); private static final RowMapper ITEM = (rs, row) -> new Item( rs.getObject("id", UUID.class), rs.getString("name"), rs.getInt("quantity"), 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)); + rs.getObject("cover_photo_id", UUID.class), ItemIcon.valueOf(rs.getString("icon")), + rs.getObject("price_cents", Long.class)); + private static final String SELECT_LOCATIONS = """ + SELECT p.*,l.icon FROM location_paths(:household) p + JOIN location l ON (l.household_id,l.id)=(p.household_id,p.id) + """; private static final String SCOPED_PATHS = "WITH paths AS (SELECT * FROM location_paths(:household))\n"; private static final String SEARCH_HITS = """ , hits AS ( @@ -64,7 +69,7 @@ class InventoryService { List locations(UUID household, String actor) { access.role(household, actor); - return db.sql("SELECT * FROM location_paths(:household) ORDER BY path,id") + return db.sql(SELECT_LOCATIONS + " ORDER BY p.path,p.id") .param("household", household).query(LOCATION).list(); } @@ -74,7 +79,7 @@ class InventoryService { } private Location location(UUID household, UUID id) { - return db.sql("SELECT * FROM location_paths(:household) WHERE id=:id") + return db.sql(SELECT_LOCATIONS + " WHERE p.id=:id") .param("household", household).param("id", id).query(LOCATION).optional() .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "位置不存在")); } @@ -94,11 +99,18 @@ class InventoryService { } UUID target = id == null ? UUID.randomUUID() : location(household, id).id(); String sql = id == null - ? "INSERT INTO location(household_id,id,parent_id,name) VALUES (:household,:id,:parent,:name)" - : "UPDATE location SET name=:name,parent_id=:parent WHERE household_id=:household AND id=:id"; + ? """ + INSERT INTO location(household_id,id,parent_id,name,icon) + VALUES (:household,:id,:parent,:name,COALESCE(:icon,'FOLDER')) + """ + : """ + UPDATE location SET name=:name,parent_id=:parent,icon=COALESCE(:icon,icon) + WHERE household_id=:household AND id=:id + """; try { db.sql(sql).param("id", target).param("household", household) - .param("parent", parent, Types.OTHER).param("name", input.name().strip()).update(); + .param("parent", parent, Types.OTHER).param("name", input.name().strip()) + .param("icon", input.icon() == null ? null : input.icon().name(), Types.VARCHAR).update(); } catch (DuplicateKeyException ex) { throw new ResponseStatusException(CONFLICT, "当前层级已有同名位置"); } @@ -172,20 +184,31 @@ class InventoryService { } @Transactional - Item create(UUID household, String actor, ItemInput input) { + Item create(UUID household, String actor, ItemInput input, UUID requestKey) { access.requireWrite(household, actor); + if (requestKey != null) { + var previous = db.sql(""" + SELECT id FROM item WHERE household_id=:household AND create_subject=:actor AND create_key=:key + """).param("household", household).param("actor", actor).param("key", requestKey) + .query(UUID.class).optional(); + if (previous.isPresent()) { return item(household, previous.get()); } + } location(household, input.locationId()); - return insertItem(household, input); + return insertItem(household, input, requestKey == null ? null : actor, requestKey); } - private Item insertItem(UUID household, ItemInput input) { + private Item insertItem(UUID household, ItemInput input, String creator, UUID requestKey) { UUID id = UUID.randomUUID(); + Appearance appearance = input.appearance(); db.sql(""" - INSERT INTO item(household_id,id,name,quantity,notes,location_id) - VALUES (:household,:id,:name,:quantity,:notes,:location) + INSERT INTO item(household_id,id,name,quantity,notes,location_id,icon,price_cents,create_subject,create_key) + VALUES (:household,:id,:name,:quantity,:notes,:location,:icon,:price,:creator,:key) """).param("household", household).param("id", id).param("name", input.name().strip()) .param("quantity", input.quantity()).param("notes", text(input.notes())) - .param("location", input.locationId()).update(); + .param("location", input.locationId()) + .param("icon", appearance == null ? ItemIcon.BOX.name() : appearance.icon().name()) + .param("price", appearance == null ? null : appearance.priceCents(), Types.BIGINT) + .param("creator", creator, Types.VARCHAR).param("key", requestKey, Types.OTHER).update(); saveAliases(household, id, input.aliases()); return item(household, id); } @@ -195,11 +218,14 @@ class InventoryService { access.requireWrite(household, actor); Item current = item(household, id); checkVersion(current, input.version()); + Appearance appearance = input.appearance(); db.sql(""" - UPDATE item SET name=:name,quantity=:quantity,notes=:notes,version=version+1 + UPDATE item SET name=:name,quantity=:quantity,notes=:notes,icon=:icon,price_cents=:price,version=version+1 WHERE household_id=:household AND id=:id """).param("household", household).param("id", id).param("name", input.name().strip()) - .param("quantity", input.quantity()).param("notes", text(input.notes())).update(); + .param("quantity", input.quantity()).param("notes", text(input.notes())) + .param("icon", (appearance == null ? current.icon() : appearance.icon()).name()) + .param("price", appearance == null ? current.priceCents() : appearance.priceCents(), Types.BIGINT).update(); db.sql("DELETE FROM item_alias WHERE household_id=:household AND item_id=:id") .param("household", household).param("id", id).update(); saveAliases(household, id, input.aliases()); @@ -304,7 +330,7 @@ class InventoryService { .param("id", operation).update(); return new DeliveryResult("REJECTED"); } - for (ItemInput input : delivery.items()) { insertItem(household, input); } + for (ItemInput input : delivery.items()) { insertItem(household, input, null, null); } return new DeliveryResult("APPLIED"); } diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoController.java index bb377af..3ea74e5 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoController.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoController.java @@ -23,8 +23,9 @@ class PhotoController { @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) ResponseEntity upload(@PathVariable UUID household, @PathVariable UUID item, - Principal user, @RequestPart("image") MultipartFile image) { - return ResponseEntity.status(201).body(service.upload(household, item, user.getName(), image)); + Principal user, @RequestPart("image") MultipartFile image, + @RequestHeader(value = "Idempotency-Key", required = false) UUID requestKey) { + return ResponseEntity.status(201).body(service.upload(household, item, user.getName(), image, requestKey)); } @GetMapping("/{id}") diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoService.java index 16f23c1..e8759ce 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoService.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/PhotoService.java @@ -3,7 +3,9 @@ package com.tutudog.itematlas.inventory; import static org.springframework.http.HttpStatus.*; import io.micrometer.core.instrument.MeterRegistry; +import java.sql.Types; import java.util.List; +import java.util.Optional; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,11 +50,13 @@ class PhotoService { .param("house", household).param("item", item).query(UUID.class).list().stream().map(Photo::new).toList(); } - Photo upload(UUID household, UUID item, String actor, MultipartFile file) { + Photo upload(UUID household, UUID item, String actor, MultipartFile file, UUID requestKey) { if ("VIEWER".equals(access.role(household, actor))) { throw new ResponseStatusException(FORBIDDEN, "当前角色只有查看权限"); } requireItem(household, item); + var existing = uploaded(household, item, actor, requestKey); + if (existing.isPresent()) { return existing.get(); } requireStorage(); var images = PhotoImages.encode(file); UUID id = UUID.randomUUID(); @@ -71,12 +75,18 @@ class PhotoService { int reserved = db.sql("DELETE FROM media_cleanup WHERE object_prefix=:prefix AND due_at>now()") .param("prefix", prefix).update(); if (reserved == 0) { throw new ResponseStatusException(CONFLICT, "上传已超时,请重试"); } + var previous = uploaded(household, item, actor, requestKey); + if (previous.isPresent()) { return previous.get(); } long count = db.sql("SELECT count(*) FROM item_photo WHERE household_id=:house AND item_id=:item") .param("house", household).param("item", item).query(Long.class).single(); if (count >= 6) { throw new ResponseStatusException(CONFLICT, "一件物品最多上传 6 张图片"); } storage.store(prefix, images); - db.sql("INSERT INTO item_photo(household_id,item_id,id,object_prefix) VALUES (:house,:item,:id,:prefix)") - .param("house", household).param("item", item).param("id", id).param("prefix", prefix).update(); + db.sql(""" + INSERT INTO item_photo(household_id,item_id,id,object_prefix,upload_subject,upload_key) + VALUES (:house,:item,:id,:prefix,:actor,:key) + """).param("house", household).param("item", item).param("id", id).param("prefix", prefix) + .param("actor", requestKey == null ? null : actor, Types.VARCHAR) + .param("key", requestKey, Types.OTHER).update(); return new Photo(id); }); } catch (RuntimeException failure) { @@ -88,6 +98,14 @@ class PhotoService { } } + private Optional uploaded(UUID household, UUID item, String actor, UUID requestKey) { + if (requestKey == null) { return Optional.empty(); } + return db.sql(""" + SELECT id FROM item_photo WHERE household_id=:house AND item_id=:item AND upload_subject=:actor AND upload_key=:key + """).param("house", household).param("item", item).param("actor", actor).param("key", requestKey) + .query(UUID.class).optional().map(Photo::new); + } + byte[] image(UUID household, UUID item, UUID id, String actor, boolean thumbnail) { access.role(household, actor); String prefix = db.sql("SELECT object_prefix FROM item_photo WHERE household_id=:house AND item_id=:item AND id=:id") diff --git a/backend/inventory-service/src/main/resources/db/migration/V9__inventory_appearance.sql b/backend/inventory-service/src/main/resources/db/migration/V9__inventory_appearance.sql new file mode 100644 index 0000000..dcf9902 --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V9__inventory_appearance.sql @@ -0,0 +1,22 @@ +ALTER TABLE location + ADD COLUMN icon varchar(16) NOT NULL DEFAULT 'FOLDER' + CHECK (icon IN ('FOLDER', 'HOME', 'DESK', 'CABINET', 'DRAWER', 'BASKET')); + +ALTER TABLE item + ADD COLUMN icon varchar(16) NOT NULL DEFAULT 'BOX' + CHECK (icon IN ('BOX', 'CABLE', 'BOOK', 'TOOL', 'CLOTHING', 'KEY')), + ADD COLUMN price_cents bigint CHECK (price_cents BETWEEN 0 AND 9999999999), + ADD COLUMN create_key uuid, + ADD COLUMN create_subject text, + ADD CONSTRAINT item_create_key_owner CHECK ((create_key IS NULL) = (create_subject IS NULL)); + +CREATE UNIQUE INDEX item_create_request ON item(household_id, create_subject, create_key) + WHERE create_key IS NOT NULL; + +ALTER TABLE item_photo + ADD COLUMN upload_key uuid, + ADD COLUMN upload_subject text, + ADD CONSTRAINT item_photo_upload_key_owner CHECK ((upload_key IS NULL) = (upload_subject IS NULL)); + +CREATE UNIQUE INDEX item_photo_upload_request ON item_photo(household_id, item_id, upload_subject, upload_key) + WHERE upload_key IS NOT NULL; diff --git a/backend/tests/ios_experience_smoke.py b/backend/tests/ios_experience_smoke.py index fb26bc0..af0df39 100644 --- a/backend/tests/ios_experience_smoke.py +++ b/backend/tests/ios_experience_smoke.py @@ -1,6 +1,7 @@ """Validate iOS workflows in a disposable environment with a native_account row for viewer.""" import concurrent.futures from urllib.parse import urlencode +from uuid import uuid4 from smoke import RUN, await_operation, call, ready @@ -11,6 +12,7 @@ def verify(): space = call("POST", "/api/households", {"name": "见物体验 " + RUN}, status=201) root = "/api/households/" + space["id"] try: + verify_inventory_appearance(root) verify_search_and_voice(root) verify_direct_invitations(root) finally: @@ -90,6 +92,38 @@ def verify_search_and_voice(root): print("PASS voice rules, automatic location guard and one outbox delivery", flush=True) +def verify_inventory_appearance(root): + locations = root + "/locations" + room = call("POST", locations, {"name": "储藏室", "icon": "HOME"}, status=201) + assert room["icon"] == "HOME" + box = call("POST", locations, {"name": "收纳柜", "parentId": room["id"]}, status=201) + assert box["icon"] == "FOLDER" + path = locations + "/" + box["id"] + edited = call("PUT", path, {"name": box["name"], "parentId": room["id"], "icon": "CABINET"}) + assert edited["parentId"] == room["id"] and edited["icon"] == "CABINET" + assert call("PUT", path, {"name": box["name"], "parentId": room["id"]})["icon"] == "CABINET" + call("PUT", path, {"name": box["name"], "parentId": room["id"], "icon": "KEY"}, status=400) + + items = root + "/items" + payload = {"name": "充电器套装", "quantity": 1, "locationId": box["id"], + "appearance": {"icon": "CABLE", "priceCents": 3999}} + key = uuid4() + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + created = list(pool.map(lambda _: call("POST", items, payload, status=201, request_key=key), range(2))) + assert created[0] == created[1] and created[0]["icon"] == "CABLE" and created[0]["priceCents"] == 3999 + item = created[0] + path = items + "/" + item["id"] + basic = {"name": item["name"], "quantity": 1, "version": item["version"]} + legacy_edit = call("PUT", path, basic) + assert legacy_edit["icon"] == "CABLE" and legacy_edit["priceCents"] == 3999 + edit = dict(basic, version=legacy_edit["version"], appearance={"icon": "TOOL", "priceCents": None}) + call("PUT", path, dict(edit, appearance={"icon": "TOOL", "priceCents": -1}), status=400) + updated = call("PUT", path, edit) + assert updated["icon"] == "TOOL" and updated["priceCents"] is None + assert call("GET", path)["item"] == updated + print("PASS location and item icons, integer price, older clients and deduplicated creation", flush=True) + + def verify_direct_invitations(root): sent = root + "/direct-invitations" inbox = "/api/households/direct-invitations" diff --git a/backend/tests/media_smoke.py b/backend/tests/media_smoke.py index c163d75..b8e96cc 100644 --- a/backend/tests/media_smoke.py +++ b/backend/tests/media_smoke.py @@ -1,4 +1,5 @@ """Run against a disposable gateway and private S3 bucket. Uses curl's AWS SigV4 for object checks.""" +import concurrent.futures import os from pathlib import Path import subprocess @@ -10,10 +11,12 @@ from urllib.request import urlopen from smoke import call, make_request -def upload(path, jpeg, *, user="owner", status=201): +def upload(path, jpeg, *, user="owner", status=201, request_key=None): boundary = uuid.uuid4().hex request = make_request("POST", path, None, user) request.add_header("Content-Type", f"multipart/form-data; boundary={boundary}") + if request_key is not None: + request.add_header("Idempotency-Key", str(request_key)) request.data = (f'--{boundary}\r\nContent-Disposition: form-data; name="image"; filename="photo.jpg"\r\n' f'Content-Type: image/jpeg\r\n\r\n').encode() + jpeg + f"\r\n--{boundary}--\r\n".encode() if status == 413: @@ -77,7 +80,11 @@ def main(): upload(photos, b"not a picture", status=415) upload(photos, b"x" * (5 * 1024 * 1024 + 1), status=413) upload(photos, b"x" * (6 * 1024 * 1024), status=413) - photo = json.loads(upload(photos, jpeg))["id"] + key = uuid.uuid4() + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + receipts = list(pool.map(lambda _: json.loads(upload(photos, jpeg, request_key=key)), range(2))) + assert receipts[0] == receipts[1] and call("GET", photos) == [receipts[0]] + photo = receipts[0]["id"] assert call("GET", space + "/items")[0]["coverPhotoId"] == photo assert call("GET", space + "/items?favorites=true") == [] call("PUT", f"{space}/items/{item['id']}/preference", {"favorite": True}) @@ -104,7 +111,7 @@ def main(): call("DELETE", space, status=202) call("GET", space, status=404) await_absence(house, second["id"], remaining) - print("PASS upload limits, separate thumbnail, authorization, favorites and all three OSS cleanup paths") + print("PASS upload limits, retry deduplication, thumbnail, authorization, favorites and OSS cleanup") if os.environ.get("ATLAS_SMOKE_ADMIN_TOKEN"): from smoke import TOKENS TOKENS["admin"] = os.environ["ATLAS_SMOKE_ADMIN_TOKEN"] diff --git a/backend/tests/smoke.py b/backend/tests/smoke.py index adf55be..85a5f1f 100644 --- a/backend/tests/smoke.py +++ b/backend/tests/smoke.py @@ -35,8 +35,10 @@ def make_request(method, path, payload, user): return request -def call(method, path, payload=None, *, user="owner", status=200): +def call(method, path, payload=None, *, user="owner", status=200, request_key=None): request = make_request(method, path, payload, user) + if request_key is not None: + request.add_header("Idempotency-Key", str(request_key)) try: response = urlopen(request, timeout=78) except HTTPError as error: diff --git a/docs/architecture/inventory-appearance.md b/docs/architecture/inventory-appearance.md new file mode 100644 index 0000000..a6ac71a --- /dev/null +++ b/docs/architecture/inventory-appearance.md @@ -0,0 +1,19 @@ +# 位置图标、物品单价与首张照片 + +## 字段和权限 + +Flyway V9 给位置与物品增加各自的图标标识,由 API 枚举和 PostgreSQL 约束校验。已有位置默认用文件夹,已有物品默认用箱子。位置详情与列表读取同一图标。位置层级由空间内的复合外键约束,编辑图标和名称沿用原来的空间写权限。 + +物品的 `appearance` 包含 `icon` 和可空的 `priceCents`。购入单价按人民币分存为整数,范围是 0 到 99,999,999.99 元。旧客户端省略 `appearance` 时保留现有字段。新版传入该对象且价格为空时清空单价。物品编辑沿用现有版本号校验。 + +## 首张照片 + +iOS 从相册读图,裁剪后的 JPEG 保留在编辑表单,保存时先创建物品,再按物品 ID 调用原照片接口。照片服务继续生成展示图和缩略图,存放在私有桶的 `households/{spaceId}/items/{itemId}/{photoId}/`。删除沿用对象清理队列。 + +新建物品与上传照片分别支持 UUID 格式的 `Idempotency-Key`。新建按空间、账号和请求键识别重试,照片增加物品范围。服务端先校验权限,重复请求返回已有记录。两次上传并发时,锁内再检查请求键,两个调用会取得同一张照片。照片失败时,iOS 保留已保存的物品和待上传图片,可单独重试。 + +## 验收与回退 + +在隔离 PostgreSQL 上运行 `backend/tests/ios_experience_smoke.py`,检查主子位置图标、购入价格、旧客户端兼容和并发创建。用独立 Garage 桶运行 `backend/tests/media_smoke.py`,检查并发重试、缩略图、大小限制、查看权限与对象清理。 + +部署前备份物品库。先升级物品服务并确认 Flyway V9,通过公网读取与真机验收后再交付 iOS。回退旧镜像时保留新增字段和索引。 [后端发布流程](../deployment/backend-release.md) diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md index de82caf..22db1e2 100644 --- a/docs/product/ios-experience.md +++ b/docs/product/ios-experience.md @@ -20,6 +20,12 @@ 找物页右上角显示当前空间。点开可看到可访问的空间和当前选中项,也可以进入完整的「我的空间」列表。 +## 位置图标和物品信息 + +打开房间、区域或子位置,点右上角「编辑」即可修改名称和图标。新建时也能选图标,位置列表和选位置页面会同步显示。 + +添加或编辑物品时,可以填写可选的购入单价、选择物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。 + ## 选存放位置 录音草稿、手动添加和移位使用同一个位置选择页。从房间或区域开始,逐层进入柜子、抽屉或收纳盒。房间和柜子本身也能作为存放位置,在对应页面点「选这个位置」。 diff --git a/docs/testing/cases.md b/docs/testing/cases.md index 0b27516..54fccc5 100644 --- a/docs/testing/cases.md +++ b/docs/testing/cases.md @@ -35,5 +35,7 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前 | TC-29 我的收藏 | R08 | 从「我的」进入收藏,检查空状态。收藏一件物品后再次进入,再切换空间,模拟一次加载失败并重试。 | 空、有内容和加载失败各有状态。当前空间的个人收藏在列表显示,失败后可重试。 | | TC-30 找物页切换空间 | R01 | 用有多个空间的账号进入找物,点右上角的空间名。检查选中项,切换另一个空间,再打开「我的空间」。 | 空间名与账号的空间列表一致。只有可访问的空间可选,切换后搜索读取新空间。 | | TC-31 分级选位置 | R02 | 建两个带同名收纳盒的分支,其中一个有三级。从录音草稿、添加物品和移位分别打开位置选择,逐级找一次,再用完整路径搜索。 | 叶子和上级节点都能选。搜索显示完整路径,选好后返回原表单,取消时保留原选择。 | +| TC-32 编辑位置与物品图标 | R02 | 为房间和子位置选择图标,再编辑子位置名称。新建物品并选择另一套物品图标。 | 位置层级保持正确,列表和选择页显示最新图标。无封面照片的物品显示物品图标。 | +| TC-33 购入单价与新建照片 | R09 | 添加物品,输入 39.99 元并选相册照片裁剪。模拟上传中断后重试。随后清空购入单价。 | 价格按分精确保存。照片可单独重试,只保留一件物品和一张照片,详情可读取原图和缩略图。清空后详情收起价格项。 | [测试与演示计划](plan.md)