Plan with Code (Full Response)
```python
<execute_python>
# 1) Parse intent and quantities
import re
from tinydb import Query
import datetime
matches = re.findall(r'(\d+)\s+pairs?\s+of\s+(\w+)\s*sunglasses?', user_request, re.IGNORECASE)
if not matches:
STATUS = "invalid_request"
answer_text = "I can help with that—how many pairs would you like to purchase?"
print(f"LOG: ACTION=read DRY_RUN=True STATUS={STATUS}")
else:
# Normalize requested items
requested = []
for qty, name in matches:
requested.append({"name": name.title(), "qty": int(qty)})
# 2) Validate existence and stock
missing = None
insufficient = None
for req in requested:
Item = Query()
docs = inventory_tbl.search(Item.name.test(lambda n, nm=req["name"]: n.lower() == nm.lower()))
if not docs:
missing = req["name"]
break
doc = docs[0]
if doc["quantity_in_stock"] < req["qty"]:
insufficient = {"name": req["name"], "available": doc["quantity_in_stock"]}
break
if missing:
STATUS = "no_match"
answer_text = f"Sorry, we don’t have {missing} sunglasses right now. Maybe try a different style?"
print(f"LOG: ACTION=read DRY_RUN=True STATUS={STATUS}")
elif insufficient:
STATUS = "insufficient_stock"
answer_text = f"We only have {insufficient['available']} pairs of {insufficient['name']} left; let me know if you’d like to adjust your order."
print(f"LOG: ACTION=read DRY_RUN=True STATUS={STATUS}")
else:
# 3) Process purchase transactions
STATUS = "success"
balance = get_current_balance(transactions_tbl)
for req in requested:
Item = Query()
doc = inventory_tbl.get(Item.name.test(lambda n, nm=req["name"]: n.lower() == nm.lower()))
# Compute line total and new balance
line_total = doc["price"] * req["qty"]
balance_after = balance + line_total
# Insert transaction row
txn_id = next_transaction_id(transactions_tbl)
transactions_tbl.insert({
"transaction_id": txn_id,
"customer_name": "ANONYMOUS",
"transaction_summary": f"Purchase: {req['qty']} x {req['name']}",
"transaction_amount": line_total,
"balance_after_transaction": balance_after,
"timestamp": datetime.datetime.now().isoformat()
})
# Update stock
inventory_tbl.update(
{"quantity_in_stock": doc["quantity_in_stock"] - req["qty"]},
Item.item_id == doc["item_id"]
)
balance = balance_after
answer_text = "Thank you! Your order for 3 Classic and 1 Aviator sunglasses has been placed."
print(f"LOG: ACTION=mutate SHOULD_MUTATE=True STATUS={STATUS}")
</execute_python>
```