示例#1
0
    def form_valid(self, form):
        infolog.info("IN POBOCREATEVIEW - FORM VALID")
        if ON_HEROKU:
            # Create a Xero object that allows access to the API
            xero = get_xero(self.request)
            infolog.info("Form Valid {0}".format(xero))
            form.instance.customer = self.request.user

            self.object = form.save(commit=False)
            self.object.number = "BI-INV-{0}-{1}-{2}".format(
                randrange(10000), randrange(10000), randrange(100))
            self.object.save()

            # Setup Xero invoice dictionary
            invoice = {
                'InvoiceNumber':
                self.object.number,
                'Type':
                'ACCPAY' if form.cleaned_data.get('invoice_type', '')
                == Invoice.PAYABLE else 'ACCREC',
                'LineItems': [{
                    'Description':
                    'For Services Rendered',
                    'Quantity':
                    '1.0',
                    'UnitAmount':
                    form.cleaned_data.get('amount', '0.0'),
                    'AccountCode':
                    '310'
                }],
                'Url':
                '{0}/cashflow/pobo/pay?number={1}'.format(
                    BANKIFI_ROOT, self.object.number),
                'Contact': {
                    'ContactID': form.cleaned_data.get('contact',
                                                       '').contact_id
                },
                'Date':
                form.cleaned_data.get('raised', ''),
                'DueDate':
                form.cleaned_data.get('due', ''),
                'LineAmountTypes':
                'Inclusive',
                'Status':
                'AUTHORISED'
            }

            # Call Xero api to add invoice
            try:
                result = xero.invoices.put(invoice)
                infolog.info(
                    "Result of xero.invoices.put(invoice) in pobo.py: {0}".
                    format(result))
            except:
                errorlog.error(
                    "Unable to put new invoice into Xero app. Check log above for more details."
                )
                errorlog.error(sys.exc_info()[0])

        return super(PoboCreateView, self).form_valid(form)
示例#2
0
    def get_context_data(self, **kwargs):
        context = super(SetupView, self).get_context_data(**kwargs)

        # Clear loans and add counts to context
        context['loan_count'] = clear_loan(self.request.user)
        context['invoice_count'] = clear_invoices(self.request.user)
        context['transaction_count'] = clear_transactions(self.request.user)

        if ON_HEROKU:
            # Create a Xero object that allows access to the API
            xero = get_xero(self.request)
            if xero is not None:
                # Void Xero invoices (this removes bank account transactions too)
                try:
                    context['invoice_void_count'] = invoices_void(xero)
                except:
                    errorlog.error('Xero token expired, or our request was rejected by Xero API.')
                    errorlog.error(sys.exc_info()[0])
                    context['error'] = "Xero token invalid. Log back into Xero."

            else:
                # Log error if we failed to logon to Xero
                errorlog.error('Get xero returned none.')
                context['error'] = "Error connecting to Xero. Check you are logged in."

        return context
示例#3
0
    def post(self, request, *args, **kwargs):
        context = super(ThankyouView, self).get_context_data(**kwargs)

        xero = get_xero(self.request)

        context['offer_amount'] = self.request.GET.get('offer_amount')
        context['account'] = self.request.GET.get('account')

        # Make Transfer of funds from loan account to Bank account (need to strip commas)
        amount = self.request.GET.get('offer_amount').translate(
            {ord(c): None
             for c in ' ,'})
        xero.banktransfers.put({
            'FromBankAccount': {
                'Code': BFS_CODE
            },
            'ToBankAccount': {
                'Code': BANKIFI_CODE
            },
            'Amount': amount,
        })
        # Update shadow bank account balance
        update_balance(float(amount))
        update_loan(float(amount))

        # Post the payment
        return render(request, self.template_name, context)
