Skip to content

Instantly share code, notes, and snippets.

@adriaanbd
Last active December 30, 2020 01:51
Show Gist options
  • Save adriaanbd/2f23b49ec1cb8bda0840e4472b599d7e to your computer and use it in GitHub Desktop.
Save adriaanbd/2f23b49ec1cb8bda0840e4472b599d7e to your computer and use it in GitHub Desktop.
Allocate method coupled with OrderLine vs decoupled
# SERVICE LAYER
# we have to send an OrderLine to the domain service allocate, thus still coupled
def allocate(orderid:str, sku: str, qty: int, repo: AbstractRepository, session) -> str:
"""
Obtains a list of Batches from data layer, validates OrderLine,
calls the allocate domain service, and commits to database.
"""
batches = repo.list()
if not is_valid_sku(sku, batches):
raise InvalidSKU(f'Invalid SKU: {sku}')
line = model.OrderLine(orderid, sku, qty)
ref = model.allocate(line, batches)
session.commit()
return ref
# SERVICE LAYER
# we no longer need an OrderLine, just pass the primitives and let domain service handle it
def allocate(orderid:str, sku: str, qty: int, repo: AbstractRepository, session) -> str:
"""
Obtains a list of Batches from data layer, validates OrderLine,
calls the allocate domain service, and commits to database.
"""
batches = repo.list()
if not is_valid_sku(sku, batches):
raise InvalidSKU(f'Invalid SKU: {sku}')
ref = model.allocate(orderid, sku, qty, batches)
session.commit()
return ref
# DOMAIN LAYER
# domain service expects OrderLine
def allocate(line: OrderLine, batches: List[Batch]) -> str:
"""
Domain Service to allocate order lines against a list of batches
"""
assert len(batches) > 0, "At least 1 batch is needed"
try:
batch = next(
b for b in sorted(batches)
if b.can_allocate(line)
)
batch.allocate(line)
return batch.ref
except StopIteration:
raise OutOfStock(f'Out of stock for {line.sku}')
# DOMAIN LAYER
# domain service expects primitives instead and handles building Orderline within
def allocate(orderid: OrderId, sku: Sku, qty: Qty, batches: List[Batch]) -> str:
"""
Domain Service to allocate order lines against a list of batches
"""
assert len(batches) > 0, "At least 1 batch is needed"
line = OrderLine(orderid, sku, qty)
try:
batch = next(
b for b in sorted(batches)
if b.can_allocate(line)
)
batch.allocate(line)
return batch.ref
except StopIteration:
raise OutOfStock(f'Out of stock for {line.sku}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment