def get_initial(self): """ Provide initial data for new SupplierPart: - If 'supplier_id' provided, pre-fill supplier field - If 'part_id' provided, pre-fill part field """ initials = super(SupplierPartCreate, self).get_initial().copy() manufacturer_id = self.get_param('manufacturer') supplier_id = self.get_param('supplier') part_id = self.get_param('part') manufacturer_part_id = self.get_param('manufacturer_part') supplier = None if supplier_id: try: supplier = Company.objects.get(pk=supplier_id) initials['supplier'] = supplier except (ValueError, Company.DoesNotExist): supplier = None if manufacturer_id: try: initials['manufacturer'] = Company.objects.get(pk=manufacturer_id) except (ValueError, Company.DoesNotExist): pass if manufacturer_part_id: try: # Get ManufacturerPart instance information manufacturer_part_obj = ManufacturerPart.objects.get(pk=manufacturer_part_id) initials['part'] = Part.objects.get(pk=manufacturer_part_obj.part.id) initials['manufacturer'] = manufacturer_part_obj.manufacturer.id initials['MPN'] = manufacturer_part_obj.MPN except (ValueError, ManufacturerPart.DoesNotExist, Part.DoesNotExist, Company.DoesNotExist): pass if part_id: try: initials['part'] = Part.objects.get(pk=part_id) except (ValueError, Part.DoesNotExist): pass # Initial value for single pricing if supplier: currency_code = supplier.currency_code else: currency_code = common.settings.currency_code_default() currency = CURRENCIES.get(currency_code, None) if currency_code: initials['single_pricing'] = ('', currency) return initials
def get_initial(self): initials = super(AjaxCreateView, self).get_initial() supplier_part = self.get_part() initials['part'] = self.get_part() if supplier_part is not None: currency_code = supplier_part.supplier.currency_code else: currency_code = common.settings.currency_code_default() # Extract the currency object associated with the code currency = CURRENCIES.get(currency_code, None) if currency: initials['price'] = [1.0, currency] return initials
# -*- coding: utf-8 -*- import operator from django.conf import settings from moneyed import CURRENCIES, DEFAULT_CURRENCY, DEFAULT_CURRENCY_CODE # The default currency, you can define this in your project's settings module # This has to be a currency object imported from moneyed DEFAULT_CURRENCY = getattr(settings, 'DEFAULT_CURRENCY', DEFAULT_CURRENCY) # The default currency choices, you can define this in your project's # settings module PROJECT_CURRENCIES = getattr(settings, 'CURRENCIES', None) CURRENCY_CHOICES = getattr(settings, 'CURRENCY_CHOICES', None) if CURRENCY_CHOICES is None: if PROJECT_CURRENCIES: CURRENCY_CHOICES = [(code, CURRENCIES[code].name) for code in PROJECT_CURRENCIES] else: CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if c.code != DEFAULT_CURRENCY_CODE] CURRENCY_CHOICES.sort(key=operator.itemgetter(1, 0)) DECIMAL_PLACES = getattr(settings, 'CURRENCY_DECIMAL_PLACES', 2)
from moneyed import Money, CURRENCIES, DEFAULT_CURRENCY_CODE from decimal import Decimal import operator __all__ = ( 'InputMoneyWidget', 'CurrencySelectWidget', ) PROJECT_CURRENCIES = getattr(settings, 'CURRENCIES', None) if PROJECT_CURRENCIES: CURRENCY_CHOICES = [(code, CURRENCIES[code].name) for code in PROJECT_CURRENCIES] else: CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if c.code != DEFAULT_CURRENCY_CODE] CURRENCY_CHOICES.sort(key=operator.itemgetter(1)) class CurrencySelectWidget(forms.Select): def __init__(self, attrs=None, choices=CURRENCY_CHOICES): super(CurrencySelectWidget, self).__init__(attrs, choices) class InputMoneyWidget(forms.TextInput): def __init__(self, attrs=None, currency_widget=None): self.currency_widget = currency_widget or CurrencySelectWidget() super(InputMoneyWidget, self).__init__(attrs)
def migrate_currencies(apps, schema_editor): """ Migrate from the 'old' method of handling currencies, to the new method which uses the django-money library. Previously, we created a custom Currency model, which was very simplistic. Here we will attempt to map each existing "currency" reference for the SupplierPriceBreak model, to a new django-money compatible currency. """ logger.info("Updating currency references for SupplierPriceBreak model...") # A list of available currency codes currency_codes = CURRENCIES.keys() cursor = connection.cursor() # The 'suffix' field denotes the currency code response = cursor.execute( 'SELECT id, suffix, description from common_currency;') results = cursor.fetchall() remap = {} for index, row in enumerate(results): pk, suffix, description = row suffix = suffix.strip().upper() if suffix not in currency_codes: # pragma: no cover logger.warning(f"Missing suffix: '{suffix}'") while suffix not in currency_codes: # Ask the user to input a valid currency print(f"Could not find a valid currency matching '{suffix}'.") print("Please enter a valid currency code") suffix = str(input("> ")).strip() if pk not in remap.keys(): remap[pk] = suffix # Now iterate through each SupplierPriceBreak and update the rows response = cursor.execute( 'SELECT id, cost, currency_id, price, price_currency from part_supplierpricebreak;' ) results = cursor.fetchall() count = 0 for index, row in enumerate(results): pk, cost, currency_id, price, price_currency = row # Copy the 'cost' field across to the 'price' field response = cursor.execute( f'UPDATE part_supplierpricebreak set price={cost} where id={pk};') # Extract the updated currency code currency_code = remap.get(currency_id, 'USD') # Update the currency code response = cursor.execute( f"UPDATE part_supplierpricebreak set price_currency= '{currency_code}' where id={pk};" ) count += 1 if count > 0: logger.info(f"Updated {count} SupplierPriceBreak rows")
def get_initial(self): """ Provide initial data to create a new StockItem object """ # Is the client attempting to copy an existing stock item? item_to_copy = self.request.GET.get('copy', None) if item_to_copy: try: original = StockItem.objects.get(pk=item_to_copy) initials = model_to_dict(original) self.ajax_form_title = _("Duplicate Stock Item") except StockItem.DoesNotExist: initials = super(StockItemCreate, self).get_initial().copy() else: initials = super(StockItemCreate, self).get_initial().copy() part = self.get_part() loc_id = self.request.GET.get('location', None) sup_part_id = self.request.GET.get('supplier_part', None) location = None supplier_part = None if part is not None: initials['part'] = part initials['location'] = part.get_default_location() initials['supplier_part'] = part.default_supplier # If the part has a defined expiry period, extrapolate! if part.default_expiry > 0: expiry_date = datetime.now().date() + timedelta( days=part.default_expiry) initials['expiry_date'] = expiry_date currency_code = common.settings.currency_code_default() # SupplierPart field has been specified # It must match the Part, if that has been supplied if sup_part_id: try: supplier_part = SupplierPart.objects.get(pk=sup_part_id) if part is None or supplier_part.part == part: initials['supplier_part'] = supplier_part currency_code = supplier_part.supplier.currency_code except (ValueError, SupplierPart.DoesNotExist): pass # Location has been specified if loc_id: try: location = StockLocation.objects.get(pk=loc_id) initials['location'] = location except (ValueError, StockLocation.DoesNotExist): pass currency = CURRENCIES.get(currency_code, None) if currency: initials['purchase_price'] = (None, currency) return initials
from django import forms from django.conf import settings from moneyed import Money, CURRENCIES, DEFAULT_CURRENCY_CODE from decimal import Decimal import operator __all__ = ('InputMoneyWidget', 'CurrencySelectWidget',) PROJECT_CURRENCIES = getattr(settings, 'CURRENCIES', None) if PROJECT_CURRENCIES: CURRENCY_CHOICES = [(code, CURRENCIES[code].name) for code in PROJECT_CURRENCIES] else: CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if c.code != DEFAULT_CURRENCY_CODE] CURRENCY_CHOICES.sort(key=operator.itemgetter(1)) class CurrencySelectWidget(forms.Select): def __init__(self, attrs=None, choices=CURRENCY_CHOICES): super(CurrencySelectWidget, self).__init__(attrs, choices) class InputMoneyWidget(forms.TextInput): def __init__(self, attrs=None, currency_widget=None): self.currency_widget = currency_widget or CurrencySelectWidget() super(InputMoneyWidget, self).__init__(attrs) def render(self, name, value, attrs=None): amount = '' currency = ''
def get_title(obj: Rate) -> str: """ Get the currency title """ currency = CURRENCIES.get(obj.currency) return _(getattr(currency, 'name', '-'))
# The default currency, you can define this in your project's settings module # This has to be a currency object imported from moneyed DEFAULT_CURRENCY = getattr(settings, "DEFAULT_CURRENCY", DEFAULT_CURRENCY) # The default currency choices, you can define this in your project's # settings module PROJECT_CURRENCIES = getattr(settings, "CURRENCIES", None) CURRENCY_CHOICES = getattr(settings, "CURRENCY_CHOICES", None) if CURRENCY_CHOICES is None: if PROJECT_CURRENCIES: CURRENCY_CHOICES = [(code, CURRENCIES[code].name) for code in PROJECT_CURRENCIES] else: CURRENCY_CHOICES = [(c.code, c.name) for i, c in CURRENCIES.items() if c.code != DEFAULT_CURRENCY_CODE] CURRENCY_CHOICES.sort(key=operator.itemgetter(1, 0)) DECIMAL_PLACES = getattr(settings, "CURRENCY_DECIMAL_PLACES", 2) DECIMAL_PLACES_DISPLAY = getattr( settings, "CURRENCY_DECIMAL_PLACES_DISPLAY", {currency[0]: DECIMAL_PLACES for currency in CURRENCY_CHOICES} ) OPEN_EXCHANGE_RATES_URL = getattr(settings, "OPEN_EXCHANGE_RATES_URL", "https://openexchangerates.org/api/latest.json") OPEN_EXCHANGE_RATES_APP_ID = getattr(settings, "OPEN_EXCHANGE_RATES_APP_ID", None) FIXER_URL = getattr(settings, "FIXER_URL", "http://data.fixer.io/api/latest") FIXER_ACCESS_KEY = getattr(settings, "FIXER_ACCESS_KEY", None) BASE_CURRENCY = getattr(settings, "BASE_CURRENCY", "USD") EXCHANGE_BACKEND = getattr(settings, "EXCHANGE_BACKEND", "djmoney.contrib.exchange.backends.OpenExchangeRatesBackend") RATES_CACHE_TIMEOUT = getattr(settings, "RATES_CACHE_TIMEOUT", 600)
def get_countries(obj: Rate) -> list: """ Get the currency countries """ currency = CURRENCIES.get(obj.currency) return getattr(currency, 'countries', '-')
def get_title(rate: Rate) -> str: """Get the currency title.""" currency = CURRENCIES.get(rate.currency) return _(getattr(currency, "name", "-").strip())
def get_countries(rate: Rate) -> List[str]: """Get the currency countries.""" currency = CURRENCIES.get(rate.currency) return getattr(currency, "countries", "-")
EMAIL_MESSAGE_CONTACT_NAME = os.environ.get('EMAIL_MESSAGE_CONTACT_NAME', None) EMAIL_MESSAGE_CONTACT_EMAIL = os.environ.get( 'EMAIL_MESSAGE_CONTACT_EMAIL', None ) SCM_TOOL_URL = os.getenv('SCM_TOOL_URL', '') RALPH_HOST_URL = os.environ.get('RALPH_HOST_URL', None) # METRICS COLLECT_METRICS = False ALLOW_PUSH_GRAPHS_DATA_TO_STATSD = False STATSD_GRAPHS_PREFIX = 'ralph.graphs' TRANSITION_TEMPLATES = None CONVERT_TO_DATACENTER_ASSET_DEFAULT_STATUS_ID = 1 CONVERT_TO_BACKOFFICE_ASSET_DEFAULT_STATUS_ID = 1 # Currency choices for django-money DEFAULT_CURRENCY_CODE = 'XXX' CURRENCY_CHOICES = [ (c.code, c.code) for i, c in CURRENCIES.items() if c.code != DEFAULT_CURRENCY_CODE ] CURRENCY_CHOICES.append(('XXX', '---')) OAUTH_CLIENT_ID = "" OAUTH_SECRET = "" OAUTH_TOKEN_URL = "https://localhost/"
def get_currency_codes(self): return sorted(list(CURRENCIES.keys()), key=str.lower)