Example #1
0
def rotate_user(post_data, get_data, ip=None):
    try:
        username=unknown_username
        user_cfg, api, data_to_send, requested_form, form_type, department_id, \
            generate_tasks_for_rec, internal_kwargs = eject_settings(post_data, get_data, ip)
        username = user_cfg.user.username

        if 'distribution_settings' in internal_kwargs and internal_kwargs['distribution_settings']:
            responsible_user_id = api.rotate_user(department_id, requested_form, form_type, \
                distribution_settings=internal_kwargs['distribution_settings'])
        else:
            responsible_user_id = api.rotate_user(department_id, requested_form, form_type)

        if responsible_user_id:
            api.update_entity(
                'contacts',
                post_data['id'],
                translate = False,
                call = True,
                updated_at = time.time(),
                responsible_user_id = responsible_user_id
            )

            count_down = 4
            tasks = []
            while count_down > 0 and not tasks:
                time.sleep(0.1)
                tasks = api.get_entity(
                    'tasks',
                    element_id=post_data['id']
                )['_embedded']['items']
                count_down -= 1

            for task in tasks:
                result = api.update_task(
                    task_id = task['id'],
                    updated_at = time.time(),
                    text = task['text'],
                    call=True,
                    responsible_user_id = responsible_user_id
                )

        user_cfg.save()

        return send_data_to_amo(post_data, get_data, None)

    except AmoException as e:
        context = e.context
        log_exception('', username, get_current_function(), context)
        if e.resend:
            send_data_to_amo.retry(exc=e, countdown=retry_coef * send_data_to_amo.request.retries)
            # send_data_to_amo.retry(exc=e, countdown=retry_coef)
    except Exception as e:
        log_exception('', username, get_current_function(), {
            'post data' : post_data,
            'get_data' : get_data
        })
        client.captureException()
Example #2
0
def send_data_to_amo(post_data, get_data, ip=None):
    try:
        username=unknown_username
        user_cfg, api, data_to_send, requested_form, form_type, department_id, \
            generate_tasks_for_rec, internal_kwargs = eject_settings(post_data, get_data, ip)
        username = user_cfg.user.username

        valid_data_to_send = True

        settings = user_cfg.config[form_type][requested_form]
        exception_types = {
            'email' : 'from.email',
            'onpbx' : 'phone'
        }
        if form_type in exception_types:
            insptected_field = post_data[exception_types[form_type]]
            for exception in settings.get('exceptions', []):
                if exception['exception'] in insptected_field:
                    valid_data_to_send = False
                    log_info('Data is excepted', user_cfg.user.username, get_current_function(), post_data)

        result = None
        if valid_data_to_send:
            result = api.send_order_data(
                contact_data = data_to_send['contact_data'],
                lead_data = data_to_send['lead_data'],
                company_data = data_to_send['company_data'],
                form = requested_form,
                form_type = form_type,
                department_id = department_id,
                generate_tasks_for_rec = generate_tasks_for_rec,
                **internal_kwargs
            )

        user_cfg.save()

        return result

    except AmoException as e:
        context = e.context
        log_exception('', username, get_current_function(), context)
        if e.resend:
            send_data_to_amo.retry(exc=e, countdown=retry_coef * send_data_to_amo.request.retries)
            # send_data_to_amo.retry(exc=e, countdown=retry_coef)
    except Exception as e:
        log_exception('', username, get_current_function(), {
            'post data' : post_data,
            'get_data' : get_data
        })
        client.captureException()
Example #3
0
def configurator(request):
    try:
        user_cfg = get_object_or_404(UserConfig, user=request.user)
        config = user_cfg.config

        request_path = request.path[1:]

        valid_path = False
        if not request_path:
            valid_path = True
        elif request_path == 'accesses':
            valid_path = True
        else:
            splited_path = request_path.split('/')
            if len(splited_path) == 2:
                if splited_path[0] in config and splited_path[1] in config[splited_path[0]]:
                    valid_path = True
                elif splited_path[0] in config and splited_path[1] == 'add_form':
                    valid_path = True

        if valid_path:
            return render(request, 'requestsHandler/configurator.html', {
                'config':config,
                'username': user_cfg.user.username
            })
        else:
            raise Http404('Path %s wasnt found' % request.path[1:])

    except AmoException as e:
        context = e.context
        log_exception('', request.user.username, get_current_function(), context)
        return HttpResponseBadRequest()
Example #4
0
def on_pbx_hook(post_data, get_data, ip=None):
    try:
        username=unknown_username
        user_cfg, api, data_to_send, requested_form, form_type, department_id, \
            generate_tasks_for_rec, internal_kwargs = eject_settings(post_data, get_data, ip)
        username = user_cfg.user.username

        if 'caller_number' in post_data:
            post_data['phone'] = post_data['caller_number']
            duplicates = api.get_entity(
                'contacts',
                query=post_data['caller_number'][1:]
            )['_embedded']['items']

            if duplicates:
                for contact in duplicates:
                    if 'created_at' in contact and time.time() - \
                        contact['created_at'] < 3*60:
                        return {}

                return send_data_to_amo(post_data, get_data, None)
            else:
                return {}
        else:
            return {}

    except AmoException as e:
        context = e.context
        log_exception('', username, get_current_function(), context)
        if e.resend:
            send_data_to_amo.retry(exc=e, countdown=retry_coef * send_data_to_amo.request.retries)
            # send_data_to_amo.retry(exc=e, countdown=retry_coef)
    except Exception as e:
        log_exception('', username, get_current_function(), {
            'post data' : post_data,
            'get_data' : get_data
        })
        client.captureException()
Example #5
0
def setConfig(request):
    try:
        if request.method != 'POST':
            return HttpResponseBadRequest('Waiting for POST request')

        got_config = json.loads(request.body.decode('utf-8'))
        if not 'form' in got_config:
            return HttpResponseBadRequest('Form field is required')

        user_cfg = get_object_or_404(UserConfig, user=request.user)
        config = user_cfg.config

        log_info('Config before updateing', user_cfg.user.username, get_current_function(), user_cfg.config)

        first_lvl_data = ['user', 'subdomain', 'hash']
        for field in first_lvl_data:
            if field in got_config:
                if field == 'time_to_complete_rec_task':
                    got_config[field] *= 60
                config[field] = got_config[field]

        if got_config['form'] == 'accesses':
            user_cfg.save()
            return HttpResponse(200)

        if not 'config_type' in got_config or not got_config['config_type'] in \
            config or not got_config['form'] in config[got_config['config_type']]:
            return HttpResponseNotFound('No form %s in config %s' % \
                (got_config['form'], user_cfg.user.username))

        form = got_config['form']
        config_type = got_config['config_type']
        settings = config[config_type][form]

        if not 'fields_to_check_dups' in settings:
            settings['fields_to_check_dups'] = {}
        if 'contact_fields_to_check_dups' in got_config:
            settings['fields_to_check_dups']['contacts'] = \
                [field['field'] for field in got_config['contact_fields_to_check_dups']]
        if 'company_fields_to_check_dups' in got_config:
            settings['fields_to_check_dups']['companies'] = \
                [field['field'] for field in got_config['company_fields_to_check_dups']]

        additional_params = ['rec_lead_task_text', 'time_to_complete_rec_task', \
            'generate_tasks_for_rec', 'tag_for_rec', 'exceptions']
        for param in additional_params:
            if param in got_config:
                if param == 'time_to_complete_rec_task':
                    got_config[param] *= 60
                settings[param] = got_config[param]

        if 'another_distribution' in got_config:
            splited_distr = got_config['another_distribution'].split('/')
            if len(splited_distr) == 2:
                settings['another_dist_type'] = splited_distr[0]
                settings['another_distribution'] = splited_distr[1]
            else:
                settings['another_distribution'] = not_chosen

        if '_embedded' in user_cfg.cache:
            if 'distribution_settings' in got_config:
                for idx, distr_settings in enumerate(got_config['distribution_settings']):
                    distr_user_id = next((user_id for user_id, user in user_cfg.cache \
                        ['_embedded']['users'].items() if user['name'] == distr_settings['user']), None)
                    got_config['distribution_settings'][idx]['user'] = distr_user_id

                if not 'distribution_settings' in settings:
                    settings['distribution_settings'] = got_config['distribution_settings']
                else:
                    pairs = zip(settings['distribution_settings'], got_config['distribution_settings'])
                    if any(x != y for x, y in pairs):
                        user_cfg.last_user_cache[config_type][form] = {}
                    settings['distribution_settings'] = got_config['distribution_settings']

            if 'responsible_user' in got_config:
                if got_config['responsible_user'] == one_by_one:
                    settings['responsible_user_id'] = one_by_one
                else:
                    for user_id, user in user_cfg.cache['_embedded']['users'].items():
                        if user['name'] == got_config['responsible_user']:
                             settings['responsible_user_id'] = user_id

            if 'department' in got_config:
                # if got_config['department'] == zero_department:
                #     settings['department_id'] = 0
                # el
                if got_config['department'] == not_chosen:
                    settings['department_id'] = not_chosen
                else:
                    for group_id, group in user_cfg.cache['_embedded']['groups'].items():
                        if group['name'] == got_config['department']:
                             settings['department_id'] = int(group_id)

            if not 'pipelines' in settings:
                settings['pipelines'] = {}
            if 'status_for_new' in got_config:
                settings['pipelines']['status_for_new'] = \
                    find_pipline_id(user_cfg.cache['_embedded']['pipelines'], got_config['status_for_new'])
            if 'status_for_rec' in got_config:
                settings['pipelines']['status_for_rec'] = \
                    find_pipline_id(user_cfg.cache['_embedded']['pipelines'], got_config['status_for_rec'])

            if 'contact_fields' in got_config:
                settings['contact_data'] = {}
                for field in got_config['contact_fields']:
                    settings['contact_data'][field['amoCRM']] = field['site']

            if 'company_fields' in got_config:
                settings['company_data'] = {}
                for field in got_config['company_fields']:
                    settings['company_data'][field['amoCRM']] = field['site']

            if 'lead_fields' in got_config:
                settings['lead_data'] = {}
                for field in got_config['lead_fields']:
                    settings['lead_data'][field['amoCRM']] = field['site']


        user_cfg.save()

        log_info('Updated config', user_cfg.user.username, get_current_function(), user_cfg.config)
        return HttpResponse(200)

    except AmoException as e:
        context = e.context
        log_exception('', request.user.username, get_current_function(), context)
        return HttpResponseBadRequest()
Example #6
0
def eject_settings(post_data, get_data, ip=None):
    try:
        if 'public_hash' in get_data:
            user_cfg = UserConfig.objects.get(public_hash=get_data['public_hash'])
        elif 'private_hash' in get_data:
            user_cfg = UserConfig.objects.get(private_hash=get_data['private_hash'])
        else:
            raise Exception('No hash sent!')
    except UserConfig.DoesNotExist:
        log_error('User cfg was not found!', unknown_username, get_current_function(), post_data)
        raise

    username = user_cfg.user.username
    log_info('Got data', user_cfg.user.username, get_current_function(), post_data)

    if not user_cfg.user.is_active:
        log_info('User is not active ', user_cfg.user.username, \
            get_current_function(), user_cfg.account_rights)
        raise Exception('User not active!')

    if not 'form_type' in get_data or not get_data['form_type'] in user_cfg.config:
        message = 'No form type in config %s' % user_cfg.user.username
        raise AmoException(message, {})
    form_type = get_data['form_type']

    if not 'form' in get_data or not get_data['form'] in user_cfg.config[form_type]:
        message = 'No form in config %s' % user_cfg.user.username
        raise AmoException(message, {})
    requested_form = get_data['form']

    api = AmoIntegr(user_cfg)
    settings = user_cfg.config[form_type][requested_form]

    data_to_send, generate_tasks_for_rec, department_id, internal_kwargs = conform_fields(
        post_data, settings, user_cfg.account_rights, ip)

    if 'distribution_settings' in settings and settings['distribution_settings']:
        internal_kwargs['distribution_settings'] = \
           settings['distribution_settings']

    if 'another_distribution' in settings and 'another_dist_type' in settings:
        another_distribution = settings['another_distribution']
        type_another_form = settings['another_dist_type']

        if another_distribution != not_chosen and \
            (another_distribution != requested_form or type_another_form != form_type) and \
            another_distribution and type_another_form and \
            type_another_form in user_cfg.config and \
            another_distribution in user_cfg.config[type_another_form]:

            another_conform = user_cfg.config[type_another_form][another_distribution]
            department_id = -1
            if 'department_id' in another_conform and \
                another_conform['department_id'] != not_chosen:
                department_id = another_conform['department_id']
            internal_kwargs['responsible_user_id'] = one_by_one
            if 'responsible_user_id' in another_conform and \
                another_conform['responsible_user_id'] != one_by_one:
                internal_kwargs['responsible_user_id'] = another_conform['responsible_user_id']
            internal_kwargs['distribution_settings'] = []
            if 'distribution_settings' in another_conform and \
                another_conform['distribution_settings']:
                internal_kwargs['distribution_settings'] = another_conform['distribution_settings']
            requested_form = another_distribution
            form_type = type_another_form

    return user_cfg, api, data_to_send, requested_form, form_type, department_id, \
        generate_tasks_for_rec, internal_kwargs