Beispiel #1
0
 def test_enable_flag_boolean_exists(self):
     FlagState.objects.create(
         name="DB_FLAG", condition="boolean", value="False"
     )
     self.assertFalse(flag_enabled("DB_FLAG"))
     enable_flag("DB_FLAG")
     self.assertTrue(flag_enabled("DB_FLAG"))
Beispiel #2
0
 def create(self, **obj_data):
     obj = super().create(**obj_data)
     if flag_enabled('PUSHING_SUBDOMAIN_TO_ROUTE53'):
         if obj.subdomain:
             self.push_to_route53(obj)
     if flag_enabled('GIVING_DEFAULT_ITEMS_WHEN_PROFILE_CREATED'):
         self.give_items(obj)
     return obj
    def get_context_data(self, **kwargs):
        context = super(ComplaintLandingView, self).get_context_data(**kwargs)

        ccdb_status_json = self.get_ccdb_status_json()
        context.update(self.is_ccdb_out_of_date(ccdb_status_json))

        context.update({
            'technical_issues':
            flag_enabled('CCDB_TECHNICAL_ISSUES'),
            'ccdb_content_updates':
            flag_enabled('CCDB_CONTENT_UPDATES')
        })

        return context
Beispiel #4
0
def create_flag(request):
    """ Create a new flag.
    This will add a FlagState object with a custom name and a boolean: False
    condition """
    if request.method == 'POST':
        form = NewFlagForm(request.POST,
                           initial={
                               'condition': 'path matches',
                               'value': '/foo',
                               'required': False,
                           })
        if form.is_valid():
            form.save()
            if flag_enabled('WAGTAILFLAGS_ADMIN_BIG_LIST'):
                return redirect('{flags_list}#{flag_name}'.format(
                    flags_list=resolve_url('wagtailflags:list'),
                    flag_name=form.instance.name))
            else:
                return redirect('wagtailflags:flag_index',
                                name=form.instance.name)
    else:
        form = NewFlagForm()

    context = dict(form=form)
    return render(request, 'wagtailflags/flags/create_flag.html', context)
Beispiel #5
0
def edit_condition(request, name, condition_pk=None):
    flag = get_flags().get(name)
    try:
        condition = FlagState.objects.get(pk=condition_pk)
    except FlagState.DoesNotExist:
        condition = None

    if request.method == 'POST':
        form = FlagStateForm(request.POST,
                             initial={'name': name},
                             instance=condition)
        if form.is_valid():
            form.save()

            if flag_enabled('WAGTAILFLAGS_ADMIN_BIG_LIST'):
                return redirect('{flags_list}#{flag_name}'.format(
                    flags_list=resolve_url('wagtailflags:list'),
                    flag_name=form.instance.name))
            else:
                return redirect('wagtailflags:flag_index',
                                name=form.instance.name)

    else:
        form = FlagStateForm(initial={'name': name}, instance=condition)

    context = {
        'flag': flag,
        'form': form,
        'condition_str': str(condition),
        'condition_pk': condition_pk,
    }
    return render(request, 'wagtailflags/flags/edit_condition.html', context)
    def get_page_set(self):
        if flag_enabled('ELASTICSEARCH_FILTERABLE_LISTS'):
            categories = self.cleaned_data.get('categories')

            # If no categories are submitted by the form
            if categories == []:
                # And we have defined a prexisting set of categories
                # to limit results by Using CategoryFilterableMixin
                if self.filterable_categories not in ([], None):
                    # Search for results only within the provided categories
                    categories = ref.get_category_children(
                        self.filterable_categories)

            return FilterablePagesDocumentSearch(
                prefix=self.filterable_root,
                topics=self.cleaned_data.get('topics'),
                categories=categories,
                authors=self.cleaned_data.get('authors'),
                to_date=self.cleaned_data.get('to_date'),
                from_date=self.cleaned_data.get('from_date'),
                title=self.cleaned_data.get('title'),
                archived=self.cleaned_data.get('archived'),
                order_by=self.get_order_by()).search()
        else:
            query = self.generate_query()
            return self.filterable_pages.filter(query).distinct().order_by(
                '-date_published'
            )
