-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
580 lines (502 loc) · 25.1 KB
/
Copy pathapp.py
File metadata and controls
580 lines (502 loc) · 25.1 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
from flask import Flask, render_template, request, redirect, url_for, session, flash
import os
import requests
import urllib.parse
import json
from functools import wraps
from config import (
QB_CLIENT_ID, QB_CLIENT_SECRET, QB_REDIRECT_URI, QB_BASE_URL,
QB_OAUTH_URL, QB_GRAPHQL_URL, QB_AUTH_URL, QB_ENVIRONMENT, IS_SANDBOX,
get_headers, get_deep_link
)
app = Flask(__name__,
static_folder='static',
static_url_path='/static',
template_folder='templates')
# Configure session
app.secret_key = os.urandom(24)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['PERMANENT_SESSION_LIFETIME'] = 3600 # 1 hour
app.config['SESSION_COOKIE_SECURE'] = False # Set to False for development
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
# Clear session on startup
@app.before_request
def clear_session():
pass # Removed flash message clearing
@app.route('/')
def index():
token = session.get("oauth_token")
realm_id = session.get("realm_id")
customers = session.get("customers", [])
items = session.get("items", [])
custom_dimensions = session.get("custom_dimensions", [])
custom_dimension_values = session.get("custom_dimension_values", [])
if not token or not realm_id:
return render_template('index.html', token=None, custom_dimensions=[])
dimensions_fetched = session.get('dimensions_fetched', False)
return render_template('index.html',
token=token,
customers=customers,
items=items,
custom_dimensions=custom_dimensions,
custom_dimension_values=custom_dimension_values,
dimensions_fetched=dimensions_fetched)
# Fetch active customers from QuickBooks Online
def fetch_customers(token, realm_id):
customers = []
if token and realm_id:
headers = get_headers(token['access_token'])
import urllib.parse
customer_url = f"{QB_BASE_URL}/{realm_id}/query"
query_str = urllib.parse.urlencode({"query": "SELECT * FROM Customer WHERE Active = true MAXRESULTS 10"})
full_url = f"{customer_url}?{query_str}"
try:
resp = requests.get(full_url, headers=headers)
resp_json = resp.json()
if resp.status_code == 200 and 'QueryResponse' in resp_json:
customers = resp_json['QueryResponse'].get('Customer', [])[:10]
# Store customers in session
session['customers'] = customers
except Exception as e:
flash(f"Error fetching customers: {str(e)}", "danger")
return customers
# Fetch active items/products from QuickBooks Online
def fetch_items(token, realm_id):
items = []
if token and realm_id:
headers = get_headers(token['access_token'])
import urllib.parse
item_url = f"{QB_BASE_URL}/{realm_id}/query"
query_str = urllib.parse.urlencode({"query": "SELECT * FROM Item WHERE Active = true MAXRESULTS 10"})
full_url = f"{item_url}?{query_str}"
try:
resp = requests.get(full_url, headers=headers)
resp_json = resp.json()
if resp.status_code == 200 and 'QueryResponse' in resp_json:
items = resp_json['QueryResponse'].get('Item', [])[:10]
# Store items in session
session['items'] = items
except Exception as e:
flash(f"Error fetching items: {str(e)}", "danger")
return items
# Fetch custom dimension definitions from QuickBooks using GraphQL API
def fetch_custom_dimensions(token, realm_id):
custom_dimensions = []
if token and realm_id:
headers = get_headers(token['access_token'])
# Read GraphQL query from file
try:
with open(os.path.join(app.static_folder, 'graphql', 'query_custom_dimensions.graphql'), 'r') as file:
query = file.read()
except Exception as e:
error_msg = f"Failed to read GraphQL query file: {str(e)}"
print(error_msg)
flash(error_msg, "danger")
return custom_dimensions
payload = {"query": query}
try:
print("Sending GraphQL request for custom dimensions...")
resp = requests.post(QB_GRAPHQL_URL, json=payload, headers=headers)
print(f"Custom dimensions response status: {resp.status_code}")
resp_json = resp.json()
print(f"Custom dimensions response : {resp_json}")
# Handle GraphQL errors first - they can occur even with 200 status
if resp_json.get('errors'):
errors = resp_json['errors']
print(f"Custom dimensions GraphQL errors: {errors}")
for error in errors:
error_message = error.get('message', 'Unknown GraphQL error')
error_code = error.get('extensions', {}).get('code', 'UNKNOWN')
error_path = error.get('path', [])
print(f"GraphQL Error [{error_code}] at {error_path}: {error_message}")
# Provide user-friendly error messages based on error codes
if 'FORBIDDEN' in error_code or 'UNAUTHORIZED' in error_code:
flash(f"Access denied: {error_message}. Please check your app permissions.", "danger")
elif 'INVALID_SCOPE' in error_code:
flash(f"Scope error: {error_message}. Custom dimensions scope may not be enabled.", "warning")
else:
flash(f"GraphQL Error: {error_message}", "danger")
# If there are errors and no data, return early
if not resp_json.get('data') or resp_json['data'].get('appFoundationsActiveCustomDimensionDefinitions') is None:
return custom_dimensions
if resp.status_code == 200 and resp_json.get('data'):
data = resp_json['data']
if data.get('appFoundationsActiveCustomDimensionDefinitions') and data['appFoundationsActiveCustomDimensionDefinitions'] is not None:
edges = data['appFoundationsActiveCustomDimensionDefinitions']['edges']
print(f"Found {len(edges)} custom dimension edges")
if len(edges) == 0:
flash("No custom dimensions found, create dimensions in your QBO first", "danger")
else:
print("appFoundationsActiveCustomDimensionDefinitions is None or missing")
edges = []
for edge in edges:
node = edge['node']
if node.get('active', False):
custom_dimension = {
'id': node['id'],
'label': node['label'],
'active': node['active'],
'selected': True
}
custom_dimensions.append(custom_dimension)
print(f"Added custom dimension: {custom_dimension}")
else:
# Handle cases where status is not 200 or no data returned
if resp.status_code != 200:
error_msg = f"HTTP {resp.status_code}: Failed to fetch custom dimensions"
print(error_msg)
flash(error_msg, "danger")
elif not resp_json.get('data') and not resp_json.get('errors'):
error_msg = "No custom dimensions data returned from GraphQL"
print(error_msg)
flash(error_msg, "warning")
except Exception as e:
print(f"Exception fetching custom dimensions: {str(e)}")
flash(f"Error fetching custom dimensions: {str(e)}", "danger")
return custom_dimensions
# Fetch values for a specific custom dimension using GraphQL API
def fetch_custom_dimension_values(token, realm_id, definition_id):
custom_dimension_values = []
if token and realm_id and definition_id:
headers = get_headers(token['access_token'])
# Read GraphQL query from file
try:
query_file_path = os.path.join(app.static_folder, 'graphql', 'query_custom_dimension_values.graphql')
print(f"Reading GraphQL query from: {query_file_path}")
with open(query_file_path, 'r') as file:
query = file.read().strip()
print(f"Query content length: {len(query)}")
print(f"Query content: {query[:100]}...") # First 100 chars
except Exception as e:
error_msg = f"Failed to read GraphQL query file: {str(e)}"
print(error_msg)
flash(error_msg, "danger")
return custom_dimension_values
# Read variables template from file
try:
with open(os.path.join(app.static_folder, 'graphql', 'custom_dimension_values_variables.json'), 'r') as file:
variables_template = json.load(file)
# Replace the placeholder with actual value
variables_template['filters']['definitionId'] = definition_id
print(f"Variables template: {json.dumps(variables_template, indent=2)}")
except Exception as e:
error_msg = f"Failed to read variables template file: {str(e)}"
print(error_msg)
flash(error_msg, "danger")
return custom_dimension_values
payload = {
"query": query,
"variables": variables_template
}
try:
print("Sending GraphQL request for custom dimension values...")
resp = requests.post(QB_GRAPHQL_URL, json=payload, headers=headers)
print(f"Custom dimension values response status: {resp.status_code}")
print(f"Custom dimension values response: {resp.text}")
resp_json = resp.json()
print(f"Custom dimension values response JSON: {resp_json}")
# Handle GraphQL errors first - they can occur even with 200 status
if resp_json.get('errors'):
errors = resp_json['errors']
print(f"Custom dimension values GraphQL errors: {errors}")
for error in errors:
error_message = error.get('message', 'Unknown GraphQL error')
error_code = error.get('extensions', {}).get('code', 'UNKNOWN')
error_path = error.get('path', [])
print(f"GraphQL Error [{error_code}] at {error_path}: {error_message}")
# Provide user-friendly error messages based on error codes
if 'FORBIDDEN' in error_code or 'UNAUTHORIZED' in error_code:
flash(f"Access denied: {error_message}. Please check your app permissions.", "danger")
elif 'INVALID_SCOPE' in error_code:
flash(f"Scope error: {error_message}. Custom dimensions scope may not be enabled.", "warning")
elif 'NOT_FOUND' in error_code:
flash(f"Dimension not found: {error_message}. The dimension may have been deleted.", "warning")
else:
flash(f"GraphQL Error: {error_message}", "danger")
# If there are errors but also data, continue processing
if not resp_json.get('data'):
return custom_dimension_values
if resp.status_code == 200 and resp_json.get('data'):
edges = resp_json['data']['appFoundationsActiveCustomDimensionValues']['edges']
print(f"Found {len(edges)} custom dimension value edges")
for edge in edges:
node = edge['node']
if node.get('active', False):
custom_dimension_value = {
'id': node['id'],
'definitionId': node['definitionId'],
'label': node['label'],
'active': node['active'],
'parentId': node.get('parentId'),
'fullyQualifiedLabel': node.get('fullyQualifiedLabel'),
'level': node.get('level'),
'selected': True
}
custom_dimension_values.append(custom_dimension_value)
print(f"Added custom dimension value: {custom_dimension_value}")
else:
# Handle cases where status is not 200 or no data returned
if resp.status_code != 200:
error_msg = f"HTTP {resp.status_code}: Failed to fetch custom dimension values"
print(error_msg)
flash(error_msg, "danger")
elif not resp_json.get('data') and not resp_json.get('errors'):
error_msg = "No custom dimension values data returned from GraphQL"
print(error_msg)
flash(error_msg, "warning")
except Exception as e:
print(f"Exception fetching custom dimension values: {str(e)}")
flash(f"Error fetching custom dimension values: {str(e)}", "danger")
return custom_dimension_values
@app.route('/fetch_dimensions')
def fetch_dimensions():
"""Fetch custom dimensions when user clicks the fetch button"""
token = session.get("oauth_token")
realm_id = session.get("realm_id")
if not token or not realm_id:
flash("Please connect to QuickBooks first.", "danger")
return redirect(url_for('index'))
try:
print("Fetching custom dimensions...")
custom_dimensions = fetch_custom_dimensions(token, realm_id)
session['custom_dimensions'] = custom_dimensions
print(f"Fetched {len(custom_dimensions)} custom dimensions")
# Fetch custom dimension values for each dimension
all_custom_dimension_values = []
for dimension in custom_dimensions:
if dimension.get('active', False):
print(f"Fetching custom dimension values for dimension ID: {dimension['id']}")
dimension_values = fetch_custom_dimension_values(token, realm_id, dimension['id'])
all_custom_dimension_values.extend(dimension_values)
print(f"Fetched {len(dimension_values)} values for dimension: {dimension['label']}")
session['custom_dimension_values'] = all_custom_dimension_values
session['dimensions_fetched'] = True
print(f"Total custom dimension values fetched: {len(all_custom_dimension_values)}")
except Exception as e:
print(f"Error fetching custom dimensions: {str(e)}")
flash(f"Error fetching custom dimensions: {str(e)}", "danger")
return redirect(url_for('index'))
@app.route("/login")
def login():
scopes = [
"com.intuit.quickbooks.accounting",
"app-foundations.custom-dimensions.read"
]
params = {
"response_type": "code",
"client_id": QB_CLIENT_ID,
"redirect_uri": QB_REDIRECT_URI,
"scope": " ".join(scopes),
"state": "random_state_123", # Send state but don't validate
"locale": "en-us"
}
encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
auth_url = f"{QB_AUTH_URL}?{encoded_params}"
return redirect(auth_url)
# OAuth callback route - handles response from QuickBooks authorization
@app.route("/callback")
def callback():
# Log all callback parameters for debugging
print(f"Callback parameters: {dict(request.args)}")
# Check for OAuth errors
error = request.args.get('error')
error_description = request.args.get('error_description')
if error:
if error == "invalid_scope":
error_msg = f"OAuth Error: {error} - {error_description}. Please ensure you have enabled dimension scope for your app"
else:
error_msg = f"OAuth Error: {error} - {error_description}"
print(f"OAuth Error in callback: {error_msg}")
flash(error_msg, "danger")
return render_template('index.html', token=None, custom_dimensions=[])
auth_code = request.args.get('code')
realm_id = request.args.get('realmId')
# Check if we already have a valid session to prevent reusing auth codes
existing_token = session.get('oauth_token')
existing_realm = session.get('realm_id')
if existing_token and existing_realm == realm_id:
print("Valid session already exists, redirecting to index")
return redirect(url_for('index'))
if not auth_code or not realm_id:
error_msg = "Missing code or realmId in callback"
print(f"Missing parameters: {error_msg}")
flash(error_msg, "danger")
return render_template('index.html', token=None, custom_dimensions=[])
# Check if this auth code was already processed
processed_code = session.get('processed_auth_code')
if processed_code == auth_code:
print("Authorization code already processed, redirecting to index")
return redirect(url_for('index'))
headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
auth = (QB_CLIENT_ID, QB_CLIENT_SECRET)
data = {
"grant_type": "authorization_code",
"code": auth_code,
"redirect_uri": QB_REDIRECT_URI
}
try:
print(f"Token request data: {data}")
resp = requests.post(QB_OAUTH_URL, headers=headers, data=data, auth=auth)
print(f"Token response status: {resp.status_code}")
print(f"Token response: {resp.text}")
if resp.status_code == 200:
token_json = resp.json()
# Store token data in session
session['oauth_token'] = {
'access_token': token_json.get('access_token'),
'refresh_token': token_json.get('refresh_token'),
'id_token': token_json.get('id_token'),
'expires_in': token_json.get('expires_in'),
}
session['realm_id'] = realm_id
session['processed_auth_code'] = auth_code # Mark this code as processed
# Initialize all session data after successful authentication
print("Fetching customers...")
customers = fetch_customers(session['oauth_token'], realm_id)
# Store only essential fields to keep session size small
session['customers'] = [{'Id': c.get('Id'), 'DisplayName': c.get('DisplayName')} for c in customers]
print(f"Fetched {len(customers)} customers")
print("Fetching items...")
items = fetch_items(session['oauth_token'], realm_id)
# Store only essential fields to keep session size small
session['items'] = [{'Id': i.get('Id'), 'Name': i.get('Name')} for i in items]
print(f"Fetched {len(items)} items")
# Don't fetch custom dimensions automatically - wait for user to click fetch button
session['custom_dimensions'] = []
session['custom_dimension_values'] = []
session['dimensions_fetched'] = False
print("Custom dimensions will be fetched when user clicks fetch button")
# Custom dimension values will be fetched when dimensions are fetched
flash("Successfully authenticated with QuickBooks!", "success")
# Redirect to index to clean up URL and prevent reprocessing
return redirect(url_for('index'))
else:
error_msg = f"Failed to get tokens. Status: {resp.status_code}, Response: {resp.text}"
print(f"Token request failed: {error_msg}")
flash(error_msg, "danger")
return render_template('index.html', token=None, custom_dimensions=[])
except Exception as e:
error_msg = f"Exception during OAuth token exchange: {str(e)}"
print(f"Exception in callback: {error_msg}")
flash(error_msg, "danger")
return render_template('index.html', token=None, custom_dimensions=[])
@app.route("/create_invoice", methods=["POST"])
def create_invoice():
session.pop('invoice_id', None)
session.pop('invoice_deep_link', None)
amount = request.form.get("amount")
token = session.get("oauth_token")
realm_id = session.get("realm_id")
custom_dimension_id = request.form.get("custom_dimension_id")
custom_dimension_value = request.form.get("custom_dimension_value")
customer_id = request.form.get("customer_id")
item_id = request.form.get("item_id")
item_name = request.form.get("item_name")
if not token or not realm_id or not custom_dimension_id or not custom_dimension_value or not customer_id or not item_id:
flash("Connect to QuickBooks and select all required fields.", "danger")
return redirect(url_for('index'))
headers = get_headers(token['access_token'])
headers["Accept-Encoding"] = "gzip, deflate"
url = f"{QB_BASE_URL}/{realm_id}/invoice?minorversion=75"
# Build invoice data structure with custom dimension
data = {
"Line": [
{
"Amount": float(amount),
"DetailType": "SalesItemLineDetail",
# Add custom dimension to invoice line
"CustomExtensions": [
{
"AssociatedValues": [
{
"Value": custom_dimension_value,
"Key": custom_dimension_id
}
],
"ExtensionType": "DIMENSION"
}
],
"SalesItemLineDetail": {
"ItemRef": {"value": item_id, "name": item_name}
}
}
],
"CustomerRef": {"value": customer_id}
}
try:
print(f"Sending invoice creation request to: {url}")
print(f"Request data: {json.dumps(data, indent=2)}")
resp = requests.post(url, json=data, headers=headers)
print(f"Invoice creation response status: {resp.status_code}")
print(f"Invoice creation response: {resp.text}")
if resp.status_code == 200:
resp_json = resp.json()
if 'Invoice' in resp_json and 'Id' in resp_json['Invoice']:
inv_id = resp_json['Invoice']['Id']
session['invoice_id'] = inv_id
# Create deep link (automatically uses correct environment)
deep_link = get_deep_link(inv_id, realm_id)
session['invoice_deep_link'] = deep_link
flash(f"Success! Invoice created with ID: {inv_id}", "success")
else:
error_msg = "Invoice created but ID not found in response"
print(error_msg)
print(f"Response JSON: {json.dumps(resp_json, indent=2)}")
flash(error_msg, "warning")
else:
error_msg = f"Failed to create invoice. Status: {resp.status_code}, Response: {resp.text}"
print(error_msg)
flash(error_msg, "danger")
except requests.exceptions.ContentDecodingError as e:
error_msg = f"Error creating invoice: Content decoding error - {str(e)}"
print(error_msg)
flash(error_msg, "danger")
except Exception as e:
error_msg = f"Error creating invoice: {str(e)}"
print(error_msg)
flash(error_msg, "danger")
return redirect(url_for('index'))
@app.route('/get_dimension_values/<dimension_id>')
def get_dimension_values(dimension_id):
token = session.get("oauth_token")
realm_id = session.get("realm_id")
if not token or not realm_id:
return {"error": "Not authenticated"}, 401
try:
dimension_values = fetch_custom_dimension_values(token, realm_id, dimension_id)
return {"values": dimension_values}
except Exception as e:
return {"error": str(e)}, 500
@app.route('/disconnect')
def disconnect():
"""Disconnect the app from QuickBooks using the disconnect API endpoint"""
session.clear()
flash('Successfully logged out', 'success')
return redirect(url_for('index'))
def get_api_headers(token):
return {
"Authorization": f"Bearer {token}",
"Accept": "application/json",
"Content-Type": "application/json"
}
def validate_quickbooks_session():
token = session.get("oauth_token")
realm_id = session.get("realm_id")
if not token or not realm_id:
flash("Please connect to QuickBooks first.", "danger")
return None, None
return token, realm_id
class QuickBooksAPI:
def __init__(self, token, realm_id):
self.token = token
self.realm_id = realm_id
self.headers = get_api_headers(token)
def make_request(self, method, endpoint, data=None):
# Common request handling logic
pass
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5002, debug=True)