forked from cosmicpython/code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
62 lines (49 loc) · 1.7 KB
/
Copy pathmodel.py
File metadata and controls
62 lines (49 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from dataclasses import dataclass
from typing import List, Optional
from datetime import date
@dataclass(frozen=True) #(1)(2)
class OrderLine:
orderid: str
sku: str
qty: int
class Batch:
def __init__(self, ref: str, sku: str, qty: int, eta: Optional[date]): #(2)
self.reference = ref
self.sku = sku
self.eta = eta
self._purchased_quantity = qty
self._allocations = set()
def allocate(self, line: OrderLine): #(3)
self._allocations.add(line)
def deallocate(self, line: OrderLine):
if line in self._allocations:
self._allocations.remove(line)
@property
def allocated_quantity(self):
return sum(line.qty for line in self._allocations)
@property
def available_quantity(self):
return self._purchased_quantity - self.allocated_quantity
def can_allocate(self, line: OrderLine) -> bool:
return self.sku == line.sku and self.available_quantity >= line.qty
def __gt__(self, other)-> bool:
if self.eta is None:
return False
if other.eta is None:
return True
return self.eta > other.eta
def __eq__(self, other: object) -> bool:
if not isinstance(other, Batch):
return False
return other.reference == self.reference
def __hash__(self) -> int:
return hash(self.reference)
def allocate(line: OrderLine, batches: List[Batch,]):
try:
batch = next(b for b in sorted(batches) if b.can_allocate(line))
batch.allocate(line)
return batch.reference
except StopIteration as e:
raise OutOfStock(f'Out of stock of sku {line.sku}') from e
class OutOfStock(Exception):
pass