Beispiel #7
0
def user_successfully_activated(sender, user, request, **kwargs):
    logger.info("Received user activation signal for %s", user.username)

    # Log the user in, if this isn't the result of a password reset
    # The password reset form automatically logs the user in and activates.
    # But when it does so, it sends None for the request.
    # So when the user activates without resetting the password, the behavior
    # should be the same - the user should be automatically logged in.
    if request:
        auth_login(request, user)

    if flag_enabled("SEND_WELCOME_EMAIL"):
        text_body_template = loader.get_template(
            "emails/welcome_email_body.txt")
        text_body_message = text_body_template.render()

        html_body_template = loader.get_template(
            "emails/welcome_email_body.html")
        html_body_message = html_body_template.render()

        subject_template = loader.get_template(
            "emails/welcome_email_subject.txt")
        subject_message = subject_template.render()

        # Send welcome email
        message = EmailMultiAlternatives(
            subject=subject_message.rstrip(),
            body=text_body_message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=[user.email],
            reply_to=[settings.DEFAULT_FROM_EMAIL],
        )
        message.attach_alternative(html_body_message, "text/html")
        message.send()
Beispiel #8
0
 def suggest(self, request):
     suggestion = SearchQuerySet().spelling_suggestion(self.search_term)
     if (suggestion and suggestion != self.search_term and
             request.GET.get('correct', '1') == '1' and
             flag_enabled('ASK_SEARCH_TYPOS', request=request)):
         self.queryset = self.query_base.filter(content=suggestion)
         self.search_term, self.suggestion = suggestion, self.search_term
Beispiel #9
0
    def populate(cls, upc):
        product_data = None
        if flag_enabled('USE_LIMITED_API_CALLS'):
            API_klass_list = [
                Open_Food_Facts,
            ]

        else:
            API_klass_list = [
                Open_Food_Facts, UPC_Database, EAN_Data, EAN_Search
            ]
        if settings.MOCK_API_CALLS:
            API_klass_list = [
                Mock_API,
            ]

        for klass in API_klass_list:
            try:
                product_data = klass(upc=upc).execute()
                break
            except ProductNotFoundException:
                print('not found')
            except Exception as err:
                print(err)
                # continue anyway
        if product_data is None:
            print('not found anywhere - create placeholder')
            product_data = cls.create_placeholder_product(upc)
        p = Product(**product_data)
        p.save()
        return p
Beispiel #10
0
def importar_csv(request): #Importa datos de análisis
    context = {}
    error_log = {}
    if request.method != 'POST': #Si no se envía un post, el acceso es denegado
        raise Http404
    user_logged = IFCUsuario.objects.get(user = request.user)  # Obtener el usuario logeado
    #Si el rol del usuario no es servicio al cliente, director o superusuario, el acceso es denegado
    if not ('importar_csv' in request.session['permissions']):
        raise Http404
    response_code = 0
    if request.method == 'POST':
        if flag_enabled('Importar_Analisis', request=request):
            form = ImportarAnalisisForm(request.POST, request.FILES)
            if form.is_valid():
                error_log, aux = handle_upload_document(request.FILES['csv_analisis'],)
            else:
                raise Http404

    error_count = len(error_log)

    context = {
        'error_count' : error_count,
        'error_log' : error_log,
    }
    return render(request, 'ventas/importar_csv_resultado.html', context)
