コード例 #1
0
def Zutaten_delete(w, DB, c):
    """ Deletes an ingredient out of the DB if its not needed in any recipe. \n
    In addition to do so, a password is needed in the interface.
    """
    ZID = 0
    if w.LEpw2.text() == globals.masterpassword:
        if not w.LWZutaten.selectedItems():
            standartbox("Keine Zutat ausgewählt!")
        else:
            Zname = w.LWZutaten.currentItem().text()
            Zspeicher = c.execute("SELECT ID FROM Zutaten WHERE Name = ?",
                                  (Zname, ))
            for row in Zspeicher:
                ZID = row[0]
            c.execute("SELECT COUNT(*) FROM Zusammen WHERE Zutaten_ID=?",
                      (ZID, ))
            Zutatentest = c.fetchone()[0]
            # Checks if the ingredient is used in any bottle or in any recipe and reacts accordingly
            if Zutatentest == 0:
                c.execute("SELECT COUNT(*) FROM Belegung WHERE ID=?", (ZID, ))
                Zutatentest = c.fetchone()[0]
                if Zutatentest == 0:
                    c.execute("DELETE FROM Zutaten WHERE ID = ?", (ZID, ))
                    DB.commit()
                    ZutatenCB_Rezepte(w, DB, c)
                    # This isn't nececary, a simple remove is better
                    # ZutatenCB_Belegung(w, DB, c)
                    for box in range(1, 11):
                        CBBname = getattr(w, "CBB" + str(box))
                        index = CBBname.findText(Zname, Qt.MatchFixedString)
                        if index >= 0:
                            globals.supressbox = True
                            CBBname.removeItem(index)
                            globals.supressbox = False
                    Zutaten_clear(w, DB, c)
                    Zutaten_a(w, DB, c)
                    standartbox(
                        "Zutat mit der ID und dem Namen:\n<{}> <{}>\ngelöscht!"
                        .format(ZID, Zname))
                else:
                    standartbox(
                        "Achtung, die Zutat ist noch in der Belegung registriert!"
                    )
            # if the ingredient is still used in recipes, inform the user about it and the first 10 recipes
            else:
                stringsaver = c.execute(
                    "SELECT Rezepte.Name FROM Zusammen INNER JOIN Rezepte ON Rezepte.ID = Zusammen.Rezept_ID WHERE Zusammen.Zutaten_ID=?",
                    (ZID, ))
                Zutatenliste = []
                for output in stringsaver:
                    Zutatenliste.append(output[0])
                    if len(Zutatenliste) >= 10:
                        break
                Zutatenstring = ', '.join(Zutatenliste)
                standartbox(
                    "Zutat kann nicht gelöscht werden, da sie in {} Rezept(en) genutzt wird! Diese sind (maximal die zehn ersten):\n{}"
                    .format(Zutatentest, Zutatenstring))
    else:
        standartbox("Falsches Passwort!")
    w.LEpw2.setText("")
コード例 #2
0
def Rezepte_delete(w, DB, c):
    """ Deletes the selected recipe, requires the Password """
    if w.LEpw.text() == globals.masterpassword:
        if not w.LWRezepte.selectedItems():
            standartbox("Kein Rezept ausgewählt!")
        else:
            Rname = w.LWRezepte.currentItem().text()
            CocktailID = c.execute(
                "SELECT ID FROM Rezepte WHERE Name = ?", (Rname,)).fetchone()[0]
            c.execute("DELETE FROM Zusammen WHERE Rezept_ID = ?", (CocktailID,))
            c.execute("DELETE FROM Rezepte WHERE ID = ?", (CocktailID,))
            DB.commit()
            w.LWRezepte.clearSelection()
            delfind = w.LWRezepte.findItems(Rname, Qt.MatchExactly)
            if len(delfind) > 0:
                for item in delfind:
                    w.LWRezepte.takeItem(w.LWRezepte.row(item))
            delfind = w.LWMaker.findItems(Rname, Qt.MatchExactly)
            if len(delfind) > 0:
                for item in delfind:
                    w.LWMaker.takeItem(w.LWMaker.row(item))
            Rezepte_clear(w, DB, c, False)
            standartbox("Rezept mit der ID und dem Namen:\n<{}> <{}>\ngelöscht!".format(Rname, CocktailID))
    else:
        print("Falsches Passwort!")
    w.LEpw.setText("")
