def get_money(self, action): """METHOD: Inputs the dollar amount requested by the user. >> get_money(self, action) PARAMETERS @action: The action taken (string). RETURN The cash amount. """ cash = None while True: try: value = input("Enter {} amount: $".format(action.lower())) cash = money.Money(amount=value, currency="USD") if cash < money.Money(amount=0, currency="USD"): raise ValueError break except: sys.stderr.write("ERROR: Invalid dollar amount.\n") return cash
def _set_balance(self, new_balance, currency=None): if currency is None: currency = self.symbol.upper() if currency in STABLECOIN_SYMBOLS: currency = 'USD' available_balance, locked_balance = new_balance locked_balance = money.Money(locked_balance, currency=currency) available_balance = money.Money(available_balance, currency=currency) self._balance = { 'available_balance': available_balance, 'locked_balance': locked_balance, 'total_balance': locked_balance + available_balance }
def create_order(self): order = Order(stall=self.stall, user=self.cart.user, address=self.address) if self.has_free_shipping: order.delivery_charge = money.Money(0, DEFAULT_CURRENCY) else: order.delivery_charge = self.delivery_total() order.discount_amount = self.discount_amount() order.note = self.note order.save() if order.discount_amount > 0 and not self.shipping_discount.amount > 0: profile = self.cart.user.get_profile() discount = Discount.objects.active().get( code__iexact=self.coupon_code) profile.used_discounts.add(discount) profile.save() for cart_product in self.cart_products.all(): price = cart_product.product.get_price_instance().amount order.line_items.create(product=cart_product.product, quantity=cart_product.quantity, price=price) return order
def insert_data(self, dataEoq,dataHarga,dataTAC): for n in range(0, len(dataEoq)): self.treeview.insert('', 'end', text=str(self.i), values=(int(dataEoq[n]), dataHarga[n],money.Money(dataTAC[n],'IDR'))) self.i = self.i + 1
def save_all_money(): # saves non_gst money only for i in ['receipt', 'payment']: with conn() as cursor: cursor.execute( "select id from {} where gst_invoice_no is null".format(i)) all_id = cursor.fetchall() for a in all_id: a = a[0] money_ = money.Money(i, id_=a) money_.save()
def test_cart_stall_order_contains_all_products(self, mock_delivery): mock_delivery.return_value = money.Money(10, "GBP") order = self.cart_stall.create_order() self.assertEqual(len(order.line_items.all()), len(self.cart_stall.cart_products.all())) for cart_product in self.cart_stall.cart_products.all(): line_item = [ l for l in order.line_items.all() if l.product.id == cart_product.product.id ][0] self.assertEqual(line_item.price, cart_product.unit_price) self.assertEqual(line_item.quantity, cart_product.quantity)
def prep_balances(account): cur = money.Money( 0 if account['balances']['current'] is None else account['balances']['current'], account['balances']['iso_currency_code'] ) avail = money.Money( 0 if account['balances']['available'] is None else account['balances']['available'], account['balances']['iso_currency_code'] ) lim = money.Money( 0 if account['balances']['limit'] is None else account['balances']['limit'], account['balances']['iso_currency_code'] ) print('\t', 'cur\tavail\tlim') print('\t', '\t'.join([cur.format(), avail.format(), lim.format()])) return [ ('cur', account['account_id'], cur), ('avail', account['account_id'], avail), ('lim', account['account_id'], lim), ]
def add_player(self, content): a = money.Money(self.dpl) #Be careful, the name is NOT in .lower()! name = content['name'] amount = a.check(name) #A person who is broke cannot join if amount < 1: content['message'] = 'Error, player has no money!' return content #A person who has already joined cannot join again. elif not name.lower() in self.lower_keys(): self.players[name] = Player(name, amount) self.turnorder.append(name) self.endgame_processing_order.append(name)
def amount(self, value): """ Amount to be charged/refunded :param Decimal value: Amount :return: dict """ if not isinstance(value, decimal.Decimal): value = decimal.Decimal(value) value = round(value, 2) self.context.update({ 'amount': money.Money(value, 'USD').amount })
def prep_balance(bal): formatted = [] for b in bal: db_amount = b[0] if b[4] == 'credit': db_amount = db_amount * -1 amount = money.Money(db_amount / 100, 'USD') db_at = b[1] gmt_at = pendulum.parse(db_at) tz = pendulum.timezone('US/Eastern') est_at = tz.convert(gmt_at) formatted.append([amount.format(), str(est_at), b[2], b[3], b[4], b[5]]) return formatted
def transform(self, currency_input, currency=u'USD', currency_locale=u'en_US', currency_format=u'¤#,##0.00 ¤¤'): if currency_input is None: return u'' try: m = money.Money(currency_input, currency) except ValueError: # Return original input if we can't do anything with it return currency_input currency_locale = currency_locale.replace( '-', '_') # make sure to use the babel locale format return m.format(currency_locale, currency_format)
def __init__(self, *, name, symbol, exchange_client): if not name: raise ValueError('invalid name') self.name = name self.exchange_client = exchange_client self.symbol = symbol self._balance = { 'available_balance': None, 'locked_balance': None, 'total_balance': None } # self.update_balance() self.global_price = 0 self.update_balance() self.update_global_price() self.empty_value = money.Money(20, currency='USD') self.quote_pairs = [] # pairs where this currency is quote self.base_pairs = [] # pairs where this currency is base self._exchange_rate_last_update = 0
def setUp(self): super(PaymentReturnTestCase, self).setUp() self.cart_stall = factories.create_cart_stall() self.cart_stall.delivery_total = mock.MagicMock() self.cart_stall.delivery_total.return_value = money.Money(10, "GBP") self.user = self.cart_stall.cart.user self.payment = factories.PaymentFactory( purchaser=self.user ) self.payment_attempt = factories.PaymentAttemptFactory( payment=self.payment, cart_stall=self.cart_stall, ) self.client.login(username=self.user.username, password="******") self.view_url = reverse("paypal_adaptive_return", kwargs={ "payment_id": self.payment.id, "payment_secret_uuid": self.payment.secret_uuid })
def main(): # Initialize Variables (Imports) m = money.Money() port = portfolio.Portfolio(m) wl = watch_list.Watch_List() # Main Text Display m.print_funds() option = input(display) while True: if option == '1': port.main() elif option == '2': m.money_main() elif option == '3': wl.main() elif option == '4': ipt = input("Would you like to see your current portfolio? (Y/N) ").upper() if ipt == 'Y': port.print_portfolio() ipt = input("Would you like to see your current watch list? (Y/N) ").upper() if ipt == 'Y': wl.print_wl() stock_ipt = input("Please type the ticker symbol of a stock. ").upper() try: print('\nCurrent Ticker Symbol: ' + str(stock_ipt).upper()) stock.Stock(stock_ipt).stock_main() except (AttributeError, IndexError, KeyError) as e: print("\n" + str(stock_ipt) + ' is not a valid ticker symbol in Yahoo Finance ' 'or the given ticker symbol is not supported by the yfinance API.') elif option == '5': google_search_keyword() elif option == 'gui': gui.main(m, port, wl) elif option == 'quit': return m.print_funds() option = input(display)
def end_game(self, content): nextline = '\r\n%s %s :' % (content['type'], content['channel']) buffer = content['message'] self.dealer_draw() buffer += 'All players have played!' + nextline for a in self.endgame_processing_order: self.process_score(self.players[a]) buffer += '%s (%d): %s' % (a, self.players[a].active_hand_value(), self.players[a].print_hand()) + nextline if self.players[a].splitted: self.players[a].active_hand_number = 2 buffer += '%s (%d): %s' % ( a, self.players[a].active_hand_value(), self.players[a].print_hand()) + nextline buffer += '%s (%d): %s' % ('Dealer', self.dealer.active_hand_value(), self.dealer.print_hand()) + nextline buffer += 'Here\'s the amount of money you have left:' + nextline a = money.Money(self.dpl) for b in self.endgame_processing_order: buffer += '%s: %d' % (b, self.players[b].money) + nextline a.set(b, self.players[b].money) list = self.endgame_processing_order self.endgame_processing_order = [] self.players = {} self.turn_order = [] self.state = 'join_phase' self.dealer = Dealer() for b in list: amount = a.check(b.lower()) if amount > 0: self.players[b] = Player(b, amount) self.turnorder.append(b) self.endgame_processing_order.append(b) buffer += 'Players who are broke have been kicked. Press $join, $start or $quit.' content['message'] = buffer return content
def delivery_total(self): """Returns the delivery charges for this stall, considering all products in the cart. """ if self.address: country = self.address.country else: country = self.get_country() # This is a little complex so some explanation is in order. # # We loop through all the products, for each product if there is a # rule which matches the selected country we add the price of the # _extra_ items to the total. We also keep track of the largest # initial price. After we have been through all the products we # add the price of the largest initial item and subtract the extra # price of the largest initial item rule because otherwise it will # be charged twice, once for the initial and once for the already # counted extra. # This is the rule with the largest initial item price. We need to # store it to add to the total later. We also need the extra price # because we need to subtract that from the title. # # Ideally this would be a single variable rule object, unfortunately # the shipping rule for the rest of the world is represented as fields # on the shipping profile rather than a rule so we need both fields # here. largest_initial = None largest_initial_extra = None largest_shipping_discount = None largest_shipping_discout_extra = None total_shipping_price = money.Money(0, DEFAULT_CURRENCY) total_shipping_discount = Money(0, DEFAULT_CURRENCY) for cart_product in self.cart_products.all().prefetch_related( 'product__shipping_profile__shipping_rules__countries'): product = cart_product.product #Find the a shipping rule for the selected country shipping_price, shipping_price_extra = product.get_shipping_prices( self.speculative_country) shipping_discount, shipping_discout_extra = product.get_shipping_discounts( self.speculative_country) if largest_initial is None or shipping_price > largest_initial: largest_initial = shipping_price largest_shipping_discount = shipping_discount largest_initial_extra = shipping_price_extra largest_shipping_discout_extra = shipping_discout_extra total_shipping_price += shipping_price_extra * cart_product.quantity total_shipping_discount += shipping_discout_extra * cart_product.quantity if largest_initial is not None: total_shipping_price += largest_initial if largest_initial_extra is not None: total_shipping_price -= largest_initial_extra if largest_shipping_discount is not None: total_shipping_discount += largest_shipping_discount if largest_shipping_discout_extra is not None: total_shipping_discount -= largest_shipping_discout_extra self.shipping_discount = total_shipping_discount return total_shipping_price
def chip(): cf.clear_screen(msg="Chip") # input_ = {"arg1": 'plm'} input_ = None while True: cf.log_("start input_ is {}".format(input_)) if not input_: input_ = get_input() cf.log_("input_.get('arg1') is {}".format(input_.get('arg1'))) elif input_ == "back": input_ = None continue elif input_ == "quit": cf.log_("You quit") import sys sys.exit() break elif input_.get("arg1") == "slms": tr.view_summary() input_ = None continue elif input_.get("arg1") == "slmp": place = cf.prompt_("Enter place: ", cf.get_completer_list("place", "customer"), existing_="yes") tr.get_customer_balance(place=place) input_ = None continue elif input_.get("arg1") == "slgp": place = cf.prompt_("Enter place: ", cf.get_completer_list("place", "customer"), existing_="yes") tr.get_gst_customer_balance(place=place) input_ = None continue elif input_.get("arg1") == "slmc": tr.get_customer_balance() input_ = None continue elif input_.get("arg1") == "test": # tr.view("sale_transaction") # tr.view("purchase_transaction") # tr.view_by_nickname("sale_transaction", "Kishor Light House") # master.add_saved("sale_invoice") input_ = None continue elif input_.get('arg1') in ['saved', 'unsaved']: if input_.get('arg1') == 'unsaved': sq = 'select id, owner_name, owner_place, amount_after_freight from sale_invoice where id not in (select id_invoice from sale_transaction where id_invoice is not null) and gst_invoice_no is null' sq_purchase = 'select id, owner_name, owner_place, amount_after_freight from purchase_invoice where id not in (select id_invoice from purchase_transaction where id_invoice is not null) and gst_invoice_no is null' elif input_.get('arg1') == 'saved': sq = 'select id, owner_name, owner_place, amount_after_freight from sale_invoice where id in (select id_invoice from sale_transaction where id_invoice is not null) and gst_invoice_no is null' sq_purchase = 'select id, owner_name, owner_place, amount_after_freight from purchase_invoice where id in (select id_invoice from purchase_transaction where id_invoice is not null) and gst_invoice_no is null' with conn() as cursor: cursor.execute(sq) result = cursor.fetchall() with conn() as cursor: cursor.execute(sq_purchase) result_purchase = cursor.fetchall() for a_result in [result, result_purchase]: pt = PrettyTable(['id', 'name', 'place', 'amount']) pt.align['amount'] = 'r' for a in a_result: pt.add_row(a) print(pt) print("Count: {}".format(len(a_result))) input_ = None continue elif input_.get("arg1") == "invoice_by_id": invoice_type = input_.get("arg3") invoice_id = input_.get("arg2") invoice_ = invoice.get_existing_invoice(invoice_type, invoice_id) invoice_.view_invoice_details(invoice_.fetch_invoice_details()) input_ = cm.command_loop(invoice_) continue elif input_.get("arg1") == "todo": input_ = None continue elif input_.get("arg1") == "gbr": product_name = cf.prompt_("Enter product name: ", cf.get_completer_list("name", "product"), unique_="existing") product.get_buy_rate(product_name) input_ = None continue elif input_.get("arg1") == "sl": input_ = tr.ledger_operations("sale_transaction") continue elif input_.get("arg1") == "sbmc": input_ = tr.get_a_balance("sale_transaction", master_=True) continue elif input_.get("arg1") == "sbma": input_ = tr.get_all_balances("sale_transaction", master_=True) continue elif input_.get("arg1") == "sbga": input_ = tr.get_all_gst_balances("sale_transaction") continue elif input_.get("arg1") == "slg": input_ = tr.ledger_operations("sale_transaction", gst_=True) continue elif input_.get("arg1") == "slm": input_ = tr.ledger_operations("sale_transaction", master_="yes") continue elif input_.get("arg1") == "slmd": input_ = tr.ledger_operations("sale_transaction", master_="yes", date_='yes') continue elif input_.get("arg1") == "pl": input_ = tr.ledger_operations("purchase_transaction") continue elif input_.get("arg1") == "plg": input_ = tr.ledger_operations("purchase_transaction", gst_=True) continue elif input_.get("arg1") == "plm": input_ = tr.ledger_operations("purchase_transaction", master_="yes") continue elif input_.get("arg1") == "backup": print("This command is currently disabled") # master.export(only_backup=True) input_ = None continue elif input_.get("arg1") == "ex": confirm_ = cf.prompt_("Do you want to export? ", ['y', 'n'], unique_="existing") if confirm_ != 'y': print("You canceled. No changes were made.") input_ = None continue master.save_all_money() master.export() input_ = None continue elif input_.get("arg1") in ["rin", "ptin"]: if input_.get("arg1") == "rin": invoice_type = "receipt" elif input_.get("arg1") == "ptin": invoice_type = "payment" invoice_ = money.Money(invoice_type) input_ = None continue elif input_.get("arg1") in ["rie", "ptie"]: if input_.get("arg1") == "rie": invoice_type = "receipt" elif input_.get("arg1") == "ptie": invoice_type = "payment" invoice_id = owner.view(invoice_type, filter_type="Search By Nickname") if invoice_id in ["quit", "back"]: input_ = {"arg1": input_} continue money_ = money.Money(invoice_type, id_=invoice_id) money_.view_invoice_details(money_.fetch_invoice_details()) while True: property_ = cf.prompt_( "Enter property to edit/'delete' to delete record: ", money.sq_properties, empty_='yes') if property_ == "delete": money_.delete_() break if property_ in money.sq_properties: money_.edit_property(property_) continue if property_ in ["back", "quit"]: break input_ = None continue elif input_.get("arg1") in ["rip", "ptip"]: if input_.get("arg1") == "rip": invoice_type = "receipt" owner_type = "customer" elif input_.get("arg1") == "ptip": invoice_type = "payment" owner_type = "vendor" with conn() as cursor: cursor.execute( "select r.date_, c.name, r.amount, r.medium, r.recipient, r.detail from {} as r join {} as c on c.id = r.id_owner where gst_invoice_no is null order by r.date_" .format(invoice_type, owner_type)) result = cursor.fetchall() column_list = [ 'Date', 'Name', 'Amount', 'Medium', 'Recipient', 'Detail' ] cf.pretty_table_multiple_rows(column_list, result) input_ = None continue elif input_.get("arg1") == "praa": input_ = product.set_property("abbr_name") if input_ in ["quit", "back"]: input_ = {"arg1": input_} continue elif input_.get("arg1") == "pra": input_ = product.set_property("abbr_name", by_name="yes") if input_ in ["quit", "back"]: input_ = {"arg1": input_} continue elif input_.get("arg1") == "prn": input_ = product.set_property("name", by_name="yes") if input_ in ["quit", "back"]: input_ = {"arg1": input_} continue elif input_.get("arg1") == "prc": while True: name = cf.prompt_("Enter New Product Name: ", cf.get_completer_list("name", "product"), unique_="yes") if name in ["quit", "back"]: input_ = {"arg1": input_} break input_ = product.create_product(name) continue elif input_.get("arg1") == "prde": input_ = cf.prompt_("Enter product name: ", cf.get_completer_list("name", "product"), unique_="existing") if input_ in ["quit", "back"]: input_ = {"arg1": input_} continue product.delete_product(input_) input_ = None continue elif input_.get("arg1") in ["sipn", "pipn", ","]: if input_.get("arg1") in ["sipn", ","]: invoice_type = "sale_invoice" elif input_.get("arg1") == "pipn": invoice_type = "purchase_invoice" invoice_id = owner.view(invoice_type, filter_type="Search By Nickname") if invoice_id in ["quit", "back"]: input_ = {"arg1": input_} continue invoice_ = invoice.get_existing_invoice(invoice_type, invoice_id) invoice_.view_invoice_details(invoice_.fetch_invoice_details()) input_ = cm.command_loop(invoice_) continue elif input_.get("arg1") in ["sip", "pip"]: if input_.get("arg1") == "sip": invoice_type = "sale_invoice" elif input_.get("arg1") == "pip": invoice_type = "purchase_invoice" invoice_id = owner.view(invoice_type) if invoice_id == "back": print("you chose to cancel") input_ = None continue invoice_ = invoice.get_existing_invoice(invoice_type, invoice_id) invoice_.view_invoice_details(invoice_.fetch_invoice_details()) input_ = cm.command_loop(invoice_) continue elif input_.get("arg1") in ["sil", "pil"]: if input_.get("arg1") == "sil": invoice_type = "sale_invoice" elif input_.get("arg1") == "pil": invoice_type = "purchase_invoice" last_invoice_id = owner.get_last_invoice_id(invoice_type) if not last_invoice_id: cf.log_("There are no previous invoices") input_ = None continue invoice_ = invoice.get_existing_invoice(invoice_type, last_invoice_id) # print("reahced here0") invoice_.view_invoice_details(invoice_.fetch_invoice_details()) # print("reahced here") input_ = cm.command_loop(invoice_) continue elif input_.get("arg1") in ["cun", "ven"]: if input_.get("arg1") == "cun": invoice_type = "sale_invoice" elif input_.get("arg1") == "ven": invoice_type = "purchase_invoice" owner_type = cf.owner_type_d[invoice_type] id_ = owner.get_new_owner(owner_type) input_ = None continue elif input_.get("arg1") == "prn": input_ = cf.prompt_("Enter Product Name: ", cf.get_completer_list("name", "product"), history_file='product_name.txt') if input_ in ["quit", "back"]: input_ = {"arg1": input_} else: input_ = product.Product.init_by_name(input_) input_ = None continue elif input_.get("arg1") in ["sin", "pin"]: if input_.get("arg1") == "sin": invoice_type = "sale_invoice" elif input_.get("arg1") == "pin": invoice_type = "purchase_invoice" invoice_ = invoice.get_new_invoice(invoice_type) input_ = cm.inside_invoice(invoice_) continue elif input_.get("arg1") == "plp": input_ = plf.assign_pricelist_to_product() if input_ in ["quit", "back"]: input_ = {"arg1": input_} continue elif input_.get("arg1") in ["cupln", "vepln"]: if input_.get("arg1") == "cupln": owner_type = "customer" elif input_.get("arg1") == "vepln": owner_type = "vendor" confirm_ = cf.prompt_("Change discount for: ", ['gst', 'non-gst'], unique_="existing") if confirm_ == "gst": gst_arg = True else: gst_arg = False plf.set_pricelist_discount_for_owner(owner_type, gst_=gst_arg) continue elif input_.get('arg1') == "q" or input_.get('arg1') == "quit": cf.log_("You entered 'q' to quit") import sys sys.exit() break elif input_.get('arg1') == "b" or input_.get('arg1') == "back": input_ = None continue elif input_.get('arg1') == "ivp": invoice_ = input_.get('arg2') result = invoice_.fetch_invoice_details() invoice_.view_invoice_details(result) l = len(result) no_of_results = 5 v = l - no_of_results while True: view_command = cf.prompt_("View Previous/Next 5: (p/n)", [], empty_="yes") if view_command == "p": previous_v = v cf.log_("previous_v is {}".format(previous_v)) v = v - no_of_results cf.log_("v is {}".format(v)) if not v < 0: cf.log_("{}, {}".format(v, previous_v - 1)) invoice.view_print(result[v:previous_v - 1]) print("v, previous_v:\n{}, {}".format(v, previous_v)) continue else: invoice.view_print(result[:previous_v]) print("reached top") v = l - no_of_results continue elif view_command == "n": if 'next_v' not in locals(): next_v = previous_v else: next_v = v v = next_v + no_of_results if len(result) > v: print("v, next_v:\n{}, {}".format(v, next_v)) invoice.view_print(result[next_v:v]) continue else: invoice.view_print(result[v - no_of_results:]) print("reached bottom") v = len(result) - no_of_results continue else: break input_ = cm.command_loop(invoice_) continue elif input_.get('arg1') in ["oli", "olim"]: owner_nickname = input_.get('arg2') last_invoice_ = input_.get('arg3') if input_.get('arg1') == 'olim': master_ = True else: master_ = False invoice_type = last_invoice_.invoice_type owner_type = last_invoice_.owner_type id_owner = owner.get_id_from_nickname(owner_type, owner_nickname) invoice_id = owner.get_owner_last_invoice_id(invoice_type, id_owner, master_=master_) invoice_ = invoice.get_existing_invoice(invoice_type, invoice_id, master_=master_) sale_report.create_(invoice_, 'A6', master_=True) # invoice_.view_invoice_details(invoice_.fetch_invoice_details(master_=master_)) if master_: input_ = cm.open_invoice_by_id(last_invoice_.id, invoice_type) continue input_ = cm.command_loop(invoice_) continue elif input_.get('arg1') == "ov": owner_nickname = input_.get('arg2') last_invoice_ = input_.get('arg3') invoice_type = last_invoice_.invoice_type owner_type = last_invoice_.owner_type id_owner = owner.get_id_from_nickname(owner_type, owner_nickname) owner_ = owner.get_existing_owner_by_id(owner_type, id_owner) owner_.display_basic_info() input_ = None continue elif input_.get('arg1') == "oai": owner_nickname = input_.get('arg2') last_invoice_ = input_.get('arg3') invoice_type = last_invoice_.invoice_type owner_type = last_invoice_.owner_type id_owner = owner.get_id_from_nickname(owner_type, owner_nickname) owner_ = owner.get_existing_owner_by_id(owner_type, id_owner) invoice_id = owner_.get_owner_invoice(invoice_type) input_ = cm.open_invoice_by_id(invoice_id, invoice_type) continue elif input_.get('arg1') == "oe": try: owner_nickname = input_.get('arg2') last_invoice_ = input_.get('arg3') # above two statements do not generate exception invoice_type = last_invoice_.invoice_type except Exception as e: cf.log_(e) owner_type = cf.prompt_('Select Owner Type: ', ["customer", "vendor"]) if owner_type in ["quit", "back"]: input_ = {"arg1": "back"} owner_nickname = cf.prompt_("Enter Owner Nickname: ", cf.get_completer_list( "nickname", owner_type), unique_="existing") id_owner = owner.get_id_from_nickname(owner_type, owner_nickname) owner_ = owner.get_existing_owner_by_id(owner_type, id_owner) while True: owner_.edit_properties() input_ = None continue owner_type = last_invoice_.owner_type id_owner = owner.get_id_from_nickname(owner_type, owner_nickname) owner_ = owner.get_existing_owner_by_id(owner_type, id_owner) while True: owner_.edit_properties() input_ = None continue elif input_.get("arg1") == "osb": nickname = input_.get('arg2') last_invoice_ = input_.get('arg3') invoice_type = last_invoice_.invoice_type owner_product = cf.owner_product_from_invoice_type_d[invoice_type] owner_type = last_invoice_.owner_type id_owner = owner.get_id_from_nickname(owner_type, nickname, no_create="y") cm.sandbox(id_owner, owner_product) input_ = cm.open_invoice_by_id(last_invoice_.id, invoice_type) continue elif input_.get('arg1') == "on": owner_nickname = input_.get('arg2') last_invoice_ = input_.get('arg3') invoice_type = last_invoice_.invoice_type invoice_ = invoice.get_new_invoice(invoice_type, nickname=owner_nickname) input_ = cm.inside_invoice(invoice_) continue elif input_.get('arg1') == "op": owner_nickname = input_.get('arg2') last_invoice_ = input_.get('arg3') invoice_type = last_invoice_.invoice_type owner_type = last_invoice_.owner_type id_owner = owner.get_id_from_nickname(owner_type, owner_nickname) invoice_id = owner.get_owner_last_invoice_id( invoice_type, id_owner) invoice_ = invoice.get_existing_invoice(invoice_type, invoice_id) cf.log_("reached op here") sale_report.create_(invoice_, 'A6') # go back to current invoice invoice_ = invoice.get_existing_invoice(invoice_type, last_invoice_.id) invoice_.view_invoice_details(invoice_.fetch_invoice_details()) input_ = cm.command_loop(invoice_) # ask for invoice and print it pass elif input_.get('arg1') == "opl": input_ = None # set pricelist discount pass elif input_.get('arg1') == "ol": input_ = None pass else: cf.log_("Unknown command: {}".format(input_)) input_ = None continue
def test_create_order_sets_notes(self, mock_delivery): mock_delivery.return_value = money.Money(10, "GBP") self.cart_stall.note = "test notes" order = self.cart_stall.create_order() self.assertEqual(order.note, "test notes")
# -*- coding: utf-8 -*- # !/usr/bin/env python3 if __name__ == '__main__': import money # crafting money euro = money.Money(1.0, 'EUR') five_euros = money.Money(5.0, 'EUR') ten_euros = money.Money(10.0, 'EUR') dollar = money.Money(1.0, 'USD') # money algebra eleven_euros = euro + ten_euros sixteen_euros = euro + five_euros + ten_euros six_euros = sixteen_euros - ten_euros # money comparisons print('11 EUR > 6 EUR ? {}'.format(eleven_euros > six_euros)) print('11 EUR == (10 EUR + 1 EUR) ? {}'.format(eleven_euros == ten_euros + euro)) print( '11 EUR > 50 EUR ? {}'.format(eleven_euros > money.Money(50.0, 'EUR'))) # playing with a wallet wallet = money.Wallet('My Wallet') wallet.add(euro) wallet.add(ten_euros) wallet.add(dollar) print('\n{} has {} items:'.format(str(wallet), len(wallet)))
def test_to_json(self, mock_delivery): mock_delivery.return_value = money.Money(10, "GBP") json = self.cart_stall.to_json() self.assertEqual(len(json["cart_products"]), 3)
def main(): print('This program tests some of the methods of the Money class.\n') # You are not expected to understand the following # if/else statements. if '__float__' in money.Money.__dict__: print('Correct: The __float__ method is defined.') else: print('ERROR: The __float__ method is not defined.') if '__add__' in money.Money.__dict__: print('Correct: The __add__ method is defined.') else: print('ERROR: The __add__ method is not defined.') if '__iadd__' in money.Money.__dict__: print('Correct: The __iadd__ method is defined.') else: print('ERROR: The __iadd__ method is not defined.') money1 = money.Money(4, 45) money2 = money.Money(5, 55) money3 = money.Money(8, 99) print('\nmoney1 = %s' % money1) print('money2 = %s' % money2) print('money3 = %s' % money3) print('\nTesting the __float__ method...') print('The float value of money1 should be 4.45.') print('The float value of money1 is %.2f.' % float(money1)) float_return = float(money1) print('The type returned from the float method should be: ' \ + "<class 'float'>") print('The type returned from the float method is: %s' \ % type(float_return)) print('\nTesting the __add__ method...') print('Creating money4 by adding money1 and money2.') money4 = money1 + money2 print('money4 should be $10.00.') print('money4 is now %s.' % money4) print('Creating money5 by adding money1 and money3.') money5 = money1 + money3 print('money5 should be $13.44.') print('money5 is now %s.' % money5) print('\nThe type returned from the __add__ method should be: ') print("<class 'money.Money'>") print('The type returned from the __add__ method is:') print(type(money5)) if str(money5) != '$13.44': print('ERROR in your __add__ method since money5 is not $13.44.') print('\nTesting the __iadd__ method...') money1 += money2 print('After adding money2 to money1, money1 should be $10.00.') print('money1 is now %s.' % money1) if money1.get_dollars() == 9: print('ERROR in __iadd__ method since dollars is 9 instead of 10') if money1.get_cents() == 100: print('ERROR in __iadd__ method since cents is 100 instead of 0') money3 += money4 print('\nAfter adding money4 to money3, money3 should be $18.99.') print('money3 is now %s.' % money3) print('\nThe type returned from the __iadd__ method should be: ') print("<class 'money.Money'>") print('The type returned from the __iadd__ method is:') print(type(money3)) if str(money3) != '$18.99': print('ERROR in your __iadd__ method since money3 is not $18.99.') print('\nEnd of testing for the Money class.')
def command_loop(tr_type, owner_, result, opening_balance, view_, **kwargs): master_ = kwargs.get("master_", '') id_owner = owner_.id owner_type = owner_.owner_type if tr_type == "sale_transaction": invoice_type = "sale_invoice" money_type = "receipt" if tr_type == "purchase_transaction": invoice_type = "purchase_invoice" money_type = "payment" while True: input_ = cf.prompt_("Enter Ledger Command: ", ['p', 'pi', 'pm', 'n', 'ng', 'pr', 'del'], unique_="existing") if input_ == "del": master.backup() if master_: invoice_type = sql.SQL("master.") + sql.Identifier( invoice_type) money_type = sql.SQL("master.") + sql.Identifier(money_type) owner_type = sql.SQL("master.") + sql.Identifier(owner_type) date_list = [str(e[0]) for e in result] date_ = cf.prompt_("Enter Starting Date: ", date_list, unique_="existing") result = get_ledger_result_by_date(view_, id_owner, date_) opening_balance = get_opening_balance(view_, id_owner, result, date_=date_) with conn() as cursor: cursor.execute( sql.SQL( "select id_invoice, id_voucher from {} where id_owner = %s and date_ < %s " ).format(view_), (id_owner, date_)) result = cursor.fetchall() invoice_list = [a[0] for a in result if a[0] is not None] invoice_list = tuple(invoice_list) voucher_list = [a[1] for a in result if a[1] is not None] voucher_list = tuple(voucher_list) print(invoice_list) print(voucher_list) print(opening_balance) if invoice_list: with conn() as cursor: cursor.execute( sql.SQL("delete from {} where id in %s ").format( invoice_type), (invoice_list, )) if voucher_list: with conn() as cursor: cursor.execute( sql.SQL("delete from {} where id in %s ").format( money_type), (voucher_list, )) with conn() as cursor: cursor.execute( sql.SQL("update {} set opening_balance = %s where id = %s" ).format(owner_type), (opening_balance, owner_.id)) if input_ == "n": if tr_type == "sale_transaction": print('issuing command "slm"') return {'arg1': 'slm'} elif tr_type == "purchase_transaction": print('issuing command "plm"') return {'arg1': 'plm'} if input_ == "ng": if tr_type == "sale_transaction": print('issuing command "slg"') return {'arg1': 'slg'} elif tr_type == "purchase_transaction": print('issuing command "plg"') return {'arg1': 'plg'} if input_ == "p": ledger_report.create_(result, 'A6', owner_, opening_balance, **kwargs) continue if input_ in ["back", "quit"]: return input_ if input_ in ["pi", "pr"]: invoice_dict = { str(a[1]) if a[2] not in [None, 0] else None: str(a[2]) if a[2] not in [None, 0] else None for a in result } invoice_dict = { k: v for k, v in invoice_dict.items() if k is not None } # money_list = [a[1] if a[3] is not None for a in result] invoice_id = cf.prompt_dict("Select Invoice: ", invoice_dict) if invoice_id in ["back", "quit"]: return invoice_id invoice_ = invoice.get_existing_invoice(invoice_type, invoice_id, master_=master_) if input_ == "pi": invoice_.view_invoice_details( invoice_.fetch_invoice_details(master_=master_)) elif input_ == "pr": sale_report.create_(invoice_, 'A6', master_=master_) if input_ == "pm": invoice_dict = { str(a[1]) if a[3] not in [None, 0] else None: str(a[3]) if a[3] not in [None, 0] else None for a in result } invoice_dict = { k: v for k, v in invoice_dict.items() if k is not None } # money_list = [a[1] if a[3] is not None for a in result] input_ = cf.prompt_dict("Select Invoice: ", invoice_dict) if input_ in ["back", "quit"]: return input_ if invoice_type == "sale_invoice": money_type = "receipt" if invoice_type == "purchase_invoice": money_type = "payment" money_ = money.Money(money_type, id_=input_, **kwargs) money_details = money_.fetch_invoice_details(**kwargs) money_.view_invoice_details(money_details) return None
def reduce(self, bank, to: str): if not isinstance(bank, Bank): return False amount: int = self._augend.reduce( bank, to).amount + self._addend.reduce(bank, to).amount return money.Money(amount, to)
def test_create_order_sets_delivery_charge(self, mock_delivery): mock_delivery.return_value = money.Money(10, "GBP") order = self.cart_stall.create_order() self.assertEqual(order.delivery_charge.amount, 10)