Beispiel #11
0
def flag_index(request, name):
    flag = get_flags().get(name)

    # If there's a database boolean condition, fetch it and treat it as a
    # on/off switch
    if 'enable' in request.GET or 'disable' in request.GET:
        db_boolean_condition = next(
            (c for c in flag.conditions if c.condition == 'boolean'
             and getattr(c, 'obj', None) is not None), None)

        if db_boolean_condition is None:
            boolean_condition_obj = FlagState.objects.create(
                name=name, condition='boolean', value='True')
        else:
            boolean_condition_obj = db_boolean_condition.obj

        if 'enable' in request.GET and not bool_enabled(flag):
            boolean_condition_obj.value = True
        elif 'disable' in request.GET and bool_enabled(flag):
            boolean_condition_obj.value = False

        boolean_condition_obj.save()

        if flag_enabled('WAGTAILFLAGS_ADMIN_BIG_LIST'):
            return redirect('{flags_list}#{flag_name}'.format(
                flags_list=resolve_url('wagtailflags:list'), flag_name=name))
        else:
            return redirect('wagtailflags:flag_index', name=name)

    context = {
        'flag': flag,
    }
    return render(request, 'wagtailflags/flags/flag_index.html', context)
    def is_ccdb_out_of_date(self, res_json):
        """Parse JSON describing CCDB status to determine if it is out of date.

        Returns a dict with two keys: data_down and narratives_down. Values
        for both of these are booleans.
        """
        data_down = flag_enabled('CCDB_TECHNICAL_ISSUES')
        narratives_down = False
        # show notification starting fifth business day data has not been
        # updated M-Th, data needs to have been updated 6 days ago; F-S,
        # preceding Monday
        now = datetime.now()
        weekday = datetime.weekday(now)
        delta = weekday if weekday > 3 else 6
        four_business_days_ago = (now - timedelta(delta)).strftime("%Y-%m-%d")

        try:
            if res_json['_meta']['last_indexed'] < four_business_days_ago:
                data_down = True
            elif (res_json['_meta']['last_updated'] < four_business_days_ago):
                narratives_down = True
        except (TypeError, KeyError):
            logger.exception("CCDB JSON status not in expected format.")

        return {
            'data_down': data_down,
            'narratives_down': narratives_down,
        }
    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)

        form_data, has_active_filters = self.get_form_data(request.GET)
        queryset = self.get_filterable_queryset()
        # flag check to enable or disable archive filter options
        if flag_enabled('HIDE_ARCHIVE_FILTER_OPTIONS', request=request):
            has_archived_posts = False
        else:
            has_archived_posts = queryset.filter(is_archived='yes').count() > 0
        form = self.get_form_class()(
            form_data,
            filterable_pages=queryset,
            wagtail_block=self.get_filterable_list_wagtail_block(),
            filterable_root=self.get_filterable_root(),
            filterable_categories=self.filterable_categories)

        context.update({
            'filter_data': self.process_form(request, form),
            'get_secondary_nav_items': get_secondary_nav_items,
            'has_active_filters': has_active_filters,
            'has_archived_posts': has_archived_posts,
        })

        return context
Beispiel #14
0
 def suggest(self, request):
     suggestion = SearchQuerySet().spelling_suggestion(self.search_term)
     if (suggestion and suggestion != self.search_term
             and request.GET.get('correct', '1') == '1'
             and flag_enabled('ASK_SEARCH_TYPOS', request=request)):
         self.queryset = self.query_base.filter(content=suggestion)
         self.search_term, self.suggestion = suggestion, self.search_term
Beispiel #15
0
    def is_ccdb_out_of_date(self, res_json):
        """Parse JSON describing CCDB status to determine if it is out of date.

        Returns a dict with two keys: data_down and narratives_down. Values
        for both of these are booleans.
        """
        data_down = flag_enabled('CCDB_TECHNICAL_ISSUES')
        narratives_down = False
        # show notification starting fifth business day data has not been
        # updated M-Th, data needs to have been updated 6 days ago; F-S,
        # preceding Monday
        now = datetime.now()
        weekday = datetime.weekday(now)
        delta = weekday if weekday > 3 else 6
        four_business_days_ago = (now -
                                  timedelta(delta)).strftime("%Y-%m-%d")

        try:

            if res_json['stats']['last_updated'] < four_business_days_ago:
                data_down = True
            elif (res_json['stats']['last_updated_narratives'] <
                    four_business_days_ago):
                narratives_down = True
        except KeyError:
            logger.exception("CCDB JSON status not in expected format.")

        return {
            'data_down': data_down,
            'narratives_down': narratives_down,
        }
Beispiel #16
0
    def get_edit_handler(cls):
        if hasattr(cls, 'edit_handler'):
            return cls.edit_handler.bind_to(model=cls)

        editor_panels = [
            ObjectList(cls.content_panels + [
                AdminOnlyFieldPanel('coa_global', classname="admin-only-field")
            ],
                       heading='Content'),
            ObjectList(cls.notes_content_panel, heading='Notes')
        ]

        try:
            if flag_enabled('SHOW_EXTRA_PANELS'):
                editor_panels += (PermissionObjectList(cls.promote_panels,
                                                       heading='SEO'),
                                  PermissionObjectList(cls.settings_panels,
                                                       heading='Settings'))
        except ProgrammingError as e:
            print("some problem, maybe with flags")
            pass

        edit_handler = TabbedInterface(editor_panels)

        return edit_handler.bind_to(model=cls)