コード例 #3
0
def enableall(w, DB, c):
    idinput = []
    Zspeicher = c.execute("SELECT ID FROM Rezepte WHERE Enabled = 0")
    for Werte in Zspeicher:
        idinput.append(int(Werte[0]))
    c.execute("UPDATE OR IGNORE Rezepte SET Enabled = 1")
    DB.commit()
    Rezepte_a_M(w, DB, c, False, "enable", idinput)
    Rezepte_clear(w, DB, c, False)
    standartbox("Alle Rezepte wurden wieder aktiv gesetzt!")
コード例 #4
0
def save_quant(w, DB, c, wobject_name, filename, dbstring, searchstring1, searchstring2, where_=False):
    """ Saves all the amounts of the ingredients/recipes to a csv. 
    after that sets the variable ingredient/recipes counter to zero.
    Needs the password for that procedure.
    Needs a Filename, dbstring = Listname and the lifetime (ss1) variable (ss2) amount
    where_ == True: only values greater zero are exported
    """
    wherestring1 = ""
    wherestring2 = ""
    wobject = getattr(w, wobject_name)
    if wobject.text() == globals.masterpassword:
        with open(filename, mode='a', newline='') as writer_file:
            csv_writer = csv.writer(writer_file, delimiter=',')
            csv_writer.writerow(
                ["----- Neuer Export von %s -----" % datetime.date.today()])
            row1 = []
            row2 = []
            if where_:
                wherestring1 = " WHERE {} > 0".format(searchstring1)
                wherestring2 = " WHERE {} > 0".format(searchstring2)
            # selects the actual use and the names and writes them
            sqlstring = "SELECT Name, {0} FROM {1}{2} ORDER BY {0} DESC, Name ASC".format(
                searchstring1, dbstring, wherestring1)
            Zspeicher = c.execute(sqlstring)
            for row in Zspeicher:
                row1.append(row[0])
                row2.append(row[1])
            csv_writer.writerow(row1)
            csv_writer.writerow(row2)
            csv_writer.writerow(["----- Gesamte Mengen über Lebenszeit -----"])
            row1 = []
            row2 = []
            # selects the life time use and saves them
            sqlstring = "SELECT Name, {0} FROM {1}{2} ORDER BY {0} DESC, Name ASC".format(
                searchstring2, dbstring, wherestring2)
            Zspeicher = c.execute(sqlstring)
            for row in Zspeicher:
                row1.append(row[0])
                row2.append(row[1])
            csv_writer.writerow(row1)
            csv_writer.writerow(row2)
            csv_writer.writerow([" "])
        sqlstring = "UPDATE OR IGNORE {} SET {} = 0".format(dbstring, searchstring1)
        c.execute(sqlstring)
        DB.commit()
        standartbox(
            "Alle Daten wurden exportiert und die zurücksetzbaren Mengen zurückgesetzt!")
    else:
        standartbox("Falsches Passwort!")
    wobject.setText("")
コード例 #5
0
def Belegung_Flanwenden(w, DB, c):
    """ Renews all the Bottles which are checked as new. """
    for Flaschen_C in range(1, 11):
        PBname = getattr(w, "PBneu" + str(Flaschen_C))
        if PBname.isChecked():
            bottleid = c.execute("SELECT ID FROM Belegung WHERE Flasche = ?", (Flaschen_C,)).fetchone()[0]
            # the value can be None if the user checks a not used box, so its captured here
            if bottleid != 0:
                c.execute("UPDATE OR IGNORE Zutaten Set Mengenlevel = Flaschenvolumen WHERE ID = ?", (bottleid,))
    DB.commit()
    # remove all the checks from the combobuttons
    for Flaschen_C in range(1, 11):
        PBname = getattr(w, "PBneu" + str(Flaschen_C))
        PBname.setChecked(False)
    Belegung_progressbar(w, DB, c)
    standartbox("Alle Flaschen angewendet!")
