Admin.php 24.2 KB
Newer Older
bgm's avatar
bgm committed
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
<?php
/*
 +--------------------------------------------------------------------+
 | CiviCRM version 4.6                                                |
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2015                                |
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
*/

bgm's avatar
bgm committed
28 29
use CRM_CiviDiscount_ExtensionUtil as E;

bgm's avatar
bgm committed
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
/**
 * @package CiviDiscount
 */

/**
 * This class generates form components for cividiscount administration.
 *
 */
class CRM_CiviDiscount_Form_Admin extends CRM_Admin_Form {
  protected $_multiValued = NULL;
  protected $_orgID = NULL;
  protected $_cloneID = NULL;

  protected $select2style = array();

  function preProcess() {
    $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
    $this->_cloneID = CRM_Utils_Request::retrieve('cloneID', 'Positive', $this, FALSE, 0);
    $this->set('BAOName', 'CRM_CiviDiscount_BAO_Item');

    parent::preProcess();

    $session = CRM_Core_Session::singleton();
    $url = CRM_Utils_System::url('civicrm/cividiscount', 'reset=1');
    $session->pushUserContext($url);

    // check and ensure that update / delete have a valid id
    if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::DELETE)) {
      if (!CRM_Utils_Rule::positiveInteger($this->_id)) {
59
        CRM_Core_Error::fatal('We need a valid discount ID for update and/or delete');
bgm's avatar
bgm committed
60 61 62 63 64
      }
    }

    if ($this->_action & CRM_Core_Action::COPY) {
      if (!CRM_Utils_Rule::positiveInteger($this->_cloneID)) {
65
        CRM_Core_Error::fatal('We need a valid discount ID for update and/or delete');
bgm's avatar
bgm committed
66 67 68
      }
    }

69
    CRM_Utils_System::setTitle(E::ts('Discounts'));
bgm's avatar
bgm committed
70 71 72 73 74 75 76 77

    $this->_multiValued = array(
      'memberships' => NULL,
      'events' => NULL,
      'pricesets' => NULL
    );

    $this->select2style = array(
bgm's avatar
bgm committed
78
      'placeholder' => E::ts('- none -'),
bgm's avatar
bgm committed
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
      'multiple' => TRUE,
      'class' => 'crm-select2 huge',
    );
  }

  function setDefaultValues() {
    $origID = NULL;
    $defaults = array();

    if ($this->_action & CRM_Core_Action::COPY) {
      $origID = $this->_cloneID;
    }
    else {
      if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::DELETE)) {
        $origID = $this->_id;
      }
    }

    if ($origID) {
      $params = array('id' => $origID);
      CRM_CiviDiscount_BAO_Item::retrieve($params, $defaults);
    }
    $defaults['is_active'] = $origID ? CRM_Utils_Array::value('is_active', $defaults) : 1;
    $defaults['autodiscount_active_only'] = $origID ? CRM_Utils_Array::value('autodiscount_active_only', $defaults) : 1;
    $defaults['discount_msg_enabled'] = $origID ? CRM_Utils_Array::value('discount_msg_enabled', $defaults) : 0;
    $defaults['count_max'] = empty($defaults['count_max']) ? '' : $defaults['count_max'];

    // assign the defaults to smarty so delete can use it
    $this->assign('discountValue', $defaults);
    $this->applyFilterDefaults($defaults);
    $this->applyAutoDiscountDefaults($defaults);
    foreach ($this->_multiValued as $mv => $info) {
      if (!empty($defaults[$mv])) {
        $v = substr($defaults[$mv], 1, -1);
        $values = explode(CRM_Core_DAO::VALUE_SEPARATOR, $v);

        $defaults[$mv] = array();
        if (!empty($values)) {
          foreach ($values as $val) {
            $defaults[$mv][] = $val;
          }
        }
      }
    }

    if (!empty($defaults['active_on'])) {
      list($defaults['active_on']) = CRM_Utils_Date::setDateDefaults($defaults['active_on']);
    }
    if (!empty($defaults['expire_on'])) {
      list($defaults['expire_on']) = CRM_Utils_Date::setDateDefaults($defaults['expire_on']);
    }

    if (!empty($defaults['organization_id'])) {
      $this->_orgID = $defaults['organization_id'];
    }
    // Convert if using html
    if (!empty($defaults['discount_msg'])) {
      $defaults['discount_msg'] = html_entity_decode($defaults['discount_msg']);
    }
    return $defaults;
  }

  /**
   * Function to build the form
   *
   * @return None
   * @access public
   */
  public function buildQuickForm() {
    parent::buildQuickForm();

    if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::COPY)) {
      return;
    }

    $this->applyFilter('__ALL__', 'trim');
    $element = $this->add('text',
      'code',
bgm's avatar
bgm committed
157
      E::ts('Discount Code'),
bgm's avatar
bgm committed
158 159 160 161
      CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'code'),
      TRUE
    );
    $this->addRule('code',
bgm's avatar
bgm committed
162
      E::ts('Code already exists in Database.'),
bgm's avatar
bgm committed
163 164 165
      'objectExists',
      array('CRM_CiviDiscount_DAO_Item', $this->_id, 'code'));
    $this->addRule('code',
bgm's avatar
bgm committed
166
      E::ts('Code can only consist of alpha-numeric characters'),
bgm's avatar
bgm committed
167 168 169 170 171
      'variable');
    if ($this->_action & CRM_Core_Action::UPDATE) {
      $element->freeze();
    }

