<commit_before>import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

from rest_framework.views import APIView
from rest_framework.response import Response

from simple_salesforce import Salesforce
from django_countries import countries

from lims.users.serializers import UserSerializer
from lims.orders.models import Order
from lims.pricebook.models import Price, PriceBook
from lims.projects.models import Project
from lims.permissions.permissions import ExtendedObjectPermissions
from .models import CRMAccount, CRMProject, CRMQuote


class CRMUserView(APIView):
    """
    Deals with the creation and upkeep of SalesForce account and
    contact information.
    """
    permission_classes = (ExtendedObjectPermissions,)
    queryset = CRMAccount.objects.none()

    def post(self, request, format=None):
        """
        Adds the necessary account and contact data to Salesforce if they do not exist.
        """

        if settings.ENABLE_CRM:
            sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                            username=settings.SALESFORCE_USERNAME,
                            password=<PASSWORD>,
                            security_token=settings.SALESFORCE_TOKEN)

            contact_id = ''
            account_id = ''

            add_only = request.data.get('add_only', False)

            contacts_query = ("SELECT Id,AccountId,Account.name,FirstName,LastName,Email "
                              "FROM Contact WHERE Email = '{}'").format(request.data['email'])
            contacts = sf.query(contacts_query)
            if contacts['totalSize'] > 0:
                contact_id = contacts['records'][0]['Id']
                account_id = contacts['records'][0]['AccountId']
                account_name = contacts['records'][0]['Account']['Name']
            elif add_only is False:
                account_query = "SELECT Id,Name FROM Account WHERE Name = '{}'".format(
                    request.data['institution_name'])
                accounts = sf.query(account_query)
                if accounts['totalSize'] == 0:
                    result = sf.Account.create({'Name': request.data['institution_name']})
                    account_id = result['id']
                else:
                    account_id = accounts['records'][0]['Id']

                country_codes = dict((value, key) for key, value in dict(countries).items())

                contact = sf.Contact.create({
                    'FirstName': request.data['first_name'],
                    'LastName': request.data['last_name'],
                    'AccountId': account_id,
                    'Email': request.data['email'],
                    'MailingStreet':
                        request.data['address_1'] + '\n ' + request.data.get('address_2', ''),
                    'MailingCity': request.data['city'],
                    'MailingPostalCode': request.data['postcode'],
                    'MailingCountryCode': country_codes[request.data['country']],
                })
                contact_id = contact['id']

            if contact_id and account_id:
                user = User.objects.get(email=request.data['email'])

                details = CRMAccount(contact_identifier=contact_id,
                                     account_identifier=account_id,
                                     account_name=account_name,
                                     user=user)
                details.save()

                user = User.objects.get(email=request.data['email'])

                s = UserSerializer(user)
                return Response(s.data)
            return Response({'No CRM data added to account'}, status=204)
        return Response({'message': 'CRM is currently disabled'}, status=501)

    def delete(self, request, format=None):
        if settings.ENABLE_CRM:
            email = request.query_params.get('email', None)
            if email:
                try:
                    user = User.objects.get(email=email)
                    crm_account = CRMAccount.objects.get(user=user)
                except:
                    return Response({'message': 'User or account not found'}, status=404)
                else:
                    crm_account.delete()
                    return Response({'message': 'CRM account removed'})
            return Response({'message': 'Please provide an email address'}, status=400)
        return Response({'message': 'CRM is currently disabled'}, status=501)


class CRMProjectView(APIView):
    """
    Fetch project information from CRM and create CRM objects
    """
    permission_classes = (ExtendedObjectPermissions,)
    queryset = CRMProject.objects.none()

    def get(self, request, format=None):
        """
        Lists all projects on Salesforce.
        """

        if settings.ENABLE_CRM:
            search = request.query_params.get('search', '')

            sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                            username=settings.SALESFORCE_USERNAME,
                            password=<PASSWORD>.<PASSWORD>_PASSWORD,
                            security_token=settings.SALESFORCE_TOKEN)

            projects_query = ("SELECT Id,Name,Description,Project_Status__c, CreatedDate "
                              "FROM Opportunity WHERE Name LIKE '%{}%'").format(search)
            projects = sf.query(projects_query)
            return Response({'results': projects['records'],
                             'meta': {'count': len(projects['records'])}})
        return Response({'message': 'CRM is currently disabled'}, status=501)

    def post(self, request, format=None):
        """
        Adds a project to Salesforce and creates references on system.
        """
        if settings.ENABLE_CRM:
            sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                            username=settings.SALESFORCE_USERNAME,
                            password=<PASSWORD>.<PASSWORD>,
                            security_token=settings.SALESFORCE_TOKEN)

            stage = 'Proposal/Price Quote'
            now = datetime.date.today()
            close_date = now + datetime.timedelta(days=30)

            name = request.data['name']
            account = request.data['account_id']

            project = Order.objects.get(pk=request.data['project_id'])<commit_msg>Fix error with missing ProjectStatus import<commit_after>import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

from rest_framework.views import APIView
from rest_framework.response import Response