示例#4
0
    def post(self, request, *args, **kwargs):
        context = super(AuthorizationView, self).get_context_data(**kwargs)

        xero = get_xero(self.request)

        # Save the payments
        amount = self.request.GET.get('amount').translate(
            {ord(c): None
             for c in ' ,'})
        xero.payments.put({
            'Invoice': {
                'InvoiceNumber': self.request.GET.get('invoice')
            },
            # Add to Bankifi Bank Account - 12345
            'Account': {
                'Code': BANKIFI_CODE
            },
            'Amount': amount,
            'Date': datetime.now().date()
        })

        # Update shadow bank account balance
        update_balance(float(amount))

        context['invoices'] = xero.invoices.filter(Status='AUTHORISED')
        context['offer'], context['offer_amount'] = make_offer(
            xero.invoices.filter(Status='AUTHORISED'))
        context['loan_balance_str'] = "£{0:,}".format(
            int(Loan.objects.first().balance))
        context['loan_balance'] = int(Loan.objects.first().balance)
        context['bank_balance'] = "£{0:,}".format(
            int(BankAccount.objects.first().balance))

        # Post the payment
        return render(request, self.template_name, context)
示例#5
0
    def post(self, request, *args, **kwargs):
        context = super(LoanPayView, self).get_context_data(**kwargs)

        # Retrieve outstanding loan object
        loan = Loan.objects.filter(customer=request.user,
                                   status=Loan.OUTSTANDING).first()

        xero = get_xero(request)

        # Pay the loan and update Bankifi and Xero
        reply = pay_loan(request.user, xero)
        if xero and reply[0]:
            # Display loan paid template if successful
            request.session['title'] = 'Loan Payment Complete'
            request.session['description'] = reply[1]
            request.session['status'] = ''

            return HttpResponseRedirect(reverse_lazy('cashflow:forecast'))

            # return render(request, self.template_name, context)

        else:
            # Return to invoice list if unsuccessful
            request.session['title'] = 'Loan Payment Failed'
            request.session[
                'description'] = 'You have insufficient funds to clear your loan.'
            request.session['status'] = ''
            return HttpResponseRedirect(reverse('cashflow:forecast'))
示例#6
0
    def get_context_data(self, **kwargs):
        context = super(ApplyView, self).get_context_data(**kwargs)

        xero = get_xero(self.request)
        context['offer'], context['offer_amount'] = make_offer(
            xero.invoices.filter(Status='AUTHORISED'))
        context['accounts'] = xero.accounts.filter(Code=BANKIFI_CODE)

        return context
示例#7
0
    def get_context_data(self, **kwargs):
        context = super(ContactImportView, self).get_context_data(**kwargs)

        if ON_HEROKU:
            # We can now create a Xero object that allows access to the API
            xero = get_xero(self.request)
            context['add_count'] = add_contacts(xero)

        return context
示例#8
0
 def get_context_data(self, **kwargs):
     context = super(TransactionImportView, self).get_context_data(**kwargs)
     
     if ON_HEROKU:
         # create a Xero object that allows access to the API
         xero = get_xero(self.request)
         # Add transactions to Bankifi and add count to context
         context['add_count'] = add_transactions(xero, self.request.user)
     
     return context
示例#9
0
    def get_context_data(self, **kwargs):
        context = super(PoboThankyouView, self).get_context_data(**kwargs)
        if ON_HEROKU:
            xero = get_xero(self.request)
            # context['loan_status'] = pay_loan(xero)[1]
            message = {
                'title': 'Payment Complete',
                'description':
                'Thankyou. We have successfully completed your payment.',
                'status': pay_loan(xero)[1]
            }

        return context
示例#10
0
    def get_context_data(self, **kwargs):
        context = super(AuthorizationView, self).get_context_data(**kwargs)

        # # We can now create a Xero object that allows access to the API
        xero = get_xero(self.request)
        context['invoices'] = xero.invoices.filter(Status='AUTHORISED')
        context['offer'], context['offer_amount'] = make_offer(
            xero.invoices.filter(Status='AUTHORISED'))
        loan = Loan.objects.first()
        if loan:
            context['loan_balance_str'] = "£{0:,}".format(int(loan.balance))
            context['loan_balance'] = int(loan.balance)
        account = BankAccount.objects.first()
        if account:
            context['bank_balance'] = "£{0:,}".format(int(account.balance))

        return context
