Exemplo n.º 1
0
def pageInit(subHeading=None, formJS=0):
    table_data = declarations.define_tables()
    print "<HTML>"
    print "<HEAD>"
    if formJS:
        pmt_utils.generate_form_javascript(table_data, 'inventory',
                                           'inv_admin', 0)
    else:
        pmt_utils.javaScript("inv_admin")
    pmt_utils.title("Inventory")
    print "</HEAD>"
    pmt_utils.bodySetup()
    pmt_utils.mainHeading('Inventory')
    if subHeading != None:
        pmt_utils.subHeading(subHeading)
    pmt_utils.formSetup("inv_admin", declarations.pmt_info['db_name'],
                        "inv_admin", "return submitForm(document.inv_admin)")

    dbResult = pmt_utils.connectDB(declarations.pmt_info['browser_username'],
                                   declarations.pmt_info['browser_password'],
                                   declarations.pmt_info['db_name'])

    if dbResult['status'] != 'success':
        db = None
        status = dbResult['message']
    else:
        db = dbResult['result']
        status = 'success'

    return status, table_data, db
Exemplo n.º 2
0
	def create_policy_dialog(self):

		table_data = declarations.define_tables()

		result = gadfly_utils.execute_sql_statement(db=self.db,
			sqlStatement=gadfly_utils.build_select_all_table_columns_statement(table_data,'store_info','1'),
			commit_after=1,
			leave_cursor_open=1,
			create_cursor_also=0)

		if result['status'] != 'success':
			print 'DB Error: Could not retrieve store info'
			return result

		self.policy_dialog = Pmw.Dialog(self._hull, buttons=('Ok',), defaultbutton='Ok', title='Order Policies')

		self.policy_data = Pmw.ScrolledText(
			self.policy_dialog.interior(),
			borderframe=1,
			text_padx=10,
			text_pady=10,
			text_wrap='word')

		order_policies = string.replace(result['result'][0][15],'<CR>','\n')

		self.policy_data.settext(order_policies)
		self.policy_data._textbox.configure(state='disabled')
		self.policy_data.pack(expand=1,fill=BOTH)
		self.policy_dialog.withdraw()
Exemplo n.º 3
0
	def view_cart(self,display_customer_data=0):

		if self.cart == {}:
			self.info_dialog.configure(message_text='You have no items in your shopping cart!')
			self.info_dialog.activate()
			return

		else:

			table_data = declarations.define_tables()

			if display_customer_data:
				product_data_lines = 'First Name: ' + self.firstnametextvar.get() + '\n'
				product_data_lines = product_data_lines + 'Middle Initial: ' + self.initialtextvar.get() + '\n'
				product_data_lines = product_data_lines + 'Last Name: ' + self.initialtextvar.get() + '\n'
				product_data_lines = product_data_lines + 'Street Line 1: ' + self.streetline1textvar.get() + '\n'
				product_data_lines = product_data_lines + 'Street Line 2: ' + self.streetline2textvar.get() + '\n'
				product_data_lines = product_data_lines + 'City: ' + self.citytextvar.get() + '\n'
				product_data_lines = product_data_lines + 'State: ' + self.statetextvar.get() + '\n'
				product_data_lines = product_data_lines + 'Zip: ' + self.ziptextvar.get() + '\n'

				product_data_lines = product_data_lines + 'Card Number: ' + self.cardnotextvar.get() + '\n'
				product_data_lines = product_data_lines + 'Expiration Date: ' + self.expdatetextvar.get() + '\n'
				product_data_lines = product_data_lines + 'Payment Method: ' + self.payment_methodvar.get() + '\n\nItems Ordered:\n\n'

			else:
				product_data_lines = ''

			product_data_lines = product_data_lines + string.center('Id',10) + '  ' + string.center('Name',40) + '  ' +  string.center('Weight',6) + '  ' + string.center('Qty',3) + '  ' + string.center('Price',11) + '  ' + string.center('Total',11) + '\n'

			line_total = 0.0

			for product_id in self.cart.keys():
				result = gadfly_utils.execute_sql_statement(db=self.db,
					sqlStatement=gadfly_utils.build_select_all_table_columns_statement(table_data,'products',product_id),
					commit_after=1,
					leave_cursor_open=1,
					create_cursor_also=0)

				if result['status'] != 'success':
					print 'DB Error: Could not retrieve product info'
					return result

				product_data_lines = product_data_lines + '\n' + \
					string.center(result['result'][0][0],10) + '  ' + \
					string.center(result['result'][0][5],40) + '  ' + \
					string.center('%s lbs.' % (result['result'][0][8]),6) + '  ' + \
					string.center(`self.cart[product_id]`,3) + '  ' + \
					string.center('$%9.2f' % (result['result'][0][7]),11) + '  ' + \
					string.center('$%9.2f' % (self.cart[product_id] * float(result['result'][0][7])),11) + '\n'
				line_total = line_total + (self.cart[product_id] * float(result['result'][0][7]))

			product_data_lines = product_data_lines + '\n\nOrder Total: $'
			product_data_lines = product_data_lines + ('%9.2f' % (line_total))

		self.view_cart_data.settext(product_data_lines)
		self.view_cart_dialog.activate()
Exemplo n.º 4
0
def displayEmail(table, data, email):
    print '<form method=post>'
    print '<table>'
    print '<tr><td>To:</td><td><input type=text name=to_box></td>'
    print "<tr><td>From:</td><td>"
    print "<input type=hidden name=from_box value='%s'>%s</td>" % (email,
                                                                   email)
    print '<tr><td>Subject:</td><td><input type=text name=subject></td>'
    print '</table><hr><table>'

    content = ''
    table_data = declarations.define_tables()[table]

    # Arrange table_data by display_order
    displayList = []
    for i in xrange(0, len(table_data) + 5):
        displayList.append('')

    for key in table_data.keys():
        index = table_data[key]['display_order']
        displayList[index] = key

    for key in displayList:
        if key == '':
            continue
        content = content + '%s:\t' % table_data[key]['label']
        if not data.has_key(key):
            key = key[:31]
        content = content + '%s\n' % data[key]

    html_content = string.replace(content, '\n', '</td><tr><td>')
    html_content = string.replace(html_content, '\t', '</td><td>')
    print '<tr><td>' + html_content
    print '</table>'

    print '<input type=hidden name=content value="%s">' % urllib.quote(content)
    print '<input type=hidden name=username value="%s">' % username
    print '<input type=hidden name=table value="%s">' % form['table'].value
    print '<input type=hidden name=key value="%s"><HR>' % form['key'].value

    link = '/%s-cgi-bin/email.pyc' % declarations.pmt_info['db_name']
    java = "return goto_url('%s')" % link
    print '<input type=submit name=send value="Send Email" onClick="%s">' % java
    print '</form>'
Exemplo n.º 5
0
	def display_product_info(self, name, db_key):

		table_data = declarations.define_tables()

		result = gadfly_utils.execute_sql_statement(db=self.db,
			sqlStatement=gadfly_utils.build_select_all_table_columns_statement(table_data,'products',db_key),
			commit_after=1,
			leave_cursor_open=1,
			create_cursor_also=0)
		if result['status'] != 'success':
			print 'DB Error: Could not retrieve product info'
			return result

		self.productidlabel.configure(text='Product Id:')
		self.productid.configure(image='',text=result['result'][0][0],font=default_font)
		self.productid.pack(side=LEFT)
		self.productdescription.configure(text=result['result'][0][5],font=default_font)
		if self.productimagedata:
			del self.productimagedata
		self.productimagedata = ImageTk.PhotoImage(Image.open('%s%s' % (imgs,result['result'][0][9])))
		self.productimage['image'] = self.productimagedata
		self.productlongdescription.configure(text=result['result'][0][6],
			font=default_font,
			wraplength=300)
		self.productlongdescription.pack(side=TOP)
		self.shippingweightlabel.configure(text='Shipping Weight:',font=default_font)
		self.shippingweightlabel.pack(side=LEFT,expand=NO)
		self.shippingweight.configure(text='%s lbs' % (result['result'][0][8]),font=default_font)
		self.shippingweight.pack(side=LEFT,expand=NO)
		self.productpricelabel.configure(text='Price:',font=default_font)
		self.productprice.configure(text="$ %9.2f" % (result['result'][0][7]),font=default_font)
		self.quantitylabel.pack(side=LEFT,expand=NO)

		# initialize quantity to 0
		self.quantitytextvar.set('0')

		self.quantitytext.pack(side=LEFT,expand=NO)