コード例 #6
0
def Belegung_Flanwenden(w, DB, c):
    """ Renews all the Bottles which are checked as new. """
    for Flaschen_C in range(1, 11):
        PBname = getattr(w, "PBneu" + str(Flaschen_C))
        if PBname.isChecked():
            storevar = c.execute(
                "SELECT Zutaten.Flaschenvolumen FROM Belegung INNER JOIN Zutaten ON Zutaten.ID = Belegung.ID WHERE Belegung.Flasche = ?", (Flaschen_C,)).fetchone()
            # the value can be None if the user checks a not used box, so its captured here
            if storevar is not None:
                storevol = storevar[0]
                c.execute(
                    "UPDATE OR IGNORE Belegung SET Mengenlevel = ? WHERE Flasche = ?", (storevol, Flaschen_C))
    DB.commit()
    # remove all the checks from the combobuttons
    for Flaschen_C in range(1, 11):
        PBname = getattr(w, "PBneu" + str(Flaschen_C))
        PBname.setChecked(False)
    Belegung_progressbar(w, DB, c)
    standartbox("Alle Flaschen angewendet!")
コード例 #7
0
def CleanMachine(w, DB, c, devenvironment):
    """ Activate all Pumps for 20 s to clean them. Needs the Password. Logs the Event. """
    if not devenvironment:
        import RPi.GPIO as GPIO
        GPIO.setmode(GPIO.BCM)
    if w.LECleanMachine.text() == globals.masterpassword:
        standartbox(
            "Achtung!: Maschine wird gereinigt, genug Wasser bereitstellen! Ok zum Fortfahren.")
        logger = logging.getLogger('cocktail_application')
        template = "{:*^80}"
        logger.info(template.format("Cleaning the Pumps",))
        Pinvektor = globals.usedpins
        w.LECleanMachine.setText("")
        for row in range(0, 9):
            if not devenvironment:
                GPIO.setup(Pinvektor[row], GPIO.OUT)
        T_aktuell = 0
        while (T_aktuell < 20):
            for row in range(0, 9):
                if not devenvironment:
                    GPIO.output(Pinvektor[row], 0)
            T_aktuell += 0.1
            T_aktuell = round(T_aktuell, 1)
            time.sleep(0.1)
            qApp.processEvents()
        for row in range(0, 9):
            if not devenvironment:
                GPIO.output(Pinvektor[row], 1)
        standartbox("Fertig!!!")
    else:
        standartbox("Falsches Passwort!!!!")
    w.LECleanMachine.setText("")
コード例 #8
0
def Belegung_eintragen(w, DB, c, msgcall=False):
    """ Insert the selected Bottleorder into the DB. """
    # this import is neccecary on module level, otherwise there would be a circular import
    from maker import Rezepte_a_M
    # Checks where are entries and appends them to a list
    CBB_List = []
    dbl_check = 0
    for Flaschen_C in range(1, 11):
        CBBname = getattr(w, "CBB" + str(Flaschen_C))
        if (CBBname.currentText() != "" and CBBname.currentText() != 0):
            CBB_List.append(CBBname.currentText())
    # Checks if any ingredient is used twice, if so, dbl_check gets activated 
    for Flaschen_i in range(0, len(CBB_List)):
        for Flaschen_j in range(0, len(CBB_List)):
            if ((CBB_List[Flaschen_i] == CBB_List[Flaschen_j]) and (Flaschen_i != Flaschen_j)):
                dbl_check = 1
                standartbox("Eine der Zutaten wurde doppelt zugewiesen!")
                break
        if dbl_check == 1:
            break
    # If no error, insert values into DB
    if dbl_check == 0:
        for Flaschen_C in range(1, 11):
            Speicher_ID = 0
            CBBname = getattr(w, "CBB" + str(Flaschen_C))
            ingredientname = CBBname.currentText()
            buffer = c.execute(
                "SELECT ID FROM Zutaten WHERE Name = ?", (ingredientname,))
            for buf in buffer:
                Speicher_ID = buf[0]
            c.execute("UPDATE OR IGNORE Belegung SET ID = ?, Zutat_F = ? WHERE Flasche = ?",
                (int(Speicher_ID), ingredientname, Flaschen_C))
            DB.commit()
        Belegung_a(w, DB, c)
        Rezepte_a_M(w, DB, c)
        Belegung_progressbar(w, DB, c)
        if msgcall:
            standartbox("Belegung wurde geändert!")        
