예제 #1
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email') #email of current user

	try:
		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if email is None:
			print "Location: login.py?redirect=1\r\n"

		cur = con.cursor()
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user_= cur.fetchone() 
		
		sidebar = utilities.getSideBar(email, user_[9], cur)
		print display("checkout.html").render(sidebar=sidebar,user=user_)
		sess.close()

	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #2
0
def main():
    form = cgi.FieldStorage()

    password = form.getvalue('password')
    cpass = form.getvalue('confpwd')
    fname = form.getvalue('fname')
    lname = form.getvalue('lname')
    email = form.getvalue('email')
    email_exists = False
    
    #From registration, verifies that password and cpass are the same
    if(password != cpass):
        print "Location: index.py?redirect=1\r\n"
    else:
        try:
            cur = con.cursor()
            # From registration, verifies if email is unique
            command = "SELECT email FROM Users"
            cur.execute(command)
            for i in range(cur.rowcount):
                row = cur.fetchone()
                if(email == row[0]):
                    email_exists = True

        except mdb.Error, e:
            if con:
                con.rollback()
        if email_exists:
            print "Location: index.py?redirect=0\r\n"
        else:
            register(fname, lname, email, password)
예제 #3
0
def main():
	try:
		form = cgi.FieldStorage()
		email= form.getvalue('email')
		password = form.getvalue('password')
		
		cur = con.cursor()
		command = "SELECT password FROM Users WHERE email = %s";
		cur.execute(command, (email))
		row = cur.fetchone()
		
		if (row != None):
			enc_password = row[0]
			verify = sha512_crypt.verify(password, enc_password)
			if (verify):
				sess = session.Session(expires=365*24*60*60, cookie_path='/')
				sess.data['lastvisit'] = repr(time.time())
				sess.data['user'] = email
				print "Location: home.py?\r\n"
			else:
				print "Location: login.py?redirect=0\r\n"
		else:
			print "Location: login.py?redirect=0\r\n"
	except KeyError:
		print "Location: login.py\r\n"
예제 #4
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email')
	search = form.getvalue('search')
	genre = form.getvalue('genre')

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user= cur.fetchone()

		titles = []
		
		if(search != None):
			put = "ISBN, Title, Price, Publisher, Description, Image"
			command = "SELECT " + put + " from ComicBooks NATURAL JOIN BookWriter NATURAL JOIN Writers WHERE WriterName LIKE '%" + search + "%'"
			cur.execute(command)
			rows = cur.fetchall()
			for row in rows:
				if row not in titles:
					titles.append(row)

			command = "SELECT " + put + " from ComicBooks WHERE ISBN LIKE '%" + search + "%'"
			cur.execute(command)
			rows = cur.fetchall()
			for row in rows:
				if row not in titles:
					titles.append(row)

			command = "SELECT " + put + " from ComicBooks WHERE Title LIKE '%" + search + "%'"
			cur.execute(command)
			rows = cur.fetchall()
			for row in rows:
				if row not in titles:
					titles.append(row)

		
		else:
			search = " "
		
		sidebar = utilities.getSideBar(email, user[9], cur)	
		print display("home.html").render(user=user,titles=titles,sidebar=sidebar,genre=genre,search=search)
		sess.close()

	except mdb.Error, e:
	    if con:
	        con.rollback()
	    print "Location: login.py?error=1"
예제 #5
0
def register(fname, lname, email, password):
    enc_password = sha512_crypt.encrypt(password) 

    command = "INSERT INTO Users(FirstName, LastName, Email, Password, DateJoined) VALUES(%s, %s, %s, %s, NOW())"
    try:
        cur = con.cursor()
        cur.execute(command, (fname, lname, email, enc_password))      
        con.commit()

    except mdb.Error, e:
        if con:
            con.rollback()
예제 #6
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email')
	genre = form.getvalue('genre')
	publisher = form.getvalue('publisher')

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user = cur.fetchone()

		if(genre != None):
			command = "SELECT * from ComicBooks NATURAL JOIN BookGenre WHERE Genre='" + genre + "'"
		elif (publisher != None) :
			command = "SELECT * from ComicBooks WHERE Publisher='" + publisher + "'"
		else:
			command = "SELECT * from ComicBooks"
			
		cur.execute(command)
		rows = cur.fetchall()
		titles = []
		for row in rows:
			titles.append(row)

		genre_ = [None, None]
		if (genre != None):
			command = "SELECT * FROM Genres WHERE Genre = '" + genre + "'";
			cur.execute(command)
			genre_ = cur.fetchone()

		sidebar = utilities.getSideBar(email, user[9], cur)
		print display("home.html").render(user=user,titles=titles,sidebar=sidebar,genre=genre_[0],genredesc=genre_[1],search=' ',publisher=publisher)
		sess.close()
	
	except mdb.Error, e:
	    if con:
	        con.rollback()
	    print "Location: login.py?error=1"
예제 #7
0
def main():
    form = cgi.FieldStorage()
    isbn = form.getvalue("ISBN")

    try:
        cur = con.cursor()

        sess = session.Session(expires=365 * 24 * 60 * 60, cookie_path="/")
        lastvisit = sess.data.get("lastvisit")
        email = sess.data.get("user")
        print sess.cookie

        if email is None:
            print "Location: login.py?redirect=1\r\n"

        command = "SELECT * FROM Users WHERE Email = '" + email + "'"
        cur.execute(command)
        user = cur.fetchone()

        command = "DELETE FROM ComicBooks Where ISBN = '" + isbn + "'"
        cur.execute(command)
        con.commit()

        command = "SELECT * from ComicBooks"
        cur.execute(command)
        rows = cur.fetchall()
        titles = []
        for row in rows:
            titles.append(row)

        sidebar = utilities.getSideBar(email, user[9], cur)
        successMsg = "<strong>Success:</strong> Comic Book '" + isbn + "' has been deleted."
        print display("home.html").render(
            user=user, titles=titles, sidebar=sidebar, search=" ", genre=None, publisher=None, success=successMsg
        )
        sess.close()

    except mdb.Error, e:
        if con:
            con.rollback()

            sidebar = utilities.getSideBar(email, user[9], cur)
        print "Location: comic-book-item.py?ISBN=" + isbn + "&error=0\r\n"