Exemplo n.º 6
0
    def create_db(self):

        import declarations

        dbResult = pmt_utils.connectDB(self.postgres_username,
                                       self.postgres_password, self.db_name)

        # could not connect to db
        if dbResult['status'] != 'success':

            # database does not exist so we do not have to backup
            # table data from previous version of this database
            print 'Could not connect to %s database, no db backup to perform.' % (
                self.db_name),

        else:
            # else there is a database that exists with this name
            db = dbResult['result']

            # backup all tables to dat files
            #pmt_utils.exec_sql_file(db, '%s_tables.backup' % (self.db_name))

            db.close()

            # destroy the previous version of this database
            os.system('dropdb %s' % (self.db_name))

        # connect to template database to get maximum user
        # id in use at this time
        dbResult = pmt_utils.connectDB(self.postgres_username,
                                       self.postgres_password, 'template1')

        if dbResult['status'] != "success":
            print dbResult['message']
            sys.exit(1)

        db = dbResult['result']

        queryResult = pmt_utils.executeSQL(
            db, "SELECT MAX(usesysid) FROM pg_user")

        if queryResult["status"] != 'success':
            print queryResult["status"]
            sys.exit(1)

        result = queryResult['result']

        user_id = result[0]['max']

        user_id = user_id + 1

        db.close()

        # create database
        os.system("createdb %s" % (self.db_name))

        os.system("/usr/bin/destroyuser " + self.db_admin_username)

        # print "Answer NO to the next prompt"

        os.system("/usr/bin/createuser -D -A %s" % (self.db_admin_username))

        user_id = user_id + 1

        os.system("/usr/bin/destroyuser " + self.visitor_username)

        # print "Answer NO to the next prompt"

        os.system("/usr/bin/createuser -D -A %s" % (self.visitor_username))

        dbResult = pmt_utils.connectDB(self.postgres_username,
                                       self.postgres_password, self.db_name)

        if dbResult['status'] != "success":
            print dbResult['message']
            sys.exit(1)

        db = dbResult['result']

        # queryResult = pmt_utils.executeSQL(db, "DELETE FROM pg_group WHERE groname = 'admins'")

        # queryResult = pmt_utils.executeSQL(db, "INSERT INTO pg_group (groname, grosysid, grolist) VALUES ('admins', '1', '{1000}')")

        #if queryResult["status"] != 'success':
        #	print queryResult["status"]
        #	sys.exit(1)

        # queryResult = pmt_utils.executeSQL(db, "DELETE FROM pg_group WHERE groname = 'users'")

        # queryResult = pmt_utils.executeSQL(db, "INSERT INTO pg_group (groname, grosysid, grolist) VALUES ('users', '2', '{2000}')")

        # if queryResult["status"] != 'success':
        #	print queryResult["status"]
        #	sys.exit(1)

        queryResult = pmt_utils.executeSQL(
            db, "ALTER USER postgres WITH PASSWORD '%s'" %
            (self.postgres_password))

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        queryResult = pmt_utils.executeSQL(
            db, "ALTER USER %s WITH PASSWORD '%s'" %
            (self.db_admin_username, self.db_admin_password))

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        queryResult = pmt_utils.executeSQL(
            db, "ALTER USER %s WITH PASSWORD '%s'" %
            (self.visitor_username, self.visitor_password))

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        queryResult = pmt_utils.create_tables(db, declarations.define_tables(),
                                              1)

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        pmt_utils.exec_sql_file(db, self.db_name + '.tables')

        grantList = []

        privileges = declarations.table_privileges()

        for table_name in privileges.keys():
            for user_name in privileges[table_name].keys():
                grantStatement = "GRANT "
                for privilege in privileges[table_name][user_name]:
                    grantStatement = grantStatement + privilege + ", "

                grantStatement = grantStatement[:
                                                -2] + " ON " + table_name + " TO " + user_name
                grantList.append(grantStatement)

            # grant all privileges to the db admin
            grantList.append("GRANT ALL ON " + table_name + " TO " +
                             self.db_admin_username)

        queryResult = pmt_utils.executeSqlItemList(db, grantList, 1)

        if queryResult["status"] != 'success':
            print "Failed to execute all GRANTS"
            sys.exit(1)
Exemplo n.º 7
0
def query_orders(performDbQuery=0, onLoad=None, queryFields=None):

	table_data = declarations.define_tables()

	print "<HTML>"
	print "<HEAD>"

	ecommerce.javaScript("order_admin", 1)

	ecommerce.title("Order Administration")

	print "</HEAD>"

	ecommerce.bodySetup(onLoad)

	print '<CENTER>'
	print '<TABLE COLS=1 WIDTH=585>'
	print '<TR><TD>'

	ecommerce.mainHeading('Order Administration')

	ecommerce.subHeading('Order Listing')

	ecommerce.formSetup("order_admin","order_admin","return submitForm(document.order_admin)",declarations.store_info['db_name'])

	if form.has_key("username"):
		username = form["username"].value
	else:
		if form.has_key("uHidden"):
			username = form["uHidden"].value
		else:
			username = ''

	if form.has_key("password"):
		password = form["password"].value
	else:
		if form.has_key("pHidden"):
			password = form["pHidden"].value
		else:
			password = ''

	ecommerce.usernamePasswordDisplay(username, password)

	if form.has_key("performDbQuery") or performDbQuery == 1:

		dbResult = ecommerce.connectDB(username, password, declarations.store_info['db_name'])
		
		# could not connect to db
		if dbResult['status'] != 'success':
			
			ecommerce.alertsArea(form, "Can not connect to database,\n" + dbResult['message'])
			
			# connected to db

			ecommerce.queryFunctionButtons(0, declarations.store_info['help_file'])

		else:

			db = dbResult['result']
			
			# check to see if a query has been performed with at least one column

			queryFields, whereFields = ecommerce.getQueryWhereFields(form, table_data, 'orders')

			if queryFields == None or queryFields == []:
				queryFields = []
				whereFields = None
				queryFields.append('id')
				queryFields.append('customer_id')
				queryFields.append('creation_date')
				queryFields.append('shipped_date')
				queryFields.append('total')

			dbResult, queryStatement = ecommerce.executeQuery(db, table_data, 'orders', queryFields, whereFields, 'query', ecommerce.queryItemFunctionsHtml)

			# if query was not successful
			if dbResult['status'] != 'success':
				ecommerce.alertsArea(form, "Invalid query where clause specified,\n" + dbResult['message'] + '\nLast Query Statement: ' +  queryStatement)

			# else orders were retrieved ok
			else:
				ecommerce.alertsArea(form, "Last Query Statement: " + queryStatement + "\n" + `len(dbResult['result'])` + " orders retrieved from database")
				
			ecommerce.queryFunctionButtons(1, declarations.store_info['help_file'])

	else:
		ecommerce.queryFunctionButtons(0, declarations.store_info['help_file'])

	ecommerce.queryHiddenFields(username, password)

	print "</FORM>"

	try:
		ecommerce.trailer(table_data, db)
		db.close()
	except NameError:
		pass

	print '</TD>'
	print '</TR>'
	print '</TABLE>'
	print '</CENTER>'

	print "</BODY>"
	print "</HTML>"

	if form.has_key("performDbQuery") or performDbQuery == 1:
		return dbResult
	else:
		return {'status' : 'success', 'message' : 'query successful', 'result' : 0}
