def friends(): if 'access_token' not in session: return redirect(url_for("home")) sObj = Splitwise(Config.consumer_key, Config.consumer_secret) sObj.setAccessToken(session['access_token']) friends = sObj.getFriends( ) #Get a list of friends object using Splitwise API friend_list = [] #Friends list bal_list = [] #Balance list # li = [] for friend in friends: friend_list.append(friend.getFirstName()) print(friend.getBalances()) print(len(friend.getBalances())) if len(friend.getBalances()) == 0: bal_list.append("0") else: for bal in friend.getBalances(): if len(bal.getAmount()) == 0: bal_list.append("0") else: bal_list.append(bal.getAmount()) output = {'friends': friend_list, 'balances': bal_list} return jsonify(output)
class GroupTestCase(unittest.TestCase): def setUp(self): consumer_key = os.environ['CONSUMER_KEY'] consumer_secret = os.environ['CONSUMER_SECRET'] oauth_token = os.environ['OAUTH_TOKEN'] oauth_token_secret = os.environ['OAUTH_TOKEN_SECRET'] self.sObj = Splitwise(consumer_key, consumer_secret) self.sObj.setAccessToken({ 'oauth_token': oauth_token, 'oauth_token_secret': oauth_token_secret }) def test_group_flow(self): group = Group() group.setName("Splitwise_test_case") # Create Group group, error = self.sObj.createGroup(group) self.assertIsNotNone(group.getId()) # Delete Group self.sObj.deleteGroup(group.getId()) def test_group_invalidkeys_fail(self): sObj = Splitwise('consumerkey', 'consumersecret', { "oauth_token": "sdsd", "oauth_token_secret": "sdsdd" }) group = Group() with self.assertRaises(SplitwiseUnauthorizedException): sObj.createGroup(group)
def friends(): wise = Splitwise('consumer_key', 'consumer_secret') wise.setAccessToken(session[KEY_ACCESS_TOKEN]) friend_names = [' '.join(filter(None, (f.first_name, f.last_name))) for f in wise.getFriends()] template = f"<ul>{''.join(f'<li>{name}</li>' for name in friend_names)}</ul>" return render_template_string(template)
def groups(): if 'access_token' not in session: return redirect(url_for("home")) sObj = Splitwise(Config.consumer_key, Config.consumer_secret) sObj.setAccessToken(session['access_token']) groups = sObj.getGroups() #Get a list of grpups object group_list = [] #group list bal_list = [] #Balance list for group in groups: group_list.append(group.getName()) print(group.getName()) group_bal = [] for debt in group.getSimplifiedDebts(): group_bal.append( (debt.getFromUser(), debt.getToUser(), debt.getAmount())) print(debt.getFromUser(), debt.getToUser(), debt.getAmount()) bal_list.append(group_bal) output = {'groups': group_list, 'balances': bal_list} return jsonify(output)
def authorize(path_to_auth = None): if path_to_auth == None: path_to_auth = 'auth.json' if os.path.isfile(path_to_auth): with open(path_to_auth) as json_file: auth = json.load(json_file) sObj = Splitwise(auth['consumer_key'],auth['consumer_secret'],auth['access_token']) else: print("No pre-existing authorization found. Creating new auth") auth = {} # Go to https://secure.splitwise.com/apps/new and register the app to get your consumer key and secret auth['consumer_key'] = input("Please enter your consumer key:\n") auth['consumer_secret'] = input("Please enter your consumer secret:\n") sObj = Splitwise(auth['consumer_key'],auth['consumer_secret']) url, auth['secret'] = sObj.getAuthorizeURL() print("Authroize via the following URL") print(url) auth['oauth_token'] = url.split("=")[1] auth['oauth_verifier'] = input("Please enter the oauth_verifier:\n") auth['access_token'] = sObj.getAccessToken(auth['oauth_token'],auth['secret'],auth['oauth_verifier']) print("Successfully Authorized\n") sObj.setAccessToken(auth['access_token']) save = input("Save these credentials for future use? (y/n):\n") if save == "y": with open(path_to_auth, 'w') as outfile: json.dump(auth, outfile, indent=4) print("auth.json file has been saved in the current directory. Keep this file safe.") return sObj
def home(): global backupset if backupset: return render_template("home.html") #Check for Google Credentials if 'googlecredentials' not in session: return redirect(url_for('googleLogin')) googlecredentials = client.OAuth2Credentials.from_json(session['googlecredentials']) if googlecredentials.access_token_expired: return redirect(url_for('googleLogin')) googleSheet = GoogleSheet(googlecredentials) #Check for splitwise credentials if 'splitwiseaccesstoken' not in session: return redirect(url_for('splitwiseLogin')) sObj = Splitwise(Config.splitwise_consumer_key,Config.splitwise_consumer_secret) sObj.setAccessToken(session['splitwiseaccesstoken']) scheduler = BackgroundScheduler() scheduler.add_job(backupData, 'cron', hour=21,minute=34,second=0,args=[googleSheet,sObj]) scheduler.start() backupset = True return render_template("home.html")
def groupMembersString(groupName): sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) friends = None for group in sObj.getGroups(): if group.getName() == groupName: friends = group return [friend.getFirstName() + ' ' + friend.getLastName() for friend in friends.getMembers()]
def addUser(first,last,email): sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) user = createUser(first,last,email) groups = sObj.getGroups() for group in groups: if group.getName() == 'The Room': group.setMembers(group.getMembers().extend([user]))
def friends(): if 'access_token' not in session: return redirect(url_for("home")) sObj = Splitwise(Config.consumer_key, Config.consumer_secret) sObj.setAccessToken(session['access_token']) friends = sObj.getFriends() return render_template("friends.html", friends=friends)
def balances(): sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) friends = sObj.getFriends() amount = [] for friend in friends: for balance in friend.getBalances(): amount.append(balance.getAmount()) return amount
def expenses(): if 'access_token' not in session: return redirect(url_for("home2")) curr_dir = os.path.dirname(inspect.getfile(inspect.currentframe())) parent_dir = os.path.dirname(curr_dir) file_dir = os.path.join(parent_dir, 'txt_files') sObj = Splitwise(Config.consumer_key, Config.consumer_secret) sObj.setAccessToken(session['access_token']) exps = sObj.getExpenses(dated_after=session['date_from'], dated_before=session['date_to'], limit=0) expenseids = [] for i in exps: expenseids.append(i.getId()) exp_concat = [] for i in expenseids: exp = sObj.getExpense(i) for j in exp.getUsers(): if j.getFirstName() == 'Marathe': #3708390: if exp.getCreatedBy().getFirstName() == j.getFirstName( ) or exp.getDescription() == 'Payment': owed = 0 else: owed = j.getOwedShare() exp_concat.append([ exp.getId(), exp.getDate(), '', j.getFirstName(), exp.getCost(), exp.getCategory().getName(), exp.getDescription(), 'SPLITWISE', '', owed ]) else: pass df = pd.DataFrame(exp_concat, columns=[ 'transation_id', 'date', 'account_id', 'account_owner', 'amount', 'old_category', 'name', 'acct_type', 'pending', 'actual_amount' ]) df['category'] = '' df['date'] = pd.to_datetime(df['date']).dt.date df = df[df['name'] != 'Settle all balances'] df.to_csv(os.path.join(file_dir, 'trans_splitwise.txt'), sep='|', header=False, index=False) session.clear() return render_template('close_split.html')
def getSplitwiseObj(user_id): splitwise = Splitwise(app.config['SPLITWISE_CONSUMER_KEY'], app.config['SPLITWISE_CONSUMER_SECRET']) user = User.getUserById(user_id) accessToken = { "oauth_token": str(user.splitwise_token), "oauth_token_secret": str(user.splitwise_token_secret) } splitwise.setAccessToken(accessToken) return splitwise
def authorize(): if 'secret' not in session: return redirect(url_for("home")) oauth_token = request.args.get('oauth_token') oauth_verifier = request.args.get('oauth_verifier') sObj = Splitwise(consumer_key, secret_key) access_token = sObj.getAccessToken(oauth_token,session['secret'],oauth_verifier) session['access_token'] = access_token sObj.setAccessToken(session['access_token']) createGroup([[sObj.getCurrentUser().getFirstName(),sObj.getCurrentUser().getLastName(), sObj.getCurrentUser().getEmail()]], "The Room") return redirect(url_for("home"))
def friends(): if 'access_token' not in session: return redirect(url_for("home")) sObj = Splitwise(Config.consumer_key,Config.consumer_secret) sObj.setAccessToken(session['access_token']) friends = sObj.getExpenses() for i in friends: print(i) return jsonify({'result':'success'})
def get_expenses(self): sObj = Splitwise(Config.consumer_key, Config.consumer_secret) sObj.setAccessToken(session['access_token']) content = sObj.getExpenses() session['expenses'] = content friends = sObj.getFriends() self.debtors = friendsload(friends) #print(friendsload(friends)) #print("\n\n\n\n\n\n" , content) #resp = splitwise.get('get_current_user') return render2('output.html', getresp="waddup")
def friends(): if 'access_token' not in session: return redirect(url_for("home")) sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) me = ['David', 'Terpay', '*****@*****.**'] ram = ['Ram', 'Muthukumaran', '*****@*****.**'] # transaction("pie",'Testing2','David', 10,['David','Ram']) print(groupMembersString('Testing2')) # print(sObj.getGroups()) friends = sObj.getFriends() return render_template("friends.html",friends=friends)
def createGroup(info,groupName): # info contains, list of lists which have name and email sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) group = Group() group.setName(groupName) users = [] for data in info: newUser = createUser(data[0], data[1], data[2]) users.append(newUser) group.setMembers(users) sObj.createGroup(group)
def authorize(): if 'secret' not in session: return redirect(url_for("home")) oauth_token = request.args.get('oauth_token') oauth_verifier = request.args.get('oauth_verifier') sObj = Splitwise(consumer_key, secret_key) access_token = sObj.getAccessToken(oauth_token,session['secret'],oauth_verifier) session['access_token'] = access_token sObj.setAccessToken(session['access_token']) ram = ['Ram','Muthukumaran', '*****@*****.**'] david = ["David",'Terpay','*****@*****.**'] # createGroup([[sObj.getCurrentUser().getFirstName(),sObj.getCurrentUser().getLastName(), sObj.getCurrentUser().getEmail()],ram,david], "The Room") return redirect(url_for("home"))
def friends(): if 'access_token' not in session: return redirect(url_for("home")) consumer_key = '' consumer_secret = '' sObj = Splitwise(consumer_key, consumer_secret) access_token = 0 with open('accesstoken.json', 'r') as f: access_token = json.load(f) print access_token sObj.setAccessToken(access_token) return "friends\n"
def settle(self): sObj = Splitwise(Config.consumer_key, Config.consumer_secret) sObj.setAccessToken(session['access_token']) content = sObj.getExpenses() session['expenses'] = content friends = sObj.getFriends() self.debtors = friendsload(friends) d = [] d.append(Debtor("Hugh Mungus", 69.0)) d.append(Debtor("Gareth Funk", 100000)) d.append(Debtor("The Queen", 1000000000.01)) return render2("settle.html", debtors=self.debtors)
def getMaxFriendOwed(access_token): sObj = Splitwise(consumer_key, consumer_secret) sObj.setAccessToken(access_token) friends = sObj.getFriends() maxSum = 100000 maxFriend = '' for friend in friends: for balance in friend.getBalances(): print balance.getAmount(), friend.getFirstName() if float(balance.getAmount()) < maxSum: maxSum = float(balance.getAmount()) maxFriend = friend.getFirstName() #print "Max friend " + maxFriend + " Max Balance " + maxSum status_code = 200 payload = {'friend': maxFriend, 'amount': float(maxSum)} return status_code, payload
def getFriends(): access_token = session.get('access_token', '') if access_token == '': return authorize_step1() spltwse = Splitwise(consumer_key, consumer_secret) spltwse.setAccessToken(access_token) frnds = '' for frnd in spltwse.getFriends(): frnds += frnd.getFirstName() frnds += '\n' return frnds
def getSplitWiseBalance(access_token): if access_token is not None: sObj = Splitwise(consumer_key, consumer_secret) sObj.setAccessToken(access_token) status_code = 200 friends = sObj.getFriends() owedSum = 0 oweSum = 0 for friend in friends: for balance in friend.getBalances(): if float(balance.getAmount()) > 0: owedSum = owedSum + float(balance.getAmount()) elif float(balance.getAmount()) < 0: oweSum = oweSum + float(balance.getAmount()) payload = {'owedShare': owedSum, 'oweShare': oweSum} else: status_code = 400 payload = {"error": "can not access splitwise data"} return status_code, payload
def addMoney(friendName, currency, expenseReason): speech = "hello" print "name =", friendName print currency print "inside add money" if not friendName or not currency: print "error in name or currency" return tell("sorry couldn't proceed with transaction") consumer_key = '' consumer_secret = '' sObj = Splitwise(consumer_key, consumer_secret) with open('accesstoken.json', 'r') as f: access_token = json.load(f) print access_token sObj.setAccessToken(access_token) amountOwed = currency['amount'] expense = Expense() expense.setCost(amountOwed) expense.setDescription(expenseReason) user1 = ExpenseUser() user1.setId(utils.getSplitwiseId('nirmit')) user1.setPaidShare(str(amountOwed)) user1.setOwedShare('0.0') user2 = ExpenseUser() user2.setId(utils.getSplitwiseId(friendName)) user2.setPaidShare('0.00') user2.setOwedShare(str(amountOwed)) users = [] users.append(user1) users.append(user2) expense.setUsers(users) expense = sObj.createExpense(expense) print expense
class ExpenseTestCase(unittest.TestCase): def setUp(self): consumer_key = os.environ['CONSUMER_KEY'] consumer_secret = os.environ['CONSUMER_SECRET'] oauth_token = os.environ['OAUTH_TOKEN'] oauth_token_secret = os.environ['OAUTH_TOKEN_SECRET'] self.sObj = Splitwise(consumer_key, consumer_secret) self.sObj.setAccessToken({ 'oauth_token': oauth_token, 'oauth_token_secret': oauth_token_secret }) def test_expense_flow(self): receipt = os.path.join(os.path.dirname(os.path.realpath(__file__)), "receipt.jpg") expense = Expense() expense.setDescription("End2EndTest") expense.setCost('10') expense.setGroupId(19571167) expense.setSplitEqually() expense.setReceipt(receipt) # create expense expense, error = self.sObj.createExpense(expense) self.assertIsNone(error) self.assertIsNotNone(expense.getId()) # delete expense success, error = self.sObj.deleteExpense(expense.getId()) self.assertIsNone(error) self.assertTrue(success) def test_expense_invalidkeys_fail(self): sObj = Splitwise('consumerkey', 'consumersecret', { "oauth_token": "sdsd", "oauth_token_secret": "sdsdd" }) expense = Expense() with self.assertRaises(SplitwiseUnauthorizedException): sObj.createExpense(expense)
def analyzer(): if 'access_token' not in session: return redirect(url_for("home")) sObj = Splitwise(Config.consumer_key, Config.consumer_secret) sObj.setAccessToken(session['access_token']) groups = sObj.getGroups() group = [x for x in groups if x.name == "88 Chemin 2018"][0] group.members.sort(key=wallstreet.get_index_for_dude) expenses = sObj.getExpenses(group_id=group.id, limit=10000, dated_after=datetime.datetime(2017, 5, 1)) matrix = payment_matrix(expenses) wallstreet.print_matrix(matrix) simplified_matrix = simplify_matrix(deepcopy(matrix)) wallstreet.print_matrix(simplified_matrix) return render_template("payment_matrix.html", users=group.members, matrix=matrix, simplified_matrix=simplified_matrix)
def transaction(Description, Group, Payer, Price, Contributors): # price, date, description, group ID or this particular groups name, members sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) user = sObj.getCurrentUser() groups = sObj.getGroups() group_dict = {group.getName(): group for group in groups} importedData = {'Date': datetime.datetime.now(), 'Description': Description, 'Group': Group, 'Payer': Payer, 'Debit': Price} expense = Expense() price = float(importedData['Debit'] or 0) expense.setCost(price) expense.setDate(importedData['Date']) expense.setDescription(importedData['Description']) expense.setGroupId(group_dict[importedData['Group']].getId()) members = group_dict[importedData['Group']].getMembers() users = [] contributors = Contributors for member in members: if member.getFirstName() in contributors: user = ExpenseUser() user.setId(member.getId()) if member.getFirstName() == importedData['Payer']: user.setPaidShare(price) else: user.setPaidShare(0) users.append(user) paid = 0 share = round(price/len(users), 2) for user in users: user.setOwedShare(share) paid = paid + share diff = price - paid if diff != 0: user = random.choice(users) user.setOwedShare(share + diff) expense.setUsers(users) expense = sObj.createExpense(expense)
def submission(): global df # TODO: add checks beforehand whether the user has clicked on all checkboxes # print(request.form) sObj = Splitwise(Config.consumer_key,Config.consumer_secret) sObj.setAccessToken(session['access_token']) saleh = ExpenseUser() saleh.setId(2242086) paypal = ExpenseUser() paypal.setId(18572820) nuraini = ExpenseUser() nuraini.setId(2705458) for key in request.form: if not is_number(key): continue value = request.form[key] if value == 'Payment': continue # we dont handle payments yet print(key, value) amount = df.iloc[int(float(key))]['Amount'] users = [] users.append(saleh) users.append(paypal) users.append(nuraini) saleh.setPaidShare('0.00') nuraini.setPaidShare('0.00') paypal.setPaidShare('0.00') saleh.setOwedShare('0.00') nuraini.setOwedShare('0.00') paypal.setOwedShare('0.00') expense = Expense() expense.setUsers(users) expense.setGroupId(6456733) expense.setCost(str(abs(float(amount)))) expense.setDescription(df.iloc[int(float(key))]['Description']) try: expense.setDate(datetime.datetime.strptime(df.iloc[int(float(key))]['Trans Date'], '%m/%d/%Y').strftime('%d/%m/%Y')) except: expense.setDate(datetime.datetime.strptime(df.iloc[int(float(key))]['Trans Date'], '%m/%d/%y').strftime('%d/%m/%Y')) # case where a transaction is refunded if float(amount) > 0: if value == 'Saleh': paypal.setOwedShare(str(abs(float(amount)))) saleh.setPaidShare(str(abs(float(amount)))) elif value == 'Nuraini': paypal.setOwedShare(str(abs(float(amount)))) nuraini.setPaidShare(str(abs(float(amount)))) expense = sObj.createExpense(expense) continue # case for expenses if value == 'Saleh': saleh.setOwedShare(str(abs(float(amount)))) paypal.setPaidShare(str(abs(float(amount)))) expense = sObj.createExpense(expense) elif value == 'Nuraini': nuraini.setOwedShare(str(abs(float(amount)))) paypal.setPaidShare(str(abs(float(amount)))) expense = sObj.createExpense(expense) elif value == 'Half-Split': half = round(abs(float(amount))/2,2) other_half = abs(float(amount))-half nuraini.setOwedShare(half) saleh.setOwedShare(other_half) paypal.setPaidShare(str(abs(float(amount)))) expense = sObj.createExpense(expense) elif value == 'Share': continue return redirect(url_for("success"))
def getExpenses(): sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) total_expenses = sObj.getExpenses() descriptions = [name.getDescription() for name in total_expenses] return descriptions
def clear(): sObj = Splitwise(consumer_key, secret_key) sObj.setAccessToken(session['access_token']) expenses = sObj.getExpenses() for expense in expenses: expense.setCost(0)