예제 #8
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email')
	action = form.getvalue('action')
	title = form.getvalue('title')
	desc = form.getvalue('desc')
	format = form.getvalue('format')
	length = form.getvalue('length')
	publisher = form.getvalue('publisher')
	datepub = form.getvalue('datepub')
	price = form.getvalue('price')
	awards = form.getvalue('awards')
	isbn = form.getvalue('ISBN')
	genres = form.getlist('genres')
	illustrators= form.getlist('illustrators')
	writers= form.getlist('writers')
	stock = form.getvalue('stock')

	try:
		state = "update"
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user= cur.fetchone()

		if desc != None:
			desc = desc.replace('\r\n', '<br>')

		if action == "edit":
			bookform = []
			if isbn != None :
				bookform = []
				command = "SELECT * FROM  ComicBooks where ISBN='" + isbn + "'";
				cur.execute(command)
				book = cur.fetchone()
				for i in book:
					bookform.append(i)
				bookform[4] = bookform[4].strip() 

				awards = []
				command = "SELECT Award from LiteraryAwards WHERE ISBN='" + isbn + "'"
				cur.execute(command)
				award = cur.fetchall()
				for i in range(len(award)):
					award_ = award[i][0].strip()
					awards.append(award_)
				bookform.append(awards)

				command = "SELECT WriterName from BookWriter WHERE ISBN='" + isbn + "'"
				cur.execute(command)
				rows = cur.fetchall()

				writers_= []
				for row in rows:
					writers_.append(row[0])
				writers = utilities.getWriters(writers_, cur)

				command = "SELECT IllustratorName from BookIllustrator WHERE ISBN='" + isbn + "'"
				cur.execute(command)
				rows = cur.fetchall()

				illustrators_= []
				for row in rows:
					illustrators_.append(row[0])
				illustrators = utilities.getIllustrators(illustrators_, cur)

				command = "SELECT Genre from ComicBooks NATURAL JOIN BookGenre WHERE ISBN ='" + book[0] + "'"
				cur.execute(command)
				rows = cur.fetchall()
				genres_= []
				for row in rows:
					genres_.append(row[0])
				genres = utilities.getGenres(genres_, cur)
			else :
				writers = utilities.getWriters([], cur)	
				illustrators = utilities.getIllustrators([], cur)
				genres = utilities.getGenres([], cur)

			sidebar = utilities.getSideBar(email, user[9], cur)
			print display("comic-book-create-update.html").render(state=state,user=user,sidebar=sidebar,bookform=bookform,genres=genres,writers=writers,illustrators=illustrators)
			return

		elif action == "save":

			update_command = "UPDATE ComicBooks SET "
			
			update_command = update_command + " Format = '" + format + "' "
			update_command = update_command + ", Title = '" + title + "' "
			update_command = update_command + ", Length = '" + length + "' "
			update_command = update_command + ", Publisher = '" + publisher + "' "
			update_command = update_command + ", DatePublished = '" + datepub + "' "
			update_command = update_command + ", Price = '" + price + "' "
			update_command = update_command + ", Stock = '" + stock + "' "

			if desc is None:
				 update_command = update_command + ", Description = null "
			else :
				update_command = update_command + """, Description = " """ + desc + """ " """	

			# upload image is user specified
			if form.has_key('image_file'):
				fileitem = form['image_file']
				if fileitem.file:
					extension = os.path.splitext(fileitem.filename)[1] 
					if extension != '' :
						fout = file ("model/images/cover-" +  isbn + extension , 'wb')
						while 1:
							chunk = fileitem.file.read(100000)
							if not chunk: 
								break
							fout.write(chunk)
						fout.close()
						update_command = update_command + ", Image = '" + "model/images/cover-" + isbn + extension  + "' "

			update_command =  update_command + " WHERE ISBN = '" + isbn +  "'"
			cur.execute(update_command)

			command = "DELETE FROM LiteraryAwards Where ISBN = '" + isbn +  "'";
			cur.execute(command)
			
			if awards != None:
				awards = awards.split(',')
				for award in awards:
					insert_command = "INSERT INTO LiteraryAwards(ISBN, Award) VALUES "
					insert_command =  insert_command + "( '" + isbn + """' , " """ + award + """ ")"""
					cur.execute(insert_command)
					con.commit() 

			command = "DELETE FROM BookGenre Where ISBN = '" + isbn +  "'";		
			cur.execute(command)
			con.commit()
			
			if genres is not None:
				for genre in genres:
					insert_command = "INSERT INTO BookGenre(ISBN, Genre) VALUES "
					insert_command =  insert_command + "( '" + isbn + "' , '" + genre + "')"
					cur.execute(insert_command)

			command = "DELETE FROM BookIllustrator Where ISBN = '" + isbn +  "'";		
			cur.execute(command)
			
			if illustrators is not None:
				for illustrator in illustrators:
					insert_command = "INSERT INTO BookIllustrator(ISBN, IllustratorName) VALUES "
					insert_command =  insert_command + "( '" + isbn + "' , '" + illustrator + "')"
					cur.execute(insert_command)

			command = "DELETE FROM BookWriter Where ISBN = '" + isbn +  "'";		
			cur.execute(command)
			
			if writers is not None:
				for writer in writers:
					insert_command = "INSERT INTO BookWriter(ISBN, WriterName) VALUES "
					insert_command =  insert_command + "( '" + isbn + "' , '" + writer + "')"
					cur.execute(insert_command)
			con.commit() 
			
			print "Location: comic-book-item.py?ISBN=" + isbn + "&success=1\r\n"
			
	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #9
0
def main():
	form = cgi.FieldStorage()
	
	userprof = form.getvalue('user') #email of userprofile
	userprofile = form.getvalue('user')
	#email = form.getvalue('email') #email of current user
	firstname = form.getvalue('first_name')
	lastname = form.getvalue('last_name')
	current_password = form.getvalue('current_password')
	new_password = form.getvalue('new_password')
	country = form.getvalue('country')
	birthdate = form.getvalue('birth_date')
	is_administrator = form.getvalue('is_administrator') 	

	#TODO: If current user != email 

	try:

		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		update_command = "UPDATE Users SET FirstName = '" + firstname + "', LastName = '" + lastname + "' "

		# check if password changed
		if current_password != new_password :
			enc_password = sha512_crypt.encrypt(new_password)
			update_command = update_command + ", Password = '******' "

		# set country
		if country is None:
			update_command = update_command + ", Country = null "
		else :
			update_command = update_command + ", Country = '" + country + "' " 

		# set birth date
		if birthdate is None:
			update_command = update_command + ", Birthdate = null "
		else :
			update_command = update_command + ", Birthdate = '" + birthdate + "' "

		# upload image is user specified
 		if form.has_key('image_file'):
			
    			fileitem = form['image_file']
    			if fileitem.file :
				extension = os.path.splitext(fileitem.filename)[1] 
				if extension != '' :
					fout = file ("model/users/" +  userprof + extension , 'wb')
    					while 1:
        					chunk = fileitem.file.read(100000)
        					if not chunk: break
        					fout.write(chunk)
    					fout.close()
					update_command = update_command + ", Image = '" + "model/users/" +  userprof + extension  + "' "
		
		# set is administrator
		if is_administrator is not None:
			update_command = update_command + ", IsAdmin = '" + is_administrator + " '"

		update_command = update_command + "WHERE Email = '" + userprof + "'"
		cur.execute(update_command)
		con.commit() 
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user= cur.fetchone() #

		command = "SELECT * FROM Users WHERE Email = '" + userprof + "'";
		cur.execute(command)
		userprof = cur.fetchone() #

		command = "SELECT * from ComicBooks NATURAL JOIN UserCart WHERE Email='" + email + "'"
		
		cur.execute(command)
		rows = cur.fetchall()
		titles = []
		for row in rows:
			titles.append(row)

		
		# Retrieve Pending Orders
                command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, Status " + \
                          "FROM Orders o, BookOrder bo, ComicBooks cb " + \
                          "WHERE o.OrderID = bo.OrderID " + \
                          "  AND bo.ISBN = cb.ISBN " + \
                          "  AND o.Status in ('Paid', 'Shipped') " + \
                          "  AND o.CustomerEmail = '" + userprofile + "' " + \
                          "ORDER BY OrderDate DESC"
                cur.execute(command)
                rows = cur.fetchall()
                pendingOrders = []
                i=0
                while i < len(rows) :
                	j = i + 1
                        bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
                                   ' (' +str(rows[i][3]) +  ')</a>'
                        while j < len(rows) and (rows[i][0]==rows[j][0]):
                        	bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
                                           str(rows[j][4]) + ' (' +str(rows[j][3]) +  ')</a>'
                                j = j + 1
                        pendingOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], rows[i][6]] )
                       	i = j


		# Retrieve 3 Latest Completed Orders
                command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, Status " + \
                          "FROM BookOrder bo, ComicBooks cb, " + \
                          "(SELECT OrderID, OrderDate, DeliveryAddress, Status " + \
                           "FROM Orders WHERE Status in ('Delivered', 'Canceled') AND CustomerEmail = '" + userprofile + "' " + \
                           "ORDER BY OrderDate DESC LIMIT 3) o " + \
                           "WHERE o.OrderID = bo.OrderID AND bo.ISBN = cb.ISBN"
                cur.execute(command)
                rows = cur.fetchall()
                completedOrders = []
                i=0
                while i < len(rows) :
                	j = i + 1
                        bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
                                   ' (' +str(rows[i][3]) +  ')</a>'
                        while j < len(rows) and (rows[i][0]==rows[j][0]):
                        	bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
                                           str(rows[j][4]) + ' (' +str(rows[j][3]) +  ')</a>'
                                j = j + 1
                        completedOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], rows[i][6]] )
                        i = j
	
		sidebar = utilities.getSideBar(email,user[9], cur)
		successmsg = '<strong>Success:</strong> User Profile has been updated.'
		print display("user-profile.html").render(user=user,userprof=userprof,sidebar=sidebar,titles=titles,pendingOrders=pendingOrders,completedOrders=completedOrders,success=successmsg)
		sess.close()		
	
	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #10
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email')
	illustrator = form.getvalue('illustrator')

	#TODO: For fname, lname == None redirect to login page
	#TODO: Implement sessions using Cookies
	
	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user= cur.fetchone()

		command = "DELETE FROM Illustrators Where IllustratorName = '" + illustrator +  "'";		
		cur.execute(command)
		con.commit()

		command = "SELECT * from ComicBooks"	
		cur.execute(command)
		rows = cur.fetchall()
		titles = []
		for row in rows:
			titles.append(row)		

		sidebar = utilities.getSideBar(email, user[9], cur)
		successMsg = "<strong>Success:</strong> Illustrator '" + illustrator + "' has been deleted."
		print display("home.html").render(user=user,titles=titles,sidebar=sidebar,search=' ',genre=None,publisher=None, success=successMsg)

	except mdb.Error, e:
	    if con:
	        con.rollback()

	    	command = "SELECT * from Illustrators WHERE IllustratorName ='" + illustrator + "'"
		cur.execute(command)
		illustrator_ = cur.fetchone()

		command = "SELECT ISBN, Title, Price, Image from ComicBooks NATURAL JOIN BookIllustrator NATURAL JOIN Illustrators WHERE IllustratorName='" + illustrator + "'"
		
		cur.execute(command)
		rows = cur.fetchall()
		titles = []
		for row in rows:
			titles.append(row)

		command = "SELECT Genre from ComicBooks NATURAL JOIN BookGenre NATURAL JOIN BookIllustrator WHERE IllustratorName ='" + illustrator + "'"
		cur.execute(command)
		genres = cur.fetchall()
		genres_ = []
		for genre in genres:
			if genre not in genres_:
				genres_.append(genre)
		sidebar = utilities.getSideBar(email, user[9], cur)

            #print display("home.html").render(user=user,sidebar=sidebar,error=e.args[1])
	    if 'FOREIGN KEY' in e.args[1] :
		errMsg = '<strong>Database Error:</strong> Foreign key constraint violated. Make sure to remove child records first.'
	    else : 
	    	errMsg = e.args[1]
            print display("illustrator-profile.html").render(sidebar=sidebar,user=user,illustrator=illustrator_,titles=titles,genres=genres_,error=errMsg)
