views.py 8.86 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2017  Gabriel Détraz
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# App de gestion des machines pour re2o
# Gabriel Détraz, Augustin Lemesle
# Gplv2
26 27 28 29
"""
Vue d'affichage, et de modification des réglages (réglages machine,
topologie, users, service...)
"""
30

31
from __future__ import unicode_literals
32

33
from django.urls import reverse
34
from django.shortcuts import redirect
35
from django.contrib import messages
36
from django.contrib.auth.decorators import login_required
37
from django.db.models import ProtectedError
38
from django.db import transaction
39
from django.utils.translation import ugettext as _
40 41 42

from reversion import revisions as reversion

43
from re2o.views import form
44
from re2o.acl import can_create, can_edit, can_delete_set, can_view_all
45

46 47 48
from .forms import (
    ServiceForm, DelServiceForm, MailContactForm, DelMailContactForm
)
Gabriel Detraz's avatar
Gabriel Detraz committed
49 50
from .models import (
    Service,
51
    MailContact,
Gabriel Detraz's avatar
Gabriel Detraz committed
52 53 54 55 56 57
    OptionalUser,
    OptionalMachine,
    AssoOption,
    MailMessageOption,
    GeneralOption,
    OptionalTopologie,
Gabriel Detraz's avatar
Gabriel Detraz committed
58
    HomeOption
Gabriel Detraz's avatar
Gabriel Detraz committed
59
)
60 61
from . import models
from . import forms
62 63 64


@login_required
65 66
@can_view_all(OptionalUser, OptionalMachine, OptionalTopologie, GeneralOption,
              AssoOption, MailMessageOption, HomeOption)
67
def display_options(request):
68 69 70 71 72 73 74
    """Vue pour affichage des options (en vrac) classé selon les models
    correspondants dans un tableau"""
    useroptions, _created = OptionalUser.objects.get_or_create()
    machineoptions, _created = OptionalMachine.objects.get_or_create()
    topologieoptions, _created = OptionalTopologie.objects.get_or_create()
    generaloptions, _created = GeneralOption.objects.get_or_create()
    assooptions, _created = AssoOption.objects.get_or_create()
Gabriel Detraz's avatar
Gabriel Detraz committed
75
    homeoptions, _created = HomeOption.objects.get_or_create()
76
    mailmessageoptions, _created = MailMessageOption.objects.get_or_create()
77
    service_list = Service.objects.all()
78
    mailcontact_list = MailContact.objects.all()
79 80 81 82 83 84
    return form({
        'useroptions': useroptions,
        'machineoptions': machineoptions,
        'topologieoptions': topologieoptions,
        'generaloptions': generaloptions,
        'assooptions': assooptions,
Gabriel Detraz's avatar
Gabriel Detraz committed
85
        'homeoptions': homeoptions,
86
        'mailmessageoptions': mailmessageoptions,
87 88
        'service_list': service_list,
        'mailcontact_list': mailcontact_list
89 90
        }, 'preferences/display_preferences.html', request)

91 92

@login_required
93 94 95 96
def edit_options(request, section):
    """ Edition des préférences générales"""
    model = getattr(models, section, None)
    form_instance = getattr(forms, 'Edit' + section + 'Form', None)
97 98 99 100 101 102 103 104 105 106 107 108
    if not (model or form_instance):
        messages.error(request, "Objet  inconnu")
        return redirect(reverse('preferences:display-options'))

    options_instance, _created = model.objects.get_or_create()
    can, msg = options_instance.can_edit(request.user)
    if not can:
        messages.error(request, msg or "Vous ne pouvez pas éditer cette\
                   option.")
        return redirect(reverse('index'))
    options = form_instance(
        request.POST or None,
109
        request.FILES or None,
110 111 112 113 114 115 116 117 118
        instance=options_instance
    )
    if options.is_valid():
        with transaction.atomic(), reversion.create_revision():
            options.save()
            reversion.set_user(request.user)
            reversion.set_comment(
                "Champs modifié(s) : %s" % ', '.join(
                    field for field in options.changed_data
119 120
                )
            )
121
            messages.success(request, "Préférences modifiées")
122
        return redirect(reverse('preferences:display-options'))
123 124 125 126 127
    return form(
        {'options': options},
        'preferences/edit_preferences.html',
        request
    )
128

129

130
@login_required
131 132
@can_create(Service)
def add_service(request):
133
    """Ajout d'un service de la page d'accueil"""