Beispiel #17
0
def _get_meta():
    # Hard code noon Eastern Time zone since that is where it is built
    body = {
        # size: 0 here to prevent taking too long since we only needed max_date
        "size": 0,
        "aggs": {
            "max_date": {
                "max": {
                    "field": "date_received",
                    "format": "yyyy-MM-dd'T'12:00:00-05:00"
                }
            },
            "max_indexed_date": {
                "max": {
                    "field": "date_indexed",
                    "format": "yyyy-MM-dd'T'12:00:00-05:00"
                }
            },
            "max_narratives": {
                "filter": {
                    "term": {
                        "has_narrative": "true"
                    }
                },
                "aggs": {
                    "max_date": {
                        "max": {
                            "field": ":updated_at",
                        }
                    }
                }
            }
        }
    }
    max_date_res = _get_es().search(index=_COMPLAINT_ES_INDEX, body=body)
    count_res = _get_es().count(index=_COMPLAINT_ES_INDEX,
                                doc_type=_COMPLAINT_DOC_TYPE)

    result = {
        "license":
        "CC0",
        "last_updated":
        max_date_res["aggregations"]["max_date"]["value_as_string"],
        "last_indexed":
        max_date_res["aggregations"]["max_indexed_date"]["value_as_string"],
        "total_record_count":
        count_res["count"],
        "is_data_stale":
        _is_data_stale(
            max_date_res["aggregations"]["max_date"]["value_as_string"]),
        "is_narrative_stale":
        _is_data_stale(
            from_timestamp(max_date_res["aggregations"]["max_narratives"]
                           ["max_date"]["value"])),
        "has_data_issue":
        bool(flag_enabled('CCDB_TECHNICAL_ISSUES'))
    }

    return result
Beispiel #18
0
def request_site_recrawl(sender, **kwargs):
    try:
        if flag_enabled('PING_GOOGLE_ON_PUBLISH'):
            response = requests.get(GOOGLE_URL, {'sitemap': SITEMAP_URL})
            response.raise_for_status()
            logger.info('Pinged Google after job page publication.')
    except Exception:
        logger.exception('Pinging Google after job page publication failed.')
Beispiel #19
0
    def render_to_response(self, context, **response_kwargs):
        response = super(CCDB5MainView,
                         self).render_to_response(context, **response_kwargs)

        show_trends = flag_enabled('CCDB5_TRENDS')

        response.set_cookie('showTrends', 'show' if show_trends else 'hide')
        return response
Beispiel #20
0
 def get_messaging_emails(self, request):
     if not self.email and flag_enabled("MESSAGING_FLAG", request=request):
         return [
             user.email for user in self.organisers.all()
             if user.profile.allow_messaging
         ]
     elif self.email:
         return [self.email]
Beispiel #21
0
    def get_context_data(self, **kwargs):
        context = super(ComplaintLandingView, self).get_context_data(**kwargs)

        complaint_source = getattr(settings, 'COMPLAINT_LANDING_STATS_SOURCE',
                                   None)

        if complaint_source:
            ccdb_status_json = self.get_ccdb_status_json(complaint_source)
            context.update(self.is_ccdb_out_of_date(ccdb_status_json))

        context.update({
            'technical_issues':
            flag_enabled('CCDB_TECHNICAL_ISSUES'),
            'ccdb_content_updates':
            flag_enabled('CCDB_CONTENT_UPDATES'),
        })

        return context
