Skip to content
This repository has been archived by the owner on Feb 8, 2018. It is now read-only.

Commit

Permalink
Rip out balanced-ba references
Browse files Browse the repository at this point in the history
I left the ones in test_history because #3616 takes care of those. Note
that I also left `balanced-ba` in the schema and the database, because
we still want a record of those routes in the db. We just don't want to
do anything with them anymore.
  • Loading branch information
chadwhitacre committed Jul 16, 2015
1 parent d09d976 commit c123e0e
Show file tree
Hide file tree
Showing 9 changed files with 13 additions and 185 deletions.
103 changes: 0 additions & 103 deletions gratipay/billing/exchanges.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,74 +85,6 @@ def repr_exception(e):
return repr(e)


def ach_credit(db, participant, withhold, minimum_credit=MINIMUM_CREDIT):

# Compute the amount to credit them.
# ==================================
# Leave money in Gratipay to cover their obligations next week (as these
# currently stand).

balance = participant.balance
assert balance is not None, balance # sanity check
amount = balance - withhold

# Do some last-minute checks.
# ===========================

if amount <= 0:
return # Participant not owed anything.

if amount < minimum_credit:
also_log = ""
if withhold > 0:
also_log = " ($%s balance - $%s in obligations)"
also_log %= (balance, withhold)
log("Minimum payout is $%s. %s is only due $%s%s."
% (minimum_credit, participant.username, amount, also_log))
return # Participant owed too little.

if not participant.is_whitelisted:
raise NotWhitelisted # Participant not trusted.

route = ExchangeRoute.from_network(participant, 'balanced-ba')
if not route:
return 'No bank account'


# Do final calculations.
# ======================

credit_amount, fee = skim_credit(amount)
cents = credit_amount * 100

if withhold > 0:
also_log = "$%s balance - $%s in obligations"
also_log %= (balance, withhold)
else:
also_log = "$%s" % amount
msg = "Crediting %s %d cents (%s - $%s fee = $%s) on Balanced ... "
msg %= (participant.username, cents, also_log, fee, credit_amount)


# Try to dance with Balanced.
# ===========================

e_id = record_exchange(db, route, -credit_amount, fee, participant, 'pre')
meta = dict(exchange_id=e_id, participant_id=participant.id)
try:
ba = thing_from_href('bank_accounts', route.address)
ba.credit(amount=cents, description=participant.username, meta=meta)
record_exchange_result(db, e_id, 'pending', None, participant)
log(msg + "succeeded.")
error = ""
except Exception as e:
error = repr_exception(e)
record_exchange_result(db, e_id, 'failed', error, participant)
log(msg + "failed: %s" % error)

return error


