Form.php 16.2 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
totten's avatar
totten committed
4
 | CiviCRM version 5                                                  |
totten's avatar
totten committed
5
 +--------------------------------------------------------------------+
Seamus Lee's avatar
Seamus Lee committed
6
 | Copyright CiviCRM LLC (c) 2004-2019                                |
totten's avatar
totten committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 +--------------------------------------------------------------------+
 | 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        |
 +--------------------------------------------------------------------+
26
 */
totten's avatar
totten committed
27 28 29 30

/**
 *
 * @package CRM
Seamus Lee's avatar
Seamus Lee committed
31
 * @copyright CiviCRM LLC (c) 2004-2019
totten's avatar
totten committed
32 33 34 35 36 37
 */

/**
 * Base class for offline membership / membership type / membership renewal and membership status forms
 *
 */
38
class CRM_Member_Form extends CRM_Contribute_Form_AbstractEditPayment {
totten's avatar
totten committed
39

40
  use CRM_Core_Form_EntityFormTrait;
totten's avatar
totten committed
41 42 43 44 45
  /**
   * The id of the object being edited / created
   *
   * @var int
   */
46
  public $_id;
totten's avatar
totten committed
47

48 49
  /**
   * Membership Type ID
50
   * @var int
51 52 53 54 55 56 57
   */
  protected $_memType;

  /**
   * Array of from email ids
   * @var array
   */
58
  protected $_fromEmails = [];
59

60 61 62 63 64
  /**
   * Details of all enabled membership types.
   *
   * @var array
   */
65
  protected $allMembershipTypeDetails = [];
66 67 68 69 70 71

  /**
   * Array of membership type IDs and whether they permit autorenewal.
   *
   * @var array
   */
72
  protected $membershipTypeRenewalStatus = [];
73

74 75 76 77 78 79 80 81 82 83 84 85 86 87
  /**
   * Price set ID configured for the form.
   *
   * @var int
   */
  public $_priceSetId;

  /**
   * Price set details as an array.
   *
   * @var array
   */
  public $_priceSet;

88 89 90 91 92 93 94
  /**
   * Explicitly declare the entity api name.
   */
  public function getDefaultEntity() {
    return 'Membership';
  }

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  /**
   * @var array
   */
  protected $statusMessage = [];

  /**
   * Add to the status message.
   *
   * @param $message
   */
  protected function addStatusMessage($message) {
    $this->statusMessage[] = $message;
  }

  /**
   * Get the status message.
   *
   * @return string
   */
  protected function getStatusMessage() {
    return implode(' ', $this->statusMessage);
  }

118 119 120 121 122
  /**
   * Values submitted to the form, processed along the way.
   *
   * @var array
   */
123
  protected $_params = [];
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  /**
   * Fields for the entity to be assigned to the template.
   *
   * Fields may have keys
   *  - name (required to show in tpl from the array)
   *  - description (optional, will appear below the field)
   *  - not-auto-addable - this class will not attempt to add the field using addField.
   *    (this will be automatically set if the field does not have html in it's metadata
   *    or is not a core field on the form's entity).
   *  - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
   *  - template - use a field specific template to render this field
   *  - required
   *  - is_freeze (field should be frozen).
   *
   * @var array
   */
  protected $entityFields = [];

143
  public function preProcess() {
144 145 146 147
    // Check for edit permission.
    if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
      CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
    }
eileen's avatar
eileen committed
148 149 150 151 152
    if (!CRM_Member_BAO_Membership::statusAvailabilty()) {
      // all possible statuses are disabled - redirect back to contact form
      CRM_Core_Error::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
    }

153
    parent::preProcess();
154
    $params = [];
155
    $params['context'] = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'membership');
156
    $params['id'] = CRM_Utils_Request::retrieve('id', 'Positive', $this);
157
    $params['mode'] = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
158 159

    $this->setContextVariables($params);
160 161 162

    $this->assign('context', $this->_context);
    $this->assign('membershipMode', $this->_mode);
163
    $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, [], TRUE);
164 165 166 167 168 169
    foreach ($this->allMembershipTypeDetails as $index => $membershipType) {
      if ($membershipType['auto_renew']) {
        $this->_recurMembershipTypes[$index] = $membershipType;
        $this->membershipTypeRenewalStatus[$index] = $membershipType['auto_renew'];
      }
    }
