From 4d254c612f27ea4fa67542b61ce496afe485df48 Mon Sep 17 00:00:00 2001 From: Christoffer Viken Date: Fri, 10 Feb 2017 17:09:22 +0000 Subject: [PATCH] PEP-8 compliance for text-based --- text_based.py | 451 +++++++++++++++++++++++++------------------------- 1 file changed, 228 insertions(+), 223 deletions(-) diff --git a/text_based.py b/text_based.py index b99977f..57ff710 100755 --- a/text_based.py +++ b/text_based.py @@ -1,17 +1,17 @@ #!/usr/bin/python # -*- coding: utf-8 -*- -import sqlalchemy -from sqlalchemy import distinct -from sqlalchemy.sql import func -from sqlalchemy import desc -import re, sys, os, traceback, signal, readline -from select import select -import os -from helpers import * import random +import re +import sys +import traceback +from select import select + +import sqlalchemy +from helpers import * +from sqlalchemy import desc +from sqlalchemy.sql import func from statistikkHelpers import statisticsTextOnly -from math import ceil random.seed() exit_commands = ['exit', 'abort', 'quit', 'bye', 'eat flaming death', 'q'] @@ -25,13 +25,14 @@ restart_commands = ['restart'] class ExitMenu(Exception): pass -class Menu(): - def __init__(self, name, items=[], prompt='> ', + +class Menu(object): + def __init__(self, name, items=None, prompt='> ', return_index=True, exit_msg=None, exit_confirm_msg=None, exit_disallowed_msg=None, help_text=None, uses_db=False): self.name = name - self.items = items + self.items = items if items is not None else [] self.prompt = prompt self.return_index = return_index self.exit_msg = exit_msg @@ -44,10 +45,10 @@ class Menu(): self.session = None def exit_menu(self): - if self.exit_disallowed_msg != None: + if self.exit_disallowed_msg is not None: print self.exit_disallowed_msg return - if self.exit_confirm_msg != None: + if self.exit_confirm_msg is not None: if not self.confirm(self.exit_confirm_msg, default=True): return raise ExitMenu() @@ -58,7 +59,7 @@ class Menu(): def set_context(self, string, display=True): self.context = string - if self.context != None and display: + if self.context is not None and display: print self.context def add_to_context(self, string): @@ -66,14 +67,14 @@ class Menu(): def printc(self, string): print string - if self.context == None: + if self.context is None: self.context = string else: self.context += '\n' + string def show_context(self): print self.header_format % self.name - if self.context != None: + if self.context is not None: print self.context def item_is_submenu(self, i): @@ -94,22 +95,22 @@ class Menu(): return i return self.items[i] - def input_str(self, prompt=None, regex=None, length_range=(None,None), + def input_str(self, prompt=None, regex=None, length_range=(None, None), empty_string_is_none=False, timeout=None): - if prompt == None: + if prompt is None: prompt = self.prompt - if regex != None: + if regex is not None: while True: result = self.input_str(prompt, length_range=length_range, empty_string_is_none=empty_string_is_none) - if result == None or re.match(regex+'$', result): + if result is None or re.match(regex + '$', result): return result else: print 'Value must match regular expression "%s"' % regex - if length_range != (None,None): + if length_range != (None, None): while True: result = self.input_str(prompt, empty_string_is_none=empty_string_is_none) - if result == None: + if result is None: length = 0 else: length = len(result) @@ -125,7 +126,8 @@ class Menu(): return result while True: try: - result = None + # result = None + # It is replaced either way if timeout: # assuming line buffering sys.stdout.write(safe_str(prompt)) @@ -166,18 +168,18 @@ class Menu(): return None return result - def special_input_choice(self, str): - ''' + def special_input_choice(self, in_str): + """ Handle choices which are not simply menu items. Override this in subclasses to implement magic menu choices. Return True if str was some valid magic menu choice, False otherwise. - ''' + """ return False def input_choice(self, number_of_choices, prompt=None): - if prompt == None: + if prompt is None: prompt = self.prompt while True: result = self.input_str(prompt) @@ -185,7 +187,7 @@ class Menu(): print 'Please enter something' # 'c' i hovedmenyen for å endre farger elif result == 'c': - os.system('echo -e "\033['+str(random.randint(40,49))+';'+str(random.randint(30,37))+';5m"') + os.system('echo -e "\033[' + str(random.randint(40, 49)) + ';' + str(random.randint(30, 37)) + ';5m"') os.system('clear') self.show_context() @@ -198,18 +200,18 @@ class Menu(): else: if result.isdigit(): choice = int(result) - if (choice == 0 and 10 <= number_of_choices): + if choice == 0 and 10 <= number_of_choices: return 10 - if (choice > 0 and choice <= number_of_choices): + if choice > 0 and choice <= number_of_choices: return choice if not self.special_input_choice(result): self.invalid_menu_choice(result) - def invalid_menu_choice(self, str): + def invalid_menu_choice(self, in_str): print 'Please enter a valid choice.' - def input_int(self, prompt=None, allowed_range=(None,None), null_allowed=False, default=None): - if prompt == None: + def input_int(self, prompt=None, allowed_range=(None, None), null_allowed=False, default=None): + if prompt is None: prompt = self.prompt if default is not None: prompt += ("[%s] " % default) @@ -237,7 +239,7 @@ class Menu(): def input_user(self, prompt=None): user = None - while user == None: + while user is None: user = self.retrieve_user(self.input_str(prompt)) return user @@ -246,27 +248,28 @@ class Menu(): def input_product(self, prompt=None): product = None - while product == None: + while product is None: product = self.retrieve_product(self.input_str(prompt)) return product def retrieve_product(self, search_str): return self.search_ui(search_product, search_str, 'product') - def input_thing(self, prompt=None, permitted_things=('user','product'), + def input_thing(self, prompt=None, permitted_things=('user', 'product'), add_nonexisting=(), empty_input_permitted=False, find_hidden_products=True): result = None - while result == None: + while result is None: search_str = self.input_str(prompt) if search_str == '' and empty_input_permitted: return None result = self.search_for_thing(search_str, permitted_things, add_nonexisting, find_hidden_products) return result - def input_multiple(self, prompt=None, permitted_things=('user','product'), + def input_multiple(self, prompt=None, permitted_things=('user', 'product'), add_nonexisting=(), empty_input_permitted=False, find_hidden_products=True): - result=None - while result == None: + result = None + num = 0 + while result is None: search_str = self.input_str(prompt) search_lst = search_str.split(" ") if search_str == '' and empty_input_permitted: @@ -275,20 +278,20 @@ class Menu(): result = self.search_for_thing(search_str, permitted_things, add_nonexisting, find_hidden_products) num = 1 - if (result == None) and (len(search_lst) > 1): + if (result is None) and (len(search_lst) > 1): print 'Interpreting input as " "' try: num = int(search_lst[0]) - result = self.search_for_thing(" ".join(search_lst[1:]), permitted_things,add_nonexisting, find_hidden_products) + result = self.search_for_thing(" ".join(search_lst[1:]), permitted_things, add_nonexisting, + find_hidden_products) # Her kan det legges inn en except ValueError, # men da blir det fort mye plaging av brukeren except Exception as e: print(e) - return (result,num) + return result, num - - def search_for_thing(self, search_str, permitted_things=('user','product'), - add_nonexisting=(), find_hidden_products = True): + def search_for_thing(self, search_str, permitted_things=('user', 'product'), + add_nonexisting=(), find_hidden_products=True): search_fun = {'user': search_user, 'product': search_product} results = {} @@ -297,18 +300,18 @@ class Menu(): results[thing] = search_fun[thing](search_str, self.session, find_hidden_products) result_values[thing] = self.search_result_value(results[thing]) selected_thing = argmax(result_values) - if results[selected_thing] == []: + if not results[selected_thing]: thing_for_type = {'card': 'user', 'username': 'user', 'bar_code': 'product', 'rfid': 'rfid'} type_guess = guess_data_type(search_str) - if type_guess != None and thing_for_type[type_guess] in add_nonexisting: + if type_guess is not None and thing_for_type[type_guess] in add_nonexisting: return self.search_add(search_str) - #print 'No match found for "%s".' % search_str + # print 'No match found for "%s".' % search_str return None return self.search_ui2(search_str, results[selected_thing], selected_thing) def search_result_value(self, result): - if result == None: + if result is None: return 0 if not isinstance(result, list): return 3 @@ -334,7 +337,7 @@ class Menu(): selection = selector.execute() if selection == 'create': username = self.input_str('Username for new user (should be same as PVV username)> ', - User.name_re, (1,10)) + User.name_re, (1, 10)) user = User(username, string) self.session.add(user) return user @@ -349,7 +352,6 @@ class Menu(): print '"%s" looks like the bar code for a product, but no such product exists.' % string return None - def search_ui(self, search_fun, search_str, thing): result = search_fun(search_str, self.session) return self.search_ui2(search_str, result, thing) @@ -379,13 +381,11 @@ class Menu(): return_index=False) return selector.execute() - - def confirm(self, prompt, default=None, timeout=None): return ConfirmMenu(prompt, default, timeout).execute() def print_header(self): - print + print "" print self.header_format % self.name def pause(self): @@ -393,34 +393,34 @@ class Menu(): def general_help(self): print ''' -DIBBLER HELP + DIBBLER HELP -The following commands are recognized (almost) everywhere: + The following commands are recognized (almost) everywhere: - help, ? -- display this help - what, ?? -- redisplay the current context - help!, ??? -- display context-specific help (if any) - faq -- display frequently asked questions (with answers) - exit, quit, etc. -- exit from the current menu + help, ? -- display this help + what, ?? -- redisplay the current context + help!, ??? -- display context-specific help (if any) + faq -- display frequently asked questions (with answers) + exit, quit, etc. -- exit from the current menu -When prompted for a user, you can type (parts of) the user name or -card number. When prompted for a product, you can type (parts of) the -product name or barcode. + When prompted for a user, you can type (parts of) the user name or + card number. When prompted for a product, you can type (parts of) the + product name or barcode. -About payment and "credit": When paying for something, use either -Dibbler or the good old money box -- never both at the same time. -Dibbler keeps track of a "credit" for each user, which is the amount -of money PVVVV owes the user. This value decreases with the -appropriate amount when you register a purchase, and you may increase -it by putting money in the box and using the "Adjust credit" menu. -''' + About payment and "credit": When paying for something, use either + Dibbler or the good old money box -- never both at the same time. + Dibbler keeps track of a "credit" for each user, which is the amount + of money PVVVV owes the user. This value decreases with the + appropriate amount when you register a purchase, and you may increase + it by putting money in the box and using the "Adjust credit" menu. + ''' def local_help(self): - if self.help_text == None: + if self.help_text is None: print 'no help here' else: - print - print 'Help for %s:' % (self.header_format%self.name) + print '' + print 'Help for %s:' % (self.header_format % self.name) print self.help_text def execute(self, **kwargs): @@ -433,22 +433,22 @@ it by putting money in the box and using the "Adjust credit" menu. self.at_exit() return None finally: - if self.session != None: + if self.session is not None: self.session.close() self.session = None - def _execute(self): + def _execute(self, **kwargs): line_format = '%' + str(len(str(len(self.items)))) + 'd ) %s' while True: self.print_header() self.set_context(None) - if len(self.items)==0: + if len(self.items) == 0: self.printc('(empty menu)') self.pause() return None for i in range(len(self.items)): - self.printc(line_format % (i+1, self.item_name(i))) - item_i = self.input_choice(len(self.items), prompt=self.prompt) -1 + self.printc(line_format % (i + 1, self.item_name(i))) + item_i = self.input_choice(len(self.items), prompt=self.prompt) - 1 if self.item_is_submenu(item_i): self.items[item_i].execute() else: @@ -456,10 +456,10 @@ it by putting money in the box and using the "Adjust credit" menu. class Selector(Menu): - def __init__(self, name, items=[], prompt='select> ', - return_index=True, - exit_msg=None, exit_confirm_msg=None, + def __init__(self, name, items=None, prompt='select> ', return_index=True, exit_msg=None, exit_confirm_msg=None, help_text=None): + if items is None: + items = [] Menu.__init__(self, name, items, prompt, return_index, exit_msg) self.header_format = '%s' @@ -467,11 +467,11 @@ class Selector(Menu): print self.header_format % self.name def local_help(self): - if self.help_text == None: + if self.help_text is None: print 'This is a selection menu. Enter one of the listed numbers, or' print '\'exit\' to go out and do something else.' else: - print + print '' print 'Help for selector (%s):' % self.name print self.help_text @@ -480,19 +480,19 @@ class ConfirmMenu(Menu): def __init__(self, prompt='confirm?', default=None, timeout=0): Menu.__init__(self, 'question', prompt=prompt, exit_disallowed_msg='Please answer yes or no') - self.default=default - self.timeout=timeout + self.default = default + self.timeout = timeout def _execute(self): options = {True: '[y]/n', False: 'y/[n]', None: 'y/n'}[self.default] while True: result = self.input_str('%s (%s) ' % (self.prompt, options), timeout=self.timeout) result = result.lower().strip() - if result in ['y','yes']: + if result in ['y', 'yes']: return True - elif result in ['n','no']: + elif result in ['n', 'no']: return False - elif self.default != None and result == '': + elif self.default is not None and result == '': return self.default else: print 'Please answer yes or no' @@ -506,7 +506,7 @@ class MessageMenu(Menu): def _execute(self): self.print_header() - print + print '' print self.message if self.pause_after_message: self.pause() @@ -608,7 +608,6 @@ class FAQMenu(Menu): ''')] - class TransferMenu(Menu): def __init__(self): Menu.__init__(self, 'Transfer credit between users', @@ -616,7 +615,7 @@ class TransferMenu(Menu): def _execute(self): self.print_header() - amount = self.input_int('Transfer amount> ', (1,100000)) + amount = self.input_int('Transfer amount> ', (1, 100000)) self.set_context('Transfering %d kr' % amount, display=False) user1 = self.input_user('From user> ') self.add_to_context(' from ' + user1.name) @@ -624,9 +623,9 @@ class TransferMenu(Menu): self.add_to_context(' to ' + user2.name) t1 = Transaction(user1, amount, - 'transfer to '+user2.name) + 'transfer to ' + user2.name) t2 = Transaction(user2, -amount, - 'transfer from '+user1.name) + 'transfer from ' + user1.name) t1.perform_transaction() t2.perform_transaction() self.session.add(t1) @@ -638,7 +637,7 @@ class TransferMenu(Menu): print 'User %s\'s credit is now %d kr' % (user2, user2.credit) except sqlalchemy.exc.SQLAlchemyError, e: print 'Could not perform transfer: %s' % e - #self.pause() + # self.pause() class AddUserMenu(Menu): @@ -647,17 +646,17 @@ class AddUserMenu(Menu): def _execute(self): self.print_header() - username = self.input_str('Username (should be same as PVV username)> ', User.name_re, (1,10)) - cardnum = self.input_str('Card number (optional)> ', User.card_re, (0,10)) + username = self.input_str('Username (should be same as PVV username)> ', User.name_re, (1, 10)) + cardnum = self.input_str('Card number (optional)> ', User.card_re, (0, 10)) cardnum = cardnum.lower() - rfid = self.input_str('RFID (optional)> ', User.rfid_re, (0,10)) + rfid = self.input_str('RFID (optional)> ', User.rfid_re, (0, 10)) user = User(username, cardnum, rfid) self.session.add(user) try: self.session.commit() print 'User %s stored' % username except sqlalchemy.exc.IntegrityError, e: - print 'Could not store user %s: %s' % (username,e) + print 'Could not store user %s: %s' % (username, e) self.pause() @@ -676,25 +675,25 @@ user, then rfid (write an empty line to remove the card number or rfid). user = self.input_user('User> ') self.printc('Editing user %s' % user.name) card_str = '"%s"' % user.card - if user.card == None: + if user.card is None: card_str = 'empty' user.card = self.input_str('Card number (currently %s)> ' % card_str, - User.card_re, (0,10), + User.card_re, (0, 10), empty_string_is_none=True) if user.card: user.card = user.card.lower() rfid_str = '"%s"' % user.rfid - if user.rfid == None: + if user.rfid is None: rfid_str = 'empty' user.rfid = self.input_str('RFID (currently %s)> ' % rfid_str, - User.rfid_re, (0,10), + User.rfid_re, (0, 10), empty_string_is_none=True) try: self.session.commit() print 'User %s stored' % user.name except sqlalchemy.exc.SQLAlchemyError, e: - print 'Could not store user %s: %s' % (user.name,e) + print 'Could not store user %s: %s' % (user.name, e) self.pause() @@ -704,16 +703,16 @@ class AddProductMenu(Menu): def _execute(self): self.print_header() - bar_code = self.input_str('Bar code> ', Product.bar_code_re, (8,13)) - name = self.input_str('Name> ', Product.name_re, (1,Product.name_length)) - price = self.input_int('Price> ', (1,100000)) + bar_code = self.input_str('Bar code> ', Product.bar_code_re, (8, 13)) + name = self.input_str('Name> ', Product.name_re, (1, Product.name_length)) + price = self.input_int('Price> ', (1, 100000)) product = Product(bar_code, name, price) self.session.add(product) try: self.session.commit() print 'Product %s stored' % name except sqlalchemy.exc.SQLAlchemyError, e: - print 'Could not store product %s: %s' % (name,e) + print 'Could not store product %s: %s' % (name, e) self.pause() @@ -734,11 +733,11 @@ class EditProductMenu(Menu): ('store', 'Store')]) what = selector.execute() if what == 'name': - product.name = self.input_str('Name[%s]> ' % product.name, Product.name_re, (1,product.name_length)) + product.name = self.input_str('Name[%s]> ' % product.name, Product.name_re, (1, product.name_length)) elif what == 'price': - product.price = self.input_int('Price[%s]> ' % product.price, (1,100000)) + product.price = self.input_int('Price[%s]> ' % product.price, (1, 100000)) elif what == 'barcode': - product.bar_code = self.input_str('Bar code[%s]> ' % product.bar_code, Product.bar_code_re, (8,13)) + product.bar_code = self.input_str('Bar code[%s]> ' % product.bar_code, Product.bar_code_re, (8, 13)) elif what == 'hidden': product.hidden = self.confirm('Hidden[%s]' % ("Y" if product.hidden else "N"), False) elif what == 'store': @@ -749,7 +748,7 @@ class EditProductMenu(Menu): print 'Could not store product %s: %s' % (product.name, e) self.pause() return - elif what == None: + elif what is None: print 'Edit aborted' return else: @@ -768,7 +767,8 @@ class ShowUserMenu(Menu): print 'RFID: %s' % user.rfid print 'Credit: %s kr' % user.credit selector = Selector('What do you want to know about %s?' % user.name, - items=[('transactions', 'Recent transactions (List of last ' + str(conf.user_recent_transaction_limit) + ')'), + items=[('transactions', 'Recent transactions (List of last ' + str( + conf.user_recent_transaction_limit) + ')'), ('products', 'Which products %s has bought, and how many' % user.name), ('transactions-all', 'Everything (List of all transactions)')]) what = selector.execute() @@ -787,7 +787,7 @@ class ShowUserMenu(Menu): for t in user.transactions[::-1]: string += ' * %s: %s %d kr, ' % \ (t.time.strftime('%Y-%m-%d %H:%M'), - {True:'in', False:'out'}[t.amount<0], + {True: 'in', False: 'out'}[t.amount < 0], abs(t.amount)) if t.purchase: string += 'purchase (' @@ -807,11 +807,11 @@ class ShowUserMenu(Menu): string = '%s\'s transactions (%d):\n' % (user.name, num_trans) else: string = '%s\'s transactions (%d, showing only last %d):\n' % (user.name, num_trans, limit) - for t in user.transactions[-1:-limit-1:-1]: + for t in user.transactions[-1:-limit - 1:-1]: string += ' * %s: %s %d kr, ' % \ - (t.time.strftime('%Y-%m-%d %H:%M'), - {True:'in', False:'out'}[t.amount<0], - abs(t.amount)) + (t.time.strftime('%Y-%m-%d %H:%M'), + {True: 'in', False: 'out'}[t.amount < 0], + abs(t.amount)) if t.purchase: string += 'purchase (' string += ', '.join(map(lambda e: e.product.name, @@ -832,7 +832,7 @@ class ShowUserMenu(Menu): products.append((product, count)) num_products = len(products) if num_products == 0: - print('No products purchased yet') + print 'No products purchased yet' else: text = '' text += 'Products purchased:\n' @@ -877,6 +877,7 @@ addition, and you can type 'what' at any time to redisplay it. When finished, write an empty line to confirm the purchase. ''' + def credit_check(self, user): """ @@ -893,7 +894,7 @@ When finished, write an empty line to confirm the purchase. print "***********************************************************************" print "***********************************************************************" - print + print "" print "$$\ $$\ $$$$$$\ $$$$$$$\ $$\ $$\ $$$$$$\ $$\ $$\ $$$$$$\\" print "$$ | $\ $$ |$$ __$$\ $$ __$$\ $$$\ $$ |\_$$ _|$$$\ $$ |$$ __$$\\" print "$$ |$$$\ $$ |$$ / $$ |$$ | $$ |$$$$\ $$ | $$ | $$$$\ $$ |$$ / \__|" @@ -902,29 +903,28 @@ When finished, write an empty line to confirm the purchase. print "$$$ / \$$$ |$$ | $$ |$$ | $$ |$$ |\$$$ | $$ | $$ |\$$$ |$$ | $$ |" print "$$ / \$$ |$$ | $$ |$$ | $$ |$$ | \$$ |$$$$$$\ $$ | \$$ |\$$$$$$ |" print "\__/ \__|\__| \__|\__| \__|\__| \__|\______|\__| \__| \______/" - print + print "" print "***********************************************************************" print "***********************************************************************" - print + print "" print "USER %s HAS LOWER CREDIT THAN %d." % (user.name, conf.low_credit_warning_limit) print "THIS PURCHASE WILL CHARGE YOUR CREDIT TWICE AS MUCH." print "CONSIDER PUTTING MONEY IN THE BOX TO AVOID THIS." - print + print "" print "Do you want to continue with this purchase?" if timeout: - print "THIS PURCHASE WILL AUTOMATICALLY BE PERFORMED IN 3 MINUTES!" + print"THIS PURCHASE WILL AUTOMATICALLY BE PERFORMED IN 3 MINUTES!" return self.confirm(prompt=">", default=True, timeout=180) else: return self.confirm(prompt=">", default=True) - def add_thing_to_purchase(self, thing): if isinstance(thing, User): if thing.is_anonymous(): print '--------------------------------------------' - print 'You are now purchasing as the user anonym.' - print 'You have to put money in the anonym-jar.' + print'You are now purchasing as the user anonym.' + print'You have to put money in the anonym-jar.' print '--------------------------------------------' if not self.credit_check(thing): @@ -938,18 +938,20 @@ When finished, write an empty line to confirm the purchase. PurchaseEntry(self.purchase, thing, 1) return True - - def _execute(self, initialContents=[]): + def _execute(self, initial_contents=None): self.print_header() self.purchase = Purchase() - self.exit_confirm_msg=None + self.exit_confirm_msg = None self.superfast_mode = False - for thing in initialContents: + if initial_contents is None: + initial_contents = [] + + for thing in initial_contents: self.add_thing_to_purchase(thing) isproduct = lambda t: isinstance(t, Product) - if len(initialContents) > 0 and all(map(isproduct, initialContents)): + if len(initial_contents) > 0 and all(map(isproduct, initial_contents)): self.superfast_mode = True print '***********************************************' print '****** Buy menu is in SUPERFASTmode[tm]! ******' @@ -959,10 +961,10 @@ When finished, write an empty line to confirm the purchase. while True: self.print_purchase() - self.printc({(False,False): 'Enter user or product identification', - (False,True): 'Enter user identification or more products', - (True,False): 'Enter product identification or more users', - (True,True): 'Enter more products or users, or an empty line to confirm' + self.printc({(False, False): 'Enter user or product identification', + (False, True): 'Enter user identification or more products', + (True, False): 'Enter product identification or more users', + (True, True): 'Enter more products or users, or an empty line to confirm' }[(len(self.purchase.transactions) > 0, len(self.purchase.entries) > 0)]) @@ -972,7 +974,7 @@ When finished, write an empty line to confirm the purchase. find_hidden_products=False) # Possibly exit from the menu: - if thing == None: + if thing is None: if not self.complete_input(): if self.confirm('Not enough information entered. Abort purchase?', default=True): @@ -983,7 +985,7 @@ When finished, write an empty line to confirm the purchase. # once we get something in the # purchase, we want to protect the # user from accidentally killing it - self.exit_confirm_msg='Abort purchase?' + self.exit_confirm_msg = 'Abort purchase?' # Add the thing to our purchase object: if not self.add_thing_to_purchase(thing): @@ -1006,11 +1008,11 @@ When finished, write an empty line to confirm the purchase. if not t.user.is_anonymous(): print 'User %s\'s credit is now %d kr' % (t.user.name, t.user.credit) if t.user.credit < conf.low_credit_warning_limit: - print ('USER %s HAS LOWER CREDIT THAN %d, AND SHOULD CONSIDER PUTTING SOME MONEY IN THE BOX.' - % (t.user.name, conf.low_credit_warning_limit)) - #skriver til log - #print Product.price - #with open("dibbler-out.txt", "a") as f: + print 'USER %s HAS LOWER CREDIT THAN %d, AND SHOULD CONSIDER PUTTING SOME MONEY IN THE BOX.'\ + % (t.user.name, conf.low_credit_warning_limit) + # skriver til log + # print Product.price + # with open("dibbler-out.txt", "a") as f: # f.write("purchase|"+ time() +"|"+self.purchase.entries[0].product.name+"|"+t.user.name+"|+str(Product.price)+|"+'-1'+"|\n") return True @@ -1029,13 +1031,14 @@ When finished, write an empty line to confirm the purchase. if len(transactions) == 0: string += '(empty)' else: - string += ', '.join(map(lambda t: t.user.name + ("*" if t.user.credit < conf.user_recent_transaction_limit else ""), - transactions)) + string += ', '.join( + map(lambda t: t.user.name + ("*" if t.user.credit < conf.user_recent_transaction_limit else ""), + transactions)) string += '\n products: ' if len(entries) == 0: string += '(empty)' else: - string += ', '.join(map(lambda e: '%s (%d kr)'%(e.product.name, e.product.price), + string += ', '.join(map(lambda e: '%s (%d kr)' % (e.product.name, e.product.price), entries)) if len(transactions) > 1: string += '\n price per person: %d kr' % self.purchase.price_per_transaction() @@ -1045,29 +1048,30 @@ When finished, write an empty line to confirm the purchase. string += '\n total price: %d kr' % self.purchase.price if any(t.penalty > 1 for t in transactions): - string += '\n *total with penalty: %d kr' % sum(self.purchase.price_per_transaction() * t.penalty for t in transactions) + string += '\n *total with penalty: %d kr' % sum( + self.purchase.price_per_transaction() * t.penalty for t in transactions) return string def print_purchase(self): info = self.format_purchase() - if info != None: + if info is not None: self.set_context(info) + class AdjustStockMenu(Menu): def __init__(self): - Menu.__init__(self,'Adjust stock', uses_db=True) + Menu.__init__(self, 'Adjust stock', uses_db=True) def _execute(self): self.print_header() product = self.input_product('Product> ') - print 'The stock of this product is: %d ' % (product.stock) print 'Write the number of products you have added to the stock' print 'Alternatively, correct the stock for any mistakes' add_stock = self.input_int('Added stock> ', (-1000, 1000)) - print 'You added %d to the stock of %s' % (add_stock,product) + print 'You added %d to the stock of %s' % (add_stock, product) product.stock += add_stock @@ -1086,7 +1090,7 @@ class AdjustStockMenu(Menu): class CleanupStockMenu(Menu): def __init__(self): - Menu.__init__(self,'Stock Cleanup', uses_db=True) + Menu.__init__(self, 'Stock Cleanup', uses_db=True) def _execute(self): self.print_header() @@ -1104,12 +1108,11 @@ class CleanupStockMenu(Menu): for product in products: oldstock = product.stock - product.stock = self.input_int(product.name, (0,10000), default=max(0, oldstock)) + product.stock = self.input_int(product.name, (0, 10000), default=max(0, oldstock)) self.session.add(product) if oldstock != product.stock: changed_products.append((product, oldstock)) - try: self.session.commit() print 'New stocks are now stored.' @@ -1123,8 +1126,7 @@ class CleanupStockMenu(Menu): print p[0].name, ".", p[1], "->", p[0].stock - -class AdjustCreditMenu(Menu): # reimplements ChargeMenu; these should be combined to one +class AdjustCreditMenu(Menu): # reimplements ChargeMenu; these should be combined to one def __init__(self): Menu.__init__(self, 'Adjust credit', uses_db=True) @@ -1136,11 +1138,11 @@ class AdjustCreditMenu(Menu): # reimplements ChargeMenu; these should be combine print '(Note on sign convention: Enter a positive amount here if you have' print 'added money to the PVVVV money box, a negative amount if you have' print 'taken money from it)' - amount = self.input_int('Add amount> ', (-100000,100000)) + amount = self.input_int('Add amount> ', (-100000, 100000)) print '(The "log message" will show up in the transaction history in the' print '"Show user" menu. It is not necessary to enter a message, but it' print 'might be useful to help you remember why you adjusted the credit)' - description = self.input_str('Log message> ', length_range=(0,50)) + description = self.input_str('Log message> ', length_range=(0, 50)) if description == '': description = 'manually adjusted credit' transaction = Transaction(user, -amount, description) @@ -1151,7 +1153,7 @@ class AdjustCreditMenu(Menu): # reimplements ChargeMenu; these should be combine print 'User %s\'s credit is now %d kr' % (user.name, user.credit) except sqlalchemy.exc.SQLAlchemyError, e: print 'Could not store transaction: %s' % e - #self.pause() + # self.pause() class ProductListMenu(Menu): @@ -1164,14 +1166,14 @@ class ProductListMenu(Menu): product_list = self.session.query(Product).filter(Product.hidden == False).order_by(Product.stock.desc()) total_value = 0 for p in product_list: - total_value += p.price*p.stock - line_format = '%-15s | %5s | %-'+str(Product.name_length)+'s | %5s \n' + total_value += p.price * p.stock + line_format = '%-15s | %5s | %-' + str(Product.name_length) + 's | %5s \n' text += line_format % ('bar code', 'price', 'name', 'stock') - text += 78*'-'+'\n' + text += 78 * '-' + '\n' for p in product_list: text += line_format % (p.bar_code, p.price, p.name, p.stock) - text += 78*'-'+'\n' - text += line_format % ('Total value',total_value,'','', ) + text += 78 * '-' + '\n' + text += line_format % ('Total value', total_value, '', '',) less(text) @@ -1184,9 +1186,9 @@ class ProductSearchMenu(Menu): self.set_context('Enter (part of) product name or bar code') product = self.input_product() print 'Result: %s, price: %d kr, bar code: %s, stock: %d, hidden: %s' % (product.name, product.price, - product.bar_code, product.stock, - ("Y" if product.hidden else "N")) - #self.pause() + product.bar_code, product.stock, + ("Y" if product.hidden else "N")) + # self.pause() class ProductPopularityMenu(Menu): @@ -1203,17 +1205,18 @@ class ProductPopularityMenu(Menu): .subquery() product_list = \ self.session.query(Product, sub.c.purchase_count) \ - .outerjoin((sub, Product.product_id==sub.c.product_id)) \ + .outerjoin((sub, Product.product_id == sub.c.product_id)) \ .order_by(desc(sub.c.purchase_count)) \ - .filter(sub.c.purchase_count != None) \ + .filter(sub.c.purchase_count is not None) \ .all() - line_format = '%10s | %-'+str(Product.name_length)+'s\n' + line_format = '%10s | %-' + str(Product.name_length) + 's\n' text += line_format % ('items sold', 'product') - text += '-'*58 + '\n' + text += '-' * 58 + '\n' for product, number in product_list: text += line_format % (number, product.name) less(text) + class ProductRevenueMenu(Menu): def __init__(self): Menu.__init__(self, 'Products by revenue', uses_db=True) @@ -1228,17 +1231,18 @@ class ProductRevenueMenu(Menu): .subquery() product_list = \ self.session.query(Product, sub.c.purchase_count) \ - .outerjoin((sub, Product.product_id==sub.c.product_id)) \ - .order_by(desc(sub.c.purchase_count*Product.price)) \ - .filter(sub.c.purchase_count != None) \ + .outerjoin((sub, Product.product_id == sub.c.product_id)) \ + .order_by(desc(sub.c.purchase_count * Product.price)) \ + .filter(sub.c.purchase_count is not None) \ .all() - line_format = '%7s | %10s | %5s | %-'+str(Product.name_length)+'s\n' + line_format = '%7s | %10s | %5s | %-' + str(Product.name_length) + 's\n' text += line_format % ('revenue', 'items sold', 'price', 'product') - text += '-'*(31+Product.name_length) + '\n' + text += '-' * (31 + Product.name_length) + '\n' for product, number in product_list: - text += line_format % (number*product.price, number, product.price, product.name) + text += line_format % (number * product.price, number, product.price, product.name) less(text) + class BalanceMenu(Menu): def __init__(self): Menu.__init__(self, 'Total balance of PVVVV', uses_db=True) @@ -1246,27 +1250,31 @@ class BalanceMenu(Menu): def _execute(self): self.print_header() text = '' - total_value = 0; + total_value = 0 product_list = self.session.query(Product).all() for p in product_list: - total_value += p.stock*p.price + total_value += p.stock * p.price total_credit = self.session.query(sqlalchemy.func.sum(User.credit)).first()[0] total_balance = total_value - total_credit line_format = '%15s | %5d \n' text += line_format % ('Total value', total_value) - text += 24*'-'+'\n' + text += 24 * '-' + '\n' text += line_format % ('Total credit', total_credit) - text += 24*'-'+'\n' + text += 24 * '-' + '\n' text += line_format % ('Total balance', total_balance) less(text) + + class LoggedStatisticsMenu(Menu): def __init__(self): Menu.__init__(self, 'Statistics from log', uses_db=True) def _execute(self): statisticsTextOnly() + + def restart(): # Does not work if the script is not executable, or if it was # started by searching $PATH. @@ -1280,36 +1288,34 @@ if not conf.stop_allowed: signal.signal(signal.SIGTSTP, signal.SIG_IGN) - class MainMenu(Menu): - def special_input_choice(self, str): + def special_input_choice(self, in_str): buy_menu = BuyMenu(Session()) - thing = buy_menu.search_for_thing(str) + thing = buy_menu.search_for_thing(in_str) if thing: buy_menu.execute(initialContents=[thing]) - print - self.show_context() + print self.show_context() return True return False - def invalid_menu_choice(self, str): - print - self.show_context() + def invalid_menu_choice(self, in_str): + print self.show_context() + class AddStockMenu(Menu): def __init__(self): Menu.__init__(self, 'Add stock and adjust credit', uses_db=True) - self.help_text=''' + self.help_text = ''' Enter what you have bought for PVVVV here, along with your user name and how much money you're due in credits for the purchase when prompted. ''' def _execute(self): questions = { - (False,False): 'Enter user id or a string of the form " "', - (False,True): 'Enter user id or more strings of the form " "', - (True,False): 'Enter a string of the form " "', - (True,True): 'Enter more strings of the form " ", or an empty line to confirm' + (False, False): 'Enter user id or a string of the form " "', + (False, True): 'Enter user id or more strings of the form " "', + (True, False): 'Enter a string of the form " "', + (True, True): 'Enter more strings of the form " ", or an empty line to confirm' } self.user = None @@ -1322,20 +1328,22 @@ much money you're due in credits for the purchase when prompted. thing_price = 0 # Read in a 'thing' (product or user): - line = self.input_multiple(add_nonexisting=('user','product'), empty_input_permitted=True, find_hidden_products=False) + line = self.input_multiple(add_nonexisting=('user', 'product'), empty_input_permitted=True, + find_hidden_products=False) if line: (thing, amount) = line if isinstance(thing, Product): self.printc("%d of %s registered" % (amount, thing.name)) - thing_price = self.input_int('What did you pay a piece? ', (1,100000), default=thing.price) * amount + thing_price = self.input_int('What did you pay a piece? ', (1, 100000), + default=thing.price) * amount self.price += thing_price # once we get something in the # purchase, we want to protect the # user from accidentally killing it - self.exit_confirm_msg='Abort transaction?' + self.exit_confirm_msg = 'Abort transaction?' else: thing = None @@ -1350,7 +1358,7 @@ much money you're due in credits for the purchase when prompted. self.add_thing_to_pending(thing, amount, thing_price) if self.confirm('Do you want to change the credited amount?', default=False): - self.price = self.input_int('Total amount> ', (1,100000), default=self.price) + self.price = self.input_int('Total amount> ', (1, 100000), default=self.price) self.perform_transaction() @@ -1358,23 +1366,22 @@ much money you're due in credits for the purchase when prompted. return (bool(self.user) and len(self.products) and self.price) def print_info(self): - print (6+Product.name_length)*'-' + print(6 + Product.name_length) * '-' if self.price: - print ("Amount to be credited: %"+str(Product.name_length-17)+"i") % (self.price) + print("Amount to be credited: %" + str(Product.name_length - 17) + "i") % (self.price) if self.user: - print ("User to credit: %"+str(Product.name_length-10)+"s") % (self.user.name) - print ('\n%-'+str(Product.name_length-1)+'s Amount') % ("Product") - print (6+Product.name_length)*'-' + print("User to credit: %" + str(Product.name_length - 10) + "s") % (self.user.name) + print('\n%-' + str(Product.name_length - 1) + 's Amount') % ("Product") + print(6 + Product.name_length) * '-' if len(self.products): - # print "Products added:" - # print (6+Product.name_length)*'-' + # print "Products added:" + # print (6+Product.name_length)*'-' for product in self.products.keys(): - print ('%'+str(-Product.name_length)+'s %5i') % (product.name, self.products[product][0]) - print (6+Product.name_length)*'-' - + print('%' + str(-Product.name_length) + 's %5i') % (product.name, self.products[product][0]) + print(6 + Product.name_length) * '-' def add_thing_to_pending(self, thing, amount, price): - if isinstance(thing,User): + if isinstance(thing, User): if self.user: print "Only one user may be credited for a purchase, transfer credit manually afterwards" return @@ -1388,34 +1395,32 @@ much money you're due in credits for the purchase when prompted. self.products[thing] = [amount, price] def perform_transaction(self): - # self.user.credit += self.price - description = self.input_str('Log message> ', length_range=(0,50)) + # self.user.credit += self.price + description = self.input_str('Log message> ', length_range=(0, 50)) if description == '': - description = 'Purchased products for PVVVV, adjusted credit '+str(self.price) + description = 'Purchased products for PVVVV, adjusted credit ' + str(self.price) transaction = Transaction(self.user, -self.price, description) transaction.perform_transaction() self.session.add(transaction) for product in self.products: - value = max(product.stock, 0)*product.price + self.products[product][1] + value = max(product.stock, 0) * product.price + self.products[product][1] old_price = product.price old_hidden = product.hidden - product.price = int(ceil(float(value)/(max(product.stock, 0) + self.products[product][0]))) + product.price = int(ceil(float(value) / (max(product.stock, 0) + self.products[product][0]))) product.stock += self.products[product][0] product.hidden = False print "New stock for %s: %d" % (product.name, product.stock), \ - ("- New price: " + str(product.price) if old_price != product.price else ""),\ + ("- New price: " + str(product.price) if old_price != product.price else ""), \ ("- Removed hidden status" if old_hidden != product.hidden else "") try: self.session.commit() print "Success! Transaction performed:" - # self.print_info() + # self.print_info() print "User %s's credit is now %i" % (self.user.name, self.user.credit) except sqlalchemy.exc.SQLAlchemyError, e: print 'Could not perform transaction: %s' % e - - main = MainMenu('Dibbler main menu', items=[BuyMenu(), ProductListMenu(), @@ -1430,7 +1435,7 @@ main = MainMenu('Dibbler main menu', AddProductMenu(), EditProductMenu(), AdjustStockMenu(), - CleanupStockMenu(),]), + CleanupStockMenu(), ]), ProductSearchMenu(), Menu('Statistics', items=[ProductPopularityMenu(), @@ -1447,11 +1452,11 @@ while True: try: main.execute() except KeyboardInterrupt: - print + print '' print 'Interrupted.' except: print 'Something went wrong.' - print '%s: %s' % sys.exc_info()[0:2] + print '%s: %s' % sys.exc_info()[0], sys.exc_info()[1] if conf.show_tracebacks: traceback.print_tb(sys.exc_info()[2]) else: