Exemplo n.º 1
0
def new_user(request):
    """ Vue de création d'un nouvel utilisateur,
    envoie un mail pour le mot de passe"""
    user = AdherentCreationForm(request.POST or None, user=request.user)
    GTU_sum_up = GeneralOption.get_cached_value('GTU_sum_up')
    GTU = GeneralOption.get_cached_value('GTU')
    if user.is_valid():
        # Virtually fill the password reset form
        password_reset = PasswordResetForm(data={'email': request.user.email})
        if password_reset.is_valid():
            user = user.save()
            password_reset.save(request=request, use_https=request.is_secure())
            messages.success(request, _("The user %s was created,"
                                        " an email to set the password"
                                        " was sent.") % user.username)
            return redirect(reverse(
                'users:profil',
                kwargs={'userid': str(user.id)}
            ))
        else:
            messages.error(request, _("The email is invalid."))

    return form(
        {
            'userform': user,
            'GTU_sum_up': GTU_sum_up,
            'GTU': GTU,
            'showCGU': True,
            'action_name': _("Commit")
        },
        'users/user.html',
        request
    )
Exemplo n.º 2
0
def mass_archive(request):
    """ Permet l'archivage massif"""
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    to_archive_form = MassArchiveForm(request.POST or None)
    to_archive_list = []
    if to_archive_form.is_valid():
        date = to_archive_form.cleaned_data['date']
        full_archive = to_archive_form.cleaned_data['full_archive']
        to_archive_list = User.objects.exclude(id__in=all_has_access()).exclude(id__in=all_has_access(search_time=date)).exclude(state=User.STATE_NOT_YET_ACTIVE).exclude(state=User.STATE_FULL_ARCHIVE)
        if not full_archive:
            to_archive_list = to_archive_list.exclude(state=User.STATE_ARCHIVE)
        if "valider" in request.POST:
            if full_archive:
                User.mass_full_archive(to_archive_list)
            else:
                User.mass_archive(to_archive_list)
            messages.success(request, _("%s users were archived.") %
                to_archive_list.count()
            )
            return redirect(reverse('users:index'))
        to_archive_list = re2o_paginator(request, to_archive_list, pagination_number)
    return form(
        {'userform': to_archive_form, 'to_archive_list': to_archive_list},
        'users/mass_archive.html',
        request
    )
Exemplo n.º 3
0
def index(request):
    """ Vue d'affichage de tous les swicthes"""
    switch_list = (Switch.objects.prefetch_related(
        Prefetch(
            'interface_set',
            queryset=(
                Interface.objects.select_related('ipv4__ip_type__extension').
                select_related('domain__extension')))).select_related('stack'))
    switch_list = SortTable.sort(switch_list, request.GET.get('col'),
                                 request.GET.get('order'),
                                 SortTable.TOPOLOGIE_INDEX)

    pagination_number = GeneralOption.get_cached_value('pagination_number')
    switch_list = re2o_paginator(request, switch_list, pagination_number)

    if any(service_link.need_regen
           for service_link in Service_link.objects.filter(
               service__service_type='graph_topo')):
        make_machine_graph()
        for service_link in Service_link.objects.filter(
                service__service_type='graph_topo'):
            service_link.done_regen()

    if not isfile("/var/www/re2o/media/images/switchs.png"):
        make_machine_graph()
    return render(request, 'topologie/index.html',
                  {'switch_list': switch_list})
Exemplo n.º 4
0
def finish_results(results, col, order):
    """Sort the results by applying filters and then limit them to the
    number of max results. Finally add the info of the nmax number of results
    to the dict"""

    results['users'] = SortTable.sort(results['users'], col, order,
                                      SortTable.USERS_INDEX)
    results['machines'] = SortTable.sort(results['machines'], col, order,
                                         SortTable.MACHINES_INDEX)
    results['factures'] = SortTable.sort(results['factures'], col, order,
                                         SortTable.COTISATIONS_INDEX)
    results['bans'] = SortTable.sort(results['bans'], col, order,
                                     SortTable.USERS_INDEX_BAN)
    results['whitelists'] = SortTable.sort(results['whitelists'], col, order,
                                           SortTable.USERS_INDEX_WHITE)
    results['rooms'] = SortTable.sort(results['rooms'], col, order,
                                      SortTable.TOPOLOGIE_INDEX_ROOM)
    results['ports'] = SortTable.sort(results['ports'], col, order,
                                      SortTable.TOPOLOGIE_INDEX_PORT)
    results['switches'] = SortTable.sort(results['switches'], col, order,
                                         SortTable.TOPOLOGIE_INDEX)

    max_result = GeneralOption.get_cached_value('search_display_page')
    for name, val in results.items():
        results[name] = val.distinct()[:max_result]
    results.update({'max_result': max_result})

    return results
Exemplo n.º 5
0
def send_mail_voucher(invoice):
    """Creates a voucher from an invoice and sends it by email to the client"""
    ctx = {
        'asso_name': AssoOption.get_cached_value('name'),
        'pres_name': AssoOption.get_cached_value('pres_name'),
        'firstname': invoice.user.name,
        'lastname': invoice.user.surname,
        'email': invoice.user.email,
        'phone': invoice.user.telephone,
        'date_end': invoice.get_subscription().latest('date_end').date_end,
        'date_begin':
        invoice.get_subscription().earliest('date_start').date_start
    }
    templatename = CotisationsOption.get_cached_value(
        'voucher_template').template.name.split('/')[-1]
    pdf = create_pdf(templatename, ctx)
    template = get_template('cotisations/email_subscription_accepted')

    ctx = {
        'name': "{} {}".format(invoice.user.name, invoice.user.surname),
        'asso_email': AssoOption.get_cached_value('contact'),
        'asso_name': AssoOption.get_cached_value('name')
    }

    mail = EmailMessage('Votre reçu / Your voucher',
                        template.render(ctx),
                        GeneralOption.get_cached_value('email_from'),
                        [invoice.user.get_mail],
                        attachments=[('voucher.pdf', pdf, 'application/pdf')])
    mail.send()
Exemplo n.º 6
0
def control(request):
    """
    View used to control the invoices all at once.
    """
    pagination_number = GeneralOption.get_cached_value("pagination_number")
    invoice_list = Facture.objects.select_related("user").select_related(
        "paiement")
    invoice_list = SortTable.sort(
        invoice_list,
        request.GET.get("col"),
        request.GET.get("order"),
        SortTable.COTISATIONS_CONTROL,
    )
    control_invoices_formset = modelformset_factory(Facture,
                                                    fields=("control",
                                                            "valid"),
                                                    extra=0)
    invoice_list = re2o_paginator(request, invoice_list, pagination_number)
    control_invoices_form = control_invoices_formset(
        request.POST or None, queryset=invoice_list.object_list)
    if control_invoices_form.is_valid():
        control_invoices_form.save()
        reversion.set_comment("Control")
        messages.success(
            request, _("Your changes have been properly taken into account."))
        return redirect(reverse("cotisations:control"))
    return render(
        request,
        "cotisations/control.html",
        {
            "facture_list": invoice_list,
            "controlform": control_invoices_form
        },
    )
Exemplo n.º 7
0
def stats_logs(request):
    """View used to do an advanced search through the logs."""
    actions_form = ActionsSearchForm(request.GET or None)

    if actions_form.is_valid():
        actions = ActionsSearch()
        revisions = actions.get(actions_form.cleaned_data)
        revisions = SortTable.sort(
            revisions,
            request.GET.get("col"),
            request.GET.get("order"),
            SortTable.LOGS_STATS_LOGS,
        )

        pagination_number = GeneralOption.get_cached_value("pagination_number")
        revisions = re2o_paginator(request, revisions, pagination_number)

        # Only do this now so it's not applied to objects which aren't displayed
        # It can take a bit of time because it has to compute the diff of each version
        revisions.object_list = [RevisionAction(r) for r in revisions.object_list]
        return render(request, "logs/stats_logs.html", {"revisions_list": revisions})

    return render(
        request, "logs/search_stats_logs.html", {"actions_form": actions_form}
    )
