Files

215 lines
7.3 KiB
Python

'''
Created on Jan 30, 2017
@author: Wes
'''
from alert import send_alert_html
from glob import glob
import os, sys, logging, time, StringIO, datetime
import pyodbc
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import update
RECIPIENTS = ['admin@example.com']
SUBJECT = 'ETA Update Transmitted to Momentum.'
MESSAGE = None
TEST_MODE = False
LOG_LEVEL = logging.DEBUG
ACC_NUMBERS = ['3398', '4318', '5230']
#Yeah.....
#Don't forget to fix account numbers 2215 should be 3398
EXTRACT_QUERY = "select mo.VKTR, mo.VANR, mo.VDAT, mo.VLBLN, mo.VLLFN, SUM(ypp.VYDPERPCE) qty, UKDR, PSFD01, UACPAT, UACCOL from TXUYUF01 mo INNER JOIN TXUYUF01 ypp ON ypp.VBLN = mo.VLBLN AND ypp.VLFN = mo.VLLFN INNER JOIN TXUYUV00 ON mo.VLBLN = UBLN INNER JOIN TXUYAT01 ON UACCNR = UKDR AND UACANR = mo.VANR INNER JOIN TXMYAT03 ON XANR = mo.VANR INNER JOIN TXRYPS00 ON TXMYAT03.XFLX33 = PSPRT AND TXMYAT03.XFLX34 = PSANR AND PSKDN = mo.VKDL and PSKST IN ('COL') WHERE mo.VKDL IN (select KKDN from TXUYKD00 WHERE KKDR IN ('2215', '4318', '5230')) AND mo.VERA NOT LIKE 'E' AND mo.VBLA = 'IB' GROUP BY mo.VKTR, mo.VANR, mo.VDAT, mo.VLBLN, mo.VLLFN, UKDR, PSFD01, UACPAT, UACCOL"
#engine = create_engine("mssql+pyodbc://@jsisbprod", echo=False)
engine = create_engine("mssql+pyodbc://@JTest", echo=False)
Base = declarative_base(engine)
metadata = Base.metadata
logger = None
########################################################################
# SQL Alchemy table declarations. Not sure if I need any for this. #
########################################################################
class TransactionTable(Base):
__tablename__ = 'ftp_trans_numbers'
__table_args__ = {'autoload':True}
#class CSPINV00(Base):
# __tablename__ = 'CSPINV00'
# __table_args__ = {'autoload':True}
def loadSession():
global engine
Session = sessionmaker(bind=engine)
session = Session()
return session
def initializeLogger(name='log'):
global logger
global MESSAGE
#logger = logging.getLogger(__name__)
logger = logging.getLogger(name)
if len(logger.handlers) > 0:
return logger
logger.setLevel(LOG_LEVEL)
handler = logging.FileHandler('D:\\FTP\\logs\\' + name + '.log')
handler.setLevel(LOG_LEVEL)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
#Also send logs > DEBUG to stdout
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
#Capture log messages in a string for e-mail alert
MESSAGE = StringIO.StringIO()
sh = logging.StreamHandler(MESSAGE)
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter)
logger.addHandler(sh)
'''
@todo: Not sure if I'll actually need this. This is the last document that
the AS400 is sending to them. Just in case...
Gotta get transaction number from AS400 until ALL transmissions
are handled on the new system... whoopee
'''
def getTransNumber():
connection = pyodbc.connect(
driver='{iSeries Access ODBC Driver}',
system='SUNBURY',
uid=os.environ['AS400_UID'],
pwd=os.environ['AS400_PWD'])
c1 = connection.cursor()
ret = -1
c1.execute('select * from stmdata.MGTX#FL')
for row in c1:
ret = int(row[1]) + 1
c1.close()
return ret
'''
@todo: Not sure if I'll actually need this. This is the last document that
the AS400 is sending to them. Just in case...
Update the Momentum transaction number in the AS400 database
'''
def updateTransNumber(txnum):
connection = pyodbc.connect(
driver='{iSeries Access ODBC Driver}',
system='SUNBURY',
uid=os.environ['AS400_UID'],
pwd=os.environ['AS400_PWD'],
autocommit=True)
c1 = connection.cursor()
c1.execute('UPDATE STMDATA.MGTX#FL SET MGSEQ# = ' + str(txnum))
c1.close()
def createMomentumETADocument():
global MESSAGE
initializeLogger('MOM_418_GENERATE')
xmission = [] #List of strings, the individual lines of the transmission file that will be sent
if(TEST_MODE):
logger.info('**RUNNING IN TEST MODE**')
else:
logger.info('**RUNNING IN PRODUCTION MODE**')
logger.debug('Connecting to database...')
session = loadSession()
trans_no = -1
# @todo: create method to grab this from new database
trans_no = getTransNumber()
logger.debug('Using transaction number: %s', trans_no)
'''
Main processing loop goes here
'''
current_po = ''
extract = session.execute(EXTRACT_QUERY)
dCount = 0
for row in extract:
#Level break on PO number
if row.VKTR not in current_po:
#dCount will only be zero for the first pass
#Write t record for previous PO
if dCount > 0:
tRec = 'T~%s\n' % (dCount)
xmission.append(tRec)
logger.debug(tRec[:-1])
dCount = 0
#Write new header record
current_po = row.VKTR
hRec = 'H~%s\n' % (current_po)
xmission.append(hRec)
logger.debug(hRec[:-1])
# @todo: bother figuring out date slip reason code? see doc specs...
dateSlipCode = '0'
promiseDate = datetime.datetime.strptime(str(row.VDAT), "%Y%m%d")
pDate = promiseDate.strftime('%m/%d/%y')
quantity = "{0:.3f}".format(row.qty)
dRec = 'D~%s~%s~%s~%s~%s~%s~YDS\n' % (row.PSFD01, row.UACPAT, row.UACCOL, pDate, dateSlipCode, quantity)
xmission.append(dRec)
dCount += 1 #increment dCount, this is the number that is inserted into the T record for each PO
logger.debug(dRec[:-1])
if dCount > 0:
tRec = 'T~%s\n' % (dCount)
xmission.append(tRec)
logger.debug(tRec[:-1])
# @todo: may need to tune this number later
if len(xmission) > 2:
xmission.append('S~' + str(len(xmission)) + '\n')
logger.debug('S~' + str(len(xmission)))
#delete/comment this later
print ''
for row in xmission:
print row[:-1]
#Write transmission data out to file here
logger.info('Creating D:\\FTP\\SEND_MG\\SBR_418_' + str(trans_no) + '.txt')
f = open('SEND_MG\\SBR_418_' + str(trans_no) + '.txt', 'w')
f.writelines(xmission)
f.close()
try:
logger.info('Sending e-mail alert...')
#send_alert_html(RECIPIENTS, SUBJECT, attachments=glob('D:\\FTP\\SEND_MG\\SBR_418_*.txt'), message=MESSAGE.getvalue())
except:
logger.error('Unable to send e-mail. Is the internet out?')
if not TEST_MODE:
#Might as well keep the table in the new database up to date
ex2 = update(TransactionTable.__table__).where(TransactionTable.client.in_(['MOMTEX'])).values(xaction=(trans_no))
session.execute(ex2)
ex2 = None
#updateTransNumber(trans_no) #Update transaction number in AS400
else:
logger.warn('Nothing to send!')
session.close()
MESSAGE.truncate(0)
if __name__ == '__main__':
createMomentumETADocument()