cnytech

sebd.py

Jun 2nd, 2017
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.05 KB | None | 0 0
  1. #!/Python36
  2. """This script checks the SmartEcho database for the set business date with options to fix database"""
  3.  
  4. # import modules and set initial variables
  5. try:
  6.     import datetime
  7.     import time
  8.     import os
  9.     import sys
  10.     import ctypes
  11.     import logging
  12.     from colorama import init
  13.     from colorama import Fore
  14.     import pypyodbc
  15.     init()
  16.     apptitl = ("sebd.py")
  17.     appvers = ("1.05")
  18.     appname = ("SmartEcho Business Date Checker")
  19.     appupdt = ("06/01/2017 @ 10:17pm")
  20.     logging.basicConfig(filename=apptitl + "." + 'LOG', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p -')
  21.  
  22. except ImportError as ex:
  23.     print("\nImport Error: " + str(ex))
  24.     print("\nAborting application...\n")
  25.     sys.exit()
  26. # set the title of the console
  27. clear = os.system('cls')
  28. title = ctypes.windll.kernel32.SetConsoleTitleW("%s - version %s - updated %s - (%s)" %(appname, appvers, appupdt, apptitl))
  29. logging.debug("started " + apptitl)
  30.  
  31. # connect to the SmartEcho database
  32. try:
  33.     sesqlconn = pypyodbc.connect('Driver={SQL Server}; Server=localhost; Database=SmartEcho_Fuel_100; Trusted_Connection=yes;')
  34.     sesqlcrsr = sesqlconn.cursor()
  35. except pypyodbc.Error as ex:
  36.     sqlstate = ex.args[1]
  37.     if not sqlstate == '1':
  38.         print(Fore.RED + "Database Error" + sqlstate + "\nUnable to connect to the SmartEcho Database\n")
  39.         logging.debug("Database Error" + sqlstate)
  40.     sys.exit()
  41.  
  42. # query SmartEcho database for site name and businessdate
  43. try:
  44.     SQLCommand = ("Select name from Site")
  45.     if sesqlcrsr.execute(SQLCommand):
  46.         print(Fore.YELLOW + "\nSmartEcho Database Connected on " + time.strftime("%B %d %Y @ %H:%M%p" + Fore.CYAN))
  47.         logging.debug("SmartEcho Database Connected")
  48.         sitename = sesqlcrsr.fetchone()
  49.     else:
  50.         pass
  51. except pypyodbc.Error as ex:
  52.     sqlstate = ex.args[1]
  53.     if not sqlstate == '1':
  54.         print(Fore.RED + "Database Error" + sqlstate + "\n\nUnable to connect to the SmartEcho Database\n\n")
  55.         logging.debug("Database Error" + sqlstate)
  56.     sys.exit()
  57.  
  58. try:
  59.     SQLCommand = ("Select businessdate from Site")
  60.     sesqlcrsr.execute(SQLCommand)
  61.     sitebusinessdate = sesqlcrsr.fetchone()
  62.     BusinessDate = sitebusinessdate[0]
  63.     BusinessDateYear = int(BusinessDate // 10000) # year
  64.     BusinessDateMonth = int((BusinessDate // 100) % 100) # month
  65.     BusinessDateDay = int(BusinessDate % 100) # day
  66.     BusinessDateString = str(BusinessDateYear) + "-" + str(BusinessDateMonth)
  67.     BusinessDateString = BusinessDateString + "-" + str(BusinessDateDay)
  68.     now = datetime.date.today()
  69.     nowdate = now.strftime("%Y%m%d")
  70.     FromDate = datetime.date(BusinessDateYear, BusinessDateMonth, BusinessDateDay)
  71.     DateDiff = (now - FromDate).days
  72. except pypyodbc.Error as ex:
  73.     sqlstate = ex.args[1]
  74.     if not sqlstate == '1':
  75.         print("Database Error" + sqlstate + "\n\nUnable to connect to the SmartEcho Database\n\n")
  76.         logging.debug("Database Error" + sqlstate)
  77.         os.system("pause")
  78.         sys.exit()
  79.  
  80. # format message to display in console
  81. strTextBody1 = "\n" + "At " + sitename[0] + " the SmartEcho Business Date is set to "
  82. strTextBody1 = strTextBody1 + BusinessDateString + "\n"
  83. strTextBody1 = strTextBody1 + Fore.RED + "The SmartEcho Business Date is off by " + str(DateDiff,) + " day(s)"
  84. strTextBody1 = strTextBody1 + Fore.CYAN
  85.  
  86. # display message if business date is off otherwise exit
  87. try:
  88.     if not DateDiff == 0:
  89.         print(strTextBody1)
  90.         ynchoice = input("\nWould you like to set the business date to todays date now? [Y/n] ")
  91.         if ynchoice.startswith('y'):
  92.             DateUpdate = ("UPDATE Site SET BusinessDate = " + str(nowdate) + " WHERE BusinessDate = " + str(BusinessDate))
  93.             SQLCommand = DateUpdate
  94.             sesqlcrsr.execute(SQLCommand)
  95.             sesqlcrsr.commit()
  96.             dbynchoice = input("\nWould you like to fix the businessdate columns in the SmartEcho Database now? [Y/n] ")
  97.             if dbynchoice.startswith('y'):
  98.                 try:
  99.                     daysinput = int(input("\nEnter the number of days to go back: "))
  100.                     if daysinput == "":
  101.                         print("\nYou selected nothing - setting to 1 day ")
  102.                         daysinput = 1
  103.                     else:
  104.                         pass
  105.                 except ValueError:
  106.                     print("\nNot a number - setting to 1 day ")
  107.                     daysinput = 1
  108.             else:
  109.                 pass
  110.             daysback = datetime.timedelta(days=int(daysinput))
  111.             qtydaysback = now - daysback
  112.             daytostart = str(qtydaysback)
  113.             print("\nDate to start :" + daytostart)
  114.             os.system("pause")
  115.             try:
  116.                 SQLFileName = 'FixBusinessDate.SQL'
  117.                 if os.path.isfile(SQLFileName):
  118.                     print("\nRunning external SQLCOMMAND... Please Wait")
  119.                     FixBusDateCmd = (r"SQLCMD -E -i .\FixBusinessDate.SQL -o .\BusinessDateFixResults.TXT -v dayendstart=") + daytostart + ("")
  120.                     os.system(FixBusDateCmd)
  121.                     print("\nThe SmartEcho database 'businessdate' columns have been updated.")
  122.                     print("\nYou can check the results in the BusinessDateFixResults.TXT file")
  123.                 else:
  124.                     print("\nFixBusinessDate.SQL file does not exist... aborting")
  125.                     logging.debug("FixBusinessDate.SQL file does not exist")
  126.             except IOError:
  127.                 print("\nRead error.... aborting")
  128.         else:
  129.             pass
  130.     else:
  131.         print(Fore.GREEN + "\nSmartEcho Business Date is already current")
  132.         logging.debug("SmartEcho Business Date is already current")
  133. except SystemExit:
  134.     pass
  135.  
  136. # finish up and close connection to database
  137. try:
  138.     sesqlcrsr.close()
  139.     sesqlconn.close()
  140.     print(Fore.YELLOW + "\nSmartEcho Database Connection Closed")
  141.     logging.debug("SmartEcho Database Connection Closed")
  142.     sys.exit(1)
  143. except SystemExit:
  144.     pass
Advertisement
Add Comment
Please, Sign In to add comment