Exemplo n.º 8
0
def index_module(request):
    """Display all modules of switchs"""
    module_list = ModuleSwitch.objects.all()
    modular_switchs = Switch.objects.filter(model__is_modular=True)
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    module_list = re2o_paginator(request, module_list, pagination_number)
    return render(request, 'topologie/index_module.html', {
        'module_list': module_list,
        'modular_switchs': modular_switchs
    })
Exemplo n.º 9
0
def index_port_profile(request):
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    port_profile_list = PortProfile.objects.all().select_related(
        'vlan_untagged')
    port_profile_list = re2o_paginator(request, port_profile_list,
                                       pagination_number)
    vlan_list = Vlan.objects.all().order_by('vlan_id')
    return render(request, 'topologie/index_portprofile.html', {
        'port_profile_list': port_profile_list,
        'vlan_list': vlan_list
    })
Exemplo n.º 10
0
def index(request):
    """ Affiche l'ensemble des adherents, need droit cableur """
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    users_list = Adherent.objects.select_related('room')
    users_list = SortTable.sort(
        users_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX
    )
    users_list = re2o_paginator(request, users_list, pagination_number)
    return render(request, 'users/index.html', {'users_list': users_list})
Exemplo n.º 11
0
def history(request, application, object_name, object_id):
    """Render history for a model.

    The model is determined using the `HISTORY_BIND` dictionnary if none is
    found, raises a Http404. The view checks if the user is allowed to see the
    history using the `can_view` method of the model.

    Args:
        request: The request sent by the user.
        application: Name of the application.
        object_name: Name of the model.
        object_id: Id of the object you want to acces history.

    Returns:
        The rendered page of history if access is granted, else the user is
        redirected to their profile page, with an error message.

    Raises:
        Http404: This kind of models doesn't have history.
    """
    try:
        model = apps.get_model(application, object_name)
    except LookupError:
        raise Http404(_("No model found."))
    object_name_id = object_name + 'id'
    kwargs = {object_name_id: object_id}
    try:
        instance = model.get_instance(**kwargs)
    except model.DoesNotExist:
        messages.error(request, _("Nonexistent entry."))
        return redirect(reverse(
            'users:profil',
            kwargs={'userid': str(request.user.id)}
        ))
    can, msg = instance.can_view(request.user)
    if not can:
        messages.error(request, msg or _("You don't have the right to access this menu."))
        return redirect(reverse(
            'users:profil',
            kwargs={'userid': str(request.user.id)}
        ))
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    reversions = Version.objects.get_for_object(instance)
    if hasattr(instance, 'linked_objects'):
        for related_object in chain(instance.linked_objects()):
            reversions = (reversions |
                          Version.objects.get_for_object(related_object))
    reversions = re2o_paginator(request, reversions, pagination_number)
    return render(
        request,
        're2o/history.html',
        {'reversions': reversions, 'object': instance}
    )
Exemplo n.º 12
0
def history(request, application, object_name, object_id):
    """Render history for a model.

    The model is determined using the `HISTORY_BIND` dictionnary if none is
    found, raises a Http404. The view checks if the user is allowed to see the
    history using the `can_view` method of the model, or the generic
    `can_view_app("logs")` for deleted objects (see `get_history_object`).

    Args:
        request: The request sent by the user.
        application: Name of the application.
        object_name: Name of the model.
        object_id: Id of the object you want to acces history.

    Returns:
        The rendered page of history if access is granted, else the user is
        redirected to their profile page, with an error message.

    Raises:
        Http404: This kind of models doesn't have history.
    """
    try:
        model = apps.get_model(application, object_name)
    except LookupError:
        raise Http404(_("No model found."))

    authorized, instance = get_history_object(request, model, object_name, object_id)
    if not authorized:
        return instance

    history = get_history_class(model)
    events = history.get(int(object_id), model)

    # Events is None if object wasn't found
    if events is None:
        messages.error(request, _("Nonexistent entry."))
        return redirect(
            reverse("users:profil", kwargs={"userid": str(request.user.id)})
        )

    # Generate the pagination with the objects
    max_result = GeneralOption.get_cached_value("pagination_number")
    events = re2o_paginator(request, events, max_result)

    # Add a default title in case the object was deleted
    title = instance or "{} ({})".format(history.name, _("Deleted"))

    return render(
        request,
        "re2o/history.html",
        {"title": title, "events": events, "related_history": history.related},
    )