bgm's avatar
bgm committed
172
    $this->add('text', 'description', E::ts('Description'), CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'description'));
bgm's avatar
bgm committed
173

bgm's avatar
bgm committed
174
    $this->addMoney('amount', E::ts('Discount Amount'), TRUE, CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'amount'), FALSE);
bgm's avatar
bgm committed
175 176 177

    $this->add('select', 'amount_type', NULL,
      array(
bgm's avatar
bgm committed
178 179
        1 => E::ts('Percent'),
        2 => E::ts('Fixed Amount')
bgm's avatar
bgm committed
180 181 182
      ),
      TRUE);

bgm's avatar
bgm committed
183 184
    $this->add('text', 'count_max', E::ts('Usage Limit'), CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'count_max') + array('min' => 1));
    $this->addRule('count_max', E::ts('Must be an integer'), 'integer');
bgm's avatar
bgm committed
185

bgm's avatar
bgm committed
186 187
    $this->addDate('active_on', E::ts('Activation Date'), FALSE);
    $this->addDate('expire_on', E::ts('Expiration Date'), FALSE);
bgm's avatar
bgm committed
188

bgm's avatar
bgm committed
189
    $this->addEntityRef('organization_id', E::ts('Organization'), array('api' => array('params' => array('contact_type' => 'Organization'))));
bgm's avatar
bgm committed
190 191

    // is this discount active ?
bgm's avatar
bgm committed
192
    $this->addElement('checkbox', 'is_active', E::ts('Is this discount active?'));
bgm's avatar
bgm committed
193

bgm's avatar
bgm committed
194 195
    $this->addElement('checkbox', 'discount_msg_enabled', E::ts('Display a message to users not eligible for this discount?'));
    $this->add('textarea', 'discount_msg', E::ts('Message to non-eligible users'), array('class' => 'big'));
bgm's avatar
bgm committed
196 197 198 199 200 201

    // add memberships, events, pricesets
    $membershipTypes = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
    if (!empty($membershipTypes)) {
      $this->add('select',
        'memberships',
bgm's avatar
bgm committed
202
        E::ts('Memberships'),
bgm's avatar
bgm committed
203 204 205 206 207 208
        $membershipTypes,
        FALSE,
        $this->select2style
      );
    }
    $this->assignAutoDiscountFields();
bgm's avatar
bgm committed
209 210
    $this->addElement('text', 'advanced_autodiscount_filter_entity', E::ts('Specify entity for advanced autodiscount'));
    $this->addElement('text', 'advanced_autodiscount_filter_string', E::ts('Specify api string for advanced filter'), array('class' => 'huge'));