Gabriel Detraz's avatar
Gabriel Detraz committed
134
    service = ServiceForm(request.POST or None, request.FILES or None)
135
    if service.is_valid():
136
        with transaction.atomic(), reversion.create_revision():
137
            service.save()
138 139
            reversion.set_user(request.user)
            reversion.set_comment("Création")
140
        messages.success(request, "Ce service a été ajouté")
141
        return redirect(reverse('preferences:display-options'))
142
    return form(
Maël Kervella's avatar
Maël Kervella committed
143
        {'preferenceform': service, 'action_name': 'Ajouter'},
144 145 146 147
        'preferences/preferences.html',
        request
        )

148 149

@login_required
150
@can_edit(Service)
151
def edit_service(request, service_instance, **_kwargs):
152
    """Edition des services affichés sur la page d'accueil"""
153
    service = ServiceForm(
154 155 156 157
        request.POST or None,
        request.FILES or None,
        instance=service_instance
    )
158
    if service.is_valid():
159
        with transaction.atomic(), reversion.create_revision():
160
            service.save()
161
            reversion.set_user(request.user)
162 163
            reversion.set_comment(
                "Champs modifié(s) : %s" % ', '.join(
164
                    field for field in service.changed_data
165 166
                    )
            )
167
        messages.success(request, "Service modifié")
168
        return redirect(reverse('preferences:display-options'))
169
    return form(
Maël Kervella's avatar
Maël Kervella committed
170
        {'preferenceform': service, 'action_name': 'Editer'},
171 172 173 174
        'preferences/preferences.html',
        request
    )

175 176

@login_required
177
@can_delete_set(Service)
178
def del_service(request, instances):
179
    """Suppression d'un service de la page d'accueil"""
180
    services = DelServiceForm(request.POST or None, instances=instances)
181 182 183 184 185 186 187
    if services.is_valid():
        services_dels = services.cleaned_data['services']
        for services_del in services_dels:
            try:
                with transaction.atomic(), reversion.create_revision():
                    services_del.delete()
                    reversion.set_user(request.user)
188
                messages.success(request, "Le service a été supprimé")
189
            except ProtectedError:
190 191
                messages.error(request, "Erreur le service\
                suivant %s ne peut être supprimé" % services_del)
192
        return redirect(reverse('preferences:display-options'))
193
    return form(
Maël Kervella's avatar
Maël Kervella committed
194
        {'preferenceform': services, 'action_name': 'Supprimer'},
195 196 197
        'preferences/preferences.html',
        request
    )
198 199 200 201 202


@login_required
@can_create(MailContact)
def add_mailcontact(request):
203
    """Add a contact email adress."""
204 205 206 207 208
    mailcontact = MailContactForm(
        request.POST or None,
        request.FILES or None
    )
    if mailcontact.is_valid():
209 210
        mailcontact.save()
        messages.success(request, _("The adress was created."))
211 212 213 214 215 216 217 218 219 220 221
        return redirect(reverse('preferences:display-options'))
    return form(
        {'preferenceform': mailcontact, 'action_name': 'Ajouter'},
        'preferences/preferences.html',
        request
        )


@login_required
@can_edit(MailContact)
def edit_mailcontact(request, mailcontact_instance, **_kwargs):
222
    """Edit contact email adress."""
223 224 225 226 227 228
    mailcontact = MailContactForm(
        request.POST or None,
        request.FILES or None,
        instance=mailcontact_instance
    )
    if mailcontact.is_valid():
229 230
        mailcontact.save()
        messages.success(request, _("Email adress updated."))
231 232
        return redirect(reverse('preferences:display-options'))
    return form(
233
        {'preferenceform': mailcontact, 'action_name': _('Edit')},
234 235 236 237 238 239 240 241
        'preferences/preferences.html',
        request
    )


@login_required
@can_delete_set(MailContact)
def del_mailcontact(request, instances):
242
    """Delete an email adress"""
243 244 245 246 247 248 249
    mailcontacts = DelMailContactForm(
        request.POST or None,
        instances=instances
    )
    if mailcontacts.is_valid():
        mailcontacts_dels = mailcontacts.cleaned_data['mailcontacts']
        for mailcontacts_del in mailcontacts_dels:
250 251
            mailcontacts_del.delete()
            messages.success(request, _("The email adress was deleted."))
252 253
        return redirect(reverse('preferences:display-options'))
    return form(
254
        {'preferenceform': mailcontacts, 'action_name': _('Delete')},
255 256 257
        'preferences/preferences.html',
        request
    )