def validate_listing_format(self, validation_data=[]): """ Function used to check if auction listing list is valid (syntax + datatype) expecting list order: validation_data[0] = timestamp (int) validation_data[1] = userid (int) validation_data[2] = action (str) validation_data[3] = item (str) validation_data[4] = reserve_price (decimal) validation_data[5] = close_time (int) output: boolean: """ is_valid = False # need to think of how to validate 'item' is a unique string code try: timestamp_check = validation_data[0] int(timestamp_check) user_id_check = validation_data[1] int(user_id_check) action_check = True if validation_data[2] == 'SELL' else False reserve_price_check = validation_data[4] decimal(reserve_price_check) close_time_check = validation_data[5] int(close_time_check) if action_check: is_valid = True return is_valid except ValueError as value_validation: self.logger.error('{0}'.format(value_validation))
def json_decode(obj): """ Override default JSON decoder to recursively convert strings into numeric or boolean """ from six import string_types from decimal import InvalidOperation, Decimal as decimal from distutils.util import strtobool str_converters = [(lambda x: int(x) if (int(x) == decimal(x)) else decimal(x), (ValueError, InvalidOperation)), (lambda x: decimal(x), (ValueError, InvalidOperation)), (lambda x: bool(strtobool(x)), ValueError)] if isinstance(obj, string_types): for converter, error in str_converters: if not callable(converter): continue try: return converter(obj) except error: pass return obj elif isinstance(obj, (float, decimal)) and (int(obj) == decimal(obj)): return int(obj) elif isinstance(obj, dict): return {k: json_decode(v) for k, v in obj.items()} elif isinstance(obj, list): return [json_decode(v) for v in obj] else: return obj
def get_namespace(self, resource): context = self.context abspath = resource.get_abspath() # products namespace products_ns = [] total_with_tax = decimal(0) total_pre_tax = decimal(0) for product_cart in self.products: # Get product product = context.root.get_resource(product_cart['name'], soft=True) # Check product is buyable if not product or not product.is_buyable(context): continue quantity = product_cart['quantity'] id_declination = product_cart['declination'] unit_price_with_tax = product.get_price_with_tax(id_declination) unit_price_with_tax = decimal(unit_price_with_tax) total_with_tax += unit_price_with_tax * quantity unit_price_pre_tax = product.get_price_without_tax(id_declination) unit_price_pre_tax = decimal(unit_price_pre_tax) total_pre_tax += unit_price_pre_tax * quantity product_ns = {'id': product_cart['id'], 'name': product.name, 'title': product.get_title(), 'href': context.get_link(product), 'price': unit_price_with_tax * quantity, 'quantity': quantity} products_ns.append(product_ns) # Build namespace return {'nb_products': self.get_nb_products(), 'total_with_tax': format_price(total_with_tax), 'total_pre_tax': format_price(total_pre_tax), 'products': products_ns}
def validate_bid_format(self, validation_data=[]): """ Function used to check if a bid is valid (syntax + datatype) Parameters: validation_data[0] (int): timestamp validation_data[1] (int): user_id validation_data[2] (int): action validation_data[3] (str): item validation_data[4] (decimal): bid_amount Return: boolean : True or False """ is_valid = False try: timestamp_check = validation_data[0] int(timestamp_check) user_id_check = validation_data[1] int(user_id_check) action_check = True if validation_data[2] == 'BID' else False bid_amount_check = validation_data[4] decimal(bid_amount_check) if action_check: is_valid = True return is_valid except ValueError as value_validation: self.logger.error('{0}'.format(value_validation))
class Payments_ChoosePayment(STLForm): access = 'is_authenticated' title = MSG(u'Choose a payment way') template = '/ui/backoffice/payments/choose_payment.xml' total_price = {'with_tax': decimal('0'), 'without_tax': decimal('0')} def get_namespace(self, resource, context): total_price = self.total_price namespace = {'payments': [], 'total_price': total_price} for mode in resource.search_resources(cls=PaymentWay): logo = mode.get_property('logo') if logo: logo = mode.get_resource(logo, soft=True) shipping_groups = mode.get_property('only_this_groups') user_group = context.user.get_property('user_group') if len(shipping_groups) > 0 and user_group not in shipping_groups: continue if mode.is_enabled(context) is False: continue namespace['payments'].append({ 'name': mode.name, 'value': mode.get_title(), 'description': mode.get_payment_way_description(context, total_price), 'logo': str(context.resource.get_pathto(logo)) if logo else None, 'enabled': True }) return namespace
def float_hex_2_float(str_pi_hex_digits, precisao) -> decimal: getcontext().prec = precisao getcontext().rounding = ROUND_FLOOR mypi10 = decimal(0) for i in range(len(str_pi_hex_digits)-1, -1, -1): mypi10 += decimal(int(str_pi_hex_digits[i], base=16) * 16 ** -i) return mypi10
def is_greater_than_reserve_price(self, reserve_price, bid_price): """ Returns the status of a bid, by checking the reserve price """ try: status = False bid_price = decimal(bid_price) reserve_price = decimal(reserve_price) if bid_price > reserve_price: self.logger.info( 'Bid price £{0} is greater than reserve price £{1}'.format( bid_price, reserve_price)) status = True #self.logger.info('Bid price £{0} is greater than reserve price £{1}'.format(bid_price, reserve_price)) else: self.logger.info( 'Bid price £{0} is less than reserve price £{1} for the item' .format(bid_price, reserve_price)) return status except Exception as is_greater_than_reserve_price_error: output = str(is_greater_than_reserve_price_error) self.logger.error( 'Error in is_greater_than_reserve_price function: {0}'.format( output))
def __init__(self, minimum=None, maximum=None, **params): super(Decimal, self).__init__(**params) if isinstance(minimum, string): try: minimum = decimal(minimum) except InvalidOperation: raise TypeError("argument 'minimum' must be either None, a decimal.Decimal value," " or a string representing a valid decimal value") if not (minimum is None or isinstance(minimum, decimal)): raise TypeError("argument 'minimum' must be either None, a decimal.Decimal value," " or a string representing a valid decimal value") if isinstance(maximum, string): try: maximum = decimal(maximum) except InvalidOperation: raise TypeError("argument 'maximum' must be either None, a decimal.Decimal value," " or a string representing a valid decimal value") if not (maximum is None or isinstance(maximum, decimal)): raise TypeError("argument 'maximum' must be either None, a decimal.Decimal value," " or a string representing a valid decimal value") self.maximum = maximum self.minimum = minimum
def action_pay(self, resource, context, form): from orders import Order cart = ProductCart(context) root = context.root # Check if cart is valid if not cart.is_valid(): return context.come_back(CART_ERROR, goto='/') # Calcul total price total_price_with_tax = decimal(0) total_price_without_tax = decimal(0) total_weight = decimal(0) for cart_elt in cart.products: product = context.root.get_resource(cart_elt['name']) quantity = cart_elt['quantity'] declination = cart_elt['declination'] unit_price_with_tax = product.get_price_with_tax(declination) unit_price_without_tax = product.get_price_without_tax(declination) total_price_with_tax += unit_price_with_tax * quantity total_price_without_tax += unit_price_without_tax * quantity total_weight += product.get_weight(declination) * quantity # Get Shipping price shipping_price = cart.get_shipping_ns(resource, context)['price'] total_price_with_tax += shipping_price total_price_without_tax += shipping_price # Arrondi total_price_with_tax = get_arrondi(total_price_with_tax) total_price_without_tax = get_arrondi(total_price_without_tax) # Guess ref number # We take last order name + 1 search = root.search(format='order') orders = search.get_documents(sort_by='creation_datetime', reverse=True) if orders: ref = str(int(orders[0].name) + 1) else: ref = '1' # We create a new order kw = {'user': context.user, 'payment_mode': form['payment'], 'shipping_price': shipping_price, 'total_price': total_price_with_tax, 'total_weight': total_weight, 'cart': cart, 'shop': resource, 'shop_uri': context.uri.resolve('/')} orders = resource.get_resource('orders') order = Order.make_resource(Order, orders, ref, title={'en': u'#%s' % ref}, **kw) # We clear the cart cart.clear() # We show the payment form kw = {'ref': ref, 'amount': total_price_with_tax, 'amount_without_tax': total_price_without_tax, 'resource_validator': str(order.get_abspath()), 'mode': form['payment']} payments = resource.get_resource('payments') return payments.show_payment_form(context, kw)
def _show_payment_form(self, context, payment): percent = self.get_property('percent') payment['mode'] = 'paybox' # XXX (Can have another name ?) if self.get_property('pay_tax'): payment['amount'] = payment['amount'] * (percent / decimal('100.0')) else: payment['amount'] = payment['amount_without_tax'] * (percent / decimal('100.0')) return self.parent.show_payment_form(context, payment)
def _as_decimal(s): # this will raise a type error if s cannoy be parsed into a # decimal. It presumes strongly that there was a d or D suffix on # the value s = s[:-1] decimal(s) return cons(_symbol_decimal, s, nil)
def get_credit_available_for_user(self, user_name): users_credit = self.get_resource('users-credit').handler results = users_credit.search(user=user_name) if len(results) == 0: return decimal('0.0') credit = decimal('0.0') for record in results: credit += users_credit.get_record_value(record, 'amount') return credit
def test_maximum(self): field = Decimal(maximum='0.0') self.assert_processed( field, (decimal('0'), '0'), (decimal('0.0'), '0.0'), (decimal('-1.0'), '-1.0'), ) self.assert_not_processed(field, 'maximum', decimal('1.0'), decimal('1'))
def test_processing(self): field = Decimal() self.assert_processed( field, None, (decimal('0'), '0'), (decimal('-1.0'), '-1.0'), (decimal('1'), '1'), ) self.assert_not_processed(field, 'invalid', '')
def getBalanceOf(self, walletAddress): global balance balance = 0 if (len(self.getChains()) > 0): for block in self.getChains(): for txn in block.getTransactions(): if (txn.fromAddress == walletAddress): balance = (decimal(balance) - decimal(txn.amount)) elif (txn.toAddress == walletAddress): balance += decimal(txn.amount) return balance
def test_decimal(self): self.setup(Decimal, default=decimal('50.5'), allow_none=False) self.commons(DecimalVariable) self.assertEqual(self.obj.prop1, decimal('50.5')) self.assertRaises(NoneError, setattr, self.obj, 'prop1', None) self.obj.prop2 = None self.assertEqual(self.obj.prop2, None) self.obj.prop1 = 1 self.assertTrue(isinstance(self.obj.prop1, decimal))
def get_schema(self, resource, context): schema = {'paths': String(multiple=True, mandatory=True)} for group in UserGroup_Enumerate.get_options(): group = context.root.get_resource(group['name']) prefix = group.get_prefix() schema.update( {'%spre-tax-price' % prefix: Decimal(default=decimal(0), mandatory=True), '%stax' % prefix: TaxesEnumerate(mandatory=True), '%shas_reduction' % prefix: Boolean, '%snot_buyable_by_groups' % prefix: Tokens, '%sreduce-pre-tax-price' % prefix: Decimal(default=decimal(0))}) return schema
def get_payment_way_description(self, context, total_amount): msg = MSG(u"Pay {percent}% of {original_amount} now ({amount})") percent = self.get_property('percent') if self.get_property('pay_tax'): total_amount = total_amount['with_tax'].split(' ')[0] total_amount = decimal(total_amount) else: total_amount = total_amount['without_tax'].split(' ')[0] total_amount = decimal(total_amount) amount = total_amount * (percent / decimal('100.0')) msg = msg.gettext(percent=percent, original_amount=format_price(total_amount), amount=format_price(amount)) return list(XMLParser(msg.encode('utf-8'))) + self.get_property('data')
def interpolate(self, subject, parameters, interpolator=None): if subject is None: return None elif isinstance(subject, decimal): return subject else: return decimal(interpolate_parameters(subject, parameters, True, interpolator))
def get_products_namespace(self, context): root = context.root query = AndQuery( get_base_path_query(self.get_canonical_path()), PhraseQuery('format', 'order-product')) l = [] for brain in root.search(query).get_documents(): resource = root.get_resource(brain.abspath, soft=True) if resource is None: log_warning('ORDER-PRODUCT not found : %s' % brain.abspath) continue # Get base product namespace kw = {} for key in ['reference', 'title', 'tax', 'quantity']: kw[key] = resource.get_property(key) kw['pre_tax_price'] = resource.get_property('pre_tax_price') tax = kw['tax'] / decimal(100) + 1 kw['price_with_tax'] = get_arrondi(kw['pre_tax_price'] * tax) total_price = kw['price_with_tax'] * kw['quantity'] kw['pre_tax_price'] = self.format_price(kw['pre_tax_price']) kw['total_price'] = self.format_price(total_price) kw['price_with_tax'] = self.format_price(kw['price_with_tax']) # Get product link (if exist) abspath = resource.get_property('abspath') product = root.get_resource(abspath, soft=True) if product: # Add link only if edit allowed link = None ac = resource.get_access_control() if ac.is_allowed_to_edit(context.user, product): link = context.get_link(product) kw['link'] = link # Add product to list of products l.append(kw) return l
def coerce(self, unit, value): """Coerce the given value to the proper type for this property. This function MUST be called when retrieving unit property values from storage, and SHOULD be called when accepting new values from user interfaces. Therefore, it SHOULD NOT perform input validation beyond type-coercion. Override __set__ for that instead (or use the 'on_set' method of a TriggerProperty, below). In the base class, the 'unit' arg is not used. When overriding this class, you should allow for meaningful results even if the supplied 'unit' arg is None. """ if value is not None: selftype = self.type if not isinstance(value, selftype): # Try to cast the value to self.type. try: value = selftype(value) except Exception, x: msg = ("%r is type %r (expected %r)" % (value, type(value), selftype)) x.args += (msg,) raise # The final indignity ;) if decimal and (selftype is decimal): scale = self.hints.get('scale', None) if scale: value = value.quantize(decimal("." + ("0" * scale)))
def _pack_decimal(d, case_sensitive=True, neg=False): ''' This supports decimals on the order of +/- 10**(-32768) to 10**32767 . This is over 100 orders of magnitude greater than floats, and can support whatever precision your decimals already have. ''' td = decimal(d) if neg: td._sign ^= 1 sign = 'n' if td._sign else 'p' si = td._int lsi = len(si) magnitude = lsi + td._exp if td._sign: # We need to mangle negative numbers into positive numbers for proper # sorts. si = ("%%0%ii"%(lsi,))%(10**lsi - int(td._int)) ## si = ''.join(map(str, [10-i for i in map(int, si)])) magnitude = struct.pack('>H', 32768+((-magnitude) if sign == 'n' else magnitude)) mantissa = si if USE_BCD: # This will use binary-coded decimal to store the value instead of the # pre-existing decimal representation. This will halve the storage # requirements for the 'mantissa' portion of the value. imantissa = iter(itertools.imap(int, mantissa)) mantissa = ''.join(itertools.imap(chr, (((l+1)<<4) + (r+1) for l,r in itertools.izip_longest(imantissa, imantissa, fillvalue=0)))) return sign + magnitude + mantissa + '\0'
def convertDuration(dur): '''Convert ISO 8601 duration string to seconds Simplified from isodate by Gerhard Weis (https://github.com/gweis/isodate) :param dur: ISO 8601 duration string :type dur: string ''' reg = re.compile(r"^(?P<sign>[+-])?" r"P(?!\b)" r"(?P<years>[0-9]+([,.][0-9]+)?Y)?" r"(?P<months>[0-9]+([,.][0-9]+)?M)?" r"(?P<weeks>[0-9]+([,.][0-9]+)?W)?" r"(?P<days>[0-9]+([,.][0-9]+)?D)?" r"((?P<separator>T)(?P<hours>[0-9]+([,.][0-9]+)?H)?" r"(?P<minutes>[0-9]+([,.][0-9]+)?M)?" r"(?P<seconds>[0-9]+([,.][0-9]+)?S)?)?$") items = reg.match(dur) el = items.groupdict() for key, val in el.items(): if key not in ('separator', 'sign'): if val is None: el[key] = "0n" if key in ('years', 'months'): el[key] = decimal(el[key][:-1].replace(',', '.')) else: el[key] = float(el[key][:-1].replace(',', '.')) return int(el["weeks"] * 604800 + el["days"] * 86400 + el["hours"] * 3600 + el["minutes"] * 60 + el["seconds"])
def POST(self, resource, context): form = self._get_form(resource, context) # Get payment record payments = resource.get_resource('payments').handler record = payments.search(ref=form['ref'])[0] # Get informations infos = {'state': True if form['autorisation'] else False} for key in ['transaction', 'autorisation', 'advance_state']: infos[key] = form[key] # We Check amount amount = form['amount'] / decimal('100') if payments.get_record_value(record, 'amount') != amount: infos['state'] = False infos['advance_state'] = 'amount_invalid' # We ensure that remote ip address belongs to Paybox remote_ip = context.get_remote_ip() if remote_ip not in self.authorized_ip: infos['state'] = False infos['advance_state'] = 'ip_not_authorized' # Update record payments.update_record(record.id, **infos) # XXX TODO Check signature # Confirm_payment if infos['state']: resource.set_payment_as_ok(record.id, context) # Return a blank page to payment context.set_content_type('text/plain')
def get_price_with_tax(self, with_devise=False): price = self.get_property('pre_tax_price') tax = self.get_tax_value() / decimal(100) + 1 price = get_arrondi(price * tax) if with_devise is False: return price return format_price(price)
def get_tax_value(self, prefix=None): shop = get_shop(self) if prefix is None: prefix = self.get_price_prefix() # Get zone from cookie id_zone = ProductCart(get_context()).id_zone # If not define... get default zone if id_zone is None: id_zone = shop.get_property('shop_default_zone') # Check if zone has tax ? zones = shop.get_resource('countries-zones').handler zone_record = zones.get_record(int(id_zone)) if zones.get_record_value(zone_record, 'has_tax') is True: tax = self.get_property('%stax' % prefix) tax_value = TaxesEnumerate.get_value(tax) or decimal(0) return (tax_value / decimal(100) + 1) return decimal(1)
def get_tax_value(self, prefix=None): shop = get_shop(self) if prefix is None: prefix = self.get_price_prefix() # Get zone from cookie id_zone = ProductCart(get_context()).id_zone # If not define... get default zone if id_zone is None: id_zone = shop.get_property('shop_default_zone') # Check if zone has tax ? zones = shop.get_resource('countries-zones').handler zone_record = zones.get_record(int(id_zone)) if zones.get_record_value(zone_record, 'has_tax') is True: tax = self.get_property('%stax'% prefix) tax_value = TaxesEnumerate.get_value(tax) or decimal(0) return (tax_value/decimal(100) + 1) return decimal(1)
def get_payment_way_description(self, context, total_amount): total_amount = total_amount['with_tax'] if not type(total_amount) is decimal: # XXX We don't need currency total_amount = decimal(total_amount.split(' ')[0]) amount_available = self.get_credit_available_for_user(context.user.name) remaining_amount = amount_available - total_amount if remaining_amount < decimal('0'): remaining_amount = decimal('0') namespace = {'amount_available': format_price(amount_available), 'has_to_complete_payment': amount_available < total_amount, 'amount_to_pay': format_price(total_amount-amount_available), 'remaining_amount': format_price(remaining_amount), 'total_amount': format_price(total_amount)} description_template = self.get_resource( '/ui/backoffice/payments/credit/description.xml') return stl(description_template, namespace=namespace)
def _unserialize_value(self, value, ancestry): if isinstance(value, decimal): return value try: return decimal(value) except Exception: raise InvalidTypeError(identity=ancestry, field=self, value=value).construct('invalid')
def is_greater_than_existing_bids(self, valid_bid_list, current_bid): """ Returns the status of a bid, by comparing the highest bid to current bid """ status = False if not valid_bid_list: status = True self.logger.info( 'Current highest bid submitted at £{0}'.format(current_bid)) return status else: try: self.logger.info( 'Assigning variables(highest bid, current bid and converting to decimal)' ) highest_bid = valid_bid_list[-1].bid_amount item = valid_bid_list[-1].item current_bid = decimal(current_bid) highest_bid = decimal(highest_bid) self.logger.info( 'Completed variable assignment, attempting to validate price' ) if current_bid > highest_bid: self.logger.info( 'Bid price £{0} is greater than current highest bid price £{1}' .format(str(current_bid), str(highest_bid))) status = True self.logger.info( 'Attempting to make £{0} the highest bid so far'. format(str(current_bid))) self.all_listed_items[item].highest_bid = str(current_bid) self.logger.info( 'Successfully set £{0} as the highest bid so far for {1}' .format(str(current_bid), item)) else: self.logger.info( 'Bid price £{0} is less than current highest bid price £{1}' .format(current_bid, highest_bid)) self.logger.info('Unfortunately this bid is unsuccessful') return status except Exception as existing_bids_error: output = str(existing_bids_error) self.logger.error( 'Error translating data from string to decimal: {0}'. format(output))
def clean_price(self): price = self.cleaned_data['price'] try: cleaned = decimal.decimal(price) except decimal.InvalidOperation: raise forms.ValidationError(_(u'Поле "Цена" должно содержать только цифры.')) if len(str(cleaned)) > 8: raise forms.ValidationError(_(u'Цена невероятно высока.')) return price
def apply_random_seed(seed=None, **kwargs): ''' Applies a certain seed in the same format as init_random_seed() ''' if seed is None: seed = init_random_seed() if type(seed) is not decimal: seed = decimal(seed) random.seed(seed)
def test_decimal(self): self.setup(Decimal, default=decimal("50.5"), allow_none=False) self.assertTrue(isinstance(self.column1, Column)) self.assertTrue(isinstance(self.column2, Column)) self.assertEquals(self.column1.name, "column1") self.assertEquals(self.column1.table, self.SubClass) self.assertEquals(self.column2.name, "prop2") self.assertEquals(self.column2.table, self.SubClass) self.assertTrue(isinstance(self.variable1, DecimalVariable)) self.assertTrue(isinstance(self.variable2, DecimalVariable)) self.assertEquals(self.obj.prop1, decimal("50.5")) self.assertRaises(NoneError, setattr, self.obj, "prop1", None) self.obj.prop2 = None self.assertEquals(self.obj.prop2, None) self.obj.prop1 = 1 self.assertTrue(isinstance(self.obj.prop1, decimal))
def _decode_simple_value(field_cls, data): """Used to decode values in stored fields. """ # Overload the Integer type, cf _encode_simple_value if issubclass(field_cls, Integer): return int(sortable_unserialise(data)) elif issubclass(field_cls, Decimal): return decimal(sortable_unserialise(data)) # A common field or a new field return field_cls.decode(data)
def init_random_seed(timestamp=None, worker=0, iteration=0, **kwargs): ''' Initializes a random seed based on the current time, simulaton worker and iteration, which ensures a unique seed ''' if timestamp is None: timestamp = time.time() seed = "{:.0f}".format(timestamp * 10**7) + str(worker) + str(iteration) random.seed(decimal(seed)) # print(seed) return seed
def get_vat_details(self, context): vat = 0 pre_vat = 0 query = AndQuery( get_base_path_query(self.get_canonical_path()), PhraseQuery('format', 'order-product')) for brain in context.root.search(query).get_documents(): resource = context.root.get_resource(brain.abspath) tax = resource.get_property('tax') / decimal(100) pre_tax_price = resource.get_property('pre_tax_price') pre_vat += pre_tax_price vat += tax * pre_tax_price return pre_vat, vat
def test_interpolation(self): field = Decimal() self.assert_interpolated( field, None, ('1', decimal('1')), (decimal('1'), decimal('1')), ('1.0', decimal('1.0')), ) self.assert_interpolated(field, ('${value}', decimal('1.0')), value=decimal('1.0')) self.assert_interpolated(field, ('${value}', decimal('1.0')), value='1.0')
def scifi(lex): # check for 1 and only 1 E if(lex.count('E') == 1): pos = lex.index('E') # position of E int_chk = lex[pos+1: ] # create string before E dec_chk = lex[ : pos] # create string after E else: return False # check if before and after strings hold if(integer(int_chk) and decimal(dec_chk)): return True else: return False
def render(cls, value, context): if value is None: return None # Get informations accept = context.accept_language site_root = context.resource.get_site_root() ws_languages = site_root.get_property('website_languages') lang = accept.select_language(ws_languages) # Render mesure = u'cm' if lang == 'en': inch = decimal('2.54') mesure = u'inch' value = format_price(value/inch) return u'%s %s' % (value, mesure)
def get_total_price(self, shop, with_delivery=True, pretty=True): context = self.context total_price_with_tax = decimal(0) total_price_without_tax = decimal(0) total_weight = decimal(0) for cart_elt in self.products: product = context.root.get_resource(cart_elt['name']) quantity = cart_elt['quantity'] declination = cart_elt['declination'] unit_price_with_tax = product.get_price_with_tax(declination) unit_price_without_tax = product.get_price_without_tax(declination) total_price_with_tax += unit_price_with_tax * quantity total_price_without_tax += unit_price_without_tax * quantity total_weight += product.get_weight(declination) * quantity # XXX GEt Shipping price (Hardcoded, fix it) if with_delivery is True: shipping_price = self.get_shipping_ns(shop, context)['price'] total_price_with_tax += shipping_price total_price_without_tax += shipping_price if pretty is True: return {'with_tax': format_price(total_price_with_tax), 'without_tax': format_price(total_price_without_tax)} return {'with_tax': total_price_with_tax, 'without_tax': total_price_without_tax}
def _show_payment_form(self, context, payment): amount_available = self.get_credit_available_for_user(context.user.name) remaining_to_pay = payment['amount'] - amount_available # Partial payment if remaining_to_pay > decimal('0'): # Delete credit users_credit = self.get_resource('users-credit') results = users_credit.handler.search(user=context.user.name) if len(results) == 0: raise ValueError, 'Error, credit do not exist' record = results[0] old_amount = users_credit.handler.get_record_value(record, 'amount') new_amount = old_amount - payment['amount'] if new_amount < decimal('0'): users_credit.del_record(record.id) else: kw = {'amount': new_amount} users_credit.update_recod(record.id, **kw) # Encapsulate in pay view payment['mode'] = 'paybox' # XXX (Can have another name ?) payment['amount'] = remaining_to_pay return self.parent.show_payment_form(context, payment) # Complete payment return PaymentWay._show_payment_form(self, context, payment)
def render(cls, value, context): if value is None: return None # Get informations accept = context.accept_language site_root = context.resource.get_site_root() ws_languages = site_root.get_property('website_languages') lang = accept.select_language(ws_languages) # Render mesure = u'cm' if lang == 'en': inch = decimal('2.54') mesure = u'inch' value = format_price(value / inch) return u'%s %s' % (value, mesure)
def ConvertValue(self, srcum, dstum, total): srcum = '' if srcum is None else srcum dstum = '' if dstum is None else dstum total = dcm.decimal(0, CurrencyContext) if total is None else \ dcm.decimal(total, CurrencyContext) convinfo = self.getConvTable(srcum, dstum) retval = dcm.decimal(0, CurrencyContext) cval = dcm.decimal(0, CurrencyContext) if convinfo[0] is None else \ dcm.decimal(convinfo[0], CurrencyContext) dcm.getcontext().prec = 9 if convinfo[1] == '*': return dcm.decimal(total * cval, CurrencyContext) elif convinfo[1] == '/': if cval == 0: raise Exception('Conversion factor is Zero, value could not be devided') return dcm.decimal(total / cval, CurrencyContext) raise Exception('No conversion could be calculated')
def update_payment_state(self, context): """Update order payment state.""" total_paid = decimal('0') for brain in self.get_payments(as_results=False): payment = context.root.get_resource(brain.abspath) if payment.get_property('is_paid') is False: continue total_paid += payment.get_property('amount') self.set_property('total_paid', total_paid) if total_paid < self.get_property('total_price'): self.set_workflow_state('partially-paid') self.set_property('is_paid', False) elif total_paid == self.get_property('total_price'): self.generate_bill(context) self.set_workflow_state('paid') self.set_property('is_paid', True) self.onenter_paid() elif total_paid > self.get_property('total_price'): self.set_workflow_state('to-much-paid')
def get_default_shipping_way(self, context, widgets): if len(widgets) == 1: return widgets[0] price = decimal('0') for widget in widgets: price += widget['price'] logo_uri = self.get_property('default_shipping_way_logo') if logo_uri is not None: logo = self.get_resource(logo_uri, soft=True) img = context.resource.get_pathto(logo) else: img = None return { 'title': self.get_property('default_shipping_way_title'), 'description': self.get_property('default_shipping_way_description'), 'enabled': True, 'img': img, 'name': 'default', 'pretty_price': format_price(price), 'price': price}
def POST(self, resource, context): # XXX TODO Check signature form = self._get_form(resource, context) # Set payment as paid if form['autorisation']: resource.update_payment_state(context, paid=True) else: resource.update_payment_state(context, paid=False) for key in ['transaction', 'autorisation', 'advanced_state']: resource.set_property(key, form[key]) # We check amount amount = form['amount'] / decimal('100') if resource.get_property('amount') != amount: raise ValueError, 'invalid payment amount' # We ensure that remote ip address belongs to Paybox authorized_ip = self.authorized_ip payment_way = get_payment_way(resource, 'paybox') if not payment_way.get_property('real_mode'): authorized_ip = authorized_ip + [None] if context.get_remote_ip() not in authorized_ip: resource.set_property('advanced_state', 'ip_not_authorized') # Return a blank page to payment context.set_content_type('text/plain')
from dynamic_folder import DynamicFolder from widgets import DeclinationPricesWidget from shop.enumerate_table import EnumerateTable_to_Enumerate from shop.utils import get_shop declination_schema = {#General informations 'reference': String, 'title': Unicode, # Default declination ? 'is_default': Boolean, # Stock 'stock-quantity': Integer(default=0), # Weight 'impact-on-weight': DeclinationImpact, 'weight-impact-value': Decimal(default=decimal(0)), # Price 'impact_on_price': Decimal(default=decimal(0)), 'pro-impact_on_price': Decimal(default=decimal(0)), # Associated images #'associated-image': ImagesEnumerate # XXX Old to delete 'pro-price-impact-value': Decimal(default=decimal(0)), 'impact-on-price': DeclinationImpact, 'price-impact-value': Decimal(default=decimal(0)), } declination_widgets = [ TextWidget('reference', title=MSG(u'Reference')), TextWidget('title', title=MSG(u'Title')),