示例#1
0
	def validate(self, event=None):
		#Dictionary for list of users (username : password)
		userid = {}
		users = {}
		role = {}
		keys = CRUD.retrieve_employee()

		#Saves the input for username and pasword
		username = self.userName.get()
		Pass = self.password.get()

		for key in keys:
			if (username == key[1]):
				if (Pass == key[2]):
					self.promptWindow.destroy()

					hid = util.history()
					print(hid)
					_time = datetime.now().strftime("%H:%M:%S")
					_date = date.today().strftime("%m/%d/%y")
					_date = util.date_split(_date)


					CRUD.add_history(str(hid), 'sign', key[0], 'logged in ' + str(username), _date, _time)
					home = window(key)
					home.root.mainloop()
				else:
					self.label3.configure(text="Incorrect Password")		# Displays error if incorrect password
					self.label3.grid(column=0, row=6)
		try:	
			self.label3.configure(text="Username does not exist")		# Displays error nonexistent username
			self.label3.grid(column=0, row=6)		
		except TclError:
			pass
示例#2
0
def modify_product(productId):
    login_required(productId)
    check_if_admin(productId)
    product_name = request.form['product_name']
    product_price = request.form['product_price']
    enabled = request.form.get('enabled')
    if enabled == None:
        enabled = False
    try:
        product_filename = ""
        if 'file' in request.files:
            file = request.files['file']
            if file and allowed_file(file.filename) and file.filename != '':
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                product_filename = filename
        CRUD.actualizar_producto(productId, product_name, product_price,
                                 product_filename, enabled)
        return redirect("/admin/products/edit")
    except:
        return render_template(
            "admin-panel-products-error.html",
            message=
            "Error en la actualización del producto. Favor verificar campos ingresados."
        )
示例#3
0
    def retrieve_list(self,cat):
        if (cat == 'rdy'):
            self.current_cat='Ready to cook'
        elif (cat == 'ckd'):
            self.current_cat='Cooked'
        elif (cat == 'chc'):
            self.current_cat='Chicken'
        elif (cat == 'prk'):
            self.current_cat='Pork'

        row=CRUD.retrieve_category('"'+self.current_cat+'"')
        ylist = []
        flag = 0

        for i in range(0, len(self.item_list)): 
         
            if(util.check_if_exists(self.current_cat, self.item_list[i])):
                flag=1
                for j in range(1, len(self.item_list[i])):
                    row=CRUD.retreive_name("'"+self.item_list[i][j]+"'")
                    print(len(self.item_list[i]))
                    self._list.append("(" + str(row[0][6]) + ")" +  row[0][1] )
                break
        if(flag==0):
            for i in range(0, len(row) + 1):
                ylist.append(self.current_cat) if (i<1) else ylist.append(row[i-1][1] )
                try: self._list.append("(" + str(row[i][6]) + ")" +  row[i][1] )
                except IndexError: pass
            self.item_list.append(ylist)
示例#4
0
def update_order_total(order_id):
    items_in_order = CRUD.leer_detalles_orden(order_id)
    total = 0
    for item in items_in_order:
        total += item[3] * item[4]
    now = datetime.datetime.now()
    CRUD.update_order_total(order_id, total, now)
示例#5
0
def getOrdersInfo():
    currentOrder = CRUD.buscar_orden(session.get('user_id'))
    if not currentOrder:
        return {}
    order_id = currentOrder[0][0]
    products_in_order = CRUD.get_order_complete_info(order_id)
    return jsonify(products_in_order)
示例#6
0
def reset_password():
    try:
        if request.method == 'POST':
            email = request.form['email']
            if utils.isEmailValid(email):
                user = CRUD.buscar_un_correo(email)
                if user == None:
                    return render_template(
                        'reset-password.html',
                        RESET_OK="false",
                        Message="Correo ingresado no es válido")
                recoveryKey = get_random_key(30)
                now = datetime.datetime.now()
                CRUD.create_recovery_data(user[0], recoveryKey, now)

                yag = yagmail.SMTP(user='******',
                                   password='******')
                yag.send(to=email,
                         subject='Recupera tu contraseña',
                         contents=render_template('reset-email-template.html',
                                                  username=user[1],
                                                  email=user[2].replace(
                                                      "@", "%40", 1),
                                                  recoveryKey=recoveryKey,
                                                  url=request.url_root))
                return render_template('reset-password.html', RESET_OK="true")
            else:
                return render_template('reset-password.html',
                                       RESET_OK="false",
                                       Message="Correo ingresado no es válido")
        else:
            return render_template('reset-password.html', RESET_OK="false")
    except:
        return "render_template('reset-password.html')"