コード例 #9
0
ファイル: maker.py プロジェクト: GabeOchieng/Cocktailmaker_AW
def Maker_Zubereiten(w, DB, c, normalcheck, devenvironment):
    """ Starts the Cocktail Making procedure, if not already started.\n
    ------------------------------------------------------------ 
    Two different Modes (normalcheck) are available: \n
    "True:"   Uses the regular amount of Volume \n
    "False:"  Uses the User defined (over the GUI) Volume \n
    ------------------------------------------------------------ 
    The global variable "loopcheck" is to interrupt the procedure over the cancel button
    and the belonging function for this button. \n
    ------------------------------------------------------------
    In this Function, the Pins and the Volumeflow of each connected Pump are defined,
    if anything changes, it needs to be adapted here/in the global.py.
    """
    if not devenvironment:
        import RPi.GPIO as GPIO
        GPIO.setmode(GPIO.BCM)
    # can only start one process
    if globals.startcheck == False:
        globals.startcheck = True
        V_ZM = []
        V_FNr = []
        V_Zeit = []
        V_Volumen = 0
        V_Verbrauch = []
        timestep = 0.05
        Fixmenge = int(w.LCustomMenge.text())
        Alkoholfaktor = 1 + (w.HSIntensity.value()/100)
        MFaktor = 1
        globals.loopcheck = True
        createcheck = True
        Pinvektor = globals.usedpins
        Volumenstrom = globals.pumpvolume
        if not w.LWMaker.selectedItems():
            standartbox("Kein Rezept ausgewählt!")
        # Select ID, Bottles and amount, calculate the time and update the counter
        else:
            Zspeicher = c.execute(
                "SELECT ID, Menge FROM Rezepte WHERE Name = ?", (w.LWMaker.currentItem().text(),))
            for row in Zspeicher:
                CocktailID = row[0]
                Cocktailmenge = row[1]
            c.execute(
                "UPDATE OR IGNORE Rezepte SET Anzahl_Lifetime = Anzahl_Lifetime + 1, Anzahl = Anzahl + 1 WHERE ID = ?", (CocktailID,))
            if normalcheck == False:
                Cocktailmenge = Fixmenge
            Zspeicher = c.execute(
                "SELECT Zusammen.Menge, Belegung.Flasche, Zusammen.Alkoholisch From Zusammen INNER JOIN Belegung ON Zusammen.Zutaten_ID = Belegung.ID WHERE Zusammen.Rezept_ID = ?", (CocktailID,))
            for row in Zspeicher:
                if row[2] == 1:
                    MFaktor = Alkoholfaktor
                else:
                    MFaktor = 1
                V_ZM.append(round(int(row[0])*MFaktor, 1))
                V_FNr.append(int(row[1]))
                V_Zeit.append(
                    round((int(row[0])*MFaktor)/Volumenstrom[row[1]-1], 2))
                V_Volumen += round(int(row[0])*MFaktor, 1)
                V_Verbrauch.append(0)
            # If there is a comment, it will be checked, and the quantity of the ingredients will be added to the V_Volumen
            c.execute("SELECT Kommentar FROM Rezepte WHERE Name = ?",(w.LWMaker.currentItem().text(),))
            Zspeicher = c.fetchone()[0]
            if Zspeicher is None:
                pass
            elif len(Zspeicher) >= 1:
                mysplitstring = re.split(', | |,', Zspeicher) 
                for allwords in mysplitstring:
                    try:
                        V_Volumen += int(allwords)
                    except:
                        pass
            MVH = Cocktailmenge/V_Volumen
            if MVH != 1:
                for x in range(0, len(V_ZM)):
                    V_ZM[x] = round(V_ZM[x]*MVH, 1)
                    V_Zeit[x] = round(V_Zeit[x]*MVH, 1)
            # Checks if there is still enough volume in the Bottle
            for x in range(0, len(V_ZM)):
                mengentest = c.execute("SELECT Zutaten.Name FROM Zutaten INNER JOIN Belegung ON Zutaten.ID = Belegung.ID WHERE Belegung.Flasche = ? AND Zutaten.Mengenlevel<?", (V_FNr[x], V_ZM[x])).fetchone()
                if mengentest is not None:
                    createcheck = False
                    mangelzutat = mengentest[0]
                    standartbox("Es ist in Flasche %i mit der Zutat %s nicht mehr genug Volumen vorhanden, %.0f ml wird benötigt!" % (
                        V_FNr[x], mangelzutat, V_ZM[x]))
                    w.tabWidget.setCurrentIndex(3)
                    break
            # if all conditions are met, go on
            if createcheck:
                # Generate the Comment for the end of the Programm
                c.execute("SELECT Kommentar FROM Rezepte WHERE Name = ?",(w.LWMaker.currentItem().text(),))
                Zspeicher = c.fetchone()[0]
                if Zspeicher is not None:
                    if len(Zspeicher) >= 1:
                        mysplitstring = re.split(', |,', str(Zspeicher))
                        zusatzstring = "\n\nNoch hinzufügen:"
                        for x in mysplitstring:
                            y = x.split(' ')
                            z = "{} ".format(str(round(int(y[0])*MVH))) + ' '.join(y[1:])
                            zusatzstring = zusatzstring + "\n- ca. {}".format(z)
                    else:
                        zusatzstring = ""
                else:
                    zusatzstring = ""
                # search for the longest time
                T_max = V_Zeit[0]
                for row in range(1, len(V_Zeit)):
                    if T_max < V_Zeit[row]:
                        T_max = V_Zeit[row]
                T_aktuell = 0
                w.progressionqwindow()
                # activate the pins
                for row in range(0, len(V_FNr)):
                    if not devenvironment:
                        GPIO.setup(Pinvektor[V_FNr[row] - 1], GPIO.OUT)
                    print(
                        "Pin: " + str(Pinvektor[V_FNr[row] - 1]) + " wurde initialisiert")
                # Until the max time is reached check which channel still needs to be opened
                while (T_aktuell < T_max and globals.loopcheck):
                    if (T_aktuell) % 1 == 0:
                        print(str(T_aktuell) + " von " +
                              str(T_max) + " Sekunden ")
                    w.prow_change(T_aktuell/T_max*100)
                    for row in range(0, len(V_FNr)):
                        if V_Zeit[row] > T_aktuell:
                            if (T_aktuell) % 1 == 0:
                                print("Pin: " + str(Pinvektor[V_FNr[row] - 1]) + " aktiv, aktuelles Volumen: " + str(
                                    round(Volumenstrom[V_FNr[row] - 1]*T_aktuell, 1)))
                            if not devenvironment:
                                GPIO.output(Pinvektor[V_FNr[row] - 1], 0)
                            V_Verbrauch[row] += Volumenstrom[V_FNr[row] - 1]*timestep
                        else:
                            if (T_aktuell) % 1 == 0:
                                print(
                                    "Pin: " + str(Pinvektor[V_FNr[row] - 1]) + " geschlossen!")
                            if not devenvironment:
                                GPIO.output(Pinvektor[V_FNr[row] - 1], 1)
                    T_aktuell += timestep
                    T_aktuell = round(T_aktuell, 2)
                    time.sleep(timestep)
                    qApp.processEvents()
                # Due to safety, each channel is closed at the end
                print("-- Ende --")
                for row in range(0, len(V_FNr)):
                    print(
                        "Pin: " + str(Pinvektor[V_FNr[row] - 1]) + " wurde geschlossen")
                    if not devenvironment:
                        GPIO.output(Pinvektor[V_FNr[row] - 1], 1)
                w.prow_close()
                # Adds the usage
                for x in range(0, len(V_FNr)):
                    c.execute("UPDATE OR IGNORE Zutaten SET Mengenlevel = Mengenlevel - ? WHERE ID = (SELECT ID FROM Belegung WHERE Flasche = ?)", (round(V_Verbrauch[x]), V_FNr[x]))
                # logs all value, checks if recipe was interrupted and where
                if normalcheck:
                    mengenstring = "Standard"
                else:
                    mengenstring = str(Cocktailmenge) + " ml"
                if globals.loopcheck == False:
                    abbruchstring = " - Rezept wurde bei " + \
                        str(round(T_aktuell, 1)) + " s abgebrochen - " + \
                        str(round(Cocktailmenge*(T_aktuell + timestep)/T_max)) + " ml"
                else:
                    abbruchstring = ""
                template = "{:8} | {}{}"
                logger = logging.getLogger('cocktail_application')
                logger.info(template.format(
                    mengenstring, w.LWMaker.currentItem().text(), abbruchstring))
                print("Verbrauchsmengen: ", [round(x) for x in V_Verbrauch])
                for x in range(0, len(V_Verbrauch)):
                    c.execute("UPDATE OR IGNORE Zutaten SET Verbrauchsmenge = Verbrauchsmenge + ?, Verbrauch = Verbrauch + ? WHERE ID = (SELECT ID FROM Belegung WHERE Flasche = ?)",
                              (round(V_Verbrauch[x]), round(V_Verbrauch[x]), V_FNr[x]))
                DB.commit()
                Belegung_progressbar(w, DB, c)
                if globals.loopcheck:
                    standartbox(
                        "Der Cocktail ist fertig! Bitte kurz warten, falls noch etwas nachtropft.{}".format(zusatzstring))
                elif not globals.loopcheck:
                    standartbox("Der Cocktail wurde abgebrochen!")
                Maker_nullProB(w, DB, c)
        globals.startcheck = False
