## 👋 Hello Cristina
### Python
### Context
Cloud Function (serverless and event-driven computing) processing order events (JSON).
The Cloud Function should calculate the total amount of the order and then log the order.
### Expectation
A new field `totalAmount` is added to `orderDetails` containing the total amount due.
### Initial Problem
The following message was send to cloud function in a CI test pipeline.
Build failed with the following message:
```
Traceback (most recent call last):
File "python/cloud_function/src/process_order.py", line 36, in <module>
calculateTotal({
~~~~~~~~~~~~~~^^
"eventId": "123456",
^^^^^^^^^^^^^^^^^^^^
...<36 lines>...
"status": "CONFIRMED"
^^^^^^^^^^^^^^^^^^^^^
})
^^
File "python/cloud_function/src/process_order.py", line 13, in calculateTotal
for item in order_data["items"]:
~~~~~~~~~~^^^^^^^^^
KeyError: 'items'
```
{
"eventId": "123456",
"timestamp": "2023-10-01T12:30:00Z",
"orderDetails": {
"orderId": "ORD987654",
"customerId": "CUST12345",
"items": [
{
"itemId": "ITEM001",
"productName": "Wireless Headphones",
"quantity": 2,
"singleItemPrice": 59.99,
"category": "Electronics"
},
{
"itemId": "ITEM002",
"productName": "T-Shirt",
"quantity": 1,
"singleItemPrice": 39.99,
"category": "Clothing"
},
{
"itemId": "ITEM003",
"productName": "Cable Headphones",
"quantity": 2,
"singleItemPrice": 29.99,
"category": "Electronics"
}
],
"currency": "EUR",
"shippingAddress": {
"street": "123 Main St",
"city": "Hamburg",
"postalCode": "20095",
"country": "Germany"
},
"paymentMethod": "Credit Card"
},
"status": "CONFIRMED"
}
### Part 2
``` python
import base64
import json
import logging
from cloudevents.http import CloudEvent
import functions_framework
logger = logging.getLogger(__name__)
def calculateTotal(order_data):
order_details = order_data.get("orderDetails",{} )
items = order_details.get("items")
## Calculate the total
total = 0
for item in items:
total += item['singleItemPrice'] * item["quantity"]
return total
def set_key_value(order_data, value):
order_data["totalAmount"] = value
# Triggered by a pubsub event
@functions_framework.cloud_event
def accept(cloud_event: CloudEvent) -> None:
# Create dict from pubsub event data (verified)
event_data = base64.b64decode(cloud_event.data["message"]["data"])
order_data: dict = json.loads(event_data.decode('utf-8'))
# Process order
total = calculateTotal(order_data)
set_key_value(order_data, total)
# Print result
print(f"Processed order: {order_data}")
```
**TASKS:**
- First, find the reason for the error and fix it.
- Then review the whole code and improve it. Think about code quality, complexity and possible errors.