-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitwise
More file actions
executable file
·853 lines (702 loc) · 29.5 KB
/
splitwise
File metadata and controls
executable file
·853 lines (702 loc) · 29.5 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
#!/usr/bin/env python3
"""
Splitwise CLI - Manage Splitwise expenses from command line
Usage:
splitwise user # Show current user
splitwise groups # List all groups
splitwise groups show <name> # Show group details
splitwise expenses <group> # List expenses in group
splitwise add <desc> <amount> # Add expense
splitwise delete <id> # Show expense details
splitwise delete <id> --yes # Delete expense (requires --yes)
splitwise search <text> # Search expenses
"""
import sys
import argparse
import json
from pathlib import Path
# Determine the base directory (where this script lives)
BASE_DIR = Path(__file__).resolve().parent
SCRIPTS_DIR = BASE_DIR / 'scripts'
# Add scripts to path
sys.path.insert(0, str(SCRIPTS_DIR))
# Also load .env file
from dotenv import load_dotenv
load_dotenv(BASE_DIR / '.env')
from splitwise_api import (
get_current_user,
get_groups,
get_group,
get_group_members,
find_group_by_name,
find_member_by_name,
get_expenses,
create_expense,
delete_expense,
api_get,
api_post,
get_auth_url,
exchange_verifier,
save_auth_token,
clear_auth_token,
is_authenticated
)
# Colors for output
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BLUE = '\033[94m'
BOLD = '\033[1m'
RESET = '\033[0m'
def print_user():
"""Show current user info"""
user = get_current_user().get('user', {})
print(f"\n{BOLD}👤 Current User{RESET}")
print(f" Name: {user.get('first_name')} {user.get('last_name')}")
print(f" Email: {user.get('email')}")
print(f" ID: {user.get('id')}")
print(f" Default Currency: {user.get('default_currency', 'N/A')}")
print(f" Country: {user.get('country_code', 'N/A')}")
print()
def print_groups():
"""List all groups"""
data = get_groups()
groups = data.get('groups', [])
print(f"\n{BOLD}📁 Groups ({len(groups)}){RESET}")
print("-" * 50)
for g in groups:
members = g.get('members', [])
member_names = [m.get('first_name', '') for m in members[:3]]
extra = f" (+{len(members)-3} more)" if len(members) > 3 else ""
print(f" [{g.get('id')}] {g.get('name')}")
print(f" Members: {', '.join(member_names)}{extra}")
print()
def show_group(name):
"""Show details of a specific group"""
groups = find_group_by_name(name)
if not groups:
print(f"{RED}❌ No group found matching '{name}'{RESET}")
return
if len(groups) > 1:
print(f"{YELLOW}⚠️ Multiple matches:{RESET}")
for g in groups:
print(f" [{g.get('id')}] {g.get('name')}")
return
g = groups[0]
group_id = g.get('id')
group = get_group(group_id)
print(f"\n{BOLD}📁 {group.get('name')}{RESET} (ID: {group_id})")
print(f" Created: {group.get('created_at', '')[:10]}")
print(f"\n {BOLD}Members ({len(group.get('members', []))}):{RESET}")
for m in group.get('members', []):
name_str = f"{m.get('first_name', '')} {m.get('last_name', '')}".strip()
print(f" [{m.get('id')}] {name_str}")
# Show balances
balances = []
for m in group.get('members', []):
for b in m.get('balance', []):
amount = float(b.get('amount', 0))
if amount != 0:
currency = b.get('currency_code', 'INR')
sign = '+' if amount > 0 else ''
balances.append(f"{m.get('first_name', '')}: {sign}{amount} {currency}")
if balances:
print(f"\n {BOLD}💰 Balances:{RESET}")
for b in balances:
print(f" {b}")
print()
def list_expenses(group_name, limit=20):
"""List expenses in a group"""
if not group_name:
# Show all non-group expenses
expenses = get_expenses(group_id=0, limit=limit)
group_name = "Non-group expenses"
else:
groups = find_group_by_name(group_name)
if not groups:
print(f"{RED}❌ No group found matching '{group_name}'{RESET}")
return
group_id = groups[0].get('id')
group_name = groups[0].get('name')
expenses = get_expenses(group_id=group_id, limit=limit)
print(f"\n{BOLD}📋 Expenses in {group_name}{RESET} (showing {len(expenses)} recent)")
print("-" * 60)
if not expenses:
print(" No expenses found.")
print()
return
for e in expenses:
date = e.get('date', '')[:10]
desc = e.get('description', 'N/A')
cost = e.get('cost', '0')
currency = e.get('currency_code', '₹')
print(f"\n [{e.get('id')}] {date}")
print(f" {desc}")
print(f" {currency}{cost}")
# Show who paid and split
users = e.get('users', [])
if users:
payer = None
for u in users:
if float(u.get('paid_share', 0)) > 0:
payer = u['user'].get('first_name', '')
if payer:
print(f" Paid by: {payer}")
print()
def add_expense(args):
"""Add a new expense"""
# Find group
groups = find_group_by_name(args.group)
if not groups:
print(f"{RED}❌ No group found matching '{args.group}'{RESET}")
return
group_id = groups[0].get('id')
group_name = groups[0].get('name')
# Get current user
user = get_current_user().get('user', {})
user_id = user.get('id')
user_name = f"{user.get('first_name')} {user.get('last_name')}"
# Determine who paid
payer_id = user_id
payer_name = user_name
if args.paid_by:
matches = find_member_by_name(group_id, args.paid_by)
if matches:
payer_id = matches[0].get('id')
payer_name = f"{matches[0].get('first_name')} {matches[0].get('last_name')}"
# Determine split participants
split_user_ids = [payer_id]
split_names = [payer_name]
if args.split_with:
for name in args.split_with:
matches = find_member_by_name(group_id, name)
if matches:
member_id = matches[0].get('id')
member_name = f"{matches[0].get('first_name')} {matches[0].get('last_name')}"
if member_id not in split_user_ids:
split_user_ids.append(member_id)
split_names.append(member_name)
else:
print(f"{YELLOW}⚠️ Member '{name}' not found in group{RESET}")
# Handle different split types
split_type = args.type
# If --user was used, skip to exact split creation
if args.user:
split_type = 'exact'
# Build expense with custom user splits
currency = args.currency or 'INR'
flat_users = {}
for i, uid in enumerate(split_user_ids):
paid, owed = split_ratios[uid]
flat_users[f'users__{i}__user_id'] = uid
flat_users[f'users__{i}__paid_share'] = str(paid)
flat_users[f'users__{i}__owed_share'] = str(owed)
data = {
'group_id': group_id,
'cost': str(args.amount),
'description': args.description,
'currency_code': currency,
**flat_users
}
if args.date:
data['date'] = args.date
result = api_post('create_expense', data)
expense = result.get('expenses', [{}])[0] if result.get('expenses') else None
elif split_type == 'exact' and args.amounts:
# Custom exact amounts - order is: payer first, then --split-with names
split_ratios = {}
for i, uid in enumerate(split_user_ids):
if i < len(args.amounts):
owed = args.amounts[i]
paid = args.amount if uid == payer_id else 0
split_ratios[uid] = (paid, owed)
currency = args.currency or 'INR'
flat_users = {}
for i, uid in enumerate(split_user_ids):
paid, owed = split_ratios[uid]
flat_users[f'users__{i}__user_id'] = uid
flat_users[f'users__{i}__paid_share'] = str(paid)
flat_users[f'users__{i}__owed_share'] = str(owed)
data = {
'group_id': group_id,
'cost': str(args.amount),
'description': args.description,
'currency_code': currency,
**flat_users
}
if args.date:
data['date'] = args.date
result = api_post('create_expense', data)
expense = result.get('expenses', [{}])[0] if result.get('expenses') else None
elif split_type == 'equal':
expense = create_expense(
group_id=group_id,
description=args.description,
cost=args.amount,
paid_by_user_id=payer_id,
split_type='equal',
split_with_user_ids=split_user_ids,
date=args.date,
currency=args.currency or 'INR'
)
else:
# Default to equal
expense = create_expense(
group_id=group_id,
description=args.description,
cost=args.amount,
paid_by_user_id=payer_id,
split_type='equal',
split_with_user_ids=split_user_ids,
date=args.date,
currency=args.currency or 'INR'
)
if expense:
print(f"\n{GREEN}✅ Expense Added!{RESET}")
print(f" Group: {group_name}")
print(f" Description: {expense.get('description')}")
print(f" Amount: ₹{expense.get('cost')}")
print(f" Date: {args.date or 'today'}")
print(f" Paid by: {payer_name}")
print(f" Split: {split_type}")
if args.amounts:
print(f" Custom amounts: {args.amounts}")
# Show individual shares
for u in expense.get('users', []):
owed = float(u.get('owed_share', 0))
net = float(u.get('net_balance', 0))
name = u['user'].get('first_name', '')
if net > 0:
print(f" {name}: gets ₹{net}")
elif net < 0:
print(f" {name}: owes ₹{abs(net)}")
else:
print(f"{RED}❌ Failed to create expense{RESET}")
print()
def show_expense(expense_id):
"""Show expense details"""
result = api_get(f'get_expense/{expense_id}')
expense = result.get('expense')
if not expense or expense.get('deleted_at'):
print(f"{RED}❌ Expense {expense_id} not found or deleted{RESET}")
return
print(f"\n{BOLD}📋 Expense Details{RESET}")
print("-" * 40)
print(f" ID: {expense.get('id')}")
print(f" Description: {expense.get('description')}")
print(f" Amount: ₹{expense.get('cost')}")
print(f" Date: {expense.get('date', '')[:10]}")
print(f" Group ID: {expense.get('group_id')}")
print(f" Category: {expense.get('category', {}).get('name', 'N/A')}")
print(f"\n {BOLD}Split:{RESET}")
for u in expense.get('users', []):
name = u['user'].get('first_name', '')
paid = float(u.get('paid_share', 0))
owed = float(u.get('owed_share', 0))
net = float(u.get('net_balance', 0))
net_str = f"+₹{net:.2f}" if net > 0 else f"-₹{abs(net):.2f}"
print(f" {name}: paid ₹{paid:.2f}, owes ₹{owed:.2f} ({net_str})")
print(f"\n 💡 To delete: splitwise delete {expense_id} --yes")
print()
def delete_expense(expense_id, force=False):
"""Delete an expense"""
# First show what will be deleted
result = api_get(f'get_expense/{expense_id}')
expense = result.get('expense')
if not expense or expense.get('deleted_at'):
print(f"{RED}❌ Expense {expense_id} not found or already deleted{RESET}")
return
print(f"\n{RED}⚠️ About to DELETE:{RESET}")
print(f" Description: {expense.get('description')}")
print(f" Amount: ₹{expense.get('cost')}")
print(f" Date: {expense.get('date', '')[:10]}")
print(f" ID: {expense_id}")
if not force:
print(f"\n This action cannot be undone!")
print(f" Use {BOLD}--yes{RESET} flag to confirm deletion.")
return
# force=True: proceed with deletion
from splitwise_api import delete_expense as api_delete
result = api_delete(expense_id)
if result.get('success'):
print(f"\n{GREEN}✅ Deleted successfully!{RESET}")
else:
print(f"{RED}❌ Failed to delete: {result}{RESET}")
def search_expenses(text, group_name=None, limit=20):
"""Search expenses"""
if group_name:
groups = find_group_by_name(group_name)
if not groups:
print(f"{RED}❌ No group found matching '{group_name}'{RESET}")
return
group_id = groups[0].get('id')
group_name = groups[0].get('name')
expenses = get_expenses(group_id=group_id, limit=limit)
else:
expenses = get_expenses(limit=limit)
group_name = "all groups"
matches = [e for e in expenses if text.lower() in e.get('description', '').lower()]
print(f"\n{BOLD}🔍 Search results for '{text}' in {group_name}{RESET}")
print("-" * 60)
if not matches:
print(" No matches found.")
else:
for e in matches:
date = e.get('date', '')[:10]
print(f" [{e.get('id')}] {date} | {e.get('description')} | ₹{e.get('cost')}")
print(f"\n 💡 To view details: splitwise show {matches[0].get('id') if matches else '<id>'}")
print()
def show_balances(group_name=None):
"""Show who owes whom"""
if group_name:
groups = find_group_by_name(group_name)
if not groups:
print(f"{RED}❌ No group found matching '{group_name}'{RESET}")
return
group_id = groups[0].get('id')
group_name = groups[0].get('name')
group = get_group(group_id)
print(f"\n{BOLD}💰 Balances in {group_name}{RESET}")
print("-" * 50)
debts = group.get('simplified_debts', [])
if not debts:
print(" All settled up! 🎉")
else:
members = {m['id']: m for m in group.get('members', [])}
for debt in debts:
from_id = debt.get('from')
to_id = debt.get('to')
amount = float(debt.get('amount', 0))
from_name = members.get(from_id, {}).get('first_name', f'User {from_id}')
to_name = members.get(to_id, {}).get('first_name', f'User {to_id}')
print(f" {from_name} → {to_name}: ₹{amount:.2f}")
print()
else:
print(f"\n{BOLD}💰 All Balances{RESET}")
print("-" * 50)
friends_result = api_get('get_friends')
friends = friends_result.get('friends', [])
total_owed = 0
total_owing = 0
for f in friends:
balances = f.get('balance', [])
for b in balances:
amount = float(b.get('amount', 0))
currency = b.get('currency_code', '')
if amount > 0:
print(f" {f.get('first_name')} owes you: ₹{abs(amount):.2f}")
total_owed += amount
elif amount < 0:
print(f" You owe {f.get('first_name')}: ₹{abs(amount):.2f}")
total_owing += abs(amount)
print(f"\n {BOLD}Summary:{RESET}")
print(f" You are owed: ₹{total_owed:.2f}")
print(f" You owe: ₹{total_owing:.2f}")
print(f" Net: ₹{total_owed - total_owing:.2f}")
print()
def show_currencies():
"""List supported currencies"""
result = api_get('get_currencies')
currencies = result.get('currencies', [])
print(f"\n{BOLD}💱 Supported Currencies ({len(currencies)}){RESET}")
print("-" * 40)
for c in currencies[:30]:
code = c.get('currency_code', '')
symbol = c.get('symbol', '')
name = c.get('name', '')
print(f" {code} {symbol} - {name}")
if len(currencies) > 30:
print(f" ... and {len(currencies) - 30} more")
print()
def show_categories():
"""List expense categories"""
result = api_get('get_categories')
categories = result.get('categories', [])
print(f"\n{BOLD}📂 Expense Categories{RESET}")
print("-" * 50)
def print_category(cat, indent=0):
name = cat.get('name', '')
cat_id = cat.get('id', '')
subcats = cat.get('subcategories', [])
prefix = " " * indent
print(f"{prefix}[{cat_id}] {name}")
for sub in subcats:
print_category(sub, indent + 1)
for cat in categories:
print_category(cat)
print()
def show_friends():
"""List all friends"""
result = api_get('get_friends')
friends = result.get('friends', [])
print(f"\n{BOLD}👥 Friends ({len(friends)}){RESET}")
print("-" * 50)
if not friends:
print(" No friends found.")
else:
for f in friends:
name = f"{f.get('first_name', '')} {f.get('last_name', '')}".strip()
fid = f.get('id')
balances = f.get('balance', [])
balance_str = ""
for b in balances:
amount = float(b.get('amount', 0))
if amount > 0:
balance_str = f" → owes you ₹{abs(amount):.2f}"
elif amount < 0:
balance_str = f" → you owe ₹{abs(amount):.2f}"
print(f" [{fid}] {name}{balance_str}")
print()
def show_comments(expense_id):
"""Show comments on an expense"""
result = api_get(f'get_expense/{expense_id}')
expense = result.get('expense')
if not expense:
print(f"{RED}❌ Expense {expense_id} not found{RESET}")
return
comments = expense.get('comments', [])
print(f"\n{BOLD}💬 Comments on '{expense.get('description')}'{RESET}")
print("-" * 50)
if not comments:
print(" No comments.")
else:
for c in comments:
author = c.get('user', {}).get('first_name', 'Unknown')
content = c.get('content', '')
date = c.get('created_at', '')[:10]
print(f" [{date}] {author}:")
print(f" {content}")
print()
def show_members(group_name=None):
"""List members of a group"""
if not group_name:
print(f"{RED}❌ Please specify a group: splitwise members 'Trip'{RESET}")
return
groups = find_group_by_name(group_name)
if not groups:
print(f"{RED}❌ No group found matching '{group_name}'{RESET}")
return
if len(groups) > 1:
print(f"{YELLOW}⚠️ Multiple groups match '{group_name}':{RESET}")
for g in groups:
print(f" [{g.get('id')}] {g.get('name')}")
return
group = get_group(groups[0]['id'])
members = group.get('members', [])
print(f"\n{BOLD}👥 Members in {group.get('name')}{RESET} ({len(members)} total)")
print("-" * 50)
for m in members:
name = f"{m.get('first_name', '')} {m.get('last_name', '')}".strip()
mid = m.get('id')
balance = m.get('balance', [])
balance_str = ""
for b in balance:
amount = float(b.get('amount', 0))
currency = b.get('currency_code', 'INR')
if amount > 0:
balance_str = f" → {currency}{abs(amount):.2f} owed to them"
elif amount < 0:
balance_str = f" → owes {currency}{abs(amount):.2f}"
print(f" [{mid}] {name}{balance_str}")
print()
def main():
parser = argparse.ArgumentParser(
description=f"{BOLD}Splitwise CLI{RESET} - Manage expenses from command line",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=f"""
Examples:
{BOLD}# Show info
splitwise user{RESET} Show current user
{BOLD}splitwise groups{RESET} List all groups
{BOLD}splitwise members "MyGroup"{RESET} List group members
{BOLD}# Add expense - equal split (use name or ID)
splitwise add "Dinner" 500 --group "MyGroup"{RESET} Split equally
{BOLD}splitwise add "Coffee" 150 --group "MyGroup" --split-with "Friend"{RESET} Name or ID works!
{BOLD}# Add expense - custom amounts (who owes what)
splitwise add "Groceries" 1000 --group "MyGroup" \\
--split-with "Friend1" "Friend2" \\
--type exact --amounts 600 400{RESET}
# Friend1 owes 600, Friend2 owes 400
{BOLD}# Other commands
{BOLD}splitwise show 123456{RESET} Show expense details
{BOLD}splitwise delete 123456{RESET} Show delete confirmation
{BOLD}splitwise delete 123456 --yes{RESET} Actually delete
{BOLD}splitwise search "coffee"{RESET} Search expenses
"""
)
subparsers = parser.add_subparsers(dest='command', help='Commands')
# user command
subparsers.add_parser('user', help='Show current user')
# groups command
groups_parser = subparsers.add_parser('groups', help='List all groups')
groups_parser.add_argument('action', nargs='?', default='list',
choices=['list', 'show'], help='Action (default: list)')
groups_parser.add_argument('name', nargs='?', help='Group name to show')
# expenses command
exp_parser = subparsers.add_parser('expenses', help='List expenses in a group')
exp_parser.add_argument('group', nargs='?', help='Group name (optional)')
exp_parser.add_argument('-n', '--limit', type=int, default=20, help='Number to show')
# add command
add_parser = subparsers.add_parser('add', help='Add new expense')
add_parser.add_argument('description', help='Expense description')
add_parser.add_argument('amount', type=float, help='Total amount')
add_parser.add_argument('-g', '--group', default='Non-group expenses', help='Group name')
add_parser.add_argument('-s', '--split-with', nargs='+', help='Split with (names or IDs from members command)')
add_parser.add_argument('-p', '--paid-by', help='Who paid (default: you)')
add_parser.add_argument('-d', '--date', help='Date (YYYY-MM-DD)')
add_parser.add_argument('-c', '--currency', default='INR', help='Currency')
add_parser.add_argument('--type', choices=['equal', 'exact'],
default='equal', help='Split type (default: equal)')
add_parser.add_argument('--amounts', nargs='+', type=float,
help='Custom owed amounts (e.g., --amounts 250 150)')
# show command
show_parser = subparsers.add_parser('show', help='Show expense details')
show_parser.add_argument('expense_id', type=int, help='Expense ID')
# delete command
del_parser = subparsers.add_parser('delete', help='Delete expense')
del_parser.add_argument('expense_id', type=int, help='Expense ID')
del_parser.add_argument('--yes', action='store_true', help='Skip confirmation')
# search command
search_parser = subparsers.add_parser('search', help='Search expenses')
search_parser.add_argument('text', help='Search text')
search_parser.add_argument('-g', '--group', help='Group to search in')
search_parser.add_argument('-n', '--limit', type=int, default=20)
# balances command
bal_parser = subparsers.add_parser('balances', help='Show balances')
bal_parser.add_argument('group', nargs='?', help='Group name (optional)')
# currencies command
subparsers.add_parser('currencies', help='List supported currencies')
# categories command
subparsers.add_parser('categories', help='List expense categories')
# friends command
subparsers.add_parser('friends', help='List all friends')
# comments command
comments_parser = subparsers.add_parser('comments', help='Show expense comments')
comments_parser.add_argument('expense_id', type=int, help='Expense ID')
# members command
members_parser = subparsers.add_parser('members', help='List group members')
members_parser.add_argument('group', nargs='?', default='', help='Group name (optional)')
# auth command
auth_parser = subparsers.add_parser('auth', help='Authenticate with OAuth')
auth_parser.add_argument('verifier', nargs='?', help='OAuth verifier (from callback URL)')
# logout command
subparsers.add_parser('logout', help='Clear stored credentials (logout)')
args = parser.parse_args()
# Route commands
if not args.command or args.command == 'user':
print_user()
elif args.command == 'groups':
if args.action == 'show' and args.name:
show_group(args.name)
elif args.name:
show_group(args.name)
else:
print_groups()
elif args.command == 'expenses':
list_expenses(args.group, args.limit)
elif args.command == 'add':
add_expense(args)
elif args.command == 'show':
show_expense(args.expense_id)
elif args.command == 'delete':
delete_expense(args.expense_id, args.yes)
elif args.command == 'search':
search_expenses(args.text, args.group, args.limit)
elif args.command == 'balances':
show_balances(args.group)
elif args.command == 'currencies':
show_currencies()
elif args.command == 'categories':
show_categories()
elif args.command == 'friends':
show_friends()
elif args.command == 'comments':
show_comments(args.expense_id)
elif args.command == 'members':
show_members(args.group)
elif args.command == 'auth':
handle_auth(args.verifier)
elif args.command == 'logout':
handle_logout()
else:
parser.print_help()
def handle_auth(verifier=None):
"""
Handle OAuth authentication flow.
Step 1: No verifier -> Generate auth URL and save secret
Step 2: Verifier provided -> Exchange for access token and save to .env
"""
from urllib.parse import urlparse, parse_qs
# Path to store temporary OAuth data
auth_data_file = BASE_DIR / '.oauth_data'
if not verifier:
# Step 1: Generate authorization URL
print(f"\n{BOLD}🔐 Splitwise OAuth Authentication{RESET}")
print("-" * 50)
url, oauth_secret, oauth_token, error = get_auth_url()
if error:
print(f"{RED}❌ {error}{RESET}")
print(f"\n Make sure you have SPLITWISE_CONSUMER_KEY and")
print(f" SPLITWISE_CONSUMER_SECRET in your .env file")
return
# Save the OAuth data for later use
auth_data = {
'oauth_token': oauth_token,
'oauth_secret': oauth_secret
}
with open(auth_data_file, 'w') as f:
json.dump(auth_data, f)
print(f"\n{GREEN}✅ Authorization URL generated!{RESET}\n")
print(f" {BOLD}Step 1:{RESET} Copy and visit this URL in your browser:")
print(f"\n {BLUE}{url}{RESET}\n")
print(f" {BOLD}Step 2:{RESET} After authorizing, you'll be redirected to a callback")
print(f" page. Copy the 'oauth_verifier' parameter from the URL.")
print(f"\n {BOLD}Step 3:{RESET} Come back here and run:")
print(f"\n {BOLD} splitwise auth YOUR_OAUTH_VERIFIER{RESET}\n")
print(f" Example: splitwise auth Abc123Xyz456Def789")
else:
# Step 2: Exchange verifier for access token
print(f"\n{BOLD}🔐 Exchanging verifier for access token...{RESET}\n")
# Read the saved OAuth data
if not auth_data_file.exists():
print(f"{RED}❌ No pending authorization found.{RESET}")
print(f" Run {BOLD}'splitwise auth'{RESET} first to get the authorization URL.")
return
with open(auth_data_file, 'r') as f:
auth_data = json.load(f)
oauth_token = auth_data.get('oauth_token', '')
oauth_secret = auth_data.get('oauth_secret', '')
if not oauth_token or not oauth_secret:
print(f"{RED}❌ Invalid OAuth data. Run 'splitwise auth' again.{RESET}")
return
# Exchange for access token
access_token, error = exchange_verifier(oauth_token, oauth_secret, verifier)
if error:
print(f"{RED}❌ {error}{RESET}")
return
if access_token:
# Save to separate tokens file (replaces old tokens)
save_auth_token(access_token)
# Clean up temporary OAuth data
auth_data_file.unlink(missing_ok=True)
print(f"{GREEN}✅ Authentication successful!{RESET}")
print(f"\n Access token saved to .tokens.json")
print(f"\n {BOLD}You can now use splitwise commands!{RESET}")
print(f"\n Try: {BOLD}splitwise user{RESET} to verify")
else:
print(f"{RED}❌ Failed to get access token{RESET}")
def handle_logout():
"""Clear stored credentials (logout)"""
print(f"\n{BOLD}🔐 Logging out...{RESET}")
# Clear access tokens from .env
cleared = clear_auth_token()
# Clean up OAuth data file
auth_data_file = BASE_DIR / '.oauth_data'
auth_data_file.unlink(missing_ok=True)
if cleared:
print(f"\n{GREEN}✅ Logged out successfully!{RESET}")
print(f"\n To login again, run: {BOLD}splitwise auth{RESET}")
else:
print(f"{YELLOW}⚠️ No credentials found to clear.{RESET}")
if __name__ == '__main__':
main()