コード例 #10
0
def Zutat_eintragen(w, DB, c, newingredient=True):
    """ Insert the new ingredient into the DB, if all values are given 
    and its name is not already in the DB.
    Also can change the current selected ingredient (newingredient = False)
    """
    # print("Zutat ist: ", w.LEZutatRezept.text())
    # print("Alkoholanteil ist: ", w.LEGehaltRezept.text())
    # print("Flaschenvolumen ist: ", w.LEFlaschenvolumen.text())
    # print("Neues Rezept: {}".format(newingredient))
    Zutatentest = 0
    ingredientname = w.LEZutatRezept.text()
    # counts the entries in the DB with the name and checks if its already there
    if newingredient:
        c.execute("SELECT COUNT(*) FROM Zutaten WHERE Name=?",
                  (ingredientname, ))
        Zutatentest = c.fetchone()[0]
    if Zutatentest != 0 and newingredient:
        standartbox("Dieser Name existiert schon in der Datenbank!")
    # if the ingredient should be changed, check if its selected (should always be) and get the ID
    if not newingredient and not w.LWZutaten.selectedItems():
        Zutatentest = 1
        standartbox("Es ist keine Zutat ausgewählt!")
    elif not newingredient and w.LWZutaten.selectedItems():
        altername = w.LWZutaten.currentItem().text()
        Zspeicher = c.execute("SELECT ID FROM Zutaten WHERE Name = ?",
                              (altername, )).fetchone()[0]
        ZID = int(Zspeicher)
    # check if all Fields are filled
    if Zutatentest == 0:
        if (ingredientname == "") or (w.LEGehaltRezept.text()
                                      == "") or (w.LEFlaschenvolumen.text()
                                                 == ""):
            standartbox("Eine der Eingaben ist leer!")
            Zutatentest = 1
    # check if the numbers make sense and then saves them into variables
    if Zutatentest == 0:
        try:
            conc = int(w.LEGehaltRezept.text())
            vol = int(w.LEFlaschenvolumen.text())
            if conc > 100:
                Zutatentest = 1
                standartbox("Alkoholgehalt kann nicht größer als 100 sein!")
        except ValueError:
            Zutatentest = 1
            standartbox(
                "Alkoholgehalt und Flaschenvolumen muss eine Zahl sein!")
    # if everything is okay, insert or update the db, and the List widget
    if Zutatentest == 0:
        if newingredient:
            c.execute(
                "INSERT OR IGNORE INTO Zutaten(Name,Alkoholgehalt,Flaschenvolumen,Verbrauchsmenge,Verbrauch) VALUES (?,?,?,0,0)",
                (ingredientname, conc, vol))
        else:
            c.execute(
                "UPDATE OR IGNORE Zutaten SET Name = ?, Alkoholgehalt = ?, Flaschenvolumen = ? WHERE ID = ?",
                (ingredientname, conc, vol, ZID))
        DB.commit()
        # old ingredients need to be deleted and readded
        # also when you delete an item, the selection jumps to the next item
        # to prevent strange bugs deselect all items
        if not newingredient:
            delfind = w.LWZutaten.findItems(altername, Qt.MatchExactly)
            if len(delfind) > 0:
                for item in delfind:
                    w.LWZutaten.takeItem(w.LWZutaten.row(item))
            for i in range(w.LWZutaten.count()):
                w.LWZutaten.item(i).setSelected(False)
        w.LWZutaten.addItem(ingredientname)
        # Deletes the used values
        w.LEZutatRezept.clear()
        w.LEGehaltRezept.clear()
        w.LEFlaschenvolumen.clear()
        ZutatenCB_Rezepte(w, DB, c)
        # if its a new ingredient, adds it to the boxes and sorts them
        # if its a changed one, update the values
        for box in range(1, 11):
            CBBname = getattr(w, "CBB" + str(box))
            if newingredient:
                CBBname.addItem(ingredientname)
                CBBname.model().sort(0)
            else:
                index = CBBname.findText(altername, Qt.MatchFixedString)
                if index >= 0:
                    CBBname.setItemText(index, ingredientname)
        if newingredient:
            standartbox("Zutat eingetragen")
        else:
            standartbox(
                "Zutat mit dem Namen: <{}> under <{}> aktualisiert".format(
                    altername, ingredientname))