Exemplo n.º 8
0
def query_properties(performDbQuery=0, onLoad=None, queryFields=None):

    table_data = declarations.define_tables()

    print "<HTML>"
    print "<HEAD>"

    ecommerce.javaScript("view_properties", 1)

    ecommerce.title("Property Listing")

    print "</HEAD>"

    ecommerce.bodySetup(onLoad)

    print '<CENTER>'
    print '<TABLE COLS=1 WIDTH=585>'
    print '<TR><TD>'

    ecommerce.mainHeading('Property Listing')

    ecommerce.subHeading('View Properties')

    ecommerce.formSetup("view_properties", "view_properties",
                        "return submitForm(document.view_properties)",
                        declarations.store_info['db_name'])

    if form.has_key("performDbQuery") or performDbQuery == 1:

        dbResult = ecommerce.connectDB(
            declarations.store_info['browser_username'],
            declarations.store_info['browser_password'],
            declarations.store_info['db_name'])

        # could not connect to db
        if dbResult['status'] != 'success':

            ecommerce.alertsArea(
                form, "Can not connect to database,\n" + dbResult['message'])

            # connected to db

            ecommerce.queryFunctionButtons(
                0, declarations.store_info['help_file'])

        else:
            db = dbResult['result']

            queryFields, whereFields = ecommerce.getQueryWhereFields(
                form, table_data, 'properties')

            if queryFields == None or queryFields == []:
                queryFields = []
                whereFields = None
                queryFields.append('town')
                queryFields.append('price')
                queryFields.append('square_footage')

            dbResult, queryStatement = ecommerce.executeQuery(
                db, table_data, 'properties', queryFields, whereFields,
                'query', ecommerce.viewPropertiesFunctionsHtml, 'ORDER BY id',
                'id', "display_property = 't'",
                ['order_id', 'customer_id', 'display_property', 'image'])

            # if query was not successful
            if dbResult['status'] != 'success':
                ecommerce.alertsArea(
                    form, "Could not retrieve properties from database,\n" +
                    dbResult['message'])
            # else properties were retrieved ok
            else:
                ecommerce.alertsArea(
                    form, "Last Query Statement: " + queryStatement + "\n" +
                    ` len(dbResult['result']) ` +
                    " properties retrieved from database")

            ecommerce.viewPropertiesFunctionButtons(
                declarations.store_info['help_file'])

    else:
        ecommerce.viewPropertiesFunctionButtons(
            declarations.store_info['help_file'])

    ecommerce.viewPropertiesHiddenFields(
        declarations.store_info['browser_username'],
        declarations.store_info['browser_password'])

    print "</FORM>"

    try:
        ecommerce.trailer(table_data, db)
        db.close()
    except NameError:
        pass

    print '</TD>'
    print '</TR>'
    print '</TABLE>'
    print '</CENTER>'
    print "</BODY>"
    print "</HTML>"

    if form.has_key("performDbQuery") or performDbQuery == 1:
        return dbResult
    else:
        return {
            'status': 'success',
            'message': 'query successful',
            'result': 0
        }
