Source

trac.plugins.traccron / src / traccron / task.py

  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
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# -*- encoding: UTF-8 -*-
"""
Created on 28 oct. 2010

@author: thierry
"""
###############################################################################
##
##             O U T    O F    T H E    B O X    T A S K
##
###############################################################################
from datetime import datetime, timedelta
from time import time, localtime

from trac.ticket.model import Ticket
from trac.core import Component, implements
from trac.notification import NotifyEmail
from trac.util.datefmt import utc, from_utimestamp, to_utimestamp
from trac.web.chrome import ITemplateProvider
from traccron.api import ICronTask
from traccron.core import CronConfig


class HeartBeatTask(Component, ICronTask):
    """
    This is a simple task for testing purpose.
    It only write a trace in log at debug level
    """
    implements(ICronTask)

    def wake_up(self, *args):
        if len(args) > 0:
            for arg in args:
                self.env.log.debug('Heart beat: %s' % arg)
        else:
            self.env.log.debug('Heart beat: boom boom !!!')

    def getId(self):
        return 'heart_beat'

    def getDescription(self):
        return self.__doc__


class SleepingTicketNotification(NotifyEmail):

    template_name = 'sleeping_ticket_template.txt'

    def __init__(self, env):
        NotifyEmail.__init__(self, env)

    def get_recipients(self, owner):
        return ([owner], [])

    def remind(self, tiketsByOwner, delay):
        """
        Send a digest mail to ticket owner to remind him of those
        sleeping tickets
        """
        for owner in tiketsByOwner:
            # prepare the data for the email content generation
            self.data.update({
                'ticket_count': len(tiketsByOwner[owner]),
                'delay': delay
            })
            NotifyEmail.notify(self, owner, 'Sleeping ticket notification')

    def send(self, torcpts, ccrcpts):
        return NotifyEmail.send(self, torcpts, ccrcpts)


class OrphanedTicketNotification(NotifyEmail):

    template_name = 'orphaned_ticket_template.txt'

    def __init__(self, env):
        NotifyEmail.__init__(self, env)

    def get_recipients(self, reporter):
        return ([reporter], [])

    def remind(self, tiketsByReporter, delay):
        """
        Send a digest mail to the reporter to remind them
        of those orphaned tickets
        """
        for reporter in tiketsByReporter:
            # prepare the data for the email content generation
            self.data.update({
                'ticket_count': len(tiketsByReporter[reporter]),
                'delay': delay
            })
            NotifyEmail.notify(self, reporter, 'orphaned ticket notification')

    def send(self, torcpts, ccrcpts):
        return NotifyEmail.send(self, torcpts, ccrcpts)


class SleepingTicketReminderTask(Component, ICronTask, ITemplateProvider):
    """
    Remind user about sleeping ticket they are assigned to.
    """
    implements(ICronTask, ITemplateProvider)

    delay_days = 3

    select_assigned_ticket = """
        SELECT t.id , t.owner
        FROM ticket t, ticket_change tc
        WHERE t.id = tc.ticket
        AND t.status in ('new','assigned','accepted')
        AND (SELECT MAX(tc2.time)
             FROM ticket_change tc2
             WHERE tc2.ticket=tc.ticket) < %s
        GROUP BY t.id
    """

    select_orphaned_ticket = """
       SELECT t.id, t.reporter
       FROM ticket t
       WHERE t.id not in (SELECT tc.ticket
                          FROM ticket_change tc
                          WHERE tc.ticket=t.id)
       AND t.time < %s
       AND t.status = 'new'
    """

    def get_htdocs_dirs(self):
        return []

    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__, 'templates')]

    def _find_sleeping_ticket(self, sql, delay, dico, msg):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        delay_time = datetime.now(utc) - timedelta(days=delay)
        cursor.execute(sql, (to_utimestamp(delay_time),))
        for ticket, recipient in cursor:
            self.env.log.info(msg % (ticket, recipient, delay))
            if recipient in dico:
                dico[recipient].append(ticket)
            else:
                dico[recipient] = [ticket]

    def remind_assigned_ticket(self, delay):
        dico = {}
        msg = 'warning sleeping ticket %d assigned to %s ' \
              'but is inactive since more than %d day'
        self._find_sleeping_ticket(self.select_assigned_ticket,
                                   delay, dico, msg)
        SleepingTicketNotification(self.env).remind(dico, delay)

    def remind_orphaned_ticket(self, delay):
        dico = {}
        msg = 'warning ticket %d is new but orphaned: %s, %d'
        self._find_sleeping_ticket(self.select_orphaned_ticket,
                                   delay, dico, msg)
        OrphanedTicketNotification(self.env).remind(dico, delay)

    def wake_up(self, *args):
        delay = SleepingTicketReminderTask.delay_days
        if len(args) > 0:
            delay = int(args[0])

        # look for ticket assigned but not touched since more that the delay
        self.remind_assigned_ticket(delay)
        self.remind_orphaned_ticket(delay)

    def getId(self):
        return 'sleeping_ticket'

    def getDescription(self):
        return self.__doc__


