def getExpenseUser(self, friend, paid, owed): user = ExpenseUser() user.setId(friend.getId()) user.setPaidShare(str(paid)) user.setOwedShare(str(owed)) return user
def import_expenses(self): try: row = int(self.le_initial_row.text()) - 1 description_col = int(self.le_description_col.text()) - 1 date_col = int(self.le_date_col.text()) - 1 default_date = self.default_date.date() date_format = self.le_date_format.text() percent = 1.0 / len(list(self.current_group.getMembers())) while self.model.item(row) is not None: print("Row ", row) expense = Expense() expense.setDescription( self.model.item(row, description_col).text()) print("Expense: ", expense.getDescription()) date = QDate.fromString( self.model.item(row, date_col).text(), date_format) if not date.isValid(): date = default_date expense.setDate(date.toString(Qt.ISODate)) print("Date: ", expense.getDate()) cost = 0 users = [] for member in self.current_group.getMembers(): print("Processing member ", member.getFirstName()) member_column = int( self.member_widget_map[member.getId()].text()) - 1 paid = 0 try: paid = float( self.model.item(row, member_column).text()) print("Expense: ", self.model.item(row, member_column).text()) except: pass cost = cost + paid expense_user = ExpenseUser() expense_user.setId(member.getId()) expense_user.setPaidShare(str(paid)) users.append(expense_user) for expense_user in users: expense_user.setOwedShare(str(cost * percent)) if cost == 0: raise Exception( self.tr('No se ha introducido monto para el gasto')) expense.setCost(str(cost)) expense.setUsers(users) expense.setGroupId(self.current_group.id) self.sObj.createExpense(expense) row = row + 1 self.le_initial_row.setText(str(row + 1)) except Exception as inst: QMessageBox.critical( self, self.tr("Error"), self.tr("Se ha producido un error en la fila") + str(row + 1) + "\n" + str(inst)) traceback.print_exc()
def __init__(self,data=None): if data: self.id = data["id"] self.group_id = data["group_id"] self.description = data["description"] self.repeats = data["repeats"] self.repeat_interval = data["repeat_interval"] self.email_reminder = data["email_reminder"] self.email_reminder_in_advance = data["email_reminder_in_advance"] self.next_repeat = data["next_repeat"] self.details = data["details"] self.comments_count = data["comments_count"] self.payment = data["payment"] self.creation_method = data["creation_method"] self.transaction_method = data["transaction_method"] self.transaction_confirmed = data["transaction_confirmed"] self.cost = data["cost"] self.currency_code = data["currency_code"] self.created_by = User(data["created_by"]) self.date = data["date"] self.created_at = data["created_at"] self.updated_at = data["updated_at"] self.deleted_at = data["deleted_at"] self.receipt = Receipt(data["receipt"]) self.category = Category(data["category"]) if data["updated_by"] is not None: self.updated_by = User(data["updated_by"]) else: self.updated_by = None if data["deleted_by"] is not None: self.deleted_by = User(data["deleted_by"]) else: self.deleted_by = None if "friendship_id" in data: self.friendship_id = data["friendship_id"] else: self.friendship_id = None if "expense_bundle_id" in data: self.expense_bundle_id = data["expense_bundle_id"] else: self.expense_bundle_id = None self.repayments = [] for repayment in data["repayments"]: self.repayments.append(Debt(repayment)) self.users = [] for user in data["users"]: self.users.append(ExpenseUser(user))
def post_transactions_to_splitwise(self, oauth_token, oauth_verifier): access_token = SplitwiseApiUtils.splitwise_obj.getAccessToken( oauth_token, SplitwiseApiUtils.secret, oauth_verifier) SplitwiseApiUtils.splitwise_obj.setAccessToken(access_token) self.create_group_if_not_exists() current_user_id = SplitwiseApiUtils.splitwise_obj.getCurrentUser().id friend_obj = self.get_friend( SplitwiseApiUtils.splitwise_obj.getFriends()) group_id = self.client.get(f"sw-${current_user_id}") user1 = ExpenseUser() user1.setId(current_user_id) user2 = ExpenseUser() user2.setId(friend_obj.id) self.create_expense_on_splitwise(group_id, user1, user2)
def get_expense_user(self): return ExpenseUser()
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 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 _create_expense(initiator_id: str, recipient_id: str, amount: float, description: str): """ This will create an expense where the {initiator} owes the {recipient} {amount}. """ if amount <= 0: raise CommandException('Negative amounts not allowed') tso: User = User.objects.get(friendly_name='tso') initiator: User = User.objects.get(slack_id=initiator_id) recipient: User = User.objects.get(slack_id=recipient_id) users = [] expense = Expense() expense.setGroupId(settings.SPLITWISE_GROUP_ID) expense.setDescription(description) expense.setCost(amount) initiator_user = ExpenseUser() initiator_user.setId(initiator.splitwise_id) initiator_user.setPaidShare(0) initiator_user.setOwedShare(amount) users.append(initiator_user) recipient_user = ExpenseUser() recipient_user.setId(recipient.splitwise_id) recipient_user.setPaidShare(amount) recipient_user.setOwedShare(0) users.append(recipient_user) # We do this because we're using my access token. if tso.id not in [initiator.id, recipient.id]: tso_user = ExpenseUser() tso_user.setId(tso.splitwise_id) tso_user.setPaidShare(0) tso_user.setOwedShare(0) users.append(tso_user) expense.setUsers(users) if not sObj.createExpense(expense): raise CommandException('Failed to create SW expense')
def add_bill(): data = request.get_json() cost = data['value'] users = [] group = sObj.getGroup(10204809) people = group.getMembers() expense = Expense() expense.setCost(str(cost)) expense.setDescription("Capital One Transfer") # per_person = str(round(cost / len(people), 2)) per_person = cost paying_user = sObj.getCurrentUser() paying_id = paying_user.getId() paying_expense_user = ExpenseUser() paying_expense_user.setId(paying_id) paying_expense_user.setPaidShare(str(cost)) paying_expense_user.setOwedShare(per_person) users.append(paying_expense_user) for friend in people: id = friend.getId() if id == paying_id: continue user = ExpenseUser() user.setId(id) user.setPaidShare('0.0') user.setOwedShare(per_person) users.append(user) expense.setUsers(users) expense = sObj.createExpense(expense) print(expense.getId()) return jsonify({'auth': 1})
def addExpense(self, cost: float, description: str, group_id: int, payer: str) -> None: """ Adds expense to Splitwise group. If expenses don't evenly get distributed, it will randomly assign pennies to even things off """ expense = Expense() expense.setCost(str(cost)) expense.setDescription(description) expense.setGroupId(group_id) group = self.sObj.getGroup(group_id) member_dict = self.getGroupMemberIDs(group) member_count = len(member_dict) per_person_cost = round(cost / member_count, 2) expense_members = [] print(per_person_cost * member_count, cost) for member in member_dict: expense_user = ExpenseUser() expense_user.setId(member_dict[member]) expense_user.setFirstName(member) expense_user.setOwedShare(str(per_person_cost)) if member == payer: expense_user.setPaidShare(cost) else: expense_user.setPaidShare('0.00') expense_members.append(expense_user) if cost < per_person_cost * member_count: remainder = (per_person_cost * float(member_count)) - cost shuffle(expense_members) i = 0 while remainder > 0.00: owed = float(expense_members[i].getOwedShare()) owed -= 0.01 expense_members[i].setOwedShare(str(owed)) remainder -= 0.01 if i == member_count - 1: i = 0 else: i += 1 elif cost > per_person_cost * member_count: remainder = round(cost - (per_person_cost * float(member_count)), 2) print(remainder) shuffle(expense_members) i = 0 while remainder > 0.00: owed = float(expense_members[i].getOwedShare()) owed += 0.01 expense_members[i].setOwedShare(str(owed)) remainder -= 0.01 if i == member_count - 1: i = 0 else: i += 1 expense.setUsers(expense_members) expenses = self.sObj.createExpense(expense) print('Successfully added to Splitwise. Expense ID:', expenses.getId())
def create_expense_object(self, payer_id, payee_id, amount, description): expense = Expense() expense.setCost(amount) expense.setDescription(description) payer = ExpenseUser() payer.setId(payer_id) payer.setPaidShare(amount) payer.setOwedShare(0.00) payee = ExpenseUser() payee.setId(payee_id) payee.setPaidShare(0.00) payee.setOwedShare(amount) users = [payer, payee] expense.setUsers(users) expense = self.createExpense(expense) return expense
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
def main(): if 'access_token' in session: sObj.setAccessToken(session['access_token']) user = sObj.getCurrentUser() friends = sObj.getFriends() friends_dict = {friend.getFirstName():friend.getId() for friend in friends} groups = sObj.getGroups() group_list = [group.getName() for group in groups] group_id = [group.getId() for group in groups] group_dict = {group.getName():group for group in groups} with open(CSV_FILE_LOCATION, encoding='utf-8-sig') as data: importedData = list(csv.DictReader(data)) # print(importedData) ##### Vet csv before proceeding ##### for i, row in enumerate(importedData): if not (row.get('Debit') and row.get('Payer') and row.get('Group')): return f"Remove blanks on row {i+1} in your CSV and try again." with open(DB) as db_json: db = json.load(db_json) msg = [] # Begin loop reading the CSV for row in importedData: rowstring = f"{row.get('Date')}, {row.get('Debit')}, {row.get('Description')}, {row.get('Group')}, {row.get('Payer')}" rsbytes = bytes(rowstring, 'utf-8') hash_obj = hashlib.sha256(rsbytes) hex_dig = hash_obj.hexdigest() # print(hex_dig) if hex_dig in db: msg.append(f"{rowstring} looks like a duplicate, skipping") continue else: db[hex_dig] = "True" expense = Expense() price = float(row['Debit'] or 0) expense.setCost(price) expense.setDate(row['Date']) expense.setDescription(row['Description']) expense.setGroupId(group_dict[row['Group']].getId()) members = group_dict[row['Group']].getMembers() users = [] for member in members: user = ExpenseUser() user.setId(member.getId()) if member.getFirstName() == row['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) msg.append('Import successful!') with open(DB, 'w') as outfile: json.dump(db, outfile) msg.append('New entries recorded in db.') message = "<br>".join(msg) return message return 'User is not logged in'
def addSplitwise(tf): amount = tf['number_oNYSbrj3CNlF'] name = False if 'textfield_Maf3TeF00J84' in tf: name = tf['textfield_Maf3TeF00J84'] catagory = tf['list_uDy8LvuB3wTa_choice'] split = [tf[i].lower() for i in tf.keys() if 'list_SFFmFqOvH1Xv_choice' in i] users = [] namesfg = [] if split: for i in self.sw.getGroups(): if i.getName().lower() in split: namefg.extend(i.getMembers()) split.extend(namesfg) for i in self.sw.getFriends(): print(i.__dict__) first = i.getFirstName() if not first: first = "" last = i.getLastName() if not last: last = "" if first.lower() + ' ' + last.lower() in split: user = ExpenseUser() user.setId(i.getId()) user.setPaidShare('0') user.setOwedShare('1') users.append(user) each = '%.2f'%(float(amount)/(len(users)+1)) for user in users: user.setOwedShare(each) me = ExpenseUser() me.setId(self.sw.getCurrentUser().getId()) me.setOwedShare('%.2f'%(float(100*int(amount)-int(100*float(each)*len(users)))/100)) me.setPaidShare(amount) users.append(me) expense = Expense() expense.setCost(str(amount)) expense.setDescription(name) expense.setUsers(users) print(users) self.sw.createExpense(expense) row = self.gs.getRow(catagory) monYr = datetime.datetime.now().strftime("%b %Y") col = self.gs.getCol(monYr) self.gs.addCell(col, row, amount)
def share_expense_with_group_members(sw: Splitwise, desc, cost, group_id, date): grp = sw.getGroup(group_id) current_user = sw.getCurrentUser() other_members = [m for m in grp.getMembers() if m.id != current_user.id] _debug(current_user) _debug(other_members) cost_per_user = round(cost / len(grp.members), 2) expense = Expense() expense.cost = f"{cost}" expense.description = f"{desc}" expense.group_id = f"{group_id}" expense.setDate(date.strftime("%Y/%m/%d")) users = [] for om in other_members: user = ExpenseUser() user.setId(om.id) user.setPaidShare(f"0") user.setOwedShare(f"{cost_per_user}") users.append(user) user = ExpenseUser() user.setId(current_user.id) user.setPaidShare(f"{cost}") user.setOwedShare(f"{cost - len(users) * cost_per_user}") users.append(user) expense.users = users sw.createExpense(expense)