예제 #11
0
def main():
	form = cgi.FieldStorage()
	
	ISBN = form.getvalue('ISBN')
	code = form.getvalue('success')
	err = form.getvalue('error')

	try:
		cur = con.cursor()

		success = None
		error = None
		if code == '1':
			success = '<strong>Success: </strong> Comic Book successfully updated.'
		elif code == '2':
			success = '<strong>Success: </strong> Comic Book successfully created.'
		if err == '0':
			error = '<strong>Database Error:</strong> Foreign key constraint violated. Make sure to remove child records first.'

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"
		
		books = []
		command = "SELECT * from ComicBooks WHERE ISBN='" + ISBN + "'"
		cur.execute(command)
		book = cur.fetchone()
		for i in range(len(book)):
			books.append(book[i])

		awards = []
		command = "SELECT Award from LiteraryAwards WHERE ISBN='" + ISBN + "'"
		cur.execute(command)
		award = cur.fetchall()
		for i in range(len(award)):
			awards.append(award[i][0])
		books.append(awards)

		command = "SELECT WriterName from ComicBooks NATURAL JOIN BookWriter NATURAL JOIN Writers WHERE ISBN ='" + book[0] + "'"
		cur.execute(command)
		writers = cur.fetchall()

		command = "SELECT IllustratorName from ComicBooks NATURAL JOIN BookIllustrator NATURAL JOIN Illustrators WHERE ISBN ='" + book[0] + "'"
		cur.execute(command)
		illustrators= cur.fetchall()

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user = cur.fetchone()

		command = "SELECT Genre from ComicBooks NATURAL JOIN BookGenre WHERE ISBN ='" + book[0] + "'"
		cur.execute(command)
		genres = cur.fetchall()

		book_exists = False
		command = "SELECT * FROM UserCart WHERE Email=%s AND ISBN=%s"
		cur = con.cursor()
		cur.execute(command, (email, ISBN))
		book_ = cur.fetchone()
		if (book_ != None):
			book_exists = True

		book_owned = False
		command = "SELECT 1 from ComicBooks NATURAL JOIN UserOwned WHERE Email=%s AND ISBN=%s"
		cur = con.cursor()
                cur.execute(command, (email, ISBN))
                book_ = cur.fetchone()
                if (book_ != None):
                        book_owned = True
        
		
		sidebar = utilities.getSideBar(email,user[9], cur)
		print display("comic-book-item.html").render(error=error,success=success,book=books,user=user,sidebar=sidebar,writers=writers,illustrators=illustrators,genres=genres,book_exists=book_exists,book_owned=book_owned)
		sess.close()
		
	except mdb.Error, e:
	    if con:
	        con.rollback()
	    print "Location: login.py?error=1"
예제 #12
0
def main():
	form = cgi.FieldStorage()
	
	userprofile = form.getvalue('user') #email of userprofile
	#email = form.getvalue('email') #email of current user
	action = form.getvalue('action') # action 

	#TODO: If current user != email 

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user = cur.fetchone() #

		if action != 'create' :
			command = "SELECT * FROM Users WHERE Email = '" + userprofile + "'";
			cur.execute(command)
			userprof = cur.fetchone() #

			command = "SELECT * from ComicBooks NATURAL JOIN UserCart WHERE Email='" + userprofile + "'"
		
			cur.execute(command)
			rows = cur.fetchall()
			titles = []
			for row in rows:
				titles.append(row)

			# Retrieve Pending Orders
			command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, Status " + \
				  "FROM Orders o, BookOrder bo, ComicBooks cb " + \
				  "WHERE o.OrderID = bo.OrderID " + \
  				  "  AND bo.ISBN = cb.ISBN " + \
  				  "  AND o.Status in ('Paid', 'Shipped') " + \
				  "  AND o.CustomerEmail = '" + userprofile + "' " + \
				  "ORDER BY OrderDate DESC"
			cur.execute(command)
			rows = cur.fetchall()
			pendingOrders = []
			i=0
			while i < len(rows) :
				j = i + 1
				bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
					   ' (' +str(rows[i][3]) +  ')</a>'
				while j < len(rows) and (rows[i][0]==rows[j][0]):
					bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
						   str(rows[j][4]) + ' (' +str(rows[j][3]) +  ')</a>'
					j = j + 1
				pendingOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], rows[i][6]] )
				i = j

			# Retrieve 3 Latest Completed Orders
			command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, Status " + \
				  "FROM BookOrder bo, ComicBooks cb, " + \
				  "(SELECT OrderID, OrderDate, DeliveryAddress, Status " + \
 				   "FROM Orders WHERE Status in ('Delivered', 'Canceled') AND CustomerEmail = '" + userprofile + "' " + \
 				   "ORDER BY OrderDate DESC LIMIT 3) o " + \
				   "WHERE o.OrderID = bo.OrderID AND bo.ISBN = cb.ISBN"
			cur.execute(command)
                        rows = cur.fetchall()
			completedOrders = []
                        i=0
                        while i < len(rows) :
                                j = i + 1
                                bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
                                           ' (' +str(rows[i][3]) +  ')</a>'
                                while j < len(rows) and (rows[i][0]==rows[j][0]):
                                        bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
                                                   str(rows[j][4]) + ' (' +str(rows[j][3]) +  ')</a>'
                                        j = j + 1
                                completedOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], rows[i][6]] )
                                i = j

				
		sidebar = utilities.getSideBar(email,user[9], cur)
		
		if action == 'edit':
			countryDropDown = utilities.generateCountryDropDown(userprof[5]) 
			print display("user-profile-edit.html").render(user=user,userprof=userprof,sidebar=sidebar,countryDropDown=countryDropDown)
		elif action == 'create':
			countryDropDown = utilities.generateCountryDropDown(None)
			print display("user-profile-create.html").render(user=user,createform=None,sidebar=sidebar,countryDropDown=countryDropDown)	
		else :
			print display("user-profile.html").render(user=user,userprof=userprof,sidebar=sidebar,titles=titles,pendingOrders=pendingOrders,completedOrders=completedOrders)
		sess.close()

	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #13