示例#7
0
def save_trip_sights():
    data = request.get_json()
    # TODO:Remove this
    print(data)

    cityValue = data['selectedCityValue']  #change variable name city_Value
    travel_date_from = data['fromDate']
    travel_date_to = data['toDate']
    trip_name = data['tripName']
    checkedValuesDict = data['checkedValuesDict']
    traveler_id = CRUD.get_user_by_user_name(
        session['current_user']).traveler_id

    created_trip = CRUD.create_Trip(traveler_id, trip_name, cityValue,
                                    travel_date_from, travel_date_to)

    for place_id, sight in checkedValuesDict.items():
        get_sight = CRUD.get_sight_by_place_id(place_id)  #

        if get_sight:
            created_sight = get_sight
            print("***** found existing sight get_sight **** :", created_sight)
        else:
            created_sight = CRUD.create_Sight(place_id, sight)
            print("***** creating new sight **** :", created_sight)

        # Inserting sights in Trip Sight Table as soon as Sights are being created
        created_trip_sight = CRUD.create_Trip_Sight(
            trip_id=created_trip.trip_id, sight_id=created_sight.sight_id)

        print(created_trip_sight)

    return redirect('/itinerary')
示例#8
0
    def add_to_cart(self, product):
        product_ = CRUD.retreive_name('"'+product+'"')
        print(product)
        if(util.check_if_exists(product, self.order_list)):
            index = util.get_index(product, self.order_list)
            self.order_qty[index] = self.Tracker.qty_change
            util.replace(index, self.Table_)
            s = str(index)
        else:
            self.order_list.append(product)
            self.order_qty.append(self.Tracker.qty_change)
            s = 'end'

        print(product_)
        qty = self.Tracker.qty_change
        price = util.wholesale_check(qty, product_)
        total = price * qty
        delta = self.Tracker.qty_change - self.Tracker.qty_ref
        stock = self.Tracker.qty_s - delta
        CRUD.update_stock(str(product), int(stock))
        
        if(qty == 0):
            a = int(util.get_index(product, self.order_list))
            name=self.order_list.pop(a)
            quan=self.order_qty.pop(a)
            # self.focus_item(a)
            # self.Table_.tree.delete(self.Table_.tree.selection())
        else:
            product=product.replace(" ", "")
        
            product=(product+" "+str(qty)+" " + str(price) + " "+ str(total))
            self.Table_.tree.insert('', s, values=(product))

        total = sum(float(self.Table_.tree.set(item,3)) for item in self.Table_.tree.get_children())
        self.totala.set(total)
示例#9
0
def fetchProducts():
    product_name = request.args["name"]
    if product_name:
        res = CRUD.buscar_productos(product_name)
        return jsonify(res)
    res = CRUD.leer_productos()
    return jsonify(res)
示例#10
0
def dummy2():
    CRUD.sqlitequery()
    CRUD.adjust()

    CRUD.add_role('Admin', '111111111')
    CRUD.add_role('Cashier', '111111111')
    CRUD.add_role('Inventory Staff', '111111111')
示例#11
0
def stockReport():
    postData = request.body.read()
    queryElements = []
    input_dict = json.loads(postData)
    for x in input_dict:
        queryString = "{\"Ticker\" : \"" + str(x) + "\"}"
        print(queryString)
        CRUD.read(queryString)
示例#12
0
def orderCheckout():
    currentOrder = CRUD.buscar_orden(session.get('user_id'))
    if not currentOrder:
        return {}
    order_id = currentOrder[0][0]
    now = datetime.datetime.now()
    CRUD.order_checkout(order_id, now)
    return {}
示例#13
0
def add_stock(pid, n):
    con = sqlite3.connect('pointofsale.db')
    c = con.cursor()
    c.execute("SELECT stock FROM product WHERE productName = " + '"' +
              str(pid) + '"')
    stock = c.fetchall()
    stock_ = int(stock[0][0]) + n
    CRUD.update_stock(pid, int(stock_))
    con.close()
示例#14
0
def emptyCart():
    currentOrder = CRUD.buscar_orden(session.get('user_id'))
    if not currentOrder:
        return {}
    order_id = currentOrder[0][0]
    CRUD.delete_cart_items(order_id)
    now = datetime.datetime.now()
    CRUD.update_order_total(order_id, 0, now)
    return {}
