forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1919 lines (1626 loc) · 82.4 KB
/
Copy pathmain.py
File metadata and controls
1919 lines (1626 loc) · 82.4 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Shopify Integration App for Omi
This app provides Shopify integration through OAuth authentication
and chat tools for analytics, orders, and customer management.
"""
import os
import hmac
import hashlib
import urllib.parse
from datetime import datetime, timedelta
from typing import Optional, Dict, Any, List
import requests
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, Query, Form
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from db import (
store_shopify_tokens,
get_shopify_tokens,
delete_shopify_tokens,
store_default_store,
get_default_store,
get_user_settings,
)
from models import (
ChatToolResponse,
ShopifyOrder,
ShopifyCustomer,
ShopifyLineItem,
ShopifyAnalytics,
ShopifyShop,
)
load_dotenv()
# Shopify API Configuration
SHOPIFY_CLIENT_ID = os.getenv("SHOPIFY_CLIENT_ID", "YOUR_CLIENT_ID_HERE")
SHOPIFY_CLIENT_SECRET = os.getenv("SHOPIFY_CLIENT_SECRET", "YOUR_CLIENT_SECRET_HERE")
SHOPIFY_REDIRECT_URI = os.getenv("SHOPIFY_REDIRECT_URI", "http://localhost:8080/auth/shopify/callback")
# Shopify API version
SHOPIFY_API_VERSION = "2024-01"
# Required Shopify scopes
SHOPIFY_SCOPES = [
"read_all_orders",
"read_analytics",
"read_customers",
"write_customers",
"write_draft_orders",
"read_draft_orders",
"read_orders",
"write_orders",
]
app = FastAPI(
title="Shopify Omi Integration",
description="Shopify integration for Omi - Analytics, orders, and customer management",
version="1.0.0"
)
# Mount static files and templates
templates_dir = os.path.join(os.path.dirname(__file__), "templates")
if os.path.exists(templates_dir):
static_dir = os.path.join(templates_dir, "static")
if os.path.exists(static_dir):
app.mount("/static", StaticFiles(directory=static_dir), name="static")
templates = Jinja2Templates(directory=templates_dir)
# ============================================
# Helper Functions
# ============================================
def get_auth_header(access_token: str) -> Dict[str, str]:
"""Get authorization header for Shopify API requests."""
return {
"X-Shopify-Access-Token": access_token,
"Content-Type": "application/json",
}
def shopify_api_request(
uid: str,
method: str,
endpoint: str,
params: Optional[Dict] = None,
json_data: Optional[Dict] = None
) -> Dict[str, Any]:
"""Make an authenticated request to Shopify API."""
tokens = get_shopify_tokens(uid)
if not tokens:
return {"error": "User not authenticated with Shopify"}
access_token = tokens["access_token"]
shop_domain = tokens["shop_domain"]
url = f"https://{shop_domain}/admin/api/{SHOPIFY_API_VERSION}{endpoint}"
headers = get_auth_header(access_token)
try:
if method.upper() == "GET":
response = requests.get(url, headers=headers, params=params)
elif method.upper() == "POST":
response = requests.post(url, headers=headers, json=json_data, params=params)
elif method.upper() == "PUT":
response = requests.put(url, headers=headers, json=json_data, params=params)
elif method.upper() == "DELETE":
response = requests.delete(url, headers=headers, params=params)
else:
return {"error": f"Unsupported HTTP method: {method}"}
if response.status_code == 204:
return {"success": True}
elif response.status_code >= 400:
error_data = response.json() if response.content else {}
error_msg = error_data.get("errors", f"API error: {response.status_code}")
if isinstance(error_msg, dict):
error_msg = str(error_msg)
return {"error": error_msg}
return response.json() if response.content else {"success": True}
except requests.RequestException as e:
return {"error": f"Request failed: {str(e)}"}
def verify_shopify_hmac(query_string: str, hmac_value: str) -> bool:
"""Verify the HMAC signature from Shopify."""
# Parse query string and remove hmac parameter
params = urllib.parse.parse_qs(query_string)
params.pop('hmac', None)
# Sort and encode parameters
sorted_params = sorted(params.items())
encoded = urllib.parse.urlencode([(k, v[0]) for k, v in sorted_params])
# Calculate HMAC
digest = hmac.new(
SHOPIFY_CLIENT_SECRET.encode('utf-8'),
encoded.encode('utf-8'),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(digest, hmac_value)
def format_currency(amount: str, currency: str = "USD") -> str:
"""Format currency amount."""
try:
value = float(amount)
return f"${value:,.2f} {currency}"
except (ValueError, TypeError):
return f"${amount} {currency}"
def format_datetime(dt_string: str) -> str:
"""Format datetime string to readable format."""
try:
dt = datetime.fromisoformat(dt_string.replace('Z', '+00:00'))
return dt.strftime("%B %d, %Y at %I:%M %p")
except (ValueError, TypeError):
return dt_string
# ============================================
# OAuth Endpoints
# ============================================
@app.get("/", response_class=HTMLResponse)
async def home(request: Request, uid: Optional[str] = None):
"""Home page / App settings page."""
if not uid:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Missing user ID"
})
tokens = get_shopify_tokens(uid)
authenticated = tokens is not None
# Get shop info if authenticated
shop_info = None
recent_orders = []
if authenticated:
shop_result = shopify_api_request(uid, "GET", "/shop.json")
if "error" not in shop_result:
shop_info = shop_result.get("shop", {})
# Get recent orders count
orders_result = shopify_api_request(uid, "GET", "/orders/count.json")
if "error" not in orders_result:
recent_orders = orders_result
return templates.TemplateResponse("setup.html", {
"request": request,
"uid": uid,
"authenticated": authenticated,
"shop_info": shop_info,
"recent_orders": recent_orders,
"shop_domain": tokens.get("shop_domain") if tokens else None,
})
@app.get("/auth/shopify")
async def shopify_auth(uid: str, shop: Optional[str] = None):
"""Initiate Shopify OAuth flow."""
if not uid:
raise HTTPException(status_code=400, detail="User ID is required")
if not shop:
# Return a page to enter shop domain
raise HTTPException(status_code=400, detail="Shop domain is required. Use /auth/shopify?uid=...&shop=your-store.myshopify.com")
# Ensure shop domain is properly formatted
if not shop.endswith('.myshopify.com'):
shop = f"{shop}.myshopify.com"
# Build OAuth URL
scopes = ",".join(SHOPIFY_SCOPES)
params = {
"client_id": SHOPIFY_CLIENT_ID,
"scope": scopes,
"redirect_uri": SHOPIFY_REDIRECT_URI,
"state": uid, # Use uid as state to identify user on callback
}
auth_url = f"https://{shop}/admin/oauth/authorize?{urllib.parse.urlencode(params)}"
print(f"🔐 SHOPIFY OAUTH - Redirecting to: {auth_url}")
print(f"🔐 Client ID: {SHOPIFY_CLIENT_ID}")
print(f"🔐 Redirect URI: {SHOPIFY_REDIRECT_URI}")
print(f"🔐 Shop: {shop}")
print(f"🔐 Scopes: {scopes}")
return RedirectResponse(url=auth_url)
@app.get("/auth/shopify/callback", response_class=HTMLResponse)
async def shopify_callback(
request: Request,
code: Optional[str] = None,
state: Optional[str] = None,
shop: Optional[str] = None,
hmac: Optional[str] = None,
error: Optional[str] = None,
error_description: Optional[str] = None
):
"""Handle Shopify OAuth callback."""
if error:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": f"Authorization failed: {error_description or error}"
})
if not code or not state or not shop:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Invalid callback parameters"
})
uid = state
# Exchange code for access token
token_url = f"https://{shop}/admin/oauth/access_token"
response = requests.post(
token_url,
json={
"client_id": SHOPIFY_CLIENT_ID,
"client_secret": SHOPIFY_CLIENT_SECRET,
"code": code,
},
)
if response.status_code != 200:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Failed to exchange authorization code"
})
token_data = response.json()
access_token = token_data.get("access_token")
scope = token_data.get("scope", "")
if not access_token:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "No access token received"
})
# Store tokens
store_shopify_tokens(uid, access_token, shop, scope)
# Get shop name and store as default
headers = get_auth_header(access_token)
shop_response = requests.get(
f"https://{shop}/admin/api/{SHOPIFY_API_VERSION}/shop.json",
headers=headers
)
if shop_response.status_code == 200:
shop_data = shop_response.json().get("shop", {})
store_default_store(uid, shop, shop_data.get("name", shop))
# Redirect to home with uid
return RedirectResponse(url=f"/?uid={uid}")
@app.get("/setup/shopify", tags=["setup"])
async def check_setup(uid: str):
"""Check if the user has completed Shopify setup (used by Omi)."""
tokens = get_shopify_tokens(uid)
return {"is_setup_completed": tokens is not None}
@app.get("/disconnect")
async def disconnect_shopify(uid: str):
"""Disconnect Shopify account."""
delete_shopify_tokens(uid)
return RedirectResponse(url=f"/?uid={uid}")
# ============================================
# Chat Tool Endpoints
# ============================================
def parse_date(date_str: str) -> Optional[datetime]:
"""Parse various date formats into datetime object."""
if not date_str:
return None
# Try various date formats
formats = [
"%Y-%m-%d", # 2024-11-28
"%m/%d/%Y", # 11/28/2024
"%d/%m/%Y", # 28/11/2024
"%B %d, %Y", # November 28, 2024
"%b %d, %Y", # Nov 28, 2024
"%B %d %Y", # November 28 2024
"%b %d %Y", # Nov 28 2024
"%d %B %Y", # 28 November 2024
"%d %b %Y", # 28 Nov 2024
"%Y/%m/%d", # 2024/11/28
]
for fmt in formats:
try:
return datetime.strptime(date_str.strip(), fmt)
except ValueError:
continue
return None
@app.post("/tools/get_analytics", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_get_analytics(request: Request):
"""
Get store analytics.
Chat tool for Omi - retrieves store analytics and sales data.
Supports both preset periods and custom date ranges.
"""
try:
body = await request.json()
uid = body.get("uid")
period = body.get("period", "today")
custom_start_date = body.get("start_date") # Custom start date
custom_end_date = body.get("end_date") # Custom end date
if not uid:
return ChatToolResponse(error="User ID is required")
# Check authentication
if not get_shopify_tokens(uid):
return ChatToolResponse(error="Please connect your Shopify store first in the app settings.")
# Calculate date range based on period or custom dates
today = datetime.utcnow().date()
period_text = ""
# If custom dates are provided, use them
if custom_start_date and custom_end_date:
parsed_start = parse_date(custom_start_date)
parsed_end = parse_date(custom_end_date)
if not parsed_start or not parsed_end:
return ChatToolResponse(error=f"Invalid date format. Please use formats like '2024-11-28', 'Nov 28, 2024', or '11/28/2024'.")
start_date = parsed_start.date()
end_date = parsed_end.date()
period_text = f"{start_date.strftime('%b %d')} - {end_date.strftime('%b %d, %Y')}"
elif custom_start_date:
# Only start date provided - use today as end
parsed_start = parse_date(custom_start_date)
if not parsed_start:
return ChatToolResponse(error=f"Invalid start date format. Please use formats like '2024-11-28', 'Nov 28, 2024', or '11/28/2024'.")
start_date = parsed_start.date()
end_date = today
period_text = f"{start_date.strftime('%b %d')} - {end_date.strftime('%b %d, %Y')}"
else:
# Use preset period
if period == "yesterday":
start_date = today - timedelta(days=1)
end_date = today - timedelta(days=1)
elif period == "last_7_days":
start_date = today - timedelta(days=7)
end_date = today
elif period == "last_30_days":
start_date = today - timedelta(days=30)
end_date = today
elif period == "this_month":
start_date = today.replace(day=1)
end_date = today
elif period == "last_month":
first_of_this_month = today.replace(day=1)
end_date = first_of_this_month - timedelta(days=1)
start_date = end_date.replace(day=1)
elif period == "this_year":
start_date = today.replace(month=1, day=1)
end_date = today
else: # today
start_date = today
end_date = today
period_text = {
"today": "Today",
"yesterday": "Yesterday",
"last_7_days": "Last 7 Days",
"last_30_days": "Last 30 Days",
"this_month": "This Month",
"last_month": "Last Month",
"this_year": "This Year"
}.get(period, period)
# Get orders - need to handle pagination for large date ranges
all_orders = []
params = {
"status": "any",
"created_at_min": f"{start_date}T00:00:00Z",
"created_at_max": f"{end_date}T23:59:59Z",
"limit": 250, # Max per page
}
# Fetch first page
orders_result = shopify_api_request(uid, "GET", "/orders.json", params=params)
if "error" in orders_result:
return ChatToolResponse(error=f"Failed to get analytics: {orders_result['error']}")
all_orders.extend(orders_result.get("orders", []))
# Fetch additional pages if needed (up to 1000 orders total)
page_count = 1
while len(orders_result.get("orders", [])) == 250 and page_count < 4:
# Get the last order ID for pagination
last_order_id = orders_result["orders"][-1]["id"]
params["since_id"] = last_order_id
orders_result = shopify_api_request(uid, "GET", "/orders.json", params=params)
if "error" in orders_result:
break
all_orders.extend(orders_result.get("orders", []))
page_count += 1
orders = all_orders
# Calculate detailed financial analytics
total_orders = len(orders)
# Gross sales (subtotal before discounts, taxes, shipping)
gross_sales = sum(float(o.get("subtotal_price", 0)) for o in orders)
# Total discounts applied
total_discounts = sum(float(o.get("total_discounts", 0)) for o in orders)
# Calculate refunds
total_refunds = 0
refunded_orders = 0
for order in orders:
refunds = order.get("refunds", [])
if refunds:
refunded_orders += 1
for refund in refunds:
for transaction in refund.get("transactions", []):
total_refunds += float(transaction.get("amount", 0))
# Net sales (gross - discounts - refunds)
net_sales = gross_sales - total_discounts - total_refunds
# Total collected (what was actually charged - includes tax & shipping)
total_collected = sum(float(o.get("total_price", 0)) for o in orders)
# Taxes and shipping
total_tax = sum(float(o.get("total_tax", 0)) for o in orders)
total_shipping = sum(
float(o.get("total_shipping_price_set", {}).get("shop_money", {}).get("amount", 0))
for o in orders
)
avg_order_value = total_collected / total_orders if total_orders > 0 else 0
# Count unique customers
customer_ids = set()
new_customers = 0
returning_customers = 0
for order in orders:
if order.get("customer"):
customer_id = order["customer"].get("id")
customer_ids.add(customer_id)
# Check if new customer (orders_count == 1 at time of order)
if order["customer"].get("orders_count", 0) <= 1:
new_customers += 1
else:
returning_customers += 1
# Get currency from first order or default
currency = orders[0].get("currency", "USD") if orders else "USD"
# Calculate additional metrics
total_items = sum(
sum(item.get("quantity", 0) for item in o.get("line_items", []))
for o in orders
)
avg_items_per_order = total_items / total_orders if total_orders > 0 else 0
# Discount rate
discount_rate = (total_discounts / gross_sales * 100) if gross_sales > 0 else 0
# Calculate COGS (Cost of Goods Sold) by fetching variant costs
total_cogs = 0
variant_costs = {} # Cache variant costs to avoid repeated API calls
cogs_available = True
# Collect all unique variant IDs
variant_ids = set()
for order in orders:
for item in order.get("line_items", []):
variant_id = item.get("variant_id")
if variant_id:
variant_ids.add(variant_id)
# Fetch costs for variants (batch fetch products)
if variant_ids:
# Get unique product IDs
product_ids = set()
for order in orders:
for item in order.get("line_items", []):
product_id = item.get("product_id")
if product_id:
product_ids.add(product_id)
# Fetch products with variants to get inventory_item_ids
inventory_item_ids = []
for product_id in list(product_ids)[:50]: # Limit to avoid too many API calls
product_result = shopify_api_request(uid, "GET", f"/products/{product_id}.json")
if "error" not in product_result:
product = product_result.get("product", {})
for variant in product.get("variants", []):
inv_item_id = variant.get("inventory_item_id")
if inv_item_id:
inventory_item_ids.append((variant["id"], inv_item_id))
# Fetch inventory items to get costs (batch up to 100)
if inventory_item_ids:
inv_ids_str = ",".join(str(iid[1]) for iid in inventory_item_ids[:100])
inv_result = shopify_api_request(
uid, "GET", "/inventory_items.json",
params={"ids": inv_ids_str}
)
if "error" not in inv_result:
for inv_item in inv_result.get("inventory_items", []):
inv_id = inv_item.get("id")
cost = inv_item.get("cost")
# Find matching variant
for var_id, iid in inventory_item_ids:
if iid == inv_id and cost:
variant_costs[var_id] = float(cost)
# Calculate total COGS
items_with_cost = 0
items_without_cost = 0
for order in orders:
for item in order.get("line_items", []):
variant_id = item.get("variant_id")
quantity = item.get("quantity", 0)
if variant_id and variant_id in variant_costs:
total_cogs += variant_costs[variant_id] * quantity
items_with_cost += quantity
else:
items_without_cost += quantity
# Calculate profit metrics
gross_profit = net_sales - total_cogs
profit_margin = (gross_profit / net_sales * 100) if net_sales > 0 else 0
# Check if COGS data is complete
cogs_note = ""
if items_without_cost > 0:
cogs_coverage = (items_with_cost / (items_with_cost + items_without_cost) * 100) if (items_with_cost + items_without_cost) > 0 else 0
if cogs_coverage < 100:
cogs_note = f" ({cogs_coverage:.0f}% of items have cost data)"
result = f"""📊 **Store Analytics - {period_text}**
**💵 FINANCIAL SUMMARY**
━━━━━━━━━━━━━━━━━━━━━━
📈 **Gross Sales:** {format_currency(str(gross_sales), currency)}
🏷️ **Discounts:** -{format_currency(str(total_discounts), currency)} ({discount_rate:.1f}%)
↩️ **Refunds:** -{format_currency(str(total_refunds), currency)} ({refunded_orders} orders)
━━━━━━━━━━━━━━━━━━━━━━
💰 **Net Sales:** {format_currency(str(net_sales), currency)}
**📊 PROFIT & LOSS**
━━━━━━━━━━━━━━━━━━━━━━
💰 **Net Sales:** {format_currency(str(net_sales), currency)}
📦 **COGS:** -{format_currency(str(total_cogs), currency)}{cogs_note}
━━━━━━━━━━━━━━━━━━━━━━
💹 **Gross Profit:** {format_currency(str(gross_profit), currency)}
📈 **Profit Margin:** {profit_margin:.1f}%
**📦 ORDER METRICS**
━━━━━━━━━━━━━━━━━━━━━━
📦 **Total Orders:** {total_orders}
💵 **Avg Order Value:** {format_currency(str(avg_order_value), currency)}
🛒 **Items Sold:** {total_items}
📊 **Avg Items/Order:** {avg_items_per_order:.1f}
**👥 CUSTOMERS**
━━━━━━━━━━━━━━━━━━━━━━
👥 **Unique Customers:** {len(customer_ids)}
✨ **New Customers:** {new_customers}
🔄 **Returning:** {returning_customers}
**💳 COLLECTED**
━━━━━━━━━━━━━━━━━━━━━━
💳 **Total Collected:** {format_currency(str(total_collected), currency)}
🏛️ **Tax:** {format_currency(str(total_tax), currency)}
🚚 **Shipping:** {format_currency(str(total_shipping), currency)}"""
# Add top products if we have orders
if orders:
product_sales = {}
product_revenue = {}
for order in orders:
for item in order.get("line_items", []):
title = item.get("title", "Unknown")
qty = item.get("quantity", 0)
price = float(item.get("price", 0)) * qty
product_sales[title] = product_sales.get(title, 0) + qty
product_revenue[title] = product_revenue.get(title, 0) + price
if product_sales:
top_products = sorted(product_sales.items(), key=lambda x: x[1], reverse=True)[:5]
result += "\n\n📈 **Top Products (by quantity):**"
for i, (name, qty) in enumerate(top_products, 1):
revenue = product_revenue.get(name, 0)
result += f"\n{i}. {name} - {qty} sold ({format_currency(str(revenue), currency)})"
return ChatToolResponse(result=result)
except Exception as e:
return ChatToolResponse(error=f"Failed to get analytics: {str(e)}")
@app.post("/tools/get_orders", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_get_orders(request: Request):
"""
Get recent orders.
Chat tool for Omi - retrieves a list of recent orders.
"""
try:
body = await request.json()
uid = body.get("uid")
status = body.get("status", "any")
financial_status = body.get("financial_status")
limit = min(body.get("limit", 10), 50)
if not uid:
return ChatToolResponse(error="User ID is required")
# Check authentication
if not get_shopify_tokens(uid):
return ChatToolResponse(error="Please connect your Shopify store first in the app settings.")
params = {
"status": status,
"limit": limit,
}
if financial_status:
params["financial_status"] = financial_status
result = shopify_api_request(uid, "GET", "/orders.json", params=params)
if "error" in result:
return ChatToolResponse(error=f"Failed to get orders: {result['error']}")
orders = result.get("orders", [])
if not orders:
return ChatToolResponse(result="📦 No orders found matching your criteria.")
# Format results
lines = [f"📦 **Recent Orders** ({len(orders)} found):\n"]
for order in orders:
order_name = order.get("name", f"#{order.get('order_number', 'N/A')}")
total = format_currency(order.get("total_price", "0"), order.get("currency", "USD"))
status_emoji = {
"paid": "✅",
"pending": "⏳",
"refunded": "↩️",
"partially_refunded": "↩️",
"voided": "❌",
}.get(order.get("financial_status", ""), "❓")
fulfillment = order.get("fulfillment_status") or "unfulfilled"
fulfillment_emoji = "📬" if fulfillment == "fulfilled" else "📦"
customer_name = "Guest"
if order.get("customer"):
first = order["customer"].get("first_name", "")
last = order["customer"].get("last_name", "")
customer_name = f"{first} {last}".strip() or order["customer"].get("email", "Guest")
created = format_datetime(order.get("created_at", ""))
lines.append(f"**{order_name}** - {total} {status_emoji}")
lines.append(f" 👤 {customer_name} | {fulfillment_emoji} {fulfillment.title()}")
lines.append(f" 📅 {created}\n")
return ChatToolResponse(result="\n".join(lines))
except Exception as e:
return ChatToolResponse(error=f"Failed to get orders: {str(e)}")
@app.post("/tools/get_order_details", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_get_order_details(request: Request):
"""
Get details of a specific order.
Chat tool for Omi - retrieves detailed information about an order.
"""
try:
body = await request.json()
uid = body.get("uid")
order_id = body.get("order_id")
order_number = body.get("order_number")
if not uid:
return ChatToolResponse(error="User ID is required")
if not order_id and not order_number:
return ChatToolResponse(error="Please provide an order ID or order number.")
# Check authentication
if not get_shopify_tokens(uid):
return ChatToolResponse(error="Please connect your Shopify store first in the app settings.")
# If we have order number, search for it
if order_number and not order_id:
# Remove # if present
order_number = str(order_number).lstrip('#')
result = shopify_api_request(
uid, "GET", "/orders.json",
params={"name": f"#{order_number}", "status": "any"}
)
if "error" in result:
return ChatToolResponse(error=f"Failed to find order: {result['error']}")
orders = result.get("orders", [])
if not orders:
return ChatToolResponse(error=f"Order #{order_number} not found.")
order_id = orders[0]["id"]
# Get order details
result = shopify_api_request(uid, "GET", f"/orders/{order_id}.json")
if "error" in result:
return ChatToolResponse(error=f"Failed to get order: {result['error']}")
order = result.get("order", {})
if not order:
return ChatToolResponse(error="Order not found.")
# Format order details
order_name = order.get("name", f"#{order.get('order_number', 'N/A')}")
currency = order.get("currency", "USD")
status_emoji = {
"paid": "✅ Paid",
"pending": "⏳ Pending",
"refunded": "↩️ Refunded",
"partially_refunded": "↩️ Partially Refunded",
"voided": "❌ Voided",
}.get(order.get("financial_status", ""), "❓ Unknown")
fulfillment = order.get("fulfillment_status") or "unfulfilled"
fulfillment_text = "📬 Fulfilled" if fulfillment == "fulfilled" else "📦 " + fulfillment.title()
# Customer info
customer_info = "👤 Guest checkout"
if order.get("customer"):
c = order["customer"]
name = f"{c.get('first_name', '')} {c.get('last_name', '')}".strip()
email = c.get("email", "")
customer_info = f"👤 {name or 'Customer'}"
if email:
customer_info += f" ({email})"
# Line items
items_text = ""
for item in order.get("line_items", []):
qty = item.get("quantity", 1)
title = item.get("title", "Unknown")
price = format_currency(item.get("price", "0"), currency)
items_text += f"\n • {qty}x {title} @ {price}"
# Shipping address
shipping_text = ""
if order.get("shipping_address"):
addr = order["shipping_address"]
shipping_text = f"\n\n📍 **Shipping to:**\n {addr.get('name', '')}\n {addr.get('address1', '')}"
if addr.get("address2"):
shipping_text += f"\n {addr['address2']}"
shipping_text += f"\n {addr.get('city', '')}, {addr.get('province', '')} {addr.get('zip', '')}\n {addr.get('country', '')}"
result_text = f"""📋 **Order {order_name}**
{status_emoji} | {fulfillment_text}
{customer_info}
📅 **Created:** {format_datetime(order.get('created_at', ''))}
🛒 **Items:**{items_text}
💰 **Subtotal:** {format_currency(order.get('subtotal_price', '0'), currency)}
📦 **Shipping:** {format_currency(order.get('total_shipping_price_set', {}).get('shop_money', {}).get('amount', '0'), currency)}
💵 **Tax:** {format_currency(order.get('total_tax', '0'), currency)}
**Total:** {format_currency(order.get('total_price', '0'), currency)}{shipping_text}"""
if order.get("note"):
result_text += f"\n\n📝 **Note:** {order['note']}"
return ChatToolResponse(result=result_text)
except Exception as e:
return ChatToolResponse(error=f"Failed to get order details: {str(e)}")
@app.post("/tools/create_order", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_create_order(request: Request):
"""
Create a new order.
Chat tool for Omi - creates a new order. Can search for customer by name or email.
Automatically fetches product prices from store.
"""
try:
body = await request.json()
print(f"🛒 CREATE ORDER - Received request: {body}")
uid = body.get("uid")
customer_email = body.get("customer_email")
customer_name = body.get("customer_name", "") # Can search by name
customer_first_name = body.get("customer_first_name", "")
customer_last_name = body.get("customer_last_name", "")
customer_phone = body.get("customer_phone", "")
customer_id_provided = body.get("customer_id") # Direct customer ID selection
line_items = body.get("line_items", [])
shipping_address = body.get("shipping_address")
note = body.get("note", "")
tags = body.get("tags", "")
send_receipt = body.get("send_receipt", True)
financial_status = body.get("financial_status", "pending")
discount_code = body.get("discount_code", "") # Coupon/discount code
free_shipping = body.get("free_shipping", False) # Skip shipping charges
# Check if discount code implies free shipping
if discount_code and "freeshipping" in discount_code.lower().replace("_", "").replace("-", "").replace(" ", ""):
free_shipping = True
print(f"🆓 Free shipping detected from discount code: {discount_code}")
# Address fields - can be passed individually
address_line1 = body.get("address_line1", "") or body.get("address1", "") or body.get("street", "")
address_line2 = body.get("address_line2", "") or body.get("address2", "")
city = body.get("city", "")
state = body.get("state", "") or body.get("province", "")
zip_code = body.get("zip_code", "") or body.get("zip", "") or body.get("postal_code", "")
country = body.get("country", "US")
# Build shipping address from individual fields if not provided as object
if not shipping_address and (address_line1 or city):
shipping_address = {
"first_name": customer_first_name or (customer_name.split()[0] if customer_name else ""),
"last_name": customer_last_name or (customer_name.split()[-1] if customer_name and len(customer_name.split()) > 1 else ""),
"address1": address_line1,
"address2": address_line2,
"city": city,
"province": state,
"zip": zip_code,
"country": country,
"phone": customer_phone,
}
print(f"📍 Built shipping address: {shipping_address}")
print(f"🔍 DEBUG: uid={uid}, line_items={line_items}")
if not uid:
print(f"❌ No UID provided")
return ChatToolResponse(error="User ID is required")
if not line_items:
print(f"❌ No line items provided")
return ChatToolResponse(error="At least one line item is required. Please provide items with product name and quantity.")
# Check authentication
try:
print(f"🔍 DEBUG: Getting tokens...")
tokens = get_shopify_tokens(uid)
print(f"🔍 DEBUG: tokens={tokens is not None}")
except Exception as e:
print(f"❌ Exception getting tokens: {e}")
import traceback
traceback.print_exc()
return ChatToolResponse(error=f"Auth error: {str(e)}")
if not tokens:
print(f"❌ No Shopify tokens found")
return ChatToolResponse(error="Please connect your Shopify store first in the app settings.")
customer_id = None
customer_created = False
customer_display_name = ""
# If customer_id provided directly, use it
if customer_id_provided:
customer_id = customer_id_provided
# Fetch customer details for display
cust_result = shopify_api_request(uid, "GET", f"/customers/{customer_id}.json")
if "error" not in cust_result and cust_result.get("customer"):
c = cust_result["customer"]
customer_display_name = f"{c.get('first_name', '')} {c.get('last_name', '')}".strip()
customer_email = c.get("email", "")
customer_first_name = c.get("first_name", "")
customer_last_name = c.get("last_name", "")
print(f"🛒 Using provided customer ID: {customer_id}")
# Search for customer by email first, then by name
elif customer_email or customer_name:
customers_found = []
# Search by email if provided
if customer_email:
result = shopify_api_request(
uid, "GET", "/customers/search.json",
params={"query": f"email:{customer_email}"}
)
if "error" not in result:
customers_found = result.get("customers", [])
# Search by name if no email or no results
if not customers_found and customer_name:
print(f"🔍 Searching for customer by name: {customer_name}")
result = shopify_api_request(
uid, "GET", "/customers/search.json",
params={"query": customer_name}
)
if "error" not in result:
customers_found = result.get("customers", [])
# Also try first/last name if provided
if not customers_found and (customer_first_name or customer_last_name):
search_term = f"{customer_first_name} {customer_last_name}".strip()
if search_term:
print(f"🔍 Searching for customer by first/last name: {search_term}")
result = shopify_api_request(
uid, "GET", "/customers/search.json",
params={"query": search_term}
)
if "error" not in result:
customers_found = result.get("customers", [])
if len(customers_found) > 1:
# Multiple matches - ask user to choose
lines = ["🔍 **Multiple customers found. Please specify which one:**\n"]
for i, c in enumerate(customers_found[:10], 1):
name = f"{c.get('first_name', '')} {c.get('last_name', '')}".strip() or "No name"
email = c.get("email", "No email")
orders_count = c.get("orders_count", 0)
lines.append(f"{i}. **{name}** - {email} ({orders_count} orders) [ID: {c['id']}]")
lines.append("\n💡 Try again with: 'create order for [email] for 3 Omis'")