import os, requests
from collections import defaultdict
STORE = os.environ["SHOPIFY_STORE"]
TOKEN = os.environ["SHOPIFY_ACCESS_TOKEN"]
MV = os.environ["MAVERA_API_KEY"]
SH = f"https://{STORE}.myshopify.com/admin/api/2024-10/graphql.json"
SH_H = {"X-Shopify-Access-Token": TOKEN, "Content-Type": "application/json"}
MB = "https://app.mavera.io/api/v1"
MH = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
QUERY = """query ($cursor: String) {
orders(first: 250, after: $cursor, sortKey: CREATED_AT, query: "created_at:>2023-01-01") {
edges { node { createdAt totalPriceSet { shopMoney { amount } } lineItems(first: 3) { edges { node { title quantity } } } } }
pageInfo { hasNextPage endCursor }
}
}"""
orders, cursor = [], None
while True:
resp = requests.post(SH, json={"query": QUERY, "variables": {"cursor": cursor} if cursor else {}}, headers=SH_H)
resp.raise_for_status()
data = resp.json()["data"]["orders"]
orders.extend(e["node"] for e in data["edges"])
if not data["pageInfo"]["hasNextPage"]: break
cursor = data["pageInfo"]["endCursor"]
monthly = defaultdict(lambda: {"revenue": 0, "orders": 0, "items": defaultdict(int)})
for o in orders:
k = o["createdAt"][:7]
monthly[k]["revenue"] += float(o["totalPriceSet"]["shopMoney"]["amount"])
monthly[k]["orders"] += 1
for li in o["lineItems"]["edges"]:
monthly[k]["items"][li["node"]["title"]] += li["node"]["quantity"]
lines = ["Month | Orders | Revenue | AOV | Top Product", "------|--------|---------|-----|------------"]
for m, d in sorted(monthly.items()):
top = max(d["items"], key=d["items"].get) if d["items"] else "N/A"
lines.append(f"{m} | {d['orders']} | ${d['revenue']:.0f} | ${d['revenue']/d['orders']:.0f} | {top}")
summary = "\n".join(lines)
print(summary)
plan = requests.post(f"{MB}/mave/chat", json={"input": [
{"role": "system", "content": "Senior marketing strategist. Given monthly sales data, create a 12-month campaign calendar. Per campaign: timing, theme, audience, messaging, budget share (%)."},
{"role": "user", "content": f"Sales data:\n\n{summary}\n\nCreate campaign calendar for next 12 months."},
]}, headers=MH)
plan.raise_for_status()
print(f"\n--- Campaign Plan ---\n{plan.json()['choices'][0]['message']['content']}")