add support to milti transaction

This commit is contained in:
2026-01-13 03:18:05 -03:00
parent ad23e9aa51
commit da10a36a1d
11 changed files with 287 additions and 56 deletions

View File

@@ -4,9 +4,12 @@ from aws_lambda_powertools.utilities.data_classes import (
event_source,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dateutils import now
from layercake.dynamodb import (
DynamoDBPersistenceLayer,
KeyPair,
)
from layercake.extra_types import CreditCard
from boto3clients import dynamodb_client
from config import IUGU_ACCOUNT_ID, IUGU_API_TOKEN, IUGU_TEST_MODE, ORDER_TABLE
@@ -25,4 +28,72 @@ iugu = Iugu(
@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool: ...
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
new_image = event.detail['new_image']
order_id = new_image['id']
invoice_id = new_image['invoice_id']
installments = new_image['installments']
credit_card = CreditCard(**new_image['credit_card'])
now_ = now()
token = iugu.payment_token(credit_card)
charge = iugu.charge(
invoice_id=invoice_id,
token=token['id'],
installments=installments,
)
with dyn.transact_writer() as transact:
transact.delete(key=KeyPair(order_id, 'TRANSACTION'))
transact.update(
key=KeyPair(order_id, 'TRANSACTION#STATS'),
update_expr='SET #count = if_not_exists(#count, :zero) + :one, \
updated_at = :now',
expr_attr_names={
'#count': 'payment_attempts',
},
expr_attr_values={
':zero': 0,
':one': 1,
':now': now(),
},
)
if charge['success'] is True:
transact.update(
key=KeyPair(order_id, '0'),
update_expr='SET #status = :status, \
paid_at = :now, \
updated_at = :now',
expr_attr_names={
'#status': 'status',
},
expr_attr_values={
':status': 'PAID',
':now': now_,
},
cond_expr='attribute_exists(sk)',
)
transact.put(
item={
'id': order_id,
'sk': f'TRANSACTION#ATTEMPTS#{now_.isoformat()}',
'brand': credit_card.brand,
'last4': credit_card.last4,
'status': 'SUCCEEDED',
'transaction': charge,
},
)
else:
transact.put(
item={
'id': order_id,
'sk': f'TRANSACTION#ATTEMPTS#{now_.isoformat()}',
'brand': credit_card.brand,
'last4': credit_card.last4,
'status': 'FAILED',
'transaction': charge,
},
)
return charge['success']