blob: ead72adf7f2200b59907d0330bdd94986afd990a [file] [log] [blame]
Copybara854996b2021-09-07 19:36:02 +00001# Copyright 2016 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style
3# license that can be found in the LICENSE file or at
4# https://developers.google.com/open-source/licenses/bsd
5
6"""A servlet for project owners to create a new field def."""
7from __future__ import print_function
8from __future__ import division
9from __future__ import absolute_import
10
11import logging
12import re
13import time
14
15import ezt
16
17from framework import exceptions
18from framework import framework_helpers
19from framework import jsonfeed
20from framework import permissions
21from framework import servlet
22from framework import urls
23from proto import tracker_pb2
24from tracker import field_helpers
25from tracker import tracker_bizobj
26from tracker import tracker_constants
27from tracker import tracker_helpers
28
29
30class FieldCreate(servlet.Servlet):
31 """Servlet allowing project owners to create a custom field."""
32
33 _MAIN_TAB_MODE = servlet.Servlet.MAIN_TAB_PROCESS
34 _PAGE_TEMPLATE = 'tracker/field-create-page.ezt'
35
36 def AssertBasePermission(self, mr):
37 """Check whether the user has any permission to visit this page.
38
39 Args:
40 mr: commonly used info parsed from the request.
41 """
42 super(FieldCreate, self).AssertBasePermission(mr)
43 if not self.CheckPerm(mr, permissions.EDIT_PROJECT):
44 raise permissions.PermissionException(
45 'You are not allowed to administer this project')
46
47 def GatherPageData(self, mr):
48 """Build up a dictionary of data values to use when rendering the page.
49
50 Args:
51 mr: commonly used info parsed from the request.
52
53 Returns:
54 Dict of values used by EZT for rendering the page.
55 """
56 config = self.services.config.GetProjectConfig(mr.cnxn, mr.project_id)
57 well_known_issue_types = tracker_helpers.FilterIssueTypes(config)
58 approval_names = [fd.field_name for fd in config.field_defs if
59 fd.field_type is tracker_pb2.FieldTypes.APPROVAL_TYPE and
60 not fd.is_deleted]
61
62 return {
63 'admin_tab_mode': servlet.Servlet.PROCESS_TAB_LABELS,
64 'initial_field_name': '',
65 'initial_field_docstring': '',
66 'initial_importance': 'normal',
67 'initial_is_multivalued': ezt.boolean(False),
68 'initial_parent_approval_name': '',
69 'initial_choices': '',
70 'initial_admins': '',
71 'initial_editors': '',
72 'initial_type': 'enum_type',
73 'initial_applicable_type': '', # That means any issue type
74 'initial_applicable_predicate': '',
75 'initial_needs_member': ezt.boolean(False),
76 'initial_needs_perm': '',
77 'initial_grants_perm': '',
78 'initial_notify_on': 0,
79 'initial_date_action': 'no_action',
80 'well_known_issue_types': well_known_issue_types,
81 'initial_approvers': '',
82 'initial_survey': '',
83 'approval_names': approval_names,
84 'initial_is_phase_field': ezt.boolean(False),
85 'initial_is_restricted_field': ezt.boolean(False),
86 }
87
88 def ProcessFormData(self, mr, post_data):
89 """Validate and store the contents of the issues tracker admin page.
90
91 Args:
92 mr: commonly used info parsed from the request.
93 post_data: HTML form data from the request.
94
95 Returns:
96 String URL to redirect the user to, or None if response was already sent.
97 """
98 config = self.services.config.GetProjectConfig(mr.cnxn, mr.project_id)
99 parsed = field_helpers.ParseFieldDefRequest(post_data, config)
100
101 if not tracker_constants.FIELD_NAME_RE.match(parsed.field_name):
102 mr.errors.field_name = 'Invalid field name'
103
104 field_name_error_msg = FieldNameErrorMessage(parsed.field_name, config)
105 if field_name_error_msg:
106 mr.errors.field_name = field_name_error_msg
107
108 admin_ids, admin_str = tracker_helpers.ParsePostDataUsers(
109 mr.cnxn, post_data['admin_names'], self.services.user)
110 editor_ids, editor_str = tracker_helpers.ParsePostDataUsers(
111 mr.cnxn, post_data.get('editor_names', ''), self.services.user)
112
113 field_helpers.ParsedFieldDefAssertions(mr, parsed)
114
115 if not (parsed.is_restricted_field):
116 assert not editor_ids, 'Editors are only for restricted fields.'
117
118 # TODO(crbug/monorail/7275): This condition could potentially be
119 # included in the field_helpers.ParsedFieldDefAssertions method,
120 # just remember that it should be compatible with its usage in
121 # fielddetail.py where there is a very similar condition.
122 if parsed.field_type_str == 'approval_type':
123 assert not (
124 parsed.is_restricted_field), 'Approval fields cannot be restricted.'
125 if parsed.approvers_str:
126 approver_ids_dict = self.services.user.LookupUserIDs(
127 mr.cnxn, re.split('[,;\s]+', parsed.approvers_str),
128 autocreate=True)
129 approver_ids = list(set(approver_ids_dict.values()))
130 else:
131 mr.errors.approvers = 'Please provide at least one default approver.'
132
133 if mr.errors.AnyErrors():
134 self.PleaseCorrect(
135 mr,
136 initial_field_name=parsed.field_name,
137 initial_type=parsed.field_type_str,
138 initial_parent_approval_name=parsed.parent_approval_name,
139 initial_field_docstring=parsed.field_docstring,
140 initial_applicable_type=parsed.applicable_type,
141 initial_applicable_predicate=parsed.applicable_predicate,
142 initial_needs_member=ezt.boolean(parsed.needs_member),
143 initial_needs_perm=parsed.needs_perm,
144 initial_importance=parsed.importance,
145 initial_is_multivalued=ezt.boolean(parsed.is_multivalued),
146 initial_grants_perm=parsed.grants_perm,
147 initial_notify_on=parsed.notify_on,
148 initial_date_action=parsed.date_action_str,
149 initial_choices=parsed.choices_text,
150 initial_approvers=parsed.approvers_str,
151 initial_survey=parsed.survey,
152 initial_is_phase_field=parsed.is_phase_field,
153 initial_admins=admin_str,
154 initial_editors=editor_str,
155 initial_is_restricted_field=parsed.is_restricted_field)
156 return
157
158 approval_id = None
159 if parsed.parent_approval_name and (
160 parsed.field_type_str != 'approval_type'):
161 approval_fd = tracker_bizobj.FindFieldDef(
162 parsed.parent_approval_name, config)
163 if approval_fd:
164 approval_id = approval_fd.field_id
165 field_id = self.services.config.CreateFieldDef(
166 mr.cnxn,
167 mr.project_id,
168 parsed.field_name,
169 parsed.field_type_str,
170 parsed.applicable_type,
171 parsed.applicable_predicate,
172 parsed.is_required,
173 parsed.is_niche,
174 parsed.is_multivalued,
175 parsed.min_value,
176 parsed.max_value,
177 parsed.regex,
178 parsed.needs_member,
179 parsed.needs_perm,
180 parsed.grants_perm,
181 parsed.notify_on,
182 parsed.date_action_str,
183 parsed.field_docstring,
184 admin_ids,
185 editor_ids,
186 approval_id,
187 parsed.is_phase_field,
188 is_restricted_field=parsed.is_restricted_field)
189 if parsed.field_type_str == 'approval_type':
190 revised_approvals = field_helpers.ReviseApprovals(
191 field_id, approver_ids, parsed.survey, config)
192 self.services.config.UpdateConfig(
193 mr.cnxn, mr.project, approval_defs=revised_approvals)
194 if parsed.field_type_str == 'enum_type':
195 self.services.config.UpdateConfig(
196 mr.cnxn, mr.project, well_known_labels=parsed.revised_labels)
197
198 return framework_helpers.FormatAbsoluteURL(
199 mr, urls.ADMIN_LABELS, saved=1, ts=int(time.time()))
200
201
202def FieldNameErrorMessage(field_name, config):
203 """Return an error message for the given field name, or None."""
204 field_name_lower = field_name.lower()
205 if field_name_lower in tracker_constants.RESERVED_PREFIXES:
206 return 'That name is reserved.'
207 if field_name_lower.endswith(
208 tuple(tracker_constants.RESERVED_COL_NAME_SUFFIXES)):
209 return 'That suffix is reserved.'
210
211 for fd in config.field_defs:
212 fn_lower = fd.field_name.lower()
213 if field_name_lower == fn_lower:
214 return 'That name is already in use.'
215 if field_name_lower.startswith(fn_lower + '-'):
216 return 'An existing field name is a prefix of that name.'
217 if fn_lower.startswith(field_name_lower + '-'):
218 return 'That name is a prefix of an existing field name.'
219
220 return None