def create_card_hold(db, participant, amount):
"""Create a hold on the participant's credit card.
Expand Down Expand Up @@ -408,38 +340,3 @@ def propagate_exchange(cursor, participant, route, error, amount):

if hasattr(participant, 'set_attributes'):
participant.set_attributes(balance=new_balance)


def sync_with_balanced(db):
"""We can get out of sync with Balanced if record_exchange_result was
interrupted or wasn't called. This is where we fix that.
"""
check_db(db)
exchanges = db.all("""
SELECT *
FROM exchanges
WHERE status = 'pre'
""")
meta_exchange_id = balanced.Transaction.f.meta.exchange_id
for e in exchanges:
p = Participant.from_username(e.participant)
cls = balanced.Debit if e.amount > 0 else balanced.Credit
transactions = cls.query.filter(meta_exchange_id == e.id).all()
assert len(transactions) < 2
if transactions:
t = transactions[0]
error = t.failure_reason
status = t.status
assert (not error) ^ (status == 'failed')
record_exchange_result(db, e.id, status, error, p)
else:
# The exchange didn't happen, remove it
db.run("DELETE FROM exchanges WHERE id=%s", (e.id,))
# and restore the participant's balance if it was a credit
if e.amount < 0:
db.run("""
UPDATE participants
SET balance=(balance + %s)
WHERE id=%s
""", (-e.amount + e.fee, p.id))
check_db(db)
2 changes: 1 addition & 1 deletion gratipay/billing/payday.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ def notify_participants(self):
AND (SELECT count(*)
FROM current_exchange_routes er
WHERE er.participant = p.id
AND network IN ('balanced-ba', 'paypal')
AND network = 'paypal'
AND error = ''
) > 0
)
Expand Down
17 changes: 1 addition & 16 deletions gratipay/models/exchange_route.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,6 @@ def from_address(cls, participant, network, address):
r.__dict__['participant'] = participant
return r

@classmethod
def associate_balanced(cls, participant, balanced_account, network, address):
if network == 'balanced-cc':
obj = balanced.Card.fetch(address)
else:
assert network == 'balanced-ba', network # sanity check
obj = balanced.BankAccount.fetch(address)
obj.associate_to_customer(balanced_account)

return cls.insert(participant, network, address)

@classmethod
def insert(cls, participant, network, address, error='', fee_cap=None):
participant_id = participant.id
Expand All @@ -75,11 +64,7 @@ def insert(cls, participant, network, address, error='', fee_cap=None):
return r

def invalidate(self):
if self.network == 'balanced-ba':
balanced.BankAccount.fetch(self.address).delete()
elif self.network == 'balanced-cc':
balanced.Card.fetch(self.address).unstore()
elif self.network == 'braintree-cc':
if self.network == 'braintree-cc':
braintree.PaymentMethod.delete(self.address)

# For Paypal, we remove the record entirely to prevent
Expand Down
3 changes: 0 additions & 3 deletions gratipay/models/participant.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,9 +669,6 @@ def render_notifications(self, state):
# Exchange-related stuff
# ======================

def get_bank_account_error(self):
return getattr(ExchangeRoute.from_network(self, 'balanced-ba'), 'error', None)

def get_paypal_error(self):
return getattr(ExchangeRoute.from_network(self, 'paypal'), 'error', None)

Expand Down
2 changes: 1 addition & 1 deletion sql/payday.sql
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ CREATE TABLE payday_teams AS
AND (SELECT count(*)
FROM current_exchange_routes er
WHERE er.participant = p.id
AND network IN ('balanced-ba', 'paypal')
AND network = 'paypal'
AND error = ''
) > 0
;
Expand Down
41 changes: 0 additions & 41 deletions tests/py/test_callbacks.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
from __future__ import absolute_import, division, print_function, unicode_literals

import json

from mock import patch

from gratipay.billing.exchanges import record_exchange
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.testing import Harness


Expand All @@ -28,38 +22,3 @@ def test_simplate_doesnt_require_a_csrf_token(self):
def test_no_csrf_cookie_set_for_callbacks(self):
r = self.callback(body=b'{"events": []}', csrf_token=False)
assert b'csrf_token' not in r.headers.cookie

@patch('gratipay.billing.exchanges.record_exchange_result')
def test_credit_callback(self, rer):
alice = self.make_participant('alice')
ExchangeRoute.insert(alice, 'balanced-ba', '/bank/foo', '')
ba = ExchangeRoute.from_network(alice, 'balanced-ba')
for status in ('succeeded', 'failed'):
error = 'FOO' if status == 'failed' else None
e_id = record_exchange(self.db, ba, 10, 0, alice, 'pre')
body = json.dumps({
"events": [
{
"type": "credit."+status,
"entity": {
"credits": [
{
"failure_reason": error,
"meta": {
"participant_id": alice.id,
"exchange_id": e_id,
},
"status": status,
}
]
}
}
]
})
r = self.callback(body=body, csrf_token=False)
assert r.code == 200, r.body
assert rer.call_count == 1
assert rer.call_args[0][:-1] == (self.db, e_id, status, error)
assert rer.call_args[0][-1].id == alice.id
assert rer.call_args[1] == {}
rer.reset_mock()
15 changes: 8 additions & 7 deletions www/about/stats.spt
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,19 @@ subhead = _("Stats")
yesterday = datetime.datetime.utcnow() - datetime.timedelta(hours=24)
db = website.db
escrow = db.one("SELECT sum(balance) FROM participants", default=0)
nach = db.one("""
nach = 0
npaypal = db.one("""
SELECT count(*)
FROM current_exchange_routes r
JOIN participants p ON p.id = r.participant
WHERE r.network = 'balanced-ba'
WHERE r.network = 'paypal'
AND r.error = ''
AND p.is_suspicious IS NOT true
""")
if nach < 10:
nach = CARDINALS[nach].title()
if npaypal < 10:
npaypal = CARDINALS[npaypal].title()
else:
nach = commaize(nach)
npaypal = commaize(npaypal)
payday = db.one( "SELECT ts_start, ts_end FROM paydays WHERE ts_start > %s"
, (yesterday,)
)
Expand Down Expand Up @@ -161,8 +162,8 @@ elif now.weekday() == SATURDAY:

def out():
names = ['ncc', 'pcc', 'transfer_volume', 'last_thursday',
'this_thursday', 'punc', 'other_people', 'average_tip',
'average_tippees', 'total_backed_tips', 'tip_n', 'nach', 'escrow',
'this_thursday', 'punc', 'other_people', 'average_tip', 'nach',
'average_tippees', 'total_backed_tips', 'tip_n', 'npaypal', 'escrow',
'ngivers', 'nreceivers', 'noverlap', 'nactive']
d = globals()
r = {name: d[name] for name in names}
Expand Down
13 changes: 1 addition & 12 deletions www/~/%username/routes/associate.json.spt
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,7 @@ if change:
if not address:
raise Response(400, _("The address cannot be empty."))

if network == 'balanced-ba':
account = participant.get_balanced_account()

if account.merchant_status != 'underwritten':
raise Response(400, _("You need to verify your identity first."))

try:
ExchangeRoute.associate_balanced(participant, account, network, address)
except balanced.exc.HTTPError as err:
raise Response(400, repr_exception(err))

elif network == 'braintree-cc':
if network == 'braintree-cc':
result = braintree.PaymentMethod.create({
"customer_id": participant.braintree_customer_id,
"payment_method_nonce": address,
Expand Down
2 changes: 1 addition & 1 deletion www/~/%username/routes/delete.json.spt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ if 'address' not in request.body:

network = request.body['network']

if network not in ['balanced-ba', 'balanced-cc', 'braintree-cc', 'paypal', 'bitcoin']:
if network not in ['balanced-cc', 'braintree-cc', 'paypal', 'bitcoin']:
raise Response(400, "invalid 'network' param.")

route = ExchangeRoute.from_address(participant,
Expand Down

0 comments on commit c123e0e

Please sign in to comment.