コード例 #11
0
def Rezept_eintragen(w, DB, c, newrecipe):
    """ Enter a new recipe into the DB, if all values are given an logical. \n
    There can be up to 8 different ingredients for each recipe. \n
    To store the values into the DB, a many to many relation is used. \n
    The newrecipe dertermines if the recipe is a new one, or an old is being updated
    """
    # val_check if triggered (eg = 1) if any condition is not met
    val_check = 0
    neuername = w.LECocktail.text()
    # Checking if Cocktailname is missing
    if (neuername == "" or neuername == 0):
        val_check = 1
        standartbox("Bitte Cocktailnamen eingeben!")
    # Checking if both values are given (ingredient and quantity)
    if val_check == 0:
        for check_v in range(1, 9):
            CBRname = getattr(w, "CBR" + str(check_v))
            LERname = getattr(w, "LER" + str(check_v))
            if ((CBRname.currentText() != "") and LERname.text() == "") or ((CBRname.currentText() == "") and LERname.text() != ""):
                val_check = 1
                standartbox("Irgendwo ist ein Wert vergessen worden!")
                break
            else:
                # Checks if quantity is a number
                if LERname.text() != "":
                    try:
                        int(LERname.text())
                    except ValueError:
                        val_check = 1
                        standartbox("Menge muss eine Zahl sein!")
                        break
    # Checks, if any ingredient was used twice
    if val_check == 0:
        Zutaten_V = []
        Mengen_V = []
        # in addition, also the values are stored into a list for later
        for check_v in range(1, 9):
            CBRname = getattr(w, "CBR" + str(check_v))
            LERname = getattr(w, "LER" + str(check_v))
            if CBRname.currentText() != "":
                Zutaten_V.append(CBRname.currentText())
                Mengen_V.append(int(LERname.text()))
        for Flaschen_i in range(0, len(Zutaten_V)):
            for Flaschen_j in range(0, len(Zutaten_V)):
                if ((Zutaten_V[Flaschen_i] == Zutaten_V[Flaschen_j]) and (Flaschen_i != Flaschen_j)):
                    standartbox("Eine der Zutaten:\n<{}>\nwurde doppelt verwendet!".format(Zutaten_V[Flaschen_i]))
                    val_check = 1
                    break
            if val_check == 1:
                break
    # checks if there is at least one ingredient, else this would make no sense
    if val_check == 0:
        if len(Zutaten_V) < 1:
            val_check = 1
            standartbox("Es muss mindestens eine Zutat eingetragen sein!")
    # Checks if both commentvalues are given (or none) and if they are, if they are numbers
    if val_check == 0:
        if (w.LEmenge_a.text() != "" and w.LEprozent_a.text() == "") or (w.LEmenge_a.text() == "" and w.LEprozent_a.text() != ""):
            val_check = 1
            standartbox("Bei den Kommentarwerten muss sowohl die Menge, als auch die Konzentration eingegeben werden!")
        elif (w.LEmenge_a.text() != "" and w.LEprozent_a.text() != ""):
            try:
                int(w.LEmenge_a.text())
                int(w.LEprozent_a.text())
            except ValueError:
                val_check = 1
                standartbox("Bei den Kommentarwerten wurde mindestens einmal keine Zahl eingegeben!")
    # Checks if the name of the recipe already exists in case of a new recipe
    if val_check == 0 and newrecipe:
        c.execute("SELECT COUNT(*) FROM Rezepte WHERE Name=?",(neuername,))
        val_check = c.fetchone()[0]
        if not val_check == 0:
            standartbox("Dieser Name existiert schon in der Datenbank!")
    # If nothing is wrong, starts writing into DB
    if val_check == 0:
        if not newrecipe:
            altername = w.LWRezepte.currentItem().text()
            c.execute("SELECT ID FROM Rezepte WHERE Name = ?", (altername,))
            CocktailID = c.fetchone()[0]
        SVol = 0
        SVolcon = 0
        SVol_alk = 0
        SVolcon_alk = 0
        # Calculates the concentration of the recipe and of the alcoholic/comment part
        for Anzahl in range(0, len(Zutaten_V)):
            c.execute("SELECT Alkoholgehalt FROM Zutaten WHERE Name = ?", (Zutaten_V[Anzahl],))
            Konzentration = c.fetchone()[0]
            Volcon = Mengen_V[Anzahl]*int(Konzentration)
            if Konzentration > 0:
                SVol_alk += Mengen_V[Anzahl]
                SVolcon_alk += Volcon
            SVol += Mengen_V[Anzahl]
            SVolcon +=  Volcon
        SVol2 = SVol
        c_com = 0
        v_com = 0
        # includes the Concentration and Amount if there was a Comment
        if w.LEmenge_a.text() != "":
            SVol2 += int(w.LEmenge_a.text())
            v_com = int(w.LEmenge_a.text())
            SVolcon += int(w.LEmenge_a.text())*int(w.LEprozent_a.text())
            c_com = int(w.LEprozent_a.text())
        Alkoholgehalt_Cocktail = int(SVolcon/SVol2)
        # for none alcoholic recipes, you can't devide by zero (SVol_alk is zero if there is no alcohol)
        if SVol_alk > 0:
            c_alk = int(SVolcon_alk/SVol_alk)
        else:
            c_alk = 0
        v_alk = SVol_alk
        if w.CHBenabled.isChecked():
            isenabled = 1
        else:
            isenabled = 0
        # Insert into recipe DB
        if newrecipe:
            c.execute("INSERT OR IGNORE INTO Rezepte(Name, Alkoholgehalt, Menge, Kommentar, Anzahl_Lifetime, Anzahl, Enabled, V_Alk, c_Alk, V_Com, c_Com) VALUES (?,?,?,?,0,0,?,?,?,?,?)",
                      (neuername, Alkoholgehalt_Cocktail, SVol, w.LEKommentar.text(), isenabled, v_alk, c_alk, v_com, c_com))
        if not newrecipe:
            c.execute("UPDATE OR IGNORE Rezepte SET Name = ?, Alkoholgehalt = ?, Menge = ?, Kommentar = ?, Enabled = ?, V_Alk = ?, c_Alk = ?, V_Com = ?, c_Com = ? WHERE ID = ?",
                      (neuername, Alkoholgehalt_Cocktail, SVol, w.LEKommentar.text(), isenabled, v_alk, c_alk, v_com, c_com, int(CocktailID)))
            c.execute("DELETE FROM Zusammen WHERE Rezept_ID = ?", (CocktailID,))
        # RezeptID, Alkoholisch and ZutatenIDs gets inserted into Zusammen DB
        c.execute("SELECT ID FROM Rezepte WHERE Name = ?", (neuername,))
        RezepteDBID = c.fetchone()[0]
        for Anzahl in range(0, len(Zutaten_V)):
            temp1 = c.execute(
                "SELECT ID, Alkoholgehalt FROM Zutaten WHERE Name = ?", (Zutaten_V[Anzahl],))
            for temp3 in temp1:
                ZutatenDBID = temp3[0]
                if temp3[1] > 0:
                    isalkoholic = 1
                else:
                    isalkoholic = 0
            c.execute("INSERT OR IGNORE INTO Zusammen(Rezept_ID, Zutaten_ID, Menge, Alkoholisch) VALUES (?, ?, ?, ?)",
                      (RezepteDBID, ZutatenDBID, Mengen_V[Anzahl], isalkoholic))
        DB.commit()
        # Removing the old name from the list and adds the new one, clears the fields
        if not newrecipe:
            delfind = w.LWRezepte.findItems(altername, Qt.MatchExactly)
            if len(delfind) > 0:
                for item in delfind:
                    w.LWRezepte.takeItem(w.LWRezepte.row(item))
            delfind = w.LWMaker.findItems(altername, Qt.MatchExactly)
            if len(delfind) > 0:
                for item in delfind:
                    w.LWMaker.takeItem(w.LWMaker.row(item))
        w.LWRezepte.addItem(neuername)
        # add needs to be checked, if all ingredients are used 
        Rezepte_a_M(w, DB, c, False, "add", RezepteDBID, isenabled)
        Rezepte_clear(w, DB, c, True)
        if newrecipe:
            standartbox("Rezept unter der ID und dem Namen:\n<{}> <{}>\neingetragen!".format(RezepteDBID, neuername))
        else:
            standartbox("Rezept mit der ID und dem Namen:\n<{}> <{}>\nunter dem Namen:\n<{}>\naktualisiert!".format(RezepteDBID, altername, neuername))