import Foundation import Observation struct Space: Decodable, Identifiable, Hashable { let id: UUID let name: String let role: String var canWrite: Bool { role == "OWNER" || role == "EDITOR" } } struct Place: Decodable, Identifiable { let id: UUID let parentId: UUID? let name: String let path: String var icon: String? = nil var coverPhotoId: UUID? = nil var iconPhotoId: UUID? = nil var displayIcon: String? = nil var depth: Int? = nil var levelDepth: Int { depth ?? (parentId == nil ? 1 : path.components(separatedBy: " / ").count) } } struct Item: Decodable, Identifiable { let id: UUID let name: String let quantity: Int let notes: String let locationId: UUID? let locationPath: String let version: Int let aliases: [String] let coverPhotoId: UUID? var icon: String? = nil var priceCents: Int64? = nil var published: Bool? = nil var communityPostId: UUID? = nil var locationLabel: String { locationPath.isEmpty ? "未设置位置" : locationPath } } struct AccountInventorySummary: Decodable { static let path = "/api/me/inventory-summary" let activeItems: Int64 let activeUnits: Int64 let pricedItems: Int64 let archivedItems: Int64 let publishedItems: Int64 let totalValueCents: String } struct ItemInput: Encodable { let name: String let quantity: Int let notes: String 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 { let item: Item let moves: [Move] let relations: [Relation] let preference: Preference struct Move: Decodable { let fromPath: String let toPath: String let movedAt: String } struct Relation: Decodable, Identifiable { let itemId: UUID let name: String let locationPath: String let kind: String var id: UUID { itemId } } struct Preference: Codable { var favorite: Bool var rating: Int? var note: String } } 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 { let account: AtlasAccount let space: Space private(set) var locations: [Place] private(set) var locationsReady: Bool private(set) var locationAccessLost = false private(set) var revision = 0 var root: String { "/api/households/\(space.id)" } var canWrite: Bool { space.canWrite } init(account: AtlasAccount, space: Space) { self.account = account self.space = space let preview: [Place]? = account.cached("/api/households/\(space.id)/locations") locations = preview ?? [] locationsReady = preview != nil } func refreshLocations(refresh: Bool = false) async throws { let requestedRevision = revision do { let updated: [Place] = try await account.read(root + "/locations", refresh: refresh) guard revision == requestedRevision else { return } locations = updated locationsReady = true locationAccessLost = false } catch let error as AtlasError where error.resourceUnavailable { guard revision == requestedRevision else { return } locations = [] locationsReady = false locationAccessLost = true account.invalidateReads(root + "/", discard: true) throw error } } func warm() async { async let places: Void? = try? refreshLocations() async let items: [Item]? = try? search("", favorites: false) _ = await (places, items) } func cachedItems(favorites: Bool, location: UUID? = nil) -> [Item]? { account.cached(itemSearchPath("", favorites: favorites, location: location, offset: 0)) } func search(_ query: String, favorites: Bool, location: UUID? = nil, offset: Int = 0, refresh: Bool = false) async throws -> [Item] { let path = itemSearchPath(query, favorites: favorites, location: location, offset: offset) if query.isEmpty && offset == 0 { return try await account.read(path, refresh: refresh) } let data = try await account.request(path, timeout: 12) return try JSONDecoder().decode([Item].self, from: data) } private func itemSearchPath(_ query: String, favorites: Bool, location: UUID?, offset: Int) -> String { var url = URLComponents() url.path = root + "/items" url.queryItems = [.init(name: "q", value: query), .init(name: "offset", value: String(offset)), .init(name: "favorites", value: favorites ? "true" : "false")] if let location { url.queryItems?.append(.init(name: "location", value: location.uuidString)) } return url.string ?? root + "/items" } func get(_ path: String) async throws -> T { try JSONDecoder().decode(T.self, from: await account.request(path)) } 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) if path.hasSuffix("/publication") { account.invalidateReads("/api/community/") } return try JSONDecoder().decode(R.self, from: response) } 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(inventorySummaryChanged: true) return created } struct LocationDisplay: Encodable { var photoId: UUID? = nil var icon: String? = nil } 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)) updateLocation(place) return place.id } func saveLocationDisplay(_ selection: LocationDisplay, location: UUID) async throws { let place: Place = try await send(root + "/locations/\(location)/thumbnail", method: "PUT", selection) updateLocation(place) } private func updateLocation(_ place: Place) { if let index = locations.firstIndex(where: { $0.id == place.id }) { locations[index] = place } else { locations.append(place) } changed() } func itemPath(_ id: UUID?) -> String { root + "/items" + (id.map { "/\($0)" } ?? "") } 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(root + target.path, method: "POST", data: payload, contentType: "multipart/form-data; boundary=\(boundary)", idempotencyKey: idempotencyKey) changed() } func imagePath(target: PhotoTarget, photo: UUID, thumbnail: Bool) -> String { root + target.path + "/\(photo)?thumbnail=\(thumbnail)" } func image(target: PhotoTarget, photo: UUID, thumbnail: Bool, refresh: Bool = false) async throws -> Data { let path = imagePath(target: target, photo: photo, thumbnail: thumbnail) if thumbnail { return try await account.readPreview(path, refresh: refresh) } return try await account.request(path) } func delete(_ path: String, affectsCommunity: Bool = false, changesItemCount: Bool = false) async throws { _ = try await account.request(path, method: "DELETE") let resource = path.components(separatedBy: "?")[0] account.invalidateReads(resource, discard: true) if resource == root { account.invalidateReads("/api/households", discard: true) } if resource == root || resource.hasSuffix("/publication") || affectsCommunity { account.invalidateReads("/api/community/", discard: true) } changed(inventorySummaryChanged: changesItemCount || resource == root || resource.hasSuffix("/publication")) } func changed(inventorySummaryChanged: Bool = false) { if inventorySummaryChanged { account.invalidateReads(AccountInventorySummary.path) } account.invalidateReads(root + "/") revision += 1 } }