50 lines
2.0 KiB
Swift
50 lines
2.0 KiB
Swift
import Foundation
|
|
import InventoryCore
|
|
import Observation
|
|
|
|
@MainActor
|
|
@Observable
|
|
final class InventoryStore {
|
|
private let archive = InventoryArchive(
|
|
url: URL.applicationSupportDirectory.appending(path: "ItemAtlas/inventory.json")
|
|
)
|
|
private(set) var inventory = Inventory()
|
|
private(set) var startupError: String?
|
|
|
|
init() {
|
|
do {
|
|
inventory = try archive.load() ?? Self.sample()
|
|
} catch {
|
|
startupError = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
func update(_ change: (inout Inventory) throws -> Void) throws {
|
|
var next = inventory
|
|
try change(&next)
|
|
try archive.save(next)
|
|
inventory = next
|
|
}
|
|
|
|
private static func sample() throws -> Inventory {
|
|
var inventory = Inventory()
|
|
let study = try inventory.addLocation(name: "书房", parentID: nil)
|
|
let desk = try inventory.addLocation(name: "书桌", parentID: study)
|
|
let drawer = try inventory.addLocation(name: "右抽屉", parentID: desk)
|
|
let livingRoom = try inventory.addLocation(name: "客厅", parentID: nil)
|
|
let cabinet = try inventory.addLocation(name: "电视柜", parentID: livingRoom)
|
|
let entry = try inventory.addLocation(name: "玄关", parentID: nil)
|
|
let box = try inventory.addLocation(name: "白盒", parentID: entry)
|
|
|
|
try inventory.addItem(name: "备用钥匙", aliases: ["门钥匙"], quantity: 1,
|
|
notes: "", locationID: box)
|
|
try inventory.addItem(name: "HDMI 线", aliases: ["视频线"], quantity: 2,
|
|
notes: "一根长线,一根短线。", locationID: drawer)
|
|
let ssd = try inventory.addItem(name: "外接固态硬盘", aliases: ["移动硬盘"], quantity: 1,
|
|
notes: "带电脑出门时一起拿。", locationID: cabinet)
|
|
try inventory.moveItem(id: ssd, to: drawer)
|
|
try inventory.toggleFavorite(id: ssd)
|
|
return inventory
|
|
}
|
|
}
|