Exemplo n.º 13
0
def context_user(request):
    """Fonction de context lorsqu'un user est logué (ou non),
    renvoie les infos sur l'user, la liste de ses droits, ses machines"""
    user = request.user
    if get_language() == 'fr':
        global_message = GeneralOption.get_cached_value('general_message_fr')
    else:
        global_message = GeneralOption.get_cached_value('general_message_en')
    if global_message:
        if isinstance(request, HttpRequest):
            messages.warning(request, global_message)
        else:
            messages.warning(request._request, global_message)
    if user.is_authenticated():
        interfaces = user.user_interfaces()
    else:
        interfaces = None
    return {
        'request_user': user,
        'interfaces': interfaces,
        'ipv6_enabled': OptionalMachine.get_cached_value('ipv6'),
    }
Exemplo n.º 14
0
def index_ap(request):
    """ Affichage de l'ensemble des bornes"""
    ap_list = (AccessPoint.objects.prefetch_related(
        Prefetch(
            'interface_set',
            queryset=(
                Interface.objects.select_related('ipv4__ip_type__extension').
                select_related('domain__extension')))).distinct())
    ap_list = SortTable.sort(ap_list, request.GET.get('col'),
                             request.GET.get('order'),
                             SortTable.TOPOLOGIE_INDEX_BORNE)
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    ap_list = re2o_paginator(request, ap_list, pagination_number)
    return render(request, 'topologie/index_ap.html', {'ap_list': ap_list})
Exemplo n.º 15
0
def index(request):
    """
    View used to display the list of all exisitng invoices.
    """
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    invoice_list = Facture.objects.select_related('user')\
        .select_related('paiement').prefetch_related('vente_set')
    invoice_list = SortTable.sort(invoice_list, request.GET.get('col'),
                                  request.GET.get('order'),
                                  SortTable.COTISATIONS_INDEX)
    invoice_list = re2o_paginator(request, invoice_list, pagination_number)
    return render(request, 'cotisations/index.html', {
        'facture_list': invoice_list,
    })
Exemplo n.º 16
0
def send_mail_invoice(invoice, request=None):
    """Creates the pdf of the invoice and sends it by email to the client"""
    purchases_info = []
    for purchase in invoice.vente_set.all():
        purchases_info.append({
            "name": purchase.name,
            "price": purchase.prix,
            "quantity": purchase.number,
            "total_price": purchase.prix_total,
        })

    ctx = {
        "paid": True,
        "fid": invoice.id,
        "DATE": invoice.date,
        "recipient_name": "{} {}".format(invoice.user.name,
                                         invoice.user.surname),
        "address": invoice.user.room,
        "article": purchases_info,
        "total": invoice.prix_total(),
        "asso_name": AssoOption.get_cached_value("name"),
        "line1": AssoOption.get_cached_value("adresse1"),
        "line2": AssoOption.get_cached_value("adresse2"),
        "siret": AssoOption.get_cached_value("siret"),
        "email": AssoOption.get_cached_value("contact"),
        "phone": AssoOption.get_cached_value("telephone"),
        "tpl_path": os.path.join(settings.BASE_DIR, LOGO_PATH),
    }

    template = CotisationsOption.get_cached_value(
        "invoice_template").template.name.split("/")[-1]
    pdf = create_pdf(template, ctx)
    template = get_template("cotisations/email_invoice")

    ctx = {
        "name": "{} {}".format(invoice.user.name, invoice.user.surname),
        "contact_mail": AssoOption.get_cached_value("contact"),
        "asso_name": AssoOption.get_cached_value("name"),
    }

    mail = EmailMessage(
        "Votre facture / Your invoice",
        template.render(ctx),
        GeneralOption.get_cached_value("email_from"),
        [invoice.user.get_mail],
        attachments=[("invoice.pdf", pdf, "application/pdf")],
    )

    send_mail_object(mail, request)
