Skip to content

Commit cd23512

Browse files
Refactor participant creation logic in lambda_function.py to improve clarity and error handling. Introduce a new function for creating participant objects, streamline event and certificate initialization, and enhance logging for better traceability during processing. Update lambda_handler to handle SQS messages and return detailed results.
1 parent 09b43ec commit cd23512

1 file changed

Lines changed: 105 additions & 49 deletions

File tree

lambda_function.py

Lines changed: 105 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
from models.certificate import Certificate
66
from models.event import Event
77
from datetime import datetime
8+
import base64
9+
import os
810

911
# Configure logging for CloudWatch
1012
logger = logging.getLogger()
@@ -22,6 +24,14 @@
2224
))
2325
logger.addHandler(handler)
2426

27+
class DateTimeEncoder(json.JSONEncoder):
28+
def default(self, obj):
29+
if isinstance(obj, datetime):
30+
return obj.strftime('%Y-%m-%d %H:%M:%S')
31+
if hasattr(obj, 'dict'):
32+
return obj.dict()
33+
return super().default(obj)
34+
2535
def extract_data_body(event):
2636
try:
2737
logger.info("Event recebido : {}".format(event))
@@ -35,68 +45,114 @@ def extract_data_body(event):
3545
logger.error(f"Erro ao extrair dados do body: {str(e)}", exc_info=True)
3646
raise
3747

38-
def create_participants_list(data):
39-
participants = []
40-
for item in data:
41-
# Create certificate object if certificate details exist
42-
certificate = None
43-
if 'certificate_details' in item and 'certificate_logo' in item and 'certificate_background' in item:
44-
certificate = Certificate(
45-
details=item['certificate_details'],
46-
logo=item['certificate_logo'],
47-
background=item['certificate_background']
48-
)
49-
50-
# Create event object
51-
event = None
52-
if all(key in item for key in ['order_id', 'product_id', 'product_name', 'order_date', 'time_checkin', 'checkin_latitude', 'checkin_longitude']):
53-
event = Event(
54-
order_id=item['order_id'],
55-
product_id=item['product_id'],
56-
product_name=item['product_name'],
57-
date=datetime.strptime(item['order_date'], '%Y-%m-%d %H:%M:%S'),
58-
time_checkin=datetime.strptime(item['time_checkin'], '%Y-%m-%d %H:%M:%S'),
59-
checkin_latitude=float(item['checkin_latitude']) if item['checkin_latitude'] else 0.0,
60-
checkin_longitude=float(item['checkin_longitude']) if item['checkin_longitude'] else 0.0
61-
)
48+
def create_participant_object(participant_data):
49+
# Create Certificate object
50+
certificate = Certificate(
51+
details=participant_data.get('certificate_details'),
52+
logo=participant_data.get('certificate_logo'),
53+
background=participant_data.get('certificate_background')
54+
)
55+
56+
# Create Event object
57+
event = Event(
58+
order_id=participant_data.get('order_id'),
59+
product_id=participant_data.get('product_id'),
60+
product_name=participant_data.get('product_name'),
61+
date=datetime.strptime(participant_data.get('order_date'), "%Y-%m-%d %H:%M:%S"),
62+
time_checkin=datetime.strptime(participant_data.get('time_checkin'), "%Y-%m-%d %H:%M:%S") if participant_data.get('time_checkin') else None,
63+
checkin_latitude=float(participant_data.get('checkin_latitude')) if participant_data.get('checkin_latitude') else None,
64+
checkin_longitude=float(participant_data.get('checkin_longitude')) if participant_data.get('checkin_longitude') else None
65+
)
66+
67+
# Create Participant object
68+
participant = Participant(
69+
first_name=participant_data.get('first_name'),
70+
last_name=participant_data.get('last_name'),
71+
email=participant_data.get('email'),
72+
phone=participant_data.get('phone'),
73+
cpf=participant_data.get('cpf', ''),
74+
certificate=certificate,
75+
event=event
76+
)
77+
return participant
6278

63-
participant = Participant(
64-
first_name=item['first_name'],
65-
last_name=item['last_name'],
66-
email=item['email'],
67-
phone=item['phone'],
68-
cpf=item['cpf'],
69-
certificate=certificate,
70-
event=event
71-
)
72-
participants.append(participant)
73-
return participants
79+
def format_result(result):
80+
if isinstance(result, dict):
81+
formatted = {}
82+
for key, value in result.items():
83+
if isinstance(value, (Participant, Certificate, Event)):
84+
formatted[key] = value.model_dump()
85+
elif isinstance(value, datetime):
86+
formatted[key] = value.strftime('%Y-%m-%d %H:%M:%S')
87+
else:
88+
formatted[key] = value
89+
return formatted
90+
return result
7491

7592
def lambda_handler(event, context):
7693
# Log the start of the Lambda execution
7794
try:
7895
logger.info("Starting Lambda execution")
7996
body = extract_data_body(event)
80-
participants_data = body['participants'] # New field expected in the body
97+
participants_data = body.get('participants', [])
98+
99+
if not participants_data:
100+
logger.warning("No participants found in message")
101+
return {
102+
'statusCode': 400,
103+
'body': json.dumps({
104+
'error': 'No participants found in message',
105+
'message': 'Nenhum participante encontrado para processamento'
106+
})
107+
}
108+
81109
logger.info("Iniciando geração de certificados")
82110

83111
# Create list of participants
84-
participants = create_participants_list(participants_data)
85-
logger.info(f"Created {len(participants)} participants")
112+
participants = []
113+
results = []
86114

87-
certified_builder = CertifiedBuilder()
88-
certified_builder.build_certificates(participants)
115+
for participant_data in participants_data:
116+
try:
117+
participant = create_participant_object(participant_data)
118+
participants.append(participant)
119+
except Exception as e:
120+
logger.error(f"Error creating participant object: {str(e)}")
121+
results.append({
122+
'participant_data': participant_data,
123+
'error': str(e),
124+
'success': False
125+
})
89126

90-
logger.info("Certificados gerados com sucesso")
91-
return {
92-
'statusCode': 200,
93-
'body': json.dumps({
94-
'message': 'Certificados gerados com sucesso',
95-
'participants_processed': len(participants)
96-
})
97-
}
127+
# Generate certificates if we have valid participants
128+
if participants:
129+
builder = CertifiedBuilder()
130+
certificates_results = builder.build_certificates(participants)
131+
# Format results before adding to response
132+
formatted_results = [format_result(result) for result in certificates_results]
133+
results.extend(formatted_results)
134+
135+
logger.info("Certificados gerados com sucesso")
136+
return {
137+
'statusCode': 200,
138+
'body': json.dumps({
139+
'message': 'Processamento concluído',
140+
'results': results
141+
}, cls=DateTimeEncoder)
142+
}
143+
else:
144+
logger.warning("No valid participants to process")
145+
return {
146+
'statusCode': 400,
147+
'body': json.dumps({
148+
'error': 'No valid participants to process',
149+
'message': 'Nenhum participante válido para processamento',
150+
'results': results
151+
}, cls=DateTimeEncoder)
152+
}
153+
98154
except Exception as e:
99-
logger.error(f"Erro ao gerar certificados: {str(e)}", exc_info=True)
155+
logger.error(f"Error in lambda handler: {str(e)}")
100156
return {
101157
'statusCode': 500,
102158
'body': json.dumps({

0 commit comments

Comments
 (0)