81 lines
2.2 KiB
Python
81 lines
2.2 KiB
Python
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.dateutils import now
|
|
from layercake.dynamodb import (
|
|
DynamoDBPersistenceLayer,
|
|
SortKey,
|
|
TransactKey,
|
|
)
|
|
|
|
from boto3clients import dynamodb_client
|
|
from config import (
|
|
IUGU_ACCOUNT_ID,
|
|
IUGU_API_TOKEN,
|
|
IUGU_POSTBACK_URL,
|
|
IUGU_TEST_MODE,
|
|
ORDER_TABLE,
|
|
)
|
|
from iugu import Credentials, Iugu, Order
|
|
|
|
logger = Logger(__name__)
|
|
dyn = DynamoDBPersistenceLayer(ORDER_TABLE, dynamodb_client)
|
|
iugu = Iugu(
|
|
Credentials(
|
|
IUGU_ACCOUNT_ID,
|
|
IUGU_API_TOKEN,
|
|
test_mode=IUGU_TEST_MODE,
|
|
)
|
|
)
|
|
|
|
|
|
@event_source(data_class=EventBridgeEvent)
|
|
@logger.inject_lambda_context
|
|
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
|
new_image = event.detail['new_image']
|
|
now_ = now()
|
|
order_id = new_image['id']
|
|
r = dyn.collection.get_items(
|
|
TransactKey(order_id)
|
|
+ SortKey('ADDRESS', rename_key='address')
|
|
+ SortKey('ITEMS', path_spec='items', rename_key='items'),
|
|
flatten_top=False,
|
|
)
|
|
|
|
payment_method = new_image['payment_method']
|
|
is_pix = payment_method == 'PIX'
|
|
is_bank_slip = payment_method == 'BANK_SLIP'
|
|
|
|
invoice = iugu.create_invoice(
|
|
order=Order(
|
|
address=r.get('address', {}),
|
|
items=r.get('items', []),
|
|
**new_image,
|
|
),
|
|
postback_url=f'{IUGU_POSTBACK_URL}/{order_id}/postback',
|
|
)
|
|
|
|
try:
|
|
dyn.put_item(
|
|
item={
|
|
'id': order_id,
|
|
'sk': 'INVOICE',
|
|
'payment_method': payment_method,
|
|
'secure_id': invoice['secure_id'],
|
|
'secure_url': invoice['secure_url'],
|
|
'created_at': now_,
|
|
# Uncomment this when adding for multiple payment providers
|
|
# 'payment_provider': 'iugu',
|
|
}
|
|
| ({'bank_slip': invoice['bank_slip']} if is_bank_slip else {})
|
|
| ({'pix': invoice['pix']} if is_pix else {}),
|
|
cond_expr='attribute_not_exists(sk)',
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
return True
|