item-atlas/apps/ios/ItemAtlas/InventoryStore.swift

184 lines
5.9 KiB
Swift

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
}
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
}
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 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
}
func refreshLocations() async throws {
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] {
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)) }
let data = try await account.request(url.string ?? root + "/items", timeout: 12)
return try JSONDecoder().decode([Item].self, from: data)
}
func get<T: Decodable>(_ path: String) async throws -> T {
try JSONDecoder().decode(T.self, from: await account.request(path))
}
func send<T: Encodable, R: Decodable>(_ 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, 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?, 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
}
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 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 {
_ = try await account.request(path, method: "DELETE")
changed()
}
func changed() { revision += 1 }
}