示例#1
0
    def connect(self, request, company):
        """
           Connects a company to Xero
           company must be included in the querystring /?company=<id>
        """
        try:
            secret_keys = Utils.get_access_keys(company)

            consumer_key = secret_keys.client_id
            consumer_secret = secret_keys.client_secret

            global credentials
            call_back_uri = settings.XERO_CALL_BACK_URI + "/" + company

            # call_back_url = 'http://localhost/oauth'
            if AccountingConfiguration.PRIVATE == secret_keys.type:
                credentials = PrivateCredentials(consumer_key=consumer_key,rsa_key=consumer_secret)
                OAUTH_PERSISTENT_SERVER_STORAGE.update({'consumer_key':credentials.consumer_key})
                OAUTH_PERSISTENT_SERVER_STORAGE.update({'rsa_key':credentials.rsa_key})
                url = call_back_uri
            else:
                credentials = PublicCredentials(consumer_key, consumer_secret, callback_uri=call_back_uri)
                # Save generated credentials details to persistent storage
                for key, value in credentials.state.items():
                    OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

                LoginInfo.objects.create(company_id=company, status=LoginInfo.IN_PROGRESS, created=timezone.now())
                url = credentials.url

        except Exception as e:
            auth_cancel_url = settings.QBO_AUTH_CANCEL_URL
            Utils.send_company_misconfig(company,e)
            return redirect(auth_cancel_url + '/error')
        return Utils.redirect_response(url)
示例#2
0
    def connect(self, request, company_id):
        """
           Connects a company to quickbooks
           company must be included in the querystring /?company=<id>
           :param company_id:
           :return: Redirect url of QuickBook
        """
        try:
            if not getDiscoveryDocument:
                # todo: need to clarify this scenario occurs or not and handle correct redirct urls
                auth_cancel_url = settings.QBO_AUTH_CANCEL_URL
                return redirect(auth_cancel_url)
            url = getDiscoveryDocument.auth_endpoint

            configuration = Utils.get_access_keys(company_id)
            client_id = configuration.client_id

            params = {
                'scope': settings.ACCOUNTING_SCOPE,
                'redirect_uri': settings.REDIRECT_URI,
                'response_type': 'code',
                'state': company_id,
                'client_id': client_id
            }
            url += '?' + urllib.urlencode(params)
            LoginInfo.objects.create(company_id=company_id,
                                     status=LoginInfo.IN_PROGRESS,
                                     created=timezone.now())
            return redirect(url)
        except Exception as e:
            auth_cancel_url = settings.QBO_AUTH_CANCEL_URL
            Utils.send_company_misconfig(company_id, e)
            return redirect(auth_cancel_url + '/error')
示例#3
0
    def auth_code_handler(self, request, pk=None):
        """
        Handle Auth Code of xero
        :param request: GET Request
        :param pk: Company ID
        :return: Response
        """
        try:
            # Get xero auth access information form xero connection
            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE


            if len(stored_values) == 0:
                return Utils.dispatch_failure(request, 'NO_TOKEN_AUTHENTICATION')

            secret_keys = Utils.get_access_keys(pk)
            if AccountingConfiguration.PRIVATE == secret_keys.type:
                exists = AccountingOauth2.objects.filter(company=pk).first()
                if not exists:
                    auth = AccountingOauth2(accessToken=stored_values['consumer_key'],
                                            accessSecretKey=stored_values['rsa_key'],
                                        company_id=pk)
                    auth.save()
                else:
                    exists.accessToken = stored_values['consumer_key']
                    exists.accessSecretKey = stored_values['rsa_key']
                    exists.save()
            else:
                auth_verifier_uri = settings.XERO_AUTH_VERIFIER_URI
                oauth_verifier = request.GET.get('oauth_verifier')
                credentials = Utils.get_xero_public_credentials(stored_values)

                if credentials.expired():
                    return Utils.dispatch_failure(request, 'NO_TOKEN_AUTHENTICATION')

                # Verify the auth verifier for establish the connection

                credentials.verify(oauth_verifier)
                # Resave our verified credentials
                for key, value in credentials.state.items():
                    OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

                stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
                exists = AccountingOauth2.objects.filter(company=pk).first()

                if exists:
                    exists.accessToken = stored_values['oauth_token']
                    exists.realmId = oauth_verifier
                    exists.accessSecretKey = stored_values['oauth_token_secret']
                    exists.tokenAcitvatedOn = stored_values['oauth_expires_at']
                    exists.tokenExpiryON = stored_values['oauth_authorization_expires_at']
                    exists.save()
                else:
                    auth = AccountingOauth2(accessToken=stored_values['oauth_token'],
                                            refreshToken='',
                                            realmId=oauth_verifier,
                                            accessSecretKey=stored_values['oauth_token_secret'],
                                            tokenAcitvatedOn=stored_values['oauth_expires_at'],
                                            tokenExpiryON=stored_values['oauth_authorization_expires_at'],
                                            company_id=pk)
                    auth.save()
                # auth_redirect_url = os.environ.get ('QBO_AUTH_REDIRECT_URL',
                #                                        'http://localhost:4200/coa-match/quickbooks')

                # auth_redirect_url = os.environ.get ('QBO_AUTH_REDIRECT_URL','http://ec2-52-207-28-114.compute-1.amazonaws.com/ix/coa-match/quickbooks')

                # return redirect(auth_redirect_url)

        except Exception as e:
            auth_cancel_url = settings.QBO_AUTH_CANCEL_URL
            Utils.send_company_misconfig(pk, e)
            return redirect(auth_cancel_url + '/error')
            #return Utils.dispatch_success(request, 'TOKEN_ALREADY_VALIDATED')

        auth_redirect_url = settings.XERO_AUTH_REDIRECT_URL
        return redirect(auth_redirect_url)