Exemplo n.º 9
0
	def createProductDisplay(self):

		global default_font

		self.cart = {}
		table_data = declarations.define_tables()

		result = gadfly_utils.execute_sql_statement(db=self.db,
			sqlStatement=gadfly_utils.build_select_all_table_columns_statement(table_data,'store_info','1'),
			commit_after=1,
			leave_cursor_open=1,
			create_cursor_also=0)

		if result['status'] != 'success':
			print 'DB Error: Could not retrieve product categories'
			return result

		self.line1frame = self.createcomponent('line1frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line1frame.pack(side=TOP,fill=Y,expand=YES)

		self.productidlabel = self.createcomponent('productidlabel', (), None,
			Label,
			(self.line1frame,),
			background='white',
			foreground='black',
			font=default_font)

		self.productidlabel.pack(side=LEFT,fill=BOTH,expand=YES)

		self.productid = self.createcomponent('productid', (), None,
			Label,
			(self.line1frame,),
			background='white',
			font=default_font,
			foreground='black')

		self.productid.pack(side=LEFT,fill=BOTH,expand=YES)

		self.browser.productimagedata = ImageTk.PhotoImage(Image.open('%s%s' % (imgs,'store_logo.gif')))

		self.productimagedata = self.browser.productimagedata

		self.productid['image'] = self.browser.productimagedata

		self.line2frame = self.createcomponent('line2frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line2frame.pack(side=TOP,fill=Y,expand=YES)

		self.productdescription = self.createcomponent('productdescription', (), None,
			Label,
			(self.line2frame,),
			text='To Order by Phone Call: %s' % (result['result'][0][10]),
			font=default_font,
			background='white',
			foreground='black')

		self.productdescription.pack(side=TOP,expand=YES,fill=Y)

		self.line3frame = self.createcomponent('line3frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line3frame.pack(side=TOP,fill=Y,expand=YES)

		self.productimage = self.createcomponent('productimage', (), None,
			Label,
			(self.line3frame,),
			text=result['result'][0][2],
			font=default_font,
			background='white',
			foreground='black')

		self.productimage.pack(expand=YES,fill=Y)

		self.line4frame = self.createcomponent('line4frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line4frame.pack(side=TOP,fill=Y,expand=YES)

		self.productlongdescription = self.createcomponent('productlongdescription', (), None,
			Label,
			(self.line4frame,),
			font=default_font,
			background='white',
			foreground='black')



		self.line5frame = self.createcomponent('line5frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line5frame.pack(side=TOP,fill=Y,expand=YES)

		self.shippingweightlabel = self.createcomponent('shippingweightlabel', (), None,
			Label,
			(self.line5frame,),
			font=default_font,
			background='white',
			foreground='black')

		#self.shippingweightlabel.pack(side=LEFT,expand=YES,fill=Y)

		self.shippingweight = self.createcomponent('shippingweight', (), None,
			Label,
			(self.line5frame,),
			text='%s' % (result['result'][0][14]),
			font=default_font,
			background='white')

		#self.shippingweight.pack(side=LEFT,expand=YES,fill=Y)

		self.line6frame = self.createcomponent('line6frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line6frame.pack(side=TOP,fill=Y,expand=YES)

		self.productpricelabel = self.createcomponent('productpricelabel', (), None,
			Label,
			(self.line6frame,),
			font=default_font,
			background='white',
			foreground='black')

		self.productpricelabel.pack(side=LEFT,expand=YES,fill=Y)

		self.productprice = self.createcomponent('productprice', (), None,
			Label,
			(self.line6frame,),
			text='%s' % (result['result'][0][14]),
			wraplength=350,
			font=default_font,
			background='white')

		self.productprice.pack(side=LEFT,expand=YES,fill=Y)

		self.line7frame = self.createcomponent('line7frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line7frame.pack(side=TOP,fill=Y,expand=YES)

		self.quantitylabel = self.createcomponent('quantitylabel', (), None,
			Label,
			(self.line7frame,),
			text='Quantity:',
			font=default_font,
			background='white',
			foreground='black')

		#self.quantitylabel.pack(side=LEFT,fill=Y,expand=YES)

		self.quantitytextvar = StringVar()

		self.quantitytextvar.set('0')

		self.quantitytext = self.createcomponent('quantitytext', (), None,
			Pmw.EntryField,
			(self.line7frame,),
			value='0',
			validate= {"validator" : "numeric", "min" : 0, "max" : 999},
			entry_textvariable=self.quantitytextvar)
		self.quantitytext._entryFieldEntry.configure(width=3)

		self.line8frame = self.createcomponent('line8frame', (), None,
			Frame,
			(self.datasite,),
			background='white')

		self.line8frame.pack(side=TOP,fill=Y,expand=YES)

		self.copyrightimage = self.createcomponent('copyrightimage', (), None,
			Label,
			(self.line8frame,),
			background='white')


		self.browser.copyrightimagedata = ImageTk.PhotoImage(Image.open('%s%s' % (imgs,'linuxdenlogo.jpg')))

		self.copyrightimage['image'] = self.browser.copyrightimagedata

		self.copyrightimage.pack(side=RIGHT,padx=5)

		self.browser.quantitytext = self.quantitytext

		self.copyrightlabel = self.createcomponent('copyrightlabel', (), None,
			Label,
			(self.line8frame,),text='Copyright (c) 2000\nwww.linuXden.com\nAll Rights Reserved.',font=copyright_font,background='white',foreground='blue')

		self.copyrightlabel.pack(side=RIGHT)

		self.browser.copyrightlabel = self.copyrightlabel
		self.browser.copyrightimage = self.copyrightimage
		self.browser.productid = self.productid
		self.browser.productimage = self.productimage
		self.browser.productdescription = self.productdescription
		self.browser.productprice = self.productprice
		self.browser.quantitylabel = self.quantitylabel
Exemplo n.º 10
0
	def create_customer_data_dialog(self):
		table_data = declarations.define_tables()

		result = gadfly_utils.execute_sql_statement(db=self.db,
			sqlStatement=gadfly_utils.build_select_all_table_columns_statement(table_data,'store_info','1'),
			commit_after=1,
			leave_cursor_open=1,
			create_cursor_also=0)

		if result['status'] != 'success':
			print 'DB Error: Could not retrieve store info'
			return result

		self.customer_data_dialog = Pmw.Dialog(self._hull, buttons=('Ok',), defaultbutton='Ok', title='Customer Data Entry')

		self.customer_data = Pmw.ScrolledFrame(
			self.customer_data_dialog.interior(),
			borderframe=1,
			usehullsize=1,
			hull_width = 400,
			hull_height = 220)

		self.customer_data.pack(expand=1,fill=BOTH)

		self.firstnametextvar = StringVar()
		self.initialtextvar = StringVar()
		self.lastnametextvar = StringVar()
		self.streetline1textvar = StringVar()
		self.streetline2textvar = StringVar()
		self.citytextvar = StringVar()
		self.statetextvar = StringVar()
		self.ziptextvar = StringVar()
		self.cardnotextvar = StringVar()
		self.expdatetextvar = StringVar()

		self.first_name = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'First Name:',
			value = '',
			validate = {'max' : 40},
			entry_textvariable=self.firstnametextvar)

		#self.first_name._entryFieldEntry.configure(width=40)

		self.initial = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Middle Initial:',
			validate = {'max' : 1},
			entry_textvariable=self.initialtextvar)

		self.last_name = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Last Name:',
			validate = {'max' : 40},
			entry_textvariable=self.lastnametextvar)

		self.street_line1 = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Street Line 1:',
			validate = {'max' : 40},
			entry_textvariable=self.streetline1textvar)

		self.street_line2 = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Street Line 2:',
			validate = {'max' : 40},
			entry_textvariable=self.streetline2textvar)

		self.city = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'City:',
			validate = {'max' : 40},
			entry_textvariable=self.citytextvar)

		self.state = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'State:',
			validate = {'max' : 2},
			entry_textvariable=self.statetextvar)

		self.zip = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Zip Code:',
			validate = {'max' : 5},
			entry_textvariable=self.ziptextvar)


		result = gadfly_utils.execute_sql_statement(db=self.db,
			sqlStatement='SELECT payment_type FROM payment_methods',
			commit_after=1,
			leave_cursor_open=1,
			create_cursor_also=0)

		if result['status'] != 'success':
			print 'DB Error: Could not retrieve product categories'
			return result

		self.payment_methodvar = StringVar()
		self.payment_methodvar.set(result['result'][0][0])

		payment_options = []

		for i in xrange(0,len(result['result'])):
			payment_options.append(result['result'][i][0])

		self.payment_method = Pmw.OptionMenu(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Payment method:',
			menubutton_textvariable = self.payment_methodvar,
			items = payment_options,
			menubutton_width = 15,
			)


		self.card_number = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Credit Card Number:',
			validate = {'max' : 20},
			entry_textvariable=self.cardnotextvar)


		self.expdate = Pmw.EntryField(self.customer_data.interior(),
			labelpos = 'w',
			label_text = 'Expiration Date:',
			value = '1-1-2000',
			validate = {'validator' : 'date', 'separator' : '-',
			'min' : '1-1-2000',
			'minstrict' : 0, 'maxstrict' : 0,
			'format' : 'mdy'},
			entry_textvariable=self.expdatetextvar)
		# payment methods

		# shipping method

		entries = (self.first_name, self.initial, self.last_name,
			self.street_line1,self.street_line2,self.city,
			self.state,self.zip, self.payment_method,self.card_number,self.expdate)

		for entry in entries:
			entry.pack(fill='x', expand=1, padx=10, pady=5)

		Pmw.alignlabels(entries)

		self.customer_data_dialog.withdraw()
Exemplo n.º 11
0
def create_database(site_name, pg_password):

    # Import the new declarations file
    # Create the database
    # Create the db user and set password
    # Connect to the database as the new user and create the tables
    # Set permissions
    # Customize and run pmt_site.tables file

    print "Creating %s database" % site_name

    import declarations

    db_name = declarations.pmt_info['db_name']
    username = declarations.pmt_info['browser_username']
    password = declarations.pmt_info['browser_password']

    os.system('createdb -U postgres -q %s >> log.txt 2>> log.txt' % db_name)
    os.system('createuser -U postgres -q -D -A %s >> log.txt 2>> log.txt' %
              username)

    db = pmt_utils.connectDB('postgres', pg_password, db_name)
    sqlStatement = "ALTER USER %s WITH PASSWORD '%s'" % (username, password)
    pmt_utils.executeSQL(db['result'], sqlStatement)

    db = pmt_utils.connectDB(username, password, db_name)
    if db['status'] != 'success':
        print dbResult['message']
        sys.exit(1)

    db = db['result']

    dbCreate = pmt_utils.create_tables(db, declarations.define_tables(), 0)
    if dbCreate['status'] != 'success':
        print 'Could not create DB'
        sys.exit()

    # Create sequences
    seqList = ['project', 'pai', 'task', 'spr', 'ecp', 'project_members']
    for seq in seqList:
        sqlStatement = "CREATE SEQUENCE %s_id_seq START 1" % seq
        pmt_utils.executeSQL(db, sqlStatement)

    # Grant privileges specified in declarations
    privs = declarations.table_privileges()
    for table_name in privs.keys():
        sqlStatement = "GRANT "
        for user in privs[table_name].keys():
            for privilege in privs[table_name][user]:
                sqlStatement = sqlStatement + privilege + ', '

            sqlStatement = sqlStatement[:-2] + ' ON ' + table_name + ' TO ' + user
            #print sqlStatement
            pmt_utils.executeSQL(db, sqlStatement)

    # Customize file, run it, then change it back
    os.system('vi -c %s/pmt_usr/%s/g -c wq pmt_site.tables' % ('%s', username))
    os.system("psql %s %s -f 'pmt_site.tables' >> log.txt" %
              (db_name, username))
    #pmt_utils.exec_sql_file(db,'pmt_site.tables')
    os.system('vi -c %s/%s/pmt_usr/g -c wq pmt_site.tables' % ('%s', username))

    return db
	print "</BODY>"
	print "</HTML>"

	if form.has_key("performDbQuery") or performDbQuery == 1:
		return dbResult
	else:
		return {'status' : 'success', 'message' : 'query successful', 'result' : 0}