totten's avatar
totten committed
170 171 172
  }

  /**
173
   * Set default values for the form. MobileProvider that in edit/view mode
totten's avatar
totten committed
174 175 176
   * the default values are retrieved from the database
   *
   *
177 178
   * @return array
   *   defaults
totten's avatar
totten committed
179
   */
180
  public function setDefaultValues() {
181
    $defaults = [];
182
    if (isset($this->_id)) {
183
      $params = ['id' => $this->_id];
184
      CRM_Member_BAO_Membership::retrieve($params, $defaults);
185 186 187
      if (isset($defaults['minimum_fee'])) {
        $defaults['minimum_fee'] = CRM_Utils_Money::format($defaults['minimum_fee'], NULL, '%a');
      }
totten's avatar
totten committed
188

189 190 191
      if (isset($defaults['status'])) {
        $this->assign('membershipStatus', $defaults['status']);
      }
192 193 194 195 196 197 198

      if (!empty($defaults['is_override'])) {
        $defaults['is_override'] = CRM_Member_StatusOverrideTypes::PERMANENT;
      }
      if (!empty($defaults['status_override_end_date'])) {
        $defaults['is_override'] = CRM_Member_StatusOverrideTypes::UNTIL_DATE;
      }
totten's avatar
totten committed
199 200 201 202 203 204 205 206 207 208 209 210 211
    }

    if ($this->_action & CRM_Core_Action::ADD) {
      $defaults['is_active'] = 1;
    }

    if (isset($defaults['member_of_contact_id']) &&
      $defaults['member_of_contact_id']
    ) {
      $defaults['member_org'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
        $defaults['member_of_contact_id'], 'display_name'
      );
    }
212 213 214 215
    if (!empty($defaults['membership_type_id'])) {
      $this->_memType = $defaults['membership_type_id'];
    }
    if (is_numeric($this->_memType)) {
216
      $defaults['membership_type_id'] = [];
217 218 219 220 221 222 223 224 225 226
      $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
        $this->_memType,
        'member_of_contact_id',
        'id'
      );
      $defaults['membership_type_id'][1] = $this->_memType;
    }
    else {
      $defaults['membership_type_id'] = $this->_memType;
    }
totten's avatar
totten committed
227 228 229 230
    return $defaults;
  }

  /**
231
   * Build the form object.
totten's avatar
totten committed
232 233
   */
  public function buildQuickForm() {
234
    $this->assignSalesTaxMetadataToTemplate();
235

236
    $this->addPaymentProcessorSelect(TRUE, FALSE, TRUE);
237
    CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->getDefaultPaymentInstrumentId());
238 239 240
    // Build the form for auto renew. This is displayed when in credit card mode or update mode.
    // The reason for showing it in update mode is not that clear.
    if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
241 242
      if (!empty($this->_recurPaymentProcessors)) {
        $this->assign('allowAutoRenew', TRUE);
243 244
      }

245
      $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
246
        NULL, ['onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );"]
247 248 249 250
      );
      if ($this->_action & CRM_Core_Action::UPDATE) {
        $autoRenewElement->freeze();
      }
251

252
      $this->assign('recurProcessor', json_encode($this->_recurPaymentProcessors));
253 254
      $this->addElement('checkbox',
        'auto_renew',
255
        ts('Membership renewed automatically')
256 257 258
      );

    }
259
    $this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus));
260

totten's avatar
totten committed
261
    if ($this->_action & CRM_Core_Action::RENEW) {
262 263
      $this->addButtons([
        [
264 265 266
          'type' => 'upload',
          'name' => ts('Renew'),
          'isDefault' => TRUE,
267 268
        ],
        [
269 270
          'type' => 'cancel',
          'name' => ts('Cancel'),
271 272
        ],
      ]);
totten's avatar
totten committed
273 274
    }
    elseif ($this->_action & CRM_Core_Action::DELETE) {
275 276
      $this->addButtons([
        [
277 278 279
          'type' => 'next',
          'name' => ts('Delete'),
          'isDefault' => TRUE,
280 281
        ],
        [
282 283
          'type' => 'cancel',
          'name' => ts('Cancel'),
284 285
        ],
      ]);
totten's avatar
totten committed
286 287
    }
    else {
288 289
      $this->addButtons([
        [
290 291 292
          'type' => 'upload',
          'name' => ts('Save'),
          'isDefault' => TRUE,
293 294
        ],
        [
295 296 297
          'type' => 'upload',
          'name' => ts('Save and New'),
          'subName' => 'new',
298 299
        ],
        [
300 301
          'type' => 'cancel',
          'name' => ts('Cancel'),
302 303
        ],
      ]);
totten's avatar
totten committed
304 305 306
    }
  }

