Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda_function.py
More file actions
Latest commit
209 lines (184 loc) · 7.13 KB
/
Copy pathlambda_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
importlogging
importjson
fromcertified_builder.certified_builderimportCertifiedBuilder
frommodels.participantimportParticipant
frommodels.certificateimportCertificate
frommodels.eventimportEvent
fromdatetimeimportdatetime
importbase64
importos
fromaws.s3_serviceimportS3Service
fromaws.sqs_serviceimportSQSService
# Configure logging for CloudWatch
logger=logging.getLogger()
logger.setLevel(logging.INFO)
# Remove any existing handlers to avoid duplicate logs
forhandlerinlogger.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)
classDateTimeEncoder(json.JSONEncoder):
defdefault(self, obj):
ifisinstance(obj, datetime):
returnobj.strftime("%Y-%m-%d %H:%M:%S")
ifhasattr(obj, "model_dump"):
returnobj.model_dump()
returnsuper().default(obj)
defextract_data_body(event):
try:
logger.info("Event recebido : {}".format(event))
record=event["Records"][0]
ifisinstance(record["body"], str):
body=json.loads(record["body"])
returnbody
else:
returnrecord["body"]
exceptExceptionase:
logger.error(f"Erro ao extrair dados do body: {str(e)}", exc_info=True)
raise
defcreate_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")
ifparticipant_data.get("time_checkin")
elseNone
),
checkin_latitude=(
float(participant_data.get("checkin_latitude"))
ifparticipant_data.get("checkin_latitude")
elseNone
),
checkin_longitude=(
float(participant_data.get("checkin_longitude"))
ifparticipant_data.get("checkin_longitude")
elseNone
),
)
# 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,
)
returnparticipant
deflambda_handler(event, context):
# Log the start of the Lambda execution
try:
logger.info("Starting Lambda execution")
body=extract_data_body(event)
participants_data=body
ifnotparticipants_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= []
forparticipant_datainparticipants_data:
try:
participant=create_participant_object(participant_data)
participants.append(participant)
exceptExceptionase:
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
ifparticipants:
builder=CertifiedBuilder()
certificates_results=builder.build_certificates(participants)
# Format results before adding to response
certificates_results_messagens= []
forresultincertificates_results:
ifresult.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,
),
}
exceptExceptionase:
logger.error(f"Error in lambda handler: {str(e)}")
return {
"statusCode": 500,
"body": json.dumps(
{"error": str(e), "message": "Erro ao gerar certificados"}
),
}