Exemplo n.º 17
0
def index_cost_estimate(request):
    """View used to display every custom invoice."""
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    cost_estimate_list = CostEstimate.objects.prefetch_related('vente_set')
    cost_estimate_list = SortTable.sort(cost_estimate_list,
                                        request.GET.get('col'),
                                        request.GET.get('order'),
                                        SortTable.COTISATIONS_CUSTOM)
    cost_estimate_list = re2o_paginator(
        request,
        cost_estimate_list,
        pagination_number,
    )
    return render(request, 'cotisations/index_cost_estimate.html',
                  {'cost_estimate_list': cost_estimate_list})
Exemplo n.º 18
0
def stats_logs(request):
    """Affiche l'ensemble des logs et des modifications sur les objets,
    classés par date croissante, en vrac"""
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    revisions = Revision.objects.all().select_related('user')\
        .prefetch_related('version_set__object')
    revisions = SortTable.sort(
        revisions,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.LOGS_STATS_LOGS
    )
    revisions = re2o_paginator(request, revisions, pagination_number)
    return render(request, 'logs/stats_logs.html', {
        'revisions_list': revisions
    })
Exemplo n.º 19
0
def index(request):
    """
    View used to display the list of all exisitng invoices.
    """
    pagination_number = GeneralOption.get_cached_value("pagination_number")
    invoice_list = (Facture.objects.select_related("user").select_related(
        "paiement").prefetch_related("vente_set"))
    invoice_list = SortTable.sort(
        invoice_list,
        request.GET.get("col"),
        request.GET.get("order"),
        SortTable.COTISATIONS_INDEX,
    )
    invoice_list = re2o_paginator(request, invoice_list, pagination_number)
    return render(request, "cotisations/index.html",
                  {"facture_list": invoice_list})
Exemplo n.º 20
0
def index_clubs(request):
    """ Affiche l'ensemble des clubs, need droit cableur """
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    clubs_list = Club.objects.select_related('room')
    clubs_list = SortTable.sort(
        clubs_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX
    )
    clubs_list = re2o_paginator(request, clubs_list, pagination_number)
    return render(
        request,
        'users/index_clubs.html',
        {'clubs_list': clubs_list}
    )
Exemplo n.º 21
0
def index_cost_estimate(request):
    """View used to display every custom invoice."""
    pagination_number = GeneralOption.get_cached_value("pagination_number")
    cost_estimate_list = CostEstimate.objects.prefetch_related("vente_set")
    cost_estimate_list = SortTable.sort(
        cost_estimate_list,
        request.GET.get("col"),
        request.GET.get("order"),
        SortTable.COTISATIONS_CUSTOM,
    )
    cost_estimate_list = re2o_paginator(request, cost_estimate_list,
                                        pagination_number)
    return render(
        request,
        "cotisations/index_cost_estimate.html",
        {"cost_estimate_list": cost_estimate_list},
    )
Exemplo n.º 22
0
def stats_search_machine_history(request):
    """View used to display the history of machines with the given IP or MAC
    address.
    """
    history_form = MachineHistorySearchForm(request.GET or None)
    if history_form.is_valid():
        history = MachineHistorySearch()
        events = history.get(
            history_form.cleaned_data.get("q", ""), history_form.cleaned_data
        )
        max_result = GeneralOption.get_cached_value("pagination_number")
        events = re2o_paginator(request, events, max_result)

        return render(request, "logs/machine_history.html", {"events": events},)
    return render(
        request, "logs/search_machine_history.html", {"history_form": history_form}
    )