307
  /**
colemanw's avatar
colemanw committed
308
   * Extract values from the contact create boxes on the form and assign appropriately  to
totten's avatar
totten committed
309 310 311
   *
   *  - $this->_contributorEmail,
   *  - $this->_memberEmail &
312
   *  - $this->_contributionName
totten's avatar
totten committed
313 314 315 316 317 318 319 320
   *  - $this->_memberName
   *  - $this->_contactID (effectively memberContactId but changing might have spin-off effects)
   *  - $this->_contributorContactId - id of the contributor
   *  - $this->_receiptContactId
   *
   * If the member & contributor are the same then the values will be the same. But if different people paid
   * then they weill differ
   *
colemanw's avatar
colemanw committed
321 322
   * @param array $formValues
   *   values from form. The important values we are looking for are.
colemanw's avatar
colemanw committed
323 324
   *  - contact_id
   *  - soft_credit_contact_id
totten's avatar
totten committed
325
   */
totten's avatar
totten committed
326
  public function storeContactFields($formValues) {
totten's avatar
totten committed
327
    // in a 'standalone form' (contact id not in the url) the contact will be in the form values
colemanw's avatar
colemanw committed
328 329
    if (!empty($formValues['contact_id'])) {
      $this->_contactID = $formValues['contact_id'];
totten's avatar
totten committed
330 331 332
    }

    list($this->_memberDisplayName,
totten's avatar
totten committed
333 334
      $this->_memberEmail
      ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
totten's avatar
totten committed
335 336 337

    //CRM-10375 Where the payer differs to the member the payer should get the email.
    // here we store details in order to do that
colemanw's avatar
colemanw committed
338 339
    if (!empty($formValues['soft_credit_contact_id'])) {
      $this->_receiptContactId = $this->_contributorContactID = $formValues['soft_credit_contact_id'];
340
      list($this->_contributorDisplayName,
totten's avatar
totten committed
341
        $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contributorContactID);
totten's avatar
totten committed
342 343 344 345 346 347 348
    }
    else {
      $this->_receiptContactId = $this->_contributorContactID = $this->_contactID;
      $this->_contributorDisplayName = $this->_memberDisplayName;
      $this->_contributorEmail = $this->_memberEmail;
    }
  }
349

eileenmcnaugton's avatar
eileenmcnaugton committed
350 351 352 353 354 355 356
  /**
   * Set variables in a way that can be accessed from different places.
   *
   * This is part of refactoring for unit testability on the submit function.
   *
   * @param array $params
   */
357
  protected function setContextVariables($params) {
358
    $variables = [
359 360 361 362 363
      'action' => '_action',
      'context' => '_context',
      'id' => '_id',
      'cid' => '_contactID',
      'mode' => '_mode',
364
    ];
365 366 367 368 369 370 371 372 373 374 375 376 377
    foreach ($variables as $paramKey => $classVar) {
      if (isset($params[$paramKey]) && !isset($this->$classVar)) {
        $this->$classVar = $params[$paramKey];
      }
    }

    if ($this->_id) {
      $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
      $this->_membershipIDs[] = $this->_id;
    }
    $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
  }

378 379 380 381 382 383 384 385 386 387 388 389 390
  /**
   * Create a recurring contribution record.
   *
   * Recurring contribution parameters are set explicitly rather than merging paymentParams because it's hard
   * to know the downstream impacts if we keep passing around the same array.
   *
   * @param $paymentParams
   *
   * @return array
   * @throws \CiviCRM_API3_Exception
   */
  protected function processRecurringContribution($paymentParams) {
    $membershipID = $paymentParams['membership_type_id'][1];
391
    $contributionRecurParams = [
392 393
      'contact_id' => $paymentParams['contactID'],
      'amount' => $paymentParams['total_amount'],
394
      'contribution_status_id' => 'Pending',
395
      'payment_processor_id' => $paymentParams['payment_processor_id'],
396
      'campaign_id' => $paymentParams['campaign_id'],
397
      'financial_type_id' => $paymentParams['financial_type_id'],
398 399 400
      'is_email_receipt' => $paymentParams['is_email_receipt'],
      'payment_instrument_id' => $paymentParams['payment_instrument_id'],
      'invoice_id' => $paymentParams['invoice_id'],
401
    ];
402

403
    $mapping = [
404 405
      'frequency_interval' => 'duration_interval',
      'frequency_unit' => 'duration_unit',
406 407
    ];
    $membershipType = civicrm_api3('MembershipType', 'getsingle', [
408 409
      'id' => $membershipID,
      'return' => $mapping,
410
    ]);
411

412
    $returnParams = ['is_recur' => TRUE];
413 414
    foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
      $contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
415
      $returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
416 417 418
    }

    $contributionRecur = civicrm_api3('ContributionRecur', 'create', $contributionRecurParams);
419
    $returnParams['contributionRecurID'] = $contributionRecur['id'];
420 421 422
    return $returnParams;
  }

