Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / controllers / plugins / date.py @ 2bcebf54

History | View | Annotate | Download (5.39 KB)

1
# -*- coding: utf-8 -*-
2
# vim:set expandtab tabstop=4 shiftwidth=4:
3
################################################################################
4
#
5
# Copyright (C) 2007-2016 CS-SI
6
#
7
# This program is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License version 2 as
9
# published by the Free Software Foundation.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
################################################################################
20

    
21
"""
22
Un plugin pour VigiBoard qui ajoute une colonne avec la date à laquelle
23
est survenu un événement et la durée depuis laquelle l'événement est actif.
24
"""
25
from datetime import datetime, timedelta
26
import tw.forms as twf
27
from pylons.i18n import ugettext as _, lazy_ugettext as l_
28

    
29
from vigilo.models import tables
30

    
31
from vigiboard.controllers.plugins import VigiboardRequestPlugin, ITEMS
32
from vigiboard.lib import dateformat, error_handler
33

    
34

    
35
class ExampleDateFormat(object):
36
    """
37
    Une classe permettant d'obtenir un exemple de date
38
    correspondant au format de la locale de l'utilisateur.
39
    """
40
    def __str__(self):
41
        """
42
        Retourne l'heure courante au format attendu,
43
        encodée en UTF-8.
44

45
        @return: Heure courante au format attendu (en UTF-8).
46
        @rtype: C{str}
47
        """
48
        return unicode(self).encode('utf-8')
49

    
50
    def __unicode__(self):
51
        """
52
        Retourne l'heure courante au format attendu.
53

54
        @return: Heure courante au format attendu.
55
        @rtype: C{unicode}
56
        """
57
        format = dateformat.get_date_format()
58
        date = datetime.strftime(datetime.now(), format).decode('utf-8')
59
        return _('Eg. %(date)s') % {'date': date}
60

    
61

    
62
class PluginDate(VigiboardRequestPlugin):
63
    """Plugin pour l'ajout d'une colonne Date."""
64
    def get_search_fields(self):
65
        return [
66
            twf.Label('date', text=l_('Last occurrence')),
67
            twf.CalendarDateTimePicker(
68
                'from_date',
69
                label_text=l_('Between'),
70
                button_text=l_("Choose"),
71
                not_empty=False,
72
                validator=dateformat.DateFormatConverter(if_missing=None),
73
                date_format=dateformat.get_date_format,
74
                calendar_lang=dateformat.get_calendar_lang,
75
                attrs={
76
                    # Affiche un exemple de date au survol
77
                    # et en tant qu'indication (placeholder).
78
                    'title': ExampleDateFormat(),
79
                    'placeholder': ExampleDateFormat()
80
                },
81
            ),
82
            twf.CalendarDateTimePicker(
83
                'to_date',
84
                label_text=l_('And'),
85
                button_text=l_("Choose"),
86
                not_empty=False,
87
                validator=dateformat.DateFormatConverter(if_missing=None),
88
                date_format=dateformat.get_date_format,
89
                calendar_lang=dateformat.get_calendar_lang,
90
                attrs={
91
                    # Affiche un exemple de date au survol
92
                    # et en tant qu'indication (placeholder).
93
                    'title': ExampleDateFormat(),
94
                    'placeholder': ExampleDateFormat()
95
                },
96
            ),
97
        ]
98

    
99
    def handle_search_fields(self, query, search, state, subqueries):
100
        if state != ITEMS:
101
            return
102

    
103
        if search.get('from_date'):
104
            query.add_filter(tables.CorrEvent.timestamp_active >=
105
                search['from_date'])
106

    
107
            # Ajout de contrôles sur la date de début
108
            if search['from_date'] >= datetime.now():
109
                error_handler.handle_error_message(
110
                    _('Start date cannot be greater than current date'))
111

    
112
            if search.get('to_date') and \
113
               search['from_date'] > search['to_date']:
114
                error_handler.handle_error_message(
115
                    _('Start date cannot be greater than end date'))
116

    
117
        if search.get('to_date'):
118
            query.add_filter(tables.CorrEvent.timestamp_active <=
119
                search['to_date'])
120

    
121
            # Ajout de contrôles sur la date de fin
122
            if search['to_date'] >= datetime.now():
123
                error_handler.handle_error_message(
124
                    _('End date cannot be greater than current date'))
125

    
126
    def get_data(self, event):
127
        state = tables.StateName.value_to_statename(
128
                    event[0].cause.current_state)
129
        # La résolution maximale de Nagios est la seconde.
130
        # On supprime les microsecondes qui ne nous apportent
131
        # aucune information et fausse l'affichage dans l'export CSV
132
        # en créant un nouvel objet timedelta dérivé du premier.
133
        duration = datetime.now() - event[0].timestamp_active
134
        duration = timedelta(days=duration.days, seconds=duration.seconds)
135
        return {
136
            'state': state,
137
            'date': event[0].cause.timestamp,
138
            'duration': duration,
139
        }
140

    
141
    def get_sort_criterion(self, query, column):
142
        if column == 'date':
143
            return tables.Event.timestamp
144
        return None
145