Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-01-12-16-09-32
[civicrm-core.git] / CRM / Campaign / Form / Task / Reserve.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class provides the functionality to add contacts for
38 * voter reservation.
39 */
40 class CRM_Campaign_Form_Task_Reserve extends CRM_Campaign_Form_Task {
41
42 /**
43 * Survet id`
44 *
45 * @var int
46 */
47 protected $_surveyId;
48
49 /**
50 * Interviewer id
51 *
52 * @var int
53 */
54 protected $_interviewerId;
55
56 /**
57 * Survey details
58 *
59 * @var object
60 */
61 protected $_surveyDetails;
62
63 /**
64 * Number of voters
65 *
66 * @var int
67 */
68 protected $_numVoters;
69
70 /**
71 * Build all the data structures needed to build the form
72 *
73 * @return void
74 */
75 public function preProcess() {
76 parent::preProcess();
77
78 //get the survey id from user submitted values.
79 $this->_surveyId = $this->get('surveyId');
80 $this->_interviewerId = $this->get('interviewerId');
81 if (!$this->_surveyId) {
82 CRM_Core_Error::statusBounce(ts("Could not find Survey Id."));
83 }
84 if (!$this->_interviewerId) {
85 CRM_Core_Error::statusBounce(ts("Missing Interviewer contact."));
86 }
87 if (!is_array($this->_contactIds) || empty($this->_contactIds)) {
88 CRM_Core_Error::statusBounce(ts("Could not find contacts for reservation."));
89 }
90
91 $params = array('id' => $this->_surveyId);
92 CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
93
94 //get the survey activities.
95 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
96 $statusIds = array();
97 foreach (array(
98 'Scheduled'
99 ) as $name) {
100 if ($statusId = array_search($name, $activityStatus)) {
101 $statusIds[] = $statusId;
102 }
103 }
104
105 // these are the activities count that are linked to the current
106 // interviewer and current survey and not the list of ALL survey activities
107 $this->_numVoters = CRM_Campaign_BAO_Survey::getSurveyActivities($this->_surveyId,
108 $this->_interviewerId,
109 $statusIds,
110 NULL,
111 TRUE
112 );
113 //validate the selected survey.
114 $this->validateSurvey();
115 $this->assign('surveyTitle', $this->_surveyDetails['title']);
116 $this->assign('activityType', $this->_surveyDetails['activity_type_id']);
117 $this->assign('surveyId', $this->_surveyId);
118
119 //append breadcrumb to survey dashboard.
120 if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
121 $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
122 CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
123 }
124
125 //set the title.
126 CRM_Utils_System::setTitle(ts('Reserve Respondents'));
127 }
128
129 public function validateSurvey() {
130 $errorMsg = NULL;
131 $maxVoters = CRM_Utils_Array::value('max_number_of_contacts', $this->_surveyDetails);
132 if ($maxVoters) {
133 if ($maxVoters <= $this->_numVoters) {
134 $errorMsg = ts('The maximum number of contacts is already reserved for this interviewer.');
135 }
136 elseif (count($this->_contactIds) > ($maxVoters - $this->_numVoters)) {
137 $errorMsg = ts('You can reserve a maximum of %1 contact(s) at a time for this survey.',
138 array(1 => $maxVoters - $this->_numVoters)
139 );
140 }
141 }
142
143 $defaultNum = CRM_Utils_Array::value('default_number_of_contacts', $this->_surveyDetails);
144 if (!$errorMsg && $defaultNum && (count($this->_contactIds) > $defaultNum)) {
145 $errorMsg = ts('You can reserve a maximum of %1 contact(s) at a time for this survey.',
146 array(1 => $defaultNum)
147 );
148 }
149
150 if ($errorMsg) {
151 CRM_Core_Error::statusBounce($errorMsg);
152 }
153 }
154
155 /**
156 * Build the form object
157 *
158 *
159 * @return void
160 */
161 public function buildQuickForm() {
162 // allow to add contact to either new or existing group.
163 $this->addElement('text', 'ActivityType', ts('Activity Type'));
164 $this->addElement('text', 'newGroupName', ts('Name for new group'));
165 $this->addElement('text', 'newGroupDesc', ts('Description of new group'));
166 $groups = CRM_Core_PseudoConstant::nestedGroup();
167 $hasExistingGroups = FALSE;
168 if (is_array($groups) && !empty($groups)) {
169 $hasExistingGroups = TRUE;
170 $this->addElement('select', 'groups', ts('Add respondent(s) to existing group(s)'),
171 $groups, array('multiple' => "multiple", 'class' => 'crm-select2')
172 );
173 }
174 $this->assign('hasExistingGroups', $hasExistingGroups);
175
176 $buttons = array(
177 array(
178 'type' => 'done',
179 'name' => ts('Reserve'),
180 'subName' => 'reserve',
181 'isDefault' => TRUE,
182 )
183 );
184
185 if (CRM_Core_Permission::check('manage campaign') ||
186 CRM_Core_Permission::check('administer CiviCampaign') ||
187 CRM_Core_Permission::check('interview campaign contacts')
188 ) {
189 $buttons[] = array(
190 'type' => 'next',
191 'name' => ts('Reserve and Interview'),
192 'subName' => 'reserveToInterview',
193 );
194 }
195 $buttons[] = array(
196 'type' => 'back',
197 'name' => ts('Cancel'),
198 );
199
200 $this->addButtons($buttons);
201 $this->addFormRule(array('CRM_Campaign_Form_Task_Reserve', 'formRule'), $this);
202 }
203
204 /**
205 * Global validation rules for the form
206 *
207 * @param array $fields
208 * Posted values of the form.
209 *
210 * @param $files
211 * @param $self
212 *
213 * @return array
214 * list of errors to be posted back to the form
215 * @static
216 */
217 public static function formRule($fields, $files, $self) {
218 $errors = array();
219 $invalidGroupName = FALSE;
220 if (!empty($fields['newGroupName'])) {
221 $title = trim($fields['newGroupName']);
222 $name = CRM_Utils_String::titleToVar($title);
223 $query = 'select count(*) from civicrm_group where name like %1 OR title like %2';
224 $grpCnt = CRM_Core_DAO::singleValueQuery($query, array(
225 1 => array($name, 'String'),
226 2 => array($title, 'String'),
227 ));
228 if ($grpCnt) {
229 $invalidGroupName = TRUE;
230 $errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
231 }
232 }
233 $self->assign('invalidGroupName', $invalidGroupName);
234
235 return empty($errors) ? TRUE : $errors;
236 }
237
238 /**
239 * Process the form after the input has been submitted and validated
240 *
241 *
242 * @return void
243 */
244 public function postProcess() {
245 //add reservation.
246 $countVoters = 0;
247 $maxVoters = CRM_Utils_Array::value('max_number_of_contacts', $this->_surveyDetails);
248 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
249 $statusHeld = array_search('Scheduled', $activityStatus);
250
251 $reservedVoterIds = array();
252 foreach ($this->_contactIds as $cid) {
253 $subject = ts('%1', array(1 => $this->_surveyDetails['title'])) . ' - ' . ts('Respondent Reservation');
254 $session = CRM_Core_Session::singleton();
255 $activityParams = array(
256 'source_contact_id' => $session->get('userID'),
257 'assignee_contact_id' => array($this->_interviewerId),
258 'target_contact_id' => array($cid),
259 'source_record_id' => $this->_surveyId,
260 'activity_type_id' => $this->_surveyDetails['activity_type_id'],
261 'subject' => $subject,
262 'activity_date_time' => date('YmdHis'),
263 'status_id' => $statusHeld,
264 'skipRecentView' => 1,
265 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_surveyDetails),
266 );
267 $activity = CRM_Activity_BAO_Activity::create($activityParams);
268 if ($activity->id) {
269 $countVoters++;
270 $reservedVoterIds[$cid] = $cid;
271 }
272 if ($maxVoters && ($maxVoters <= ($this->_numVoters + $countVoters))) {
273 break;
274 }
275 }
276
277 //add reserved voters to groups.
278 $groupAdditions = $this->_addRespondentToGroup($reservedVoterIds);
279
280 // Success message
281 if ($countVoters > 0) {
282 $status = '<p>' . ts("%1 Contact(s) have been reserved.", array(1 => $countVoters)) . '</p>';
283 if ($groupAdditions) {
284 $status .= '<p>' . ts('Respondent(s) has been added to %1 group(s).',
285 array(1 => implode(', ', $groupAdditions))
286 ) . '</p>';
287 }
288 CRM_Core_Session::setStatus($status, ts('Reservation Added'), 'success');
289 }
290 // Error message
291 if (count($this->_contactIds) > $countVoters) {
292 CRM_Core_Session::setStatus(ts('Reservation did not add for %1 contact(s).',
293 array(1 => (count($this->_contactIds) - $countVoters))
294 ), ts('Notice'));
295 }
296
297 //get ready to jump to voter interview form.
298 $buttonName = $this->controller->getButtonName();
299 if (!empty($reservedVoterIds) &&
300 $buttonName == '_qf_Reserve_next_reserveToInterview'
301 ) {
302 $this->controller->set('surveyId', $this->_surveyId);
303 $this->controller->set('contactIds', $reservedVoterIds);
304 $this->controller->set('interviewerId', $this->_interviewerId);
305 $this->controller->set('reserveToInterview', TRUE);
306 }
307 }
308
309 /**
310 * @param $contactIds
311 *
312 * @return array
313 */
314 private function _addRespondentToGroup($contactIds) {
315 $groupAdditions = array();
316 if (empty($contactIds)) {
317 return $groupAdditions;
318 }
319
320 $params = $this->controller->exportValues($this->_name);
321 $groups = CRM_Utils_Array::value('groups', $params, array());
322 $newGroupName = CRM_Utils_Array::value('newGroupName', $params);
323 $newGroupDesc = CRM_Utils_Array::value('newGroupDesc', $params);
324
325 $newGroupId = NULL;
326 //create new group.
327 if ($newGroupName) {
328 $grpParams = array(
329 'title' => $newGroupName,
330 'description' => $newGroupDesc,
331 'is_active' => TRUE,
332 );
333 $group = CRM_Contact_BAO_Group::create($grpParams);
334 $groups[] = $newGroupId = $group->id;
335 }
336
337 //add the respondents to groups.
338 if (is_array($groups)) {
339 $existingGroups = CRM_Core_PseudoConstant::group();
340 foreach ($groups as $groupId) {
341 $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
342 $totalCount = CRM_Utils_Array::value(1, $addCount);
343 if ($groupId == $newGroupId) {
344 $name = $newGroupName;
345 $new = TRUE;
346 }
347 else {
348 $name = $existingGroups[$groupId];
349 $new = FALSE;
350 }
351 if ($totalCount) {
352 $url = CRM_Utils_System::url('civicrm/group/search',
353 'reset=1&force=1&context=smog&gid=' . $groupId
354 );
355 $groupAdditions[] = '<a href="' . $url . '">' . $name . '</a>';
356 }
357 }
358 }
359
360 return $groupAdditions;
361 }
362 }