|
1 | | -from __future__ import annotations |
2 | | -from dataclasses import dataclass |
3 | | -from datetime import date |
4 | | -from typing import Optional, List, Set |
5 | | - |
6 | | - |
7 | | -class OutOfStock(Exception): |
8 | | - pass |
9 | | - |
10 | | - |
11 | | -def allocate(line: OrderLine, batches: List[Batch]) -> str: |
12 | | - try: |
13 | | - batch = next(b for b in sorted(batches) if b.can_allocate(line)) |
14 | | - batch.allocate(line) |
15 | | - return batch.reference |
16 | | - except StopIteration: |
17 | | - raise OutOfStock(f"Out of stock for sku {line.sku}") |
18 | | - |
19 | | - |
20 | | -@dataclass(frozen=True) |
21 | | -class OrderLine: |
22 | | - orderid: str |
23 | | - sku: str |
24 | | - qty: int |
25 | | - |
26 | | - |
27 | | -class Batch: |
28 | | - def __init__(self, ref: str, sku: str, qty: int, eta: Optional[date]): |
29 | | - self.reference = ref |
30 | | - self.sku = sku |
31 | | - self.eta = eta |
32 | | - self._purchased_quantity = qty |
33 | | - self._allocations = set() # type: Set[OrderLine] |
34 | | - |
35 | | - def __repr__(self): |
36 | | - return f"<Batch {self.reference}>" |
37 | | - |
38 | | - def __eq__(self, other): |
39 | | - if not isinstance(other, Batch): |
40 | | - return False |
41 | | - return other.reference == self.reference |
42 | | - |
43 | | - def __hash__(self): |
44 | | - return hash(self.reference) |
45 | | - |
46 | | - def __gt__(self, other): |
47 | | - if self.eta is None: |
48 | | - return False |
49 | | - if other.eta is None: |
50 | | - return True |
51 | | - return self.eta > other.eta |
52 | | - |
53 | | - def allocate(self, line: OrderLine): |
54 | | - if self.can_allocate(line): |
55 | | - self._allocations.add(line) |
56 | | - |
57 | | - def deallocate(self, line: OrderLine): |
58 | | - if line in self._allocations: |
59 | | - self._allocations.remove(line) |
60 | | - |
61 | | - @property |
62 | | - def allocated_quantity(self) -> int: |
63 | | - return sum(line.qty for line in self._allocations) |
64 | | - |
65 | | - @property |
66 | | - def available_quantity(self) -> int: |
67 | | - return self._purchased_quantity - self.allocated_quantity |
68 | | - |
69 | | - def can_allocate(self, line: OrderLine) -> bool: |
70 | | - return self.sku == line.sku and self.available_quantity >= line.qty |
0 commit comments