class BaseTicketNotification(NotifyEmail):

    def __init__(self, env, milestone):
        NotifyEmail.__init__(self, env)
        self.milestone = milestone

    def get_recipients(self, recipient):
        return ([recipient], [])

    def send(self, torcpts, ccrcpts):
        return NotifyEmail.send(self, torcpts, ccrcpts)

    def populate_unreachable_tickets_data(self, tickets):
        # we are not called if there is no tickets
        self.data['milestone'] = tickets[0]['milestone']
        due_date = from_utimestamp(tickets[0]['due'])
        self.data['due_date'] = due_date.strftime('%Y-%m-%d')

        tickets_list = ''
        for ticket in tickets:
            tickets_list += ticket['summary'] + '\n'
            tickets_list += self.env.abs_href.ticket(ticket['ticket']) + '\n'
            tickets_list += '\n'

        self.data['tickets_list'] = tickets_list

    def notify_opened_ticket(self, recipient, tickets):
        """
        Send a digest mail to recipients (e.g. ticket owner and reporter)
        about ticket still opened
        """
        self.populate_unreachable_tickets_data(tickets)
        subject = 'Milestone %s with still opened ticket' % self.milestone
        NotifyEmail.notify(self, recipient, subject)
        self.env.log.debug('notify opened ticket: %s, %s, %s' % (
                           recipient, self.milestone, self.__class__.__name__))


class ReporterOpenedTicketNotification(BaseTicketNotification):
    """
    Notify reporter about an opened ticket in a near milestone
    """
    template_name = "opened_ticket_for_reporter_template.txt"

    def __init__(self, env, milestone):
        BaseTicketNotification.__init__(self, env, milestone)


class OwnerOpenedTicketNotification(BaseTicketNotification):
    """
    Notify owner about an opened ticket in a near milestone
    """
    template_name = "opened_ticket_for_owner_template.txt"

    def __init__(self, env, milestone):
        BaseTicketNotification.__init__(self, env, milestone)


class UnreachableMilestoneNotification(BaseTicketNotification):
    """
    Notify the specified person (ex: admin, release manager) that a milestone
    is about to closed but there still are opened ticket
    """
    template_name = 'unreachable_milestone_template.txt'

    def __init__(self, env, milestone):
        BaseTicketNotification.__init__(self, env, milestone)
        self.cronconf = CronConfig(self.env)

    def get_recipients(self, milestone):
        reclist = self.cronconf.get_unreachable_milestone_task_recipient_list()
        return (reclist, [])

    def notify_unreachable_milestone(self, tickets):
        """
        Send a digest mail listing all tickets still opened in the milestone
        """
        self.populate_unreachable_tickets_data(tickets)
        subject = "Milestone %s still has opened ticket" % self.milestone
        NotifyEmail.notify(self, self.milestone, subject)
        self.env.log.debug('notify unreachable milestone: %s, %s' % (
                           self.milestone, self.__class__.__name__))


