def create(self, validated_data): consumptions_data_check = validated_data.get('withdraw_lines') tracks_data = validated_data.pop('withdraw_lines') transaction = Transaction.objects.create( types=1, created_user=self.context['request'].user, last_modified_users=self.context['request'].user, **validated_data) transaction.created_date = validated_data["date"] transaction.save() for track_data in tracks_data: withdraw_instance = WithdrawDetail.objects.create( transaction=transaction, created_user=self.context['request'].user, last_modified_users=self.context['request'].user, **track_data) withdraw_instance.created_date = validated_data["date"] withdraw_instance.save() if withdraw_instance != None: withdraw_stock(track_data, withdraw_instance, 1) if 'test' not in sys.argv: transaction_log_sync() return transaction
def create(self, validated_data): consumptions_data_check = validated_data.get('return_lines') tracks_data = validated_data.pop('return_lines') transaction = Transaction.objects.create(types=3, created_user=self.context['request'].user, last_modified_users=self.context['request'].user, **validated_data) transaction.created_date = validated_data["date"] transaction.save() for track_data in tracks_data: if track_data.get("array") != None: array = track_data.pop("array") else: array = None return_instance = ReturnDetail.objects.create(transaction=transaction, created_user=self.context['request'].user, last_modified_users=self.context['request'].user, **track_data) return_instance.created_date = validated_data["date"] return_instance.save() if return_instance != None: if array != None: withdraw_stock_withoutfifo(track_data, return_instance, 3, array) else: withdraw_stock(track_data, return_instance, 3) if 'test' not in sys.argv: transaction_log_sync() return transaction
def tradeOperation(request, *args, **kwargs): initParam = kwargs.get('initParam') transaction = kwargs.get('transaction') if transaction and request.method == 'POST': delivery = request.POST.get('delivery') if delivery and delivery == 'confirm_delivery': if transaction.status == 3: transaction.status = 4 transaction.end_time = datetime.datetime.now() transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.save() #Send email to seller and buyer notificationViews.closedTradeInform(transaction=transaction) return transaction else: initParam['error_msg'] = _('Transaction can not be confirmed delivery.') log.error(_('Transaction: %(param1)s, status: %(param2)s can not confirm delivery.') % {'param1': transaction.id, 'param2': transaction.status}) #TODO:if no complain, then increase credit point. #Increase seller and buyer credit point # point = common.getSystemParam(key='cp_closed_trade', default=50) # creditViews.increaseCreditPoint(user=transaction.buyer, point=point) # creditViews.increaseCreditPoint(user=transaction.seller, point=point) return None
def get_platform_wallet(): """ Returns the wallet used by the platform to transfer bitcoins to other wallets of the platform, or to receive bitcoins from profits. """ platform_user = get_platform_user() last_updated = timezone.now() platform_wallet, created = Wallet.objects.get_or_create( address=settings.PLATFORM_WALLET_ADDRESS, user=platform_user, defaults={ "address": settings.PLATFORM_WALLET_ADDRESS, "user": platform_user, "alias": "Platform Wallet", "last_updated": last_updated, }, ) # Add some BTCs transaction = Transaction( wallet_to=platform_wallet, transaction_type=Transaction.PLATFORM, amount=1000, details="Initial funds", created_at=last_updated, ) transaction.save() return platform_wallet
def initTransaction(request, *args, **kwargs): """Init transaction model data, when seller pay the service fee.""" app = kwargs.get('app') if app: transactions = models.Transaction.objects.filter(app_id=app.id, seller_id=request.user.id, is_active=True) if transactions: transaction = transactions[0] transaction.buyer = None transaction.price = None transaction.end_time = None transaction.buy_type = None transaction.seller_price = None transaction.appswalk_price = None transaction.gateway = None transaction.buyer_account = None transaction.seller_account = None transaction.appswalk_account = None transaction.pay_key = None else: transaction = models.Transaction() transaction.app = app transaction.seller = request.user transaction.is_active = True transaction.status = 1 transaction.save() return transaction
def create_recurring_exchanges(): messages = [] for repeat_period in ledger.RepeatPeriod.objects.filter(active=True): exchange = repeat_period.exchanges.order_by('-date').select_related()[0] transactions = exchange.transactions.all() while exchange.date + repeat_period.delta() <= datetime.date.today(): exchange.id = None exchange.date += repeat_period.delta() if exchange.date_due: exchange.date_due += repeat_period.delta() exchange.delivered = False exchange.save(force_insert=True) url_kwargs = { 'exchange_id': exchange.id, 'exchange_type_slug': exchange.type.slug, } messages.append('%s%s' % ( settings.APP_URL_BASE, reverse('edit_exchange', kwargs=url_kwargs), )) for transaction in transactions: transaction.id = None transaction.exchange = exchange transaction.date = exchange.date transaction.debit_reconciled = False transaction.credit_reconciled = False transaction.save(force_insert=True) if messages: messages.insert(0, 'created the following exchanges:') return messages
def on_commit(): instance = kwargs.get('instance') if instance: if instance.status == "Accepted": transaction_tag = "bank_payment_{id}".format(id=instance.id) if Transaction.objects.filter( identifiers__value=transaction_tag).exists(): transactions = Transaction.objects.filter( identifiers__value=transaction_tag) for tran in transactions: tran.delete() transaction = Transaction.objects.create( debit=True, pocket=instance.pocket, amount=instance.amount, datetime=datetime.now()) tag = UniqueIdentifier.objects.get_or_create( name="transaction_tag", value=transaction_tag)[0] transaction.identifiers.add(tag) instance.identifiers.add(tag) instance.transactions.add(transaction) elif instance.status in ["Declined", "Canceled"]: for transaction in instance.transactions.all(): transaction.active = False transaction.save()
def tradeOperation(request, *args, **kwargs): initParam = kwargs.get('initParam') transaction = kwargs.get('transaction') if transaction and request.method == 'POST': delivery = request.POST.get('delivery') if delivery and delivery == 'confirm_delivery': if transaction.status == 3: transaction.status = 4 transaction.end_time = datetime.datetime.now() transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.save() #Send email to seller and buyer notificationViews.closedTradeInform(transaction=transaction) return transaction else: initParam['error_msg'] = _( 'Transaction can not be confirmed delivery.') log.error( _('Transaction: %(param1)s, status: %(param2)s can not confirm delivery.' ) % { 'param1': transaction.id, 'param2': transaction.status }) #TODO:if no complain, then increase credit point. #Increase seller and buyer credit point # point = common.getSystemParam(key='cp_closed_trade', default=50) # creditViews.increaseCreditPoint(user=transaction.buyer, point=point) # creditViews.increaseCreditPoint(user=transaction.seller, point=point) return None
def closedTrade(request, *args, **kwargs): """Need update end_time to now.""" initParam = {} transaction = get_object_or_404(models.Transaction, pk=kwargs.get('txn_id'), buyer_id=kwargs.get('buyer_id'), is_active=True) transaction.status = 4 transaction.end_date = datetime.datetime.now() transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.save() #Increase seller and buyer credit point point = common.getSystemParam(key='cp_closed_trade', default=50) creditViews.increaseCreditPoint(user=transaction.buyer, point=point) creditViews.increaseCreditPoint(user=transaction.seller, point=point) #Send email to seller and buyer notificationViews.closedTradeInform(transaction=transaction) initParam['transaction'] = transaction return render_to_response('transaction/trade_action.html', initParam, context_instance=RequestContext(request))
def CreateDebit(user, fromAccountNumber, amount): print("Do Debit Here") try: amount = int(amount.strip()) fromAccountNumber = int(fromAccountNumber.strip()) except: raise SecureBankException( 'Error in format of account number/amount') if (amount <= 0): raise SecureBankException('Negative Ammount') fromAccount = Account.objects.filter(AccountNumber=fromAccountNumber) if len(fromAccount) == 0: raise SecureBankException("Account belongs to someone else") fromAccount = fromAccount[0] if fromAccount.AccountHolder.user.username != user.username: raise SecureBankException("Trying to access someones else account") if fromAccount.Balance < amount: raise SecureBankException("Insufficient Funds") #STATUS as O - OTP transaction = Transaction(FromAccount=fromAccount, ToAccount=None, Amount=amount, Status='O', Type='D') #fromAccount.Debit(amount) transaction.save() print("Done") return transaction
def post(self, request, pk): caterer = get_object_or_404(Caterer, pk=pk) consumer = get_object_or_404(Consumer, pk=self.request.user.catruser.id) try: transaction = consumer.history.transaction_set\ .exclude(tray__exact=None)\ .get(caterer_id=caterer.id) except (KeyError, Transaction.DoesNotExist): transaction = Transaction(transaction_date=timezone.now()) tray = Tray(tray_cumulative_price=0, created_date=timezone.now()) tray.save() transaction.transaction_is_completed = False transaction.tray = tray transaction.history = consumer.history transaction.caterer = caterer transaction.save() tray = transaction.tray # find the key that matches an integer, which should be the menu_id for key in request.POST: if re.match("^[0-9]+$", key): try: menu_id = int(key) queried_menu_item = get_object_or_404(Menu, pk=menu_id) pass except (KeyError, Menu): return render( request, 'orders/book.html', { 'menu': Menu.objects.filter(caterer_id=caterer.id), 'packages': [ menu.package for menu in caterer.menu_set.distinct('package') ], 'item_set': tray.item_set.all(), 'tray': tray }) else: item = Item() item.menu = queried_menu_item tray.tray_cumulative_price += Decimal(request.POST[key + 'x']) tray.save() item.tray = tray item.item_quantity = request.POST[key + 'z'] # logger.error(tray) # logger.error(item.tray) item.save() # logger.error(item.tray.tray_cumulative_price) return redirect(reverse('orders:book', args=(pk, )))
def awaiting_deposit(self, request, pk=None, deposit_pk=None, **kwargs): """ Gets or updates awaiting deposit by id. """ goal = self.get_object() sr_id = SupportRequest.get_current(request) try: transaction = Transaction.objects.get( Q(pk=deposit_pk), Q(status=Transaction.STATUS_AWAITING_APPROVAL), Q(to_goal=goal)) except ObjectDoesNotExist: raise ValidationError( 'Can not find specified awaiting one-time deposit') if request.method == 'GET': serializer = serializers.TransactionSerializer(transaction) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_200_OK, headers=headers) elif request.method == 'PUT': client = goal.account.primary_owner site = get_current_site(request) serializer = serializers.TransactionSerializer(transaction, data=request.data) serializer.is_valid(raise_exception=True) if site.config().plaid_enabled: # make sure user has connected a plaid_user target_user = client.user plaid_user = getattr(target_user, 'plaid_user', False) if not plaid_user: logger.error( 'Deposit attempted by %s but no plaid_user found' % request.user) raise ValidationError('Client has no plaid_user linked') if not serializer.validated_data.get('account_id', False): logger.error( 'No plaid account_id sent with deposit request') raise ValidationError( 'No plaid account_id sent with deposit request') transaction = serializer.save() transaction.save() # TODO: Check whether other event log type is required for deposit update Event.GOAL_DEPOSIT.log('{} {}'.format(request.method, request.path), request.data, user=request.user, obj=goal, support_request_id=sr_id) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_200_OK, headers=headers)
def post(self, request, _id): user = request.yoo["user"] ticket = LotteryTicket.objects.get(pk=_id) if ticket.user != user: raise exceptions.WebServiceAuthorizationFailed() try: data = json.loads(request.body) except: data = {} type = data.get("type", None) if type not in ["facebook", "twitter"]: raise exceptions.WebServiceException("Unsupported Share Type") if not ticket.coin_share_transaction.filter(type=type).exists(): parent = CoinTransaction(wallet=user.get_wallet()) parent.save() transaction = CoinShareTransaction(ticket=ticket, type=type, transaction=parent) transaction.save() parent.amount = transaction.amount parent.save() return self.get(request, _id)
def _handle_error(cls, transaction, message): transaction.status_message = message transaction.status = Transaction.STATUS.error transaction.pending_execution_attempt = False transaction.save() logger.error(transaction.status_message) maybe_make_callback(transaction)
def transaction_detail(request, id): transaction = Transactions.objects.filter(id=id).first() alert = False if request.POST: comments = request.POST.get("comments") transaction.comments = comments transaction.save() alert = True account = 'GS' if transaction.vendor == GS else 'SSB' total = transaction.total trader_total = transaction.trader_total exception = abs(total - trader_total) status = 'matched' if trader_total == total else 'not matched' status_class = 'matched-transaction' if trader_total == total else 'unmatched-transaction' date = transaction.date idx = transaction.id comments = transaction.comments or '' return render( request, "transactiondetail.html", { 'account': account, 'total': total, 'trader_total': trader_total, 'exception': exception, 'status': status, 'date': date, 'status_class': status_class, 'idx': idx, 'comments': comments, 'alert': alert })
def initTransaction(request, *args, **kwargs): """Init transaction model data, when seller pay the service fee.""" app = kwargs.get('app') if app: transactions = models.Transaction.objects.filter( app_id=app.id, seller_id=request.user.id, is_active=True) if transactions: transaction = transactions[0] transaction.buyer = None transaction.price = None transaction.end_time = None transaction.buy_type = None transaction.seller_price = None transaction.appswalk_price = None transaction.gateway = None transaction.buyer_account = None transaction.seller_account = None transaction.appswalk_account = None transaction.pay_key = None else: transaction = models.Transaction() transaction.app = app transaction.seller = request.user transaction.is_active = True transaction.status = 1 transaction.save() return transaction
def _update_decision(self, order, transaction, update): elems = update.xpath("*[local-name()='NewDecision']") if len(elems) <= 0: return new_decision = elems[0].text elems = update.xpath("*[local-name()='Reviewer']") reviewer = elems[0].text if len(elems) else '' elems = update.xpath("*[local-name()='ReviewerComments']") comments = elems[0].text if len(elems) else '' note = OrderNote() note.order = order note.note_type = OrderNote.SYSTEM note.message = '[Decision Manager] %s changed decision from %s to %s.\n\nComments: %s' % ( reviewer, transaction.status, new_decision, comments) note.save() if new_decision != DECISION_ACCEPT: order.status = ORDER_STATUS_PAYMENT_DECLINED order.save() transaction.status = new_decision transaction.save()
def Create(user, fromAccountNumber, toAccountNumber, amount): print("create") try: amount = int(amount.strip()) fromAccountNumber = int(fromAccountNumber.strip()) toAccountNumber = int(toAccountNumber.strip()) except: raise SecureBankException( 'Error in format of account number/amount') if (amount <= 0): raise SecureBankException('Negative Ammount') fromAccount = Account.objects.filter(AccountNumber=fromAccountNumber) if len(fromAccount) == 0: raise SecureBankException("Account belongs to someone else") fromAccount = fromAccount[0] if fromAccount.AccountHolder.user.username != user.username: raise SecureBankException("Trying to access someones else account") if fromAccount.Balance < amount: raise SecureBankException("Insufficient Funds") toAccount = Account.objects.filter(AccountNumber=toAccountNumber) if len(toAccount) == 0: raise SecureBankException('Cannot send to this account') toAccount = toAccount[0] if fromAccount.AccountNumber == toAccount.AccountNumber: raise SecureBankException("Cannot transfer to same account") transaction = Transaction(FromAccount=fromAccount, ToAccount=toAccount, Amount=amount, Status='O', Type='T') print("Done") transaction.save() return transaction
def _record_payment(self, order, token, request, reply_log_entry): source_type, created = SourceType.objects.get_or_create(name=settings.SOURCE_TYPE) source, created = Source.objects.get_or_create(order=order, source_type=source_type) source.currency = request.data.get('req_currency') source.amount_allocated += Decimal(request.data.get('auth_amount', '0')) source.save() transaction = Transaction() transaction.log = reply_log_entry transaction.source = source transaction.token = token transaction.txn_type = Transaction.AUTHORISE transaction.amount = request.data.get('req_amount', 0) transaction.reference = request.data.get('transaction_id') transaction.status = request.data.get('decision') transaction.request_token = request.data.get('request_token') transaction.processed_datetime = datetime.strptime(request.data.get('signed_date_time'), settings.DATE_FORMAT) transaction.save() event = PaymentEvent() event.order = order event.amount = request.data.get('auth_amount', 0) event.reference = request.data.get('transaction_id') event.event_type = PaymentEventType.objects.get_or_create(name=Transaction.AUTHORISE)[0] event.save() for line in order.lines.all(): line_event = PaymentEventQuantity() line_event.event = event line_event.line = line line_event.quantity = line.quantity line_event.save() return transaction
def edit_transaction(request, id=None): """ Create or edit a transaction. """ transaction = id and get_object_or_404( Transaction, pk=id, user=request.user) if request.method == 'POST': form = EditTransactionForm(request.user, instance=transaction, data=request.POST) if form.is_valid(): transaction = form.save(commit=False) transaction.user = request.user transaction.save() form.save_m2m() return redirect(transaction) else: initial = {} if not transaction: initial['account'] = request.GET.get('account', None) initial['date'] = now() form = EditTransactionForm(request.user, instance=transaction, initial=initial) return render( request, 'pages/form.html', { 'title': "{} Transaction".format("Edit" if transaction else "New"), 'breadcrumbs': [transaction.account, transaction] if transaction else [], 'form': form, })
def correct_transaction(self, transaction, update) -> None: FIELDS_ALLOWED_FOR_UPDATE = set([ "executed_at", "quantity", "price", "local_value", "transaction_costs", "value_in_account_currency", "total_in_account_currency", ]) for field in update.keys(): if field not in FIELDS_ALLOWED_FOR_UPDATE: raise ValueError( f"Correcting transaction with incorrect arguments," f"field: '{field}' not allowed ") position = transaction.position account = position.account position.quantity -= transaction.quantity account.balance -= transaction.total_in_account_currency for attr, value in update.items(): setattr(transaction, attr, value) position.quantity += transaction.quantity account.balance += transaction.total_in_account_currency position.save() account.save() transaction.save() gains.update_lots(position) position.quantity_history.cache_clear() position.value_history.cache_clear()
def unlink(request, id, id2): """ Unlink a transaction """ transaction = get_object_or_404(Transaction, pk=id, user=request.user) transaction2 = get_object_or_404(Transaction, pk=id2, user=request.user) if request.method == 'POST': form = DeleteForm(data=request.POST) if form.is_valid(): transaction.links.remove(transaction2) transaction.save() return redirect(transaction) else: form = DeleteForm() return render( request, 'pages/delete.html', { 'title': "Unlink Transaction", 'description': "You are about to unlink {}. Links will be removed in both directions." .format(transaction2), 'breadcrumbs': [transaction.account, transaction], 'form': form, })
def execBuy(request, context=None): #obj=stocks.objects.get(name=request.POST['choice']) buyer_user = User.objects.get(username=request.user) stockname,owner_username=request.POST['choice'].split() owner_user = getProfile2(owner_username).user startup_Profile=StartupProfile.objects.get(stockName=stockname) qtypurchase=float(request.POST['qty'+request.POST.get('choice')]) if not isInvestor(buyer_user): raise Exception('You must be Investor') owner_onsale = onsale.objects.get(owner__username=owner_username, startup__stockName=stockname) try: owner_onsale=onsale.objects.get(owner__username=owner_username,startup__stockName=stockname) qtyonsale=owner_onsale.stockpercentage print 'raman' if qtyonsale is None: raise Exception('yo') typeOwner=isInvestor(owner_username) except: raise Exception("Not on sale") print(qtyonsale) print(qtypurchase) if qtyonsale<qtypurchase: raise Exception if qtypurchase<0: raise Exception ownerProfile=getProfile(owner_user) buyerProfile=getProfile(buyer_user) if ownerProfile is None: raise Exception if buyerProfile is None: raise Exception try: buyer_ownership=ownership.objects.get(owner=buyer_user,startup=startup_Profile) except: buyer_ownership=ownership() buyer_ownership.owner=buyer_user buyer_ownership.startup=startup_Profile buyer_ownership.sharepercentage=0 owner_ownership=ownership.objects.get(owner=owner_user,startup=startup_Profile) buyer_ownership.sharepercentage=buyer_ownership.sharepercentage+qtypurchase owner_onsale.stockpercentage=owner_onsale.stockpercentage-qtypurchase owner_ownership.sharepercentage = owner_ownership.sharepercentage - qtypurchase buyer_ownership.save() print(buyer_ownership.sharepercentage) owner_ownership.save() owner_onsale.save() if(owner_onsale.stockpercentage==0): owner_onsale.delete() if (owner_ownership.sharepercentage == 0): owner_ownership.delete() transaction=transactions(owner=owner_user,buyer=buyer_user,stockpercentage=qtypurchase,stockprice=owner_onsale.stockprice,timestamp=datetime.now(),startup=startup_Profile) transaction.save() return redirect('/investor/')#render(request,'market/index.html',context)
def unlink(request, id): """ Unlink a transaction """ transaction = get_object_or_404(Transaction, pk=id, user=request.user) transaction.linked = None transaction.save() return redirect(transaction)
def form_valid(self, form): transaction = self.get_transaction() transaction.save() self.object = form.save(commit=False) self.object.update_type = UpdateType.CREATE self.object.transaction = transaction self.object.save() return super().form_valid(form)
def execute_deposits(cls): module = sys.modules[__name__] try: ready_transactions = PendingDeposits.get_ready_deposits() except Exception: logger.exception( "poll_pending_deposits() threw an unexpected exception") return for i, transaction in enumerate(ready_transactions): if module.TERMINATE: still_processing_transactions = ready_transactions[i:] Transaction.objects.filter( id__in=[t.id for t in still_processing_transactions]).update( pending_execution_attempt=False) break cls.execute_deposit(transaction) with django.db.transaction.atomic(): multisig_transactions = list( Transaction.objects.filter( kind=Transaction.KIND.deposit, status=Transaction.STATUS.pending_anchor, pending_signatures=False, pending_execution_attempt=False, ).select_for_update()) Transaction.objects.filter( id__in=[t.id for t in multisig_transactions]).update( pending_execution_attempt=True) for i, transaction in enumerate(multisig_transactions): if module.TERMINATE: still_processing_transactions = ready_transactions[i:] Transaction.objects.filter( id__in=[t.id for t in still_processing_transactions]).update( pending_execution_attempt=False) break try: success = PendingDeposits.submit(transaction) except Exception as e: logger.exception("submit() threw an unexpected exception") transaction.status_message = str(e) transaction.status = Transaction.STATUS.error transaction.pending_execution_attempt = False transaction.save() maybe_make_callback(transaction) continue if success: transaction.refresh_from_db() try: rdi.after_deposit(transaction) except Exception: logger.exception( "after_deposit() threw an unexpected exception")
def executeOnePriceBuy(*args, **kwargs): """The operation of one price buy, after buyer payed successfully.""" initParam = kwargs.get('initParam') transaction = initParam.get('transaction') if transaction: transaction.status = 3 transaction.is_active = True txn_expiry_date = string.atoi( common.getSystemParam(key='txn_expiry_date', default=15)) transaction.end_time = datetime.datetime.now() + datetime.timedelta( days=txn_expiry_date) transaction.buyer_account = initParam.get('buyer_account') acceptGateways = paymentModels.AcceptGateway.objects.filter( user_id=transaction.seller.id, type_id=transaction.gateway.id, is_active=True) transaction.seller_account = acceptGateways[0].value transaction.appswalk_account = settings.APPSWALK_ACCOUNT txn_fee_pct = string.atof( common.getSystemParam(key='txn_fee_pct', default=0.01)) transaction.appswalk_price = transaction.price * txn_fee_pct transaction.seller_price = transaction.price * (1 - txn_fee_pct) transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buyer_account = transaction.buyer_account transactionsLog.seller_account = transaction.seller_account transactionsLog.appswalk_account = transaction.appswalk_account transactionsLog.gateway = transaction.gateway transactionsLog.appswalk_price = transaction.appswalk_price transactionsLog.seller_price = transaction.seller_price transactionsLog.pay_key = transaction.pay_key transactionsLog.save() #Update app status and end_date. app = transaction.app if app.status == 2: app.status = 3 app.end_date = datetime.datetime.now() app.save() #Send email to seller notificationViews.onePriceBuyInformSellerEmail(transaction=transaction) log.info( _('The transaction of one price buy with id %(param1)s is payed by %(param2)s.' ) % { 'param1': transaction.id, 'param2': transaction.buyer.username }) return transaction return None
def _log_failed_mop_payment(self,message,token,communication_successful): transaction = Transaction( communication_successful = communication_successful, payment_successful = False, meal = self, gateway = 's', token = token, json_result = message ) transaction.save()
def post(self, request): transaction = UnconfirmedTransactionSerializer(data=request.data) transaction.is_valid(raise_exception=True) transaction.save() # Mine a block if we have at least 10 transaction waiting if UnconfirmedTransaction.objects.count() >= 10: logger.info('At least 10 transactions waiting, mining new block.') mine_block() return Response()
def make_transaction(self,from_user, to_user, amount, reason): status = False if from_user.amount >= amount: from_user.amount -= amount to_user.amount += amount from_user.save() to_user.save() status = True transaction = Transaction(from_user=from_user.user, to_user=to_user.user, amount=amount, success=status, reason=reason) transaction.save() return transaction, status
def make_transaction(request, amount): customer = Customer.objects.get(pk=request.user.id) customer.credit += amount transaction = Transaction() transaction.value = amount transaction.state = "D" transaction.transactions_type = "RCH" transaction.creator = customer customer.save() transaction.save() return transaction
def make_transaction(self,from_user, to_hotel, amount, reason): status = False if from_user.wallet >= amount: from_user.wallet -= amount to_hotel.wallet += amount from_user.save() to_hotel.save() status = True transaction = Transaction(from_user=from_user.user, to_hotel=to_hotel, amount=amount, success=status, reason=reason) transaction.save() self.send_email(transaction) return transaction, status
def _log_successful_mop_payment(self,token,charge): transaction = Transaction( communication_successful = True, payment_successful = charge.paid, meal = self, amount = charge.amount, currency = charge.currency, gateway = 's', token = token, json_result = json.dumps(charge) ) transaction.save()
def transaction_view(request): user = request.user profile = Profile.objects.get(user=user) accounts = Account.objects.filter(account_user_fk=profile) # @transaction.atomic # Logic to get the balance from the current usery context = { "accounts": accounts, } if request.method == 'POST': account_sender = request.POST['account_number_sender'] account_selected = Account.objects.get(account_number=account_sender) print(account_selected) receiver = request.POST['receiver'] amount = request.POST['amount'] if amount.isdigit(): amount = int(amount) if account_selected.account_balance >= amount: transaction = Transaction() unique_id = get_random_string(length=20) # Getting the account data from the receiver transaction.transaction_account_number_sender = account_selected.account_number #should be autogenerate, check UUID transaction.transaction_user_account_fk = account_selected transaction.transaction_id = unique_id transaction.transaction_account_number_receiver = receiver try: receiver_ = Account.objects.get(account_number=receiver) transaction.transaction_amount = amount transaction.transaction_currency = 'DKK' balance_sender = account_selected.account_balance - amount account_selected.account_balance = balance_sender receiver_.account_balance = receiver_.account_balance + amount receiver_.save() account_selected.save() transaction.save() print('the balance of the sender is: ', balance_sender) return HttpResponseRedirect('/transaction/confirmation/') except Account.DoesNotExist: context = {'error': 'error', "accounts": accounts} return render(request, 'transaction_app/transaction.html', context) else: #Should print some error message in the frontend, maybe with the if operator print("you don't have enough money") else: print('please enter a valid amount') return render(request, 'transaction_app/transaction.html', context)
def init_transaction(self, wallet_id_from, wallet_id_to, amount, message): # TODO: There are should be currency conversion (ignored for now) # or restricted transactions between wallets in different curencies try: sender_wallet = self.wallet_set.get(wallet_id=wallet_id_from) except Wallet.DoesNotExist: logger.log(f'Wallet {wallet_id_from} is not your wallet!') raise else: system_wallet = Wallet.objects.get( account__user__is_superuser=True, currency=sender_wallet.currency) try: reciever_wallet = Wallet.objects.get(wallet_id=wallet_id_to) except Wallet.DoesNotExist: logger.log(f'Wallet {wallet_id_to} or ' f'{wallet_id_from} doesn`t exist!') raise else: transaction = fee = None if self == reciever_wallet.account: # no fee fee_amount = 0.0 else: fee_amount = amount * settings.SYSTEM_FEE if sender_wallet.money >= amount + fee_amount: fee = Transaction(from_wallet=sender_wallet, to_wallet=system_wallet, message=f'fee for ' f'{sender_wallet.account}', amount=fee_amount) fee.save() if sender_wallet.money >= amount + fee_amount: transaction = Transaction(from_wallet=sender_wallet, to_wallet=reciever_wallet, fee=fee, message=message, amount=amount) transaction.save() else: error_message = f'You have not enough money in ' \ f'{wallet_id_from}.' logger.error(error_message) raise NotEnoughMoneyError(error_message) sender_wallet.money -= amount + fee_amount reciever_wallet.money += amount system_wallet.money += fee_amount Wallet.objects.bulk_update( [sender_wallet, reciever_wallet, system_wallet], fields=['money']) return transaction
def request(self, source, destination, with_taxes, amount): transaction = self.model( source=source, destination=destination, status=constants.PaymentTransactionStatus.SCHEDULED, amount=amount, currency=destination.currency, with_taxes=with_taxes, ) if settings.IMMEDIATELY_RATE: transaction.set_rate_and_taxes() transaction.save() return transaction
def get_ready_deposits(cls) -> List[Transaction]: pending_deposits = Transaction.objects.filter( status__in=[ Transaction.STATUS.pending_user_transfer_start, Transaction.STATUS.pending_external, ], kind=Transaction.KIND.deposit, pending_execution_attempt=False, ).select_for_update() with django.db.transaction.atomic(): ready_transactions = rri.poll_pending_deposits(pending_deposits) Transaction.objects.filter( id__in=[t.id for t in ready_transactions]).update( pending_execution_attempt=True) verified_ready_transactions = [] for transaction in ready_transactions: # refresh from DB to pull pending_execution_attempt value and to ensure invalid # values were not assigned to the transaction in rri.poll_pending_deposits() transaction.refresh_from_db() if transaction.kind != transaction.KIND.deposit: cls.handle_error( transaction, "poll_pending_deposits() returned a non-deposit transaction", ) continue if transaction.amount_in is None: cls.handle_error( transaction, "poll_pending_deposits() did not assign a value to the " "amount_in field of a Transaction object returned", ) continue elif transaction.amount_fee is None: if registered_fee_func is calculate_fee: try: transaction.amount_fee = calculate_fee({ "amount": transaction.amount_in, "operation": settings.OPERATION_DEPOSIT, "asset_code": transaction.asset.code, }) except ValueError as e: cls.handle_error(transaction, str(e)) continue else: transaction.amount_fee = Decimal(0) transaction.save() verified_ready_transactions.append(transaction) return verified_ready_transactions
def do_transactions(request, amount, type): manager = Manager.objects.get(pk=10) customer = Customer.objects.get(pk=request.user) customer.credit -= amount manager.credit += amount customer.save() manager.save() transaction = Transaction() transaction. value = amount transaction.creator = customer transaction.state ='W' transaction.transactions_type=type transaction.save() request.session['trans_id']= transaction.id
def executeOnePriceBuy(*args, **kwargs): """The operation of one price buy, after buyer payed successfully.""" initParam = kwargs.get('initParam') transaction = initParam.get('transaction') if transaction: transaction.status = 3 transaction.is_active = True txn_expiry_date = string.atoi(common.getSystemParam(key='txn_expiry_date', default=15)) transaction.end_time = datetime.datetime.now() + datetime.timedelta(days=txn_expiry_date) transaction.buyer_account = initParam.get('buyer_account') acceptGateways = paymentModels.AcceptGateway.objects.filter(user_id=transaction.seller.id, type_id=transaction.gateway.id, is_active=True) transaction.seller_account = acceptGateways[0].value transaction.appswalk_account = settings.APPSWALK_ACCOUNT txn_fee_pct = string.atof(common.getSystemParam(key='txn_fee_pct', default=0.01)) transaction.appswalk_price = transaction.price * txn_fee_pct transaction.seller_price = transaction.price * (1 - txn_fee_pct) transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buyer_account = transaction.buyer_account transactionsLog.seller_account = transaction.seller_account transactionsLog.appswalk_account = transaction.appswalk_account transactionsLog.gateway = transaction.gateway transactionsLog.appswalk_price = transaction.appswalk_price transactionsLog.seller_price = transaction.seller_price transactionsLog.pay_key = transaction.pay_key transactionsLog.save() #Update app status and end_date. app = transaction.app if app.status == 2: app.status = 3 app.end_date = datetime.datetime.now() app.save() #Send email to seller notificationViews.onePriceBuyInformSellerEmail(transaction=transaction) log.info(_('The transaction of one price buy with id %(param1)s is payed by %(param2)s.') % {'param1': transaction.id, 'param2': transaction.buyer.username}) return transaction return None
def person_merge(person_from, person_to): """ Merge two people into one Move all related items from person_from to person_to Then delete person_to and their address record """ person_reassign_records(person_from, person_to) for sub in person_from.subscription_set.all(): sub.person_member = person_to sub.save() # if person_from.sub and not person_to.sub: # person_to.sub = person_from.sub # if person_from.auth and not person_to.auth: # person_to.auth = person_from.auth # if person_from.cardless_id and not person_to.cardless_id: # person_to.cardless_id = person_from.cardless_id for invitem in person_from.invoiceitem_set.all(): invitem.person = person_to invitem.save() for application in person_from.adultapplication_set.all(): application.person = person_to application.save() for group in person_from.groups.all(): person_from.groups.remove(group) person_to.groups.add(group) person_from.save() person_to.save() for transaction in person_from.transaction_set.all(): transaction.person = person_to transaction.save() for entry in person_from.visitorbook_set.all(): entry.person = person_to entry.save() for entry in person_from.participant_set.all(): entry.person = person_to entry.save() for entry in person_from.waitinglist_set.all(): entry.person = person_to entry.save() for field in ('sub', 'auth', 'cardless_id'): _move_field(field, person_from, person_to) person_from.save() person_to.save()
def duplicate_exchange(request, exchange_id): exchange = get_object_or_404(ledger.Exchange, pk=exchange_id, editor=request.user) transactions = exchange.transactions.filter(editor=request.user) exchange.id = None exchange.memo = "Copy of %s" % (exchange.memo) exchange.delivered = False exchange.save(force_insert=True) for transaction in transactions: transaction.id = None transaction.memo = "Copy of %s" % (transaction.memo) transaction.exchange = exchange transaction.debit_reconciled = False transaction.credit_reconciled = False transaction.save(force_insert=True) if request.GET["next"]: return HttpResponseRedirect(request.GET["next"]) else: return HttpResponseRedirect(reverse("list_exchanges"))
def new_transaction(request, transaction_key): if request.method == 'POST': form = TransactionForm(request.POST, auto_id='transaction-%s') if form.is_valid(): transaction = form.save(commit=False) transaction.staff_member = request.user transaction.save() now = transaction.timestamp periods = transaction.catalog.periods.all() assets_in_ids = request.POST.getlist('asset_in') assets_in = Asset.objects.in_bulk(assets_in_ids) for asset_id, asset in assets_in.iteritems(): reservation = asset.get_current_reservation() if reservation: reservation.transaction_in = transaction reservation.save() else: print 'No current reservation' renew_ids = request.POST.getlist('renew') assets_out_ids = renew_ids + request.POST.getlist('asset_out') assets_out = Asset.objects.in_bulk(assets_out_ids) custom_due_date = form.cleaned_data['due_date'] for asset_id, asset in assets_out.iteritems(): if custom_due_date: due_date = custom_due_date else: duration = asset.get_reservation_duration() due_date = duration and duration.get_due_date(now, periods) try: transaction.reservations_out.create(asset=asset, due_date=due_date) except Exception: raise print 'Redirecting...' return redirect('reservations:receipt', transaction.pk) else: print 'Transaction failed' return redirect('reservations:scan')
def reconcile_transaction(request): value = False reconciled_balance = "0.0" errors = [] if request.POST: form = ledger_forms.ReconcileTransactionForm(request.POST) if form.is_valid(): try: transaction = form.cleaned_data["transaction"] account = form.cleaned_data["account"] value = not getattr(transaction, "%s_reconciled" % account) setattr(transaction, "%s_reconciled" % account, value) transaction.save() account_id = getattr(transaction, "%s_id" % account) account = ledger.Account.objects.get(pk=account_id, editor=request.user) to_date = form.cleaned_data["to_date"] reconciled_balance = "%.2f" % account.reconciled_balance(to_date=to_date) except Exception, e: errors.append("%s: %s" % (type(e).__name__, e.message)) else: for k, v in form.errors.iteritems(): errors.append("%s: %s" % (k, v))
def edit_transaction(request, id=None): """ Create or edit a transaction. """ transaction = id and get_object_or_404(Transaction, pk=id, user=request.user) if request.method == 'POST': form = EditTransactionForm(request.user, instance=transaction, data=request.POST) if form.is_valid(): transaction = form.save(commit=False) transaction.user = request.user transaction.save() form.save_m2m() return redirect(transaction) else: initial = {} if not transaction: initial['account'] = request.GET.get('account', None) initial['date'] = now() form = EditTransactionForm(request.user, instance=transaction, initial=initial) return render(request, 'pages/form.html', { 'title': "{} Transaction".format("Edit" if transaction else "New"), 'breadcrumbs': [transaction.account, transaction] if transaction else [], 'form': form, })
def confirm_trans_record(trans_record): """Confirm a transaction record.""" # Build and save matching record confirm_record = models.TransactionRecord( creator_person=trans_record.target_person, target_person=trans_record.creator_person, from_receiver=not trans_record.from_receiver, currency=trans_record.currency, transaction_time=trans_record.transaction_time, value=trans_record.value ) transaction = models.Transaction() transaction.save() confirm_record.transaction_id = trans_record.transaction_id = transaction.id confirm_record.save() trans_record.save() # Update the balance, or create a new one update_balance( trans_record, trans_record.provider, trans_record.receiver )
def onePriceBuy(request, *args, **kwargs): """ Buyer pay by clicking button 'Buy It Now with 10 USD' in app detail page. Note: url include app_id, and publisher_id, because of preventing user to cheat. """ initParam = {} app_id = kwargs.get('app_id') publisher_id = kwargs.get('publisher_id') app = get_object_or_404(appModels.App, pk=app_id, publisher_id=publisher_id, status=2) transactions = models.Transaction.objects.filter(app_id=app.id, seller_id=publisher_id, buyer_id=request.user.id, status=1) if transactions: transaction = transactions[0] else: transaction = models.Transaction() transaction.app = app transaction.seller = app.publisher transaction.status = 1 transaction.is_active = False transaction.buyer = request.user transaction.price = app.one_price transaction.buy_type = 1 paid_expiry_date = string.atoi(common.getSystemParam(key='paid_expiry_date', default=7)) transaction.end_time = datetime.datetime.now() + datetime.timedelta(days=paid_expiry_date) transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buy_type = transaction.buy_type transactionsLog.save() initParam['transaction'] = transaction initParam['page_source'] = 'one-price' if transaction.end_time > datetime.datetime.now(): initParam['time_remaining'] = time.mktime(time.strptime(transaction.end_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) else: initParam['time_remaining'] = "Deal Closed" initParam['paid_expiry'] = True if request.method == 'POST': #Buyer credit point judge for bidding. min_cp = common.getSystemParam(key='min_cp_for_bid', default=50) cp = creditViews.getUserCreditPoint(user=request.user) if cp == -1 or cp < string.atoi(min_cp): initParam['error_msg'] = _('You are not allowed to buy, because your credit points is too low.') else: #Buyser pay for app. txn_fee_pct = string.atof(common.getSystemParam(key='txn_fee_pct', default=0.01)) initParam['currency'] = app.currency.currency initParam['appsWalk_account'] = settings.APPSWALK_ACCOUNT initParam['gateway'] = 'paypal' gateways = paymentModels.Gateway.objects.filter(name__iexact=initParam.get('gateway')) acceptGateways = paymentModels.AcceptGateway.objects.filter(user_id=transaction.seller.id, type_id=gateways[0].id, is_active=True) initParam['seller_account'] = acceptGateways[0].value initParam['appsWalk_amount'] = app.one_price * txn_fee_pct initParam['seller_amount'] = app.one_price * (1 - txn_fee_pct) initParam['txn_id'] = transaction.id #The needed operation method in pay. initParam['executeMethod'] = updateTransaction #The back page, when pay has error. if request.session.get('back_page', None): del request.session['back_page'] if request.session.get('back_page_msg', None): del request.session['back_page_msg'] request.session['back_page'] = '/'.join([common.getHttpHeader(request), 'query/app-detail', str(app.id)]) request.session['back_page_msg'] = 'App Detail' #The success return page, when pay finish. if request.session.get('success_page', None): del request.session['success_page'] if request.session.get('success_page_msg', None): del request.session['success_page_msg'] request.session['success_page'] = '/'.join([common.getHttpHeader(request), 'transaction/trade-action/buy', str(app.id), str(request.user.id)]) request.session['success_page_msg'] = 'Trade Action' return paymentViews.pay(request, initParam=initParam) return render_to_response('transaction/one_price_buy.html', initParam, context_instance=RequestContext(request))
def insert_new_fpds(self, to_insert, total_rows): place_of_performance_field_map = { "location_country_code": "place_of_perform_country_c", "country_name": "place_of_perf_country_desc", "state_code": "place_of_performance_state", "state_name": "place_of_perfor_state_desc", "city_name": "place_of_perform_city_name", "county_name": "place_of_perform_county_na", "county_code": "place_of_perform_county_co", "zip_4a": "place_of_performance_zip4a", "congressional_code": "place_of_performance_congr", "zip_last4": "place_of_perform_zip_last4", "zip5": "place_of_performance_zip5", } legal_entity_location_field_map = { "location_country_code": "legal_entity_country_code", "country_name": "legal_entity_country_name", "state_code": "legal_entity_state_code", "state_name": "legal_entity_state_descrip", "city_name": "legal_entity_city_name", "county_name": "legal_entity_county_name", "county_code": "legal_entity_county_code", "address_line1": "legal_entity_address_line1", "address_line2": "legal_entity_address_line2", "address_line3": "legal_entity_address_line3", "zip4": "legal_entity_zip4", "congressional_code": "legal_entity_congressional", "zip_last4": "legal_entity_zip_last4", "zip5": "legal_entity_zip5", } for index, row in enumerate(to_insert, 1): upper_case_dict_values(row) # Create new LegalEntityLocation and LegalEntity from the row data legal_entity_location = create_location( legal_entity_location_field_map, row, {"recipient_flag": True, "is_fpds": True} ) recipient_name = row["awardee_or_recipient_legal"] legal_entity = LegalEntity.objects.create( recipient_unique_id=row["awardee_or_recipient_uniqu"], recipient_name=recipient_name if recipient_name is not None else "", ) legal_entity_value_map = { "location": legal_entity_location, "business_categories": get_business_categories(row=row, data_type="fpds"), "is_fpds": True, } set_legal_entity_boolean_fields(row) legal_entity = load_data_into_model(legal_entity, row, value_map=legal_entity_value_map, save=True) # Create the place of performance location pop_location = create_location(place_of_performance_field_map, row, {"place_of_performance_flag": True}) # Find the toptier awards from the subtier awards awarding_agency = Agency.get_by_subtier_only(row["awarding_sub_tier_agency_c"]) funding_agency = Agency.get_by_subtier_only(row["funding_sub_tier_agency_co"]) # Generate the unique Award ID # "CONT_AW_" + agency_id + referenced_idv_agency_iden + piid + parent_award_id generated_unique_id = ( "CONT_AW_" + (row["agency_id"] if row["agency_id"] else "-NONE-") + "_" + (row["referenced_idv_agency_iden"] if row["referenced_idv_agency_iden"] else "-NONE-") + "_" + (row["piid"] if row["piid"] else "-NONE-") + "_" + (row["parent_award_id"] if row["parent_award_id"] else "-NONE-") ) # Create the summary Award (created, award) = Award.get_or_create_summary_award( generated_unique_award_id=generated_unique_id, piid=row["piid"] ) award.parent_award_piid = row.get("parent_award_id") award.save() # Append row to list of Awards updated AWARD_UPDATE_ID_LIST.append(award.id) if row["last_modified"] and len(str(row["last_modified"])) == len("YYYY-MM-DD HH:MM:SS"): # 19 characters dt_fmt = "%Y-%m-%d %H:%M:%S" else: dt_fmt = "%Y-%m-%d %H:%M:%S.%f" # try using this even if last_modified isn't a valid string try: last_mod_date = datetime.strptime(str(row["last_modified"]), dt_fmt).date() except ValueError: # handle odd-string formats and NULLs from the upstream FPDS-NG system info_message = "Invalid value '{}' does not match: '{}'".format(row["last_modified"], dt_fmt) logger.info(info_message) last_mod_date = None award_type, award_type_desc = award_types(row) parent_txn_value_map = { "award": award, "awarding_agency": awarding_agency, "funding_agency": funding_agency, "recipient": legal_entity, "place_of_performance": pop_location, "period_of_performance_start_date": format_date(row["period_of_performance_star"]), "period_of_performance_current_end_date": format_date(row["period_of_performance_curr"]), "action_date": format_date(row["action_date"]), "last_modified_date": last_mod_date, "transaction_unique_id": row["detached_award_proc_unique"], "generated_unique_award_id": generated_unique_id, "is_fpds": True, "type": award_type, "type_description": award_type_desc, } contract_field_map = {"description": "award_description"} transaction_normalized_dict = load_data_into_model( TransactionNormalized(), # thrown away row, field_map=contract_field_map, value_map=parent_txn_value_map, as_dict=True, ) contract_instance = load_data_into_model(TransactionFPDS(), row, as_dict=True) # thrown away detached_award_proc_unique = contract_instance["detached_award_proc_unique"] unique_fpds = TransactionFPDS.objects.filter(detached_award_proc_unique=detached_award_proc_unique) if unique_fpds.first(): transaction_normalized_dict["update_date"] = datetime.now(timezone.utc) transaction_normalized_dict["fiscal_year"] = fy(transaction_normalized_dict["action_date"]) # update TransactionNormalized TransactionNormalized.objects.filter(id=unique_fpds.first().transaction.id).update( **transaction_normalized_dict ) # update TransactionFPDS unique_fpds.update(**contract_instance) else: # create TransactionNormalized transaction = TransactionNormalized(**transaction_normalized_dict) transaction.save() # create TransactionFPDS transaction_fpds = TransactionFPDS(transaction=transaction, **contract_instance) transaction_fpds.save() # Update legal entity to map back to transaction legal_entity.transaction_unique_id = detached_award_proc_unique legal_entity.save()
def crud_pledge_need(request, project_key, need_id, action=None): if not request.user.is_authenticated() : if request.is_ajax() : return HttpResponseBadRequest() else : return redirect('bitfund.core.login') project = get_object_or_404(Project, key=project_key) need = get_object_or_404(ProjectNeed, id=need_id) template_data = {'project': project, 'request': request, 'today': datetime.utcnow().replace(tzinfo=utc).today(), 'site_currency_sign': SITE_CURRENCY_SIGN, } if request.method == 'POST' : if action == 'pledge' : pledge_need_form = PledgeProjectNeedForm(request.POST, prefix='need-'+str(need.id)) if pledge_need_form.is_valid() : with transaction.commit_on_success(): cleaned_pledge_type = pledge_need_form.cleaned_data['pledge_type'] cleaned_pledge_amount = pledge_need_form.cleaned_data['pledge_amount'] if cleaned_pledge_type == DONATION_TYPES_CHOICES.onetime : transaction = DonationTransaction() transaction.populatePledgeTransaction(project=project, user=request.user, need=need, pledge_amount=cleaned_pledge_amount) transaction.save() transaction.createRedonationTransactions() else : pledge_subscription = (DonationSubscription.objects .filter(user=request.user) .filter(project=project) .select_related()) if pledge_subscription.count() == 1 : pledge_subscription = pledge_subscription[0] pledge_subscription_need = (DonationSubscriptionNeeds.objects .filter(donation_subscription=pledge_subscription) .filter(need=need)) if pledge_subscription_need.count() == 1 : pledge_subscription_need = pledge_subscription_need[0] pledge_subscription.cancelPendingTransactions(pledge_subscription_need) pledge_subscription_need.amount = cleaned_pledge_amount pledge_subscription_need.save() else : pledge_subscription_need = DonationSubscriptionNeeds() pledge_subscription_need.donation_subscription = pledge_subscription pledge_subscription_need.need = need pledge_subscription_need.amount = cleaned_pledge_amount pledge_subscription_need.save() else : pledge_subscription = DonationSubscription() pledge_subscription.user = request.user pledge_subscription.project = project pledge_subscription.save() pledge_subscription_need = DonationSubscriptionNeeds() pledge_subscription_need.donation_subscription = pledge_subscription pledge_subscription_need.need = need pledge_subscription_need.amount = cleaned_pledge_amount pledge_subscription_need.save() transaction = DonationTransaction() transaction.populatePledgeTransaction(project=project, user=request.user, need=need, pledge_amount=cleaned_pledge_amount, donation_subscription=pledge_subscription) transaction.transaction_status = DONATION_TRANSACTION_STATUSES_CHOICES.pending transaction.save() transaction.createRedonationTransactions() return redirect('bitfund.project.views.crud_pledge_need', project_key=project.key, need_id=need.id) else : template_data['need'] = _prepare_need_item_template_data(request, project, need, pledge_need_form) if not request.is_ajax() : if not request.user_has_bank_card_attached : request.session[SESSION_PARAM_RETURN_TO_PROJECT] = project.key return redirect('bitfund.pledger.attach_card') else : return redirect('bitfund.project.budget', project_key=project.key) elif action == 'switch_monthly' : pledge_need_form = PledgeProjectNeedForm(request.POST, prefix='need-'+str(need.id)) if pledge_need_form.is_valid() : with transaction.commit_on_success(): pledge_subscription = (DonationSubscription.objects .filter(user=request.user) .filter(project=project) .select_related()) if pledge_subscription.count() == 1 : pledge_subscription = pledge_subscription[0] else : pledge_subscription = DonationSubscription() pledge_subscription.user = request.user pledge_subscription.project = project pledge_subscription.save() pledge_subscription_need = (DonationSubscriptionNeeds.objects .filter(donation_subscription=pledge_subscription) .filter(need=need)) if pledge_subscription_need.count() == 0 : cleaned_pledge_amount = pledge_need_form.cleaned_data['pledge_amount'] pledge_subscription_need = DonationSubscriptionNeeds() pledge_subscription_need.donation_subscription = pledge_subscription pledge_subscription_need.need = need pledge_subscription_need.amount = cleaned_pledge_amount pledge_subscription_need.save() return redirect('bitfund.project.views.crud_pledge_need', project_key=project.key, need_id=need.id) else : template_data['need'] = _prepare_need_item_template_data(request, project, need, pledge_need_form) elif action == 'drop_subscription' : existing_subscription = (DonationSubscription.objects .filter(user=request.user, project=project) .select_related()) if existing_subscription.count() == 1 : with transaction.commit_on_success(): existing_subscription = existing_subscription[0] existing_subscription_need = (DonationSubscriptionNeeds.objects .filter(donation_subscription=existing_subscription, need=need)) if existing_subscription_need.count() == 1 : existing_subscription_need = existing_subscription_need[0] existing_subscription.cancelPendingTransactions(existing_subscription_need) existing_subscription_need.delete() other_subscriptions_count = (DonationSubscriptionNeeds.objects .filter(donation_subscription_id=existing_subscription.id) .count()) if other_subscriptions_count == 0 : existing_subscription.delete() return redirect('bitfund.project.views.crud_pledge_need', project_key=project.key, need_id=need.id) if 'need' not in template_data: template_data['need'] = _prepare_need_item_template_data(request, project, need) template_data['budget'] = _prepare_project_budget_template_data(request, project) return render_to_response('project/budget/ajax-pledge_need_form.djhtm', template_data, context_instance=RequestContext(request))
def register_transaction(self, giftcard, charge, comment = '', id = ''): transaction = Transaction(merchant = self, comment = comment, purchase_item_id = id, amount = charge, giftcard= giftcard) transaction.save() #TODO SEND E_MAIL TO MERCHANT ADMIN return transaction
def tradeNow(request, *args, **kwargs): """Trade app.""" initParam = {} app = get_object_or_404(appModels.App, pk=kwargs.get('app_id'), publisher_id=request.user.id) user = get_object_or_404(User, pk=kwargs.get('buyer_id')) bid = get_object_or_404(bidModels.Bidding, pk=kwargs.get('bid_id'), buyer_id=user.id, app_id=app.id, status=1) initParam['app'] = app initParam['user'] = user initParam['bid'] = bid transactions = models.Transaction.objects.filter(app_id=app.id, seller_id=request.user.id, is_active=True) if transactions: transaction = transactions[0] else: transaction = models.Transaction() transaction.app = app transaction.status = 1 transaction.seller = request.user transaction.is_active = True transaction.save() #Remind that seller has 7 days to trade now, if bid price is more than reserve price. cur_time = datetime.datetime.now() if transaction.status == 1 and app.status != 1 and app.end_date <= cur_time and bid.price >= app.reserve_price: if transaction.end_time is None: paid_expiry_date = string.atoi(common.getSystemParam(key='sell_expiry_date', default=7)) transaction.end_time = app.end_date + datetime.timedelta(days=paid_expiry_date) transaction.save() if transaction.end_time > cur_time: initParam['time_remaining'] = time.mktime(time.strptime(str(transaction.end_time), '%Y-%m-%d %H:%M:%S')) initParam['is_expiry_date'] = False else: initParam['is_expiry_date'] = True initParam['transaction'] = transaction if request.method == 'POST': if transaction and transaction.status != 1: initParam['error_msg'] = _('You have traded with buyer %(param)s, can not trade again.') % {'param': user.username} else: if transaction is None: transaction = models.Transaction() transaction.app = app transaction.seller = request.user transaction.is_active = True transaction.status = 2 transaction.buyer = user transaction.price = bid.price paid_expiry_date = string.atoi(common.getSystemParam(key='paid_expiry_date', default=7)) transaction.end_time = cur_time + datetime.timedelta(days=paid_expiry_date) transaction.buy_type = 2 transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.seller = transaction.seller transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buy_type = transaction.buy_type transactionsLog.save() #Update app status and end_date if app.status == 2: app.status = 3 app.end_date = cur_time app.save() #Send the email of pay to buyer notificationViews.tradeNowInformBuyerPayEmail(request, app=app, user=user) return redirect(reverse('transaction:trade_action', kwargs={'action': 'sell', 'app_id': app.id, 'user_id': request.user.id})) return render_to_response('transaction/trade_now.html', initParam, context_instance=RequestContext(request))
def success(request): from payments.gateways.paypal import PayPalGateway from payments.models import PayPalShopSettings, PayPalToken, PayPalTransaction from preferences.models import Preference from sell.templatetags.sell_tags import money_format cart = request.cart #### Verify Products Availability if not cart.is_available(): request.flash['message'] = 'Items not longer available: ' for item in cart.items_not_availables(): request.flash['message'] += item.product.title cart.remove_not_available_items() return HttpResponseRedirect(reverse('my_shopping')) if request.method == 'GET': payerid = request.GET.get('PayerID', None) token = request.GET.get('token', None) else: payerid = request.POST.get('PayerID', None) token = request.POST.get('token', None) if None in (token, payerid): request.flash['message'] = unicode(_("Payment failed, try other method.")) request.flash['severity'] = "error" return HttpResponseRedirect(reverse('my_shopping')) shop = request.shop paypal_settings = PayPalShopSettings.objects.filter(shop = shop).get() try: paypaltoken = PayPalToken.objects.filter(token=token).get() except PayPalToken.DoesNotExist: request.flash['message'] = unicode(_("Payment failed, try other method.")) request.flash['severity'] = "error" return HttpResponseRedirect(reverse('my_shopping')) if paypaltoken.confirmed == True: request.flash['message'] = unicode(_("Payment is already confirmed!")) request.flash['severity'] = "notice" return HttpResponseRedirect(reverse('my_shopping')) cart = paypaltoken.cart #currency = Preference.get_preference(shop).checkout_currency total_amount = "%0.2f" % cart.total_with_taxes() if request.method != 'POST': t = loader.get_template('payments/payment_paypal_confirm.html') c = RequestContext(request, { 'payerid': payerid, 'token': token, #'api_signature': settings.PAYPAL_SIGNATURE, #'api_user': settings.PAYPAL_USERNAME, #'api_password': settings.PAYPAL_PASSWORD }) block = (t.render(c)) param = {'total_amount': money_format(total_amount, shop), 'paypaltoken': paypaltoken, 'cart': cart, 'cancel_url': reverse('payments_cancel'), 'form_paypal_confirm': block, } return HttpResponse(my_render(request, param, 'payment_paypal_confirm')) action = request.POST.get('action', 'cancel').lower() if action == 'confirm': paypal_gw = PayPalGateway(username=settings.PAYPAL_USERNAME, password=settings.PAYPAL_PASSWORD, sign=settings.PAYPAL_SIGNATURE, debug=settings.PAYPAL_DEBUG) #return_url = request.build_absolute_uri(reverse("paypal_success")) #cancel_url = request.build_absolute_uri(reverse("paypal_cancel")) is_token_data = paypal_gw.GetExpressCheckoutDetails(paypaltoken.token, subject=paypal_settings.email) if not is_token_data: logging.critical("Error found when trying to do a GetExpressCheckoutDetails api call on Paypal. RESPONSE: %s" % paypal_gw.api_response) request.flash['message'] = unicode(_("Could not get transaction data from PayPal. Please contact admin to complete your purchase!")) request.flash['severity'] = "error" return HttpResponseRedirect(reverse('my_shopping')) ack = paypal_gw.api_response['ACK'][0] if ack != "Success": logging.critical("Paypal Api Response Failure. RESPONSE: %s" % paypal_gw.api_response) request.flash['message'] = unicode(_("There was an error when trying to get data from PayPal. Please contact admin to complete your purchase!")) request.flash['severity'] = "error" return HttpResponseRedirect(reverse('my_shopping')) try: amount = decimal.Decimal(paypal_gw.api_response['PAYMENTREQUEST_0_AMT'][0]) except KeyError: logging.critical("Fail when trying to read the payment amount. The API response don't have an AMT key. RESPONSE: %s" % paypal_gw.api_response) request.flash['message'] = unicode(_("We have found an error when trying to validate your purchase!")) request.flash['severity'] = "error" return HttpResponseRedirect(reverse('my_shopping')) if amount != cart.total_with_taxes(): request.flash['message'] = unicode(_("You have authorized us to charge you just $%s, but you want buy $%s! Please contact admin if you think this is a mistake!" % (amount, cart.total_with_taxes()))) request.flash['severity'] = "error" return HttpResponseRedirect(reverse('my_shopping')) payment_request = { 'PAYMENTREQUEST_0_PAYMENTACTION': 'Sale', 'PAYMENTREQUEST_0_AMT': "%0.2f" % cart.total_with_taxes(), #'PAYMENTREQUEST_0_TAXAMT': "%0.2f" % cart.taxes(), #'PAYMENTREQUEST_n_SHIPPINGAMT': "%0.2f" % cart.shipping_charge(), #'PAYMENTREQUEST_0_ITEMAMT': "%0.2f" % cart.total(), 'PAYMENTREQUEST_0_CURRENCYCODE': Preference.get_preference(shop).checkout_currency, 'PAYMENTREQUEST_0_NOTIFYURL': request.build_absolute_uri(reverse("payments_paypal_ipn")), 'SUBJECT': paypal_settings.email } success = paypal_gw.DoExpressCheckoutPayment(payment_request, paypaltoken.token, payerid) if success: #Close and clean the cart sell = cart.close("PayPal") #Set the sell payments as paid sell.payment.pay() paypaltoken.confirmed = True paypaltoken.save() # {'PAYMENTINFO_0_TRANSACTIONTYPE': 'expresscheckout', 'ACK': 'Success', 'PAYMENTINFO_0_PAYMENTTYPE': 'instant', 'PAYMENTINFO_0_REASONCODE': 'None', 'SHIPPINGOPTIONISDEFAULT': 'false', 'INSURANCEOPTIONSELECTED': 'false', 'CORRELATIONID': '8d20dfd3e3575', 'PAYMENTINFO_0_TAXAMT': '0.00', 'PAYMENTINFO_0_TRANSACTIONID': '6MH53467HE876651A', 'PAYMENTINFO_0_PENDINGREASON': 'None', 'PAYMENTINFO_0_AMT': '57.00', 'PAYMENTINFO_0_PROTECTIONELIGIBILITY': 'Ineligible', 'PAYMENTINFO_0_ERRORCODE': '0', 'TOKEN': 'EC-7MR99474WD5992801', 'VERSION': '63.0', 'SUCCESSPAGEREDIRECTREQUESTED': 'false', 'BUILD': '1482946', 'PAYMENTINFO_0_CURRENCYCODE': 'USD', 'PAYMENTINFO_0_FEEAMT': '1.95', 'TIMESTAMP': '2010-09-08T18:03:24Z', 'PAYMENTINFO_0_ACK': 'Success', 'PAYMENTINFO_0_ORDERTIME': '2010-09-08T18:03:23Z', 'PAYMENTINFO_0_PAYMENTSTATUS': 'Completed'} txn_id = paypal_gw.api_response['PAYMENTINFO_0_TRANSACTIONID'] transaction = PayPalTransaction() transaction.transaction_id = txn_id transaction.sell = sell transaction.save() return HttpResponseRedirect(reverse('payments_success')) else: request.flash['message'] = unicode(_("Payment Failed!")) request.flash['severity'] = "error" return HttpResponseRedirect(reverse('my_shopping')) else: paypaltoken.delete() request.flash['message'] = unicode(_("Payment cancel!")) request.flash['severity'] = "notice" return HttpResponseRedirect(reverse('my_shopping'))
def contract_uploader_view(request): csv_file = request.FILES.get('file', None) contract_id = request.data.get('contract_id', None) data = { 'errors' : { 'user_exists' : [], 'class_not_found' : [], }, 'stats' : { 'inserted' : 0, 'num_errors': 0, 'new_groups':0, } } if not contract_id: data['errors']['form'] = "Contract must be specified" return Response(data, status.HTTP_400_BAD_REQUEST) contract = Contract.objects.get(pk=contract_id) if csv_file: import unicodecsv as csv transactions = { 'create' : [], 'group_users' : {}, 'class_users' : {}, 'contract' : { 'group' : [], 'class' : [], 'unities' : [] } } try: cf = csv_file.read().splitlines() csv_reader = csv.DictReader(cf) csv_reader = [c for c in csv_reader] groups = set([c for u in csv_reader for c in u['Grupos'] .split(';')]) for group in groups: if not Group.objects.filter(name=group).exists(): g = Group(name=group) transactions['create'].append(g) data['stats']['new_groups']+=1 for user in csv_reader: transactions['contract']['unities'] += user[u'Município']\ .split(';') if not TimtecUser.objects.filter(email=user['Email']).exists(): username = slugify((user['Nome'] + user['Sobrenome'])[0:30]) tries = 0 while TimtecUser.objects.filter(username=username)\ .exists() and tries < 10: tries+=1 username = username[0:-1] + str(tries) u = TimtecUser(email=user['Email'], cpf=user['CPF'], username=username, first_name=user['Nome'][0:30], last_name=user['Sobrenome'][0:30]) transactions['create'].append(u) data['stats']['inserted']+=1 else: data['errors']['user_exists'].append(user['Nome'] + user['Sobrenome']) data['stats']['num_errors']+=1 u = None groups = user['Grupos'].split(';') for group in groups: if not transactions['group_users'].has_key(group): transactions['group_users'][group] = [] transactions['contract']['group'].append(group) if u: transactions['group_users'][group].append(u) classes = user['Turmas'].split(';') for class_course in classes: (cclass, course) = class_course.split(' @ ') if Class.objects.filter(name=cclass, course__slug=course)\ .exists(): if not transactions['class_users']\ .has_key(class_course): transactions['class_users'][class_course] = [] if u: transactions['class_users'][class_course].append(u) transactions['contract']['class']\ .append(Class.objects .get(name=cclass, course__slug=course)) else: data['errors']['class_not_found'].append(class_course) data['stats']['num_errors']+=1 if data['stats']['num_errors'] == 0: from django.db import transaction with transaction.atomic(): # create entities for transaction in transactions['create']: transaction.save() # add to groups for group_transaction in transactions['group_users']: group = Group.objects.get(name=group_transaction) for u in transactions['group_users'][group_transaction]: group.user_set.add(u) group.save() # add to classes for class_transaction in transactions['class_users']: (cclass, course) = class_transaction.split(' @ ') cclass = Class.objects\ .get(name=cclass, course__slug=course) for u in transactions['class_users'][class_transaction]: cclass.students.add(u) cclass.save() if not CourseStudent.objects\ .filter(user=u, course=cclass.course).exists(): cs = CourseStudent(user=u, course=cclass.course) cs.save() # add groups and classes to contract groups = Group.objects\ .filter(name__in=transactions['contract']['group']) for group in groups: contract.groups.add(group) # add classes to contract classes = transactions['contract']['class'] for cclass in classes: contract.classes.add(cclass) unities = contract.unities + \ list(set(transactions['contract']['unities'])) contract.unities = unities contract.save() serializer = ContractSerializer(instance=contract) data['instance'] = serializer.data else: serializer = ContractSerializer(instance=contract) data['instance'] = serializer.data return Response(data, status.HTTP_400_BAD_REQUEST) except KeyError: data['errors']['form'] = "Not valid CSV file" return Response(data, status.HTTP_400_BAD_REQUEST) else: data['errors']['form'] = "Not valid CSV file" return Response(data, status.HTTP_400_BAD_REQUEST) return Response(data, status.HTTP_200_OK)
def crud_pledge_empty_project(request, project_key, action=None): if not request.user.is_authenticated() : if request.is_ajax() : return HttpResponseBadRequest() else : return redirect('bitfund.core.login') project = get_object_or_404(Project, key=project_key) template_data = {'project': project, 'request': request, 'today': datetime.utcnow().replace(tzinfo=utc).today(), 'site_currency_sign': SITE_CURRENCY_SIGN, } template_data['project_edit_access'] = False if request.user.id == project.maintainer_id : template_data['project_edit_access'] = True if request.method == 'POST' : if action == 'pledge' : pledge_empty_project_form = PledgeNoBudgetProjectForm(request.POST) if pledge_empty_project_form.is_valid() : with transaction.commit_on_success(): cleaned_pledge_type = pledge_empty_project_form.cleaned_data['pledge_type'] cleaned_pledge_amount = pledge_empty_project_form.cleaned_data['pledge_amount'] if cleaned_pledge_type == DONATION_TYPES_CHOICES.onetime: transaction = DonationTransaction() transaction.populatePledgeTransaction(project=project, user=request.user, pledge_amount=cleaned_pledge_amount) transaction.save() transaction.createRedonationTransactions() else: pledge_subscription = (DonationSubscription.objects .filter(user=request.user) .filter(project=project) .select_related()) if pledge_subscription.count() == 1: pledge_subscription = pledge_subscription[0] pledge_subscription.cancelPendingTransactions() pledge_subscription.amount = cleaned_pledge_amount pledge_subscription.save() else: pledge_subscription = DonationSubscription() pledge_subscription.user = request.user pledge_subscription.project = project pledge_subscription.amount = cleaned_pledge_amount pledge_subscription.save() transaction = DonationTransaction() transaction.populatePledgeTransaction(project=project, user=request.user, pledge_amount=cleaned_pledge_amount, donation_subscription=pledge_subscription) transaction.transaction_status = DONATION_TRANSACTION_STATUSES_CHOICES.pending transaction.save() transaction.createRedonationTransactions() return redirect('bitfund.project.views.crud_pledge_empty_project', project_key=project.key) else : template_data['empty_project'] = _prepare_empty_project_template_data(request, project, pledge_empty_project_form) if not request.is_ajax() : #@TODO card presence check (along with the payment integration itself) if not request.user.is_card_attached : request.session[SESSION_PARAM_RETURN_TO_PROJECT] = project.key return redirect('bitfund.pledger.attach_card') else : return redirect('bitfund.project.budget', project_key=project.key) elif action == 'switch_monthly' : pledge_empty_project_form = PledgeNoBudgetProjectForm(request.POST) if pledge_empty_project_form.is_valid() : with transaction.commit_on_success(): cleaned_pledge_amount = pledge_empty_project_form.cleaned_data['pledge_amount'] pledge_subscription = (DonationSubscription.objects .filter(user=request.user) .filter(project=project) .select_related()) if pledge_subscription.count() == 1 : pledge_subscription = pledge_subscription[0] else : pledge_subscription = DonationSubscription() pledge_subscription.user = request.user pledge_subscription.project = project pledge_subscription.amount = cleaned_pledge_amount pledge_subscription.save() return redirect('bitfund.project.views.crud_pledge_empty_project', project_key=project.key) else : template_data['empty_project'] = _prepare_empty_project_template_data(request, project, pledge_empty_project_form) elif action == 'drop_subscription' : existing_subscription = (DonationSubscription.objects .filter(user=request.user, project=project) .select_related()) if existing_subscription.count() == 1 : with transaction.commit_on_success(): existing_subscription = existing_subscription[0] existing_subscription.cancelPendingTransactions() subscription_needs_count = (DonationSubscriptionNeeds.objects .filter(donation_subscription_id=existing_subscription.id) .count()) if subscription_needs_count == 0 : existing_subscription.delete() else : existing_subscription.amount = 0 existing_subscription.save() return redirect('bitfund.project.views.crud_pledge_empty_project', project_key=project.key) template_data['empty_project'] = _prepare_empty_project_template_data(request, project) template_data['budget'] = _prepare_project_budget_template_data(request, project) return render_to_response('project/budget/ajax-pledge_empty_project_form.djhtm', template_data, context_instance=RequestContext(request))
def save_transaction(transaction): transaction.exchange = exchange transaction.editor = request.user debit_or_credit = exchange_type.debit_or_credit() setattr(transaction, debit_or_credit, exchange_form.cleaned_data[debit_or_credit]) transaction.save()