Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

#!/usr/bin/python

'''
Alerts regarding inventory update.
'''

import sys
import MySQLdb
import optparse
import time
import datetime
import smtplib
from email.mime.text import MIMEText


parser = optparse.OptionParser()
usage = "Usage: %prog -H [DB Address]"
parser.add_option("-H", "--host", dest="host",default="",type="string",help="Database Address",metavar="HOST")
(options, args) = parser.parse_args()
if ( not(options.host)):
    print "Fatal: Required arguments are missing!"
    print "Use: -h / --help to get help."
    sys.exit(1)
db = MySQLdb.connect(options.host,"root","shop2020","inventory" )
now = datetime.datetime.now()
cursor = db.cursor()
MESSAGE=[]


def getUpdate(warehouseName,warehouseId,checkInterval):
    
    try:
        print "Warehouse Name:",warehouseName
        print "Warehouse Id:",warehouseId
        print "Time Period:",checkInterval
        print str(now)
        sql = '''SELECT lastCheckedOn FROM warehouse where id=%d''' % \
        (warehouseId)
        cursor.execute(sql)
        data = cursor.fetchone()
        print "Data [0]:",data[0]
        if (data[0] is None):
            print "Inside None if"
            mailText = 'Last Checked On is NULL for '+warehouseName+" Id = "+str(warehouseId)+"\n\n"
            print mailText
            MESSAGE.append(mailText)
        else:
            diffMinutes =int((time.mktime(now.timetuple()) - time.mktime(data[0].timetuple()))/60)
            print "Diff",diffMinutes
        if ( diffMinutes > checkInterval):
            print "Diffcheck"
            mailText = "Warehouse "+warehouseName+" Id = "+str(warehouseId)+" was last checked "+str(diffMinutes)+" minutes ago while its interval is "+str(checkInterval)+" minutes"+"\n\n"
            print mailText
            MESSAGE.append(mailText)
            print "checking timediff"
    
    except:
        "MYSQL Exception"

        
def checkWarehouseHoliday(warehouseHolidays):
    currentDay=str(now.weekday())
    print "Current Day",currentDay
    print "WarehouseHoliday",warehouseHolidays
    if currentDay in warehouseHolidays:
        return True
    else:
        return False
        
def sendMail():
    
    print MESSAGE
    msg = ''.join(MESSAGE)
    smtpServer = smtplib.SMTP('localhost')
    smtpServer.set_debuglevel(1)
    msg = MIMEText(msg)
    sender = 'inventory-monitor@shop2020.in'
    recipients = ['kshitij.sood@shop2020.in', 'amar.kumar@shop2020.in']
    msg['Subject'] = "Warehouse Inventory Monitor"
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    
    try:
        smtpServer.sendmail(sender, recipients, msg.as_string())
        print "Successfully sent email"
    
    except:
        print "Error: unable to send email"
    

def main():
    try:
        sql = '''select * from warehouseMonitor'''
        cursor.execute(sql)
        listWarehouse = cursor.fetchall()
        for warehouse in listWarehouse:
            if ( checkWarehouseHoliday(str(warehouse[3])) ):
                continue
            if ( warehouse[4]==1 ):
                getUpdate(warehouse[1],warehouse[2],warehouse[5])
        if (MESSAGE[0] is not None):
            sendMail()    
    
    except:
        "MYSQL Exception"
    
    finally:
        print "Closing db connection"
        db.close()  
        
if __name__ == "__main__":
    main()