-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreconcile_customers_to_qbo.py
executable file
·240 lines (147 loc) · 6.15 KB
/
reconcile_customers_to_qbo.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
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env python
"""reconcile_customers_to_qbo.
Compare the downloaded customer list to the population of customers in Quickbooks.
Suggest modifications.
Usage:
reconcile_customer_to_qbo [options]
Options:
--debug Print debugging output. [default: False]
--doit Actually modify QBO data. Otherwise, is a no-op. [default: False]
--qboid <id[,id...]> Reconcile specified comma-delimited QBOIDs.
--sheetid <id[,id...]> Reconcile specified comma-delimited Google Sheets IDs.
"""
from docopt import docopt
import requests
import json
import hackerspace_utils as hu
import pandas as pd;
import sys
import time
import stripe;
from datetime import date
from quickbooks import Oauth2SessionManager
from quickbooks import QuickBooks
from quickbooks.objects.customer import Customer
from quickbooks.objects import Account
from quickbooks.objects import EmailAddress
from quickbooks.objects import Address
import qbo_utils as qu
# Get data from the spreadsheet download
cols_we_want = {
"ID" : "SHEETID",
"username" : "username",
"QBO ID" : "QBOID",
"Name" : "name",
"Email" : 'email',
"Phone Number" : 'phone',
"Stripe ID" : 'stripe_id',
}
dispformat = "'{name}' : '{email}' : '{phone}' "
def display_custrow(row):
return dispformat.format(**row)
def cust2bag(cust):
bag = {}
bag['id'] = cust.Id
bag['name'] = cust.DisplayName
try:
bag['email'] = cust.PrimaryEmailAddr.Address
except AttributeError:
bag['email'] = ""
try:
bag['phone'] = cust.PrimaryPhone.FreeFormNumber
except AttributeError:
bag['phone'] = ""
bag['obj'] = cust
return(bag)
def forward():
all_cust = hu.all_cust_df(cols_we_want)
all_cust['SHEETID'] = all_cust['SHEETID'].astype(int)
if (arguments['--qboid']):
all_cust = all_cust[all_cust['QBOID'].isin(arguments['--qboid'])]
if (arguments['--sheetid']):
all_cust = all_cust[all_cust['SHEETID'].isin(arguments['--sheetid'])]
# Connect to QBO, and get the current list from them.
qbo_client = qu.open_qbo_client()
qbolist = pd.DataFrame([ cust2bag(cust) for cust in qu.cust_iterable() ])
qbolist['id'] = qbolist['id'].astype(int)
if (arguments['--qboid']):
qbolist = qbolist[qbolist['id'].isin(arguments['--qboid'])]
ccount = 0;
pcount = 0;
# all_cust['QBOID']="";
for index,row in all_cust.iterrows():
ccount += 1
changes = False
if (row['QBOID'] == 0 ):
print("Sheet has no QBO ID for {name}".format(**row))
found_candidate = False
print(display_custrow(row))
maybes = qbolist[(qbolist['email'] == row['email']) | (qbolist['name']==row['name'])]
if(len(maybes) > 0):
found_candidate = True
print("Candidate matches: ")
for index,cust in maybes.iterrows():
print(display_custrow(cust)+" (QBO: {0})".format(cust['id']) )
if(found_candidate):
print("Candidates exist; not adding.")
else:
pcount += 1
if(arguments['--doit']):
print("No prospective match. Adding. ")
thisj = qu.build_cust(row)
new = Customer.from_json(thisj)
newer = new.save(qb=qbo_client)
print("# New QBO: {0}".format(newer.Id) )
else:
print("# Not adding, because you said not to (no --doit)")
else:
if (debug) :print("{name} has QBOID '{QBOID}'".format(**row))
thiscust = qbolist[qbolist['id']==int(row['QBOID'])].iloc[0]['obj']
thisjson = thiscust.to_json()
if (not thiscust.DisplayName == row['name']):
row['qbodn'] = thiscust.DisplayName
print( "# QBO#{QBOID} has DisplayName '{qbodn}' instead of '{name}'. ".format(**row))
thiscust.DisplayName = row['name']
pcount += 1
changes = True
else:
if (debug): print(" Names match")
if (thiscust.PrimaryEmailAddr and ( thiscust.PrimaryEmailAddr.Address == row['email'] )):
if (debug): print(" Emails are present and match")
# Equal; all good
elif ( thiscust.PrimaryEmailAddr is None and row['email'] == "" ) :
if (debug): print(" Emails are absent and match")
# Quasi-equal. All good.
else :
row['qboemail'] = thiscust.PrimaryEmailAddr.Address if thiscust.PrimaryEmailAddr else "not present"
print( "# QBO #{QBOID} email is '{qboemail}' instead of '{email}'. ".format(**row))
thiscust.PrimaryEmailAddr = EmailAddress()
thiscust.PrimaryEmailAddr.Address = row['email']
pcount += 1
changes=True
if(changes):
if(arguments['--doit']):
print(" # Updating... ")
thiscust.save(qb=qbo_client)
else:
print("# Not fixing, because you said not to (no --doit)")
print("Evaluated '{0}' customers.".format(ccount))
print("Found '{0}' problems.".format(pcount))
if (pcount > ccount):
print("More problems than customers! \nYOU WIN A PRIZE!")
def main():
forward();
# I was thinking we might backpropagate, but so far I think not.
# I guess I'm unbalanced.
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
debug = arguments['--debug']
if (arguments['--qboid']):
arguments['--qboid'] = [ int(x) for x in arguments['--qboid'].split(",")]
if (arguments['--sheetid']):
arguments['--sheetid'] = [ int(x) for x in arguments['--sheetid'].split(",")]
if (debug):
qu.debug=True
hu.debug=True
if (debug): print(arguments)
main()