示例#1
0
def cancel(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), profile=profile)
        order.state = ORDER_STATUS['cancelled']
        order.save()
        orderSerializer = OrderProtectedSerializer(order, context={'request': request})

        # Notification to forwarder
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.service.profile.user
        orderLink = "%sorders/forwarder/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order %s" % (order.state),
            "notifications/email/forwarder_order_change_status.html",
            {
                'order': order,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d changed status to %s" % (order.id, order.state)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/forwarder/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
示例#2
0
def uploadSelfIDoc(request):
    success = False
    user = request.user
    profile = Profile.objects.get(user=user)
    file = request.data.get('SelfIDocImage')
    if file:
        if type(file) is dict:
            file = file['changingThisBreaksApplicationSecurity']
        if file.find("http://") > -1 or file.find("https://") > -1:
            imgstr = base64.b64encode(requests.get(file).content)
            ext = file.split('/')[-1].split(".")[-1]
            SelfIDocImageName = "%d.%s" % (user.id, ext)
            data = ContentFile(base64.b64decode(imgstr),
                               name=SelfIDocImageName)
            if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                return Response({
                    'success': False,
                    'error': 'file.toobig'
                }, 500)
            if profile.SelfIDocImage:
                profile.SelfIDocImage.delete(save=True)
            profile.SelfIDocImage = data
            profile.save()
            success = True
        else:
            datapost = request.data.get('SelfIDocImage')
            if type(datapost) is dict:
                datapost = datapost['changingThisBreaksApplicationSecurity']
            format, imgstr = datapost.split(';base64,')
            ext = format.split('/')[-1]
            SelfIDocImageName = "%d.%s" % (user.id, ext)
            data = ContentFile(base64.b64decode(imgstr),
                               name=SelfIDocImageName)
            if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                return Response({
                    'success': False,
                    'error': 'file.toobig'
                }, 500)
            if profile.SelfIDocImage:
                profile.SelfIDocImage.delete(save=True)
            profile.SelfIDocImage = data
            profile.save()
            success = True

    if success:
        # Admin Notification
        adminNotification = Notification()
        adminNotification.email = True
        adminNotification.user = User.objects.get(username="******")
        adminNotification.setEmailData(
            "User uploaded documents",
            "notifications/email/admin_email_user_uploaded_docs.html", {
                'user': user,
                'documentType': 'Selfie Id'
            })

    return Response({'success': False})
示例#3
0
def updateForwarderTrackingInfo(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), service__profile=profile)
        try:
            orderTrackingInfo = OrderTrackingInfo.objects.get(
                order=order,
                profile=profile,
                fromForwarder=True,
                trackingStatus=settings.ORDER_TRACKING_INFO_STATUS_CHOICES[1][0]
            )
            orderTrackingInfo.courier = request.data.get('courier')
            orderTrackingInfo.courierOther = request.data.get('courierOther')
            orderTrackingInfo.trn = request.data.get('trn')
            orderTrackingInfo.link = request.data.get('link')
        except OrderTrackingInfo.DoesNotExist:
            orderTrackingInfo = OrderTrackingInfo(
                order=order,
                profile=profile,
                fromForwarder=True,
                courier=request.data.get('courier'),
                courierOther=request.data.get('courierOther'),
                trn=request.data.get('trn'),
                link=request.data.get('link'),
                trackingStatus=settings.ORDER_TRACKING_INFO_STATUS_CHOICES[1][0]
            )
        orderTrackingInfo.save()
        order.save()
        orderSerializer = OrderWithAddressesSerializer(order, context={'request': request})

        # Notification to buyer
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.profile.user
        orderLink = "%sorders/buyer/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order Tracking Info Updated",
            "notifications/email/buyer_order_tracking_changed.html",
            {
                'order': order,
                'orderTrackingInfo': orderTrackingInfo,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d tracking info updated" % (order.id)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/buyer/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
示例#4
0
def withdraw(request):
    """
    Request Withdraw from wallet.
    """
    try:
        user = request.user
        currency = request.data.get('currency')
        amount = float(request.data.get('amount'))
        ccAddress = request.data.get('address')
        freezedCurrency = Currency().getCurrency(currency)
        if not freezedCurrency:
            return Response({'success': False, 'error': 'currency.notvalid'})
        cryptoAmount = amount / freezedCurrency.usd

        #create withdrawrequest
        withdrawRequest = WithdrawRequest()
        withdrawRequest.user = user
        withdrawRequest.requestedCurrency = currency
        withdrawRequest.requestedAmount = amount
        withdrawRequest.requestedCcAddress = ccAddress
        withdrawRequest.freezedUsd = freezedCurrency.usd
        withdrawRequest.freezedEur = freezedCurrency.eur
        withdrawRequest.save()

        #create notification
        protocol = 'http'
        if settings.FRONTEND_SSL:
            protocol = 'https'
        confirmationLink = "%s://%s:%s/withdrawConfirm/%s" % (
            protocol, settings.FRONTEND_HOST, settings.FRONTEND_PORT,
            str(withdrawRequest.hash))
        notification = Notification()
        notification.email = True
        notification.user = user
        notification.setEmailData(
            "Withdraw request comfirm",
            "notifications/email/withdraw_request_confirm_email.html", {
                'user': user,
                'confirmation_link': confirmationLink,
                'currency': currency,
                'amount': amount,
                'cryptoAmount': cryptoAmount,
                'freezedUsd': freezedCurrency.usd,
                'freezedEur': freezedCurrency.eur
            })

        withdrawRequest.notification = notification
        withdrawRequest.save()

        return Response({'success': True})
    except Profile.DoesNotExist:
        return Response({'success': False, 'error': 'profile.notfound'})
    except Wallet.DoesNotExist:
        return Response({'success': False, 'error': 'wallet.notfound'})
示例#5
0
def signup(request):
    name = request.data.get("name")
    surname = request.data.get("surname")
    email = request.data.get("email")
    if email:
        email = email.lower()
    username = request.data.get("username")
    if username:
        username = username.lower()
    error = checkUserAlreadyRegistered(email, username)
    if error:
        return Response({'success': False, 'error': error})
    user = User.objects.create_user(username,
                                    email,
                                    email,
                                    last_login=timezone.now())
    user.first_name = name
    user.last_name = surname
    user.is_active = False
    user.save()
    profile = Profile()
    profile.user = user
    profile.setActivationKey()
    profile.setKeyExpires()
    profile.save()
    createDefaultWallets(profile)

    #set default avatar
    try:
        imageData = getDefaultAvatarImageData()
        ext = settings.DEFAULT_AVATAR_IMAGE_PATH.split('/')[-1].split(".")[-1]
        avatarImageName = "%d.%s" % (profile.user.id, ext)
        data = ContentFile(imageData, name=avatarImageName)
        profile.avatarImage = data
        profile.save()
    except:
        pass

    # Admin Notification
    adminNotification = Notification()
    adminNotification.email = True
    adminNotification.user = User.objects.get(username="******")
    adminNotification.setEmailData(
        "New LWF user registered",
        "notifications/email/admin_email_user_registered.html", {
            'user': user,
        })
    Thread(target=adminNotification.process, args=(), kwargs={}).start()
    sendRegistrationEmail(profile)
    return Response({'success': True})
示例#6
0
def addNewsLetterEmail(request):
    email = request.data.get("email")
    if email:
        email = email.lower()
    try:
        NewsLetterEmailAddress.objects.get(email__iexact=email)
    except NewsLetterEmailAddress.DoesNotExist:
        newEmail = NewsLetterEmailAddress()
        newEmail.email = email
        newEmail.save()
        adminNotification = Notification()
        adminNotification.email = True
        adminNotification.user = User.objects.get(username="******")
        adminNotification.setEmailData(
            "New user signed for newsletter",
            "notifications/email/newsletter_email_registered.html", {
                'email': email,
            })
        Thread(target=adminNotification.process, args=(), kwargs={}).start()
    return Response({
        'success': True,
    })
示例#7
0
def sendRegistrationEmail(profile):
    protocol = 'http'
    if settings.FRONTEND_SSL:
        protocol = 'https'
    confirmationLink = "%s://%s:%s/signup/%s" % (
        protocol, settings.FRONTEND_HOST, settings.FRONTEND_PORT,
        str(profile.activationKey))

    # User Notification
    userNotification = Notification()
    userNotification.email = True
    userNotification.user = profile.user
    userNotification.setEmailData(
        "Confirm your registration to LWF",
        "notifications/email/user_registration.html", {
            'user': profile.user,
            'confirmation_link': confirmationLink
        })

    Thread(target=userNotification.process, args=(), kwargs={}).start()

    profile.setKeyExpires()
    profile.save()
示例#8
0
def forwardedDelivered(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        order = Order.objects.get(id=request.data.get('orderId'), service__profile=profile)
        if order.service.type == settings.SERVICE_TYPES[0][0]:
            order.state = ORDER_STATUS['forwarded']
            order.forwardedDate = django.utils.timezone.now()
        if order.service.type == settings.SERVICE_TYPES[1][0]:
            order.state = ORDER_STATUS['delivered']
        order.save()
        orderSerializer = OrderWithAddressesSerializer(order, context={'request': request})

        # Notification to buyer
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.profile.user
        orderLink = "%sorders/buyer/%s" % (
            orderNotification.getEmailLinkBaseUrl(),
            order.id
        )
        orderNotification.setEmailData(
            "LWF Order %s" % (order.state),
            "notifications/email/buyer_order_change_status.html",
            {
                'order': order,
                'orderLink': orderLink
            }
        )
        alertText = "Order #%d changed status to %s" % (order.id, order.state)
        orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/buyer/", order.id)
        orderNotification.save()

        return Response({'success': True, 'order': orderSerializer.data})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
示例#9
0
def orderPayment(request):
    try:
        order = Order.objects.get(id=request.data.get("orderId"))
        inWalletId = order.profile.wallet.id
        outWalletId = order.service.profile.wallet.id

        feePercentage = Configuration().getConfiguration(
            "forwarding_fee_percentage_level_1")

        TransactionManager.createPaymentTransaction(
            amount=order.totalPrice,
            order=order,
            inWalletId=inWalletId,
            outWalletId=outWalletId,
            feePercentage=feePercentage)

        # Notification to forwarder
        orderNotification = Notification()
        orderNotification.email = True
        orderNotification.alert = True
        orderNotification.user = order.service.profile.user
        orderLink = "%sorders/forwarder/%s" % (
            orderNotification.getEmailLinkBaseUrl(), order.id)
        orderNotification.setEmailData(
            "New LWF Order",
            "notifications/email/forwarder_order_new_status.html", {
                'order': order,
                'orderLink': orderLink
            })
        alertText = "Order #%d has been paid" % order.id
        orderNotification.alertData = "%s|%s|%d" % (
            alertText, "/orders/forwarder", order.id)
        orderNotification.save()

        return Response({'success': True})
    except Exception as e:
        return Response({'success': False, 'errors': e.message})
示例#10
0
def processBtcTransactions(FreezedCurrency):
    r = {
        "processed_addresses": 0,
        "created_transactions": [],
        "errors_transactions": [],
        "errors_addresses": []
    }

    allWallets = Wallet.objects.filter()

    for wallet in allWallets:

        for btcAddress in wallet.getWalletToCcAddresses(currency='BTC'):
            r['processed_addresses'] += 1
            atm = AtmBtc(btcAddress.address.address)
            btcAddress.address.address = atm.clean(btcAddress.address.address)
            try:
                addressRemoteTransactions = atm.getTransactions()
            except Exception, ex:
                addressRemoteTransactions = []
                r['errors_addresses'].append("%s" % (traceback.format_exc()))

            if len(addressRemoteTransactions) > 0:
                for art in addressRemoteTransactions:
                    if art.get("error"):
                        r['errors_addresses'].append(
                            "failed get data for address: %s" %
                            (btcAddress.address.address))
                    else:
                        if art['positive'] and art['confirmations'] > 0:

                            try:
                                new = False
                                try:
                                    transaction = Transaction.objects.get(
                                        hash=art['hash'],
                                        currency="BTC",
                                        address=btcAddress.address)
                                except Transaction.DoesNotExist:
                                    previousCredit = wallet.credit
                                    transaction = Transaction()
                                    transaction.hash = art['hash']
                                    transaction.date = art['date']
                                    transaction.type = 'deposit'
                                    transaction.currency = 'BTC'
                                    transaction.freezedUsd = FreezedCurrency.usd
                                    transaction.freezedEur = FreezedCurrency.eur
                                    transaction.amount = art['value']
                                    transaction.wallet = wallet
                                    transaction.address = btcAddress.address
                                    transaction.save()

                                    # update wallet credit
                                    feePercentage = Configuration(
                                    ).getConfiguration(
                                        "btc_deposit_percentage")
                                    wallet.depositIn(
                                        FreezedCurrency, transaction,
                                        art['value'],
                                        'by AtmBtc found new tx: %s with positive amount: %s (BTC)'
                                        % (art['hash'], art['value']),
                                        feePercentage)
                                    new = True

                                    #all good
                                    # create transactions info btc
                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Currency Rate Date: %s' % strftime(
                                        FreezedCurrency.dateUpdated,
                                        '%Y-%m-%d %H:%M:%S')
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'BTC -> USD'
                                    transactionInfo.cost = FreezedCurrency.usd
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'BTC -> EUR'
                                    transactionInfo.cost = FreezedCurrency.eur
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Previous Credit'
                                    transactionInfo.cost = previousCredit
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    wallet = Wallet.objects.get(id=wallet.id)
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Current Credit'
                                    transactionInfo.cost = wallet.credit
                                    transactionInfo.save()

                            except Exception, ex:
                                transaction = None

                                r['errors_transactions'].append(
                                    "failed insert for transaction: %s" %
                                    (art['hash']))

                            if new:
                                if transaction:
                                    if not any(x.hash == art['hash'] for x in
                                               r['created_transactions']):
                                        r['created_transactions'].append(
                                            transaction)
                                        # Admin Notification
                                        adminNotification = Notification()
                                        adminNotification.email = True
                                        adminNotification.user = User.objects.get(
                                            username="******")
                                        adminNotification.setEmailData(
                                            "New BTC deposit transaction confirmed",
                                            "notifications/email/admin_email_new_deposit_transaction_confirmed.html",
                                            {
                                                'transaction': transaction,
                                            })
示例#11
0
        # CREATE TRANSACTION
        withdrawTransaction = TransactionManager.createWithdrawTransaction(
            withdrawRequest.requestedAmount, wallet.id, freezedCurrency,
            withdrawRequest.requestedCcAddress)

        withdrawRequest.transaction = withdrawTransaction
        withdrawRequest.confirmed = True
        withdrawRequest.save()

        adminNotification = Notification()
        adminNotification.email = True
        adminNotification.user = User.objects.get(username="******")
        adminNotification.setEmailData(
            "New withdraw request confirmed",
            "notifications/email/admin_email_withdraw_request_confirmed.html",
            {
                'user': withdrawRequest.user,
                'hash': hash,
                'withdrawRequest': withdrawRequest
            })
        try:
            Thread(target=adminNotification.process, args=(),
                   kwargs={}).start()
        except Exception, ex:
            pass

        return Response({'success': True})
    except Exception, ex:
        p_ex(request, ex, 3, 1,
             'Failed to confirm withdraw request hash: %s' % (hash))
        return Response({
            'success': False,
示例#12
0
def createOrderNote(request):
    try:
        user = request.user
        profile = Profile.objects.get(user=user)
        file = request.data.get('noteImage')
        description = request.data.get('noteText')
        orderId = int(request.data.get('orderId'))
        query = Q(profile=profile) | Q(service__profile=profile)
        order = Order.objects.get(query, id=orderId)
        maxOrderNotes = int(Configuration.objects.get(
            key__iexact='max_order_notes'
        ).value)
        if len(order.notes) >= maxOrderNotes:
            return Response({'success': False, 'error': 'maxOrderNotesReached'})
        if file:
            if file.find("http://") > -1 or file.find("https://") > -1:
                imgstr = base64.b64encode(requests.get(file).content)
                ext = file.split('/')[-1].split(".")[-1]
                noteImageName = "%d.%s" % (user.id, ext)
                data = ContentFile(base64.b64decode(imgstr), name=noteImageName)
                if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                    return Response({'success': False, 'error':'file.toobig'}, 500)
            elif request.data.get('noteImage').find(';base64,') > -1:
                format, imgstr = request.data.get('noteImage').split(';base64,')
                ext = format.split('/')[-1]
                noteImageName = "%d.%s" % (user.id, ext)
                data = ContentFile(base64.b64decode(imgstr), name=noteImageName)
                if data.size > settings.MAX_IMAGE_SIZE_UPLOAD:
                    return Response({'success': False, 'error':'file.toobig'}, 500)
            else:
                data = None

            newOrderNote = OrderNote()
            newOrderNote.profile = profile
            newOrderNote.order = order
            newOrderNote.orderStatus = order.state
            if data:
                if data.size < settings.MAX_IMAGE_SIZE_UPLOAD:
                    newOrderNote.document = data
            newOrderNote.description = description
            newOrderNote.save()
            order = Order.objects.get(id=orderId)

            if order.state == ORDER_STATUS['paid'] \
                    or order.state == ORDER_STATUS['new'] \
                    or order.state == ORDER_STATUS['refused']:
                orderSerializer = OrderProtectedSerializer(
                    order,
                    context={'request': request}
                )
            else:
                orderSerializer = OrderWithAddressesSerializer(
                    order,
                    context={'request': request},
                )

            # Notification to buyer or Forwarder
            orderNotification = Notification()
            orderNotification.email = True
            orderNotification.alert = True
            alertText = "Order #%d has new note" % (order.id)
            if user.id == order.profile.user.id:
                orderNotification.user = order.service.profile.user
                notificationProfile = order.service.profile
                orderLink = "%sorders/forwarder/%s" % (
                    orderNotification.getEmailLinkBaseUrl(),
                    order.id
                )
                orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/forwarder/", order.id)
            else:
                orderNotification.user = order.profile.user
                notificationProfile = order.profile
                orderLink = "%sorders/buyer/%s" % (
                    orderNotification.getEmailLinkBaseUrl(),
                    order.id
                )
                orderNotification.alertData = "%s|%s|%d" % (alertText, "/orders/buyer/", order.id)
            orderNotification.setEmailData(
                "LWF Order Has New Note",
                "notifications/email/order_note_new.html",
                {
                    'order': order,
                    'profile': notificationProfile,
                    'orderLink': orderLink
                }
            )
            orderNotification.save()

            return Response({'success': True, 'order': orderSerializer.data})
        else:
            return Response({'success': False, 'error': 'nofile'})
    except Exception as e:
        return Response({'success': False, 'error': e.message})