-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
batch.py
228 lines (165 loc) · 5.84 KB
/
batch.py
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
import logging
from datetime import datetime, timedelta
import redis
from celery import shared_task
from pytz import timezone
from charges import ChargeException, QuarantinedException, amount_to_charge, calculate_amount_fees, charge
from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_TLS_URL, TIMEZONE, UPDATE_STRIPE_FEES, UPDATE_FAILED_CHARGES
from npsp import Opportunity
from util import send_email, update_fees, fail_expired_charges
zone = timezone(TIMEZONE)
log_level = logging.getLevelName(LOG_LEVEL)
root = logging.getLogger()
root.setLevel(log_level)
class Log(object):
"""
This encapulates sending to the console/stdout and email all in one.
"""
def __init__(self):
self.log = list()
def it(self, string):
"""
Add something to the log.
"""
logging.debug(string)
self.log.append(string)
def send(self):
"""
Send the assembled log out as an email.
"""
body = "\n".join(self.log)
recipient = ACCOUNTING_MAIL_RECIPIENT
subject = "Batch run"
send_email(body=body, recipient=recipient, subject=subject)
class AlreadyExecuting(Exception):
"""
Here to show when more than one job of the same type is running.
"""
pass
class Lock(object):
"""
Claim an exclusive lock. Using Redis.
"""
def __init__(self, key):
self.key = key
self.connection = redis.from_url(REDIS_TLS_URL)
def acquire(self):
if self.connection.get(self.key):
raise AlreadyExecuting
self.connection.setex(name=self.key, value="bar", time=1200)
def append(self, key, value):
if self.connection.get(key):
self.connection.setex(name=key, value=value, time=1200)
def release(self):
self.connection.delete(self.key)
# TODO stop sending this email and just rely on Sentry and logs?
@shared_task()
def charge_cards():
lock = Lock(key="charge-cards-lock")
lock.acquire()
log = Log()
log.it("---Starting batch card job...")
begin_closedate_range = (datetime.now(tz=zone) - timedelta(days=14)).strftime("%Y-%m-%d")
today = datetime.now(tz=zone).strftime("%Y-%m-%d")
opportunities = Opportunity.list(begin=begin_closedate_range, end=today)
log.it("---Processing charges...")
log.it(f"Found {len(opportunities)} opportunities available to process.")
for opportunity in opportunities:
# texas does not check the payment type here, but we want to
if not opportunity.stripe_customer_id or opportunity.payment_type != "Stripe":
continue
amount = amount_to_charge(opportunity)
log.it(
f"---- Charging ${amount} to {opportunity.stripe_customer_id} ({opportunity.name})"
)
try:
charge(opportunity)
except ChargeException as e:
logging.info("Batch charge error")
e.send_slack_notification()
except QuarantinedException:
logging.info(
"Failed to charge because Opportunity %s is quarantined", opportunity
)
log.send()
lock.release()
@shared_task()
def update_ach_charges():
lock = Lock(key='update-ach-charges-lock')
lock.acquire()
log = Log()
log.it('---Starting batch ach job...')
log.it('---Checking for status changes on ACH charges...')
begin_closedate_range = (datetime.now(tz=zone) - timedelta(days=3)).strftime("%Y-%m-%d")
today = datetime.now(tz=zone).strftime("%Y-%m-%d")
opportunities = Opportunity.list(begin=begin_closedate_range, end=today, stage_name="ACH Pending")
for opportunity in opportunities:
if not opportunity.stripe_customer_id:
continue
amount = amount_to_charge(opportunity)
log.it(
f"---- ACH Charging ${amount} to {opportunity.stripe_customer_id} ({opportunity.name})"
)
try:
charge(opportunity)
except ChargeException as e:
logging.info("ACH batch charge error")
e.send_slack_notification()
except QuarantinedException:
logging.info(
"Failed to charge because Opportunity %s is quarantined", opportunity
)
log.send()
lock.release()
@shared_task()
def update_failed_charges():
log = Log()
log.it('---Starting batch update failed charges job...')
if UPDATE_FAILED_CHARGES is False:
log.it('---Update failed charges is false. Get out.')
return
lock = Lock(key='update-failed-charges-lock')
lock.acquire()
seven_days_ago = (datetime.now(tz=zone) - timedelta(days=7)).strftime("%Y-%m-%d")
query = f"""
SELECT
Amount,
CloseDate,
Id,
Name,
StageName,
Type
FROM Opportunity
WHERE StageName = 'Failed'
AND CloseDate <= {seven_days_ago}
ORDER BY CloseDate DESC
LIMIT 25
"""
try:
fail_expired_charges(query)
finally:
lock.release()
@shared_task()
def save_stripe_fee():
log = Log()
log.it('---Starting batch stripe fee job...')
if UPDATE_STRIPE_FEES is False:
log.it('---Update fee is false. Get out.')
return
lock = Lock(key='save-stripe-fee-lock')
lock.acquire()
query = """
SELECT Id, Name, npe03__Amount__c, Stripe_Customer_Id__c, Stripe_Card__c, Stripe_Bank_Account__c, Card_type__c, Stripe_Payment_Type__c, Stripe_Agreed_to_pay_fees__c, Stripe_Transaction_Fee__c
FROM npe03__Recurring_Donation__c
WHERE npe03__Open_Ended_Status__c = 'Open'
AND Stripe_Transaction_Fee__c = null
AND Stripe_Customer_Id__c != ''
ORDER BY npe03__Date_Established__c DESC
LIMIT 50
"""
try:
update_fees(query, log, 'recurring')
finally:
lock.release()
if __name__ == "__main__":
charge_cards()