0
def main():
	form = cgi.FieldStorage()
	
	#userprof_form = form.getvalue('user') #email of userprofile
	#email = form.getvalue('email') #email of current user
	name = form.getvalue('name')
	born = form.getvalue('country')
	birthdate = form.getvalue('birth_date')
	gender = form.getvalue('gender') 	
	description = form.getvalue('desc')
	illustratorbooks = form.getlist('illustratorbooks')

	#TODO: If current user != email 

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
                cur.execute(command)
                user= cur.fetchone()

		command = "SELECT * from Illustrators WHERE lower(IllustratorName)=lower('" + name + "')"
		cur.execute(command)
		writer_ = cur.fetchone()		
		

		sidebar = utilities.getSideBar(email,user[9], cur)
		
		if writer_  is not None :
			createform = []
			createform.append(name)
			createform.append(birthdate)
			createform.append(gender)
			createform.append(description)

			error = '<strong>Database Error:</strong> Illustrator with name ' + name + ' already exists.' 
                        countryDropDown = utilities.generateCountryDropDown(born)
			bookitems = utilities.getBookItems(illustratorbooks, cur)	
			print display("illustrator-profile-create.html").render(user=user,createform=createform,sidebar=sidebar,countryDropDown=countryDropDown,error=error,bookitems=bookitems)
		else :
			# Required Fields
			insert_command_1 = "INSERT INTO Illustrators(IllustratorName "
			insert_command_2 = "VALUES ( '" + name + "'"

			# Born / Country
			if born is not None:
				insert_command_1 = insert_command_1 + ", Born "
				insert_command_2 = insert_command_2 + " ,'" + born + "' "

			# Birthdate
			if birthdate is not None:
				insert_command_1 = insert_command_1 + ", Birthdate "
				insert_command_2 = insert_command_2 + " ,'" + birthdate + "' "

			# Gender
			if gender is not None :
				insert_command_1 = insert_command_1 + ", Gender "
				insert_command_2 = insert_command_2 + " ,'" + gender + "' "

			# Description
			if description is not None:
				insert_command_1 = insert_command_1 + ", IllustratorDescription "
                                insert_command_2 = insert_command_2 + " ,'" + description + "' "
		
			 # upload image is user specified
                	if form.has_key('image_file'):

                        	fileitem = form['image_file']
                        	if fileitem.file :
                                	extension = os.path.splitext(fileitem.filename)[1]
                                	if extension != '' :
                                        	fout = file ("model/writers/illustrator-" +  name + extension , 'wb')
                                        	while 1:
                                                	chunk = fileitem.file.read(100000)
                                                	if not chunk: break
                                                	fout.write(chunk)
                                        	fout.close()
                                        	insert_command_1 = insert_command_1 + ", IllustratorImage " 
						insert_command_2 = insert_command_2 + ", 'model/writers/illustrator-" +  name + extension  + "' "


			insert_command_1 = insert_command_1 + ") "
			insert_command_2 = insert_command_2 + ") " 
			cur.execute(insert_command_1 + insert_command_2)

			# Associate Books to Writer
                        for book in illustratorbooks:
                                command = "INSERT INTO BookIllustrator(ISBN, IllustratorName) VALUES (" + book + ",'"  + name + "')"
                                cur.execute(command)
                	con.commit()

			command = "SELECT * FROM Users WHERE Email = '" + email + "'";
			cur.execute(command)
			user_= cur.fetchone() #

			command = "SELECT * from Illustrators WHERE IllustratorName ='" + name + "'"
			cur.execute(command)
			illustrator_ = cur.fetchone()

			command = "SELECT ISBN, Title, Price, Image from ComicBooks NATURAL JOIN BookIllustrator NATURAL JOIN Illustrators WHERE IllustratorName='" + name + "'"
		
			cur.execute(command)
			rows = cur.fetchall()
			titles = []
			for row in rows:
				titles.append(row)

			command = "SELECT Genre from ComicBooks NATURAL JOIN BookGenre NATURAL JOIN BookIllustrator WHERE IllustratorName ='" + name + "'"
			cur.execute(command)
			genres = cur.fetchall()
			genres_ = []
			for genre in genres:
				if genre not in genres_:
					genres_.append(genre)

                	sidebar = utilities.getSideBar(email,user[9], cur)
			successmsg = '<strong>Success:</strong> Illustrator has been created.'
			print display("illustrator-profile.html").render(sidebar=sidebar,user=user_,illustrator=illustrator_,titles=titles,genres=genres_,success=successmsg)		
                	sess.close()
	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #14
0
def main():

	form = cgi.FieldStorage()
	email = form.getvalue('email') #email of current user
	book = form.getvalue('ISBN')
	action = form.getvalue('action')
	total = 0.0

	try:
		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		# Checks if book already exists in cart
		command = "SELECT * FROM UserCart WHERE Email=%s AND ISBN=%s"
		cur = con.cursor()
		cur.execute(command, (email, book))
		book_ = cur.fetchone()

		if email is None:
			print "Location: login.py?redirect=1\r\n"

		#Delete book into user's cart
		if book_ != None:
			if action == 'subtract' :
				quantity = 1
				command = "UPDATE UserCart SET Quantity = Quantity - 1 WHERE Email=%s AND ISBN=%s"
			else :
				# Check quantity first
				command = "SELECT QUANTITY FROM UserCart WHERE Email=%s AND ISBN=%s"
				cur.execute(command, (email, book))
				row = cur.fetchone()
				quantity = row[0]

				command = "DELETE FROM UserCart WHERE Email=%s AND ISBN=%s"
			cur = con.cursor()
			cur.execute(command, (email, book))

			command = "SELECT TotalCost from Users WHERE Email='" + email + "'"
			cur.execute(command)
			row = cur.fetchone()
			total = row[0]

			command = "SELECT Price from ComicBooks WHERE ISBN='" + book + "'"
			cur.execute(command)
			row = cur.fetchone()
			price = row[0]

			if (total >= price):
				total = total - (price*quantity)
			else:
				total = 0

			command = "UPDATE Users SET TotalCost=%s WHERE Email=%s"
			cur.execute(command, (total, email))
			con.commit()
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user= cur.fetchone() 

		command = "SELECT ISBN, Title, Price, Format, Quantity, Stock from ComicBooks NATURAL JOIN UserCart WHERE Email='" + email + "'"
		
		cur.execute(command)
		rows = cur.fetchall()
		titles_temp = []
		for row in rows:
			titles_temp.append(row)

		titles = []
		total = 0
		for title in titles_temp:

			#command = "SELECT WriterName from ComicBooks NATURAL JOIN BookWriter NATURAL JOIN Writers WHERE ISBN='" + title[0] + "'"
			#cur.execute(command)
			#row = cur.fetchone()

			new_title = title #+ (row)
			titles.append(new_title)


		command = "SELECT TotalCost from Users WHERE Email='" + email + "'"
		cur.execute(command)
		row = cur.fetchone()
		total = row[0]

		
		sidebar = utilities.getSideBar(email,user[9], cur)
		print display("shopping-cart.html").render(sidebar=sidebar,user=user,titles=titles,total=total)
		sess.close()
	except mdb.Error, e:
		if con:
			con.rollback()
