From 3cf0728b81964126e906b3ae49a8654c2d4fcaec Mon Sep 17 00:00:00 2001 From: dongjf <1+dongjf@noreply.git.tutudog.com> Date: Thu, 26 Nov 2026 20:47:51 +0800 Subject: [PATCH] =?UTF-8?q?feat(ios):=20=E6=94=AF=E6=8C=81=E4=BD=8D?= =?UTF-8?q?=E7=BD=AE=E6=8B=8D=E7=85=A7=E3=80=81=E7=9B=B8=E5=86=8C=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0=E5=92=8C=E7=85=A7=E7=89=87=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/ios/AppInfo.plist | 2 + apps/ios/ItemAtlas.xcodeproj/project.pbxproj | 4 +- apps/ios/ItemAtlas/Editors.swift | 4 +- apps/ios/ItemAtlas/InventoryStore.swift | 32 ++- apps/ios/ItemAtlas/InventoryView.swift | 4 +- apps/ios/ItemAtlas/ItemPhotos.swift | 200 +++++++++++++----- apps/ios/ItemAtlas/LocationView.swift | 22 +- .../src/main/resources/application.yml | 4 +- .../itematlas/inventory/HouseholdService.java | 3 +- .../itematlas/inventory/InventoryDtos.java | 2 +- .../itematlas/inventory/InventoryService.java | 9 +- .../itematlas/inventory/PhotoController.java | 20 +- .../itematlas/inventory/PhotoService.java | 97 ++++++--- .../db/migration/V10__location_photos.sql | 29 +++ backend/tests/media_smoke.py | 51 ++++- docs/deployment/identity-and-media.md | 4 +- docs/product/ios-experience.md | 2 + docs/testing/cases.md | 1 + 18 files changed, 370 insertions(+), 120 deletions(-) create mode 100644 backend/inventory-service/src/main/resources/db/migration/V10__location_photos.sql diff --git a/apps/ios/AppInfo.plist b/apps/ios/AppInfo.plist index 0b5d491..14003ab 100644 --- a/apps/ios/AppInfo.plist +++ b/apps/ios/AppInfo.plist @@ -6,6 +6,8 @@ $(ATLAS_API_BASE_URL) AtlasOIDCIssuer $(ATLAS_OIDC_ISSUER) + NSCameraUsageDescription + 用于拍摄物品和位置照片,裁剪确认后上传到当前空间。 NSMicrophoneUsageDescription 用于录入物品时接收你说的话。 NSSpeechRecognitionUsageDescription diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj index c646606..53ff09c 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 = 10; + CURRENT_PROJECT_VERSION = 11; 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 = 10; + CURRENT_PROJECT_VERSION = 11; GENERATE_INFOPLIST_FILE = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; diff --git a/apps/ios/ItemAtlas/Editors.swift b/apps/ios/ItemAtlas/Editors.swift index 9f04595..96e1181 100644 --- a/apps/ios/ItemAtlas/Editors.swift +++ b/apps/ios/ItemAtlas/Editors.swift @@ -148,7 +148,7 @@ struct ItemEditor: View { 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) + PhotoImage(store: store, target: .item(existing.id), photo: cover, thumbnail: true) .frame(width: 82, height: 82).clipShape(.rect(cornerRadius: 10)) } if savedItem == nil { @@ -180,7 +180,7 @@ struct ItemEditor: View { 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) } + if let photo { try await store.upload(photo, target: .item(item.id), idempotencyKey: photoKey) } dismiss() } catch { self.error = error.localizedDescription } } diff --git a/apps/ios/ItemAtlas/InventoryStore.swift b/apps/ios/ItemAtlas/InventoryStore.swift index 04e3adc..a08054f 100644 --- a/apps/ios/ItemAtlas/InventoryStore.swift +++ b/apps/ios/ItemAtlas/InventoryStore.swift @@ -14,6 +14,7 @@ struct Place: Decodable, Identifiable { let name: String let path: String var icon: String? = nil + var coverPhotoId: UUID? = nil } struct Item: Decodable, Identifiable { @@ -72,6 +73,25 @@ struct ItemDetail: Decodable { struct Photo: Decodable, Identifiable { let id: UUID } +enum PhotoTarget: Hashable { + case item(UUID) + case location(UUID) + + var path: String { + switch self { + case let .item(id): "/items/\(id)/photos" + case let .location(id): "/locations/\(id)/photos" + } + } + + var title: String { + switch self { + case .item: "物品照片" + case .location: "位置照片" + } + } +} + @MainActor @Observable final class InventoryStore { @@ -88,7 +108,9 @@ final class InventoryStore { } func refreshLocations() async throws { - locations = try await get(root + "/locations") + let updated: [Place] = try await get(root + "/locations") + try Task.checkCancellation() + locations = updated } func search(_ query: String, favorites: Bool, location: UUID? = nil, offset: Int = 0) async throws -> [Item] { @@ -137,19 +159,19 @@ final class InventoryStore { root + "/items" + (id.map { "/\($0)" } ?? "") } - func upload(_ image: Data, item: UUID, idempotencyKey: UUID? = nil) async throws { + func upload(_ image: Data, target: PhotoTarget, 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, + _ = try await account.request(root + target.path, method: "POST", data: payload, contentType: "multipart/form-data; boundary=\(boundary)", idempotencyKey: idempotencyKey) changed() } - func image(item: UUID, photo: UUID, thumbnail: Bool) async throws -> Data { - try await account.request(itemPath(item) + "/photos/\(photo)?thumbnail=\(thumbnail)") + func image(target: PhotoTarget, photo: UUID, thumbnail: Bool) async throws -> Data { + try await account.request(root + target.path + "/\(photo)?thumbnail=\(thumbnail)") } func delete(_ path: String) async throws { diff --git a/apps/ios/ItemAtlas/InventoryView.swift b/apps/ios/ItemAtlas/InventoryView.swift index 35b3707..47b6ec6 100644 --- a/apps/ios/ItemAtlas/InventoryView.swift +++ b/apps/ios/ItemAtlas/InventoryView.swift @@ -199,7 +199,7 @@ 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, target: .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) { @@ -267,7 +267,7 @@ struct ItemDetailView: View { if !detail.item.aliases.isEmpty { LabeledContent("别名", value: detail.item.aliases.joined(separator: "、")) } if !detail.item.notes.isEmpty { Text(detail.item.notes) } } - ItemPhotos(store: store, item: itemID) + PhotoGallery(store: store, target: .item(itemID)) Section("我的评价") { PreferenceEditor(store: store, detail: detail, saved: { self.detail = $0 }) } if !detail.relations.isEmpty { Section("关联物品") { diff --git a/apps/ios/ItemAtlas/ItemPhotos.swift b/apps/ios/ItemAtlas/ItemPhotos.swift index 28eae0c..bc04e50 100644 --- a/apps/ios/ItemAtlas/ItemPhotos.swift +++ b/apps/ios/ItemAtlas/ItemPhotos.swift @@ -1,3 +1,4 @@ +import AVFoundation import ImageIO import PhotosUI import SwiftUI @@ -5,10 +6,11 @@ import UniformTypeIdentifiers struct PhotoImage: View { let store: InventoryStore - let item: UUID + let target: PhotoTarget let photo: UUID? let thumbnail: Bool var placeholderSymbol = "shippingbox.fill" + var placeholderTint: Color = .teal @State private var image: UIImage? @State private var error = false @State private var retry = 0 @@ -27,7 +29,7 @@ struct PhotoImage: View { Button("重新加载图片") { retry += 1 } } else { Image(systemName: error ? "photo" : placeholderSymbol) - .foregroundStyle(error ? Color.secondary : Color.teal) + .foregroundStyle(error ? Color.secondary : placeholderTint) } } .frame(width: geometry.size.width, height: geometry.size.height) @@ -38,7 +40,7 @@ struct PhotoImage: View { error = false guard let photo else { return } do { - let bytes = try await store.image(item: item, photo: photo, thumbnail: thumbnail) + let bytes = try await store.image(target: target, photo: photo, thumbnail: thumbnail) try Task.checkCancellation() image = UIImage(data: bytes) error = image == nil @@ -48,76 +50,174 @@ struct PhotoImage: View { } } -struct ItemPhotos: View { +struct PhotoGallery: View { let store: InventoryStore - let item: UUID + let target: PhotoTarget @State private var photos: [Photo] = [] @State private var picker: PhotosPickerItem? @State private var crop: CropSource? + @State private var cameraCrop: CropSource? + @State private var showingCamera = false @State private var preview: Photo? @State private var busy = false @State private var error: String? var body: some View { - Section("照片") { - if !photos.isEmpty { - ScrollView(.horizontal) { - HStack { - ForEach(photos) { photo in - Button { preview = photo } label: { - PhotoImage(store: store, item: item, photo: photo.id, thumbnail: true) - .frame(width: 74, height: 74).clipShape(.rect(cornerRadius: 9)) + Section(target.title) { + VStack(alignment: .leading, spacing: 14) { + if !photos.isEmpty { + ScrollView(.horizontal) { + HStack { + ForEach(photos) { photo in + Button { preview = photo } label: { + PhotoImage(store: store, target: target, photo: photo.id, thumbnail: true) + .frame(width: 74, height: 74).clipShape(.rect(cornerRadius: 9)) + } + .buttonStyle(.plain) + .accessibilityLabel("查看照片") } - .buttonStyle(.plain) - .accessibilityLabel("查看照片") } } + .scrollIndicators(.hidden) + } else { Text("暂无照片").foregroundStyle(.secondary) } + if store.canWrite && photos.count < 6 { + HStack(spacing: 20) { + if UIImagePickerController.isSourceTypeAvailable(.camera) { + Button { Task { await openCamera() } } label: { + Label("拍照", systemImage: "camera") + } + .buttonStyle(.borderless) + } + PhotosPicker(selection: $picker, matching: .images, preferredItemEncoding: .current) { + Label("从相册选", systemImage: "photo.badge.plus") + } + .buttonStyle(.borderless) + } + .disabled(busy) } - .scrollIndicators(.hidden) - } else { Text("暂无照片").foregroundStyle(.secondary) } - if store.canWrite && photos.count < 6 { - PhotosPicker(selection: $picker, matching: .images, preferredItemEncoding: .current) { - Label("添加照片", systemImage: "photo.badge.plus") - }.disabled(busy) - } - if busy { ProgressView() } - if let error { Text(error).foregroundStyle(.red); Button("刷新照片") { Task { await load() } } } - } - .task(id: store.revision) { await load() } - .task(id: picker) { - guard let picker else { return } - busy = true - defer { busy = false; self.picker = nil } - do { - guard let source = try await picker.loadTransferable(type: CropSource.self) else { - throw AtlasError("这张图片无法读取,请重新选择。") + if busy { ProgressView() } + if let error { Text(error).foregroundStyle(.red).font(.footnote) } + if error != nil { + Button("刷新照片") { Task { await load() } }.buttonStyle(.borderless) } - try Task.checkCancellation() - error = nil - crop = source - } catch { self.error = error.localizedDescription } - } - .sheet(item: $crop) { source in - CropEditor(source: source) { image in - try await store.upload(image, item: item) } - } - .sheet(item: $preview) { photo in - PhotoPreview(store: store, item: item, photo: photo) + .padding(.vertical, 4) + .task(id: store.revision) { await load() } + .task(id: picker) { + guard let selection = picker else { return } + busy = true + defer { + if picker == selection { + busy = false + picker = nil + } + } + do { + guard let source = try await selection.loadTransferable(type: CropSource.self) else { + throw AtlasError("这张图片无法读取,请重新选择。") + } + try Task.checkCancellation() + error = nil + crop = source + } catch where !Task.isCancelled { self.error = error.localizedDescription } + catch {} + } + .fullScreenCover(isPresented: $showingCamera, onDismiss: { + crop = cameraCrop + cameraCrop = nil + }) { + CameraPicker { image in + if let image { + cameraCrop = CropSource.cameraImage(image) + if cameraCrop == nil { error = "照片无法读取,请重新拍摄。" } + } + showingCamera = false + } + .ignoresSafeArea() + } + .sheet(item: $crop) { source in + CropEditor(source: source) { image in + try await store.upload(image, target: target, idempotencyKey: source.id) + } + } + .sheet(item: $preview) { photo in + PhotoPreview(store: store, target: target, photo: photo) + } } } + private func openCamera() async { + guard !busy, UIImagePickerController.isSourceTypeAvailable(.camera) else { return } + busy = true + defer { busy = false } + guard await AVCaptureDevice.requestAccess(for: .video) else { + error = "相机权限未开启。可以在系统设置中开启,或从相册选图。" + return + } + error = nil + showingCamera = true + } + private func load() async { - do { photos = try await store.get(store.itemPath(item) + "/photos"); error = nil } - catch where !Task.isCancelled { self.error = error.localizedDescription } + do { + let updated: [Photo] = try await store.get(store.root + target.path) + try Task.checkCancellation() + photos = updated + error = nil + } catch where !Task.isCancelled { self.error = error.localizedDescription } catch {} } } +private struct CameraPicker: UIViewControllerRepresentable { + let complete: (UIImage?) -> Void + + func makeCoordinator() -> Coordinator { Coordinator(complete: complete) } + + func makeUIViewController(context: Context) -> UIImagePickerController { + let camera = UIImagePickerController() + camera.sourceType = .camera + camera.cameraCaptureMode = .photo + camera.delegate = context.coordinator + return camera + } + + func updateUIViewController(_ controller: UIImagePickerController, context: Context) {} + + final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { + let complete: (UIImage?) -> Void + + init(complete: @escaping (UIImage?) -> Void) { self.complete = complete } + + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { complete(nil) } + + func imagePickerController(_ picker: UIImagePickerController, + didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { + complete(info[.originalImage] as? UIImage) + } + } +} + struct CropSource: Transferable, Identifiable { let id = UUID() let image: CGImage + @MainActor + static func cameraImage(_ photo: UIImage) -> CropSource? { + let longest = max(photo.size.width, photo.size.height) + guard longest.isFinite, longest > 0 else { return nil } + let factor = min(1, 2400 / longest) + let size = CGSize(width: photo.size.width * factor, height: photo.size.height * factor) + guard size.width > 0, size.height > 0 else { return nil } + let format = UIGraphicsImageRendererFormat() + format.scale = 1 + format.opaque = true + let rendered = UIGraphicsImageRenderer(size: size, format: format).image { _ in + photo.draw(in: CGRect(origin: .zero, size: size)) + } + return rendered.cgImage.map { CropSource(image: $0) } + } + static var transferRepresentation: some TransferRepresentation { FileRepresentation(importedContentType: .image) { source in let size = try source.file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 @@ -223,7 +323,7 @@ struct CropEditor: View { private struct PhotoPreview: View { let store: InventoryStore - let item: UUID + let target: PhotoTarget let photo: Photo @Environment(\.dismiss) private var dismiss @State private var confirm = false @@ -233,10 +333,10 @@ private struct PhotoPreview: View { var body: some View { NavigationStack { VStack { - PhotoImage(store: store, item: item, photo: photo.id, thumbnail: false) + PhotoImage(store: store, target: target, photo: photo.id, thumbnail: false) if let error { Text(error).foregroundStyle(.red) } } - .navigationTitle("物品照片") + .navigationTitle(target.title) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() }.disabled(busy) } @@ -256,7 +356,7 @@ private struct PhotoPreview: View { private func delete() async { busy = true defer { busy = false } - do { try await store.delete(store.itemPath(item) + "/photos/\(photo.id)"); dismiss() } + do { try await store.delete(store.root + target.path + "/\(photo.id)"); dismiss() } catch { self.error = error.localizedDescription } } } diff --git a/apps/ios/ItemAtlas/LocationView.swift b/apps/ios/ItemAtlas/LocationView.swift index 254e87d..77f2a30 100644 --- a/apps/ios/ItemAtlas/LocationView.swift +++ b/apps/ios/ItemAtlas/LocationView.swift @@ -29,12 +29,23 @@ private struct LocationContents: View { if let location { Label(location.path, systemImage: InventorySymbol.location(location.icon).image) .foregroundStyle(.secondary) + PhotoGallery(store: store, target: .location(location.id)) } Section(location == nil ? "房间和区域" : "子位置") { ForEach(store.locations.filter { $0.parentId == location?.id }) { child in NavigationLink { LocationContents(store: store, initialLocation: child) } label: { - Label(child.name, systemImage: InventorySymbol.location(child.icon).image) - .labelStyle(.titleAndIcon) + HStack(spacing: 12) { + Label(child.name, systemImage: InventorySymbol.location(child.icon).image) + if let cover = child.coverPhotoId { + Spacer(minLength: 0) + PhotoImage(store: store, target: .location(child.id), photo: cover, thumbnail: true, + placeholderSymbol: InventorySymbol.location(child.icon).image, + placeholderTint: .atlasBlue) + .frame(width: 38, height: 38) + .clipShape(.rect(cornerRadius: 7)) + .accessibilityHidden(true) + } + } } } if store.canWrite { @@ -61,9 +72,10 @@ private struct LocationContents: View { .task(id: items.loadID(query: "", revision: store.revision)) { if let location { await items.load(store: store, location: location.id) } } - .task(id: retry) { + .task(id: "\(retry):\(store.revision)") { do { try await store.refreshLocations(); error = nil } - catch { self.error = error.localizedDescription } + catch where !Task.isCancelled { self.error = error.localizedDescription } + catch {} } .sheet(isPresented: $addingLocation) { PlaceEditor(store: store, parent: location?.id) { _ in } @@ -86,7 +98,7 @@ private struct LocationContents: View { } catch { self.error = error.localizedDescription } } } - } message: { Text("有物品或子位置的位置需要先清空。") } + } message: { Text("请先清空物品和子位置。删除这个位置时,里面的照片会一起删除。") } } } diff --git a/backend/gateway/src/main/resources/application.yml b/backend/gateway/src/main/resources/application.yml index a34b545..0269786 100644 --- a/backend/gateway/src/main/resources/application.yml +++ b/backend/gateway/src/main/resources/application.yml @@ -24,12 +24,12 @@ spring: - Path=/api/model-providers,/api/households/{householdId}/drafts,/api/households/{householdId}/drafts/**,/api/households/{householdId}/operations/** filters: - RequestSize=64KB - - id: item-photo-upload + - id: photo-upload order: -5 uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081} predicates: - Method=POST - - Path=/api/households/{householdId}/items/{itemId}/photos + - Path=/api/households/{householdId}/items/{itemId}/photos,/api/households/{householdId}/locations/{locationId}/photos filters: - RequestSize=6MB - id: inventory diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java index 430f925..de8b4c9 100644 --- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java +++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/HouseholdService.java @@ -44,7 +44,8 @@ class HouseholdService { ManagedSpace managedSpace(UUID household) { return db.sql(""" SELECT h.id,h.name,(SELECT count(*) FROM item WHERE household_id=h.id AND archived_at IS NULL), - (SELECT count(*) FROM item_photo WHERE household_id=h.id) + (SELECT count(*) FROM item_photo WHERE household_id=h.id) + + (SELECT count(*) FROM location_photo WHERE household_id=h.id) FROM household h WHERE h.id=:id """).param("id", household).query((rs, row) -> new ManagedSpace(rs.getObject(1, UUID.class), rs.getString(2), rs.getLong(3), rs.getLong(4))).optional().orElseThrow(HouseholdAccess::missing); 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 717121a..c8bf37d 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 @@ -15,7 +15,7 @@ final class InventoryDtos { 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 Location(UUID id, UUID parentId, String name, String path, LocationIcon icon, UUID coverPhotoId) {} 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, 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 27b56bc..ab315fb 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,7 +19,8 @@ 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"), LocationIcon.valueOf(rs.getString("icon"))); + rs.getString("name"), rs.getString("path"), LocationIcon.valueOf(rs.getString("icon")), + rs.getObject("cover_photo_id", UUID.class)); 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"), @@ -27,7 +28,11 @@ class InventoryService { 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 + SELECT p.*,l.icon, + (SELECT photo.id FROM location_photo photo + WHERE (photo.household_id,photo.location_id)=(p.household_id,p.id) + ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id + 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"; 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 3ea74e5..477248b 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 @@ -1,5 +1,7 @@ package com.tutudog.itematlas.inventory; +import static com.tutudog.itematlas.inventory.PhotoService.Target.fromCollection; + import java.security.Principal; import java.util.List; import java.util.UUID; @@ -10,35 +12,35 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController -@RequestMapping("/api/households/{household}/items/{item}/photos") +@RequestMapping("/api/households/{household}/{collection:items|locations}/{entity}/photos") class PhotoController { private final PhotoService service; PhotoController(PhotoService service) { this.service = service; } @GetMapping - List list(@PathVariable UUID household, @PathVariable UUID item, Principal user) { - return service.list(household, item, user.getName()); + List list(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity, Principal user) { + return service.list(household, fromCollection(collection), entity, user.getName()); } @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - ResponseEntity upload(@PathVariable UUID household, @PathVariable UUID item, + ResponseEntity upload(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity, 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)); + return ResponseEntity.status(201).body(service.upload(household, fromCollection(collection), entity, user.getName(), image, requestKey)); } @GetMapping("/{id}") - ResponseEntity image(@PathVariable UUID household, @PathVariable UUID item, @PathVariable UUID id, + ResponseEntity image(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity, @PathVariable UUID id, Principal user, @RequestParam(defaultValue = "false") boolean thumbnail) { return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).cacheControl(CacheControl.noStore()) - .body(service.image(household, item, id, user.getName(), thumbnail)); + .body(service.image(household, fromCollection(collection), entity, id, user.getName(), thumbnail)); } @DeleteMapping("/{id}") - ResponseEntity delete(@PathVariable UUID household, @PathVariable UUID item, @PathVariable UUID id, + ResponseEntity delete(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity, @PathVariable UUID id, Principal user) { - service.delete(household, item, id, user.getName()); + service.delete(household, fromCollection(collection), entity, id, user.getName()); return ResponseEntity.accepted().build(); } } 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 e8759ce..f897329 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 @@ -43,27 +43,58 @@ class PhotoService { record Photo(UUID id) {} private record Cleanup(String prefix, int attempts) {} - List list(UUID household, UUID item, String actor) { - access.role(household, actor); - requireItem(household, item); - return db.sql("SELECT id FROM item_photo WHERE household_id=:house AND item_id=:item ORDER BY created_at,id") - .param("house", household).param("item", item).query(UUID.class).list().stream().map(Photo::new).toList(); + enum Target { + ITEM("items", "item", "item_photo", "item_id", "物品"), + LOCATION("locations", "location", "location_photo", "location_id", "位置"); + + final String collection; + final String entityTable; + final String photoTable; + final String foreignKey; + final String label; + + Target(String collection, String entityTable, String photoTable, String foreignKey, String label) { + this.collection = collection; + this.entityTable = entityTable; + this.photoTable = photoTable; + this.foreignKey = foreignKey; + this.label = label; + } + + static Target fromCollection(String collection) { + return switch (collection) { + case "items" -> ITEM; + case "locations" -> LOCATION; + default -> throw new ResponseStatusException(NOT_FOUND); + }; + } + + String photosWhere() { + return " FROM " + photoTable + " WHERE household_id=:house AND " + foreignKey + "=:entity"; + } } - Photo upload(UUID household, UUID item, String actor, MultipartFile file, UUID requestKey) { + List list(UUID household, Target target, UUID entity, String actor) { + access.role(household, actor); + requireEntity(household, target, entity); + return db.sql("SELECT id" + target.photosWhere() + " ORDER BY created_at,id") + .param("house", household).param("entity", entity).query(UUID.class).list().stream().map(Photo::new).toList(); + } + + Photo upload(UUID household, Target target, UUID entity, 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); + requireEntity(household, target, entity); + var existing = uploaded(household, target, entity, actor, requestKey); if (existing.isPresent()) { return existing.get(); } requireStorage(); var images = PhotoImages.encode(file); UUID id = UUID.randomUUID(); - String prefix = "households/" + household + "/items/" + item + "/" + id; + String prefix = "households/" + household + "/" + target.collection + "/" + entity + "/" + id; transaction.executeWithoutResult(status -> { access.requireWrite(household, actor); - requireItem(household, item); + requireEntity(household, target, entity); db.sql("INSERT INTO media_cleanup(object_prefix,due_at) VALUES (:prefix, now()+interval '1 hour')") .param("prefix", prefix).update(); }); @@ -71,20 +102,21 @@ class PhotoService { try { return transaction.execute(status -> { access.requireWrite(household, actor); - requireItem(household, item); + requireEntity(household, target, entity); 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); + var previous = uploaded(household, target, entity, 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 张图片"); } + long count = db.sql("SELECT count(*)" + target.photosWhere()) + .param("house", household).param("entity", entity).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,upload_subject,upload_key) - VALUES (:house,:item,:id,:prefix,:actor,:key) - """).param("house", household).param("item", item).param("id", id).param("prefix", prefix) + INSERT INTO %s(household_id,%s,id,object_prefix,upload_subject,upload_key) + VALUES (:house,:entity,:id,:prefix,:actor,:key) + """.formatted(target.photoTable, target.foreignKey)) + .param("house", household).param("entity", entity).param("id", id).param("prefix", prefix) .param("actor", requestKey == null ? null : actor, Types.VARCHAR) .param("key", requestKey, Types.OTHER).update(); return new Photo(id); @@ -98,18 +130,17 @@ class PhotoService { } } - private Optional uploaded(UUID household, UUID item, String actor, UUID requestKey) { + private Optional uploaded(UUID household, Target target, UUID entity, 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) + return db.sql("SELECT id" + target.photosWhere() + " AND upload_subject=:actor AND upload_key=:key") + .param("house", household).param("entity", entity).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) { + byte[] image(UUID household, Target target, UUID entity, 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") - .param("house", household).param("item", item).param("id", id).query(String.class).optional() + String prefix = db.sql("SELECT object_prefix" + target.photosWhere() + " AND id=:id") + .param("house", household).param("entity", entity).param("id", id).query(String.class).optional() .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "图片不存在")); requireStorage(); try { return storage.get(prefix, thumbnail); } @@ -117,11 +148,11 @@ class PhotoService { } @Transactional - void delete(UUID household, UUID item, UUID id, String actor) { + void delete(UUID household, Target target, UUID entity, UUID id, String actor) { access.requireWrite(household, actor); - requireItem(household, item); - db.sql("DELETE FROM item_photo WHERE household_id=:house AND item_id=:item AND id=:id") - .param("house", household).param("item", item).param("id", id).update(); + requireEntity(household, target, entity); + db.sql("DELETE" + target.photosWhere() + " AND id=:id") + .param("house", household).param("entity", entity).param("id", id).update(); } @Scheduled(fixedDelay = 2000) @@ -154,10 +185,10 @@ class PhotoService { return true; } - private void requireItem(UUID household, UUID item) { - db.sql("SELECT id FROM item WHERE household_id=:house AND id=:item AND archived_at IS NULL") - .param("house", household).param("item", item).query(UUID.class).optional() - .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在")); + private void requireEntity(UUID household, Target target, UUID entity) { + db.sql("SELECT id FROM " + target.entityTable + " WHERE household_id=:house AND id=:entity AND archived_at IS NULL") + .param("house", household).param("entity", entity).query(UUID.class).optional() + .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, target.label + "不存在")); } private void requireStorage() { if (storage == null) { throw unavailable(); } } diff --git a/backend/inventory-service/src/main/resources/db/migration/V10__location_photos.sql b/backend/inventory-service/src/main/resources/db/migration/V10__location_photos.sql new file mode 100644 index 0000000..b8adf95 --- /dev/null +++ b/backend/inventory-service/src/main/resources/db/migration/V10__location_photos.sql @@ -0,0 +1,29 @@ +CREATE TABLE location_photo ( + household_id uuid NOT NULL, + location_id uuid NOT NULL, + id uuid PRIMARY KEY, + object_prefix text NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT now(), + upload_key uuid, + upload_subject text, + FOREIGN KEY (household_id, location_id) REFERENCES location(household_id, id) ON DELETE CASCADE, + CHECK ((upload_key IS NULL) = (upload_subject IS NULL)) +); + +CREATE INDEX location_photo_location ON location_photo(household_id, location_id, created_at, id); +CREATE UNIQUE INDEX location_photo_upload_request ON location_photo(household_id, location_id, upload_subject, upload_key) + WHERE upload_key IS NOT NULL; + +CREATE TRIGGER location_photo_cleanup AFTER DELETE ON location_photo + FOR EACH ROW EXECUTE FUNCTION enqueue_photo_cleanup(); + +CREATE FUNCTION detach_archived_location_photos() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + DELETE FROM location_photo WHERE household_id=NEW.household_id AND location_id=NEW.id; + RETURN NEW; +END; +$$; + +CREATE TRIGGER location_archive_photo_cleanup AFTER UPDATE OF archived_at ON location + FOR EACH ROW WHEN (OLD.archived_at IS NULL AND NEW.archived_at IS NOT NULL) + EXECUTE FUNCTION detach_archived_location_photos(); diff --git a/backend/tests/media_smoke.py b/backend/tests/media_smoke.py index b8e96cc..b400f91 100644 --- a/backend/tests/media_smoke.py +++ b/backend/tests/media_smoke.py @@ -41,13 +41,13 @@ def response(request, status): return body -def storage_status(house, item, photo, filename): +def storage_status(house, item, photo, filename, collection="items"): endpoint = os.environ["ATLAS_MEDIA_ENDPOINT"].rstrip("/") region = os.environ["ATLAS_MEDIA_REGION"] bucket = os.environ["ATLAS_MEDIA_BUCKET"] key = os.environ["ATLAS_MEDIA_ACCESS_KEY"] secret = os.environ["ATLAS_MEDIA_SECRET_KEY"] - url = f"{endpoint}/{bucket}/households/{house}/items/{item}/{photo}/{filename}" + url = f"{endpoint}/{bucket}/households/{house}/{collection}/{item}/{photo}/{filename}" credentials = f'user = {key}:{secret}\n' result = subprocess.run(["curl", "-sS", "--max-time", "5", "-o", os.devnull, "-w", "%{http_code}", "--aws-sigv4", f"aws:amz:{region}:s3", "--config", "-", url], @@ -55,14 +55,51 @@ def storage_status(house, item, photo, filename): return result.stdout.strip() if result.returncode == 0 else "000" -def await_absence(house, item, photo): +def await_absence(house, item, photo, collection="items"): for _ in range(25): - if all(storage_status(house, item, photo, variant) == "404" for variant in ("image.jpg", "thumb.jpg")): + if all(storage_status(house, item, photo, variant, collection) == "404" + for variant in ("image.jpg", "thumb.jpg")): return time.sleep(1) raise AssertionError(f"Storage keys for {photo} still exist") +def verify_location_photos(house, space, jpeg): + import json + + room = call("POST", space + "/locations", {"name": "带照片的房间"}, status=201)["id"] + child = call("POST", space + "/locations", {"name": "收纳柜", "parentId": room}, status=201)["id"] + location = f"{space}/locations/{child}" + photos = location + "/photos" + assert call("GET", photos) == [] and call("GET", location)["coverPhotoId"] is None + upload(photos, jpeg, user="viewer", status=403) + call("GET", photos, user="other", status=404) + upload(photos, b"x" * (6 * 1024 * 1024), status=413) + 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]] + first = receipts[0]["id"] + second = json.loads(upload(photos, jpeg))["id"] + assert call("GET", location)["coverPhotoId"] == first + asset = f"{photos}/{first}" + full = response(make_request("GET", asset, None, "owner"), 200) + thumb = response(make_request("GET", asset + "?thumbnail=true", None, "viewer"), 200) + assert full[:2] == thumb[:2] == b"\xff\xd8" and len(full) > len(thumb) + assert all(storage_status(house, child, first, variant, "locations") == "200" + for variant in ("image.jpg", "thumb.jpg")) + call("DELETE", asset, user="viewer", status=403) + call("DELETE", asset, status=202) + await_absence(house, child, first, "locations") + assert call("GET", location)["coverPhotoId"] == second + call("DELETE", location, status=204) + call("GET", photos, status=404) + await_absence(house, child, second, "locations") + room_photo = json.loads(upload(f"{space}/locations/{room}/photos", jpeg))["id"] + print("PASS location photo routing, cover, permissions, retry and location cleanup", flush=True) + return room, room_photo + + def main(): import json @@ -106,11 +143,13 @@ def main(): await_absence(house, item["id"], archived) second = call("POST", space + "/items", {"name": "相册", "quantity": 1, "locationId": location}, status=201) remaining = json.loads(upload(f"{space}/items/{second['id']}/photos", jpeg))["id"] + room, room_photo = verify_location_photos(house, space, jpeg) call("DELETE", space, user="viewer", status=403) call("DELETE", f"/api/admin/households/{house}", status=403) call("DELETE", space, status=202) call("GET", space, status=404) await_absence(house, second["id"], remaining) + await_absence(house, room, room_photo, "locations") print("PASS upload limits, retry deduplication, thumbnail, authorization, favorites and OSS cleanup") if os.environ.get("ATLAS_SMOKE_ADMIN_TOKEN"): from smoke import TOKENS @@ -121,10 +160,12 @@ def main(): place = call("POST", api + "/locations", {"name": "盒子"}, status=201)["id"] second = call("POST", api + "/items", {"name": "纸盒", "quantity": 1, "locationId": place}, status=201) attached = json.loads(upload(f"{api}/items/{second['id']}/photos", jpeg))["id"] - assert call("GET", admin, user="admin")["photos"] == 1 + place_photo = json.loads(upload(f"{api}/locations/{place}/photos", jpeg))["id"] + assert call("GET", admin, user="admin")["photos"] == 2 call("DELETE", admin, user="admin", status=202) call("GET", api, status=404) await_absence(another, second["id"], attached) + await_absence(another, place, place_photo, "locations") print("PASS dedicated OIDC admin client, role, audited deletion and both OSS objects") finally: try: diff --git a/docs/deployment/identity-and-media.md b/docs/deployment/identity-and-media.md index 8d3aaf7..8cfd230 100644 --- a/docs/deployment/identity-and-media.md +++ b/docs/deployment/identity-and-media.md @@ -53,6 +53,8 @@ curl -sS -o /dev/null -w '%{http_code}\n' "https://$host/api/households" ## 对象存储 +Flyway V10 新增 `location_photo`,以空间和位置 ID 组成的外键约束归属。物理删除位置时外键级联删除照片记录,软删除位置时由归档触发器删除记录。这两条路径都会进入已有的清理队列,旧版物品服务回退后删除空间也受数据库约束保护。位置和物品照片共用 5 MiB 文件上限,网关为两条上传路由提供 6 MB 请求上限。 + 物品服务使用 AWS SDK for Java 2.x 的 S3 接口。Helm 从物品服务已有的 Secret 注入配置。提前创建独立私有桶,服务账号只有这个桶的指定前缀读、写和删除权限。Garage 本地环境把 `metadata_dir`、`data_dir` 和宿主容器运行数据都放在外置 SSD 上。生产实例的备份需同时考虑 PostgreSQL 和对象存储。 | 环境变量 | 用途 | @@ -65,7 +67,7 @@ curl -sS -o /dev/null -w '%{http_code}\n' "https://$host/api/households" Bucket 关闭匿名访问,当前清理语义要求关闭版本保留和对象锁。开启这些能力前须另行定义版本删除及保留策略。Nginx 上传大小设为 `6m`,网关及 multipart 总上限 6 MiB,单图上限 5 MiB。后端按解码器校验 JPEG 和像素,最长边上限为 2048,重新编码时去掉图片元数据。每张图以独立 UUID 保存两份对象。读取经 API 校验当前成员身份,列表可以只请求最长边 320 像素的 `thumbnail=true` 响应。 -对象键为 `households/{空间}/items/{物品}/{图片}/image.jpg` 和 `thumb.jpg`。上传先提交清理预留,再写两个对象,成功后提交图片和取消预留。图片删除、物品归档、空间删除使用同一数据库触发器登记清理。空间删除立即撤销访问并移除物品数据,管理路径另外写审计。旧的批量录入审计仍在录入服务库,空间删除后接口会拒绝访问,录入审计保留策略需单独维护。 +物品照片使用 `households/{空间}/items/{物品}/{图片}/`,位置照片使用 `households/{空间}/locations/{位置}/{图片}/`。每张照片存 `image.jpg` 和 `thumb.jpg`。上传先提交清理预留,再写两个对象,成功后提交照片并取消预留。照片删除、物品归档、位置归档和空间删除由数据库触发器登记清理。空间删除立即撤销访问并移除空间数据,管理路径另外写审计。旧的批量录入审计仍在录入服务库,空间删除后接口会拒绝访问,录入审计保留策略需单独维护。 清理任务在物品服务领取,利用 `FOR UPDATE SKIP LOCKED` 避免多个 Pod 重复领取,同一个对象可安全重删。丢失响应或 OSS 暂时不可用时,任务会退避后重试。观察 `atlas_media_cleanup_pending` 和 `atlas_media_cleanup_attempts_total{result="retry"}` 判断是否积压。网关和图片接口返回 `202` 表示删除已受理,核对物理删除请检查清理队列和两个对象键。 diff --git a/docs/product/ios-experience.md b/docs/product/ios-experience.md index 22db1e2..aa81bb8 100644 --- a/docs/product/ios-experience.md +++ b/docs/product/ios-experience.md @@ -24,6 +24,8 @@ 打开房间、区域或子位置,点右上角「编辑」即可修改名称和图标。新建时也能选图标,位置列表和选位置页面会同步显示。 +位置详情的「位置照片」可以拍照或从相册选图,裁剪确认后上传。已有照片可点开查看和删除,列表用第一张照片做缩略图。删除位置时,其照片随位置清理。 + 添加或编辑物品时,可以填写可选的购入单价、选择物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。 ## 选存放位置 diff --git a/docs/testing/cases.md b/docs/testing/cases.md index 54fccc5..8e2b99f 100644 --- a/docs/testing/cases.md +++ b/docs/testing/cases.md @@ -37,5 +37,6 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前 | TC-31 分级选位置 | R02 | 建两个带同名收纳盒的分支,其中一个有三级。从录音草稿、添加物品和移位分别打开位置选择,逐级找一次,再用完整路径搜索。 | 叶子和上级节点都能选。搜索显示完整路径,选好后返回原表单,取消时保留原选择。 | | TC-32 编辑位置与物品图标 | R02 | 为房间和子位置选择图标,再编辑子位置名称。新建物品并选择另一套物品图标。 | 位置层级保持正确,列表和选择页显示最新图标。无封面照片的物品显示物品图标。 | | TC-33 购入单价与新建照片 | R09 | 添加物品,输入 39.99 元并选相册照片裁剪。模拟上传中断后重试。随后清空购入单价。 | 价格按分精确保存。照片可单独重试,只保留一件物品和一张照片,详情可读取原图和缩略图。清空后详情收起价格项。 | +| TC-34 位置照片与清理 | R09 | 进入房间和子位置,分别拍照和选相册图,裁剪后上传。查看原图和缩略图,删除首图、归档空位置,再删除整个空间。 | 图标保留,缩略图随首图更新。查看者可看,编辑者可上传。删除相应记录后,两份对象都从桶中清理。 | [测试与演示计划](plan.md)