class UnreachableMilestoneTask(Component, ICronTask, ITemplateProvider):
    """
    Send notification about near milestone with opened ticked
    """
    implements(ICronTask, ITemplateProvider)

    ahead_days = 3

    select_near_milestone_ticket = """
        SELECT t.id , t.owner, t.reporter, t.milestone, t.summary, m.due
        FROM ticket t, milestone m
        WHERE t.milestone = m.name
        AND m.due < %s
    """

    def __init__(self):
        self.cronconf = CronConfig(self.env)

    def get_htdocs_dirs(self):
        return []

    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__, 'templates')]

    def _set_recipient_data(self, dico, recipient, milestone, ticket_data):
        dico.setdefault(recipient, {}).__setitem__(milestone, [ticket_data])
        dico[recipient].setdefault(milestone, []).append(ticket_data)

    def remind_unreachable_recipients(self, dico):
        """
        Send notification for each milestone
        """
        for milestone in dico:
            notifier = UnreachableMilestoneNotification(self.env, milestone)
            notifier.notify_unreachable_milestone(dico[milestone])

    def remind_recipient(self, dico, klass):
        """
        Send notification for owner or reporter
        """
        for recipient in dico:
            _dico = dico[recipient]
            for milestone in _dico:
                notifier = klass(self.env, milestone)
                notifier.notify_opened_ticket(recipient, _dico[milestone])

    def wake_up(self, *args):
        ahead = UnreachableMilestoneTask.ahead_days
        if len(args) > 0:
            ahead = int(args[0])

        # look opened ticket in near milestone
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        # select ticket whom milestone are due in less than some days ahead
        ahead_time = datetime.now(utc) + timedelta(days=ahead)
        cursor.execute(self.select_near_milestone_ticket,
                       (to_utimestamp(ahead_time),))

        dico, dico_owner, dico_reporter = {}, {}, {}
        for ticket, owner, reporter, milestone, summary, due in cursor:
            msg = 'warning ticket %d will probably miss its milestone %s' % (
                  ticket, milestone)
            self.env.log.info(msg)
            ticket_data = {
                'ticket': ticket,
                'owner': owner,
                'reporter': reporter,
                'milestone': milestone,
                'summary': summary,
                'due': due
            }
            dico.setdefault(milestone, []).append(ticket_data)
            self._set_recipient_data(dico_owner, owner, milestone, ticket_data)
            self._set_recipient_data(dico_reporter, reporter, milestone,
                                     ticket_data)

        self.remind_unreachable_recipients(dico)
        self.remind_recipient(dico_owner, OwnerOpenedTicketNotification)
        self.remind_recipient(dico_reporter, ReporterOpenedTicketNotification)

    def getId(self):
        return self.cronconf.UNREACHABLE_MILESTONE_TASK_BASEKEY

    def getDescription(self):
        return self.__doc__


class AutoPostponeTask(Component, ICronTask):
    """
    Scan closed milestone for still opened ticket then posptone those tickets
    to the next milestone
    """
    implements(ICronTask)

    select_next_milestone = """
        SELECT m.name, m.completed, m.due
        FROM milestone m
        WHERE m.completed is NULL or m.completed = 0
        AND m.due not NULL and m.due > 0
        ORDER BY m.due ASC LIMIT 1
    """

    select_closed_milestone_ticket = """
        SELECT t.id , t.milestone
        FROM ticket t, milestone m
        WHERE t.status != 'closed'
        AND t.milestone = m.name
        AND m.completed not NULL and m.completed > 0
    """

    def wake_up(self, *args):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        # find still opened more recent milestone
        # select ticket whom milestone are due in less than specified delay
        next_milestone = None
        cursor.execute(self.select_next_milestone)
        for name, completed, due in cursor:
            next_milestone = name

        if not next_milestone:
            msg = 'No opened milestone found. Cannot postpone tickets'
            self.env.log.debug(msg)
            return

        # select ticket whom milestone are due in less than specified delay
        cursor.execute(self.select_closed_milestone_ticket)
        for ticket_id, milestone in cursor:
            msg = 'Ticket %s is opened in closed milestone %s. ' \
                  'Should postpone this ticket to %s' % (
                  ticket_id, milestone, next_milestone)
            self.env.log.debug(msg)
            ticket = Ticket(self.env, ticket_id)
            ticket.populate({'milestone': next_milestone})
            ticket.save_changes(self.getId(), msg)

    def getId(self):
        return 'auto_postpone'

    def getDescription(self):
        return self.__doc__