11from __future__ import annotations
22from dataclasses import dataclass
33from datetime import date
4- from typing import Optional , List , Set
5- from . import commands , events
4+ from typing import Optional , List , Set , Iterable
5+ from . import events
66
77
88class Product :
@@ -13,7 +13,7 @@ def __init__(self, sku: str, batches: List[Batch], version_number: int = 0):
1313 self .version_number = version_number
1414 self .events = [] # type: List[events.Event]
1515
16- def allocate (self , line : OrderLine ) -> str :
16+ def allocate (self , line : OrderLine ) -> Optional [ str ] :
1717 try :
1818 batch = next (
1919 b for b in sorted (self .batches ) if b .can_allocate (line )
@@ -31,12 +31,9 @@ def allocate(self, line: OrderLine) -> str:
3131
3232 def change_batch_quantity (self , ref : str , qty : int ):
3333 batch = next (b for b in self .batches if b .reference == ref )
34- batch ._purchased_quantity = qty
35- while batch .available_quantity < 0 :
36- line = batch .deallocate_one ()
37- self .events .append (
38- events .Deallocated (line .orderid , line .sku , line .qty )
39- )
34+ deallocation_events = batch .change_quantity (qty )
35+ self .events .extend (deallocation_events )
36+
4037
4138@dataclass (unsafe_hash = True )
4239class OrderLine :
@@ -90,3 +87,9 @@ def available_quantity(self) -> int:
9087
9188 def can_allocate (self , line : OrderLine ) -> bool :
9289 return self .sku == line .sku and self .available_quantity >= line .qty
90+
91+ def change_quantity (self , qty : int ) -> Iterable [events .Deallocated ]:
92+ self ._purchased_quantity = qty # pylint: disable=protected-access
93+ while self .available_quantity < 0 :
94+ line = self .deallocate_one ()
95+ yield events .Deallocated (line .orderid , line .sku , line .qty )
0 commit comments