예제 #15
0
def main():
	form = cgi.FieldStorage()
	action = form.getvalue('action')
	isbn = form.getvalue('ISBN')
	title = form.getvalue('title')
	desc = form.getvalue('desc')
	format = form.getvalue('format')
	length = form.getvalue('length')
	publisher = form.getvalue('publisher')
	datepub = form.getvalue('datepub')
	price = form.getvalue('price')
	awards = form.getvalue('awards')
	genres = form.getlist('genres')
	illustrators= form.getlist('illustrators')
	writers= form.getlist('writers')
	stock = form.getvalue('stock')

	try:
		state = "create"
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if desc != None:
			desc = desc.replace("\r\n", '<br>')
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
                cur.execute(command)
                user= cur.fetchone()


		if action == "create":
			bookform = []
			writers = utilities.getWriters([], cur)	
			illustrators = utilities.getIllustrators([], cur)
			genres = utilities.getGenres([], cur)

			sidebar = utilities.getSideBar(email, user[9], cur)
			print display("comic-book-create-update.html").render(state=state,user=user,sidebar=sidebar,bookform=bookform,genres=genres,writers=writers,illustrators=illustrators)
			return

			sidebar = utilities.getSideBar(email, user[9], cur)
			print display("comic-book-create-update.html").render(user=user,sidebar=sidebar,bookform=bookform,genres=genres,writers=writers,illustrators=illustrators)
			return

		elif action == "save":
			if isbn != None :
				command = "SELECT ISBN from ComicBooks where ISBN = '" + isbn + "'"
				cur.execute(command)
				bookRecord = cur.fetchone()

				if bookRecord is not None:
					bookform = []
					bookform.append(isbn)
					bookform.append(title)
					bookform.append(price)
					bookform.append(publisher)
					bookform.append(desc)
					bookform.append(" ")
					bookform.append(datepub)
					bookform.append(length)
					bookform.append(format)
					writers_= []
					for writer in writers:
						writers_.append(writer)
					writers = utilities.getWriters(writers_, cur)
					illustrators_= []
					for illustrator in illustrators:
						illustrators_.append(illustrator)
					illustrators = utilities.getIllustrators(illustrators_, cur)
					genres_= []
					for genre in genres:
						genres_.append(genre)
					genres = utilities.getGenres(genres_, cur)
					sidebar = utilities.getSideBar(email, user[9], cur)
					error = "Comic book " + isbn + " already exists! Provide another comic book."

					print display("comic-book-create-update.html").render(state="create",user=user,sidebar=sidebar,bookform=bookform,genres=genres,writers=writers,illustrators=illustrators,error=error)
				else :

					insert_command = "INSERT INTO ComicBooks(ISBN, Description, Title, Price, Publisher, DatePublished, Length, Format, Stock) VALUES"
					insert_command = insert_command + "(" 
					insert_command = insert_command + "'" + isbn + "'," 
					insert_command = insert_command + """ " """ + desc + """ " """ + ", '" + title + "','" + price + "','" + publisher + "','" + datepub + "','" + length + "','" + format + "','" + stock + "')"

					cur.execute(insert_command)	

					# upload image is user specified					
					if form.has_key('image_file'):
						update_command = "UPDATE ComicBooks SET "
						fileitem = form['image_file']
						if fileitem.file:
							extension = os.path.splitext(fileitem.filename)[1] 
							if extension != '' :
								fout = file ("model/images/cover-" +  isbn + extension , 'wb')
								while 1:
									chunk = fileitem.file.read(100000)
									if not chunk: 
										break
									fout.write(chunk)
								fout.close()
								update_command = update_command + "Image = '" + "model/images/cover-" + isbn + extension  + "' "
								update_command =  update_command + " WHERE ISBN = '" + isbn +  "'"
								cur.execute(update_command)

					if awards != None:
						awards = awards.split(',')
						for award in awards:
							insert_command = "INSERT INTO LiteraryAwards(ISBN, Award) VALUES "
							insert_command =  insert_command + "( '" + isbn + """' , " """ + award + """ ")"""
							cur.execute(insert_command)
					
					if genres is not None:
						for genre in genres:
							insert_command = "INSERT INTO BookGenre(ISBN, Genre) VALUES "
							insert_command =  insert_command + "( '" + isbn + "' , '" + genre + "')"
							cur.execute(insert_command)
					
					if illustrators is not None:
						for illustrator in illustrators:
							insert_command = "INSERT INTO BookIllustrator(ISBN, IllustratorName) VALUES "
							insert_command =  insert_command + "( '" + isbn + "' , '" + illustrator + "')"
							cur.execute(insert_command)

					if writers is not None:
						for writer in writers:
							insert_command = "INSERT INTO BookWriter(ISBN, WriterName) VALUES "
							insert_command =  insert_command + "( '" + isbn + "' , '" + writer + "')"
							cur.execute(insert_command)
					
					con.commit() 

					print "Location: comic-book-item.py?ISBN=" + isbn + "&success=2\r\n"
					

	except mdb.Error, e:
	    if con:
	        con.rollback()
	    invaidPageError()
예제 #16
0
def main():

	form = cgi.FieldStorage()
	#email = form.getvalue('email') #email of current user
	book = form.getvalue('ISBN')

	try:
		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if email is None:
			print "Location: login.py?redirect=1\r\n"

		# Checks if book already exists in cart
		command = "SELECT * FROM UserCart WHERE Email=%s AND ISBN=%s"
		cur = con.cursor()
		cur.execute(command, (email, book))
		book_ = cur.fetchone()

		# Insert book into user's cart
		if book_ == None:
			command = "INSERT INTO UserCart(Email, ISBN) VALUES(%s, %s)"
			cur = con.cursor()
			cur.execute(command, (email, book))
		# Increment quantity
		else :
			command = "UPDATE UserCart SET Quantity = Quantity + 1 WHERE Email = '" + email + "' AND ISBN = " + book
			cur.execute(command)		
	
		#update total price
		command = "SELECT TotalCost from Users WHERE Email='" + email + "'"
		cur.execute(command)
		row = cur.fetchone()
		total = row[0]

		if total == None:
			total = 0

		command = "SELECT Price from ComicBooks WHERE ISBN='" + book + "'"
		cur.execute(command)
		row = cur.fetchone()
		price = row[0]

		total = total + price

		command = "UPDATE Users SET TotalCost='" + str(total) + "' WHERE Email='" + email + "'"
		cur.execute(command)
		con.commit()
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user = cur.fetchone() 

		#Get titles of ComicBooks in cart
		command = "SELECT ISBN, Title, Price, Format, Quantity, Stock from ComicBooks NATURAL JOIN UserCart WHERE Email='" + email + "'"
		
		cur.execute(command)
		rows = cur.fetchall()
		titles_temp = []
		for row in rows:
			titles_temp.append(row)

		titles = []
		total = 0
		for title in titles_temp:
			#command = "SELECT WriterName from ComicBooks NATURAL JOIN BookWriter NATURAL JOIN Writers WHERE ISBN='" + title[0] + "'"
			#cur.execute(command)
			#row = cur.fetchone()

			new_title = title # + (row)
			titles.append(new_title)

		command = "SELECT TotalCost from Users WHERE Email='" + email + "'"
		cur.execute(command)
		row = cur.fetchone()
		total = row[0]

		sidebar = utilities.getSideBar(email,user[9], cur)
		print display("shopping-cart.html").render(sidebar=sidebar,user=user,titles=titles,total=total)
		print format
		sess.close()

	except mdb.Error, e:
		if con:
			con.rollback()