示例#11
0
    def post(self, request, *args, **kwargs):
        context = super(PayLoanView, self).get_context_data(**kwargs)

        xero = get_xero(self.request)

        xero.banktransfers.put({
            'FromBankAccount': {
                'Code': BANKIFI_CODE
            },
            'ToBankAccount': {
                'Code': BFS_CODE
            },
            'Amount': loan_balance(),
        })
        # Update shadow bank account balance
        clear_loan()

        # Post the payment
        return render(request, self.template_name, context)
示例#12
0
    def post(self, request, *args, **kwargs):
        context = super(LoanThankyouView, self).get_context_data(**kwargs)

        # Add loan amount and account to deposit loan into to context
        amount = float(
            self.request.GET.get('offer_amount',
                                 '0').translate({ord(c): None
                                                 for c in ' ,'}))
        account = self.request.GET.get('account', '')
        context['offer_amount'] = amount
        context['account'] = account

        # Retrieve deposit account object
        dep_account = Account.objects.filter(customer=request.user,
                                             account_number=account).first()

        # Open a loan account
        loan = Loan(customer=request.user,
                    balance=-float(amount),
                    account=dep_account,
                    status=Loan.OUTSTANDING)
        if loan is not None:
            loan.save()
            contact = Contact.objects.filter(name=LOAN_CONTACT).first()
            # Make Transfer of funds from loan account to Bank account
            loan.transfer_funds(request.user, float(amount), get_xero(request),
                                contact.contact_id, dep_account.account_id)

        # Display thank you page
        # return render(request, self.template_name, context)

        request.session['title'] = 'Funds Transfer Complete'
        request.session[
            'description'] = "Thankyou. We have successfully transferred £{} to bank account number: {}.".format(
                amount, account)
        request.session['status'] = ''

        return HttpResponseRedirect(reverse_lazy('cashflow:forecast'))
示例#13
0
    def post(self, request, *args, **kwargs):
        """
        **post(self, request, *args, **kwargs)**

        Pay invoice and redirect to thankyou page.
        Mark the invoice as paid on Xero and Bankifi.
        Raise Debit and Credit Transaction on Xero and Bankif.
        Potentially offer loan if insufficient funds to pay invoice.
        """
        xero = get_xero(request)
        number = request.GET.get('number', '')
        account = request.GET.get('account', '')

        if xero and request.GET.get('number', ''):
            invoices = xero.invoices.filter(InvoiceNumber=number,
                                            Status='AUTHORISED')
        else:
            errorlog.error("Xero check failed {0} {1}".format(xero, number))
            raise Http404(
                "Failed to connect to Xero. Ensure you are signed in.")

        # Pay Xero and Put txn to Xero
        try:
            invoice = invoices[0]
            bk_invoice = Invoice.objects.filter(
                customer=request.user,
                number=invoice.get('InvoiceNumber')).first()
            bk_invoice.pay(request.user, account, xero)
        # Exception will occur if insufficient funds
        except ValidationError as e:
            context = {}
            context['number'] = request.GET.get('number', '')
            context['error'] = ",".join(e)
            context['object_list'] = self.queryset
            # If insufficient funds check if a loan offer can be generated
            context['offer'], context['offer_amount'] = make_offer(
                request.user)
            # Check if loan already in use
            loan = Loan.objects.filter(customer=request.user,
                                       status=Loan.OUTSTANDING).first()
            if loan is not None:
                context['loan'] = loan
                context['has_a_loan'] = True
            else:
                context['has_a_loan'] = False
            errorlog.error("Pobopayment failed {0}".format(context))

            # Return to payment view and notify with error and offer loan if available
            return render(request, self.template_name, context)
        except:
            errorlog.error("Pobopayment failed.")
            raise Http404(
                "Failed to make a payment as couldn't retrieve invoices from Xero."
            )

        if ON_HEROKU:
            xero = get_xero(self.request)
            # context['loan_status'] = pay_loan(xero)[1]
            request.session['title'] = 'Payment Complete'
            request.session[
                'description'] = 'Thankyou. We have successfully completed your payment.'
            request.session['status'] = pay_loan(request.user, xero)[1]
        return HttpResponseRedirect(reverse('cashflow:forecast'))