示例#15
0
    def sign_out(self):
        hid = util.history()

        _time = datetime.now().strftime("%H:%M:%S")
        _date = date.today().strftime("%m/%d/%y")
        _date = util.date_split(_date)

        CRUD.add_history(str(hid), 'sign', self.Page_tracker.user[0],
                         'logged out ' + str(self.Page_tracker.user[1]), _date,
                         _time)
示例#16
0
def choose_trip(city):
    """View trip page"""
    location = tuple()
    # TODO:Fetch from DB
    if city == 'SFO':
        location = (37.7749, -122.4194)
    if city == 'NYC':
        location = (40.71427, -74.00597)
    if city == 'Boston':
        location = (42.35843, -71.05977)
    if city == 'Philadelphia':
        location = (39.95233, -75.16379)
    if city == 'Miami':
        location = (25.77427, -80.19366)

    lat, lng = location

    # Send request by API
    print("##################Making API call from Server#####################")
    url_data = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lng}&rankby=prominence&types=tourist_attraction&key={gmaps_key}&radius=6000'.format(
        lat=lat, lng=lng, gmaps_key=gmaps_key)
    print(url_data)

    response = requests.get(url_data)
    # Read response as json
    resp_address = response.json()
    if resp_address['status'] == 'OK':
        resp_address = resp_address['results']

        places_dictionary = {}

        for result in resp_address:
            name = result['name']
            places = result['place_id']
            lat = result['geometry']['location']['lat']
            lng = result['geometry']['location']['lng']
            vicinity_addr = result.get('vicinity', 0)
            glb_rating = result.get('rating', 0)
            totnb_reviews = result.get('user_ratings_total', 0)

            place = CRUD.get_lat_lng_by_place_id(places)
            if place:
                print("Place id already taken !")
            else:
                CRUD.create_Place_Detail(places, lat, lng, vicinity_addr,
                                         glb_rating, totnb_reviews)

            places_dictionary[places] = name

        print(places_dictionary)

        return jsonify(places_dictionary)
    else:
        print('Failed to get json response:', resp_address)
        return ('place_id is not found', location)
示例#17
0
def void_order(pid):
    con = sqlite3.connect('pointofsale.db')
    c = con.cursor()
    c.execute("SELECT productName, quantity FROM orderx WHERE orderID = " +
              '"' + pid + '"')
    s = c.fetchall()
    #rint(order[0])
    for order in s:
        add_stock(str(order[0]), int(order[1]))
    CRUD.delete_records('"' + str(pid) + '"')
    con.close()
示例#18
0
def get_modify_products():
    if request.method == 'GET':
        products = CRUD.leer_productos()
        return render_template("admin-panel-products-edit.html",
                               products=products,
                               product="")
    else:
        product = CRUD.buscar_un_producto(request.form['product_name'], "")
        return render_template("admin-panel-products-edit.html",
                               products="",
                               product=product)
示例#19
0
def get_modify_users():
    if request.method == 'GET':
        users = CRUD.leer_usuarios()
        return render_template("admin-panel-users-edit.html",
                               users=users,
                               user="")
    else:
        user = CRUD.buscar_un_usuario(request.form['username'])
        return render_template("admin-panel-users-edit.html",
                               users="",
                               user=user)
示例#20
0
def delete_itinerary_items(trip_id, sight_id):
    trip_sight = CRUD.delete_trip_sight(trip_id, sight_id)
    print(trip_sight)

    all_sights = CRUD.get_all_sights_by_trip_id(trip_id)
    print(all_sights)
    if not all_sights:
        trip = CRUD.delete_trip(trip_id)
        print("Deleted", trip)

    return "Removed Successfully!"
示例#21
0
def delete_trip(trip_id):
    trip = CRUD.delete_trip(trip_id)
    print(trip)

    trip_sights = CRUD.get_all_sights_by_trip_id(trip_id)
    for trip_sight in trip_sights:
        deleted_trip_sights = CRUD.delete_trip_sight(trip_sight.trip_id,
                                                     trip_sight.sight_id)
        print(deleted_trip_sights)

    return "Deleted Trip Successfully!"
