Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.70 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Jun 19 17:39:48 2017
  4.  
  5. @author: Dylan Keyer
  6. """
  7.  
  8. import pyodbc
  9. import logging
  10. import os
  11. import datetime
  12. import itertools
  13.  
  14.  
  15. # uncomment below and specify working directory, if desired
  16. # os.chdir(<ENTER WORKING DIRECTORY FOR SCRIPT HERE>)
  17.  
  18. # set-up the log file
  19. logging.basicConfig(filename='quickbooks.log', level=logging.DEBUG)
  20.  
  21.  
  22. # initiating the an object of the class QuickBooks does not read the data. You need to call the
  23. # class method, self.ReadData() to do that.
  24.  
  25. class QuickBooks():
  26. # initialize our lists -- Pandas could be integrated easily in the future be passing lists to
  27. # the Pandas method, DataFrame, as a dictionary with column names as the keys and the lists as the values
  28. def __init__(self):
  29. self.TransactionID = []
  30. self.PONumber = []
  31. self.TransactionDate = []
  32. self.CustomerName = []
  33. self.Email = []
  34. self.TimeCreated = []
  35. self.InvoiceLineType = []
  36. self.InvoiceLineDesc = []
  37. self.Quantity = []
  38. self.UnitOfMeasure = []
  39. self.Rate = []
  40. self.Amount = []
  41. self.ShipDate = []
  42. self.BillingAddress1 = []
  43. self.BillingAddress2 = []
  44. self.BillingAddress3 = []
  45. self.BillingAddress4 = []
  46. self.BillingAddress5 = []
  47. self.BillingAddressCity = []
  48. self.BillingAddressState = []
  49. self.BillingAddressPostalCode = []
  50. self.BillingAddressCountry = []
  51. self.ShipAddress1 = []
  52. self.ShipAddress2 = []
  53. self.ShipAddress3 = []
  54. self.ShipAddress4 = []
  55. self.ShipAddress5 = []
  56. self.ShipAddressCity = []
  57. self.ShipAddressState = []
  58. self.ShipAddressPostalCode = []
  59. self.ShipAddressCountry = []
  60. self.ShippingMethod = []
  61. self.SalesRepName = []
  62. self.Memo = []
  63.  
  64. # this is a paramterized string, the data will be passed in from self.LookBackDate, defined below
  65. self.SQL = """SELECT InvoiceLine.TxnID, InvoiceLine.PONumber, InvoiceLine.TxnDate,
  66. InvoiceLine.CustomerRefFullName, Customer.Email,
  67. InvoiceLine.TimeCreated, InvoiceLine.InvoiceLineType, InvoiceLine.InvoiceLineDesc,
  68. InvoiceLine.InvoiceLineQuantity, InvoiceLine.InvoiceLineUnitOfMeasure,
  69. InvoiceLine.InvoiceLineRate, InvoiceLine.InvoiceLineAmount, InvoiceLine.ShipDate,
  70. InvoiceLine.BillAddressAddr1, InvoiceLine.BillAddressAddr2, InvoiceLine.BillAddressAddr3,
  71. InvoiceLine.BillAddressAddr4, InvoiceLine.BillAddressAddr5,
  72. InvoiceLine.BillAddressCity, InvoiceLine.BillAddressState,
  73. InvoiceLine.BillAddressPostalCode, InvoiceLine.BillAddressCountry,
  74. InvoiceLine.ShipAddressAddr1,
  75. InvoiceLine.ShipAddressAddr2, InvoiceLine.ShipAddressAddr3, InvoiceLine.ShipAddressAddr4,
  76. InvoiceLine.ShipAddressAddr5, InvoiceLine.ShipAddressCity, InvoiceLine.ShipAddressState,
  77. InvoiceLine.ShipAddressCountry, InvoiceLine.ShipAddressPostalCode, InvoiceLine.ShipMethodRefFullName,
  78. InvoiceLine.SalesRepRefFullName, InvoiceLine.Memo
  79. FROM InvoiceLine
  80. LEFT outer JOIN Customer
  81. ON InvoiceLine.CustomerRefListID = Customer.ListID
  82. WHERE (TxnDate >= {d '%s'})"""
  83.  
  84. # LookBackDate default to five days ago -- change the value of X in timedelta.(days=X) to the number of
  85. # days that you want to look back in the database
  86. self.LookBackDate = (datetime.datetime.today() - datetime.timedelta(days=5)).strftime("%Y-%m-%d")
  87.  
  88. # this class method initiates the log file and the DB connection. It also kicks off the reading of the data
  89. # using self.SQL as the query
  90. def ReadData(self):
  91. # write to log that DB connection is about to occur
  92. logging.info('Checking for new invoices at {}\n'.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
  93. logging.info('Connecting to the Quickbooks Enterprise Database...\n')
  94. # connect string is not necessary since we have a DSN setup on the local machine that is
  95. # going to execute the script (either manually or as a Scheduled Task)
  96.  
  97. try:
  98. conn = pyodbc.connect('DSN=QuickBooks Data', autocommit=True)
  99. cursor = conn.cursor()
  100.  
  101. # query grabs most data from table InvoiceLine, which is left joined with
  102. # table Customer, to get email info
  103. logging.info('Querying the database for invoices from the past FIVE days...')
  104. cursor.execute(str(self.SQL % self.LookBackDate))
  105.  
  106. except Exception as e:
  107. logging.error('The query failed with the following error : {}'.format(e))
  108.  
  109. # initiate row counter, simpler than enumerating over the fetchall method
  110. # this will count number of records returned
  111. ct = 0
  112.  
  113. # print results from the cursor
  114.  
  115.  
  116. all_data = (cursor.fetchall())
  117. key_function = lambda row: row[0]
  118. grouped_data = itertools.groupby(all_data, key_function)
  119. for group in grouped_data:
  120. order_title = ''
  121. order_body = ''
  122. for line in group[1]:
  123. order_body += (str(int(line[8])) + ' X ' + str((line[7])) + '\n')
  124. order_title = (line[3] + ' order ' + line[1])
  125. order_method = ('For ' + line[-3] + '\n')
  126. ship_date = line[12]
  127.  
  128. cursor.close()
  129. conn.close()
  130.  
  131. logging.info('Retrieved {} records...\n\n'.format(str(ct)))
  132.  
  133.  
  134. qb = QuickBooks()
  135. qb.ReadData()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement