Esempio n. 1
0
def deleteForm(request):
    try:
        if request.method != 'POST':
            return HttpResponseBadRequest('Waiting for POST request')

        got_data = json.loads(request.body.decode('utf-8'))
        if not 'name' in got_data:
            return HttpResponseBadRequest('name is needed')
        if not 'type' in got_data or not got_data['type'] in config_types:
            return HttpResponseBadRequest('bad type')

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

        name = got_data['name']
        form_type = got_data['type']

        if name and name in config[form_type]:
            config[form_type].pop(name, None)
            luser = user_cfg.last_user_cache
            if form_type in luser and name in luser[form_type]:
                luser[form_type].pop(name, None)

        user_cfg.save()

        log_info('Deleted form ', 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()
Esempio n. 2
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()
Esempio n. 3
0
def newForm(request):
    try:
        if request.method != 'POST':
            return HttpResponseBadRequest('Waiting for POST request')

        got_data = json.loads(request.body.decode('utf-8'))

        if not 'name' in got_data:
            return HttpResponseBadRequest('name is needed')
        if not 'type' in got_data or not got_data['type'] in config_types:
            return HttpResponseBadRequest('bad type')

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

        name = got_data['name']
        form_type = got_data['type']

        if name and not name in get_config_forms(config):
            config[form_type][name] = {}
            if config_types[form_type]:
                config[form_type][name]['allowed_enum'] = config_types[form_type]
        else:
            return HttpResponseBadRequest()

        user_cfg.save()

        log_info('New form ', 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()
Esempio n. 4
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()
Esempio n. 5
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()
Esempio n. 6
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()
Esempio n. 7
0
def getConfig(request):
    try:
        if request.method != 'GET':
            return HttpResponseBadRequest('Waiting for GET request')
        if not 'hash' in request.GET:
            return HttpResponseBadRequest('Hash parameter needed!')
        if not 'form_type' in request.GET:
            return HttpResponseBadRequest('Form type parameter needed!')

        requested_form = request.GET['hash']
        form_type = request.GET['form_type']

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

        config = user_cfg.config
        try:
            api = AmoIntegr(user_cfg)
            api.update_cache()
            user_cfg.save()
            config['valid_amo'] = True
        except AmoException as e:
            config['valid_amo'] = False

        if requested_form != 'accesses':
            if not form_type in config:
                return HttpResponseNotFound('No type %s in config %s' % \
                    (form_type, user_cfg.user.username))
            if not requested_form in config[form_type]:
                return HttpResponseNotFound('No form %s in config %s' % \
                    (requested_form, user_cfg.user.username))

        if '_embedded' in user_cfg.cache and requested_form != 'accesses':
            config['forms'] = []
            for t in config_types:
                if t in config:
                    config['forms'] += [t+'/'+form_name for form_name in config[t]]
            config['forms'].append(not_chosen)

            settings = config[form_type][requested_form]

            if 'another_distribution' in settings and 'another_dist_type' in settings and \
                settings['another_dist_type'] in config and settings['another_distribution'] \
                in config[settings['another_dist_type']]:

                config['chosen_distr'] = settings['another_dist_type']+'/'+settings['another_distribution']
            else:
                config['chosen_distr'] = not_chosen

            config['allowed_fields'] = {}
            config['allowed_statuses'] = []

            if not 'fields_to_check_dups' in settings:
                settings['fields_to_check_dups'] = {}

            additional_field_options = ['name', 'default_name', 'tags']
            contact_field_options = [field for field in user_cfg.fields_cache \
                ['contacts'] if not RepresentsInt(field)]
            contact_field_options += additional_field_options

            company_field_options = [field for field in user_cfg.fields_cache \
                ['companies'] if not RepresentsInt(field)]
            company_field_options += additional_field_options

            lead_field_options = [field for field in user_cfg.fields_cache \
                ['leads'] if not RepresentsInt(field)]
            lead_field_options += additional_field_options

            config['allowed_fields'] = {
                'contacts' : contact_field_options,
                'companies' : company_field_options,
                'leads' : lead_field_options
            }

            config['allowed_users'] = [user['name'] for user_id, user in \
                user_cfg.cache['_embedded']['users'].items() if not user['is_free'] \
                and user['is_active']]
            config['allowed_users'].append(one_by_one)

            for pipeline_id, pipeline in user_cfg.cache['_embedded']['pipelines'].items():
                for status_id, status in pipeline['statuses'].items():
                    if not int(status_id) in ending_statuses:
                        config['allowed_statuses'].append(pipeline['name']+'/'+status['name'])

            if 'responsible_user_id' in settings and settings['responsible_user_id'] != one_by_one:
                config['default_user'] = [user['name'] for user_id, user in
                    user_cfg.cache['_embedded']['users'].items() if
                    int(user_id) == int(settings['responsible_user_id'])][0]
            else:
                config['default_user'] = one_by_one

            if user_cfg.cache['_embedded']['groups']:
                config['allowed_departments'] = [group['name'] for group_id, group in
                    user_cfg.cache['_embedded']['groups'].items()]
            else:
                config['allowed_departments'] = []
            # config['allowed_departments'].append(zero_department)
            config['allowed_departments'].append(not_chosen)

            config['default_department'] = not_chosen
            if 'department_id' in settings:
                # settings['department_id'] != 0 and
                if settings['department_id'] != not_chosen:
                    config['default_department'] = [group['name'] for group_id, group in
                    user_cfg.cache['_embedded']['groups'].items() if
                        int(group_id) == int(settings['department_id'])][0]
                # elif settings['department_id'] == 0:
                #     config['default_department'] = zero_department

            if 'pipelines' in settings:
                for pipeline_id, pipeline in user_cfg.cache['_embedded']['pipelines'].items():
                    for status_id, status in pipeline['statuses'].items():
                        if 'status_for_new' in settings['pipelines'] and \
                            int(status_id) == int(settings['pipelines']['status_for_new']):

                            config['status_for_new'] = pipeline['name']+'/'+status['name']

                        if 'status_for_rec' in settings['pipelines'] and \
                            int(status_id) == int(settings['pipelines']['status_for_rec']):

                            config['status_for_rec'] = pipeline['name']+'/'+status['name']

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

            config['weekdays'] = weekdays
            config['form_type'] = form_type
            config['public_hash'] = user_cfg.public_hash
            config['private_hash'] = user_cfg.private_hash

        log_info('Response', user_cfg.user.username, get_current_function(), config)
        return HttpResponse(json.dumps(config, sort_keys=True, ensure_ascii=False))

    except AmoException as e:
        context = e.context
        log_exception('', request.user.username, get_current_function(), context)
        return HttpResponseBadRequest()
Esempio n. 8
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()