Merge pull request #14452 from eileenmcnaughton/payment_activity
[civicrm-core.git] / CRM / Core / Form / RecurringEntity.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 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2019
33 */
34
35 /**
36 * This class generates form components for processing Entity.
37 */
38 class CRM_Core_Form_RecurringEntity {
39 /**
40 * Current entity id
41 * @var int
42 */
43 protected static $_entityId = NULL;
44
45 /**
46 * Schedule Reminder ID
47 * @var int
48 */
49 protected static $_scheduleReminderID = NULL;
50
51 /**
52 * Schedule Reminder data
53 * @var array
54 */
55 protected static $_scheduleReminderDetails = [];
56
57 /**
58 * Parent Entity ID
59 * @var int
60 */
61 protected static $_parentEntityId = NULL;
62
63 /**
64 * Exclude date information
65 * @var array
66 */
67 public static $_excludeDateInfo = [];
68
69 /**
70 * Entity Table
71 * @var string
72 */
73 public static $_entityTable;
74
75 /**
76 * Checks current entityID has parent
77 * @var string
78 */
79 public static $_hasParent = FALSE;
80
81 /**
82 * @param $entityTable
83 */
84 public static function preProcess($entityTable) {
85 self::$_entityId = (int) CRM_Utils_Request::retrieve('id', 'Positive');
86 self::$_entityTable = $entityTable;
87
88 if (self::$_entityId && $entityTable) {
89 $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor(self::$_entityId, $entityTable);
90 if ($checkParentExistsForThisId) {
91 self::$_hasParent = TRUE;
92 self::$_parentEntityId = $checkParentExistsForThisId;
93 self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $entityTable);
94 }
95 else {
96 self::$_parentEntityId = self::$_entityId;
97 self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId(self::$_entityId, $entityTable);
98 }
99 if (property_exists(self::$_scheduleReminderDetails, 'id')) {
100 self::$_scheduleReminderID = self::$_scheduleReminderDetails->id;
101 }
102 }
103 CRM_Core_OptionValue::getValues(['name' => $entityTable . '_repeat_exclude_dates_' . self::$_parentEntityId], $optionValue);
104 $excludeOptionValues = [];
105 if (!empty($optionValue)) {
106 foreach ($optionValue as $key => $val) {
107 $excludeOptionValues[$val['value']] = substr(CRM_Utils_Date::mysqlToIso($val['value']), 0, 10);
108 }
109 self::$_excludeDateInfo = $excludeOptionValues;
110 }
111
112 // Assign variables
113 $entityType = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable));
114 $tpl = CRM_Core_Smarty::singleton();
115 $tpl->assign('recurringEntityType', ts($entityType));
116 $tpl->assign('currentEntityId', self::$_entityId);
117 $tpl->assign('entityTable', self::$_entityTable);
118 $tpl->assign('scheduleReminderId', self::$_scheduleReminderID);
119 $tpl->assign('hasParent', self::$_hasParent);
120 }
121
122 /**
123 * Set default values for the form. For edit/view mode
124 * the default values are retrieved from the database
125 *
126 *
127 * @return array
128 */
129 public static function setDefaultValues() {
130 // Defaults for new entity
131 $defaults = [
132 'repetition_frequency_unit' => 'week',
133 ];
134
135 // Default for existing entity
136 if (self::$_scheduleReminderID) {
137 $defaults['repetition_frequency_unit'] = self::$_scheduleReminderDetails->repetition_frequency_unit;
138 $defaults['repetition_frequency_interval'] = self::$_scheduleReminderDetails->repetition_frequency_interval;
139 $defaults['start_action_condition'] = array_flip(explode(",", self::$_scheduleReminderDetails->start_action_condition));
140 foreach ($defaults['start_action_condition'] as $key => $val) {
141 $val = 1;
142 $defaults['start_action_condition'][$key] = $val;
143 }
144 $defaults['start_action_offset'] = self::$_scheduleReminderDetails->start_action_offset;
145 if (self::$_scheduleReminderDetails->start_action_offset) {
146 $defaults['ends'] = 1;
147 }
148 $defaults['repeat_absolute_date'] = self::$_scheduleReminderDetails->absolute_date;
149 if (self::$_scheduleReminderDetails->absolute_date) {
150 $defaults['ends'] = 2;
151 }
152 $defaults['limit_to'] = self::$_scheduleReminderDetails->limit_to;
153 if (self::$_scheduleReminderDetails->limit_to) {
154 $defaults['repeats_by'] = 1;
155 }
156 if (self::$_scheduleReminderDetails->entity_status) {
157 $explodeStartActionCondition = explode(" ", self::$_scheduleReminderDetails->entity_status);
158 $defaults['entity_status_1'] = $explodeStartActionCondition[0];
159 $defaults['entity_status_2'] = $explodeStartActionCondition[1];
160 }
161 if (self::$_scheduleReminderDetails->entity_status) {
162 $defaults['repeats_by'] = 2;
163 }
164 if (self::$_excludeDateInfo) {
165 $defaults['exclude_date_list'] = implode(',', self::$_excludeDateInfo);
166 }
167 }
168 return $defaults;
169 }
170
171 /**
172 * Build form.
173 *
174 * @param CRM_Core_Form $form
175 */
176 public static function buildQuickForm(&$form) {
177 // FIXME: this is using the following as keys rather than the standard numeric keys returned by CRM_Utils_Date
178 $dayOfTheWeek = [];
179 $dayKeys = [
180 'sunday',
181 'monday',
182 'tuesday',
183 'wednesday',
184 'thursday',
185 'friday',
186 'saturday',
187 ];
188 foreach (CRM_Utils_Date::getAbbrWeekdayNames() as $k => $label) {
189 $dayOfTheWeek[$dayKeys[$k]] = $label;
190 }
191 $form->add('select', 'repetition_frequency_unit', ts('Repeats every'), CRM_Core_SelectValues::getRecurringFrequencyUnits(), FALSE, ['class' => 'required']);
192 $numericOptions = CRM_Core_SelectValues::getNumericOptions(1, 30);
193 $form->add('select', 'repetition_frequency_interval', NULL, $numericOptions, FALSE, ['class' => 'required']);
194 $form->add('datepicker', 'repetition_start_date', ts('Start Date'), [], FALSE, ['time' => TRUE]);
195 foreach ($dayOfTheWeek as $key => $val) {
196 $startActionCondition[] = $form->createElement('checkbox', $key, NULL, $val);
197 }
198 $form->addGroup($startActionCondition, 'start_action_condition', ts('Repeats on'));
199 $roptionTypes = [
200 '1' => ts('day of the month'),
201 '2' => ts('day of the week'),
202 ];
203 $form->addRadio('repeats_by', ts("Repeats on"), $roptionTypes, ['required' => TRUE], NULL);
204 $form->add('select', 'limit_to', '', CRM_Core_SelectValues::getNumericOptions(1, 31));
205 $dayOfTheWeekNo = [
206 'first' => ts('First'),
207 'second' => ts('Second'),
208 'third' => ts('Third'),
209 'fourth' => ts('Fourth'),
210 'last' => ts('Last'),
211 ];
212 $form->add('select', 'entity_status_1', '', $dayOfTheWeekNo);
213 $form->add('select', 'entity_status_2', '', $dayOfTheWeek);
214 $eoptionTypes = [
215 '1' => ts('After'),
216 '2' => ts('On'),
217 ];
218 $form->addRadio('ends', ts("Ends"), $eoptionTypes, ['class' => 'required'], NULL);
219 // Offset options gets key=>val pairs like 1=>2 because the BAO wants to know the number of
220 // children while it makes more sense to the user to see the total number including the parent.
221 $offsetOptions = range(1, 30);
222 unset($offsetOptions[0]);
223 $form->add('select', 'start_action_offset', NULL, $offsetOptions, FALSE);
224 $form->addFormRule(['CRM_Core_Form_RecurringEntity', 'formRule']);
225 $form->add('datepicker', 'repeat_absolute_date', ts('On'), [], FALSE, ['time' => FALSE]);
226 $form->add('text', 'exclude_date_list', ts('Exclude Dates'), ['class' => 'twenty']);
227 $form->addElement('hidden', 'allowRepeatConfigToSubmit', '', ['id' => 'allowRepeatConfigToSubmit']);
228 $form->addButtons([
229 [
230 'type' => 'submit',
231 'name' => ts('Save'),
232 'isDefault' => TRUE,
233 ],
234 [
235 'type' => 'cancel',
236 'name' => ts('Cancel'),
237 ],
238 ]);
239 // For client-side pluralization
240 $form->assign('recurringFrequencyOptions', [
241 'single' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::getRecurringFrequencyUnits()),
242 'plural' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::getRecurringFrequencyUnits(2)),
243 ]);
244 }
245
246 /**
247 * Global validation rules for the form.
248 *
249 * @param array $values
250 * Posted values of the form.
251 *
252 * @return array
253 * list of errors to be posted back to the form
254 */
255 public static function formRule($values) {
256 $errors = [];
257 //Process this function only when you get this variable
258 if ($values['allowRepeatConfigToSubmit'] == 1) {
259 $dayOfTheWeek = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
260 //Repeats
261 if (empty($values['repetition_frequency_unit'])) {
262 $errors['repetition_frequency_unit'] = ts('This is a required field');
263 }
264 //Repeats every
265 if (empty($values['repetition_frequency_interval'])) {
266 $errors['repetition_frequency_interval'] = ts('This is a required field');
267 }
268 //Ends
269 if (!empty($values['ends'])) {
270 if ($values['ends'] == 1) {
271 if (empty($values['start_action_offset'])) {
272 $errors['start_action_offset'] = ts('This is a required field');
273 }
274 elseif ($values['start_action_offset'] > 30) {
275 $errors['start_action_offset'] = ts('Occurrences should be less than or equal to 30');
276 }
277 }
278 if ($values['ends'] == 2) {
279 if (!empty($values['repeat_absolute_date'])) {
280 $entityStartDate = CRM_Utils_Date::processDate($values['repetition_start_date']);
281 $end = CRM_Utils_Date::processDate($values['repeat_absolute_date']);
282 if (($end < $entityStartDate) && ($end != 0)) {
283 $errors['repeat_absolute_date'] = ts('End date should be after current entity\'s start date');
284 }
285 }
286 else {
287 $errors['repeat_absolute_date'] = ts('This is a required field');
288 }
289 }
290 }
291 else {
292 $errors['ends'] = ts('This is a required field');
293 }
294
295 //Repeats BY
296 if (!empty($values['repeats_by'])) {
297 if ($values['repeats_by'] == 1) {
298 if (!empty($values['limit_to'])) {
299 if ($values['limit_to'] < 1 && $values['limit_to'] > 31) {
300 $errors['limit_to'] = ts('Invalid day of the month');
301 }
302 }
303 else {
304 $errors['limit_to'] = ts('Invalid day of the month');
305 }
306 }
307 if ($values['repeats_by'] == 2) {
308 if (!empty($values['entity_status_1'])) {
309 $dayOfTheWeekNo = ['first', 'second', 'third', 'fourth', 'last'];
310 if (!in_array($values['entity_status_1'], $dayOfTheWeekNo)) {
311 $errors['entity_status_1'] = ts('Invalid option');
312 }
313 }
314 else {
315 $errors['entity_status_1'] = ts('Invalid option');
316 }
317 if (!empty($values['entity_status_2'])) {
318 if (!in_array($values['entity_status_2'], $dayOfTheWeek)) {
319 $errors['entity_status_2'] = ts('Invalid day name');
320 }
321 }
322 else {
323 $errors['entity_status_2'] = ts('Invalid day name');
324 }
325 }
326 }
327 }
328 return $errors;
329 }
330
331 /**
332 * Process the form submission.
333 *
334 * @param array $params
335 * @param string $type
336 * @param array $linkedEntities
337 *
338 * @throws \CiviCRM_API3_Exception
339 */
340 public static function postProcess($params = [], $type, $linkedEntities = []) {
341 // Check entity_id not present in params take it from class variable
342 if (empty($params['entity_id'])) {
343 $params['entity_id'] = self::$_entityId;
344 }
345 //Process this function only when you get this variable
346 if ($params['allowRepeatConfigToSubmit'] == 1) {
347 if (!empty($params['entity_table']) && !empty($params['entity_id']) && $type) {
348 $params['used_for'] = $type;
349 if (empty($params['parent_entity_id'])) {
350 $params['parent_entity_id'] = self::$_parentEntityId;
351 }
352 if (!empty($params['schedule_reminder_id'])) {
353 $params['id'] = $params['schedule_reminder_id'];
354 }
355 else {
356 $params['id'] = self::$_scheduleReminderID;
357 }
358
359 //Save post params to the schedule reminder table
360 $recurobj = new CRM_Core_BAO_RecurringEntity();
361 $dbParams = $recurobj->mapFormValuesToDB($params);
362
363 //Delete repeat configuration and rebuild
364 if (!empty($params['id'])) {
365 CRM_Core_BAO_ActionSchedule::del($params['id']);
366 unset($params['id']);
367 }
368 $actionScheduleObj = CRM_Core_BAO_ActionSchedule::add($dbParams);
369
370 //exclude dates
371 $excludeDateList = [];
372 if (CRM_Utils_Array::value('exclude_date_list', $params) && CRM_Utils_Array::value('parent_entity_id', $params) && $actionScheduleObj->entity_value) {
373 //Since we get comma separated values lets get them in array
374 $excludeDates = explode(",", $params['exclude_date_list']);
375
376 //Check if there exists any values for this option group
377 $optionGroupIdExists = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
378 $type . '_repeat_exclude_dates_' . $params['parent_entity_id'],
379 'id',
380 'name'
381 );
382 if ($optionGroupIdExists) {
383 CRM_Core_BAO_OptionGroup::del($optionGroupIdExists);
384 }
385 $optionGroupParams = [
386 'name' => $type . '_repeat_exclude_dates_' . $actionScheduleObj->entity_value,
387 'title' => $type . ' recursion',
388 'is_reserved' => 0,
389 'is_active' => 1,
390 ];
391 $opGroup = CRM_Core_BAO_OptionGroup::add($optionGroupParams);
392 if ($opGroup->id) {
393 $oldWeight = 0;
394 $fieldValues = ['option_group_id' => $opGroup->id];
395 foreach ($excludeDates as $val) {
396 $optionGroupValue = [
397 'option_group_id' => $opGroup->id,
398 'label' => CRM_Utils_Date::processDate($val),
399 'value' => CRM_Utils_Date::processDate($val),
400 'name' => $opGroup->name,
401 'description' => 'Used for recurring ' . $type,
402 'weight' => CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues),
403 'is_active' => 1,
404 ];
405 $excludeDateList[] = $optionGroupValue['value'];
406 CRM_Core_BAO_OptionValue::create($optionGroupValue);
407 }
408 }
409 }
410
411 //Set type for API
412 $apiEntityType = explode("_", $type);
413 if (!empty($apiEntityType[1])) {
414 $apiType = $apiEntityType[1];
415 }
416 //Delete relations if any from recurring entity tables before inserting new relations for this entity id
417 if ($params['entity_id']) {
418 //If entity has any pre delete function, consider that first
419 if (CRM_Utils_Array::value('pre_delete_func', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]) &&
420 CRM_Utils_Array::value('helper_class', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']])
421 ) {
422 $preDeleteResult = call_user_func_array(CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['pre_delete_func'], [$params['entity_id']]);
423 if (!empty($preDeleteResult)) {
424 call_user_func([CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['helper_class'], $preDeleteResult]);
425 }
426 }
427 //Ready to execute delete on entities if it has delete function set
428 if (CRM_Utils_Array::value('delete_func', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]) &&
429 CRM_Utils_Array::value('helper_class', CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']])
430 ) {
431 //Check if pre delete function has some ids to be deleted
432 if (!empty(CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted)) {
433 foreach (CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted as $eid) {
434 $result = civicrm_api3(
435 ucfirst(strtolower($apiType)),
436 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
437 [
438 'sequential' => 1,
439 'id' => $eid,
440 ]
441 );
442 if ($result['error']) {
443 CRM_Core_Error::statusBounce('Error creating recurring list');
444 }
445 }
446 }
447 else {
448 $getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($params['entity_id'], $params['entity_table'], FALSE);
449 foreach ($getRelatedEntities as $key => $value) {
450 $result = civicrm_api3(
451 ucfirst(strtolower($apiType)),
452 CRM_Core_BAO_RecurringEntity::$_recurringEntityHelper[$params['entity_table']]['delete_func'],
453 [
454 'sequential' => 1,
455 'id' => $value['id'],
456 ]
457 );
458 if ($result['error']) {
459 CRM_Core_Error::statusBounce('Error creating recurring list');
460 }
461 }
462 }
463 }
464
465 // find all entities from the recurring set. At this point we 'll get entities which were not deleted
466 // for e.g due to participants being present. We need to delete them from recurring tables anyway.
467 $pRepeatingEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($params['entity_id'], $params['entity_table']);
468 foreach ($pRepeatingEntities as $val) {
469 CRM_Core_BAO_RecurringEntity::delEntity($val['id'], $val['table'], TRUE);
470 }
471 }
472
473 $recursion = new CRM_Core_BAO_RecurringEntity();
474 $recursion->dateColumns = $params['dateColumns'];
475 $recursion->scheduleId = $actionScheduleObj->id;
476
477 if (!empty($excludeDateList)) {
478 $recursion->excludeDates = $excludeDateList;
479 $recursion->excludeDateRangeColumns = $params['excludeDateRangeColumns'];
480 }
481 if (!empty($params['intervalDateColumns'])) {
482 $recursion->intervalDateColumns = $params['intervalDateColumns'];
483 }
484 $recursion->entity_id = $params['entity_id'];
485 $recursion->entity_table = $params['entity_table'];
486 if (!empty($linkedEntities)) {
487 $recursion->linkedEntities = $linkedEntities;
488 }
489
490 $recursion->generate();
491
492 $status = ts('Repeat Configuration has been saved');
493 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
494 }
495 }
496 }
497
498 /**
499 * Return a descriptive name for the page, used in wizard header
500 *
501 * @return string
502 */
503 public function getTitle() {
504 return ts('Repeat Entity');
505 }
506
507 }