-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1333 lines (1105 loc) · 51 KB
/
Copy pathmain.py
File metadata and controls
1333 lines (1105 loc) · 51 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
"""
Splitwise Integration App for Omi
This app provides Splitwise integration through OAuth2 authentication
and chat tools for creating expenses and splitting costs with friends.
"""
import os
import sys
import secrets
import difflib
from datetime import datetime, timedelta
from typing import Optional, Dict, Any, List, Tuple
from decimal import Decimal, ROUND_DOWN
def log(msg: str):
"""Print and flush immediately for Railway logging."""
print(msg)
sys.stdout.flush()
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, Query
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from splitwise import Splitwise
from splitwise.expense import Expense
from splitwise.user import ExpenseUser
from db import (
store_splitwise_tokens,
get_splitwise_tokens,
delete_splitwise_tokens,
store_oauth_state,
get_oauth_state,
delete_oauth_state,
get_user_settings,
)
from models import (
ChatToolResponse,
CreateExpenseRequest,
SplitwiseFriend,
SplitwiseGroup,
SplitwiseUser,
)
load_dotenv()
# Splitwise API Configuration
SPLITWISE_CONSUMER_KEY = os.getenv("SPLITWISE_CONSUMER_KEY", "")
SPLITWISE_CONSUMER_SECRET = os.getenv("SPLITWISE_CONSUMER_SECRET", "")
SPLITWISE_REDIRECT_URI = os.getenv("SPLITWISE_REDIRECT_URI", "http://localhost:8080/auth/splitwise/callback")
app = FastAPI(
title="Splitwise Omi Integration",
description="Splitwise integration for Omi - Split expenses with friends using voice",
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_splitwise_client(uid: str) -> Optional[Splitwise]:
"""Get an authenticated Splitwise client for a user."""
tokens = get_splitwise_tokens(uid)
if not tokens:
return None
s = Splitwise(SPLITWISE_CONSUMER_KEY, SPLITWISE_CONSUMER_SECRET)
# setOAuth2AccessToken expects a dict with access_token and token_type
token_dict = {
"access_token": tokens["access_token"],
"token_type": tokens.get("token_type", "Bearer")
}
s.setOAuth2AccessToken(token_dict)
return s
def get_current_user(uid: str) -> Optional[SplitwiseUser]:
"""Get the current Splitwise user info."""
client = get_splitwise_client(uid)
if not client:
return None
try:
user = client.getCurrentUser()
return SplitwiseUser(
id=user.getId(),
first_name=user.getFirstName() or "",
last_name=user.getLastName(),
email=user.getEmail(),
default_currency=user.getDefaultCurrency() or "USD"
)
except Exception as e:
print(f"Error getting current user: {e}")
return None
def get_friends_list(uid: str) -> List[SplitwiseFriend]:
"""Get the user's friends list from Splitwise."""
client = get_splitwise_client(uid)
if not client:
return []
try:
friends = client.getFriends()
return [
SplitwiseFriend(
id=f.getId(),
first_name=f.getFirstName() or "",
last_name=f.getLastName(),
email=f.getEmail()
)
for f in friends
]
except Exception as e:
print(f"Error getting friends: {e}")
return []
def get_groups_list(uid: str) -> List[SplitwiseGroup]:
"""Get the user's groups list from Splitwise."""
client = get_splitwise_client(uid)
if not client:
return []
try:
groups = client.getGroups()
return [
SplitwiseGroup(
id=g.getId(),
name=g.getName() or ""
)
for g in groups
if g.getId() != 0 # Exclude "non-group" group
]
except Exception as e:
print(f"Error getting groups: {e}")
return []
def fuzzy_match_friend(name: str, friends: List[SplitwiseFriend], threshold: float = 0.35) -> Tuple[Optional[SplitwiseFriend], float, List[SplitwiseFriend]]:
"""
Fuzzy match a name against the friends list.
Returns: (best_match, confidence, top_candidates)
Uses multiple strategies including phonetic similarity for voice-transcribed names.
"""
if not friends:
return None, 0.0, []
name_lower = name.lower().strip()
scored_friends = []
# Remove common prefixes/noise from voice transcription
noise_words = ["with", "and", "to", "for", "the", "a", "an"]
name_clean = name_lower
for noise in noise_words:
name_clean = name_clean.replace(noise + " ", "").replace(" " + noise, "")
name_clean = name_clean.strip()
log(f"FUZZY: Matching '{name_clean}' against {len(friends)} friends")
for friend in friends:
# Build variations of the friend's name to match against
full_name = f"{friend.first_name} {friend.last_name or ''}".strip().lower()
first_name = friend.first_name.lower() if friend.first_name else ""
last_name = (friend.last_name or "").lower()
email_prefix = (friend.email or "").split("@")[0].lower() if friend.email else ""
scores = []
# Standard similarity scores
scores.append(("seq_full", difflib.SequenceMatcher(None, name_clean, full_name).ratio()))
scores.append(("seq_first", difflib.SequenceMatcher(None, name_clean, first_name).ratio()))
if last_name:
scores.append(("seq_last", difflib.SequenceMatcher(None, name_clean, last_name).ratio()))
if email_prefix:
scores.append(("seq_email", difflib.SequenceMatcher(None, name_clean, email_prefix).ratio()))
# Exact match
if name_clean == first_name or name_clean == last_name:
scores.append(("exact", 1.0))
# Substring/prefix matching - very important for nicknames like "ridz" -> "riddhi"
if name_clean in full_name:
scores.append(("substr_full", 0.85))
if name_clean in first_name:
scores.append(("substr_first", 0.9))
if first_name.startswith(name_clean):
scores.append(("prefix", 0.85))
# Nickname-style matching: first N chars match (e.g., "rid" matches "riddhi")
min_len = min(len(name_clean), len(first_name))
if min_len >= 2:
# Check if first 2-3 chars match
if name_clean[:2] == first_name[:2]:
scores.append(("first2", 0.6))
if min_len >= 3 and name_clean[:3] == first_name[:3]:
scores.append(("first3", 0.75))
# Character overlap - good for voice transcription errors
name_chars = set(name_clean.replace(" ", ""))
first_chars = set(first_name.replace(" ", ""))
if name_chars and first_chars:
overlap = name_chars & first_chars
char_overlap = len(overlap) / max(len(name_chars), len(first_chars))
scores.append(("char_overlap", char_overlap * 0.7))
# First letter bonus
if name_clean and first_name and name_clean[0] == first_name[0]:
current_max = max(s[1] for s in scores) if scores else 0
scores.append(("first_letter_bonus", current_max + 0.1))
# Consonant matching (vowels often get transcribed wrong)
name_consonants = ''.join(c for c in name_clean if c not in 'aeiou')
first_consonants = ''.join(c for c in first_name if c not in 'aeiou')
if name_consonants and first_consonants:
consonant_score = difflib.SequenceMatcher(None, name_consonants, first_consonants).ratio()
scores.append(("consonants", consonant_score * 0.8))
best_score = max(s[1] for s in scores) if scores else 0.0
scored_friends.append((friend, best_score))
# Debug logging - show top 3 scoring methods
top_scores = sorted(scores, key=lambda x: x[1], reverse=True)[:3]
log(f" '{first_name}': {best_score:.3f} ({', '.join(f'{m}={v:.2f}' for m,v in top_scores)})")
# Sort by score descending
scored_friends.sort(key=lambda x: x[1], reverse=True)
best_match, best_score = scored_friends[0] if scored_friends else (None, 0.0)
top_candidates = [f for f, s in scored_friends[:3]]
log(f"FUZZY: Best match for '{name_clean}' = '{best_match.first_name if best_match else 'None'}' ({best_score:.3f}), threshold={threshold}")
if best_score >= threshold:
return best_match, best_score, top_candidates
else:
return None, best_score, top_candidates
def fuzzy_match_group(name: str, groups: List[SplitwiseGroup], threshold: float = 0.6) -> Tuple[Optional[SplitwiseGroup], float]:
"""Fuzzy match a group name against the groups list."""
if not groups:
return None, 0.0
name_lower = name.lower().strip()
best_match = None
best_score = 0.0
for group in groups:
group_name_lower = group.name.lower()
score = difflib.SequenceMatcher(None, name_lower, group_name_lower).ratio()
# Boost score if input is substring
if name_lower in group_name_lower or group_name_lower.startswith(name_lower):
score = max(score, 0.85)
if score > best_score:
best_score = score
best_match = group
if best_score >= threshold:
return best_match, best_score
return None, best_score
def parse_date(date_str: Optional[str]) -> datetime:
"""Parse various date formats into datetime object."""
if not date_str:
return datetime.utcnow()
date_str = date_str.strip().lower()
today = datetime.utcnow().date()
# Handle relative dates
if date_str in ("today", "now"):
return datetime.utcnow()
elif date_str == "yesterday":
return datetime.combine(today - timedelta(days=1), datetime.min.time())
# Try various date formats
formats = [
"%Y-%m-%d", # 2026-01-20
"%m/%d/%Y", # 01/20/2026
"%d/%m/%Y", # 20/01/2026
"%B %d, %Y", # January 20, 2026
"%b %d, %Y", # Jan 20, 2026
"%B %d %Y", # January 20 2026
"%b %d %Y", # Jan 20 2026
"%d %B %Y", # 20 January 2026
"%d %b %Y", # 20 Jan 2026
"%B %d", # January 20 (assume current year)
"%b %d", # Jan 20 (assume current year)
]
for fmt in formats:
try:
parsed = datetime.strptime(date_str, fmt)
# If year not in format, use current year
if "%Y" not in fmt:
parsed = parsed.replace(year=today.year)
return parsed
except ValueError:
continue
# Default to today if parsing fails
return datetime.utcnow()
def detect_currency(amount_str: str) -> Optional[str]:
"""Detect currency from amount string based on symbols or keywords."""
amount_lower = amount_str.lower().strip()
# Check for currency symbols and keywords
if "$" in amount_str or "dollar" in amount_lower or "usd" in amount_lower:
return "USD"
elif "€" in amount_str or "euro" in amount_lower or "eur" in amount_lower:
return "EUR"
elif "£" in amount_str or "pound" in amount_lower or "gbp" in amount_lower:
return "GBP"
elif "¥" in amount_str or "yen" in amount_lower or "jpy" in amount_lower:
return "JPY"
elif "₹" in amount_str or "rupee" in amount_lower or "inr" in amount_lower:
return "INR"
elif "cad" in amount_lower:
return "CAD"
elif "aud" in amount_lower:
return "AUD"
return None # No currency detected
def parse_amount(amount_str: str) -> Tuple[Decimal, Optional[str]]:
"""Parse amount string to Decimal and detect currency. Returns (amount, currency_code)."""
# Detect currency first
detected_currency = detect_currency(amount_str)
# Remove common currency symbols and whitespace
cleaned = amount_str.strip()
for symbol in ["$", "€", "£", "¥", "₹", "dollars", "dollar", "usd", "eur", "gbp", "inr", "jpy", "cad", "aud", "rupees", "rupee", "pounds", "euros"]:
cleaned = cleaned.lower().replace(symbol, "").strip()
try:
return Decimal(cleaned), detected_currency
except:
raise ValueError(f"Invalid amount: {amount_str}")
def compute_equal_shares(total: Decimal, num_people: int) -> List[Decimal]:
"""
Compute equal shares for splitting, handling rounding properly.
Returns a list of shares that sum exactly to total.
"""
# Round to 2 decimal places
base_share = (total / num_people).quantize(Decimal("0.01"), rounding=ROUND_DOWN)
remainder = total - (base_share * num_people)
# Distribute remainder cents to first N people
remainder_cents = int(remainder * 100)
shares = []
for i in range(num_people):
share = base_share
if i < remainder_cents:
share += Decimal("0.01")
shares.append(share)
return shares
# ============================================
# 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_splitwise_tokens(uid)
authenticated = tokens is not None
user_info = None
if authenticated:
user_info = get_current_user(uid)
return templates.TemplateResponse("setup.html", {
"request": request,
"uid": uid,
"authenticated": authenticated,
"user_info": user_info,
})
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "healthy", "service": "splitwise-omi"}
@app.get("/auth/splitwise")
async def splitwise_auth(uid: str):
"""Initiate Splitwise OAuth2 flow."""
if not uid:
raise HTTPException(status_code=400, detail="User ID is required")
if not SPLITWISE_CONSUMER_KEY or not SPLITWISE_CONSUMER_SECRET:
raise HTTPException(status_code=500, detail="Splitwise credentials not configured")
# Create Splitwise instance and get OAuth2 authorize URL
s = Splitwise(SPLITWISE_CONSUMER_KEY, SPLITWISE_CONSUMER_SECRET)
url, state = s.getOAuth2AuthorizeURL(SPLITWISE_REDIRECT_URI)
# Store state for CSRF verification, encode uid in state
combined_state = f"{uid}:{state}"
store_oauth_state(uid, combined_state)
# Modify URL to use our combined state
# The SDK generates a random state, but we need to include uid
# So we'll use our own state parameter
import urllib.parse
parsed = urllib.parse.urlparse(url)
query_params = urllib.parse.parse_qs(parsed.query)
query_params["state"] = [combined_state]
new_query = urllib.parse.urlencode(query_params, doseq=True)
auth_url = urllib.parse.urlunparse(parsed._replace(query=new_query))
return RedirectResponse(url=auth_url)
@app.get("/auth/splitwise/callback")
async def splitwise_callback(request: Request, code: Optional[str] = None, state: Optional[str] = None, error: Optional[str] = None):
"""Handle Splitwise OAuth2 callback."""
if error:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": f"Authorization failed: {error}"
})
if not code or not state:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Invalid callback parameters"
})
# Extract uid from state
try:
uid, original_state = state.split(":", 1)
except ValueError:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "Invalid state parameter"
})
# Verify state matches what we stored
stored_state = get_oauth_state(uid)
if stored_state != state:
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": "State mismatch - possible CSRF attack"
})
# Clean up state
delete_oauth_state(uid)
# Exchange code for access token
try:
print(f"DEBUG: Exchanging code for token")
print(f"DEBUG: SPLITWISE_REDIRECT_URI = {SPLITWISE_REDIRECT_URI}")
print(f"DEBUG: code = {code[:10]}...")
s = Splitwise(SPLITWISE_CONSUMER_KEY, SPLITWISE_CONSUMER_SECRET)
token_response = s.getOAuth2AccessToken(code, SPLITWISE_REDIRECT_URI)
print(f"DEBUG: Token response received")
# Store token (full dict including token_type)
store_splitwise_tokens(
uid,
token_response["access_token"],
token_response.get("token_type", "Bearer")
)
# Redirect to home with uid
return RedirectResponse(url=f"/?uid={uid}")
except Exception as e:
print(f"OAuth error: {e}")
print(f"DEBUG: SPLITWISE_REDIRECT_URI was: {SPLITWISE_REDIRECT_URI}")
return templates.TemplateResponse("setup.html", {
"request": request,
"authenticated": False,
"error": f"Failed to exchange authorization code: {str(e)}"
})
@app.get("/setup/splitwise", tags=["setup"])
async def check_setup(uid: str):
"""Check if the user has completed Splitwise setup (used by Omi)."""
tokens = get_splitwise_tokens(uid)
return {"is_setup_completed": tokens is not None}
@app.get("/disconnect")
async def disconnect_splitwise(uid: str):
"""Disconnect Splitwise account."""
delete_splitwise_tokens(uid)
return RedirectResponse(url=f"/?uid={uid}")
# ============================================
# Chat Tool Endpoints
# ============================================
@app.post("/tools/create_expense", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_create_expense(request: Request):
"""
Create a Splitwise expense.
Chat tool for Omi - creates an expense split among specified friends.
"""
try:
body = await request.json()
log(f"=== CREATE_EXPENSE START ===")
log(f"Request: {body}")
uid = body.get("uid")
amount_str = body.get("amount", "")
description = body.get("description", "Expense")
date_str = body.get("date")
person = body.get("person")
people = body.get("people", [])
group_name = body.get("group")
currency_code = body.get("currency_code")
details = body.get("details")
log(f"Parsed: uid={uid}, amount={amount_str}, person={person}, people={people}")
if not uid:
log("ERROR: Missing uid")
return ChatToolResponse(error="User ID is required")
if not amount_str:
log("ERROR: Missing amount")
return ChatToolResponse(error="Amount is required")
# Check authentication
log("Getting Splitwise client...")
client = get_splitwise_client(uid)
if not client:
log("ERROR: No client - not authenticated")
return ChatToolResponse(error="Please connect your Splitwise account first in the app settings.")
log("Client OK")
# Get current user
log("Getting current user...")
current_user = get_current_user(uid)
if not current_user:
log("ERROR: Could not get current user")
return ChatToolResponse(error="Could not get your Splitwise user info. Please reconnect your account.")
log(f"Current user: {current_user.first_name} (ID: {current_user.id})")
# Parse amount and detect currency
try:
amount, detected_currency = parse_amount(amount_str)
log(f"Amount: {amount}, detected currency: {detected_currency}")
if amount <= 0:
return ChatToolResponse(error="Amount must be greater than zero")
except ValueError as e:
log(f"ERROR: Invalid amount - {e}")
return ChatToolResponse(error=str(e))
# Parse date
expense_date = parse_date(date_str)
log(f"Date: {expense_date}")
# Normalize people list
friend_names = []
if person:
friend_names.append(person)
if people:
friend_names.extend(people)
log(f"Friend names to match: {friend_names}")
if not friend_names:
log("ERROR: No friends specified")
return ChatToolResponse(error="Please specify at least one person to split with (e.g., 'with John' or 'with Alice and Bob')")
# Get friends list and match names
log("Fetching friends list...")
friends = get_friends_list(uid)
if not friends:
log("ERROR: No friends returned")
return ChatToolResponse(error="Could not fetch your friends list. Please make sure you have friends on Splitwise.")
log(f"Got {len(friends)} friends")
# Log available friends for debugging
log(f"FRIENDS: {len(friends)} available: {[f'{f.first_name}' for f in friends]}")
matched_friends = []
for name in friend_names:
match, confidence, candidates = fuzzy_match_friend(name, friends)
if not match:
log(f"MATCH FAILED: '{name}' -> no match above threshold")
candidate_names = [f"{c.first_name} {c.last_name or ''}".strip() for c in candidates[:3]]
if candidate_names:
return ChatToolResponse(
error=f"Could not find friend '{name}'. Did you mean: {', '.join(candidate_names)}?"
)
else:
return ChatToolResponse(error=f"Could not find friend '{name}' in your Splitwise friends list.")
log(f"MATCH SUCCESS: '{name}' -> '{match.first_name} {match.last_name or ''}' (ID: {match.id}, score: {confidence:.2f})")
matched_friends.append(match)
log(f"MATCHED: {[f'{f.first_name} (ID:{f.id})' for f in matched_friends]}")
# Check for duplicate friends
friend_ids = [f.id for f in matched_friends]
if len(friend_ids) != len(set(friend_ids)):
return ChatToolResponse(error="Duplicate friends detected. Please specify each person only once.")
# Resolve group if specified
group_id = 0 # 0 = non-group expense
group_info = None
if group_name:
groups = get_groups_list(uid)
group_match, group_confidence = fuzzy_match_group(group_name, groups)
if not group_match:
group_names = [g.name for g in groups[:5]]
if group_names:
return ChatToolResponse(
error=f"Could not find group '{group_name}'. Your groups: {', '.join(group_names)}"
)
else:
return ChatToolResponse(error=f"Could not find group '{group_name}'. You don't have any groups.")
group_id = group_match.id
group_info = group_match
# Calculate equal shares (you + all friends)
total_people = 1 + len(matched_friends) # current user + friends
shares = compute_equal_shares(amount, total_people)
# Build expense
expense = Expense()
expense.setCost(str(amount))
expense.setDescription(description)
expense.setDate(expense_date.strftime("%Y-%m-%dT%H:%M:%SZ"))
expense.setGroupId(group_id)
# Set currency: explicit param > detected from amount > user default
if currency_code:
expense.setCurrencyCode(currency_code)
elif detected_currency:
expense.setCurrencyCode(detected_currency)
elif current_user.default_currency:
expense.setCurrencyCode(current_user.default_currency)
if details:
expense.setDetails(details)
# Build users list - current user paid full amount, everyone owes their share
users = []
# Current user (payer)
payer = ExpenseUser()
payer.setId(current_user.id)
payer.setPaidShare(str(amount)) # Paid full amount
payer.setOwedShare(str(shares[0])) # Owes their share
users.append(payer)
# Friends (owe their shares)
for i, friend in enumerate(matched_friends):
eu = ExpenseUser()
eu.setId(friend.id)
eu.setPaidShare("0.00")
eu.setOwedShare(str(shares[i + 1]))
users.append(eu)
expense.setUsers(users)
# Determine which currency was used
used_currency = currency_code or detected_currency or current_user.default_currency or "USD"
# Log full expense details before creating
participants_str = ", ".join([f"{current_user.first_name}(paid={amount},owes={shares[0]})"] +
[f"{matched_friends[i].first_name}(paid=0,owes={shares[i+1]})" for i in range(len(matched_friends))])
log(f"CREATING: '{description}' {used_currency} {amount} | date={expense_date.strftime('%Y-%m-%d')} | group={group_id} | {participants_str}")
created_expense, errors = client.createExpense(expense)
if errors:
error_msg = str(errors)
log(f"ERROR: Splitwise API error: {error_msg}")
return ChatToolResponse(error=f"Failed to create expense: {error_msg}")
# Log success
expense_id = created_expense.getId() if created_expense else "unknown"
log(f"SUCCESS: Expense ID {expense_id} created!")
# Format success message
friend_names_str = ", ".join([f"{f.first_name} {f.last_name or ''}".strip() for f in matched_friends])
share_amount = shares[1] if len(shares) > 1 else shares[0]
currency_symbol = {"USD": "$", "EUR": "€", "GBP": "£", "INR": "₹", "JPY": "¥"}.get(used_currency, used_currency + " ")
result_parts = [
f"**Expense Created!**",
f"",
f"**{description}** - {currency_symbol}{amount}",
f"Split with: {friend_names_str}",
f"Each person owes: {currency_symbol}{share_amount}",
]
if group_info:
result_parts.append(f"Group: {group_info.name}")
result_parts.append(f"Date: {expense_date.strftime('%B %d, %Y')}")
return ChatToolResponse(result="\n".join(result_parts))
except Exception as e:
import traceback
log(f"EXCEPTION: {e}")
log(traceback.format_exc())
return ChatToolResponse(error=f"Failed to create expense: {str(e)}")
@app.post("/tools/get_friends", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_get_friends(request: Request):
"""
Get the user's Splitwise friends list.
"""
try:
body = await request.json()
uid = body.get("uid")
if not uid:
return ChatToolResponse(error="User ID is required")
client = get_splitwise_client(uid)
if not client:
return ChatToolResponse(error="Please connect your Splitwise account first in the app settings.")
friends = get_friends_list(uid)
if not friends:
return ChatToolResponse(result="You don't have any friends on Splitwise yet.")
# Format friends list
result_parts = [f"**Your Splitwise Friends ({len(friends)})**", ""]
for i, friend in enumerate(friends, 1):
name = f"{friend.first_name} {friend.last_name or ''}".strip()
email_str = f" ({friend.email})" if friend.email else ""
result_parts.append(f"{i}. {name}{email_str}")
return ChatToolResponse(result="\n".join(result_parts))
except Exception as e:
print(f"Error getting friends: {e}")
return ChatToolResponse(error=f"Failed to get friends: {str(e)}")
@app.post("/tools/list_expenses", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_list_expenses(request: Request):
"""
List recent Splitwise expenses.
"""
try:
body = await request.json()
uid = body.get("uid")
limit = body.get("limit", 10)
group_name = body.get("group")
if not uid:
return ChatToolResponse(error="User ID is required")
client = get_splitwise_client(uid)
if not client:
return ChatToolResponse(error="Please connect your Splitwise account first in the app settings.")
# Get group_id if group name specified
group_id = None
if group_name:
groups = get_groups_list(uid)
group_match, _ = fuzzy_match_group(group_name, groups)
if group_match:
group_id = group_match.id
# Fetch expenses
if group_id:
expenses = client.getExpenses(group_id=group_id, limit=limit)
else:
expenses = client.getExpenses(limit=limit)
if not expenses:
return ChatToolResponse(result="No expenses found.")
# Format expenses list
result_parts = [f"**Recent Expenses ({len(expenses)})**", ""]
for exp in expenses:
desc = exp.getDescription() or "No description"
cost = exp.getCost()
currency = exp.getCurrencyCode() or "USD"
date = exp.getDate()
exp_id = exp.getId()
# Parse date
try:
date_obj = datetime.fromisoformat(date.replace('Z', '+00:00'))
date_str = date_obj.strftime("%b %d, %Y")
except:
date_str = date
result_parts.append(f"• **{desc}** - {currency} {cost} ({date_str}) [ID: {exp_id}]")
return ChatToolResponse(result="\n".join(result_parts))
except Exception as e:
print(f"Error listing expenses: {e}")
return ChatToolResponse(error=f"Failed to list expenses: {str(e)}")
@app.post("/tools/delete_expense", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_delete_expense(request: Request):
"""
Delete a Splitwise expense.
"""
try:
body = await request.json()
uid = body.get("uid")
expense_id = body.get("expense_id")
if not uid:
return ChatToolResponse(error="User ID is required")
if not expense_id:
return ChatToolResponse(error="Expense ID is required. Use 'list expenses' to find expense IDs.")
client = get_splitwise_client(uid)
if not client:
return ChatToolResponse(error="Please connect your Splitwise account first in the app settings.")
# Get expense details first for confirmation message
try:
expense = client.getExpense(expense_id)
desc = expense.getDescription() or "Expense"
cost = expense.getCost()
except:
desc = "Expense"
cost = "unknown"
# Delete expense
success, errors = client.deleteExpense(expense_id)
if errors:
return ChatToolResponse(error=f"Failed to delete expense: {errors}")
return ChatToolResponse(result=f"**Expense Deleted**\n\nDeleted: {desc} (${cost})")
except Exception as e:
print(f"Error deleting expense: {e}")
return ChatToolResponse(error=f"Failed to delete expense: {str(e)}")
@app.post("/tools/update_expense", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_update_expense(request: Request):
"""
Update a Splitwise expense.
"""
try:
body = await request.json()
uid = body.get("uid")
expense_id = body.get("expense_id")
new_description = body.get("description")
new_cost = body.get("cost")
new_date = body.get("date")
if not uid:
return ChatToolResponse(error="User ID is required")
if not expense_id:
return ChatToolResponse(error="Expense ID is required. Use 'list expenses' to find expense IDs.")
client = get_splitwise_client(uid)
if not client:
return ChatToolResponse(error="Please connect your Splitwise account first in the app settings.")
# Get existing expense
try:
expense = client.getExpense(expense_id)
except Exception as e:
return ChatToolResponse(error=f"Could not find expense with ID {expense_id}")
# Update fields
updates = []
if new_description:
expense.setDescription(new_description)
updates.append(f"Description: {new_description}")
if new_cost:
try:
cost_decimal, _ = parse_amount(new_cost)
expense.setCost(str(cost_decimal))
updates.append(f"Cost: ${cost_decimal}")
except:
return ChatToolResponse(error=f"Invalid cost: {new_cost}")
if new_date:
parsed_date = parse_date(new_date)
expense.setDate(parsed_date.strftime("%Y-%m-%dT%H:%M:%SZ"))
updates.append(f"Date: {parsed_date.strftime('%B %d, %Y')}")
if not updates:
return ChatToolResponse(error="No updates specified. Provide description, cost, or date to update.")
# Save updates
updated_expense, errors = client.updateExpense(expense)
if errors:
return ChatToolResponse(error=f"Failed to update expense: {errors}")
result_parts = ["**Expense Updated**", ""] + updates
return ChatToolResponse(result="\n".join(result_parts))
except Exception as e:
print(f"Error updating expense: {e}")
return ChatToolResponse(error=f"Failed to update expense: {str(e)}")
@app.post("/tools/get_expense_details", tags=["chat_tools"], response_model=ChatToolResponse)
async def tool_get_expense_details(request: Request):
"""
Get details of a Splitwise expense including participants.
"""
try:
body = await request.json()
uid = body.get("uid")
expense_id = body.get("expense_id")
if not uid:
return ChatToolResponse(error="User ID is required")
if not expense_id:
return ChatToolResponse(error="Expense ID is required. Use 'list expenses' to find expense IDs.")
client = get_splitwise_client(uid)
if not client:
return ChatToolResponse(error="Please connect your Splitwise account first in the app settings.")
try:
expense = client.getExpense(expense_id)
except Exception as e:
return ChatToolResponse(error=f"Could not find expense with ID {expense_id}")
desc = expense.getDescription() or "Expense"
cost = expense.getCost()
currency = expense.getCurrencyCode() or "USD"
date = expense.getDate()
# Parse date
try:
date_obj = datetime.fromisoformat(date.replace('Z', '+00:00'))
date_str = date_obj.strftime("%B %d, %Y")
except:
date_str = date
result_parts = [
f"**{desc}**",
"",
f"**Amount:** {currency} {cost}",
f"**Date:** {date_str}",
""
]
# Get participants
users = expense.getUsers()
if users:
result_parts.append("**Participants:**")
for user in users:
name = f"{user.getFirstName()} {user.getLastName() or ''}".strip()
paid = user.getPaidShare() or "0"