예제 #17
0
def main():
	form = cgi.FieldStorage()
	
	userprof_form = form.getvalue('user') #email of userprofile
	email = form.getvalue('email') #email of current user
	firstname = form.getvalue('first_name')
	lastname = form.getvalue('last_name')
	password = form.getvalue('password')
	country = form.getvalue('country')
	birthdate = form.getvalue('birth_date')
	is_administrator = form.getvalue('is_administrator') 	

	#TODO: If current user != email 

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
                cur.execute(command)
                user= cur.fetchone()

		command = "SELECT * FROM Users WHERE Email = '" + userprof_form + "'";
                cur.execute(command)
                userprof= cur.fetchone()		
		

		sidebar = utilities.getSideBar(email,user[9], cur)
		
		if userprof is not None :
			createform = []
			createform.append(userprof_form)
			createform.append(firstname)
			createform.append(lastname)
			createform.append(password)
			createform.append(birthdate)
			createform.append(is_administrator)

			error = '<strong>Database Error:</strong> User with email ' + userprof_form + ' already exists.' 
                        countryDropDown = utilities.generateCountryDropDown(country)	
			print display("user-profile-create.html").render(user=user,createform=createform,sidebar=sidebar,countryDropDown=countryDropDown,error=error)
		else :
			# Required Fields
			enc_password = sha512_crypt.encrypt(password)
			insert_command_1 = "INSERT INTO Users(FirstName, LastName, Email, Password, IsAdmin, Datejoined "
			insert_command_2 = "VALUES ( '" + firstname + "','" + lastname + "','" + userprof_form + "','" + enc_password  + "','" + is_administrator +  "', NOW() "

			# Country
			if country is not None:
				insert_command_1 = insert_command_1 + ", Country "
				insert_command_2 = insert_command_2 + " ,'" + country + "' "

			# Birthdate
			if birthdate is not None:
				insert_command_1 = insert_command_1 + ", Birthdate "
				insert_command_2 = insert_command_2 + " ,'" + birthdate + "' "
						
			 # upload image is user specified
                	if form.has_key('image_file'):

                        	fileitem = form['image_file']
                        	if fileitem.file :
                                	extension = os.path.splitext(fileitem.filename)[1]
                                	if extension != '' :
                                        	fout = file ("model/users/" +  userprof_form + extension , 'wb')
                                        	while 1:
                                                	chunk = fileitem.file.read(100000)
                                                	if not chunk: break
                                                	fout.write(chunk)
                                        	fout.close()
                                        	insert_command_1 = insert_command_1 + ", Image " 
						insert_command_2 = insert_command_2 + ", 'model/users/" +  userprof_form + extension  + "' "


			insert_command_1 = insert_command_1 + ") "
			insert_command_2 = insert_command_2 + ") " 
			cur.execute(insert_command_1 + insert_command_2)
                	con.commit()
		

			command = "SELECT * FROM Users WHERE Email = '" + userprof_form + "'";
                	cur.execute(command)
                	userprof = cur.fetchone() #

                	sidebar = utilities.getSideBar(email,user[9], cur)
			successmsg = '<strong>Success:</strong> User has been created.'
                	print display("user-profile.html").render(user=user,userprof=userprof,sidebar=sidebar,titles=[],success=successmsg)			
                	sess.close()
	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #18
0
def main():
	form = cgi.FieldStorage()
	action = form.getvalue('action') # action 
	order = form.getvalue('order')

	success = None
	error = None

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"
	
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user = cur.fetchone() #
		
		if action == 'ship' :
			command = "UPDATE Orders SET Status = 'Shipped' WHERE OrderID = " + order
			cur.execute(command)
			con.commit()
			success = "<strong>Success: </strong> Order with Order ID " + order + " has been marked as Shipped."
		elif action == 'deliver' :
			command = "UPDATE Orders SET Status = 'Delivered' WHERE OrderID = " + order
			cur.execute(command)
			con.commit()
			success = "<strong>Success: </strong> Order with Order ID " + order + " has been marked as Delivered."
		elif action == 'cancel' :
			command = "UPDATE Orders SET Status = 'Canceled' WHERE OrderID = " + order
			cur.execute(command)
			con.commit() 
			success = "<strong>Success: </strong> Order with Order ID " + order + " has been Canceled."

		# Retrieve Paid Orders
		command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, o.CustomerEmail, u.FirstName, u.LastName " + \
			  "FROM Orders o, BookOrder bo, ComicBooks cb, Users u " + \
		          "WHERE o.OrderID = bo.OrderID " + \
  		          "  AND bo.ISBN = cb.ISBN " + \
  		          "  AND o.Status in ('Paid') " + \
			  "  AND u.Email = o.CustomerEmail " + \
		          "ORDER BY OrderDate"
		cur.execute(command)
		rows = cur.fetchall()
		paidOrders = []
		i=0
		while i < len(rows) :
			j = i + 1
			userHTML = '<a href="user-profile.py?user='******'">' + rows[i][7] + ' ' +  rows[i][8] + \
				   '</a>'
			bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
				   ' (' +str(rows[i][3]) +  ')</a>'
			while j < len(rows) and (rows[i][0]==rows[j][0]):
				bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
					   str(rows[j][4]) + ' (' +str(rows[i][3]) +  ')</a>'
				j = j + 1
			paidOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], userHTML] )
			i = j

		# Retrieve Shipped Orders
                command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, o.CustomerEmail, u.FirstName, u.LastName " + \
                          "FROM Orders o, BookOrder bo, ComicBooks cb, Users u " + \
                          "WHERE o.OrderID = bo.OrderID " + \
                          "  AND bo.ISBN = cb.ISBN " + \
                          "  AND o.Status in ('Shipped') " + \
                          "  AND u.Email = o.CustomerEmail " + \
                          "ORDER BY OrderDate"
                cur.execute(command)
                rows = cur.fetchall()
                shippedOrders = []
                i=0
                while i < len(rows) :
                        j = i + 1
                        userHTML = '<a href="user-profile.py?user='******'">' + rows[i][7] + ' ' +  rows[i][8] + \
                                   '</a>'
                        bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
                                   ' (' +str(rows[i][3]) +  ')</a>'
                        while j < len(rows) and (rows[i][0]==rows[j][0]):
                                bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
                                           str(rows[j][4]) + ' (' +str(rows[i][3]) +  ')</a>'
                                j = j + 1
                        shippedOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], userHTML] )
                        i = j

		sidebar = utilities.getSideBar(email,user[9], cur)
		print display("orders-fulfillment.html").render(user=user,sidebar=sidebar,paidOrders=paidOrders,shippedOrders=shippedOrders,success=success,error=error)	
		sess.close()

	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #19
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email')
	genre = form.getvalue('genre')
	action = form.getvalue('action')
	genredesc = form.getvalue('genredesc')
	genrecreate = form.getvalue('genrecreate')
	genrebooks = form.getlist('genrebooks')

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie
		
		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
                cur.execute(command)
                user= cur.fetchone()

		if action == None :
			if genre != None :
				command = "SELECT * FROM Genres where Genre='" + genre + "'";
				cur.execute(command)
				genreform= cur.fetchone()

				# Get books associated with genre
				command = "SELECT ISBN from ComicBooks NATURAL JOIN BookGenre WHERE Genre='" + genre + "' order by Title"
				cur.execute(command)
				rows = cur.fetchall()		

				titles = []
				for row in rows:
					titles.append(row[0])

				bookitems = utilities.getBookItems(titles, cur)
			else :
				genreform = None
        			bookitems = utilities.getBookItems([], cur)	

			sidebar = utilities.getSideBar(email, user[9], cur)

			print display("genre-create-update.html").render(user=user,sidebar=sidebar,genre=genre,genreform=genreform,bookitems=bookitems)
			return

		else :
			# Update
			if genre != None :
				update_command = "UPDATE Genres SET "
				
				if genredesc == None:
					update_command = update_command + " GenreDesc = NULL "
				else :
					update_command = update_command + " GenreDesc = '" + genredesc + "' "
				
				update_command =  update_command + " WHERE Genre = '" + genre +  "'"
				cur.execute(update_command)
				

				command = "DELETE FROM BookGenre WHERE Genre = '"  + genre + "'"
				cur.execute(command)

				# Associate Books to Genre
                                for book in genrebooks:
                                	command = "INSERT INTO BookGenre(ISBN, Genre) VALUES (" + book + ",'"  + genre + "')"
                                        cur.execute(command)
                                con.commit()


                        	command = "SELECT * from ComicBooks NATURAL JOIN BookGenre WHERE Genre='" + genre + "'"
                        	cur.execute(command)
                        	rows = cur.fetchall()
                        	titles = []
                        	for row in rows:
                                	titles.append(row)

                        	sidebar = utilities.getSideBar(email, user[9], cur)
				success = '<strong>Success: </strong> Genre has been updated.'
                        	print display("home.html").render(user=user,titles=titles,sidebar=sidebar,genre=genre,genredesc=genredesc,search=' ',success=success)
			else :
				# Check if genre exists
				command = "SELECT Genre from Genres where Genre = '" + genrecreate + "'"
				cur.execute(command)
				genreRecord = cur.fetchone()

				if genreRecord is not None:
					genreform = []
					genreform.append(genrecreate)
					genreform.append(genredesc)
					sidebar = utilities.getSideBar(email, user[9], cur)
					bookitems = utilities.getBookItems(genrebooks, cur)
					error = "<strong>Database Error:</strong>  Genre " + genrecreate + " already exists! Provide another genre name."
					sidebar = utilities.getSideBar(email, user[9], cur)
					print display("genre-create-update.html").render(user=user,sidebar=sidebar,genre=genre,genreform=genreform,bookitems=bookitems,error=error)
				else :
					insert_command = "INSERT INTO Genres(Genre, GenreDesc) VALUES ('" + genrecreate + "','" + genredesc + "') "
					cur.execute(insert_command)

					# Associate Books to Genre
					for book in genrebooks:
						command = "INSERT INTO BookGenre(ISBN, Genre) VALUES (" + book + ",'"  + genrecreate + "')"
						cur.execute(command)
					con.commit()

					genre = genrecreate 			 
					command = "SELECT * from ComicBooks NATURAL JOIN BookGenre WHERE Genre='" + genre + "'"
                                	cur.execute(command)
                                	rows = cur.fetchall()
                                	titles = []
                                	for row in rows:
                                        	titles.append(row)

                                	sidebar = utilities.getSideBar(email, user[9], cur)
					success = '<strong>Success: </strong> Genre '  + genrecreate + ' has been created.'
                                	print display("home.html").render(user=user,titles=titles,sidebar=sidebar,genre=genre,genredesc=genredesc,search=' ',success=success)			

	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #20