from simple_salesforce import Salesforce
from django_countries import countries

from lims.users.serializers import UserSerializer
from lims.orders.models import Order
from lims.pricebook.models import Price, PriceBook
from lims.projects.models import Project, ProjectStatus
from lims.permissions.permissions import ExtendedObjectPermissions
from .models import CRMAccount, CRMProject, CRMQuote


class CRMUserView(APIView):
    """
    Deals with the creation and upkeep of SalesForce account and
    contact information.
    """
    permission_classes = (ExtendedObjectPermissions,)
    queryset = CRMAccount.objects.none()

    def post(self, request, format=None):
        """
        Adds the necessary account and contact data to Salesforce if they do not exist.
        """

        if settings.ENABLE_CRM:
            sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                            username=settings.SALESFORCE_USERNAME,
                            password=<PASSWORD>,
                            security_token=settings.SALESFORCE_TOKEN)

            contact_id = ''
            account_id = ''

            add_only = request.data.get('add_only', False)

            contacts_query = ("SELECT Id,AccountId,Account.name,FirstName,LastName,Email "
                              "FROM Contact WHERE Email = '{}'").format(request.data['email'])
            contacts = sf.query(contacts_query)
            if contacts['totalSize'] > 0:
                contact_id = contacts['records'][0]['Id']
                account_id = contacts['records'][0]['AccountId']
                account_name = contacts['records'][0]['Account']['Name']
            elif add_only is False:
                account_query = "SELECT Id,Name FROM Account WHERE Name = '{}'".format(
                    request.data['institution_name'])
                accounts = sf.query(account_query)
                if accounts['totalSize'] == 0:
                    result = sf.Account.create({'Name': request.data['institution_name']})
                    account_id = result['id']
                else:
                    account_id = accounts['records'][0]['Id']

                country_codes = dict((value, key) for key, value in dict(countries).items())

                contact = sf.Contact.create({
                    'FirstName': request.data['first_name'],
                    'LastName': request.data['last_name'],
                    'AccountId': account_id,
                    'Email': request.data['email'],
                    'MailingStreet':
                        request.data['address_1'] + '\n ' + request.data.get('address_2', ''),
                    'MailingCity': request.data['city'],
                    'MailingPostalCode': request.data['postcode'],
                    'MailingCountryCode': country_codes[request.data['country']],
                })
                contact_id = contact['id']

            if contact_id and account_id:
                user = User.objects.get(email=request.data['email'])

                details = CRMAccount(contact_identifier=contact_id,
                                     account_identifier=account_id,
                                     account_name=account_name,
                                     user=user)
                details.save()

                user = User.objects.get(email=request.data['email'])

                s = UserSerializer(user)
                return Response(s.data)
            return Response({'No CRM data added to account'}, status=204)
        return Response({'message': 'CRM is currently disabled'}, status=501)

    def delete(self, request, format=None):
        if settings.ENABLE_CRM:
            email = request.query_params.get('email', None)
            if email:
                try:
                    user = User.objects.get(email=email)
                    crm_account = CRMAccount.objects.get(user=user)
                except:
                    return Response({'message': 'User or account not found'}, status=404)
                else:
                    crm_account.delete()
                    return Response({'message': 'CRM account removed'})
            return Response({'message': 'Please provide an email address'}, status=400)
        return Response({'message': 'CRM is currently disabled'}, status=501)


class CRMProjectView(APIView):
    """
    Fetch project information from CRM and create CRM objects
    """
    permission_classes = (ExtendedObjectPermissions,)
    queryset = CRMProject.objects.none()

    def get(self, request, format=None):
        """
        Lists all projects on Salesforce.
        """

        if settings.ENABLE_CRM:
            search = request.query_params.get('search', '')
            sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                            username=settings.SALESFORCE_USERNAME,
                            password=settings.SALESFORCE_PASSWORD,
                            security_token=settings.SALESFORCE_TOKEN)

            projects_query = ("SELECT Id,Name,Description,Project_Status__c, CreatedDate "
                              "FROM Opportunity WHERE Name LIKE '%{}%'").format(search)
            projects = sf.query(projects_query)
            return Response({'results': projects['records'],
                             'meta': {'count': len(projects['records'])}})
        return Response({'message': 'CRM is currently disabled'}, status=501)

    def post(self, request, format=None):
        """
        Adds a project to Salesforce and creates references on system.
        """
        if settings.ENABLE_CRM:
            sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                            username=settings.SALESFORCE_USERNAME,
                            password=<PASSWORD>,
                            security_token=settings.SALESFORCE_TOKEN)

            stage = 'Proposal/Price Quote'
            now = datetime.date.today()
            close_date = now + datetime.timedelta(days=30)

            name = request.data['name']
            account = request.data['account_id']

            project = Order.objects.get(pk=request.data['project_id'])
{'fraction_non_alphanumeric': 0.10186836188851849, 'fraction_numerical': 0.004341421815644624, 'mean_word_length': 1.978526899099515, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1630492', 'n_tokens_mistral': 3328, 'n_tokens_neox': 3152, 'n_words': 711}