示例#22
0
    def OnDoubleClick(self, event):

        region = self.Table_.tree.identify("region", event.x, event.y)
        if region == "heading":
            columns = ('Order ID', 'Customer', 'Items', 'Amount', 'Date',
                       'Time')
            try:
                for col in columns:
                    self.Table_.tree.heading(col, text=col, command=lambda _col=col: \
                                self.treeview_sort_column(self.Table_.tree, _col, False))
            except TclError:
                columns = ('historyID', 'Action Type', 'User ID', 'Action',
                           'Date', 'Time')
                for col in columns:
                    self.Table_.tree.heading(col, text=col, command=lambda _col=col: \
                                self.treeview_sort_column(self.Table_.tree, _col, False))
                return

        selected_item = self.Table_.tree.selection()  ## get selected item
        info = self.Table_.tree.item(selected_item)['values']

        name = ''
        index = 0

        if info[1] == 'order' or info[1] == 'sign' or info[
                1] == 'inventory' or info[1] == 'customer' or info[1] == 'void':
            messagebox.showinfo("message", str(info[3]))
            return
        for i in range(0, len(self.list_or)):
            if (int(info[0]) == int(self.list_or[i][0])):
                name = self.list_or[i][7]
                index = i
                break

        row = self.Table_.tree.item(selected_item)['values'][0]

        if messagebox.askyesno("message", "Void order of\n" + name + "?"):
            if (self.tracker.bin[8] == '0'):
                messagebox.showwarning(
                    "showwarning", "Your account doesn't have this privilege")
                return
            if messagebox.askyesno("message", "Are you sure?"):

                util.void_order(str(self.list_or[index][0]))
                util.delete_history_entry(str(self.list_or[index][6]))
                self.list_or.pop(index)
                _time = datetime.now().strftime("%H:%M:%S")
                _date = date.today().strftime("%m/%d/%y")
                _date = util.date_split(_date)
                hid = util.history()

                CRUD.add_history(str(hid), 'void', 1, 'VOIDED order' + name,
                                 _date, _time)
                self.Table_.tree.delete(selected_item)
示例#23
0
def process_registration_form():
    """ Process registration form."""

    if "email" not in session:

        name = request.form.get('name')
        email = request.form.get('email')

        CRUD.create_user(name, email)

    flash("We will be reaching out to you soon!")
    return render_template("/register.html")
示例#24
0
def update_all_city_limits(cursor):
    cities = get_all_cities(cursor)
    for city in cities:
        bases = get_base_limits_of_city(cursor, city)
        builds = get_buildings_of_city(cursor, city)
        for buildid in builds:
            buildlims = get_building_limits(cursor, buildid)
            for key in buildlims:
                bases[key] += buildlims[key]
        for key in bases:
            CRUD.update_column(cursor, "citylimits", "cityname", city, key,
                               bases[key])
示例#25
0
def search_products():
    if request.method == "GET":
        products = CRUD.leer_productos()
    else:
        product_name = request.form['product_name']
        products = ''
        if utils.isTextValid(product_name):
            products = CRUD.buscar_productos(product_name)
        else:
            return redirect("/admin/products/search")
    return render_template("admin-panel-products-search.html",
                           products=products)
示例#26
0
def adminpanel_buildingtypes():
    with db.dataBaseLock:
        cursor = db.get_cursor()
        connection = db.get_connection()
        buildingname = request.form.get('buildingname')
        buildtime = request.form.get('buildtime')
        dct = {
            "buildingname": buildingname,
            "buildtime": buildtime,
        }
        for key in dct:
            CRUD.update(cursor, "buildingtypes", "buildingname", buildingname,
                        key, dct[key])
        connection.commit()
    return redirect(url_for('adminpanel.adminpanel_func'))
示例#27
0
def MainMenu(conn_str):

    menu = {}
    menu['1'] = "Read in a File. Example: SwimmingChampoinData.csv"
    menu['2'] = "Save Data to A File"
    menu['3'] = "Add A Row To A Table"
    menu['4'] = "Update a Row"

    menu['5'] = "Make a Heat Sheet For a Meet. Example: NCAA_Summer"
    menu['6'] = "Make a Heat Sheet for a Participant and Meet, Example: RICE,NCAA_Summer"
    menu['7'] = "Make a Heat Sheet for a School and Meet, Example: RICE,NCAA_Summer"
    menu['8'] = "For a School and Meet, Display Names of Swimmers, Example: RICE,NCAA_Summer"
    menu['9'] = "For an Event and Meet, Display all Times Sorted, Example: E0107,NCAA_Summer"
    menu['A'] = "For a Meet, Display the Scores. Example: NCAA_Summer"
    #menu['B'] = "Report Errors"
    menu['B'] = "Exit"
    menu_keys=['1', '2','3', '4','5', '6', '7', '8', '9', 'A', 'B' ]
    read_menu=True
    while(read_menu):
        for k in menu_keys:
            print(k, menu[k])

        selection=input("Please Select:")
        if(selection=='1'):
            CRUD.ReadFileMenu(conn_str)
        if(selection=='2'):
            #OutputTable(tableName, path):
            CRUD.OutputTable(conn_str)
        elif(selection=='3'):
            CRUD.AddRowMenu(conn_str)
        elif(selection=='4'):
            CRUD.ChangeRowMenu(conn_str)
        elif(selection=='5'):
            Query.HeatSheetMeetMenu(conn_str)
        elif(selection=='6'):
            Query.HeatSheetParticipantMeetMenu(conn_str)
        elif(selection=='7'):
            Query.HeatSheetSchoolMeetMenu(conn_str)
        elif(selection=='8'):
            Query.CompetingSwimmer(conn_str)
        elif(selection=='9'):
            Query.HeatSheetEventMeetMenu(conn_str)
        elif (selection=='A'):
            Query.MeetFinalScore(conn_str)
        #elif (selection=='B'):
        #     ReportError(conn_str)
        elif (selection=='B'):
            read_menu=False