0
def main():
	form = cgi.FieldStorage()
	
	illustrator= form.getvalue('illustrator') 
	#email = form.getvalue('email') #email of current user
	action = form.getvalue('action') # action 

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if email is None:
			print "Location: login.py?redirect=1\r\n"
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user_= cur.fetchone() #

		if action != 'create' :
			command = "SELECT * from Illustrators WHERE IllustratorName ='" + illustrator + "'"
			cur.execute(command)
			illustrator_ = cur.fetchone()

			command = "SELECT ISBN, Title, Price, Image from ComicBooks NATURAL JOIN BookIllustrator NATURAL JOIN Illustrators WHERE IllustratorName='" + illustrator + "'"
		
			cur.execute(command)
			rows = cur.fetchall()
			titles = []
			for row in rows:
				titles.append(row)

			command = "SELECT Genre from ComicBooks NATURAL JOIN BookGenre NATURAL JOIN BookIllustrator WHERE IllustratorName ='" + illustrator + "'"
			cur.execute(command)
			genres = cur.fetchall()
			genres_ = []
			for genre in genres:
				if genre not in genres_:
					genres_.append(genre)

		sidebar = utilities.getSideBar(email,user_[9], cur)

		if action == 'create' :
			countryDropDown = utilities.generateCountryDropDown(None)
			bookitems = utilities.getBookItems([], cur)
			print display("illustrator-profile-create.html").render(user=user_,createform=None,sidebar=sidebar,bookitems=bookitems,countryDropDown=countryDropDown)
		elif action == 'edit':
			countryDropDown = utilities.generateCountryDropDown(illustrator_[3])

			selectedBooks = []
			for title in titles :
				selectedBooks.append(title[0])
			bookitems = utilities.getBookItems(selectedBooks, cur)
			print display("illustrator-profile-edit.html").render(sidebar=sidebar,user=user_,illustrator=illustrator_,bookitems=bookitems,countryDropDown=countryDropDown)
		else :
			print display("illustrator-profile.html").render(sidebar=sidebar,user=user_,illustrator=illustrator_,titles=titles,genres=genres_)
		sess.close()

	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #21
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email') #email of current user
	creditcard = form.getvalue("creditcard")
	deliveryaddress = form.getvalue("deliveryaddress")

	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie


		if email is None:
			print "Location: login.py?redirect=1\r\n"


		update_command = "UPDATE Users SET TotalCost='0.00' WHERE Email = '" + email + "'"
		cur.execute(update_command)
		
		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user_= cur.fetchone()

		# Create order record and retrieve its OrderID
		command = "INSERT INTO Orders(OrderDate, CustomerEmail, DeliveryAddress, Status) VALUES( NOW(), '" + email + "','" + deliveryaddress + "','Paid')"
		cur.execute(command)
		command = "SELECT max(OrderID) FROM Orders where CustomerEmail ='" + email + "'"
		cur.execute(command)
		orderID = cur.fetchone()[0]
  
		# Retrieve books in User Cart
		command = "SELECT ISBN, Quantity from ComicBooks NATURAL JOIN UserCart WHERE Email='" + email + "'"
		cur.execute(command)
		rows = cur.fetchall()
		#bookorders = []
		#for row in rows:
			#bookorders.append(row)


		for book in rows:
			# Add Book to Order	
			command = "INSERT INTO BookOrder(ISBN,OrderID,Quantity) values(" + book[0] + "," + str(orderID) + "," + str(book[1]) + ")"
			cur.execute(command)
			
			# Update Stock count of the comic book
			command = "UPDATE ComicBooks SET Stock = Stock - " + str(book[1]) + " WHERE ISBN = '" + book[0] + "'"	
			cur.execute(command) 

		# Empty User Cart
		command = "DELETE FROM UserCart WHERE Email='" + email + "'"
		cur.execute(command)

				
		con.commit()

		
		sidebar = utilities.getSideBar(email,user_[9], cur)
		print display("success.html").render(sidebar=sidebar,user=user_)
		sess.close()

	except mdb.Error, e:
	    if con:
	        con.rollback()
