def create_wallet(event): logger.info("Starting function create_wallet") minimum_balance = moneyed.Money(0, 'INR') maximum_balance = moneyed.Money(0, 'INR') associated_event = event type = 'E' logger.info("Completing function create_wallet") return Wallet.objects.create(minimum_balance, maximum_balance, type, 'INR', None, associated_event)
def post(self, request, access_token=None, *args, **kwargs): try: user = BdayAppUser.objects.create_user( email_id=request.data['email_id']) minimum_balance = moneyed.Money(0, 'INR') maximum_balance = moneyed.Money(100000, 'INR') wallet = Wallet.objects.create_wallet(minimum_balance, maximum_balance, 'U', 'INR', user, None) serializer = UserSerializer(user) return response.Response(serializer.data) except Exception as e: UserView.handle_error(e)
def post(self, request, access_token, *args, **kwargs): try: user = BdayAppUser.objects.create_user() minimum_balance = moneyed.Money(0, 'INR') maximum_balance = moneyed.Money(100000, 'INR') wallet = Wallet.objects.create_wallet(minimum_balance, maximum_balance, 'U', 'INR', user, None) user_profile = UserProfile.objects.create_user_profile( access_token, request.data['profile_type'], user) serializer = UserProfileSerializer(user_profile) return response.Response(serializer.data) except Exception as e: UserProfileView.handle_error(e)
def post(self, request, access_token, id, *args, **kwargs): try: user = UserProfileView.get_profile(access_token).user if request.FILES: file = request.FILES['file_field'] else: file = None event = Event.objects.create_event(admin=user,name=request.data['name'],start_date=request.data['start_date'],end_date=request.data['end_date'],picture=file) minimum_balance = moneyed.Money(0, 'INR') maximum_balance = moneyed.Money(100000, 'INR') wallet = Wallet.objects.create_wallet(minimum_balance, maximum_balance, 'E', 'INR', None, event) serializer = EventSerializer(event) return response.Response(serializer.data) except Exception as e: EventView.handle_error(e)
def convert_money(amount, currency_from, currency_to): """ Convert 'amount' from 'currency_from' to 'currency_to' and return a Money instance of the converted amount. """ new_amount = base_convert_money(amount, currency_from, currency_to) return moneyed.Money(new_amount, currency_to)
def _set_decimal(self: GS1ElementString) -> None: variable_measure = self.ai.ai[:2] in ( "31", "32", "33", "34", "35", "36", ) amount_payable = self.ai.ai[:3] in ("390", "392") amount_payable_with_currency = self.ai.ai[:3] in ("391", "393") percentage = self.ai.ai[:3] in ("394", ) if (variable_measure or amount_payable or amount_payable_with_currency or percentage): # See GS1 General Specifications, chapter 3.6 for details. # Only group for variable_measure, amount_payable, and percentage. # Second and last group for amount_payable_with_currency. value = self.pattern_groups[-1] num_decimals = int(self.ai.ai[3]) num_units = len(value) - num_decimals units = value[:num_units] decimals = value[num_units:] self.decimal = Decimal(f"{units}.{decimals}") if amount_payable_with_currency and moneyed is not None: currency = moneyed.get_currency(iso=self.pattern_groups[0]) self.money = moneyed.Money(amount=self.decimal, currency=currency)
def test_conversion_is_working_from_other_currency(self): source = RateSource.objects.create(name="fake-backend", base_currency="USD") Rate.objects.create(source=source, currency="PLN", value=3.07) Rate.objects.create(source=source, currency="EUR", value=0.74) amount = convert_money(10.0, "PLN", "EUR") self.assertEqual(amount, moneyed.Money(Decimal("2.41"), "EUR"))
def _parse_with_regional_rules(self, region: RcnRegion) -> None: if self.usage == RcnUsage.COMPANY: # The value is an RCN, but it is intended for use within a company, # so we can only interpret it as an opaque GTIN. return if not isinstance(region, RcnRegion): region = RcnRegion(region) self.region = region strategy = _Strategy.get_for_rcn(self) if strategy is None: # Without a strategy, we cannot extract anything. return strategy.verify_check_digit(self) if strategy.measure_type == _MeasureType.WEIGHT: self.weight = strategy.get_variable_measure(self) if strategy.measure_type == _MeasureType.COUNT: self.count = int(strategy.get_variable_measure(self)) if strategy.measure_type == _MeasureType.PRICE: self.price = strategy.get_variable_measure(self) currency_code = self.region.get_currency_code() if self.price is not None and moneyed is not None and currency_code is not None: self.money = moneyed.Money(amount=self.price, currency=currency_code)
def create(self, validated_data): """Create the new account with zero balance in a given currency.""" currency = validated_data.pop("currency") validated_data["balance"] = moneyed.Money( amount=0, currency=currency ) return super().create(validated_data)
def test_conversion_works_from_base_currency(self): source = RateSource.objects.create(name="fake-backend", base_currency="USD") Rate.objects.create(source=source, currency="USD", value=1) Rate.objects.create(source=source, currency="EUR", value=0.74) amount = convert_money(1, "USD", "EUR") self.assertEqual(type(amount), moneyed.Money) self.assertEqual(amount, moneyed.Money(Decimal("0.74"), "EUR"))
def post(self, request, *args, **kwargs): try: logger.info("Starting POST method") access_token = kwargs['access_token'] logger.info("access token is " + access_token) user = UserProfileView.get_profile(access_token).user logger.info("user found from access token") file = None if request.FILES: file = request.FILES['file_field'] logger.info("file found in request") else: file = None end_date = None type = 'DEFAULT' if 'end_date' in request.data: end_date = request.data['end_date'] logger.info("end date is " + end_date) if 'type' in request.data: type = request.data['type'] logger.info("type is " + type) event = Event.objects.create_event( admin=user, name=request.data['name'], start_date=request.data['start_date'], end_date=end_date, picture=file, type=type) logger.info("event created with name " + request.data['name'] + " start date " + request.data['start_date'] + " type " + type) minimum_balance = moneyed.Money(0, 'INR') maximum_balance = moneyed.Money(100000, 'INR') wallet = Wallet.objects.create_wallet(minimum_balance, maximum_balance, 'E', 'INR', None, event) wallet.save() logger.info("wallet created") # chat_buffer = UnreadChatBuffer.objects.create(event=event, user=user, last_read_chat=None) # chat_buffer.save() serializer = EventSerializer(event) logger.info("Completing POST method") return response.Response(serializer.data) except Exception as e: EventView.handle_error(e)
def convert_money(amount, currency_from, currency_to, date=None): """ Convert 'amount' from 'currency_from' to 'currency_to' and return a Money instance of the converted amount. """ if not date: date = datetime.date.today() new_amount = base_convert_money(amount, currency_from, currency_to, date) return moneyed.Money(new_amount, currency_to)
def post(self, request, *args, **kwargs): try: logger.info("Starting function POST") access_token = self.kwargs['access_token'] logger.info("access token is " + access_token) user = UserProfile.objects.get( profile_id__exact='1069321953161548' ).user #UserProfileView.get_profile(access_token).user logger.info("user found from access token") if "amount" not in request.data or "type" not in request.data or "event_id" not in request.data: raise exceptions.APIException( "amount/type/event_id not provided") if request.data["type"] is "GIFT_CARD": if "brand_name" not in request.data: raise exceptions.APIException("brand_name not provided") event = Event.objects.get(pk=int(request.data['event_id'])) if user not in event.admin.all(): raise exceptions.APIException() amount = moneyed.Money(float(request.data['amount']), 'INR') type = request.data["type"] terms_and_conditions = "Hello Terms and Conditions" shipping_and_handling = "Shipping and Handling" brand_details = "demo brand details" coupon_code = "ARIG1234" new_card = CashoutCard.objects.create( type=type, amount=amount, terms_and_conditions=terms_and_conditions, shipping_and_handling=shipping_and_handling, brand_details=brand_details, associated_event=event, coupon_code=coupon_code) new_card.save() cashout_transaction = Transaction.objects.create( from_wallet=event.event_wallet, to_wallet=None, type='D', amount=amount, default_currency="INR", status="S", transaction_date=datetime.datetime.now()) cashout_transaction.save() new_card_serializer = CashOutCardSerializer(new_card) logger.info("other life events list found") logger.info("Completing function POST") return response.Response(new_card_serializer.data) except Event.DoesNotExist: raise exceptions.NotFound("event not found") except Exception as e: CashoutCardView.handle_error(e)
def convert_money(amount, currency_from, currency_to, date=None): """ Convert 'amount' from 'currency_from' to 'currency_to' and return a Money instance of the converted amount. """ # assign new_amount to amount in case of no convertion, avoid useless else new_amount = amount # if the currency is the same, avoid convert nothing if str(currency_from) != str(currency_to): new_amount = base_convert_money(amount, currency_from, currency_to, date) return moneyed.Money(new_amount, currency_to)
def money_field(**kwargs): """Create a money field instance. """ defaults = dict( null=False, blank=False, max_digits=10, decimal_places=2, default=moneyed.Money('0.00', "USD"), default_currency="USD") defaults.update(kwargs) return MoneyField(**defaults)
def validate(self, attrs): """Perform field validation and verify the accounts for the payment.""" if transaction.get_autocommit(): # pragma: nocover # You must wrap the ViewSet.create in transaction.atomic # This check is a safety measure as the code in create relies on # transactions and select_for_update in the from/to_account QSes. # # Note, with PostgreSQL this check is not really necessary as it # would raise exception upon seeing select_for_update on the # account fields. However, not all databases support this and # the exception won't happen if connection.has_select_for_update # is not set. It is a bad idea to test against unsupported DB, # but this check doesn't hurt as well. # # Remove if this somehow blips on perf instrumentation radar. raise RuntimeError("BUG: The code is not running in a transaction") validated_data = super().validate(attrs) from_account = validated_data.get("from_account", None) to_account = validated_data.get("to_account", None) amount = validated_data["amount"] # Ensure there is exactly one currency for all the defined account # Also ensures at least one account is specified currencies = set() if from_account is not None: currencies.add(from_account.currency) if to_account is not None: currencies.add(to_account.currency) if len(currencies) < 1: raise serializers.ValidationError( "At least one account (from_account or to_account) is required" ) currencies.add(validated_data["currency"]) if len(currencies) != 1: # No currency conversion support for now. raise serializers.ValidationError( "Accounts and payment must all use the same currency" ) if isinstance(amount, decimal.Decimal): # pragma: no branch # Add currency (DRF doesn't do this for us), or comparison'll fail amount = moneyed.Money(amount, next(iter(currencies))) # If this transfer has a source, ensure no overdraft is possible if from_account is not None and from_account.balance < amount: raise serializers.ValidationError( "Source account balance is too low for this payment" ) return validated_data
def test_transaction(): eur15 = mn.Money(15, 'EUR') i1 = ta.Income(eur15, None) i2 = ta.Income(eur15) assert i1 == i2 e1 = ta.Expense(-eur15) e2 = ta.Expense(eur15) assert e1 != e2 assert i1 != e1 assert i1 != e2
def test_prices(self): product = products_and_price() p = StockKeepingUnit.objects.get( product=product, attributes__size='large', ) self.assertEqual( moneyed.Money(100, 'SEK'), p.price, ) salesprice = Price.objects.create( amount=50, start=datetime(2015, 11, 1), ) p = StockKeepingUnit.objects.get( product=product, attributes__size='small', ) p.prices.add(salesprice) self.assertEqual( moneyed.Money(50, 'SEK'), p.price, )
def create_wallet(self, minimum_balance, maximum_balance, type, default_currency, associated_user, associated_event, creation_date=datetime.datetime.now()): initial_balance = moneyed.Money(0, 'INR') wallet = self.create(balance=initial_balance, minimum_balance=minimum_balance, maximum_balance=maximum_balance, type=type, default_currency=default_currency, associated_user=associated_user, associated_event=associated_event, creation_date=creation_date) return wallet
def _parse_with_regional_rules(self: Rcn, region: RcnRegion) -> None: if self.usage == RcnUsage.COMPANY: return self.region = region if self.region in (RcnRegion.BALTICS, ): self._parse_using_swedish_weight_rules() if self.region in (RcnRegion.GREAT_BRITAIN, ): self._parse_using_british_price_rules() if self.region in (RcnRegion.NORWAY, RcnRegion.SWEDEN): self._parse_using_swedish_price_rules() self._parse_using_swedish_weight_rules() if self.price is not None and moneyed is not None: self.money = moneyed.Money( amount=self.price, currency=self.region.get_currency_code())
class ModelWithDefaultAsMoney(models.Model): money = MoneyField(default=moneyed.Money('0.01', 'RUB'), max_digits=10, decimal_places=2)
def process_payment(request): checksum = None message = {} if request.method == "POST": respons_dict = {} for i in request.POST.keys(): print i respons_dict[i] = request.POST[i] if i == 'CHECKSUMHASH': checksum = request.POST[i] if 'GATEWAYNAME' in respons_dict: if respons_dict['GATEWAYNAME'] == 'WALLET': respons_dict['BANKNAME'] = 'null' verify = Checksum.verify_checksum(respons_dict, MERCHANT_KEY, checksum) print verify if verify: if respons_dict['RESPCODE'] == '01': print "order successful" for element in [ "SUBS_ID", "PROMO_CAMP_ID", "PROMO_STATUS", "PROMO_RESPCODE" ]: if element not in respons_dict: respons_dict[element] = None user_profile = UserProfileView.get_profile(ACCESS_TOKEN) if request.session["transaction_type"] == "USER": wallet = Wallet.objects.get( associated_user=user_profile.user) else: event = Event.objects.get(pk=EVENT_ID) wallet = Wallet.objects.get(associated_event=event) with transaction.atomic(): amount = moneyed.Money(float(respons_dict['TXNAMOUNT']), respons_dict['CURRENCY']) wallet.balance = wallet.balance + amount wallet.save() if request.session["transaction_type"] == "USER": transaction_object = Transaction.objects.create( from_wallet=None, to_wallet=Wallet.objects.get( associated_user=user_profile.user), type='CREDIT', amount=amount, default_currency=respons_dict['CURRENCY'], status=respons_dict["STATUS"], order_id=respons_dict["ORDERID"], external_transaction_flag=True, external_subscription_id=respons_dict["SUBS_ID"], external_transaction_id=respons_dict["TXNID"], bank_transaction_id=respons_dict["BANKTXNID"], transaction_date=respons_dict["TXNDATE"], gateway_name=respons_dict["GATEWAYNAME"], bank_name=respons_dict["BANKNAME"], payment_mode=respons_dict["PAYMENTMODE"], promo_camp_id=respons_dict["PROMO_CAMP_ID"], promo_status=respons_dict["PROMO_STATUS"], promo_response_code=respons_dict["PROMO_RESPCODE"]) else: transaction_object = Transaction.objects.create( from_wallet=None, to_wallet=Wallet.objects.get( associated_event=event), type='CREDIT', amount=amount, default_currency=respons_dict['CURRENCY'], status=respons_dict["STATUS"], order_id=respons_dict["ORDERID"], external_transaction_flag=True, external_subscription_id=respons_dict["SUBS_ID"], external_transaction_id=respons_dict["TXNID"], bank_transaction_id=respons_dict["BANKTXNID"], transaction_date=respons_dict["TXNDATE"], gateway_name=respons_dict["GATEWAYNAME"], bank_name=respons_dict["BANKNAME"], payment_mode=respons_dict["PAYMENTMODE"], promo_camp_id=respons_dict["PROMO_CAMP_ID"], promo_status=respons_dict["PROMO_STATUS"], promo_response_code=respons_dict["PROMO_RESPCODE"]) transaction_object.save() if request.session["transaction_type"] == "EVENT": chat = EventChat.objects.create_event_chat( Event.objects.get(pk=event.id), user_profile.user, wish=None, message_field=user_profile.user.id + " contributed " + str(amount.amount), url_field=None, file_field=None, type='CENTER') chat.save() members = event.members for member in members: notification_message = "Your friend " + user_profile.first_name + " contributed " + str( amount.amount) + " to event " + event.name notification = Notification.objects.create_notification( notification_message, member, None) notification.save() else: print "order unsuccessful because" + respons_dict['RESPMSG'] else: print "order unsuccessful because" + respons_dict['RESPMSG'] message["details"] = respons_dict['RESPMSG'] return HttpResponse(status=200, content_type="application/json", content=json.dumps(message))
def create_wallet(event): minimum_balance = moneyed.Money(0,'INR') maximum_balance = moneyed.Money(0,'INR') associated_event = event type = 'E' return Wallet.objects.create(minimum_balance, maximum_balance, type, 'INR',None, associated_event)
def process_payment(request): global exitFlag exitFlag = 0 checksum = None message = {} if request.method == "POST": respons_dict = {} for i in request.POST.keys(): print i respons_dict[i] = request.POST[i] if i == 'CHECKSUMHASH': checksum = request.POST[i] if 'GATEWAYNAME' in respons_dict: if respons_dict['GATEWAYNAME'] == 'WALLET': respons_dict['BANKNAME'] = 'null' verify = Checksum.verify_checksum(respons_dict, MERCHANT_KEY, checksum) print verify if verify: if respons_dict['RESPCODE'] == '01': print "order successful" for element in [ "SUBS_ID", "PROMO_CAMP_ID", "PROMO_STATUS", "PROMO_RESPCODE" ]: if element not in respons_dict: respons_dict[element] = None user_profile = UserProfileView.get_profile( request.session["ACCESS_TOKEN"]) if request.session["transaction_type"] == "USER": wallet = Wallet.objects.get( associated_user=user_profile.user) else: event = Event.objects.get(pk=request.session["event_id"]) wallet = Wallet.objects.get(associated_event=event) with transaction.atomic(): amount = moneyed.Money(float(respons_dict['TXNAMOUNT']), respons_dict['CURRENCY']) wallet.balance = wallet.balance + amount wallet.save() if request.session["transaction_type"] == "USER": transaction_object = Transaction.objects.create( from_wallet=None, to_wallet=Wallet.objects.get( associated_user=user_profile.user), type='CREDIT', amount=amount, default_currency=respons_dict['CURRENCY'], status=respons_dict["STATUS"], order_id=respons_dict["ORDERID"], external_transaction_flag=True, external_subscription_id=respons_dict["SUBS_ID"], external_transaction_id=respons_dict["TXNID"], bank_transaction_id=respons_dict["BANKTXNID"], transaction_date=respons_dict["TXNDATE"], gateway_name=respons_dict["GATEWAYNAME"], bank_name=respons_dict["BANKNAME"], payment_mode=respons_dict["PAYMENTMODE"], promo_camp_id=respons_dict["PROMO_CAMP_ID"], promo_status=respons_dict["PROMO_STATUS"], promo_response_code=respons_dict["PROMO_RESPCODE"]) else: transaction_object = Transaction.objects.create( from_wallet=None, to_wallet=Wallet.objects.get( associated_event=event), type='CREDIT', amount=amount, default_currency=respons_dict['CURRENCY'], status=respons_dict["STATUS"], order_id=respons_dict["ORDERID"], external_transaction_flag=True, external_subscription_id=respons_dict["SUBS_ID"], external_transaction_id=respons_dict["TXNID"], bank_transaction_id=respons_dict["BANKTXNID"], transaction_date=respons_dict["TXNDATE"], gateway_name=respons_dict["GATEWAYNAME"], bank_name=respons_dict["BANKNAME"], payment_mode=respons_dict["PAYMENTMODE"], promo_camp_id=respons_dict["PROMO_CAMP_ID"], promo_status=respons_dict["PROMO_STATUS"], promo_response_code=respons_dict["PROMO_RESPCODE"]) transaction_object.save() if request.session["transaction_type"] == "EVENT": members = event.members.all() admins = event.admin.all() workQueue = Queue.Queue(10) queueLock.acquire() for member in members: notification_message = "Your friend " + user_profile.first_name + " contributed " + str( amount.amount) + " to event " + event.name notification = Notification.objects.create_notification( notification_message, member, None) notification.save() serializer = NotificationSerializer(notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(member.id) }) for admin in admins: notification_message = "Your friend " + user_profile.first_name + " contributed " + str( amount.amount) + " to event " + event.name notification = Notification.objects.create_notification( notification_message, admin, None) notification.save() serializer = NotificationSerializer(notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(admin.id) }) queueLock.release() threads = [] for i in range(0, MAX_THREADS): thread = MultiThreading("WORKER " + str(i), workQueue) thread.start() threads.append(thread) while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 for t in threads: t.join() print "Sent all Notification" else: print "order unsuccessful because" + respons_dict['RESPMSG'] else: print "order unsuccessful because" + respons_dict['RESPMSG'] message["details"] = respons_dict['RESPMSG'] return HttpResponse(status=200, content_type="application/json", content=json.dumps(message))
from __future__ import unicode_literals from functools import partial from django.conf import settings import moneyed from djmoney.models.fields import MoneyField as _MoneyField MoneyField = partial( _MoneyField, max_digits=30, decimal_places=2, default=moneyed.Money('0.0', currency=settings.DEFAULT_CURRENCY), default_currency=settings.DEFAULT_CURRENCY )
from __future__ import unicode_literals from functools import partial import moneyed from djmoney.models.fields import MoneyField as _MoneyField from .settings import bazaar_settings MoneyField = partial(_MoneyField, max_digits=30, decimal_places=2, default=moneyed.Money(0.0, bazaar_settings.DEFAULT_CURRENCY), default_currency=bazaar_settings.DEFAULT_CURRENCY, currency_choices=bazaar_settings.CURRENCIES)
def post(self, request, access_token, *args, **kwargs): try: global exitFlag exitFlag = 0 user = BdayAppUser.objects.create_user() minimum_balance = moneyed.Money(0, 'INR') maximum_balance = moneyed.Money(100000, 'INR') wallet = Wallet.objects.create_wallet(minimum_balance, maximum_balance, 'U', 'INR', user, None) user_profile = UserProfile.objects.create_user_profile( access_token, request.data['profile_type'], user) serializer = UserProfileSerializer(user_profile) friends = user_profile.app_friends.all() total_number_of_friends = 0 workQueue = Queue.Queue(10) queueLock.acquire() for friend in friends: total_number_of_friends += 1 notification_message = "Your friend " + user_profile.first_name + " just joined BdayApp ! Gift him !!!" notification = Notification.objects.create_notification( notification_message, friend, None) notification.save() serializer = NotificationSerializer(notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(friend.id) }) queueLock.release() threads = [] for i in range(0, MAX_THREADS): thread = MultiThreading("WORKER " + str(i), workQueue) thread.start() threads.append(thread) while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 for t in threads: t.join() print "Sent all Notification" # conn = stomp.Connection([(STOMP_SERVER_URL, STOMP_PORT)]) # conn.start() # conn.connect('admin', 'password', wait=True) # conn.send(body=json.dumps(serializer.data), destination='/topic/notifications_' + str(friend.id)) # logger.info("Sending a message through apollo") # time.sleep(2) # logger.info("Message Sent.........Disconnecting") # conn.disconnect() # logger.info("Disconnected !!!") logger.info("Total friends" + str(total_number_of_friends)) if total_number_of_friends > 0: notification_message = "Your have" + str( total_number_of_friends) + " friends on Bdayapp. Kudos !!" notification = Notification.objects.create_notification( notification_message, user_profile.user, None) notification.save() serializer = NotificationSerializer(notification) conn = stomp.Connection([(STOMP_SERVER_URL, STOMP_PORT)]) conn.start() conn.connect(STOMP_ID, STOMP_PASSWORD, wait=True) conn.send(body=json.dumps(serializer.data), destination='/topic/notifications_' + str(user_profile.user.id)) logger.info("Sending a message through apollo") time.sleep(2) logger.info("Message Sent.........Disconnecting") conn.disconnect() logger.info("Disconnected !!!") return response.Response(serializer.data) except Exception as e: UserProfileView.handle_error(e)