Exemplo n.º 23
0
def send_mail_voucher(invoice, request=None):
    """Creates a voucher from an invoice and sends it by email to the client"""
    president = Mandate.get_mandate(invoice.date).president
    ctx = {
        "asso_name":
        AssoOption.get_cached_value("name"),
        "pres_name":
        " ".join([president.name, president.surname]),
        "firstname":
        invoice.user.name,
        "lastname":
        invoice.user.surname,
        "email":
        invoice.user.email,
        "phone":
        invoice.user.telephone,
        "date_end":
        invoice.get_subscription().latest("date_end_memb").date_end_memb,
        "date_begin":
        invoice.get_subscription().earliest("date_start_memb").date_start_memb,
    }
    templatename = CotisationsOption.get_cached_value(
        "voucher_template").template.name.split("/")[-1]
    pdf = create_pdf(templatename, ctx)
    template = get_template("cotisations/email_subscription_accepted")

    ctx = {
        "name":
        "{} {}".format(invoice.user.name, invoice.user.surname),
        "asso_email":
        AssoOption.get_cached_value("contact"),
        "asso_name":
        AssoOption.get_cached_value("name"),
        "date_end":
        invoice.get_subscription().latest("date_end_memb").date_end_memb,
    }

    mail = EmailMessage(
        "Votre reçu / Your voucher",
        template.render(ctx),
        GeneralOption.get_cached_value("email_from"),
        [invoice.user.get_mail],
        attachments=[("voucher.pdf", pdf, "application/pdf")],
    )

    send_mail_object(mail, request)
Exemplo n.º 24
0
def send_mail_invoice(invoice):
    """Creates the pdf of the invoice and sends it by email to the client"""
    purchases_info = []
    for purchase in invoice.vente_set.all():
        purchases_info.append({
            'name': purchase.name,
            'price': purchase.prix,
            'quantity': purchase.number,
            'total_price': purchase.prix_total
        })

    ctx = {
        'paid': True,
        'fid': invoice.id,
        'DATE': invoice.date,
        'recipient_name': "{} {}".format(invoice.user.name,
                                         invoice.user.surname),
        'address': invoice.user.room,
        'article': purchases_info,
        'total': invoice.prix_total(),
        'asso_name': AssoOption.get_cached_value('name'),
        'line1': AssoOption.get_cached_value('adresse1'),
        'line2': AssoOption.get_cached_value('adresse2'),
        'siret': AssoOption.get_cached_value('siret'),
        'email': AssoOption.get_cached_value('contact'),
        'phone': AssoOption.get_cached_value('telephone'),
        'tpl_path': os.path.join(settings.BASE_DIR, LOGO_PATH)
    }

    pdf = create_pdf('cotisations/factures.tex', ctx)
    template = get_template('cotisations/email_invoice')

    ctx = {
        'name': "{} {}".format(invoice.user.name, invoice.user.surname),
        'contact_mail': AssoOption.get_cached_value('contact'),
        'asso_name': AssoOption.get_cached_value('name')
    }

    mail = EmailMessage('Votre facture / Your invoice',
                        template.render(ctx),
                        GeneralOption.get_cached_value('email_from'),
                        [invoice.user.get_mail],
                        attachments=[('invoice.pdf', pdf, 'application/pdf')])
    mail.send()
Exemplo n.º 25
0
def index(request):
    """Affiche les logs affinés, date reformatées, selectionne
    les event importants (ajout de droits, ajout de ban/whitelist)"""
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    # The types of content kept for display
    content_type_filter = ['ban', 'whitelist', 'vente', 'interface', 'user']
    # Select only wanted versions
    versions = Version.objects.filter(
        content_type__in=ContentType.objects.filter(
            model__in=content_type_filter
        )
    ).select_related('revision')
    versions = SortTable.sort(
        versions,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.LOGS_INDEX
    )
    versions = re2o_paginator(request, versions, pagination_number)
    # Force to have a list instead of QuerySet
    versions.count(0)
    # Items to remove later because invalid
    to_remove = []
    # Parse every item (max = pagination_number)
    for i in range(len(versions.object_list)):
        if versions.object_list[i].object:
            version = versions.object_list[i]
            versions.object_list[i] = {
                'rev_id': version.revision.id,
                'comment': version.revision.comment,
                'datetime': version.revision.date_created.strftime(
                    '%d/%m/%y %H:%M:%S'
                ),
                'username':
                    version.revision.user.get_username()
                    if version.revision.user else '?',
                'user_id': version.revision.user_id,
                'version': version}
        else:
            to_remove.insert(0, i)
    # Remove all tagged invalid items
    for i in to_remove:
        versions.object_list.pop(i)
    return render(request, 'logs/index.html', {'versions_list': versions})