示例#28
0
    def inventory(self):
        if self.tracker.bin[0] == '0':
            messagebox.showwarning("showwarning",
                                   "Your account doesn't have this privilege")
            return
        for widget in self.table_frame.winfo_children():
            widget.destroy()
        self.Table_ = table(frame=self.table_frame,
                            tree_row=3,
                            tree_col=5,
                            column_id=("historyID", "Action Type", "User ID",
                                       "Action", "Date", "Time"),
                            rowheight=40,
                            height=10,
                            font_size=12,
                            font='Helvetica',
                            tablecol_width=180,
                            headingfont=30)
        list_his = CRUD.retrieve_history_byaction('inventory')
        list_his.reverse()
        self.Table_.tree.bind("<<TreeviewSelect>>", self.select_row)
        self.Table_.tree.bind("<Double-1>", self.OnDoubleClick)

        for x in list_his:
            self.Table_.tree.insert('', 'end', values=(x))
示例#29
0
def index():
    if request.method == "GET":
        return render_template('index.html')
    username = request.form["username"]
    password = request.form["password"]
    if not (utils.isUsernameValid(username)
            and utils.isPasswordValid(password)):
        return render_template("index.html",
                               Alert="Usuario y/o contraseña incorrectas.")
    user = CRUD.buscar_un_usuario(username)
    if user is None:
        flash("Usuario y/o contraseña incorrectas.")
        return render_template("index.html",
                               Alert="Usuario y/o contraseña incorrectas.")
    elif user[1] == username and check_password_hash(user[3], password):
        if user[5] == 1 or user[5] == 'True':
            create_session(user)
            resp = None
            if user[6] == 'True' or user[6] == 1:
                resp = make_response(redirect(url_for('admin')))
            else:
                resp = make_response(redirect(url_for('cashier')))
            resp.set_cookie('username', username)
            userID = str(user[0])
            resp.set_cookie('userID', userID)
            return resp
        return render_template(
            "index.html",
            Alert="Usuario deshabilitado, contacte al administrador.")
    return render_template("index.html",
                           Alert="Usuario y/o contraseña incorrectas.")
    def eliminarTarea(TablaTareas, tareas, identificador, tareaNueva):

        #Actualizar el widget correspondiente en la interfaz
        indiceNumerico = len(TablaTareas.get_children())
        TablaTareas.insert(parent='',
                           index=indiceNumerico,
                           iid=indiceNumerico,
                           text='',
                           values=(identificador, tareaNueva['descripcion'],
                                   tareaNueva['estado'], tareaNueva['tiempo']))

        #Eliminar todos los elementos (filas o hijos)
        for i in TablaTareas.get_children():
            TablaTareas.delete(i)

        #Actualizar el contenedor cargado en memoria
        CRUD.Delete(tareas, identificador)

        #Insertar en la vista todas las tareas que están cargadas en memoria posterior a la eliminación
        indiceNumerico = 0
        for identificador, tarea in tareas.items():
            TablaTareas.insert(parent='',
                               index=indiceNumerico,
                               iid=indiceNumerico,
                               text='',
                               values=(identificador, tarea['descripcion'],
                                       tarea['estado'], tarea['tiempo']))
            indiceNumerico += 1
示例#31
0
    def test_new_grid(self):
        rawData = dict(
            name="people",
            meta=[
                ["str", "firstName"],
                ["str", "lastName"],
                ["int", "age"],
                ["email", "email"],
            ])

        self.req.content = simplejson.dumps(rawData)
        g = CRUD.create_grid(self.req, None)
        self.assertEqual(rawData['name'], g.keys()[0])
        self.assertEqual(rawData['meta'], g.values()[0])