<commit_before>import datetime
import logging
import uuid

from dateutil.parser import parse
from djconnectwise.api import CompanyAPIRestClient, ServiceAPIRestClient
from djconnectwise.api import SystemAPIClient
from djconnectwise.models import ServiceTicket, Company, ConnectWiseBoardStatus
from djconnectwise.models import SyncJob
from djconnectwise.models import TicketPriority, Member, Project
from djconnectwise.models import TicketStatus, ServiceTicketAssignment

from django.core.exceptions import ObjectDoesNotExist
from django.core.files.base import ContentFile
from django.utils import timezone


logger = logging.getLogger(__name__)


class InvalidStatusError(Exception):
    pass


class CompanySynchronizer:
    """
    Coordinates retrieval and demarshalling of ConnectWise JSON
    Company instances.
    """

    def __init__(self, *args, **kwargs):
        self.company_client = CompanyAPIRestClient()
        self.companies = self.load_company_dict()

    def load_company_dict(self):
        """
        Returns a dict of all companies that reside locally
        """
        return {c.id: c for c in Company.objects.all()}

    def _assign_field_data(self, company, api_company):
        """
        Assigns field data from an api_company instance
        to a local Company model instance
        """
        company.company_name = api_company['name']
        company.company_identifier = api_company['identifier']
        company.phone_number = api_company['phoneNumber']
        company.fax_number = api_company['faxNumber']
        company.address_line1 = api_company['addressLine1']
        company.address_line2 = api_company['addressLine1']
        company.city = api_company['city']
        company.state_identifier = api_company['state']
        company.zip = api_company['zip']
        company.created = timezone.now()

    def sync_companies(self):
        api_company_data = self.company_client.get()
        created_count = 0
        updated_count = 0

        for api_company in api_company_data:
            company_id = api_company['id']

            try:
                company = Company.objects.get(id=company_id)
                updated_count += 1
            except ObjectDoesNotExist:
                company = Company.objects.create(id=company_id)
                created_count += 1

            self._assign_field_data(company, api_company)
            company.save()

        msg = 'Synced Companies - Created: {} , Updated: {}'.format(
            created_count, updated_count)

        logger.info('Synced Companies - Created: {} , Updated: {}'.format(
            created_count, updated_count))

        return created_count, updated_count, msg

    def get_or_create_company(self, company_id):
        """
        Creates and returns a Company instance if it does not already exist
        """
        # Assign company to ticket. Create a new company if it does not already
        # exist

        company = self.companies.get(company_id)
        if not company:
            # fetch company from api
            api_company = self.company_client.by_id(company_id)
            company = Company.objects.create(id=company_id)

            self._assign_field_data(company, api_company)
            company.save()
            logger.info('Company Created: {}'.format(company_id))
            self.companies[company.id] = company
        return company


class ServiceTicketSynchronizer:
    """
    Coordinates retrieval and demarshalling of ConnectWise JSON
    objects to the local counterparts.
    """

    def __init__(self, reset=False):

        self.company_synchronizer = CompanySynchronizer()
        self.reset = reset
        self.last_sync_job = None
        extra_conditions = ''
        sync_job_qset = SyncJob.objects.all()

        if sync_job_qset.exists() and not self.reset:
            self.last_sync_job = sync_job_qset.last()
            extra_conditions = "lastUpdated > [{0}]".format(
                self.last_sync_job.start_time.isoformat())
            logger.info(
                'ServiceTicket Extra Conditions: {0}'.format(extra_conditions))
        else:
            # absence of a sync job indicates that this is an initial/full
            # sync, in whichcase we do not want to retrieve closed tickets
            extra_conditions = 'ClosedFlag = False'

        self.service_client = ServiceAPIRestClient(
            extra_conditions=extra_conditions)<commit_msg>#162 - Made naming scheme more consistent<commit_after>import datetime
import logging
import uuid

