add assign tenant
This commit is contained in:
5
order-management/Makefile
Normal file
5
order-management/Makefile
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
build:
|
||||||
|
sam build --use-container
|
||||||
|
|
||||||
|
deploy: build
|
||||||
|
sam deploy --debug
|
||||||
13
order-management/app/boto3clients.py
Normal file
13
order-management/app/boto3clients.py
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
|
||||||
|
|
||||||
|
def get_dynamodb_client():
|
||||||
|
if os.getenv('AWS_LAMBDA_FUNCTION_NAME'):
|
||||||
|
return boto3.client('dynamodb')
|
||||||
|
|
||||||
|
return boto3.client('dynamodb', endpoint_url='http://localhost:8000')
|
||||||
|
|
||||||
|
|
||||||
|
dynamodb_client = get_dynamodb_client()
|
||||||
5
order-management/app/conf.py
Normal file
5
order-management/app/conf.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
USER_TABLE: str = os.getenv('USER_TABLE') # type: ignore
|
||||||
|
ORDER_TABLE: str = os.getenv('ORDER_TABLE') # type: ignore
|
||||||
|
ENROLLMENT_TABLE: str = os.getenv('ENROLLMENT_TABLE') # type: ignore
|
||||||
0
order-management/app/events/__init__.py
Normal file
0
order-management/app/events/__init__.py
Normal file
76
order-management/app/events/assign_tenant_cnpj.py
Normal file
76
order-management/app/events/assign_tenant_cnpj.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
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,
|
||||||
|
KeyPair,
|
||||||
|
SortKey,
|
||||||
|
TransactItems,
|
||||||
|
)
|
||||||
|
|
||||||
|
from boto3clients import dynamodb_client
|
||||||
|
from conf import ORDER_TABLE, USER_TABLE
|
||||||
|
|
||||||
|
logger = Logger(__name__)
|
||||||
|
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)
|
||||||
|
order_layer = DynamoDBPersistenceLayer(ORDER_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']
|
||||||
|
now_ = now()
|
||||||
|
ids = user_layer.collect.get_items(
|
||||||
|
KeyPair(
|
||||||
|
pk='cnpj',
|
||||||
|
sk=SortKey(new_image['cnpj'], path_spec='user_id'),
|
||||||
|
rename_key='org_id',
|
||||||
|
)
|
||||||
|
+ KeyPair(
|
||||||
|
pk='email',
|
||||||
|
sk=SortKey(new_image['email'], path_spec='user_id'),
|
||||||
|
rename_key='user_id',
|
||||||
|
),
|
||||||
|
flatten_top=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Sometimes, a DynamoDB insertion may take longer to complete,
|
||||||
|
# so an exception is raised to trigger a retry.
|
||||||
|
if len(ids) < 2:
|
||||||
|
raise ValueError('IDs not found.')
|
||||||
|
|
||||||
|
transact = TransactItems(order_layer.table_name)
|
||||||
|
transact.update(
|
||||||
|
key=KeyPair(new_image['id'], '0'),
|
||||||
|
update_expr='SET metadata__tenant_id = :org_id, update_date = :update_date',
|
||||||
|
expr_attr_values={
|
||||||
|
':org_id': {ids['org_id']},
|
||||||
|
':update_date': now_,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
transact.put(
|
||||||
|
item={
|
||||||
|
'id': new_image['id'],
|
||||||
|
'sk': 'metadata#tenant',
|
||||||
|
'org_id': ids['org_id'],
|
||||||
|
'create_date': now_,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
for k, v in ids.items():
|
||||||
|
transact.put(
|
||||||
|
item={
|
||||||
|
'id': new_image['id'],
|
||||||
|
'sk': 'rel#%s' % k.removesuffix('_id').upper(),
|
||||||
|
'create_date': now_,
|
||||||
|
k: v,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
order_layer.transact_write_items(transact)
|
||||||
|
return True
|
||||||
33
order-management/pyproject.toml
Normal file
33
order-management/pyproject.toml
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
[project]
|
||||||
|
name = "order-management"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = ""
|
||||||
|
readme = ""
|
||||||
|
requires-python = ">=3.13"
|
||||||
|
dependencies = ["layercake"]
|
||||||
|
|
||||||
|
[dependency-groups]
|
||||||
|
dev = [
|
||||||
|
"jsonlines>=4.0.0",
|
||||||
|
"pytest>=8.3.4",
|
||||||
|
"pytest-cov>=6.0.0",
|
||||||
|
"ruff>=0.9.1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
pythonpath = ["app/"]
|
||||||
|
addopts = "--cov --cov-report html -v"
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
target-version = "py311"
|
||||||
|
src = ["app"]
|
||||||
|
|
||||||
|
[tool.ruff.format]
|
||||||
|
quote-style = "single"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = ["E", "F", "I"]
|
||||||
|
|
||||||
|
|
||||||
|
[tool.uv.sources]
|
||||||
|
layercake = { path = "../layercake" }
|
||||||
3
order-management/pyrightconfig.json
Normal file
3
order-management/pyrightconfig.json
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"extraPaths": ["app/"]
|
||||||
|
}
|
||||||
9
order-management/samconfig.toml
Normal file
9
order-management/samconfig.toml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
version = 0.1
|
||||||
|
[default.deploy.parameters]
|
||||||
|
stack_name = "saladeaula-order-management"
|
||||||
|
resolve_s3 = true
|
||||||
|
s3_prefix = "order_management"
|
||||||
|
region = "sa-east-1"
|
||||||
|
confirm_changeset = false
|
||||||
|
capabilities = "CAPABILITY_IAM"
|
||||||
|
image_repositories = []
|
||||||
64
order-management/template.yaml
Normal file
64
order-management/template.yaml
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
AWSTemplateFormatVersion: 2010-09-09
|
||||||
|
Transform: AWS::Serverless-2016-10-31
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
UserTable:
|
||||||
|
Type: String
|
||||||
|
Default: betaeducacao-prod-users_d2o3r5gmm4it7j
|
||||||
|
EnrollmentTable:
|
||||||
|
Type: String
|
||||||
|
Default: betaeducacao-prod-enrollments
|
||||||
|
OrderTable:
|
||||||
|
Type: String
|
||||||
|
Default: betaeducacao-prod-orders
|
||||||
|
|
||||||
|
Globals:
|
||||||
|
Function:
|
||||||
|
CodeUri: app/
|
||||||
|
Runtime: python3.13
|
||||||
|
Tracing: Active
|
||||||
|
Architectures:
|
||||||
|
- x86_64
|
||||||
|
Layers:
|
||||||
|
- !Sub arn:aws:lambda:sa-east-1:336641857101:layer:layercake:65
|
||||||
|
Environment:
|
||||||
|
Variables:
|
||||||
|
TZ: America/Sao_Paulo
|
||||||
|
LOG_LEVEL: DEBUG
|
||||||
|
DYNAMODB_PARTITION_KEY: id
|
||||||
|
POWERTOOLS_LOGGER_SAMPLE_RATE: 0.1
|
||||||
|
POWERTOOLS_LOGGER_LOG_EVENT: true
|
||||||
|
USER_TABLE: !Ref UserTable
|
||||||
|
ORDER_TABLE: !Ref OrderTable
|
||||||
|
|
||||||
|
Resources:
|
||||||
|
EventLog:
|
||||||
|
Type: AWS::Logs::LogGroup
|
||||||
|
Properties:
|
||||||
|
RetentionInDays: 90
|
||||||
|
|
||||||
|
EventAssignTenantCnpjFunction:
|
||||||
|
Type: AWS::Serverless::Function
|
||||||
|
Properties:
|
||||||
|
Handler: events.assign_tenant_cnpj.lambda_handler
|
||||||
|
LoggingConfig:
|
||||||
|
LogGroup: !Ref EventLog
|
||||||
|
Policies:
|
||||||
|
- DynamoDBCrudPolicy:
|
||||||
|
TableName: !Ref UserTable
|
||||||
|
- DynamoDBCrudPolicy:
|
||||||
|
TableName: !Ref OrderTable
|
||||||
|
Events:
|
||||||
|
Event:
|
||||||
|
Type: EventBridgeRule
|
||||||
|
Properties:
|
||||||
|
Pattern:
|
||||||
|
resources: [betaeducacao-prod-orders]
|
||||||
|
detail-type: [INSERT]
|
||||||
|
detail:
|
||||||
|
new_image:
|
||||||
|
sk: ["0"]
|
||||||
|
cnpj:
|
||||||
|
- exists: true
|
||||||
|
metadata__tenant_id:
|
||||||
|
- exists: false
|
||||||
0
order-management/tests/__init__.py
Normal file
0
order-management/tests/__init__.py
Normal file
72
order-management/tests/conftest.py
Normal file
72
order-management/tests/conftest.py
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import jsonlines
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
PYTEST_TABLE_NAME = 'pytest'
|
||||||
|
PK = 'id'
|
||||||
|
SK = 'sk'
|
||||||
|
|
||||||
|
|
||||||
|
# https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.hookspec.pytest_configure
|
||||||
|
def pytest_configure():
|
||||||
|
os.environ['TZ'] = 'America/Sao_Paulo'
|
||||||
|
os.environ['DYNAMODB_PARTITION_KEY'] = PK
|
||||||
|
os.environ['DYNAMODB_SORT_KEY'] = SK
|
||||||
|
os.environ['USER_TABLE'] = PYTEST_TABLE_NAME
|
||||||
|
os.environ['COURSE_TABLE'] = PYTEST_TABLE_NAME
|
||||||
|
os.environ['ENROLLMENT_TABLE'] = PYTEST_TABLE_NAME
|
||||||
|
os.environ['ORDER_TABLE'] = PYTEST_TABLE_NAME
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LambdaContext:
|
||||||
|
function_name: str = 'test'
|
||||||
|
memory_limit_in_mb: int = 128
|
||||||
|
invoked_function_arn: str = 'arn:aws:lambda:eu-west-1:809313241:function:test'
|
||||||
|
aws_request_id: str = '52fdfc07-2182-154f-163f-5f0f9a621d72'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def lambda_context() -> LambdaContext:
|
||||||
|
return LambdaContext()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def dynamodb_client():
|
||||||
|
from boto3clients import dynamodb_client as client
|
||||||
|
|
||||||
|
client.create_table(
|
||||||
|
AttributeDefinitions=[
|
||||||
|
{'AttributeName': PK, 'AttributeType': 'S'},
|
||||||
|
{'AttributeName': SK, 'AttributeType': 'S'},
|
||||||
|
],
|
||||||
|
TableName=PYTEST_TABLE_NAME,
|
||||||
|
KeySchema=[
|
||||||
|
{'AttributeName': PK, 'KeyType': 'HASH'},
|
||||||
|
{'AttributeName': SK, 'KeyType': 'RANGE'},
|
||||||
|
],
|
||||||
|
ProvisionedThroughput={
|
||||||
|
'ReadCapacityUnits': 123,
|
||||||
|
'WriteCapacityUnits': 123,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
yield client
|
||||||
|
|
||||||
|
client.delete_table(TableName=PYTEST_TABLE_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def dynamodb_persistence_layer(dynamodb_client):
|
||||||
|
from layercake.dynamodb import DynamoDBPersistenceLayer
|
||||||
|
|
||||||
|
return DynamoDBPersistenceLayer(PYTEST_TABLE_NAME, dynamodb_client)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def dynamodb_seeds(dynamodb_client):
|
||||||
|
with jsonlines.open('tests/seeds.jsonl') as lines:
|
||||||
|
for line in lines:
|
||||||
|
dynamodb_client.put_item(TableName=PYTEST_TABLE_NAME, Item=line)
|
||||||
0
order-management/tests/events/__init__.py
Normal file
0
order-management/tests/events/__init__.py
Normal file
27
order-management/tests/events/test_assign_tenant.py
Normal file
27
order-management/tests/events/test_assign_tenant.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||||
|
from layercake.dynamodb import DynamoDBPersistenceLayer, PartitionKey
|
||||||
|
|
||||||
|
import events.assign_tenant_cnpj as app
|
||||||
|
|
||||||
|
|
||||||
|
def test_assign_tenant_cnpj(
|
||||||
|
dynamodb_seeds,
|
||||||
|
dynamodb_persistence_layer: DynamoDBPersistenceLayer,
|
||||||
|
lambda_context: LambdaContext,
|
||||||
|
):
|
||||||
|
event = {
|
||||||
|
'detail': {
|
||||||
|
'new_image': {
|
||||||
|
'id': '9omWNKymwU5U4aeun6mWzZ',
|
||||||
|
'cnpj': '15608435000190',
|
||||||
|
'email': 'sergio@somosbeta.com.br',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert app.lambda_handler(event, lambda_context) # type: ignore
|
||||||
|
|
||||||
|
result = dynamodb_persistence_layer.collect.query(
|
||||||
|
PartitionKey('9omWNKymwU5U4aeun6mWzZ')
|
||||||
|
)
|
||||||
|
assert 4 == len(result['items'])
|
||||||
7
order-management/tests/seeds.jsonl
Normal file
7
order-management/tests/seeds.jsonl
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{"id": {"S": "cJtK9SsnJhKPyxESe7g3DG"}, "sk": {"S": "0"}, "name": {"S": "EDUSEG"}}
|
||||||
|
{"id": {"S": "cJtK9SsnJhKPyxESe7g3DG"}, "sk": {"S": "metadata#payment_policy"}, "due_days": {"N": "90"}}
|
||||||
|
{"id": {"S": "9omWNKymwU5U4aeun6mWzZ"}, "sk": {"S": "0"}, "total": {"N": "398"}}
|
||||||
|
{"id": {"S": "9omWNKymwU5U4aeun6mWzZ"}, "sk": {"S": "metadata#tenant"}, "org_id": {"S": "cJtK9SsnJhKPyxESe7g3DG"}}
|
||||||
|
{"id": {"S": "cnpj"}, "sk": {"S": "15608435000190"}, "user_id": {"S": "cJtK9SsnJhKPyxESe7g3DG"}}
|
||||||
|
{"id": {"S": "email"}, "sk": {"S": "sergio@somosbeta.com.br"}, "user_id": {"S": "5OxmMjL-ujoR5IMGegQz"}}
|
||||||
|
{"id": {"S": "5OxmMjL-ujoR5IMGegQz"}, "sk": {"S": "0"}, "name": {"S": "Sérgio R Siqueira"}}
|
||||||
1052
order-management/uv.lock
generated
Normal file
1052
order-management/uv.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user