bgm's avatar
bgm committed
211 212 213

    $events = CRM_CiviDiscount_Utils::getEvents();
    if (!empty($events)) {
214
      $events = array(E::ts('--any event--')) + $events;
bgm's avatar
bgm committed
215 216 217
      $this->_multiValued['events'] = $events;
      $this->add('select',
        'events',
bgm's avatar
bgm committed
218
        E::ts('Events'),
bgm's avatar
bgm committed
219 220 221 222 223 224 225 226 227
        $events,
        FALSE,
        $this->select2style
      );

      $eventTypes = $this->getOptions('event', 'event_type_id');
      $this->_multiValued['eventtypes'] = $eventTypes;
      $this->add('select',
        'event_type_id',
bgm's avatar
bgm committed
228
        E::ts('Event Types'),
bgm's avatar
bgm committed
229 230 231 232 233 234 235 236 237 238 239
        $eventTypes,
        FALSE,
        $this->select2style
      );
    }

    $pricesets = CRM_CiviDiscount_Utils::getNestedPriceSets();
    if (!empty($pricesets)) {
      $this->_multiValued['pricesets'] = $pricesets;
      $this->add('select',
        'pricesets',
bgm's avatar
bgm committed
240
        E::ts('Price Field Options'),
bgm's avatar
bgm committed
241 242
        $pricesets,
        FALSE,
bgm's avatar
bgm committed
243
        array('placeholder' => E::ts('- any -')) + $this->select2style
bgm's avatar
bgm committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
      );
    }
  }

  /**
   * Add autodiscount fields to the form based on the definition in getSupportedAutoDiscountFilters
   */
  private function assignAutoDiscountFields() {
    $assignedAutoFilters = array();
    foreach ($this->getSupportedAutoDiscountFilters() as $entity => $autoFilters) {
      foreach ($autoFilters as $filterName => $autoFilter) {
        $optionFieldTypes = array('advmultiselect');
        if (in_array($autoFilter['field_type'], $optionFieldTypes) && empty($autoFilter['options'])) {
          continue;
        }
        $this->addElement(
          $autoFilter['field_type'],
          $autoFilter['form_field_name'],
          $autoFilter['title'],
          isset($autoFilter['options']) ? $autoFilter['options'] : array(),
          $this->select2style
        );
        $assignedAutoFilters[] = $autoFilter['form_field_name'];
        if (!empty($autoFilter['rule_data_type'])) {
268
          $this->addRule($autoFilter['form_field_name'], E::ts('Please re-enter %1, a %2 is required.', [1 => $autoFilter['title'], 2 => $autoFilter['rule_data_type']]), $autoFilter['rule_data_type']);
bgm's avatar
bgm committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        }
      }
    }
    $this->assign('autodiscounts', $assignedAutoFilters);
  }

  /**
   * Function to process the form
   *
   * @access public
   * @return None
   */
  public function postProcess() {
    if ($this->_action & CRM_Core_Action::DELETE) {
      CRM_CiviDiscount_BAO_Item::del($this->_id);
284
      CRM_Core_Session::setStatus(E::ts('Selected Discount has been deleted.'), E::ts('Deleted'), 'success');
bgm's avatar
bgm committed
285 286 287 288 289 290 291
      return;
    }

    if ($this->_action & CRM_Core_Action::COPY) {
      $params = $this->exportValues();
      $newCode = CRM_CiviDiscount_Utils::randomString('abcdefghjklmnpqrstwxyz23456789', 8);
      CRM_CiviDiscount_BAO_Item::copy($this->_cloneID, $params, $newCode);
292
      CRM_Core_Session::setStatus(E::ts('Selected Discount has been duplicated.'), E::ts('Saved'), 'success');
bgm's avatar
bgm committed
293 294 295 296 297 298 299 300 301 302 303 304 305
      return;
    }

    $params = $this->exportValues();

    $params['count_max'] = (int) $params['count_max'];

    if ($this->_action & CRM_Core_Action::UPDATE) {
      $params['id'] = $this->_id;
    }
    $params['multi_valued'] = $this->_multiValued;

    if (isset($params['events']) && in_array(0, $params['events']) && count($params['events']) > 1) {
306
      CRM_Core_Session::setStatus(E::ts('The events you selected will be ignored because you also chose "any event."'));
bgm's avatar
bgm committed
307 308 309 310 311 312 313 314 315 316 317 318
      $params['events'] = array(0);
    }
    if (!empty($params['autodiscount_membership_type_id']) && count($params['autodiscount_membership_status_id']) == 0) {
      $params['autodiscount_membership_status_id'] = array('');
    }
    $params['filters'] = $this->getFiltersFromParams($params);
    $params['autodiscount'] = $this->getAutoDiscountFromParams($params);
    if (!empty($params['advanced_autodiscount_filter_entity'])) {
      $this->addAdvancedFilterToAutodiscount($params, $params['advanced_autodiscount_filter_entity'], CRM_Utils_Array::value('advanced_autodiscount_filter_string', $params));
    }
    $item = CRM_CiviDiscount_BAO_Item::add($params);

319 320
    CRM_Core_Session::setStatus(E::ts('The discount "%1" has been saved.',
      [1 => $item->description ?: $item->code]), E::ts('Saved'), 'success');
bgm's avatar
bgm committed
321 322 323 324 325 326 327 328 329 330 331 332
  }

  /**
   * Add advanced filters from UI. Note that setting an entity but not a filter string basically means
   * that only the contact id will be passed in as a parameter (as id for contact or contact_id for all others)
   *
   * @param array $params
   * @param string $discountEntity
   * @param string $discountString
   * @throws \CRM_Core_Exception
   */
  private function addAdvancedFilterToAutodiscount(&$params, $discountEntity, $discountString) {
333
    $discounts = [];
bgm's avatar
bgm committed
334 335
    if ($discountString) {
      if (stristr($discountString, 'api.') || stristr($discountString, 'api_')) {
336
        throw new CRM_Core_Exception(E::ts('You cannot nest apis in the advanced filter'));
bgm's avatar
bgm committed
337 338 339 340 341 342 343 344
      }
      if (stristr($discountString, '{')) {
        $discounts = json_decode($discountString, TRUE);
      }
      else {
        $discounts = explode(',', $discountString);
        foreach ($discounts as $id => $discount) {
          if (!stristr($discount, '=')) {
345
            throw new CRM_Core_Exception(E::ts('You have a criteria without an = sign'));
bgm's avatar
bgm committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
          }
          $parts = explode('=', $discount);
          $discounts[$parts[0]] = $parts[1];
          unset($discounts[$id]);
        }
      }
    }
    if (!isset($params['autodiscount'][$discountEntity])) {
      $params['autodiscount'][$discountEntity] = array();
    }

    foreach ($discounts as $key => $filter) {
      $params['autodiscount'][$discountEntity][$key] = $filter;
    }
  }


  /**
   * Convert from params to values to be stored in the filter
   * @param array $params parameters submitted to form
   * @return array filters to be stored in DB
   */
  function getJsonFieldFromParams($params, $fn) {
    $filters = array();
    foreach ($this->$fn() as $entity => $fields) {
      foreach ($fields as $field => $spec) {
        $fieldName = $spec['form_field_name'];
        if (!empty($params[$fieldName])) {
          if (empty($spec['operator'])) {
            $filters[$entity][$field] = $params[$fieldName];
          }
          else {
            $filters[$entity][$field] = array($spec['operator'] => $params[$fieldName]);
          }
        }
      }
    }
    return $filters;
  }

  /**
   * Convert from params to values to be stored in the filter
   * @param array $params parameters submitted to form
   * @return array filters to be stored in DB
   */
  function getAutoDiscountFromParams($params) {
    $fields = $this->getJsonFieldFromParams($params, 'getSupportedAutoDiscountFilters');
    $this->adjustAgeFields($fields);
    $this->adjustMembershipStatusField($fields);
    return $fields;
  }

  /**
   * Convert from params to values to be stored in the filter
   * @param array $params parameters submitted to form
   * @return array filters to be stored in DB
   */
  function getFiltersFromParams($params) {
    return $this->getJsonFieldFromParams($params, 'getSupportedFilters');
  }

  /**
   * Convert handling of age fields to api-acceptable 'birth_date_high' & birth_date_low
409
   * @param array $fields
bgm's avatar
bgm committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
   */
  function adjustAgeFields(&$fields) {
    if (!empty($fields['contact'])) {
      if (!empty($fields['contact']['age_low'])) {
        $fields['contact']['birth_date_high'] = '- ' . $fields['contact']['age_low']['='] . ' years';
        unset($fields['contact']['age_low']);
      }
      if (!empty($fields['contact']['age_high'])) {
        $fields['contact']['birth_date_low'] = '- ' . $fields['contact']['age_high']['='] . ' years';
        unset($fields['contact']['age_high']);
      }
    }
  }

  /**
   * Convert handle 'any current'
   *
   * If it is set then we need to translate it to 'active_only' as
   * we want this to move over time if the membership statuses are changed so we should interpret it to
   * 'active_only'
   *
   * @param array $fields
   */
  function adjustMembershipStatusField(&$fields) {
    if (!empty($fields['membership'])) {
      if (isset($fields['membership']['status_id'])) {
        foreach ($fields['membership']['status_id']['IN'] as $status) {
          if (empty($status)) {
            $fields['membership']['active_only'] = 1;
            if (count($fields['membership']['status_id']['IN']) > 1) {
440
              CRM_Core_Session::setStatus(E::ts('The statuses you selected will be ignored because you also chose "any current status."'));
bgm's avatar
bgm committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
            }
            unset($fields['membership']['status_id']);
            continue;
          }
        }
      }
    }
  }

  /**
   * Convert from params to values to be stored in the filter
   * @param array $defaults
   */
  function applyFilterDefaults(&$defaults) {
    $this->applyJsonFieldDefaults($defaults, 'filters', 'getSupportedFilters');
  }

  /**
   * Convert from params to values to be stored in the filter
   * @param array $defaults
   */
  function applyAutoDiscountDefaults(&$defaults) {
    $this->applyJsonFieldDefaults($defaults, 'autodiscount', 'getSupportedAutoDiscountFilters');
  }


  /**
   * Apply defaults to fields stored in json fields
   * @param array defaults
   * @param string type
   * @param string $fn function to get definition from
   * @return array
   */
  private function applyJsonFieldDefaults(&$defaults, $type, $fn) {
    if (empty($defaults[$type])) {
      return array();
    }
    $fieldsDisplayedElsewhereOnForm = array(
      'contact' => array(
        'birth_date_high',
        'birth_date_low',
      ),
      'membership' => array(
        'active_only',
      ),
      'address' => array(
        'country_id',
      )
    );

    $filters = json_decode($defaults[$type], TRUE);
    $specs = $this->$fn();
    foreach ($filters as $entity => $entityFilters) {
      if (isset($fieldsDisplayedElsewhereOnForm[$entity])) {
        // probably could do next 3 lines with an array_diff
        foreach ($fieldsDisplayedElsewhereOnForm[$entity] as $fieldSetElsewhere) {
          if (isset($entityFilters[$fieldSetElsewhere])) {
            unset($entityFilters[$fieldSetElsewhere]);
          }
        }
      }
      if (!isset($specs[$entity])) {
        $defaults['advanced_' . $type . '_filter_entity'] = $entity;
        $defaults['advanced_' . $type . '_filter_string'] = $entityFilters;
      }
      else {
        foreach ($entityFilters as $key => $filter) {
          if (!isset($specs[$entity][$key])) {
            $defaults['advanced_' . $type . '_filter_entity'] = $entity;
            $defaults['advanced_' . $type . '_filter_string'][$key] = $filter;
          }
        }
      }
    }
    if (!empty($defaults['advanced_' . $type . '_filter_string'])) {
      $defaults['advanced_' . $type . '_filter_string'] = json_encode($defaults['advanced_' . $type . '_filter_string'], TRUE);
    }

    foreach ($specs as $entity => $fields) {
      foreach ($fields as $field => $spec) {
        if (!isset($filters[$entity])) {
          continue;
        }
        $fieldName = $spec['form_field_name'];
        if (!empty($spec['defaults_callback'])) {
          $callback = $spec['defaults_callback'];
          $defaults[$fieldName] = $this->$callback($defaults, $fieldName, $filters, $spec);
          continue;
        }
        if (!isset($filters[$entity][$field])) {
          continue;
        }
        if (empty($spec['operator'])) {
          $defaults[$fieldName] = $filters[$entity][$field];
        }
        else {
          $defaults[$fieldName] = $filters[$entity][$field][$spec['operator']];
        }
      }
    }
    return $filters;
  }

  /**
   * Set default for age fields as stored as birth_date_high & birth_date_low
   *
   * @param array $defaults
   * @param string $fieldName
   * @param array $values
   * @param null $spec
   */
  function setAgeDefaults(&$defaults, $fieldName, $values, $spec) {
    $fields = array(
      'autodiscount_age_low' => 'birth_date_high',
      'autodiscount_age_high' => 'birth_date_low'
    );
    if (!empty($values['contact'][$fields[$fieldName]])) {
      return abs(filter_var($values['contact'][$fields[$fieldName]], FILTER_SANITIZE_NUMBER_INT));
    }
  }

  /**
   * Set default for membership status based on presence of 'active_only' param
   *
   * @param array $defaults
   * @param string $fieldName
   * @param array $values
   * @param null $spec
569
   * @return string
bgm's avatar
bgm committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
   */
  function setMembershipStatusDefaults(&$defaults, $fieldName, $values, $spec) {
    if (!empty($values['membership']['active_only'])) {
      return '';
    }
    elseif (!empty($values['membership']['status_id']['IN'])) {
      return $values['membership']['status_id']['IN'];
    }
  }


  /**
   * Here we define filter extensions to be stored in the filters field in the DB
   * Later we will figure out how to make this hookable so that discounts can be extended
   * The format is
   *   array(
   *     'entity' => array(
   *       'field1' => array('form_field_name' => field1),
   *       'field2' => array('form_field_name' => field2),
   *   )
   * where both the entity & the field names should be valid for api calls.
   * The form field name is the name of the field on the form - we set it in case we get a conflict
   *  - eg. multiple entities have 'status_id'
   * @return array supported filters
   */
  function getSupportedFilters() {
    return array(
      'event' => array(
        'event_type_id' => array(
          'form_field_name' => 'event_type_id',
          'operator' => 'IN',
        )
      )
    );
  }

  /**
   * Here we define filter extensions to be stored in the filters field in the DB
   * Later we will figure out how to make this hookable so that discounts can be extended
   * The format is
   *   array(
   *     'entity' => array(
   *       'field1' => array('form_field_name' => field1),
   *       'field2' => array('form_field_name' => field2),
   * )
   * where both the entity & the field names should be valid for api calls.
   * The form field name is the name of the field on the form - we set it in case we get a conflict
   *  - eg. multiple entities have 'status_id'
   * @return array supported filters
   */
  function getSupportedAutoDiscountFilters() {
    return array(
      'membership' => array(
        'membership_type_id' => array(
bgm's avatar
bgm committed
624
          'title' => E::ts('Automatic discount for existing members of type'),
bgm's avatar
bgm committed
625 626 627 628 629 630
          'form_field_name' => 'autodiscount_membership_type_id',
          'operator' => 'IN',
          'field_type' => 'select',
          'options' => $this->getOptions('membership', 'membership_type_id'),
        ),
        'status_id' => array(
bgm's avatar
bgm committed
631
          'title' => E::ts('Automatic discount for Membership Statuses'),
bgm's avatar
bgm committed
632 633 634
          'form_field_name' => 'autodiscount_membership_status_id',
          'operator' => 'IN',
          'field_type' => 'select',
bgm's avatar
bgm committed
635
          'options' => array('' => E::ts('--any current status--')) + $this->getOptions('membership', 'status_id'),
bgm's avatar
bgm committed
636 637 638 639 640
          'defaults_callback' => 'setMembershipStatusDefaults',
        ),
      ),
      'contact' => array(
        'contact_type' => array(
bgm's avatar
bgm committed
641
          'title' => E::ts('Contact Type'),
bgm's avatar
bgm committed
642 643 644 645 646 647
          'form_field_name' => 'autodiscount_contact_type',
          'operator' => 'IN',
          'options' => $this->getOptions('contact', 'contact_type'),
          'field_type' => 'select',
        ),
        'age_low' => array(
bgm's avatar
bgm committed
648
          'title' => E::ts('Minimum Age'),
bgm's avatar
bgm committed
649 650 651 652 653 654 655
          'field_type' => 'Text',
          'form_field_name' => 'autodiscount_age_low',
          'rule_data_type' => 'integer',
          'operator' => '=',
          'defaults_callback' => 'setAgeDefaults',
        ),
        'age_high' => array(
bgm's avatar
bgm committed
656
          'title' => E::ts('Maximum Age'),
bgm's avatar
bgm committed
657 658 659 660 661 662 663 664 665
          'field_type' => 'Text',
          'operator' => '=',// we could make this the adjustment fn name?
          'form_field_name' => 'autodiscount_age_high',
          'rule_data_type' => 'integer',
          'defaults_callback' => 'setAgeDefaults',
        ),
      ),
      'address' => array(
        'country_id' => array(
bgm's avatar
bgm committed
666
          'title' => E::ts('Country'),
bgm's avatar
bgm committed
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
          'form_field_name' => 'autodiscount_country_id',
          'operator' => 'IN',
          'field_type' => 'select',
          'options' => $this->getOptions('address', 'country_id'),
        ),
      )
    );
  }

  /**
   * We want to avoid calling the BAO function from an extension if we can avoid it as api is more consistent
   * across versions - but the api requires 2 lines of code which is annoying so a wrapper to bring back to one
   * @param string $entity
   * @param string $field
   * @return array Options for field
   */
  function getOptions($entity, $field) {
    $result = civicrm_api3($entity, 'getoptions', array('field' => $field));
    return $result['values'];
  }

}