예제 #22
0
def main():
    form = cgi.FieldStorage()

    userprof = form.getvalue("user")  # email of userprofile
    # email = form.getvalue('email') #email of current user
    name = form.getvalue("name")
    born = form.getvalue("country")
    birthdate = form.getvalue("birth_date")
    gender = form.getvalue("gender")
    description = form.getvalue("desc")
    illustratorbooks = form.getlist("illustratorbooks")
    # TODO: If current user != email

    try:

        cur = con.cursor()

        sess = session.Session(expires=365 * 24 * 60 * 60, cookie_path="/")
        lastvisit = sess.data.get("lastvisit")
        email = sess.data.get("user")
        print sess.cookie

        if email is None:
            print "Location: login.py?redirect=1\r\n"

        if description != None:
            description = description.replace("\r\n", "<br>")

        update_command = "UPDATE Illustrators SET "

        # set gender
        update_command = update_command + " Gender = '" + gender + "' "

        # set description
        if description is None:
            update_command = update_command + ", IllustratorDescription = null "
        else:
            update_command = update_command + ", IllustratorDescription = '" + description + "' "

            # set country
        if born is None:
            update_command = update_command + ", Born = null "
        else:
            update_command = update_command + ", Born = '" + born + "' "

            # set birth date
        if birthdate is None:
            update_command = update_command + ", Birthdate = null "
        else:
            update_command = update_command + ", Birthdate = '" + birthdate + "' "

            # upload image is user specified
        if form.has_key("image_file"):

            fileitem = form["image_file"]
            if fileitem.file:
                extension = os.path.splitext(fileitem.filename)[1]
                if extension != "":
                    fout = file("model/writers/illustrator-" + name + extension, "wb")
                    while 1:
                        chunk = fileitem.file.read(100000)
                        if not chunk:
                            break
                        fout.write(chunk)
                    fout.close()
                    update_command = (
                        update_command
                        + ", IllustratorImage = '"
                        + "model/writers/illustrator-"
                        + name
                        + extension
                        + "' "
                    )

        update_command = update_command + "WHERE IllustratorName = '" + name + "'"
        cur.execute(update_command)

        # Associate Books to Writer
        command = "DELETE FROM BookIllustrator WHERE IllustratorName = '" + name + "'"
        cur.execute(command)
        for book in illustratorbooks:
            command = "INSERT INTO BookIllustrator(ISBN, IllustratorName) VALUES (" + book + ",'" + name + "')"
            cur.execute(command)

        con.commit()

        command = "SELECT * FROM Users WHERE Email = '" + email + "'"
        cur.execute(command)
        user_ = cur.fetchone()  #

        command = "SELECT * from Illustrators WHERE IllustratorName ='" + name + "'"
        cur.execute(command)
        illustrator_ = cur.fetchone()

        command = (
            "SELECT ISBN, Title, Price, Image from ComicBooks NATURAL JOIN BookIllustrator NATURAL JOIN Illustrators WHERE IllustratorName='"
            + name
            + "'"
        )

        cur.execute(command)
        rows = cur.fetchall()
        titles = []
        for row in rows:
            titles.append(row)

        command = (
            "SELECT Genre from ComicBooks NATURAL JOIN BookGenre NATURAL JOIN BookIllustrator WHERE IllustratorName ='"
            + name
            + "'"
        )
        cur.execute(command)
        genres = cur.fetchall()
        genres_ = []
        for genre in genres:
            if genre not in genres_:
                genres_.append(genre)

        sidebar = utilities.getSideBar(email, user_[9], cur)
        successmsg = "<strong>Success:</strong> Illustrator has been saved."
        print display("illustrator-profile.html").render(
            sidebar=sidebar, user=user_, illustrator=illustrator_, titles=titles, genres=genres_, success=successmsg
        )
        sess.close()

    except mdb.Error, e:
        if con:
            con.rollback()
예제 #23
0
def main():
	form = cgi.FieldStorage()
	
	#email = form.getvalue('email')
	userprofile = form.getvalue('user')

	#TODO: For fname, lname == None redirect to login page
	#TODO: Implement sessions using Cookies
	
	try:
		cur = con.cursor()

		sess = session.Session(expires=365*24*60*60, cookie_path='/')
		lastvisit = sess.data.get('lastvisit')
		email= sess.data.get('user')
		print sess.cookie

		if email is None:
			print "Location: login.py?redirect=1\r\n"

		command = "SELECT * FROM Users WHERE Email = '" + email + "'";
		cur.execute(command)
		user= cur.fetchone()

		command = "DELETE FROM Users Where Email = '" + userprofile +  "'";		
		cur.execute(command)
		con.commit()

		command = "SELECT * from ComicBooks"	
		cur.execute(command)
		rows = cur.fetchall()
		titles = []
		for row in rows:
			titles.append(row)
		

		sidebar = utilities.getSideBar(email, user[9], cur)
		successMsg = "<strong>Success:</strong> User with email '" + userprofile + "' has been deleted."
		print display("home.html").render(user=user,titles=titles,sidebar=sidebar,search=' ',genre=None,publisher=None, success=successMsg)

	except mdb.Error, e:
	    if con:
	        con.rollback()

	    command = "SELECT * FROM Users WHERE Email = '" + userprofile + "'";
	    cur.execute(command)
	    userprof = cur.fetchone() #

	    command = "SELECT * from ComicBooks NATURAL JOIN UserCart WHERE Email='" + userprofile + "'"
            cur.execute(command)
            rows = cur.fetchall()
	    titles = []
	    for row in rows:
		titles.append(row)

	    # Retrieve Pending Orders
            command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, Status " + \
                      "FROM Orders o, BookOrder bo, ComicBooks cb " + \
                      "WHERE o.OrderID = bo.OrderID " + \
                      "  AND bo.ISBN = cb.ISBN " + \
                      "  AND o.Status in ('Paid', 'Shipped') " + \
                      "  AND o.CustomerEmail = '" + userprofile + "' " + \
                      "ORDER BY OrderDate DESC"
            cur.execute(command)
            rows = cur.fetchall()
            pendingOrders = []
            i=0
            while i < len(rows) :
            	j = i + 1
                bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
                           ' (' +str(rows[i][3]) +  ')</a>'
                while j < len(rows) and (rows[i][0]==rows[j][0]):
                	bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
                                   str(rows[j][4]) + ' (' +str(rows[j][3]) +  ')</a>'
                        j = j + 1
                        pendingOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], rows[i][6]] )
                i = j

	    # Retrieve 3 Latest Completed Orders
            command = "SELECT o.OrderID, OrderDate, Quantity, cb.ISBN, cb.Title, DeliveryAddress, Status " + \
                      "FROM BookOrder bo, ComicBooks cb, " + \
                      "(SELECT OrderID, OrderDate, DeliveryAddress, Status " + \
                       "FROM Orders WHERE Status in ('Delivered', 'Canceled') AND CustomerEmail = '" + userprofile + "' " + \
                       "ORDER BY OrderDate DESC LIMIT 3) o " + \
                       "WHERE o.OrderID = bo.OrderID AND bo.ISBN = cb.ISBN"
            cur.execute(command)
            rows = cur.fetchall()
            completedOrders = []
            i=0
            while i < len(rows) :
            	j = i + 1
                bookHTML = str(rows[i][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[i][3]) + '">' + str(rows[i][4]) + \
                           ' (' +str(rows[i][3]) +  ')</a>'
                while j < len(rows) and (rows[i][0]==rows[j][0]):
                	bookHTML = bookHTML + '<br/>' + str(rows[j][2]) + ' X <a href="comic-book-item.py?ISBN=' + str(rows[j][3]) + '">' + \
                                   str(rows[j][4]) + ' (' +str(rows[j][3]) +  ')</a>'
                        j = j + 1
                completedOrders.append( [rows[i][0], rows[i][1], bookHTML, rows[i][5], rows[i][6]] )
                i = j

	    sidebar = utilities.getSideBar(email, user[9], cur)

            #print display("home.html").render(user=user,sidebar=sidebar,error=e.args[1])
	    if 'FOREIGN KEY' in e.args[1] :
		errMsg = '<strong>Database Error:</strong> Foreign key constraint violated. Make sure to remove child records first.'
	    else : 
	    	errMsg = e.args[1]
            print display("user-profile.html").render(user=user,userprof=userprof,sidebar=sidebar,titles=titles,pendingOrders=pendingOrders,completedOrders=completedOrders,error=errMsg)