eileenmcnaugton's avatar
eileenmcnaugton committed
423 424 425 426 427 428 429 430 431 432
  /**
   * Ensure price parameters are set.
   *
   * If they are not set it means a quick config option has been chosen so we
   * fill them in here to make the two flows the same. They look like 'price_2' => 2 etc.
   *
   * @param array $formValues
   */
  protected function ensurePriceParamsAreSet(&$formValues) {
    foreach ($formValues as $key => $value) {
433
      if ((substr($key, 0, 6) == 'price_') && is_numeric(substr($key, 6))) {
eileenmcnaugton's avatar
eileenmcnaugton committed
434 435 436 437 438 439
        return;
      }
    }
    $priceFields = CRM_Member_BAO_Membership::setQuickConfigMembershipParameters(
      $formValues['membership_type_id'][0],
      $formValues['membership_type_id'][1],
440
      CRM_Utils_Array::value('total_amount', $formValues),
eileenmcnaugton's avatar
eileenmcnaugton 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
      $this->_priceSetId
    );
    $formValues = array_merge($formValues, $priceFields['price_fields']);
  }

  /**
   * Get the details for the selected price set.
   *
   * @param array $params
   *   Parameters submitted to the form.
   *
   * @return array
   */
  protected static function getPriceSetDetails($params) {
    $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
    if ($priceSetID) {
      return CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
    }
    else {
      $priceSet = CRM_Price_BAO_PriceSet::getDefaultPriceSet('membership');
      $priceSet = reset($priceSet);
      return CRM_Price_BAO_PriceSet::getSetDetail($priceSet['setID']);
    }
  }

  /**
   * Get the selected price set id.
   *
   * @param array $params
   *   Parameters submitted to the form.
   *
   * @return int
   */
  protected static function getPriceSetID($params) {
    $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
    if (!$priceSetID) {
      $priceSetDetails = self::getPriceSetDetails($params);
      return key($priceSetDetails);
    }
    return $priceSetID;
  }

  /**
   * Store parameters relating to price sets.
   *
   * @param array $formValues
   *
   * @return array
   */
  protected function setPriceSetParameters($formValues) {
    $this->_priceSetId = self::getPriceSetID($formValues);
    $priceSetDetails = self::getPriceSetDetails($formValues);
    $this->_priceSet = $priceSetDetails[$this->_priceSetId];
    // process price set and get total amount and line items.
    $this->ensurePriceParamsAreSet($formValues);
    return $formValues;
  }

499 500 501 502 503 504
  /**
   * Wrapper function for unit tests.
   *
   * @param array $formValues
   */
  public function testSubmit($formValues) {
505
    $this->setContextVariables($formValues);
506 507 508 509 510
    $this->_memType = $formValues['membership_type_id'][1];
    $this->_params = $formValues;
    $this->submit();
  }

totten's avatar
totten committed
511
}