Merge pull request #15083 from civicrm/5.17
[civicrm-core.git] / CRM / Case / Form / Activity / OpenCase.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34 /**
35 * This class generates form components for OpenCase Activity.
36 */
37 class CRM_Case_Form_Activity_OpenCase {
38
39 /**
40 * The id of the client associated with this case.
41 *
42 * @var int
43 */
44 public $_contactID;
45
46 /**
47 * @param CRM_Case_Form_Case $form
48 *
49 * @throws \CRM_Core_Exception
50 */
51 public static function preProcess(&$form) {
52 //get multi client case configuration
53 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
54 $form->_allowMultiClient = (bool) $xmlProcessorProcess->getAllowMultipleCaseClients();
55
56 if ($form->_context == 'caseActivity') {
57 $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $form);
58 $atype = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Case Start Date');
59 $caseId = CRM_Utils_Array::first($form->_caseId);
60 $form->assign('changeStartURL', CRM_Utils_System::url('civicrm/case/activity',
61 "action=add&reset=1&cid=$contactID&caseid={$caseId}&atype=$atype"
62 )
63 );
64 return;
65 }
66
67 $form->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $form);
68 $form->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $form);
69 $form->assign('context', $form->_context);
70
71 // check if the case type id passed in url is a valid one
72 $caseTypeId = CRM_Utils_Request::retrieve('ctype', 'Positive', $form);
73 $caseTypes = CRM_Case_BAO_Case::buildOptions('case_type_id', 'create');
74 $form->_caseTypeId = array_key_exists($caseTypeId, $caseTypes) ? $caseTypeId : NULL;
75
76 // check if the case status id passed in url is a valid one
77 $caseStatusId = CRM_Utils_Request::retrieve('case_status_id', 'Positive', $form);
78 $caseStatus = CRM_Case_PseudoConstant::caseStatus();
79 $form->_caseStatusId = array_key_exists($caseStatusId, $caseStatus) ? $caseStatusId : NULL;
80
81 // Add attachments
82 CRM_Core_BAO_File::buildAttachment($form, 'civicrm_activity', $form->_activityId);
83 $session = CRM_Core_Session::singleton();
84 $session->pushUserContext(CRM_Utils_System::url('civicrm/case', 'reset=1'));
85 }
86
87 /**
88 * Set default values for the form. For edit/view mode
89 * the default values are retrieved from the database
90 *
91 * @param CRM_Case_Form_Case $form
92 *
93 * @return array $defaults
94 */
95 public static function setDefaultValues(&$form) {
96 $defaults = [];
97 if ($form->_context == 'caseActivity') {
98 return $defaults;
99 }
100
101 $defaults['start_date'] = date('Y-m-d H:i:s');
102
103 // set default case status, case type, encounter medium, location type and phone type defaults are set in DB
104 if ($form->_caseStatusId) {
105 $caseStatus = $form->_caseStatusId;
106 }
107 else {
108 $caseStatus = CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, 'AND is_default = 1');
109 if (count($caseStatus) == 1) {
110 //$defaults['status_id'] = key($caseStatus);
111 $caseStatus = key($caseStatus);
112 }
113 }
114 $defaults['status_id'] = $caseStatus;
115
116 // set default case type passed in url
117 if ($form->_caseTypeId) {
118 $defaults['case_type_id'] = $form->_caseTypeId;
119 }
120 else {
121 // TODO: Not possible yet to set a default case type in the system
122 // For now just add the convenience of auto-selecting if there is only one option
123 $caseTypes = CRM_Case_BAO_Case::buildOptions('case_type_id', 'create');
124 if (count($caseTypes) == 1) {
125 reset($caseTypes);
126 $defaults['case_type_id'] = key($caseTypes);
127 }
128 }
129
130 $medium = CRM_Core_OptionGroup::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
131 if (count($medium) == 1) {
132 $defaults['medium_id'] = key($medium);
133 }
134
135 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
136 if ($defaultLocationType->id) {
137 $defaults['location[1][location_type_id]'] = $defaultLocationType->id;
138 }
139
140 $phoneType = CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, 'AND is_default = 1');
141 if (count($phoneType) == 1) {
142 $defaults['location[1][phone][1][phone_type_id]'] = key($phoneType);
143 }
144
145 return $defaults;
146 }
147
148 /**
149 * @param CRM_Case_Form_Case $form
150 */
151 public static function buildQuickForm(&$form) {
152 if ($form->_context == 'caseActivity') {
153 return;
154 }
155 if ($form->_context == 'standalone') {
156 $form->addEntityRef('client_id', ts('Client'), [
157 'create' => TRUE,
158 'multiple' => $form->_allowMultiClient,
159 ], TRUE);
160 }
161
162 $element = $form->addField('case_type_id', [
163 'context' => 'create',
164 'entity' => 'Case',
165 'onchange' => "CRM.buildCustomData('Case', this.value);",
166 ], TRUE);
167 if ($form->_caseTypeId) {
168 $element->freeze();
169 }
170
171 $csElement = $form->addField('status_id', [
172 'context' => 'create',
173 'entity' => 'Case',
174 ], TRUE);
175 if ($form->_caseStatusId) {
176 $csElement->freeze();
177 }
178
179 $form->add('number', 'duration', ts('Activity Duration'), ['class' => 'four', 'min' => 1]);
180 $form->addRule('duration', ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger');
181
182 if ($form->_currentlyViewedContactId) {
183 list($displayName) = CRM_Contact_BAO_Contact::getDisplayAndImage($form->_currentlyViewedContactId);
184 $form->assign('clientName', $displayName);
185 }
186
187 $form->add('datepicker', 'start_date', ts('Case Start Date'), [], TRUE);
188
189 $form->addField('medium_id', ['entity' => 'activity', 'context' => 'create'], TRUE);
190
191 // calling this field activity_location to prevent conflict with contact location fields
192 $form->add('text', 'activity_location', ts('Location'), CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity', 'location'));
193
194 $form->add('wysiwyg', 'activity_details', ts('Details'), ['rows' => 4, 'cols' => 60], FALSE);
195
196 $form->addButtons([
197 [
198 'type' => 'upload',
199 'name' => ts('Save'),
200 'isDefault' => TRUE,
201 ],
202 [
203 'type' => 'upload',
204 'name' => ts('Save and New'),
205 'subName' => 'new',
206 ],
207 [
208 'type' => 'cancel',
209 'name' => ts('Cancel'),
210 ],
211 ]);
212 }
213
214 /**
215 * Process the form submission.
216 *
217 * @param CRM_Case_Form_Case $form
218 * @param array $params
219 */
220 public static function beginPostProcess(&$form, &$params) {
221 if ($form->_context == 'caseActivity') {
222 return;
223 }
224
225 if ($form->_context == 'standalone') {
226 $params['client_id'] = explode(',', $params['client_id']);
227 $form->_currentlyViewedContactId = $params['client_id'][0];
228 }
229
230 // rename activity_location param to the correct column name for activity DAO
231 $params['location'] = CRM_Utils_Array::value('activity_location', $params);
232
233 // Add attachments
234 CRM_Core_BAO_File::formatAttachment(
235 $params,
236 $params,
237 'civicrm_activity',
238 $form->_activityId
239 );
240
241 }
242
243 /**
244 * Global validation rules for the form.
245 *
246 * @param $fields
247 * @param $files
248 * @param CRM_Case_Form_Case $form
249 *
250 * @return array
251 * list of errors to be posted back to the form
252 */
253 public static function formRule($fields, $files, $form) {
254 if ($form->_context == 'caseActivity') {
255 return TRUE;
256 }
257
258 $errors = [];
259 return $errors;
260 }
261
262 /**
263 * Process the form submission.
264 *
265 * @param CRM_Case_Form_Case $form
266 * @param array $params
267 *
268 * @throws \Exception
269 */
270 public static function endPostProcess(&$form, &$params) {
271 if ($form->_context == 'caseActivity') {
272 return;
273 }
274
275 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
276 $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
277
278 if (!$isMultiClient && !$form->_currentlyViewedContactId) {
279 CRM_Core_Error::fatal('Required parameter missing for OpenCase - end post processing');
280 }
281
282 if (!$form->_currentUserId ||
283 !$params['case_id'] ||
284 !$params['case_type']
285 ) {
286 CRM_Core_Error::fatal('Required parameter missing for OpenCase - end post processing');
287 }
288
289 // 1. create case-contact
290 if ($isMultiClient && $form->_context == 'standalone') {
291 foreach ($params['client_id'] as $cliId) {
292 if (empty($cliId)) {
293 CRM_Core_Error::fatal('client_id cannot be empty');
294 }
295 $contactParams = [
296 'case_id' => $params['case_id'],
297 'contact_id' => $cliId,
298 ];
299 CRM_Case_BAO_CaseContact::create($contactParams);
300 }
301 }
302 else {
303 $contactParams = [
304 'case_id' => $params['case_id'],
305 'contact_id' => $form->_currentlyViewedContactId,
306 ];
307 CRM_Case_BAO_CaseContact::create($contactParams);
308 }
309
310 // 2. initiate xml processor
311 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
312
313 $xmlProcessorParams = [
314 'clientID' => $form->_currentlyViewedContactId,
315 'creatorID' => $form->_currentUserId,
316 'standardTimeline' => 1,
317 'activityTypeName' => 'Open Case',
318 'caseID' => $params['case_id'],
319 'subject' => $params['activity_subject'],
320 'location' => $params['location'],
321 'activity_date_time' => $params['start_date'],
322 'duration' => CRM_Utils_Array::value('duration', $params),
323 'medium_id' => $params['medium_id'],
324 'details' => $params['activity_details'],
325 'relationship_end_date' => CRM_Utils_Array::value('end_date', $params),
326 ];
327
328 if (array_key_exists('custom', $params) && is_array($params['custom'])) {
329 $xmlProcessorParams['custom'] = $params['custom'];
330 }
331
332 // Add parameters for attachments
333 $numAttachments = Civi::settings()->get('max_attachments');
334 for ($i = 1; $i <= $numAttachments; $i++) {
335 $attachName = "attachFile_$i";
336 if (isset($params[$attachName]) && !empty($params[$attachName])) {
337 $xmlProcessorParams[$attachName] = $params[$attachName];
338 }
339 }
340
341 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
342
343 // status msg
344 $params['statusMsg'] = ts('Case opened successfully.');
345
346 $buttonName = $form->controller->getButtonName();
347 $session = CRM_Core_Session::singleton();
348 if ($buttonName == $form->getButtonName('upload', 'new')) {
349 if ($form->_context == 'standalone') {
350 $session->replaceUserContext(CRM_Utils_System::url('civicrm/case/add',
351 'reset=1&action=add&context=standalone'
352 ));
353 }
354 else {
355 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/case',
356 "reset=1&action=add&context=case&cid={$form->_contactID}"
357 ));
358 }
359 }
360 }
361
362 }