Beispiel #22
0
def ask_search(request, language='en', as_json=False):
    if 'selected_facets' in request.GET:
        return redirect_ask_search(request, language=language)
    language_map = {'en': 'ask-cfpb-search-results', 'es': 'respuestas'}
    sqs = SearchQuerySet().models(AnswerPage)
    clean_query = Clean(request.GET.get('q', ''))
    clean_qstring = clean_query.query_string.strip()
    qstring = clean_qstring
    query_sqs = sqs.filter(content=clean_query, language=language)
    results_page = get_object_or_404(AnswerResultsPage,
                                     language=language,
                                     slug=language_map[language])

    # If there's no query string, don't search
    if not qstring:
        results_page.query = ''
        results_page.result_query = ''
        return results_page.serve(request)

    # If we have no results from our query, let's try to suggest a better one
    suggestion = sqs.spelling_suggestion(qstring)
    if suggestion == qstring:
        suggestion = None
    elif (query_sqs.count() == 0 and request.GET.get('correct', '1') == '1'
          and flag_enabled('ASK_SEARCH_TYPOS', request=request)):
        query_sqs = sqs.filter(content=suggestion)
        qstring, suggestion = suggestion, qstring

    if as_json:
        results = {
            'query':
            clean_qstring,
            'result_query':
            qstring,
            'suggestion':
            suggestion,
            'results': [{
                'question': result.autocomplete,
                'url': result.url,
                'text': result.text
            } for result in query_sqs]
        }
        json_results = json.dumps(results)
        return HttpResponse(json_results, content_type='application/json')
    else:
        results_page.query = clean_qstring
        results_page.result_query = qstring
        results_page.suggestion = suggestion
        results_page.answers = []

        for result in query_sqs:
            results_page.answers.append(
                (result.url, result.autocomplete, result.text))
        return results_page.serve(request)
Beispiel #23
0
 def portal_topic_page(self, request):
     self.portal_category = None
     if flag_enabled('ELASTICSEARCH_DSL_ASK'):
         self.query_base = AnswerPageDocument.search().filter(
             'match', portal_topics=self.portal_topic.heading)
         return self.get_results_es7(request)
     else:
         self.query_base = SearchQuerySet().filter(
             portal_topics=self.portal_topic.heading,
             language=self.language)
         return self.get_results(request)
Beispiel #24
0
 def get_context_data(self, **kwargs):
     context = super(LandingView, self).get_context_data(**kwargs)
     context['base_template'] = BASE_TEMPLATE
     if 'demo_json' in kwargs:
         res_json = get_narratives_json(demo_json=kwargs['demo_json'])
     else:
         res_json = get_narratives_json()
     context['stats'] = get_stats(res_json)
     (context['data_down'],
      context['narratives_down']) = is_data_not_updated(res_json)
     context['technical_issues'] = flag_enabled('CCDB_TECHNICAL_ISSUES')
     return context
Beispiel #25
0
def lista_empresas(request):
    empresas = {}
    context = {}

    user_logged = IFCUsuario.objects.get(user=request.user)  # obtener usuario que inició sesión
    #if not(user_logged.rol.nombre == "Ventas" or user_logged.rol.nombre=="SuperUser" or user_logged.rol.nombre == "Director"):  # verificar que el usuario pertenezca al grupo con permisos
    if not ('visualizar_empresa' in request.session['permissions']):
        raise Http404
    if flag_enabled('Modulo_Empresas', request=request):
        empresas = Empresa.objects.filter(estado=True)
        context = {'empresas':empresas}
    return render(request, 'cuentas/lista_empresas.html', context)
Beispiel #26
0
def request_site_recrawl(sender, **kwargs):
    try:
        if flag_enabled('PING_GOOGLE_ON_PUBLISH'):
            response = requests.get(GOOGLE_URL, {'sitemap': SITEMAP_URL})
            response.raise_for_status()
            logger.info(
                'Pinged Google after job page publication.'
            )
    except Exception:
        logger.exception(
            'Pinging Google after job page publication failed.'
        )
Beispiel #27
0
def exportar_datos(request):
    user_logged = IFCUsuario.objects.get(user=request.user)  # Obtener el tipo de usuario logeado
    if not ('descargar_csv' in request.session['permissions']):
        raise Http404
    if request.session.get('success_code',None) == None:
        request.session['success_code'] = 0
    context = {'success_code': request.session['success_code'],}
    request.session['success_code'] = 0
    if flag_enabled('Modulo_Catalogo', request=request):
        context = {'success_code': request.session['success_code'], }
    else:
        context = {}
    return render(request, 'ventas/exportar_datos.html',context)
def email_popup(request):
    for label, urls in settings.EMAIL_POPUP_URLS.items():
        if request.path not in urls:
            continue

        feature_flag = 'EMAIL_POPUP_{}'.format(label.upper())
        if not flag_enabled(feature_flag, request=request):
            continue

        template = 'organisms/email-popup/{}.html'.format(label)
        context = {'popup_label': label}
        return mark_safe(render_to_string(template, context=context))

    return ''