Exemplo n.º 26
0
def index(request):
    """View used to display summary of events about users."""
    pagination_number = GeneralOption.get_cached_value("pagination_number")
    # The types of content kept for display
    content_type_filter = ["ban", "whitelist", "vente", "interface", "user"]
    # Select only wanted versions
    versions = Version.objects.filter(
        content_type__in=ContentType.objects.filter(model__in=content_type_filter)
    ).select_related("revision")
    versions = SortTable.sort(
        versions, request.GET.get("col"), request.GET.get("order"), SortTable.LOGS_INDEX
    )
    versions = re2o_paginator(request, versions, pagination_number)
    # Force to have a list instead of QuerySet
    versions.count(0)
    # Items to remove later because invalid
    to_remove = []
    # Parse every item (max = pagination_number)
    for i in range(len(versions.object_list)):
        if versions.object_list[i].object:
            version = versions.object_list[i]
            versions.object_list[i] = {
                "rev_id": version.revision.id,
                "comment": version.revision.comment,
                "datetime": version.revision.date_created,
                "username": version.revision.user.get_username()
                if version.revision.user
                else "?",
                "user_id": version.revision.user_id,
                "version": version,
            }
        else:
            to_remove.insert(0, i)
    # Remove all tagged invalid items
    for i in to_remove:
        versions.object_list.pop(i)
    return render(request, "logs/index.html", {"versions_list": versions})
Exemplo n.º 27
0
def aff_profil(request, user):
    """View used to display the cotisations on a user's profil."""

    factures = Facture.objects.filter(user=user)
    factures = SortTable.sort(
        factures,
        request.GET.get("col"),
        request.GET.get("order"),
        SortTable.COTISATIONS_INDEX,
    )

    pagination_large_number = GeneralOption.get_cached_value(
        "pagination_large_number")
    factures = re2o_paginator(request, factures, pagination_large_number)

    context = {
        "users": user,
        "facture_list": factures,
    }

    return render_to_string("cotisations/aff_profil.html",
                            context=context,
                            request=request,
                            using=None)
Exemplo n.º 28
0
def profil(request, users, **_kwargs):
    """ Affiche un profil, self or cableur, prend un userid en argument """
    machines = Machine.objects.filter(user=users).select_related('user')\
        .prefetch_related('interface_set__domain__extension')\
        .prefetch_related('interface_set__ipv4__ip_type__extension')\
        .prefetch_related('interface_set__machine_type')\
        .prefetch_related('interface_set__domain__related_domain__extension')
    machines = SortTable.sort(
        machines,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.MACHINES_INDEX
    )
    pagination_large_number = GeneralOption.get_cached_value(
        'pagination_large_number'
    )
    nb_machines = machines.count()
    machines = re2o_paginator(request, machines, pagination_large_number)
    factures = Facture.objects.filter(user=users)
    factures = SortTable.sort(
        factures,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.COTISATIONS_INDEX
    )
    bans = Ban.objects.filter(user=users)
    bans = SortTable.sort(
        bans,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_BAN
    )
    whitelists = Whitelist.objects.filter(user=users)
    whitelists = SortTable.sort(
        whitelists,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_WHITE
    )
    try:
        balance = find_payment_method(Paiement.objects.get(is_balance=True))
    except Paiement.DoesNotExist:
        user_solde = False
    else:
        user_solde = (
            balance is not None
            and balance.can_credit_balance(request.user)
        )
    return render(
        request,
        'users/profil.html',
        {
            'users': users,
            'machines_list': machines,
            'nb_machines': nb_machines,
            'facture_list': factures,
            'ban_list': bans,
            'white_list': whitelists,
            'user_solde': user_solde,
            'solde_activated': Paiement.objects.filter(is_balance=True).exists(),
            'asso_name': AssoOption.objects.first().name,
            'emailaddress_list': users.email_address,
            'local_email_accounts_enabled': (
                OptionalUser.objects.first().local_email_accounts_enabled
            )
        }
    )