from dateutil.parser import parse
from djconnectwise.api import CompanyAPIClient, ServiceAPIClient
from djconnectwise.api import SystemAPIClient
from djconnectwise.models import ServiceTicket, Company, ConnectWiseBoardStatus
from djconnectwise.models import SyncJob
from djconnectwise.models import TicketPriority, Member, Project
from djconnectwise.models import TicketStatus, ServiceTicketAssignment

from django.core.exceptions import ObjectDoesNotExist
from django.core.files.base import ContentFile
from django.utils import timezone


logger = logging.getLogger(__name__)


class InvalidStatusError(Exception):
    pass


class CompanySynchronizer:
    """
    Coordinates retrieval and demarshalling of ConnectWise JSON
    Company instances.
    """

    def __init__(self, *args, **kwargs):
        self.company_client = CompanyAPIClient()
        self.companies = self.load_company_dict()

    def load_company_dict(self):
        """
        Returns a dict of all companies that reside locally
        """
        return {c.id: c for c in Company.objects.all()}

    def _assign_field_data(self, company, api_company):
        """
        Assigns field data from an api_company instance
        to a local Company model instance
        """
        company.company_name = api_company['name']
        company.company_identifier = api_company['identifier']
        company.phone_number = api_company['phoneNumber']
        company.fax_number = api_company['faxNumber']
        company.address_line1 = api_company['addressLine1']
        company.address_line2 = api_company['addressLine1']
        company.city = api_company['city']
        company.state_identifier = api_company['state']
        company.zip = api_company['zip']
        company.created = timezone.now()

    def sync_companies(self):
        api_company_data = self.company_client.get()
        created_count = 0
        updated_count = 0

        for api_company in api_company_data:
            company_id = api_company['id']

            try:
                company = Company.objects.get(id=company_id)
                updated_count += 1
            except ObjectDoesNotExist:
                company = Company.objects.create(id=company_id)
                created_count += 1

            self._assign_field_data(company, api_company)
            company.save()

        msg = 'Synced Companies - Created: {} , Updated: {}'.format(
            created_count, updated_count)

        logger.info('Synced Companies - Created: {} , Updated: {}'.format(
            created_count, updated_count))

        return created_count, updated_count, msg

    def get_or_create_company(self, company_id):
        """
        Creates and returns a Company instance if it does not already exist
        """
        # Assign company to ticket. Create a new company if it does not already
        # exist

        company = self.companies.get(company_id)
        if not company:
            # fetch company from api
            api_company = self.company_client.by_id(company_id)
            company = Company.objects.create(id=company_id)

            self._assign_field_data(company, api_company)
            company.save()
            logger.info('Company Created: {}'.format(company_id))
            self.companies[company.id] = company
        return company


class ServiceTicketSynchronizer:
    """
    Coordinates retrieval and demarshalling of ConnectWise JSON
    objects to the local counterparts.
    """

    def __init__(self, reset=False):

        self.company_synchronizer = CompanySynchronizer()
        self.reset = reset
        self.last_sync_job = None
        extra_conditions = ''
        sync_job_qset = SyncJob.objects.all()

        if sync_job_qset.exists() and not self.reset:
            self.last_sync_job = sync_job_qset.last()
            extra_conditions = "lastUpdated > [{0}]".format(
                self.last_sync_job.start_time.isoformat())
            logger.info(
                'ServiceTicket Extra Conditions: {0}'.format(extra_conditions))
        else:
            # absence of a sync job indicates that this is an initial/full
            # sync, in whichcase we do not want to retrieve closed tickets
            extra_conditions = 'ClosedFlag = False'

        self.service_client = ServiceAPIClient(
            extra_conditions=extra_conditions)
{'fraction_non_alphanumeric': 0.07882326521446216, 'fraction_numerical': 0.0025825286323826633, 'mean_word_length': 2.6564039408866993, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3909469', 'n_tokens_mistral': 2413, 'n_tokens_neox': 2332, 'n_words': 606}