def email_popup(request):
    for label, urls in settings.EMAIL_POPUP_URLS.items():
        if request.path not in urls:
            continue

        feature_flag = 'EMAIL_POPUP_{}'.format(label.upper())
        if not flag_enabled(feature_flag, request=request):
            continue

        template = 'organisms/email-popup/{}.html'.format(label)
        context = {'popup_label': label, 'request': request}
        return mark_safe(render_to_string(template, context=context))

    return ''
Beispiel #30
0
    def get_context_data(self, **kwargs):
        context = super(ComplaintLandingView, self).get_context_data(**kwargs)

        complaint_source = getattr(
            settings,
            'COMPLAINT_LANDING_STATS_SOURCE',
            None
        )

        if complaint_source:
            ccdb_status_json = self.get_ccdb_status_json(complaint_source)
            context.update(self.is_ccdb_out_of_date(ccdb_status_json))

        context['technical_issues'] = flag_enabled('CCDB_TECHNICAL_ISSUES')

        return context
 def get_page_set(self):
     if flag_enabled('ELASTICSEARCH_FILTERABLE_LISTS'):
         return EventFilterablePagesDocumentSearch(
             prefix=self.filterable_root,
             topics=self.cleaned_data.get('topics'),
             categories=self.cleaned_data.get('categories'),
             authors=self.cleaned_data.get('authors'),
             to_date=self.cleaned_data.get('to_date'),
             from_date=self.cleaned_data.get('from_date'),
             title=self.cleaned_data.get('title'),
             order_by=self.get_order_by()).search()
     else:
         query = self.generate_query()
         return self.filterable_pages.filter(query).distinct().order_by(
             '-date_published'
         )
 def get_page_set(self):
     if flag_enabled('ELASTICSEARCH_FILTERABLE_LISTS'):
         return EnforcementActionFilterablePagesDocumentSearch(
             prefix=self.filterable_root,
             topics=self.cleaned_data.get('topics'),
             categories=self.cleaned_data.get('categories'),
             authors=self.cleaned_data.get('authors'),
             to_date=self.cleaned_data.get('to_date'),
             from_date=self.cleaned_data.get('from_date'),
             title=self.cleaned_data.get('title'),
             statuses=self.cleaned_data.get('statuses'),
             products=self.cleaned_data.get('products')).search()
     else:
         query = self.generate_query()
         return self.filterable_pages.filter(query).distinct().order_by(
             '-initial_filing_date'
         )
Beispiel #33
0
def delete_condition(request, name, condition_pk):
    flag = get_flags().get(name)
    condition = get_object_or_404(FlagState, pk=condition_pk)

    if request.method == 'POST':
        condition.delete()

        if flag_enabled('WAGTAILFLAGS_ADMIN_BIG_LIST'):
            return redirect('{flags_list}#{flag_name}'.format(
                flags_list=resolve_url('wagtailflags:list'), flag_name=name))
        else:
            return redirect('wagtailflags:flag_index', name=name)

    context = {
        'flag': flag,
        'condition_str': str(condition),
        'condition_pk': condition.pk,
    }
    return render(request, 'wagtailflags/flags/delete_condition.html', context)
Beispiel #34
0
def ver_catalogo(request):
    context = {}
    if request.session.get('success_code', None) == None:
        request.session['success_code'] = 0
    user_logged = IFCUsuario.objects.get(user = request.user) # Obtener el tipo de usuario logeado
    #if user_logged.rol.nombre == "Director" or user_logged.rol.nombre == "SuperUser" or user_logged.rol.nombre == "Ventas":
    if 'consultar_catalogo_analisis' in request.session['permissions']:
        if flag_enabled('Modulo_Catalogo', request=request):
            analisis = Analisis.objects.all().exclude(nombre="Otro")
            paises = Pais.objects.all()
            context = {
                'analisis': analisis,
                'success_code' : request.session['success_code'],
                'paises' : paises
            }
            request.session['success_code'] = 0
        return render(request, 'ventas/catalogo.html', context)
    else: # Si el rol del usuario no es ventas no puede entrar a la página
        raise Http404