form = ecommerce.getFormData()

if form.has_key("action"):

	if form["action"].value == "edit":

		table_data = declarations.define_tables()

		print "<HTML>"
		print "<HEAD>"

		ecommerce.generate_form_javascript(table_data,'product_categories','product_categories_admin',0,0)

		ecommerce.title("Product Categories Administration")
		
		print "</HEAD>" 

		ecommerce.bodySetup()

		ecommerce.mainHeading('Product Categories Administration')
		
		ecommerce.subHeading('Edit Product Categories Values')
Exemplo n.º 13
0
	def create_db(self):

		import declarations

		table_data = declarations.define_tables()

		result = gadfly_utils.create_db(
			database_name = self.db_name,
			database_location = self.db_location,
			overwrite_existing_db = 1)

		if result['status'] != "success":
			print result['message']
			sys.exit(1)

		db = result['result']

		result = gadfly_utils.create_tables(
			db = db,
			table_data = table_data,
			echo_statement = 1,
			commit_after = 1,
			leave_cursor_open = 1)

		if result["status"] != 'success':
			print result['message']
			sys.exit(1)

		result = gadfly_utils.create_sequence(db=db,
			sequence_name='customer_id_seq',
			start_value=101,
			increment_by=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.create_sequence(db=db,
			sequence_name='orders_id_seq',
			start_value=101,
			increment_by=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.create_sequence(db=db,
			sequence_name='products_id_seq',
			start_value=101,
			increment_by=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.insert_from_file(db=db,
			table_data=table_data,
			table_name='products',
			filename='tec_products.dat',
			delimiter=',',
			echo_statement=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.insert_from_file(db=db,
			table_data=table_data,
			table_name='sales_tax_by_state',
			filename='tec_sales_tax_by_state.dat',
			delimiter=',',
			echo_statement=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.insert_from_file(db=db,
			table_data=table_data,
			table_name='payment_methods',
			filename='tec_payment_methods.dat',
			delimiter=',',
			echo_statement=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.insert_from_file(db=db,
			table_data=table_data,
			table_name='shipping_methods',
			filename='tec_shipping_methods.dat',
			delimiter=',',
			echo_statement=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.insert_from_file(db=db,
			table_data=table_data,
			table_name='order_status_values',
			filename='tec_order_status_values.dat',
			delimiter=',',
			echo_statement=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.insert_from_file(db=db,
			table_data=table_data,
			table_name='product_categories',
			filename='tec_product_categories.dat',
			delimiter=',',
			echo_statement=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result

		result = gadfly_utils.insert_from_file(db=db,
			table_data=table_data,
			table_name='store_info',
			filename='tec_store_info.dat',
			delimiter='|',
			echo_statement=1,
			commit_after=1,
			leave_cursor_open=1)

		if result['status'] != 'success':
			print result['message']
			return result
Exemplo n.º 14
0
def edit_project_info(performDbQuery=0, onLoad=None, queryFields=None):

    table_data = declarations.define_tables()
    print "<HTML>"
    print "<HEAD>"
    pmt_utils.javaScript("project_admin")
    pmt_utils.title("Project Administration")
    print "</HEAD>"

    pmt_utils.bodySetup(onLoad)
    pmt_utils.mainHeading('Project Administration')
    pmt_utils.subHeading('Project Info')
    pmt_utils.formSetup("project_admin", db_name, "project_admin",
                        "return submitForm(document.project_admin)")

    if username == None:
        pmt_utils.usernamePasswordDisplay()
        project_adminButtons(button_name='edit')
        pmt_utils.textbox(None, 'key_id', '1', '10', '10', None, None,
                          'hidden')
        pmt_utils.textbox(None, 'action', '', '10', '10', None, None, 'hidden')
        pmt_utils.textbox(None, 'item_no', '', '8', '8', None, None, 'hidden')
        print "</FORM>"
        try:
            pmt_utils.trailer(table_data, db)
            db.close()
        except NameError:
            pass
        print "</BODY>"
        print "</HTML>"
        return

    dbResult = pmt_utils.connectDB(declarations.pmt_info['browser_username'],
                                   declarations.pmt_info['browser_password'],
                                   declarations.pmt_info['db_name'])

    # could not connect to db
    if dbResult['status'] != 'success':
        pmt_utils.alertsArea(
            form, "Can not connect to database,\n" + dbResult['message'])
        project_adminButtons()
        print "</FORM>"
        try:
            pmt_utils.trailer(table_data, db)
            db.close()
        except NameError:
            pass
        print "</BODY>"
        print "</HTML>"
        return

    db = dbResult['result']
    status, details = db_authentication.password_valid(db,
                                                       crypt_salt=db_name,
                                                       username=username,
                                                       password=password)

    if status != 'success':
        print '<form method=post action=/%s-cgi-bin/project_admin.pyc>' % db_name
        pmt_utils.usernamePasswordDisplay(username)
        pmt_utils.alertsArea(form, 'Can not verify you as a valid user')
        print '<hr><input name=reload type=submit value="Query">'
        print '<input name=action value=edit type=hidden>'
        print '</form>'
        sys.exit()

    if pmt_utils.hasPriv(db, username, 'project_data') != 1:
        print '<form method=post action=/%s-cgi-bin/project_admin.pyc>' % db_name
        pmt_utils.usernamePasswordDisplay(username)
        msg = 'User %s does not have project admin privileges>' % username
        pmt_utils.alertsArea(form, msg)
        print '<hr><input name=reload type=submit value="Query">'
        print '<input name=action value=edit type=hidden>'
        print '</form>'
        sys.exit()

    if form.has_key('key_id'):
        key_id = form['key_id'].value
    else:
        key_id = '1'
    sqlStatement = pmt_utils.selectAllColumnsSqlStatement(
        table_data, 'project_info', key_id)
    dbResult = pmt_utils.executeSQL(db, sqlStatement)
    if dbResult['status'] != 'success':
        msg = "Could not retrieve project information\n" + dbResult['message']
        pmt_utils.alertsArea(form, msg)
    else:
        result = dbResult['result']
        table_data = pmt_utils.dbToTableData(table_data, 'project_info',
                                             result[0])
        table_data['project_info']['id']['value'] = '1'
        pmt_utils.display_form(table_data, 'project_info', 1, 'useValues', 1,
                               db)
        pmt_utils.alertsArea(form,
                             "Project Information retrieved successfully")

    project_adminButtons(button_name='save')
    pmt_utils.textbox(None, 'key_id', '', '10', '10', None, None, 'hidden')
    pmt_utils.textbox(None, 'action', '', '10', '10', None, None, 'hidden')
    pmt_utils.textbox(None, 'item_no', '', '8', '8', None, None, 'hidden')

    print "</FORM>"
    try:
        pmt_utils.trailer(table_data, db)
        db.close()
    except NameError:
        pass

    print "</BODY>"
    print "</HTML>"
Exemplo n.º 15
0
def doEdit():
    table_data = declarations.define_tables()
    print "<HTML>"
    print "<HEAD>"
    pmt_utils.generate_form_javascript(table_data, 'project_info',
                                       'project_admin', 0)
    pmt_utils.title("Project Info Administration")
    print "</HEAD>"

    pmt_utils.bodySetup()
    pmt_utils.mainHeading('Project Info Administration')
    pmt_utils.subHeading('Edit Project Info')
    pmt_utils.formSetup("project_admin", db_name, "project_admin",
                        "return submitForm(document.project_admin)")

    dbResult = pmt_utils.connectDB(declarations.pmt_info['browser_username'],
                                   declarations.pmt_info['browser_password'],
                                   declarations.pmt_info['db_name'])

    if dbResult['status'] != 'success':
        msg = "Could not connect to the database\n"
        pmt_utils.alertsArea(form, msg + dbResult['message'])
        sys.exit()

    db = dbResult['result']
    status, details = db_authentication.password_valid(db,
                                                       crypt_salt=db_name,
                                                       username=username,
                                                       password=password)
    if status != 'success':
        print '<form method=post action=/%s-cgi-bin/project_admin.pyc>' % db_name
        pmt_utils.usernamePasswordDisplay(username)
        pmt_utils.alertsArea(form, 'Can not verify you as a valid user')
        print '<hr><input name=reload type=submit value="Query">'
        print '<input name=action value=edit type=hidden>'
        print '</form>'
        sys.exit()

    if pmt_utils.hasPriv(db, username, 'project_data') != 1:
        print '<form method=post action=/%s-cgi-bin/project_admin.pyc>' % db_name
        pmt_utils.usernamePasswordDisplay(username)
        msg = 'User %s does not have project admin privileges' % username
        pmt_utils.alertsArea(form, msg)
        print '<hr><input name=reload type=submit value="Query">'
        print '<input name=action value=edit type=hidden>'
        print '</form>'
        sys.exit()

    sqlStatement = pmt_utils.selectAllColumnsSqlStatement(
        table_data, 'project_info', '1')
    dbResult = pmt_utils.executeSQL(db, sqlStatement)

    if dbResult['status'] != 'success':
        msg = "Could not retrieve project info to edit\n"
        pmt_utils.alertsArea(form, msg + dbResult['message'])
    else:
        result = dbResult['result']
        table_data = pmt_utils.dbToTableData(table_data, 'project_info',
                                             result[0])
        table_data['project_info']['id']['value'] = '1'
        pmt_utils.display_form(table_data, 'project_info', 1, 'useValues', 1,
                               db)
        pmt_utils.alertsArea(form, "Project Info retrieved successfully")

    project_adminButtons('save')
    pmt_utils.textbox(None, 'key_id', '', '10', '10', None, None, 'hidden')
    pmt_utils.textbox(None, 'action', '', '10', '10', None, None, 'hidden')
    pmt_utils.textbox(None, 'item_no', '', '8', '8', None, None, 'hidden')
    print "</FORM>"
    pmt_utils.trailer(table_data, db)
    db.close()
    print "</BODY>"
    print "</HTML>"
Exemplo n.º 16
0
def doSave():
    table_data = declarations.define_tables()

    print "<HTML>"
    print "<HEAD>"

    pmt_utils.generate_form_javascript(table_data, 'project_info',
                                       'project_admin', 0)
    pmt_utils.title("Project Info Administration")

    print "</HEAD>"

    pmt_utils.bodySetup()
    pmt_utils.mainHeading('Project Info Administration')
    pmt_utils.subHeading('Edit Project Info')
    pmt_utils.formSetup("project_admin", db_name, "project_admin",
                        "return submitForm(document.project_admin)")

    dbResult = pmt_utils.connectDB(declarations.pmt_info['browser_username'],
                                   declarations.pmt_info['browser_password'],
                                   declarations.pmt_info['db_name'])

    if dbResult['status'] != 'success':
        msg = "Project Info could not be saved, could not connect to db\n"
        pmt_utils.alertsArea(form, msg + dbResult['message'])
        # generate function button row
        project_adminButtons('save')

        # generate hidden fields for form
        pmt_utils.textbox(None, 'key_id', '', '10', '10', None, None, 'hidden')
        pmt_utils.textbox(None, 'action', '', '10', '10', None, None, 'hidden')
        pmt_utils.textbox(None, 'item_no', '', '8', '8', None, None, 'hidden')
        print "</FORM>"
        pmt_utils.trailer(table_data, db)
        db.close()
        print "</BODY>"
        print "</HTML>"
        return

    db = dbResult['result']

    # save the Form
    dbResult = pmt_utils.saveForm(table_data, db, None, "project_info",
                                  " WHERE id = '1'", form)

    # if the form was not successfully saved
    if dbResult['status'] != 'success':
        msg = "Project Info could not be saved due to an error during save,\n"
        pmt_utils.alertsArea(form, msg + dbResult['message'])
    else:
        table_data = declarations.define_tables()
        table_data = pmt_utils.formToTableData(table_data, 'project_info',
                                               form)
        table_data['project_info']['id']['value'] = '1'
        pmt_utils.display_form(table_data, 'project_info', 1, 'useValues', 1,
                               db)
        pmt_utils.alertsArea(form, "Project Info successfully saved")

    # generate function button row
    project_adminButtons('save')

    # generate hidden fields for form
    pmt_utils.textbox(None, 'key_id', '', '10', '10', None, None, 'hidden')
    pmt_utils.textbox(None, 'action', '', '10', '10', None, None, 'hidden')
    pmt_utils.textbox(None, 'item_no', '', '8', '8', None, None, 'hidden')
    print "</FORM>"
    pmt_utils.trailer(table_data, db)
    db.close()
    print "</BODY>"
    print "</HTML>"
Exemplo n.º 17
0
    def create_db(self):

        import declarations

        os.system('destroydb %s' % (self.db_name))
        os.system("createdb %s" % (self.db_name))

        os.system("/usr/bin/destroyuser " + self.db_admin_username)

        print "Answer NO to the next prompt"

        os.system("/usr/bin/createuser -i 1000 -D -U " +
                  self.db_admin_username)

        os.system("/usr/bin/destroyuser " + self.visitor_username)

        print "Answer NO to the next prompt"

        os.system("/usr/bin/createuser -i 2000 -D -U " + self.visitor_username)

        dbResult = ecommerce.connectDB(self.postgres_username,
                                       self.postgres_password, self.db_name)

        if dbResult['status'] != "success":
            print dbResult['message']
            sys.exit(1)

        db = dbResult['result']

        queryResult = ecommerce.executeSQL(
            db, "DELETE FROM pg_group WHERE groname = 'admins'")

        queryResult = ecommerce.executeSQL(
            db,
            "INSERT INTO pg_group (groname, grosysid, grolist) VALUES ('admins', '1', '{1000}')"
        )

        if queryResult["status"] != 'success':
            print queryResult["status"]
            sys.exit(1)

        queryResult = ecommerce.executeSQL(
            db, "DELETE FROM pg_group WHERE groname = 'users'")

        queryResult = ecommerce.executeSQL(
            db,
            "INSERT INTO pg_group (groname, grosysid, grolist) VALUES ('users', '2', '{2000}')"
        )

        if queryResult["status"] != 'success':
            print queryResult["status"]
            sys.exit(1)

        queryResult = ecommerce.executeSQL(
            db, "ALTER USER postgres WITH PASSWORD " + self.postgres_password)

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        queryResult = ecommerce.executeSQL(
            db, "ALTER USER %s WITH PASSWORD %s IN GROUP admins" %
            (self.db_admin_username, self.db_admin_password))

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        queryResult = ecommerce.executeSQL(
            db, "ALTER USER %s WITH PASSWORD %s IN GROUP users" %
            (self.visitor_username, self.visitor_password))

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        queryResult = ecommerce.create_tables(db, declarations.define_tables(),
                                              1)

        if queryResult["status"] != 'success':
            print queryResult['message']
            sys.exit(1)

        status, populate_tables = file_io.readFromFile(self.db_name +
                                                       '.tables')

        for index in xrange(0, len(populate_tables)):
            populate_tables[index] = string.strip(populate_tables[index])
            if populate_tables[index] == '':
                del populate_tables[index]
            elif populate_tables[index][:4] == 'COPY':
                populate_tables[index] = os.path.expandvars(
                    populate_tables[index])

        queryResult = ecommerce.executeSqlItemList(db, populate_tables, 1, 1)

        if queryResult["status"] != 'success':
            print queryResult
            print "Failed to execute all populate table statements"
            sys.exit(1)

        grantList = []

        privileges = declarations.table_privileges()

        for table_name in privileges.keys():
            for user_name in privileges[table_name].keys():
                grantStatement = "GRANT "
                for privilege in privileges[table_name][user_name]:
                    grantStatement = grantStatement + privilege + ", "

                grantStatement = grantStatement[:
                                                -2] + " ON " + table_name + " TO " + user_name
                grantList.append(grantStatement)

            # grant all privileges to the db admin
            grantList.append("GRANT ALL ON " + table_name + " TO " +
                             self.db_admin_username)

        queryResult = ecommerce.executeSqlItemList(db, grantList, 1)

        if queryResult["status"] != 'success':
            print "Failed to execute all GRANTS"
            sys.exit(1)
Exemplo n.º 18
0
def query_properties(performDbQuery=0, onLoad=None, queryFields=None):

    table_data = declarations.define_tables()

    print "<HTML>"
    print "<HEAD>"

    ecommerce.javaScript("customer_property_admin", 1)

    ecommerce.title("Customer Property Administration")

    print "</HEAD>"

    ecommerce.bodySetup(onLoad)

    print '<CENTER>'
    print '<TABLE COLS=1 WIDTH=585>'
    print '<TR><TD>'

    ecommerce.mainHeading('Customer Property Administration')

    ecommerce.subHeading('Property Listing')

    ecommerce.formSetup("customer_property_admin", "customer_property_admin",
                        "return submitForm(document.customer_property_admin)",
                        declarations.store_info['db_name'])

    if form.has_key("customer_id"):
        customer_id = form["customer_id"].value
    else:
        if form.has_key("cHidden"):
            customer_id = form["cHidden"].value
        else:
            customer_id = ''

    if form.has_key("username"):
        username = form["username"].value
    else:
        if form.has_key("uHidden"):
            username = form["uHidden"].value
        else:
            username = ''

    if form.has_key("password"):
        password = form["password"].value
    else:
        if form.has_key("pHidden"):
            password = form["pHidden"].value
        else:
            password = ''

    print '<TABLE><BORDER=0>'
    print '<TR>'

    ecommerce.tableColumn('<B>Customer ID:</B>')
    print '<TD ALIGN=CENTER NOWRAP>'

    ecommerce.textbox(None, 'customer_id', customer_id, '10', '10',
                      "checkBlankField(this, 'Customer ID')",
                      "displayHint('Enter your customer id')")
    print '</TD>'

    ecommerce.tableColumn('<B>Username:</B>')
    print '<TD ALIGN=CENTER NOWRAP>'

    ecommerce.textbox(None, 'username', username, '9', '9',
                      "checkBlankField(this, 'Username')",
                      "displayHint('Enter your username')")
    print '</TD>'

    ecommerce.tableColumn('<B>Password:</B>')

    print '<TD ALIGN=CENTER NOWRAP>'

    ecommerce.textbox(None, 'password', password, '8', '8',
                      "checkBlankField(this, 'Password')",
                      "displayHint('Enter your password')", 'password')

    print '</TD>'
    print '</TR>'
    print '</TABLE>'

    if form.has_key("performDbQuery") or performDbQuery == 1:

        dbResult = ecommerce.connectDB(
            declarations.store_info['browser_username'],
            declarations.store_info['browser_password'],
            declarations.store_info['db_name'])

        # could not connect to db
        if dbResult['status'] != 'success':

            ecommerce.alertsArea(
                form, "Can not connect to database,\n" + dbResult['message'])

            print '<HR>'
            print '<TABLE>'
            print '<TR>'
            ecommerce.tableColumn(
                '<INPUT NAME="query" type="button" value=" Query " onClick="return execute('
                + "'query'" + ')">')
            ecommerce.tableColumn(
                '<INPUT TYPE="button" NAME="help" VALUE=" Help " onClick="return goto_url ('
                + "'" + help_pdf + "'" + ')">')
            print '</TR>'
            print '</TABLE>'

        else:

            db = dbResult['result']

            # validate username password and customer id
            dbResult = ecommerce.executeSQL(
                db, "SELECT count(*) FROM customers WHERE id = '" +
                string.strip(customer_id) + "' AND account_username = '******' AND account_password = '******'")

            if dbResult['status'] != 'success':

                ecommerce.alertsArea(
                    form,
                    "Could not validate customer information provided\n" +
                    dbResult['message'])

                ecommerce.textbox(None, 'key_id', '', '10', '10', None, None,
                                  'hidden')
                ecommerce.textbox(None, 'action', '', '10', '10', None, None,
                                  'hidden')
                ecommerce.textbox(None, 'cHidden', customer_id, '10', '10',
                                  None, None, 'hidden')
                ecommerce.textbox(None, 'uHidden', username, '9', '9', None,
                                  None, 'hidden')
                ecommerce.textbox(None, 'pHidden', password, '8', '8', None,
                                  None, 'hidden')

                print "</FORM>"

                ecommerce.trailer(table_data, db)

                print '</TD>'
                print '</TR>'
                print '</TABLE>'
                print '</CENTER>'

                print "</BODY>"
                print "</HTML>"

            else:

                result = dbResult['result']

                if result[0]['count'] != 1:
                    ecommerce.alertsArea(
                        form,
                        "Could not validate customer information provided\n" +
                        dbResult['message'])
                    print '<HR>'
                    print '<TABLE>'
                    print '<TR>'
                    ecommerce.tableColumn(
                        '<INPUT NAME="query" type="button" value=" Query " onClick="return execute('
                        + "'query'" + ')">')
                    ecommerce.tableColumn(
                        '<INPUT TYPE="button" NAME="help" VALUE=" Help " onClick="return goto_url ('
                        + "'" + help_pdf + "'" + ')">')
                    print '</TR>'
                    print '</TABLE>'

                    ecommerce.textbox(None, 'key_id', '', '10', '10', None,
                                      None, 'hidden')
                    ecommerce.textbox(None, 'action', '', '10', '10', None,
                                      None, 'hidden')
                    ecommerce.textbox(None, 'cHidden', customer_id, '10', '10',
                                      None, None, 'hidden')
                    ecommerce.textbox(None, 'uHidden', username, '9', '9',
                                      None, None, 'hidden')
                    ecommerce.textbox(None, 'pHidden', password, '8', '8',
                                      None, None, 'hidden')

                    print "</FORM>"

                    ecommerce.trailer(table_data, db)

                    print '</TD>'
                    print '</TR>'
                    print '</TABLE>'
                    print '</CENTER>'

                    print "</BODY>"
                    print "</HTML>"

                    sys.exit(1)

            queryFields, whereFields = ecommerce.getQueryWhereFields(
                form, table_data, 'properties')

            if queryFields == None or queryFields == []:
                queryFields = []
                whereFields = None
                queryFields.append('id')
                queryFields.append('town')
                queryFields.append('style')
                queryFields.append('bedrooms')
                queryFields.append('price')

            dbResult, queryStatement = ecommerce.executeQuery(
                db, table_data, 'properties', queryFields, whereFields,
                'query', queryCustomerItemHtml, 'ORDER BY id', 'id',
                "customer_id='" + customer_id + "' and display_property = 't'")

            # if query was not successful
            if dbResult['status'] != 'success':
                ecommerce.alertsArea(
                    form, "Could not retrieve properties from database,\n" +
                    dbResult['message'])
            # else properties were retrieved ok
            else:
                ecommerce.alertsArea(
                    form, "Last Query Statement: " + queryStatement + "\n" +
                    ` len(dbResult['result']) ` +
                    " properties retrieved from database")

            print '<HR>'
            print '<TABLE>'
            print '<TR>'
            ecommerce.tableColumn(
                '<INPUT NAME="query" type="button" value=" Query " onClick="return execute('
                + "'query'" + ')">')
            ecommerce.tableColumn(
                '<INPUT TYPE="button" NAME="help" VALUE=" Help " onClick="return goto_url ('
                + "'" + help_pdf + "'" + ')">')
            print '</TR>'
            print '</TABLE>'

    else:
        print '<HR>'
        print '<TABLE>'
        print '<TR>'
        ecommerce.tableColumn(
            '<INPUT NAME="query" type="button" value=" Query " onClick="return execute('
            + "'query'" + ')">')
        ecommerce.tableColumn(
            '<INPUT TYPE="button" NAME="help" VALUE=" Help " onClick="return goto_url ('
            + "'" + help_pdf + "'" + ')">')
        print '</TR>'
        print '</TABLE>'

    ecommerce.textbox(None, 'key_id', '', '10', '10', None, None, 'hidden')
    ecommerce.textbox(None, 'action', '', '10', '10', None, None, 'hidden')
    ecommerce.textbox(None, 'cHidden', customer_id, '10', '10', None, None,
                      'hidden')
    ecommerce.textbox(None, 'uHidden', username, '9', '9', None, None,
                      'hidden')
    ecommerce.textbox(None, 'pHidden', password, '8', '8', None, None,
                      'hidden')

    print "</FORM>"

    try:
        ecommerce.trailer(table_data, db)
        db.close()
    except NameError:
        pass

    print '</TD>'
    print '</TR>'
    print '</TABLE>'
    print '</CENTER>'

    print "</BODY>"
    print "</HTML>"

    if form.has_key("performDbQuery") or performDbQuery == 1:
        return dbResult
    else:
        return {
            'status': 'success',
            'message': 'query successful',
            'result': 0
        }
def query_product_categories(performDbQuery=0, onLoad=None, queryFields=None):

	table_data = declarations.define_tables()

	print "<HTML>"
	print "<HEAD>"

	ecommerce.javaScript("product_categories_admin", 1)

	ecommerce.title("Product Categories Administration")

	print "</HEAD>"

	ecommerce.bodySetup(onLoad)

	ecommerce.mainHeading('Product Categories Administration')

	ecommerce.subHeading('Product Category Values')

	ecommerce.formSetup("product_categories_admin","product_categories_admin","return submitForm(document.product_categories_admin)",declarations.store_info['db_name'])

	if form.has_key("username"):
		username = form["username"].value
	else:
		if form.has_key("uHidden"):
			username = form["uHidden"].value
		else:
			username = ''

	if form.has_key("password"):
		password = form["password"].value
	else:
		if form.has_key("pHidden"):
			password = form["pHidden"].value
		else:
			password = ''

	ecommerce.usernamePasswordDisplay(username, password)

	if form.has_key("performDbQuery") or performDbQuery == 1:

		dbResult = ecommerce.connectDB(username, password, declarations.store_info['db_name'])
		
		# could not connect to db
		if dbResult['status'] != 'success':
			
			ecommerce.alertsArea(form, "Can not connect to database,\n" + dbResult['message'])
			
			# connected to db

			ecommerce.queryFunctionButtons(0, declarations.store_info['help_file'])

		else:
			db = dbResult['result']
			
			# check to see if a query has been performed with at least one column

			queryFields, whereFields = ecommerce.getQueryWhereFields(form, table_data, 'product_categories')

			if queryFields == None or queryFields == []:
				queryFields = []
				whereFields = None
				queryFields.append('category')

			dbResult, queryStatement = ecommerce.executeQuery(db, table_data, 'product_categories', queryFields, whereFields, 'query', ecommerce.queryItemFunctionsHtmlNoEdit, 'ORDER by category','category')

			# if query was not successful
			if dbResult['status'] != 'success':
				ecommerce.alertsArea(form, "Could not retrieve category values data from database,\n" + dbResult['message']);
			# else category values data was retrieved ok
			else:
				ecommerce.alertsArea(form, "Last Query Statement: " + queryStatement + "\n" + `len(dbResult['result'])` + " category value items retrieved from database");
				
			ecommerce.queryFunctionButtons(1, declarations.store_info['help_file'])

	else:
		ecommerce.queryFunctionButtons(0, declarations.store_info['help_file'])

	ecommerce.queryHiddenFields(username, password)

	print "</FORM>"

	try:
		ecommerce.trailer(table_data, db)
		db.close()
	except NameError:
		pass

	print "</BODY>"
	print "</HTML>"

	if form.has_key("performDbQuery") or performDbQuery == 1:
		return dbResult
	else:
		return {'status' : 'success', 'message' : 'query successful', 'result' : 0}
Exemplo n.º 20
0
def edit_store_info(performDbQuery=0, onLoad=None, queryFields=None):

    table_data = declarations.define_tables()

    print "<HTML>"
    print "<HEAD>"

    ecommerce.javaScript("store_admin", 1)

    ecommerce.title("Store Administration")

    print "</HEAD>"

    ecommerce.bodySetup(onLoad)

    ecommerce.mainHeading('Store Administration')

    ecommerce.subHeading('Store Info')

    ecommerce.formSetup("store_admin", "store_admin",
                        "return submitForm(document.store_admin)",
                        declarations.store_info['db_name'])

    if form.has_key("username"):
        username = form["username"].value
    else:
        if form.has_key("uHidden"):
            username = form["uHidden"].value
        else:
            username = ''

    if form.has_key("password"):
        password = form["password"].value
    else:
        if form.has_key("pHidden"):
            password = form["pHidden"].value
        else:
            password = ''

    ecommerce.usernamePasswordDisplay(username, password)

    if form.has_key("performDbQuery") or performDbQuery == 1:

        dbResult = ecommerce.connectDB(username, password,
                                       declarations.store_info['db_name'])

        # could not connect to db
        if dbResult['status'] != 'success':

            ecommerce.alertsArea(
                form, "Can not connect to database,\n" + dbResult['message'])

            # connected to db

            storeButtons()

        else:
            db = dbResult['result']

            sqlStatement = ecommerce.selectAllColumnsSqlStatement(
                table_data, 'store_info', form["key_id"].value)

            dbResult = ecommerce.executeSQL(db, sqlStatement)

            if dbResult['status'] != 'success':

                ecommerce.alertsArea(
                    form, "Could not retrieve store information\n" +
                    dbResult['message'])

            else:

                result = dbResult['result']

                table_data = ecommerce.dbToTableData(table_data, 'store_info',
                                                     result[0])

                ecommerce.table_data['store_info']['id']['value'] = '1'

                ecommerce.display_form(table_data, 'store_info', 1,
                                       'useValues', 1, db)

                ecommerce.alertsArea(
                    form, "Store Information retrieved successfully")

        storeButtons(button_name='save')

        ecommerce.editHiddenFields(form["uHidden"].value,
                                   form["pHidden"].value)

    else:

        storeButtons(button_name='edit')

        ecommerce.editHiddenFields(username, password, '1')

    print "</FORM>"

    try:
        ecommerce.trailer(table_data, db)
        db.close()
    except NameError:
        pass

    print "</BODY>"
    print "</HTML>"

    if form.has_key("performDbQuery") or performDbQuery == 1:
        return dbResult
    else:
        return {
            'status': 'success',
            'message': 'query successful',
            'result': 0
        }