Browse Source

validation prompt, calculation

Inyoung 8 years ago
parent
commit
8789861224
7 changed files with 191 additions and 56 deletions
  1. 127 47
      app.py
  2. 29 0
      appunittest.py
  3. 26 0
      appunittest2.py
  4. 1 0
      itemlist.txt
  5. 1 0
      pytest.txt
  6. 1 1
      static/js/scripts.js
  7. 6 8
      templates/index.html

+ 127 - 47
app.py

@@ -1,11 +1,14 @@
 # File Name: app.py
-# Author Name: In-young Choung
-# Date: March 1, 2017
+# Modified Date: March 24, 2017
 # Description: This python file contains database configuration and creates database tables and fields using flask_sqlalchemy.
 #              Users' values passed from Javascript are inserted into the database table.
 #              It also has mapping request to interact with specific html files and
 #              it reads a file of itemlist.text and prints out to the console.
 
+__author__ = "Inyoung Choung"
+
+import tkinter
+from tkinter import messagebox
 from flask_sqlalchemy import SQLAlchemy
 from flask import Flask, render_template, request
 
@@ -41,17 +44,15 @@ class Item(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     item_type = db.Column(db.String(64))
     brand_name = db.Column(db.String(64))
-    price = db.Column(db.Integer)
-    weight = db.Column(db.Integer)
+    price = db.Column(db.DECIMAL)
+    weight = db.Column(db.DECIMAL)
     weight_type = db.Column(db.String(5))
-    discount = db.Column(db.Integer)
+    discount = db.Column(db.DECIMAL)
     discount_type = db.Column(db.String(20))
     calc_id = db.Column(db.Integer, db.ForeignKey(Calc.id))
 
-
 # create all the tables defined as classes
-db.create_all()
-
+# db.create_all()
 
 # mapping request to URLs
 @app.route('/', methods = ['GET', 'POST'])
@@ -60,10 +61,40 @@ def index():
         # renders to html file
         return render_template('index.html')
 
+def convert(weightT1, weightT2, weight2):
+    if weightT1 == "lb":
+        if weightT2 == "kg":
+            weight2 = float(weight2) * 2.20462
+        elif weightT2 == "g":
+            weight2 = float(weight2) * 0.002205
+    elif weightT1 == "kg":
+        if weightT2 == "lb":
+            weight2 = float(weight2) * 0.453592
+        elif weightT2 == "g":
+            weight2 = float(weight2) * 0.001
+    elif weightT1 == "g":
+        if weightT2 == "kg":
+            weight2 = float(weight2) * 1000
+        elif weightT2 == "lb":
+            weight2 = float(weight2) * 453.592
+
+    return weight2
+
+
+def alert_message(message_arg):
+    if message_arg is None:
+        message = str("Please fill out all the forms.")
+    else:
+        message = message_arg
+    return message
+
+
+global newWeightForSecondItem
 
 # end point where python gets user data from javascript
 @app.route('/calculate', methods = ['GET'])
 def calculate():
+
     # get value from html
     itemtype = (request.args.get('param1'))
     brandN1 = (request.args.get('param2'))
@@ -79,33 +110,62 @@ def calculate():
     discount2 = (request.args.get('param12'))
     discountT2 = (request.args.get('param13'))
 
+    if (itemtype is None or itemtype == "" or
+        brandN1 is None or brandN1 == "" or
+        brandN2 is None or brandN2 == "" or
+        price1 is None or price1 == "" or
+        price2 is None or price2 == "" or
+        weight1 is None or weight1 == "" or
+        weightT1 is None or weightT1 == "" or
+        weight2 is None or weight2 == "" or
+        weightT2 is None or weightT2 == "" or
+        discount1 is None or discount1 == "" or
+        discountT1 is None or discountT1 == "" or
+        discount2 is None or discount2 == "" or
+        discountT2 is None or discountT2 == ""):
+            # hide main window
+            root = tkinter.Tk()
+            root.withdraw()
+            messagebox.showerror( "Alert - Empty fields", alert_message("Please fill out all the forms."))
+
+
+    # after users values are accepted, do calculation.
+    if weightT1 != weightT2:
+        newWeightForSecondItem = convert(weightT1, weightT2, weight2)
+        # both items have the same weight type from this point
+    else:
+        newWeightForSecondItem = weight2
+
+
+    if discountT1 == "percentage":
+        finalPrice1 = float((float(price1) - (float(price1) * (float(discount1) * float(0.01)))) / float(weight1))
+    elif discountT1 == "dollar":
+        finalPrice1 = float((float(price1) - float(discount1)) / float(weight1))
+
+
+    if discountT2 == "percentage":
+        finalPrice2 = float((float(price2) - (float(price2) * (float(discount2) * float(0.01)))) / float(newWeightForSecondItem))
+    elif discountT2 == "dollar":
+        finalPrice2 = float((float(price2) - (float(discount2))) / float(newWeightForSecondItem))
+
+
+
+    if finalPrice1 > finalPrice2:
+        priceDiff = round(float(finalPrice1 - finalPrice2), 3)
+        print(brandN1 + str(" is cheaper by "), priceDiff)
+        result = str(brandN1 + str(" is cheaper by ") + str(priceDiff) + str(" cents per unit weight "))
+    elif finalPrice1 < finalPrice2:
+        priceDiff = round(float(finalPrice2 - finalPrice1), 3)
+        print(brandN2 + str(" is cheaper by "), priceDiff)
+        result = str(brandN2 + str(" is cheaper by ") + str(priceDiff) + str(" cents per unit weight "))
+    else:
+        result = str("The price is equal so get anything!")
+
+    # hide main window
+    root = tkinter.Tk()
+    root.withdraw()
+    messagebox.showinfo("Calculation Result", result)
 
-    #TODO: calculate function
-    # total2 = float(total)
-    # new_total = 1.0 + total2
-    # print(new_total)
-    #
-    # weight_types = ['lb', 'kg', 'g']
-    #
-    # item1_byWeight = float(price1) / float(weight1);
-    # item2_byWeight = float(price2) / float(weight2);
-    #
-    # if (item1_byWeight < item2_byWeight) :
-    #     difference = float(item2_byWeight) - float(item1_byWeight)
-    #     result = (item1 + "is cheapter by " + difference)
-    # else :
-    #     difference = float(item1_byWeight) - float(item2_byWeight)
-    #     result = (item2 + "is cheapter by " + difference)
-    #
-    # print(param1 + param2)
-    # result = param1 + param2
-
-    # returns a row from db
-    # item_from_db = Item.query.filter_by(item_type=itemtype).first();
-
-    # if item_from_db is not None:
-    #     print("already exists in the database.")
-    # else:
 
     try:
         # define array variables to be ready to match with db columns
@@ -130,29 +190,49 @@ def calculate():
 
         # write it to db disk once the loop is done
         db.session.commit()
-
+        return result
     # catch the exception and print it
     except ValueError:
         print(ValueError)
         print("failed to create new row")
+        return -1
 
 
 # File I/O - prints a list of grocery items
-path = "C:\In-young Choung\Computer Programming\Self Programming Files\grocerycalc\itemlist.txt"
-# open a file for writing and create it if it doesn't exist.
-f = open(path,"w+")
-
-# open the file in the defined path and "r" read it
-f = open(path, "r")
-if f.mode == 'r':
-    # use read function to read the entire file.
-    contents = f.read()
-    #print the file content in the console
-    print(contents)
+def writefile(path, word):
+    # open a file for writing and create it if it doesn't exist.
+    if path is None:
+        # set a specific path
+        filepath = "C:\In-young Choung\Computer Programming\Self Programming Files\grocerycalc\itemlist.txt"
+        # output a file if it doesn't exist
+        f = open(filepath, "w+")
+        # write some texts inside the opened file
+        f.write("chicken, ")
+        f.write("milk")
+        readfile(filepath)
+    else: # when the path is specified
+        filepath= path
+        # output a file if it doesn't exist
+        f = open(filepath, "w+")
+        # write text that is passed as a paramter in the method
+        f.write(word)
+
+
+# read file that is created and pass filepath as a parameter
+def readfile(filepath):
+    # open the file in the defined path and "r" read it
+    f = open(filepath, "r")
+    if f.mode == 'r':
+        # use read function to read the entire file.
+        contents = f.read()
+
+        #print the file content in the console
+        print(contents)
 
 
 # main method
 if __name__ == '__main__':
     app.debug = True
     # app.debug = False
-    app.run()
+    writefile(None, None)
+    app.run()

+ 29 - 0
appunittest.py

@@ -0,0 +1,29 @@
+# File Name: appunittest.py
+# Date: March 3, 2017
+# Description: This class is for testing write file and read file in app.py
+__author__ = "Inyoung Choung"
+
+import os
+from os import path
+import unittest
+import app
+
+# testing file IO
+class writefiletest(unittest.TestCase):
+    def runTest(self):
+        # set path
+        filepath = "C:\In-young Choung\Computer Programming\Self Programming Files\grocerycalc\pytest.txt"
+
+        # create a file and write "pythontest"
+        app.writefile(filepath, "pythontest")
+
+        # read the file that is just created
+        app.readfile(filepath)
+
+        # check if the file is correctly created in the path
+        self.assertTrue(str(path.isfile("pytest.txt")))
+
+# class starter
+if __name__ == '__main__':
+    unittest.main()
+

+ 26 - 0
appunittest2.py

@@ -0,0 +1,26 @@
+# File Name: appunittest2.py
+# Modified Date: March 24, 2017
+# Description: This class is for testing message of show error function
+__author__ = "Inyoung Choung"
+
+import os
+from os import path
+import unittest
+import app
+
+# testing Show Error function
+class testShowError(unittest.TestCase):
+    def runTest(self):
+        # initialize value to message variable.
+        message = str("Here is a warning message.")
+
+        # pass the predefined message into alert_message function.
+        result = app.alert_message(message)
+
+        # check if the two values in the parameter are matched.
+        self.assertEqual(result, message)
+
+# class starter
+if __name__ == '__main__':
+    unittest.main()
+

+ 1 - 0
itemlist.txt

@@ -0,0 +1 @@
+chicken, milk

+ 1 - 0
pytest.txt

@@ -0,0 +1 @@
+pythontest

+ 1 - 1
static/js/scripts.js

@@ -33,7 +33,7 @@ function calc_handle(itemtype, brandN1, brandN2, price1, price2,
     x.open("GET", '/calculate?param1=' + itemtype + '&param2=' + brandN1 + '&param3=' + brandN2 +
                     '&param4=' + price1 + '&param5=' + price2 + '&param6=' + weight1 + '&param7=' + weightT1 +
                     '&param8=' + weight2 + '&param9=' + weightT2 + '&param10=' + discount1 + '&param11=' + discountT1 +
-                    '&param12=' + discount2 + '&param13=' + discountT2 + true);
+                    '&param12=' + discount2 + '&param13=' + discountT2);
 
     // fire the request
     x.send();

+ 6 - 8
templates/index.html

@@ -15,14 +15,15 @@ Description: This html serves content locally to interact with users
     <title>Calculate Grocery</title>
     <meta name="generator" content="Bootply" />
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
-    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
 {#    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">#}
     <!--[if lt IE 9]>
-{#      <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>#}
+      <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
     <![endif]-->
+    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
     <link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet">
     <link href="{{ url_for('static', filename='css/inyoung.css') }}" rel="stylesheet">
 
+
 </head>
 
 <body>
@@ -47,7 +48,7 @@ Description: This html serves content locally to interact with users
 {#                action="action_page.php"#}
 
 
-            <br>
+            <br><br>
             <form id = "calcform" style = "margin-left: 20%">
             <table id="comparison-table" style="width: auto;">
                 <tr>
@@ -115,7 +116,7 @@ Description: This html serves content locally to interact with users
                     <td>
                         <select>
                             <option>percentage</option>
-                            <option>buy and get free</option>
+                            <option>dollar</option>
                         </select>
                     </td>
                     <td>
@@ -124,13 +125,12 @@ Description: This html serves content locally to interact with users
                     <td>
                         <select>
                             <option>percentage</option>
-                            <option>buy and get free</option>
+                            <option>dollar</option>
                         </select>
                     </td>
                  </tr>
                 </table>
             <br><br>
-            <input type="text" value="{{ my_total }}" class="calculate_result" readonly>
             <button type="button"
                     onclick="calc_handle(this.form[0].value, this.form[1].value,
                                          this.form[2].value, this.form[3].value,
@@ -142,8 +142,6 @@ Description: This html serves content locally to interact with users
                     value="calculate_btn">Calculate</button>
             <br><br>
         </form>
-
-<p>If you click the "Submit" button, the form-data will be sent to a page called "action_page.php".</p>
         <!-- /row -->
 
         <div class="row">