inventory_kit/repository.rs
1use crate::model::*;
2use crate::error::InventoryError;
3
4/// Defines the core operations for managing inventory availability and transactions.
5///
6/// This trait is generic over both the inventory `Item` and the time unit `Time`.
7/// It supports querying availability and managing quantities through reservation, release, and adjustment.
8pub trait InventoryRepository<Item, Time>
9where
10 Item: InventoryItem,
11 Time: Copy + Ord,
12{
13 /// Retrieves all availability slots for a given item within a specified time range.
14 ///
15 /// Returns a list of matching `AvailabilitySlot`s or an `InventoryError` if the item is not found
16 /// or the range is invalid.
17 fn get_availability(
18 &self,
19 item_id: &Item::Id,
20 from: Time,
21 to: Time,
22 ) -> Result<Vec<AvailabilitySlot<Item::Id, Time>>, InventoryError>;
23
24 /// Attempts to reserve a specified quantity of an item for a given time range.
25 ///
26 /// Returns an error if the item is not found, the slot is not defined, or there is insufficient availability.
27 fn reserve(
28 &mut self,
29 item_id: &Item::Id,
30 from: Time,
31 to: Time,
32 quantity: u32,
33 ) -> Result<(), InventoryError>;
34
35 /// Releases a previously reserved quantity back into availability for the given time range.
36 ///
37 /// This operation increases the `available` value of the targeted slot.
38 fn release(
39 &mut self,
40 item_id: &Item::Id,
41 from: Time,
42 to: Time,
43 quantity: u32,
44 ) -> Result<(), InventoryError>;
45
46 /// Adjusts the total availability for a given slot to a new quantity.
47 ///
48 /// This operation sets the `available` value of the slot to the specified amount,
49 /// regardless of its current value.
50 fn adjust(
51 &mut self,
52 item_id: &Item::Id,
53 from: Time,
54 to: Time,
55 new_quantity: u32,
56 ) -> Result<(), InventoryError>;
57}
58
59/// An extension of `InventoryRepository` that supports atomic operations across multiple slots.
60///
61/// Useful for use cases like batch reservations, where all operations must succeed together or fail entirely.
62pub trait AtomicInventoryOps<Item, Time>: InventoryRepository<Item, Time>
63where
64 Item: InventoryItem,
65 Time: Copy + Ord,
66{
67 /// Attempts to reserve multiple availability slots in a single atomic operation.
68 ///
69 /// If any reservation fails (due to not found or insufficient availability),
70 /// no changes will be applied to any of the slots.
71 ///
72 /// # Parameters
73 /// - `item_id`: The ID of the item to reserve.
74 /// - `slots`: A slice of `(start_time, end_time, quantity)` tuples to reserve.
75 fn reserve_many(
76 &mut self,
77 item_id: &Item::Id,
78 slots: &[(Time, Time, u32)],
79 ) -> Result<(), InventoryError>;
80}