WIP
This commit is contained in:
@@ -13,6 +13,7 @@ from aws_lambda_powertools.logging import correlation_paths
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
from layercake.dateutils import now
|
||||
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
|
||||
from layercake.funcs import pick
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import ORDER_TABLE
|
||||
@@ -29,10 +30,12 @@ class OrderNotFoundError(NotFoundError): ...
|
||||
class InvoiceNotFoundError(NotFoundError): ...
|
||||
|
||||
|
||||
class StatusAttr(Enum):
|
||||
# Post-migration (orders): uncomment the following lines
|
||||
class StatusTimestampAttr(Enum):
|
||||
# Post-migration (orders): uncomment the following 2 lines
|
||||
# PAID = 'paid_at'
|
||||
# EXTERNALLY_PAID = 'paid_at'
|
||||
|
||||
# Post-migration (orders): remove the following 2 lines
|
||||
EXTERNALLY_PAID = 'payment_date'
|
||||
PAID = 'payment_date'
|
||||
|
||||
@@ -41,19 +44,24 @@ class StatusAttr(Enum):
|
||||
EXPIRED = 'expired_at'
|
||||
|
||||
|
||||
def _status_attr(status: str) -> StatusAttr | None:
|
||||
def _timestamp_attr_for_status(status: str) -> str | None:
|
||||
try:
|
||||
return StatusAttr[status]
|
||||
return StatusTimestampAttr[status].value
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
|
||||
def _friendly_status(status: str) -> str:
|
||||
if 'status' == 'EXTERNALLY_PAID':
|
||||
if status == 'EXTERNALLY_PAID':
|
||||
return 'PAID'
|
||||
return status
|
||||
|
||||
|
||||
def _get_order_owner(order_id: str) -> dict:
|
||||
r = dyn.get_item(KeyPair(order_id, '0'))
|
||||
return pick(('user_id', 'org_id'), r)
|
||||
|
||||
|
||||
@app.post('/<order_id>/postback')
|
||||
@tracer.capture_method
|
||||
def postback(order_id: str):
|
||||
@@ -62,31 +70,33 @@ def postback(order_id: str):
|
||||
|
||||
now_ = now()
|
||||
event = decoded_body['event']
|
||||
status = decoded_body.get('data[status]', '').upper()
|
||||
status_attr = _status_attr(status)
|
||||
raw_status = decoded_body.get('data[status]', '').upper()
|
||||
status = _friendly_status(raw_status)
|
||||
timestamp_attr = _timestamp_attr_for_status(raw_status)
|
||||
|
||||
if event != 'invoice.status_changed' or not status_attr:
|
||||
return Response(status_code=HTTPStatus.NO_CONTENT)
|
||||
if event != 'invoice.status_changed' or not timestamp_attr:
|
||||
logger.debug('Event not acceptable', order_id=order_id)
|
||||
return Response(status_code=HTTPStatus.NOT_ACCEPTABLE)
|
||||
|
||||
with dyn.transact_writer() as transact:
|
||||
transact.update(
|
||||
key=KeyPair(order_id, '0'),
|
||||
update_expr='SET #status = :status, \
|
||||
#status_attr = :now, \
|
||||
#ts_attr = :now, \
|
||||
updated_at = :now',
|
||||
cond_expr='attribute_exists(sk)',
|
||||
expr_attr_names={
|
||||
'#status': 'status',
|
||||
'#status_attr': status_attr.value,
|
||||
'#ts_attr': timestamp_attr,
|
||||
},
|
||||
expr_attr_values={
|
||||
':status': _friendly_status(status),
|
||||
':status': status,
|
||||
':now': now_,
|
||||
},
|
||||
exc_cls=OrderNotFoundError,
|
||||
)
|
||||
|
||||
if status == 'EXTERNALLY_PAID':
|
||||
if raw_status == 'EXTERNALLY_PAID':
|
||||
transact.update(
|
||||
key=KeyPair(order_id, 'INVOICE'),
|
||||
cond_expr='attribute_exists(sk)',
|
||||
@@ -99,6 +109,51 @@ def postback(order_id: str):
|
||||
exc_cls=InvoiceNotFoundError,
|
||||
)
|
||||
|
||||
if status == 'PAID':
|
||||
try:
|
||||
dyn.put_item(
|
||||
item={
|
||||
'id': order_id,
|
||||
'sk': 'FULFILLMENT',
|
||||
'status': 'IN_PROGRESS',
|
||||
'created_at': now_,
|
||||
**_get_order_owner(order_id),
|
||||
},
|
||||
cond_expr='attribute_not_exists(sk)',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if status in ('CANCELED', 'REFUNDED'):
|
||||
try:
|
||||
with dyn.transact_writer() as transact:
|
||||
transact.condition(
|
||||
key=KeyPair(order_id, 'FULFILLMENT'),
|
||||
cond_expr=(
|
||||
'attribute_exists(sk) '
|
||||
'AND #status <> :in_progress '
|
||||
'AND #status <> :rollback'
|
||||
),
|
||||
expr_attr_names={
|
||||
'#status': 'status',
|
||||
},
|
||||
expr_attr_values={
|
||||
':in_progress': 'IN_PROGRESS',
|
||||
':rollback': 'ROLLBACK',
|
||||
},
|
||||
)
|
||||
transact.put(
|
||||
item={
|
||||
'id': order_id,
|
||||
'sk': 'FULFILLMENT#ROLLBACK',
|
||||
'created_at': now_,
|
||||
},
|
||||
cond_expr='attribute_not_exists(sk)',
|
||||
)
|
||||
logger.debug('Fulfillment rollback event created', order_id=order_id)
|
||||
except Exception:
|
||||
logger.debug('Fulfillment rollback event already exists', order_id=order_id)
|
||||
|
||||
return Response(status_code=HTTPStatus.NO_CONTENT)
|
||||
|
||||
|
||||
|
||||
@@ -90,6 +90,8 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
item={
|
||||
'id': pk,
|
||||
'sk': f'{sk}#SCHEDULE#AUTO_CLOSE',
|
||||
# Post-migration: uncomment the following line
|
||||
# 'sk': f'{sk}#SCHEDULED#AUTO_CLOSE',
|
||||
'ttl': ttl(
|
||||
start_dt=datetime.combine(end_period, time())
|
||||
+ timedelta(days=1)
|
||||
|
||||
@@ -80,10 +80,7 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
cond_expr='attribute_not_exists(sk)',
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception(
|
||||
exc,
|
||||
keypair={'id': pk, 'sk': sk},
|
||||
)
|
||||
logger.exception(exc, keypair={'id': pk, 'sk': sk})
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
@@ -107,8 +107,8 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
transact.put(
|
||||
item={
|
||||
'id': order_id,
|
||||
'sk': 'SCHEDULE#SELF_DESTRUCTION',
|
||||
'ttl': ttl(start_dt=now_, days=14),
|
||||
'sk': 'SCHEDULED#SELF_DESTRUCTION',
|
||||
'ttl': ttl(start_dt=now_, days=7),
|
||||
'created_at': now_,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -23,7 +23,11 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
order_id = keys['id']
|
||||
|
||||
r = dyn.collection.query(PartitionKey(order_id), limit=150)
|
||||
logger.info('Records found', total_items=len(r['items']), records=r['items'])
|
||||
logger.info(
|
||||
msg='Records found',
|
||||
total_items=len(r['items']),
|
||||
records=r['items'],
|
||||
)
|
||||
|
||||
with dyn.batch_writer() as batch:
|
||||
for pair in r['items']:
|
||||
|
||||
78
orders-events/app/events/start_fulfillment.py
Normal file
78
orders-events/app/events/start_fulfillment.py
Normal file
@@ -0,0 +1,78 @@
|
||||
import pprint
|
||||
from dataclasses import asdict, dataclass
|
||||
from uuid import uuid4
|
||||
|
||||
from aws_lambda_powertools import Logger
|
||||
from aws_lambda_powertools.utilities.data_classes import (
|
||||
EventBridgeEvent,
|
||||
event_source,
|
||||
)
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyChain, KeyPair
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import ENROLLMENT_TABLE
|
||||
|
||||
logger = Logger(__name__)
|
||||
dyn = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
|
||||
|
||||
|
||||
@event_source(data_class=EventBridgeEvent)
|
||||
@logger.inject_lambda_context
|
||||
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
new_image = event.detail['new_image']
|
||||
order_id = new_image['id']
|
||||
enrollments = dyn.collection.query(
|
||||
key=KeyPair(order_id, 'ENROLLMENT#'),
|
||||
).get('items', [])
|
||||
|
||||
if not enrollments:
|
||||
items = dyn.collection.get_item(
|
||||
KeyPair(order_id, 'ITEMS'),
|
||||
raise_on_error=False,
|
||||
default=[],
|
||||
)
|
||||
pprint.pp(items)
|
||||
# docx = {
|
||||
# 'id': f'SEAT#ORG#{org_id}',
|
||||
# 'sk': f'ORDER#{order_id}#ENROLLMENT#{uuid4()}',
|
||||
# 'course': {},
|
||||
# 'created_at': now_,
|
||||
# }
|
||||
|
||||
pprint.pp(enrollments)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# Se houver matriculas
|
||||
# -> com: scheduled_for
|
||||
# -> tenta agendar, se não joga para vagas
|
||||
# -> tenta matriculas, se falhar, joga para vagas
|
||||
|
||||
# se não houver vagas, gera as vagas.
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Course:
|
||||
id: str
|
||||
name: str
|
||||
access_period: int
|
||||
|
||||
|
||||
def _get_courses(ids: set) -> tuple[Course, ...]:
|
||||
pairs = tuple(KeyPair(idx, '0') for idx in ids)
|
||||
r = dyn.collection.get_items(
|
||||
KeyChain(pairs),
|
||||
flatten_top=False,
|
||||
)
|
||||
courses = tuple(
|
||||
Course(
|
||||
id=idx,
|
||||
name=obj['name'],
|
||||
access_period=obj['access_period'],
|
||||
)
|
||||
for idx, obj in r.items()
|
||||
)
|
||||
|
||||
return courses
|
||||
Reference in New Issue
Block a user