示例#4
0
    def chart_of_accounts(self,id,request):
        """
        Get Chart of Accounts From online
        :param company: Company ID
        :return: Response
        """

        try:
            # login_status = Utils.get_login_status(company)
            # if login_status != LoginInfo.IN_PROGRESS:
            #     message = "Login Authentication Failed"
            #     return Utils.dispatch_failure(request,message)
            company = AccountsUtils.get_company(id)
            secret_keys = Utils.get_access_keys(id)
            # Get xero auth access information form xero connection
            auth_info = AccountingOauth2.objects.filter(company_id=id).values('accessToken', 'accessSecretKey',
                                                                                  'tokenAcitvatedOn', 'tokenExpiryON')
            if len(auth_info) == 0:
                return Utils.dispatch_failure(request, 'NO_TOKEN_AUTHENTICATION')

            for key, value in auth_info[0].items():
                OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})
            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE

            if len(stored_values) == 0:
                return Utils.dispatch_failure(request, "NO_TOKEN_AUTHENTICATION")

            auth = Utils.get_xero_auth(id)


            if AccountingConfiguration.PRIVATE == secret_keys.type:
                credentials = PrivateCredentials(**auth)
            else:
                credentials = PublicCredentials(**auth)

                if credentials.expired():
                    return Utils.dispatch_failure(request, 'NO_TOKEN_AUTHENTICATION')

            # Enable the access for accessing the reports from xero logged in account.
            xero = Xero(credentials)
            # Resave our verified credentials
            # stored_values = bind_auth_info(credentials, pk)

        except XeroException as e:
            if AccountingConfiguration.PRIVATE == secret_keys.type:
                error = ["%s" % e]
                return Utils.dispatch_failure(request, 'XERO_CONNECTION_ERROR', error)
            else:
                return Utils.dispatch_failure(request, "NO_TOKEN_AUTHENTICATION")
        try:
            chartofaccounts = xero.accounts.all()
            XeroAccountings.save_chart_of_accounts(company, chartofaccounts)
            return Utils.dispatch_success(request,"COA_FETECHED_SUCCESSFULLY")
        except XeroException as e:
            if AccountingConfiguration.PRIVATE == secret_keys.type:
                error = ["%s" % e]
                return Utils.dispatch_failure(request, 'XERO_CONNECTION_ERROR', error)
            else:
                return Utils.dispatch_failure(request, "NO_TOKEN_AUTHENTICATION")
        except Exception as e:
            error = ["%s" % e]
            return Utils.dispatch_failure(request, 'DATA_PARSING_ISSUE', error)
示例#5
0
    def trail_balance(self, pk, request):
        """
        Get Trail Balance From online
        :param company: Company Id
        :return: Response
        """
        try:
            # Checking Token Authentication available
            auth_info = AccountingOauth2.objects.filter(company_id=pk).values('accessToken', 'accessSecretKey',
                                                                             'tokenAcitvatedOn', 'tokenExpiryON')
            secret_keys = Utils.get_access_keys(pk)
            if len(auth_info) == 0:
                return Utils.dispatch_failure(request, "NO_TOKEN_AUTHENTICATION")

            for key, value in auth_info[0].items():
                OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})
            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE

            if len(stored_values) == 0:
                return Utils.dispatch_failure(request, "NO_TOKEN_AUTHENTICATION")


            # Checking Xero Connection Authentication available
            auth = Utils.get_xero_auth(pk)

            if AccountingConfiguration.PRIVATE == secret_keys.type:
                credentials = PrivateCredentials(**auth)
            else:
                credentials = PublicCredentials(**auth)

                if credentials.expired() or credentials is None:
                    return Utils.dispatch_failure(request, "NO_TOKEN_AUTHENTICATION")

            try:
                xero = Xero(credentials)
                xero.reports.get('TrialBalance')

            except XeroException as e:
                if AccountingConfiguration.PRIVATE == secret_keys.type:
                    error = ["%s" % e]
                    return Utils.dispatch_failure(request, 'XERO_CONNECTION_ERROR', error)
                else:
                    return Utils.dispatch_failure(request, "NO_TOKEN_AUTHENTICATION")
            try:
                meta = CompanyMeta.objects.filter(company_id=pk).first()
                if meta.monthly_reporting_current_period:
                    st = time.time()
                    from portalbackend.lendapi.v1.accounting.tasks import trial_balance_for_period
                    job = group(trial_balance_for_period.s(pk, i) for i in range(0, 23))
                    result = job.apply_async()
                else:
                    return Utils.dispatch_failure(request, 'MISSING_MONTHLY_REPORTING_CURRENT_PERIOD')

                while not result.ready():
                    continue
                return Utils.dispatch_success(request, 'TRIAL_BALANCE_RECEIVED_SUCCESS')
            except Exception as e:
                error = ["%s" % e]
                return Utils.dispatch_failure(request, 'DATA_PARSING_ISSUE', error)
        except Exception as e:
            return Utils.dispatch_failure(request, "INTERNAL_SERVER_ERROR")