Beispiel #35
0
def ver_cotizaciones(request):
    #Vista de cotizaciones del cliente. Esta funcion muestra todas las cotizaciones consultadas en una tabla.
    context = {}
    if request.session._session:
        usuario_log = IFCUsuario.objects.filter(user=request.user).first() #Obtener usuario que inició sesión
        #if usuario_log.rol.nombre == "Cliente" or usuario_log.rol.nombre == "Ventas" or usuario_log.rol.nombre == "Director" or usuario_log.rol.nombre == "SuperUser":
        if ('consultar_cotizacion' in request.session['permissions']
                or 'visualizar_cotizacion' in request.session['permissions']
        ):
            if flag_enabled('Modulo_Cotizaciones', request=request):
                if usuario_log.rol.nombre == "Ventas":
                    cotizaciones = Cotizacion.objects.filter(usuario_v=usuario_log) #Obtener cotizaciones de usuario ventas
                    analisis = Analisis.objects.all().exclude(nombre="Otro")
                    clientes = IFCUsuario.objects.filter(rol__nombre="Cliente") #Obtener usuarios tipo cliente
                    context = {
                        'analisis': analisis,
                        'cotizaciones': cotizaciones,
                        'clientes': clientes
                    }
                elif usuario_log.rol.nombre == "Cliente":
                    cotizaciones = Cotizacion.objects.filter(usuario_c=usuario_log) #Obtener cotizaciones de usuario cliente
                    context = {
                        'cotizaciones': cotizaciones,
                    }
                elif usuario_log.rol.nombre == "SuperUser" or usuario_log.rol.nombre == "Director" or usuario_log.rol.nombre == "Soporte" or usuario_log.rol.nombre == "Gerente" or usuario_log.rol.nombre == "Facturacion":
                    cotizaciones = Cotizacion.objects.all()
                    analisis = Analisis.objects.all()
                    clientes = IFCUsuario.objects.filter(rol__nombre="Cliente") #Obtener usuarios tipo cliente
                    context = {
                        'analisis': analisis,
                        'cotizaciones': cotizaciones,
                        'clientes': clientes
                    }
            return render(request, 'ventas/cotizaciones.html', context)
        else:
            raise Http404
Beispiel #36
0
def ask_search(request, language='en', as_json=False):
    if 'selected_facets' in request.GET:
        return redirect_ask_search(request, language=language)
    language_map = {
        'en': {'slug': 'ask-cfpb-search-results',
               'query': SearchQuerySet().models(EnglishAnswerProxy)},
        'es': {'slug': 'respuestas',
               'query': SearchQuerySet().models(SpanishAnswerProxy)}
    }
    _map = language_map[language]
    sqs = _map['query']
    clean_query = Clean(request.GET.get('q', ''))
    clean_qstring = clean_query.query_string.strip()
    qstring = clean_qstring
    query_sqs = sqs.filter(content=clean_query)
    results_page = get_object_or_404(
        AnswerResultsPage,
        language=language,
        slug=_map['slug']
    )

    # If there's no query string, don't search
    if not qstring:
        results_page.query = ''
        results_page.result_query = ''
        return results_page.serve(request)

    # If we have no results from our query, let's try to suggest a better one
    suggestion = sqs.spelling_suggestion(qstring)
    if suggestion == qstring:
        suggestion = None
    elif (query_sqs.count() == 0 and
            request.GET.get('correct', '1') == '1' and
            flag_enabled('ASK_SEARCH_TYPOS', request=request)):
        query_sqs = sqs.filter(content=suggestion)
        qstring, suggestion = suggestion, qstring

    if as_json:
        results = {
            'query': clean_qstring,
            'result_query': qstring,
            'suggestion': suggestion,
            'results': [
                {
                    'question': result.autocomplete,
                    'url': result.url,
                    'text': result.text
                }
                for result in query_sqs
            ]
        }
        json_results = json.dumps(results)
        return HttpResponse(json_results, content_type='application/json')
    else:
        results_page.query = clean_qstring
        results_page.result_query = qstring
        results_page.suggestion = suggestion
        results_page.answers = []

        for result in query_sqs:
            results_page.answers.append(
                (result.url, result.autocomplete, result.text)
            )
        return results_page.serve(request)