Adds the substitute list & user input #5

- Reformates code to improve readability
- Renames 3rd field of SELECT request option to harmonize data processing
- TODO : clarify messaging (CF 'WTF' strings)
This commit is contained in:
Fred Z 2018-08-07 17:40:38 +02:00
parent f9dd7d4ed6
commit e88592bf4e
2 changed files with 77 additions and 31 deletions

90
cli.py
View File

@ -15,13 +15,14 @@ You can save this product to get it later.
""" """
from os import system from os import system
from db import Db from db import Db
from config import DB_REQUEST, CLI_MSG_DISCLAIMER, CLI_MSG_ASK_CAT, \ from config import DB_REQUEST, CLI_MSG_DISCLAIMER, CLI_MSG_ASK_IDX, \
CLI_MSG_ASK_ERR, CLI_MSG_QUIT, CLI_MSG_CHOOSEN_CAT, CLI_MSG_CHOOSEN_PROD, \ CLI_MSG_ASK_ERR, CLI_MSG_QUIT, CLI_MSG_CHOOSEN_CAT, CLI_MSG_PROD, \
CLI_MSG_PROD CLI_MSG_PROD, CLI_MSG_SUBST, CLI_MSG_NO_SUBST
cli_msg = str() cli_msg = str()
product_asked = {'valid_item': False} product_asked = {'valid_item': False}
def ask_user(head_msg, foot_msg, item_list, db_obj=None): def ask_user(head_msg, foot_msg, item_list, db_obj=None):
""" """
Ask user to choose an item in the provided list, using numeric index Ask user to choose an item in the provided list, using numeric index
@ -50,7 +51,7 @@ def ask_user(head_msg, foot_msg, item_list, db_obj=None):
print(item_list['results_txt']) print(item_list['results_txt'])
print(foot_msg) print(foot_msg)
user_input = input(CLI_MSG_ASK_CAT.format(item_list['max_id'])) user_input = input(CLI_MSG_ASK_IDX.format(item_list['max_id']))
if user_input.lower() == "q": if user_input.lower() == "q":
valid_input = True valid_input = True
@ -98,13 +99,13 @@ def get_data_list(db_obj, sql):
db_obj.execute(sql) db_obj.execute(sql)
max_id = int(db_obj.cursor.rowcount - 1) max_id = int(db_obj.cursor.rowcount - 1)
results_list = [(idx, val['name'], val['COUNT(*)']) results_list = [(idx, val['name'], val['option'])
for idx, val in enumerate(db_obj.result)] for idx, val in enumerate(db_obj.result)]
# Hacky results-split for rendering in 2 columns # Hacky results-split for rendering in 2 columns
res_even = [(idx, val['name'], val['COUNT(*)']) res_even = [(idx, val['name'], val['option'])
for idx, val in enumerate(db_obj.result) if idx % 2 == 0] for idx, val in enumerate(db_obj.result) if idx % 2 == 0]
res_uneven = [(idx, val['name'], val['COUNT(*)']) res_uneven = [(idx, val['name'], val['option'])
for idx, val in enumerate(db_obj.result) if idx % 2 != 0] for idx, val in enumerate(db_obj.result) if idx % 2 != 0]
# category list # category list
results_txt = "" results_txt = ""
@ -133,14 +134,25 @@ def get_data_list(db_obj, sql):
# Starts a DB connection # Starts a DB connection
LOCAL_DB = Db() LOCAL_DB = Db()
# category list ####################
category_list = get_data_list(LOCAL_DB, DB_REQUEST['list_cat']) # LISTS CATEGORIES #
####################
category_list = get_data_list(
LOCAL_DB,
DB_REQUEST['list_cat']
)
# Prompts it with an index # Asks the user to select a category
# Asks the user to enter the index of the selected category category_asked = ask_user(
category_asked = ask_user(CLI_MSG_DISCLAIMER, cli_msg, category_list, LOCAL_DB) CLI_MSG_DISCLAIMER,
"WTF0", # cli_msg
category_list,
LOCAL_DB
)
# Lists all products ##################
# LISTS PRODUCTS #
##################
if category_asked['valid_item']: if category_asked['valid_item']:
product_list = get_data_list( product_list = get_data_list(
LOCAL_DB, DB_REQUEST['list_prod'].format(category_asked['item'][1]) LOCAL_DB, DB_REQUEST['list_prod'].format(category_asked['item'][1])
@ -148,21 +160,51 @@ if category_asked['valid_item']:
CLI_MSG_PROD = CLI_MSG_CHOOSEN_CAT.format(category_asked['item'][1]) \ CLI_MSG_PROD = CLI_MSG_CHOOSEN_CAT.format(category_asked['item'][1]) \
+ CLI_MSG_PROD + CLI_MSG_PROD
product_asked = ask_user(CLI_MSG_PROD, cli_msg, product_list) # Asks the user to select a product
product_asked = ask_user(
CLI_MSG_PROD,
"WTF1", # cli_msg
product_list
)
####################
# LISTS SUBTITUTES #
####################
if product_asked['valid_item']: if product_asked['valid_item']:
cli_msg = CLI_MSG_CHOOSEN_CAT.format(category_asked['item'][1]) substitute_list = get_data_list(
cli_msg += CLI_MSG_CHOOSEN_PROD.format(product_asked['item'][1]) LOCAL_DB,
DB_REQUEST['list_substitute'].format(
category_asked['item'][1],
product_asked['item'][2]
)
)
# No substitute found
if substitute_list['max_id'] == -1:
cli_msg = CLI_MSG_NO_SUBST.format(
product_asked['item'][1],
product_asked['item'][2]
)
# Shows product in the same category with a lowest nutriscore
elif substitute_list['max_id'] > 0:
substitute_asked = ask_user(
CLI_MSG_SUBST,
"WTF2",
substitute_list
)
if substitute_asked['valid_item']:
cli_msg = "cli_msg : «{}»\n\n".format(cli_msg)
cli_msg += "category : «{}»\n\n".format(category_asked['item'][1])
cli_msg += "product : «{}»\n\n".format(product_asked['item'][1])
cli_msg += "substitut : «{}»".format(substitute_asked['item'][1])
# Asks the user to select a substitute
# Saves if user choose it
else: else:
cli_msg = CLI_MSG_QUIT cli_msg = CLI_MSG_QUIT
# Asks the user to enter the index of the selected product
# If index is not valid, re-ask
# Shows the 1st product in the same category with the lowest nutriscore
# Saves if user choose it
print(cli_msg) print(cli_msg)

View File

@ -27,24 +27,28 @@ FIELD_KEPT = {
# CLI # CLI
DB_REQUEST = { DB_REQUEST = {
'list_cat': "SELECT c.name, COUNT(*) FROM category AS c JOIN product AS p ON p.category_id = c.id GROUP BY c.name ORDER BY COUNT(*) DESC;", 'list_cat': "SELECT c.name, COUNT(*) AS 'option' FROM category AS c JOIN product AS p ON p.category_id = c.id GROUP BY c.name ORDER BY COUNT(*) DESC;",
'list_prod': "SELECT p.name, 'COUNT(*)' FROM product AS p LEFT JOIN category AS c ON p.category_id = c.id WHERE c.name = '{}';", 'list_prod': "SELECT p.name, p.nutrition_grades AS 'option' FROM product AS p LEFT JOIN category AS c ON p.category_id = c.id WHERE c.name = '{}';",
'get_better': "SELECT p.name, p.nutrition_grades FROM product AS p LEFT JOIN category AS c ON p.category_id = c.id WHERE c.name = '{}' AND p.nutrition_grades < '{}'", 'list_substitute': "SELECT p.name, p.nutrition_grades AS 'option' FROM product AS p LEFT JOIN category AS c ON p.category_id = c.id WHERE c.name = '{}' AND p.nutrition_grades < '{}'",
'save_substitute': "UPDATE product SET substitute_id={} WHERE id={}", 'save_substitute': "UPDATE product SET substitute_id={} WHERE id={}",
} }
CLI_MSG_DISCLAIMER = "\n# # # Bienvenu sur le terminal # # #\n"\ CLI_MSG_DISCLAIMER = "\n# # # Bienvenu sur le terminal # # #\n"\
"Voici la liste des catégories disponibles : \n" "Voici la liste des catégories disponibles : \n"
CLI_MSG_PROD = "Produits disponibles :\n"
CLI_MSG_ASK_CAT = "Saisissez le nombre de la catégorie choisie [0-{}]"\ CLI_MSG_PROD = "Produits disponibles :\n"
"\n(«Q» pour quitter): " CLI_MSG_SUBST = "Substituts disponibles :\n"
CLI_MSG_ASK_IDX = "Index choisi [0-{}] («Q»uitter) :"
CLI_MSG_ASK_BAK = "Voulez vous sauvegarder «{}» en substitut du produit «{}»?"\
" [O/N]\n(«Q» pour quitter): "
CLI_MSG_ASK_ERR = "\nSaisie incorrecte : «{}»" CLI_MSG_ASK_ERR = "\nSaisie incorrecte : «{}»"
CLI_MSG_QUIT = "\nAu revoir!" CLI_MSG_QUIT = "\nAu revoir!"
CLI_MSG_CHOOSEN_CAT = "# # Categorie : [ {} ]\n" CLI_MSG_CHOOSEN_CAT = "# # Categorie : [ {} ]\n"
CLI_MSG_CHOOSEN_PROD = "\n# Produits : [ {} ]" CLI_MSG_CHOOSEN_PROD = "\n# Produits : [ {} ]"
CLI_MSG_CHOOSEN_SUBST = "\nSubstitut : [ {} ]"
CLI_MSG_NO_SUBST = "Pas de substitut trouvé pour le produit «{}» (nutriscore : «{}»)"
CLI_ITEM_MAX_LEN = 15 CLI_ITEM_MAX_LEN = 15
# DATABASE # DATABASE