-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda_function.py
More file actions
209 lines (184 loc) · 7.13 KB
/
lambda_function.py
File metadata and controls
209 lines (184 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import logging
import json
from certified_builder.certified_builder import CertifiedBuilder
from models.participant import Participant
from models.certificate import Certificate
from models.event import Event
from datetime import datetime
import base64
import os
from aws.s3_service import S3Service
from aws.sqs_service import SQSService
# Configure logging for CloudWatch
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Remove any existing handlers to avoid duplicate logs
for handler in logger.handlers:
logger.removeHandler(handler)
# Add a StreamHandler for CloudWatch
handler = logging.StreamHandler()
handler.setFormatter(
logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
logger.addHandler(handler)
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
if hasattr(obj, "model_dump"):
return obj.model_dump()
return super().default(obj)
def extract_data_body(event):
try:
logger.info("Event recebido : {}".format(event))
record = event["Records"][0]
if isinstance(record["body"], str):
body = json.loads(record["body"])
return body
else:
return record["body"]
except Exception as e:
logger.error(f"Erro ao extrair dados do body: {str(e)}", exc_info=True)
raise
def create_participant_object(participant_data):
# Create Certificate object
certificate = Certificate(
details=participant_data.get("certificate_details"),
logo=participant_data.get("certificate_logo"),
background=participant_data.get("certificate_background"),
)
# Create Event object
event = Event(
order_id=participant_data.get("order_id"),
product_id=participant_data.get("product_id"),
product_name=participant_data.get("product_name"),
date=datetime.strptime(participant_data.get("order_date"), "%Y-%m-%d %H:%M:%S"),
time_checkin=(
datetime.strptime(participant_data.get("time_checkin"), "%Y-%m-%d %H:%M:%S")
if participant_data.get("time_checkin")
else None
),
checkin_latitude=(
float(participant_data.get("checkin_latitude"))
if participant_data.get("checkin_latitude")
else None
),
checkin_longitude=(
float(participant_data.get("checkin_longitude"))
if participant_data.get("checkin_longitude")
else None
),
)
# Create Participant object
participant = Participant(
first_name=participant_data.get("first_name"),
last_name=participant_data.get("last_name"),
email=participant_data.get("email"),
phone=participant_data.get("phone"),
cpf=participant_data.get("cpf", ""),
certificate=certificate,
event=event,
)
return participant
def lambda_handler(event, context):
# Log the start of the Lambda execution
try:
logger.info("Starting Lambda execution")
body = extract_data_body(event)
participants_data = body
if not participants_data:
logger.warning("No participants found in message")
return {
"statusCode": 400,
"body": json.dumps(
{
"error": "No participants found in message",
"message": "Nenhum participante encontrado para processamento",
}
),
}
s3_service = S3Service()
sqs_service = SQSService()
logger.info(f"Processing {len(participants_data)} participants")
# Create list of participants
participants = []
results = []
for participant_data in participants_data:
try:
participant = create_participant_object(participant_data)
participants.append(participant)
except Exception as e:
logger.error(f"Error creating participant object: {str(e)}")
results.append(
{
"participant_data": participant_data,
"error": str(e),
"success": False,
}
)
# Generate certificates if we have valid participants
if participants:
builder = CertifiedBuilder()
certificates_results = builder.build_certificates(participants)
# Format results before adding to response
certificates_results_messagens = []
for result in certificates_results:
if result.get("success"):
s3_service.upload_file(
result.get("certificate_path"), result.get("certificate_key")
)
certificates_results_messagens.append(
{
"order_id": result.get("participant", {})
.get("event", {})
.get("order_id", ""),
"validation_code": result.get("participant", {}).get(
"validation_code", ""
),
"authenticity_verification_url": result.get(
"participant", {}
).get("authenticity_verification_url", ""),
"product_id": result.get("participant", {})
.get("event", {})
.get("product_id", ""),
"product_name": result.get("participant", {})
.get("event", {})
.get("product_name", ""),
"email": result.get("participant", {}).get("email", ""),
"certificate_key": result.get("certificate_key", ""),
"success": result.get("success", False),
}
)
sqs_service.send_message(certificates_results_messagens)
logger.info("Certificados gerados com sucesso")
return {
"statusCode": 200,
"body": json.dumps(
{"message": "Processamento concluído", "results": results},
cls=DateTimeEncoder,
),
}
else:
logger.warning("No valid participants to process")
return {
"statusCode": 400,
"body": json.dumps(
{
"error": "No valid participants to process",
"message": "Nenhum participante válido para processamento",
"results": results,
},
cls=DateTimeEncoder,
),
}
except Exception as e:
logger.error(f"Error in lambda handler: {str(e)}")
return {
"statusCode": 500,
"body": json.dumps(
{"error": str(e), "message": "Erro ao gerar certificados"}
),
}