/
batch.py
233 lines (204 loc) · 9.53 KB
/
batch.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Brian Meeker
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Brian Meeker <meeker.brian@gmail.com>
import re
from datetime import datetime
from genshi.builder import tag
from trac.core import *
from trac.notification.api import NotificationSystem
from trac.perm import IPermissionRequestor
from trac.ticket import TicketSystem, Ticket
from trac.ticket.notification import BatchTicketChangeEvent
from trac.util.datefmt import parse_date, user_time, utc
from trac.util.text import exception_to_unicode, to_unicode
from trac.util.translation import _, tag_
from trac.web import IRequestHandler
from trac.web.chrome import add_warning, add_script_data
class BatchModifyModule(Component):
"""Ticket batch modification module.
This component allows multiple tickets to be modified in one request from
the custom query page. For users with the TICKET_BATCH_MODIFY permission
it will add a [TracBatchModify batch modify] section underneath custom
query results. Users can choose which tickets and fields they wish to
modify.
"""
implements(IPermissionRequestor, IRequestHandler)
is_valid_default_handler = False
list_separator_re = re.compile(r'[;\s,]+')
list_connector_string = ', '
# IRequestHandler methods
def match_request(self, req):
return req.path_info == '/batchmodify'
def process_request(self, req):
req.perm.assert_permission('TICKET_BATCH_MODIFY')
comment = req.args.get('batchmod_value_comment', '')
action = req.args.get('action')
try:
new_values = self._get_new_ticket_values(req)
except TracError as e:
new_values = None
add_warning(req, tag_("The changes could not be saved: "
"%(message)s", message=to_unicode(e)))
if new_values is not None:
selected_tickets = self._get_selected_tickets(req)
self._save_ticket_changes(req, selected_tickets,
new_values, comment, action)
# Always redirect back to the query page we came from.
req.redirect(req.session['query_href'])
# IPermissionRequestor methods
def get_permission_actions(self):
return ['TICKET_BATCH_MODIFY',
('TICKET_ADMIN', ['TICKET_BATCH_MODIFY'])]
def _get_new_ticket_values(self, req):
"""Pull all of the new values out of the post data."""
values = {}
for field in TicketSystem(self.env).get_ticket_fields():
name = field['name']
if name not in ('id', 'resolution', 'status', 'owner', 'time',
'changetime', 'summary', 'description') + \
(('reporter',) if 'TICKET_ADMIN' not in req.perm
else ()) \
and field['type'] != 'textarea':
value = req.args.get('batchmod_value_' + name)
if value is not None:
values[name] = self._parse_field_value(req, field, value)
return values
def _parse_field_value(self, req, field, value):
if field['type'] == 'time':
return user_time(req, parse_date, value)
return value
def _get_selected_tickets(self, req):
"""The selected tickets will be a comma separated list
in the request arguments."""
selected_tickets = req.args.get('selected_tickets')
if selected_tickets == '':
return []
else:
return selected_tickets.split(',')
def add_template_data(self, req, data, tickets):
data['batch_modify'] = True
data['query_href'] = req.session['query_href'] or req.href.query()
data['action_controls'] = self._get_action_controls(req, tickets)
batch_list_modes = [
{'name': _("add"), 'value': "+"},
{'name': _("remove"), 'value': "-"},
{'name': _("add / remove"), 'value': "+-"},
{'name': _("set to"), 'value': "="},
]
add_script_data(req, batch_list_modes=batch_list_modes,
batch_list_properties=self._get_list_fields())
def _get_list_fields(self):
return [f['name']
for f in TicketSystem(self.env).get_ticket_fields()
if f['type'] == 'text' and f.get('format') == 'list']
def _get_action_controls(self, req, tickets):
action_controls = []
ts = TicketSystem(self.env)
tickets_by_action = {}
for t in tickets:
ticket = Ticket(self.env, t['id'])
actions = ts.get_available_actions(req, ticket)
for action in actions:
tickets_by_action.setdefault(action, []).append(ticket)
sorted_actions = sorted(set(tickets_by_action.keys()))
for action in sorted_actions:
first_label = None
hints = []
widgets = []
ticket = tickets_by_action[action][0]
for controller in self._get_action_controllers(req, ticket,
action):
label, widget, hint = controller.render_ticket_action_control(
req, ticket, action)
if not first_label:
first_label = label
widgets.append(widget)
hints.append(hint)
action_controls.append((action, first_label, tag(widgets), hints))
return action_controls
def _get_action_controllers(self, req, ticket, action):
"""Generator yielding the controllers handling the given `action`"""
for controller in TicketSystem(self.env).action_controllers:
actions = [a for w, a in
controller.get_ticket_actions(req, ticket) or []]
if action in actions:
yield controller
def _save_ticket_changes(self, req, selected_tickets,
new_values, comment, action):
"""Save all of the changes to tickets."""
when = datetime.now(utc)
list_fields = self._get_list_fields()
with self.env.db_transaction as db:
for id in selected_tickets:
t = Ticket(self.env, int(id))
_values = new_values.copy()
for field in list_fields:
if field in new_values:
old = t[field] if field in t else ''
new = new_values[field]
mode = req.args.get('batchmod_value_' + field +
'_mode')
new2 = req.args.get('batchmod_value_' + field +
'_secondary', '')
_values[field] = self._change_list(old, new, new2,
mode)
controllers = list(self._get_action_controllers(req, t,
action))
for controller in controllers:
_values.update(controller.get_ticket_changes(req, t,
action))
t.populate(_values)
t.save_changes(req.authname, comment, when=when)
for controller in controllers:
controller.apply_action_side_effects(req, t, action)
event = BatchTicketChangeEvent(selected_tickets, when,
req.authname, comment, new_values,
action)
try:
NotificationSystem(self.env).notify(event)
except Exception as e:
self.log.error("Failure sending notification on ticket batch"
"change: %s", exception_to_unicode(e))
add_warning(req, tag_("The changes have been saved, but an "
"error occurred while sending "
"notifications: %(message)s",
message=to_unicode(e)))
def _change_list(self, old_list, new_list, new_list2, mode):
changed_list = [k.strip()
for k in self.list_separator_re.split(old_list)
if k]
new_list = [k.strip()
for k in self.list_separator_re.split(new_list)
if k]
new_list2 = [k.strip()
for k in self.list_separator_re.split(new_list2)
if k]
if mode == '=':
changed_list = new_list
elif mode == '+':
for entry in new_list:
if entry not in changed_list:
changed_list.append(entry)
elif mode == '-':
for entry in new_list:
while entry in changed_list:
changed_list.remove(entry)
elif mode == '+-':
for entry in new_list:
if entry not in changed_list:
changed_list.append(entry)
for entry in new_list2:
while entry in changed_list:
changed_list.remove(entry)
return self.list_connector_string.join(changed_list)