Don't freeze the end date if the membership is linked to a recurring payment
[civicrm-core.git] / CRM / Member / Form / Membership.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
5e56c7a5 35 * This class generates form components for offline membership form.
6a488035
TO
36 */
37class CRM_Member_Form_Membership extends CRM_Member_Form {
38
39 protected $_memType = NULL;
40
41 protected $_onlinePendingContributionId;
42
43 public $_mode;
44
45 public $_contributeMode = 'direct';
46
47 protected $_recurMembershipTypes;
48
49 protected $_memTypeSelected;
50
d424ffde 51 /**
fe482240 52 * Display name of the member.
d424ffde
CW
53 *
54 * @var string
6a488035 55 */
b11c92be 56 protected $_memberDisplayName = NULL;
6a488035 57
d424ffde
CW
58 /**
59 * email of the person paying for the membership (used for receipts)
971e129b 60 * @var string
d424ffde 61 */
b11c92be 62 protected $_memberEmail = NULL;
6a488035 63
d424ffde 64 /**
fe482240 65 * Contact ID of the member.
d424ffde
CW
66 *
67 * @var int
68 */
cc984198 69 public $_contactID = NULL;
6a488035 70
d424ffde
CW
71 /**
72 * Display name of the person paying for the membership (used for receipts)
73 *
74 * @var string
75 */
b11c92be 76 protected $_contributorDisplayName = NULL;
6a488035 77
d424ffde 78 /**
b11c92be 79 * email of the person paying for the membership (used for receipts)
971e129b 80 * @var string
b11c92be 81 */
82 protected $_contributorEmail = NULL;
6a488035 83
d424ffde
CW
84 /**
85 * email of the person paying for the membership (used for receipts)
86 *
87 * @var int
88 */
b11c92be 89 protected $_contributorContactID = NULL;
6a488035 90
d424ffde 91 /**
fe482240 92 * ID of the person the receipt is to go to.
d424ffde
CW
93 *
94 * @var int
b11c92be 95 */
96 protected $_receiptContactId = NULL;
6a488035 97
d424ffde 98 /**
4aa7d844 99 * Keep a class variable for ALL membership IDs so
6a488035 100 * postProcess hook function can do something with it
d424ffde
CW
101 *
102 * @var array
6a488035 103 */
be2fb01f 104 protected $_membershipIDs = [];
6a488035 105
e4f5c851 106 /**
59c798c9 107 * Set entity fields to be assigned to the form.
108 */
109 protected function setEntityFields() {
110 $this->entityFields = [
111 'join_date' => [
112 'name' => 'join_date',
113 'description' => ts('Member Since'),
114 ],
115 'start_date' => [
116 'name' => 'start_date',
117 'description' => ts('Start Date'),
118 ],
119 'end_date' => [
120 'name' => 'end_date',
121 'description' => ts('End Date'),
122 ],
123 ];
124 }
125
126 /**
127 * Set the delete message.
e4f5c851 128 *
59c798c9 129 * We do this from the constructor in order to do a translation.
e4f5c851 130 */
59c798c9 131 public function setDeleteMessage() {
132 $this->deleteMessage = '<span class="font-red bold">'
971e129b 133 . ts("WARNING: Deleting this membership will also delete any related payment (contribution) records." . ts("This action cannot be undone.")
59c798c9 134 . '</span><p>'
135 . ts("Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.")
136 . '</p><p>'
137 . ts("Click 'Delete' if you want to continue.") . '</p>');
e4f5c851 138 }
139
59c798c9 140 /**
141 * Overriding this entity trait function as not yet tested.
142 *
143 * We continue to rely on legacy handling.
144 */
145 public function addCustomDataToForm() {}
146
59c798c9 147 /**
148 * Overriding this entity trait function as not yet tested.
149 *
150 * We continue to rely on legacy handling.
151 */
152 public function addFormButtons() {}
153
18aa3e1e 154 /**
4efc56ef
EM
155 * Get selected membership type from the form values.
156 *
e4a6290d 157 * @param array $priceSet
4efc56ef
EM
158 * @param array $params
159 *
160 * @return array
18aa3e1e 161 */
e4a6290d 162 public static function getSelectedMemberships($priceSet, $params) {
be2fb01f 163 $memTypeSelected = [];
e4a6290d 164 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSet);
ccb02c2d 165 if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
be2fb01f 166 $memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
ccb02c2d 167 }
168 else {
18aa3e1e
EM
169 foreach ($priceFieldIDS as $priceFieldId) {
170 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
171 $memTypeSelected[$id] = $id;
172 }
173 }
174 }
18aa3e1e
EM
175 return $memTypeSelected;
176 }
177
178 /**
179 * Extract price set fields and values from $params.
180 *
5e56c7a5 181 * @param array $params
e4a6290d 182 * @param array $priceSet
5e56c7a5 183 *
18aa3e1e
EM
184 * @return array
185 */
e4a6290d 186 public static function getPriceFieldIDs($params, $priceSet) {
be2fb01f 187 $priceFieldIDS = [];
e4a6290d 188 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
15724d0a 189 foreach ($priceSet['fields'] as $fieldId => $field) {
e4a6290d 190 if (!empty($params['price_' . $fieldId])) {
191 if (is_array($params['price_' . $fieldId])) {
192 foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
193 if ($isSet) {
194 $priceFieldIDS[] = $priceFldVal;
195 }
18aa3e1e
EM
196 }
197 }
15724d0a 198 elseif (!$field['is_enter_qty']) {
e4a6290d 199 $priceFieldIDS[] = $params['price_' . $fieldId];
200 }
18aa3e1e
EM
201 }
202 }
203 }
204 return $priceFieldIDS;
205 }
206
5e56c7a5 207 /**
208 * Form preProcess function.
209 *
210 * @throws \Exception
211 */
6a488035 212 public function preProcess() {
186a737c
EM
213 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
214 $this->assign('formClass', 'membership');
a6513ad5 215 parent::preProcess();
6cc27bfa 216
6a488035
TO
217 // get price set id.
218 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
219 $this->set('priceSetId', $this->_priceSetId);
220 $this->assign('priceSetId', $this->_priceSetId);
221
6a488035
TO
222 if ($this->_action & CRM_Core_Action::DELETE) {
223 $contributionID = CRM_Member_BAO_Membership::getMembershipContributionId($this->_id);
224 // check delete permission for contribution
225 if ($this->_id && $contributionID && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
96ca8376 226 CRM_Core_Error::fatal(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
6a488035
TO
227 }
228 }
229
6a488035 230 if ($this->_action & CRM_Core_Action::ADD) {
6a488035
TO
231 if ($this->_contactID) {
232 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
be2fb01f
CW
233 $contactMemberships = [];
234 $memParams = ['contact_id' => $this->_contactID];
4256ea25 235 CRM_Member_BAO_Membership::getValues($memParams, $contactMemberships, TRUE);
be2fb01f 236 $cMemTypes = [];
4256ea25
AH
237 foreach ($contactMemberships as $mem) {
238 $cMemTypes[] = $mem['membership_type_id'];
239 }
240 if (count($cMemTypes) > 0) {
241 $memberorgs = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($cMemTypes);
be2fb01f 242 $mems_by_org = [];
2e8b13d1 243 foreach ($contactMemberships as $mem) {
4256ea25 244 $mem['member_of_contact_id'] = CRM_Utils_Array::value($mem['membership_type_id'], $memberorgs);
a7488080 245 if (!empty($mem['membership_end_date'])) {
4256ea25
AH
246 $mem['membership_end_date'] = CRM_Utils_Date::customformat($mem['membership_end_date']);
247 }
248 $mem['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
249 $mem['membership_type_id'],
250 'name', 'id'
6a488035 251 );
4256ea25
AH
252 $mem['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
253 $mem['status_id'],
254 'label', 'id'
6a488035 255 );
74dd0d90
CW
256 $mem['renewUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
257 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
258 . ($this->_mode ? '&mode=live' : '')
259 );
4256ea25
AH
260 $mem['membershipTab'] = CRM_Utils_System::url('civicrm/contact/view',
261 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
262 );
263 $mems_by_org[$mem['member_of_contact_id']] = $mem;
6a488035 264 }
74dd0d90 265 $this->assign('existingContactMemberships', $mems_by_org);
6a488035
TO
266 }
267 }
1001e556 268 else {
74dd0d90 269 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
d292601b
AH
270 $resources = CRM_Core_Resources::singleton();
271 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
be2fb01f 272 $passthru = [
d292601b 273 'typeorgs' => CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(),
74dd0d90
CW
274 'memtypes' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'membership_type_id'),
275 'statuses' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'status_id'),
be2fb01f
CW
276 ];
277 $resources->addSetting(['existingMems' => $passthru]);
d292601b 278 }
6a488035
TO
279 }
280
97ae4877 281 if (!$this->_memType) {
282 $params = CRM_Utils_Request::exportValues();
06470609 283 if (!empty($params['membership_type_id'][1])) {
71098424 284 $this->_memType = $params['membership_type_id'][1];
285 }
97ae4877 286 }
6452294d
MW
287
288 // Add custom data to form
289 CRM_Custom_Form_CustomData::addToForm($this, $this->_memType);
6a488035
TO
290
291 // CRM-4395, get the online pending contribution id.
292 $this->_onlinePendingContributionId = NULL;
293 if (!$this->_mode && $this->_id && ($this->_action & CRM_Core_Action::UPDATE)) {
294 $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id,
295 'Membership'
296 );
297 }
298 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId);
6a488035 299
e2046b33 300 $this->setPageTitle(ts('Membership'));
6a488035
TO
301 }
302
303 /**
5e56c7a5 304 * Set default values for the form.
6a488035
TO
305 */
306 public function setDefaultValues() {
6a488035
TO
307
308 if ($this->_priceSetId) {
9da8dc8c 309 return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults);
6a488035
TO
310 }
311
312 $defaults = parent::setDefaultValues();
313
314 //setting default join date and receive date
6a488035 315 if ($this->_action == CRM_Core_Action::ADD) {
9eb6085d 316 $defaults['receive_date'] = date('Y-m-d H:i:s');
6a488035
TO
317 }
318
6a488035
TO
319 $defaults['num_terms'] = 1;
320
a7488080 321 if (!empty($defaults['id'])) {
6a488035
TO
322 if ($this->_onlinePendingContributionId) {
323 $defaults['record_contribution'] = $this->_onlinePendingContributionId;
324 }
325 else {
326 $contributionId = CRM_Core_DAO::singleValueQuery("
327 SELECT contribution_id
328 FROM civicrm_membership_payment
329 WHERE membership_id = $this->_id
330 ORDER BY contribution_id
331 DESC limit 1");
332
333 if ($contributionId) {
334 $defaults['record_contribution'] = $contributionId;
335 }
336 }
337 }
133e2c99 338
374a4dd6 339 //set Soft Credit Type to Gift by default
340 $scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
341 $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
342
a7488080 343 if (!empty($defaults['record_contribution']) && !$this->_mode) {
be2fb01f
CW
344 $contributionParams = ['id' => $defaults['record_contribution']];
345 $contributionIds = [];
6a488035
TO
346
347 //keep main object campaign in hand.
348 $memberCampaignId = CRM_Utils_Array::value('campaign_id', $defaults);
349
350 CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds);
351
352 //get back original object campaign id.
353 $defaults['campaign_id'] = $memberCampaignId;
354
6a488035 355 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
a7488080 356 if (!empty($defaults['membership_source'])) {
6a488035
TO
357 $defaults['source'] = $defaults['membership_source'];
358 }
359 }
d96cf288 360 //CRM-13420
a7488080 361 if (empty($defaults['payment_instrument_id'])) {
d96cf288
DG
362 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
363 }
6a488035
TO
364
365 // User must explicitly choose to send a receipt in both add and update mode.
366 $defaults['send_receipt'] = 0;
367
368 if ($this->_action & CRM_Core_Action::UPDATE) {
369 // in this mode by default uncheck this checkbox
370 unset($defaults['record_contribution']);
371 }
372
2e8b13d1 373 $subscriptionCancelled = FALSE;
a7488080 374 if (!empty($defaults['id'])) {
6a488035
TO
375 $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id);
376 }
377
378 $alreadyAutoRenew = FALSE;
a7488080 379 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
6a488035
TO
380 $defaults['auto_renew'] = 1;
381 $alreadyAutoRenew = TRUE;
382 }
383 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
384
385 $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
386
387 $this->assign('membership_status_id', CRM_Utils_Array::value('status_id', $defaults));
388
a7488080 389 if (!empty($defaults['is_pay_later'])) {
6a488035
TO
390 $this->assign('is_pay_later', TRUE);
391 }
392 if ($this->_mode) {
3b8e6c3f 393 $defaults = $this->getBillingDefaults($defaults);
5e56c7a5 394 // hack to simplify credit card entry for testing
395 // $defaults['credit_card_type'] = 'Visa';
396 // $defaults['credit_card_number'] = '4807731747657838';
397 // $defaults['cvv2'] = '000';
398 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
6a488035
TO
399 }
400
6a488035 401 //setting default join date if there is no join date
a7488080 402 if (empty($defaults['join_date'])) {
b5876030 403 $defaults['join_date'] = date('Y-m-d');
6a488035
TO
404 }
405
a7488080 406 if (!empty($defaults['membership_end_date'])) {
6a488035
TO
407 $this->assign('endDate', $defaults['membership_end_date']);
408 }
409
410 return $defaults;
411 }
412
413 /**
fe482240 414 * Build the form object.
6a488035
TO
415 */
416 public function buildQuickForm() {
6a488035 417
59c798c9 418 $this->buildQuickEntityForm();
a5dfa653 419 $this->assign('currency', CRM_Core_BAO_Country::defaultCurrencySymbol());
53d0a906 420 $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
6a488035
TO
421 // build price set form.
422 $buildPriceSet = FALSE;
8cc574cf 423 if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
a7488080 424 if (!empty($_POST['price_set_id'])) {
6a488035
TO
425 $buildPriceSet = TRUE;
426 }
427 $getOnlyPriceSetElements = TRUE;
428 if (!$this->_priceSetId) {
429 $this->_priceSetId = $_POST['price_set_id'];
430 $getOnlyPriceSetElements = FALSE;
431 }
432
433 $this->set('priceSetId', $this->_priceSetId);
9da8dc8c 434 CRM_Price_BAO_PriceSet::buildPriceSet($this);
6a488035 435
be2fb01f 436 $optionsMembershipTypes = [];
6a488035
TO
437 foreach ($this->_priceSet['fields'] as $pField) {
438 if (empty($pField['options'])) {
439 continue;
440 }
441 foreach ($pField['options'] as $opId => $opValues) {
442 $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
443 }
444 }
445
9da8dc8c 446 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
6a488035
TO
447
448 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
5a9c4d4a 449 $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
6a488035
TO
450
451 // get only price set form elements.
452 if ($getOnlyPriceSetElements) {
453 return;
454 }
455 }
456
457 // use to build form during form rule.
458 $this->assign('buildPriceSet', $buildPriceSet);
459
460 if ($this->_action & CRM_Core_Action::ADD) {
461 $buildPriceSet = FALSE;
9da8dc8c 462 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
6a488035
TO
463 if (!empty($priceSets)) {
464 $buildPriceSet = TRUE;
465 }
466
467 if ($buildPriceSet) {
468 $this->add('select', 'price_set_id', ts('Choose price set'),
be2fb01f 469 [
21dfd5f5 470 '' => ts('Choose price set'),
be2fb01f
CW
471 ] + $priceSets,
472 NULL, ['onchange' => "buildAmount( this.value );"]
6a488035
TO
473 );
474 }
475 $this->assign('hasPriceSets', $buildPriceSet);
476 }
477
6a488035 478 if ($this->_action & CRM_Core_Action::DELETE) {
be2fb01f
CW
479 $this->addButtons([
480 [
c5c263ca
AH
481 'type' => 'next',
482 'name' => ts('Delete'),
483 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
484 'isDefault' => TRUE,
be2fb01f
CW
485 ],
486 [
c5c263ca
AH
487 'type' => 'cancel',
488 'name' => ts('Cancel'),
be2fb01f
CW
489 ],
490 ]);
6a488035
TO
491 return;
492 }
493
494 if ($this->_context == 'standalone') {
be2fb01f 495 $this->addEntityRef('contact_id', ts('Contact'), [
c5c263ca 496 'create' => TRUE,
be2fb01f
CW
497 'api' => ['extra' => ['email']],
498 ], TRUE);
6a488035
TO
499 }
500
501 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
502
c60d2e2c 503 // Throw status bounce when no Membership type or priceset is present
7284a1a4
PN
504 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
505 && empty($this->allMembershipTypeDetails) && empty($priceSets)
506 ) {
c60d2e2c
PN
507 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
508 }
6a488035 509 // retrieve all memberships
be2fb01f 510 $allMembershipInfo = [];
ab30e033
EM
511 foreach ($this->allMembershipTypeDetails as $key => $values) {
512 if ($this->_mode && empty($values['minimum_fee'])) {
513 continue;
514 }
515 else {
516 $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
517 if (empty($selMemTypeOrg[$memberOfContactId])) {
518 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
519 $memberOfContactId,
520 'display_name',
521 'id'
522 );
6a488035 523
ab30e033 524 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
6a488035 525 }
ab30e033
EM
526 if (empty($selOrgMemType[$memberOfContactId][$key])) {
527 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
6a488035 528 }
6a488035 529 }
decbd3d0 530 $totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
531 //CRM-18827 - override the default value if total_amount is submitted
532 if (!empty($this->_submitValues['total_amount'])) {
533 $totalAmount = $this->_submitValues['total_amount'];
534 }
ab30e033
EM
535 // build membership info array, which is used when membership type is selected to:
536 // - set the payment information block
537 // - set the max related block
be2fb01f 538 $allMembershipInfo[$key] = [
ab30e033 539 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
decbd3d0 540 'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
541 'total_amount_numeric' => $totalAmount,
ab30e033
EM
542 'auto_renew' => CRM_Utils_Array::value('auto_renew', $values),
543 'has_related' => isset($values['relationship_type_id']),
544 'max_related' => CRM_Utils_Array::value('max_related', $values),
be2fb01f 545 ];
6a488035
TO
546 }
547
548 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
549
550 // show organization by default, if only one organization in
551 // the list
552 if (count($selMemTypeOrg) == 2) {
553 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
554 }
555 //sort membership organization and type, CRM-6099
556 natcasesort($selMemTypeOrg);
557 foreach ($selOrgMemType as $index => $orgMembershipType) {
558 natcasesort($orgMembershipType);
559 $selOrgMemType[$index] = $orgMembershipType;
560 }
561
be2fb01f 562 $memTypeJs = [
ab30e033 563 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
be2fb01f 564 ];
8deb20a3 565
ab30e033 566 if (!empty($this->_recurPaymentProcessors)) {
51a6bf4f 567 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
ab30e033 568 }
6a488035 569
6a488035
TO
570 $this->add('text', 'max_related', ts('Max related'),
571 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related')
572 );
573
353ffa53 574 $sel = &$this->addElement('hierselect',
6a488035
TO
575 'membership_type_id',
576 ts('Membership Organization and Type'),
577 $memTypeJs
578 );
579
be2fb01f 580 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
53d0a906 581 if ($isUpdateToExistingRecurringMembership) {
582 $sel->freeze();
6a488035
TO
583 }
584
6a488035 585 if ($this->_action & CRM_Core_Action::ADD) {
be2fb01f 586 $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
6a488035
TO
587 }
588
6a488035
TO
589 $this->add('text', 'source', ts('Source'),
590 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source')
591 );
592
593 //CRM-7362 --add campaigns.
594 $campaignId = NULL;
595 if ($this->_id) {
596 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
597 }
598 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
599
600 if (!$this->_mode) {
601 $this->add('select', 'status_id', ts('Membership Status'),
be2fb01f 602 ['' => ts('- select -')] + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
6a488035 603 );
e136f704
O
604
605 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
606 CRM_Member_StatusOverrideTypes::getSelectOptions()
6a488035 607 );
53d0a906 608 if ($statusOverride && $isUpdateToExistingRecurringMembership) {
609 $statusOverride->freeze();
6a488035
TO
610 }
611
be2fb01f 612 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => time(), 'time' => FALSE]);
e136f704 613
6a488035
TO
614 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
615
6a488035
TO
616 $this->add('text', 'total_amount', ts('Amount'));
617 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
618
9eb6085d 619 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
6a488035
TO
620
621 $this->add('select', 'payment_instrument_id',
4db803dd 622 ts('Payment Method'),
be2fb01f
CW
623 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
624 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
6a488035
TO
625 );
626 $this->add('text', 'trxn_id', ts('Transaction ID'));
627 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
be2fb01f 628 'objectExists', [
5e56c7a5 629 'CRM_Contribute_DAO_Contribution',
630 $this->_id,
631 'trxn_id',
be2fb01f 632 ]
6a488035
TO
633 );
634
6a488035 635 $this->add('select', 'contribution_status_id',
7fe7b63d 636 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('membership')
6a488035
TO
637 );
638 $this->add('text', 'check_number', ts('Check Number'),
639 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
640 );
641 }
642 else {
643 //add field for amount to allow an amount to be entered that differs from minimum
644 $this->add('text', 'total_amount', ts('Amount'));
645 }
5a9c4d4a
PN
646 $this->add('select', 'financial_type_id',
647 ts('Financial Type'),
be2fb01f 648 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action)
5a9c4d4a 649 );
d80dbc14 650
d80dbc14 651 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
186a737c 652
be2fb01f
CW
653 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
654 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
d80dbc14 655
6a488035
TO
656 $this->addElement('checkbox',
657 'send_receipt',
658 ts('Send Confirmation and Receipt?'), NULL,
be2fb01f 659 ['onclick' => "showEmailOptions()"]
6a488035
TO
660 );
661
662 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
663
186a737c 664 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
6a488035
TO
665
666 // Retrieve the name and email of the contact - this will be the TO for receipt email
667 if ($this->_contactID) {
668 list($this->_memberDisplayName,
669 $this->_memberEmail
b11c92be 670 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
6a488035
TO
671
672 $this->assign('emailExists', $this->_memberEmail);
673 $this->assign('displayName', $this->_memberDisplayName);
674 }
675
50b85bf9 676 if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
677 $this->assign('cancelAutoRenew',
678 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
679 );
680 }
53d0a906 681
50b85bf9 682 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
6a488035 683
be2fb01f 684 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
8c80f3f9 685 $mailingInfo = Civi::settings()->get('mailing_backend');
686 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
6a488035
TO
687
688 parent::buildQuickForm();
689 }
690
691 /**
fe482240 692 * Validation.
6a488035 693 *
b2363ea8
TO
694 * @param array $params
695 * (ref.) an assoc array of name/value pairs.
6a488035 696 *
5e56c7a5 697 * @param array $files
698 * @param CRM_Member_Form_Membership $self
2a6da8d7
EM
699 *
700 * @throws CiviCRM_API3_Exception
72b3a70c
CW
701 * @return bool|array
702 * mixed true or array of errors
6a488035 703 */
00be9182 704 public static function formRule($params, $files, $self) {
be2fb01f 705 $errors = [];
6a488035 706
ccb02c2d 707 $priceSetId = self::getPriceSetID($params);
708 $priceSetDetails = self::getPriceSetDetails($params);
6a488035 709
e4a6290d 710 $selectedMemberships = self::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
ccb02c2d 711
712 if (!empty($params['price_set_id'])) {
9da8dc8c 713 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
6a488035 714
15724d0a 715 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
6a488035
TO
716
717 if (!empty($priceFieldIDS)) {
718 $ids = implode(',', $priceFieldIDS);
719
9da8dc8c 720 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
2e8b13d1 721 foreach ($count as $occurrence) {
b44e3f84 722 if ($occurrence > 1) {
6a488035
TO
723 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
724 }
725 }
6a488035 726 }
867047cd 727 // Return error if empty $self->_memTypeSelected
728 if (empty($errors) && empty($selectedMemberships)) {
729 $errors['_qf_default'] = ts('Select at least one membership option.');
730 }
731 if (!$self->_mode && empty($params['record_contribution'])) {
732 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
733 }
6a488035 734 }
867047cd 735 else {
736 if (empty($params['membership_type_id'][1])) {
737 $errors['membership_type_id'] = ts('Please select a membership type.');
738 }
6a488035
TO
739 $numterms = CRM_Utils_Array::value('num_terms', $params);
740 if ($numterms && intval($numterms) != $numterms) {
741 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
742 }
6a488035 743
356b5786 744 if (($self->_mode || isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
867047cd 745 $errors['financial_type_id'] = ts('Please enter the financial Type.');
746 }
6a488035
TO
747 }
748
18aa3e1e
EM
749 if (!empty($errors) && (count($selectedMemberships) > 1)) {
750 $memberOfContacts = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($selectedMemberships);
6a488035
TO
751 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
752 foreach ($duplicateMemberOfContacts as $countDuplicate) {
753 if ($countDuplicate > 1) {
754 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
755 }
756 }
757 }
758
6a488035
TO
759 if (!empty($errors)) {
760 return $errors;
761 }
762
8cc574cf 763 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
4db803dd 764 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
d96cf288 765 }
6a488035 766
a7488080
CW
767 if (!empty($params['is_different_contribution_contact'])) {
768 if (empty($params['soft_credit_type_id'])) {
133e2c99 769 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
770 }
d80dbc14 771 if (empty($params['soft_credit_contact_id'])) {
772 $errors['soft_credit_contact_id'] = ts('Please select a contact');
133e2c99 773 }
774 }
775
a7488080 776 if (!empty($params['payment_processor_id'])) {
a479fe60 777 // validate payment instrument (e.g. credit card number)
f48e6cf7 778 CRM_Core_Payment_Form::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
6a488035
TO
779 }
780
781 $joinDate = NULL;
a7488080 782 if (!empty($params['join_date'])) {
6a488035
TO
783
784 $joinDate = CRM_Utils_Date::processDate($params['join_date']);
785
18aa3e1e 786 foreach ($selectedMemberships as $memType) {
6a488035 787 $startDate = NULL;
a7488080 788 if (!empty($params['start_date'])) {
6a488035
TO
789 $startDate = CRM_Utils_Date::processDate($params['start_date']);
790 }
791
792 // if end date is set, ensure that start date is also set
793 // and that end date is later than start date
6a488035 794 $endDate = NULL;
a7488080 795 if (!empty($params['end_date'])) {
6a488035
TO
796 $endDate = CRM_Utils_Date::processDate($params['end_date']);
797 }
798
799 $membershipDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($memType);
800
801 if ($startDate && CRM_Utils_Array::value('period_type', $membershipDetails) == 'rolling') {
802 if ($startDate < $joinDate) {
803 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
804 }
805 }
806
807 if ($endDate) {
808 if ($membershipDetails['duration_unit'] == 'lifetime') {
f476dde8 809 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
ae3d69ec 810 // process to update status based on end-date. The user must change the status now.
be2fb01f 811 $result = civicrm_api3('MembershipStatus', 'get', [
ae3d69ec
SG
812 'sequential' => 1,
813 'is_current_member' => 0,
be2fb01f 814 ]);
f476dde8 815 $tmp_statuses = $result['values'];
be2fb01f 816 $status_ids = [];
22e263ad 817 foreach ($tmp_statuses as $cur_stat) {
8efea814 818 $status_ids[] = $cur_stat['id'];
f476dde8 819 }
e136f704 820
481a74f4 821 if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
f476dde8 822 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
e136f704
O
823 }
824
825 if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes::isPermanent($params['is_override'])) {
826 $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
f476dde8 827 }
6a488035
TO
828 }
829 else {
830 if (!$startDate) {
831 $errors['start_date'] = ts('Start date must be set if end date is set.');
832 }
833 if ($endDate < $startDate) {
834 $errors['end_date'] = ts('End date must be the same or later than start date.');
835 }
836 }
837 }
838
5e56c7a5 839 // Default values for start and end dates if not supplied on the form.
6a488035
TO
840 $defaultDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
841 $joinDate,
842 $startDate,
843 $endDate
844 );
845
846 if (!$startDate) {
847 $startDate = CRM_Utils_Array::value('start_date',
848 $defaultDates
849 );
850 }
851 if (!$endDate) {
852 $endDate = CRM_Utils_Array::value('end_date',
853 $defaultDates
854 );
855 }
856
857 //CRM-3724, check for availability of valid membership status.
e136f704 858 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
6a488035
TO
859 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
860 $endDate,
861 $joinDate,
862 'today',
5f11bbcc
EM
863 TRUE,
864 $memType,
865 $params
6a488035
TO
866 );
867 if (empty($calcStatus)) {
868 $url = CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
869 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
be2fb01f 870 $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can <a href="%1">Configure Membership Status Rules</a>.', [1 => $url]);
6a488035 871 if (!$self->_mode) {
e136f704 872 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
6a488035
TO
873 }
874 CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
875 }
876 }
877 }
878 }
879 else {
880 $errors['join_date'] = ts('Please enter the Member Since.');
881 }
882
e136f704
O
883 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isOverridden($params['is_override']) && empty($params['status_id'])) {
884 $errors['status_id'] = ts('Please enter the Membership status.');
885 }
886
887 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isUntilDate($params['is_override'])) {
888 if (empty($params['status_override_end_date'])) {
889 $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
890 }
6a488035
TO
891 }
892
893 //total amount condition arise when membership type having no
894 //minimum fee
895 if (isset($params['record_contribution'])) {
6a488035
TO
896 if (CRM_Utils_System::isNull($params['total_amount'])) {
897 $errors['total_amount'] = ts('Please enter the contribution.');
898 }
899 }
900
901 // validate contribution status for 'Failed'.
8cc574cf 902 if ($self->_onlinePendingContributionId && !empty($params['record_contribution']) &&
6a488035
TO
903 (CRM_Utils_Array::value('contribution_status_id', $params) ==
904 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
905 )
906 ) {
907 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
908 }
909
910 return empty($errors) ? TRUE : $errors;
911 }
912
913 /**
fe482240 914 * Process the form submission.
6a488035
TO
915 */
916 public function postProcess() {
917 if ($this->_action & CRM_Core_Action::DELETE) {
3506b6cd 918 CRM_Member_BAO_Membership::del($this->_id);
6a488035
TO
919 return;
920 }
7865d848
EM
921 // get the submitted form values.
922 $this->_params = $this->controller->exportValues($this->_name);
e9fe9519 923 $this->prepareStatusOverrideValues();
6a488035 924
09108d7d 925 $this->submit();
7865d848
EM
926
927 $this->setUserContext();
928 }
929
e9fe9519
O
930 /**
931 * Prepares the values related to status override.
932 */
933 private function prepareStatusOverrideValues() {
934 $this->setOverrideDateValue();
935 $this->convertIsOverrideValue();
936 }
937
938 /**
939 * Sets status override end date to empty value if
940 * the selected override option is not 'until date'.
941 */
942 private function setOverrideDateValue() {
393f1657 943 if (!CRM_Member_StatusOverrideTypes::isUntilDate(CRM_Utils_Array::value('is_override', $this->_params))) {
e9fe9519
O
944 $this->_params['status_override_end_date'] = '';
945 }
946 }
947
e136f704
O
948 /**
949 * Convert the value of selected (status override?)
950 * option to TRUE if it indicate an overridden status
951 * or FALSE otherwise.
952 */
953 private function convertIsOverrideValue() {
954 $this->_params['is_override'] = CRM_Member_StatusOverrideTypes::isOverridden($this->_params['is_override']);
955 }
956
7865d848
EM
957 /**
958 * Send email receipt.
959 *
829df55e 960 * @deprecated
961 * This function is shared with Batch_Entry which has limited overlap
962 * & needs rationalising.
963 *
7865d848
EM
964 * @param CRM_Core_Form $form
965 * Form object.
966 * @param array $formValues
967 * @param object $membership
968 * Object.
efc0e24a 969 * @param array $customValues
7865d848
EM
970 *
971 * @return bool
972 * true if mail was sent successfully
973 */
efc0e24a 974 public static function emailReceipt(&$form, &$formValues, &$membership, $customValues = NULL) {
7865d848 975 // retrieve 'from email id' for acknowledgement
beac1417 976 $receiptFrom = CRM_Utils_Array::value('from_email_address', $formValues);
7865d848 977
efc0e24a 978 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
7865d848
EM
979 if (!empty($formValues['payment_instrument_id'])) {
980 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
981 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
982 }
983
0816949d 984 $form->assign('customValues', $customValues);
7865d848
EM
985
986 if ($form->_mode) {
efc0e24a 987 // @todo move this outside shared code as Batch entry just doesn't
5103bd18 988 $form->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
0b50eca0 989 $form->_params,
990 $form->_bltID
991 ));
7d193e45 992
7865d848
EM
993 $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']);
994 $date = CRM_Utils_Date::mysqlToIso($date);
995 $form->assign('credit_card_exp_date', $date);
996 $form->assign('credit_card_number',
997 CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number'])
998 );
999 $form->assign('credit_card_type', $form->_params['credit_card_type']);
1000 $form->assign('contributeMode', 'direct');
1001 $form->assign('isAmountzero', 0);
1002 $form->assign('is_pay_later', 0);
1003 $form->assign('isPrimary', 1);
1004 }
1005
1006 $form->assign('module', 'Membership');
1007 $form->assign('contactID', $formValues['contact_id']);
1008
1009 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
1010
1011 if (!empty($formValues['contribution_id'])) {
1012 $form->assign('contributionID', $formValues['contribution_id']);
1013 }
1014 elseif (isset($form->_onlinePendingContributionId)) {
1015 $form->assign('contributionID', $form->_onlinePendingContributionId);
1016 }
1017
1018 if (!empty($formValues['contribution_status_id'])) {
1019 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1020 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
1021 }
1022
1023 if (!empty($formValues['is_renew'])) {
1024 $form->assign('receiptType', 'membership renewal');
1025 }
1026 else {
1027 $form->assign('receiptType', 'membership signup');
1028 }
9eb6085d 1029 $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
7865d848
EM
1030 $form->assign('formValues', $formValues);
1031
1032 if (empty($lineItem)) {
1033 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y'));
1034 if (!CRM_Utils_System::isNull($membership->end_date)) {
1035 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y'));
1036 }
1037 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
1038 }
1039
efc0e24a 1040 // @todo - if we have to figure out if this is for batch processing it doesn't belong in the shared function.
7865d848
EM
1041 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1042 if ((empty($form->_contributorDisplayName) || empty($form->_contributorEmail)) || $isBatchProcess) {
1043 // in this case the form is being called statically from the batch editing screen
1044 // having one class in the form layer call another statically is not greate
1045 // & we should aim to move this function to the BAO layer in future.
1046 // however, we can assume that the contact_id passed in by the batch
1047 // function will be the recipient
1048 list($form->_contributorDisplayName, $form->_contributorEmail)
1049 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
1050 if (empty($form->_receiptContactId) || $isBatchProcess) {
1051 $form->_receiptContactId = $formValues['contact_id'];
1052 }
1053 }
efc0e24a 1054 // @todo determine isEmailPdf in calling function.
7865d848
EM
1055 $template = CRM_Core_Smarty::singleton();
1056 $taxAmt = $template->get_template_vars('dataArray');
1057 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
aaffa79f 1058 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
7865d848
EM
1059 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1060 if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1061 $isEmailPdf = TRUE;
1062 }
1063 else {
1064 $isEmailPdf = FALSE;
1065 }
1066
1067 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
be2fb01f 1068 [
7865d848
EM
1069 'groupName' => 'msg_tpl_workflow_membership',
1070 'valueName' => 'membership_offline_receipt',
1071 'contactId' => $form->_receiptContactId,
1072 'from' => $receiptFrom,
1073 'toName' => $form->_contributorDisplayName,
1074 'toEmail' => $form->_contributorEmail,
1075 'PDFFilename' => ts('receipt') . '.pdf',
1076 'isEmailPdf' => $isEmailPdf,
1077 'contributionId' => $formValues['contribution_id'],
1078 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
be2fb01f 1079 ]
7865d848
EM
1080 );
1081
1082 return TRUE;
1083 }
1084
1085 /**
5e56c7a5 1086 * Submit function.
1087 *
1088 * This is also accessed by unit tests.
7865d848 1089 */
09108d7d 1090 public function submit() {
4bd318e0 1091 $isTest = ($this->_mode == 'test') ? 1 : 0;
09108d7d 1092 $this->storeContactFields($this->_params);
ba2f3f65 1093 $this->beginPostProcess();
7865d848 1094 $joinDate = $startDate = $endDate = NULL;
be2fb01f 1095 $membershipTypes = $membership = $calcDate = [];
41709813 1096 $membershipType = NULL;
18135422 1097 $paymentInstrumentID = $this->_paymentProcessor['object']->getPaymentInstrumentID();
be2fb01f 1098 $params = $softParams = $ids = [];
7865d848 1099
64412b4e 1100 $mailSend = FALSE;
09108d7d 1101 $this->processBillingAddress();
64412b4e
MWMC
1102 $formValues = $this->_params;
1103 $formValues = $this->setPriceSetParameters($formValues);
7865d848 1104
08fd4b45
EM
1105 if ($this->_id) {
1106 $ids['membership'] = $params['id'] = $this->_id;
1107 }
1108 $ids['userId'] = CRM_Core_Session::singleton()->get('userID');
1109
7865d848
EM
1110 // Set variables that we normally get from context.
1111 // In form mode these are set in preProcess.
1112 //TODO: set memberships, fixme
1113 $this->setContextVariables($formValues);
ccb02c2d 1114
e4a6290d 1115 $this->_memTypeSelected = self::getSelectedMemberships(
ccb02c2d 1116 $this->_priceSet,
e4a6290d 1117 $formValues
1118 );
867047cd 1119 if (empty($formValues['financial_type_id'])) {
ccb02c2d 1120 $formValues['financial_type_id'] = $this->_priceSet['financial_type_id'];
867047cd 1121 }
7865d848 1122
6a488035 1123 $config = CRM_Core_Config::singleton();
6a488035 1124
be2fb01f 1125 $membershipTypeValues = [];
6a488035
TO
1126 foreach ($this->_memTypeSelected as $memType) {
1127 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1128 }
1129
1130 //take the required membership recur values.
7865d848 1131 if ($this->_mode && !empty($formValues['auto_renew'])) {
ccb02c2d 1132 $params['is_recur'] = $formValues['is_recur'] = TRUE;
6a488035
TO
1133
1134 $count = 0;
1135 foreach ($this->_memTypeSelected as $memType) {
1136 $recurMembershipTypeValues = CRM_Utils_Array::value($memType,
ec7af55f 1137 $this->allMembershipTypeDetails, []
6a488035 1138 );
ec7af55f 1139 if (!$recurMembershipTypeValues['auto_renew']) {
1140 continue;
1141 }
1142 foreach ([
1143 'frequency_interval' => 'duration_interval',
1144 'frequency_unit' => 'duration_unit',
1145 ] as $mapVal => $mapParam) {
1146 $membershipTypeValues[$memType][$mapVal] = $recurMembershipTypeValues[$mapParam];
1147
6a488035 1148 if (!$count) {
ccb02c2d 1149 $formValues[$mapVal] = CRM_Utils_Array::value($mapParam,
6a488035
TO
1150 $recurMembershipTypeValues
1151 );
1152 }
1153 }
1154 $count++;
1155 }
6a488035
TO
1156 }
1157
ccb02c2d 1158 $isQuickConfig = $this->_priceSet['is_quick_config'];
1159
be2fb01f 1160 $termsByType = [];
9f1bc5dc 1161
be2fb01f 1162 $lineItem = [$this->_priceSetId => []];
ccb02c2d 1163
b764bfd0 1164 // BEGIN Fix for dev/core/issues/860
63b45b1d
DJ
1165 // Prepare fee block and call buildAmount hook - based on CRM_Price_BAO_PriceSet::buildPriceSet().
1166 CRM_Price_BAO_PriceSet::applyACLFinancialTypeStatusToFeeBlock($this->_priceSet['fields']);
1167 CRM_Utils_Hook::buildAmount('membership', $this, $this->_priceSet['fields']);
b764bfd0
DJ
1168 // END Fix for dev/core/issues/860
1169
08fd4b45 1170 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1a1a2f4f 1171 $formValues, $lineItem[$this->_priceSetId], NULL, $this->_priceSetId);
ccb02c2d 1172
de6c59ca 1173 if (!empty($formValues['tax_amount'])) {
ccb02c2d 1174 $params['tax_amount'] = $formValues['tax_amount'];
08fd4b45 1175 }
ccb02c2d 1176 $params['total_amount'] = CRM_Utils_Array::value('amount', $formValues);
ccb02c2d 1177 if (!empty($lineItem[$this->_priceSetId])) {
1178 foreach ($lineItem[$this->_priceSetId] as &$li) {
08fd4b45
EM
1179 if (!empty($li['membership_type_id'])) {
1180 if (!empty($li['membership_num_terms'])) {
1181 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
6a488035 1182 }
08fd4b45 1183 }
6a488035 1184
08fd4b45
EM
1185 ///CRM-11529 for quick config backoffice transactions
1186 //when financial_type_id is passed in form, update the
1187 //lineitems with the financial type selected in form
c26225d2 1188 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
08fd4b45
EM
1189 if ($isQuickConfig && $submittedFinancialType) {
1190 $li['financial_type_id'] = $submittedFinancialType;
6a488035
TO
1191 }
1192 }
1193 }
1194
6a488035
TO
1195 $params['contact_id'] = $this->_contactID;
1196
be2fb01f 1197 $fields = [
6a488035
TO
1198 'status_id',
1199 'source',
1200 'is_override',
e136f704 1201 'status_override_end_date',
6a488035 1202 'campaign_id',
be2fb01f 1203 ];
6a488035
TO
1204
1205 foreach ($fields as $f) {
1206 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1207 }
1208
1209 // fix for CRM-3724
1210 // when is_override false ignore is_admin statuses during membership
1211 // status calculation. similarly we did fix for import in CRM-3570.
a7488080 1212 if (empty($params['is_override'])) {
6a488035
TO
1213 $params['exclude_is_admin'] = TRUE;
1214 }
1215
1216 // process date params to mysql date format.
be2fb01f 1217 $dateTypes = [
6a488035
TO
1218 'join_date' => 'joinDate',
1219 'start_date' => 'startDate',
1220 'end_date' => 'endDate',
be2fb01f 1221 ];
6a488035
TO
1222 foreach ($dateTypes as $dateField => $dateVariable) {
1223 $$dateVariable = CRM_Utils_Date::processDate($formValues[$dateField]);
1224 }
1225
b09fe5ed 1226 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
6a488035 1227
be2fb01f 1228 $calcDates = [];
6a488035 1229 foreach ($this->_memTypeSelected as $memType) {
1693f081 1230 if (empty($memTypeNumTerms)) {
1231 $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
1232 }
6a488035
TO
1233 $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
1234 $joinDate, $startDate, $endDate, $memTypeNumTerms
1235 );
1236 }
1237
1238 foreach ($calcDates as $memType => $calcDate) {
5d86176b 1239 foreach (array_keys($dateTypes) as $d) {
6a488035
TO
1240 //first give priority to form values then calDates.
1241 $date = CRM_Utils_Array::value($d, $formValues);
1242 if (!$date) {
1243 $date = CRM_Utils_Array::value($d, $calcDate);
1244 }
1245
1246 $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
6a488035
TO
1247 }
1248 }
1249
6a488035
TO
1250 foreach ($this->_memTypeSelected as $memType) {
1251 if (array_key_exists('max_related', $formValues)) {
c26225d2 1252 // max related memberships - take from form or inherit from membership type
6a488035
TO
1253 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
1254 }
6a488035 1255 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues,
6a488035
TO
1256 $this->_id,
1257 'Membership'
1258 );
6a488035
TO
1259 $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1260 $memType
1261 );
1262 }
1263
1264 $membershipType = implode(', ', $membershipTypes);
1265
1266 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
ab30e033 1267 list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
6a488035 1268
d80dbc14 1269 //CRM-13981, allow different person as a soft-contributor of chosen type
b11c92be 1270 if ($this->_contributorContactID != $this->_contactID) {
91ef9be0 1271 $params['contribution_contact_id'] = $this->_contributorContactID;
ccb02c2d 1272 if (!empty($formValues['soft_credit_type_id'])) {
1273 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
91ef9be0 1274 $softParams['contact_id'] = $this->_contactID;
6a488035
TO
1275 }
1276 }
c26225d2
MWMC
1277
1278 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1279
a7488080 1280 if (!empty($formValues['record_contribution'])) {
be2fb01f 1281 $recordContribution = [
b11c92be 1282 'total_amount',
b11c92be 1283 'financial_type_id',
1284 'payment_instrument_id',
1285 'trxn_id',
1286 'contribution_status_id',
1287 'check_number',
1288 'campaign_id',
1289 'receive_date',
a55e39e9 1290 'card_type_id',
1291 'pan_truncation',
be2fb01f 1292 ];
6a488035
TO
1293
1294 foreach ($recordContribution as $f) {
1295 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1296 }
1297
1298 if (!$this->_onlinePendingContributionId) {
2286d173 1299 if (empty($formValues['source'])) {
be2fb01f 1300 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', [
7865d848
EM
1301 1 => $membershipType,
1302 2 => $userName,
be2fb01f 1303 ]);
2286d173
PD
1304 }
1305 else {
0e81467c 1306 $params['contribution_source'] = $formValues['source'];
2286d173 1307 }
0e81467c 1308 }
6a488035 1309
c26225d2 1310 $completedContributionStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
a7488080 1311 if (empty($params['is_override']) &&
c26225d2 1312 CRM_Utils_Array::value('contribution_status_id', $params) != $completedContributionStatusId
6a488035 1313 ) {
c26225d2 1314 $params['status_id'] = $pendingMembershipStatusId;
6a488035
TO
1315 $params['skipStatusCal'] = TRUE;
1316 $params['is_pay_later'] = 1;
1317 $this->assign('is_pay_later', 1);
1318 }
1319
a7488080 1320 if (!empty($formValues['send_receipt'])) {
5d86176b 1321 $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
6a488035
TO
1322 }
1323
1324 //insert financial type name in receipt.
1325 $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1326 $formValues['financial_type_id']
1327 );
1328 }
1329
1330 // process line items, until no previous line items.
1331 if (!empty($lineItem)) {
1332 $params['lineItems'] = $lineItem;
1333 $params['processPriceSet'] = TRUE;
1334 }
be2fb01f 1335 $createdMemberships = [];
6a488035 1336 if ($this->_mode) {
ccb02c2d 1337 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
a7f2d5fd 1338
1339 //CRM-20264 : Store CC type and number (last 4 digit) during backoffice or online payment
1340 $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $this->_params);
1341 $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $this->_params);
a8d4ff25 1342
ccb02c2d 1343 if (!$isQuickConfig) {
b11c92be 1344 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet',
ccb02c2d 1345 $this->_priceSetId,
6a488035
TO
1346 'financial_type_id'
1347 );
1348 }
1349 else {
5a9c4d4a 1350 $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
6a488035
TO
1351 }
1352
ba2f3f65 1353 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
ccb02c2d 1354 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
09108d7d 1355 $params['register_date'] = date('YmdHis');
6a488035 1356
a1a94e61 1357 // add all the additional payment params we need
ccb02c2d 1358 $formValues['amount'] = $params['total_amount'];
ba2f3f65 1359 // @todo this is a candidate for beginPostProcessFunction.
ccb02c2d 1360 $formValues['currencyID'] = $config->defaultCurrency;
1361 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1362 $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
1363 $formValues['financial_type_id'] = $params['financial_type_id'];
6a488035
TO
1364
1365 // at this point we've created a contact and stored its address etc
1366 // all the payment processors expect the name and address to be in the
1367 // so we copy stuff over to first_name etc.
ccb02c2d 1368 $paymentParams = $formValues;
6a488035
TO
1369 $paymentParams['contactID'] = $this->_contributorContactID;
1370 //CRM-10377 if payment is by an alternate contact then we need to set that person
1371 // as the contact in the payment params
b11c92be 1372 if ($this->_contributorContactID != $this->_contactID) {
ccb02c2d 1373 if (!empty($formValues['soft_credit_type_id'])) {
133e2c99 1374 $softParams['contact_id'] = $params['contact_id'];
ccb02c2d 1375 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
6a488035
TO
1376 }
1377 }
ccb02c2d 1378 if (!empty($formValues['send_receipt'])) {
6a488035
TO
1379 $paymentParams['email'] = $this->_contributorEmail;
1380 }
1381
ba2f3f65 1382 // This is a candidate for shared beginPostProcess function.
64412b4e 1383 // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
ccb02c2d 1384 CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
6a488035 1385 // CRM-7137 -for recurring membership,
b44e3f84 1386 // we do need contribution and recurring records.
6a488035 1387 $result = NULL;
a7488080 1388 if (!empty($paymentParams['is_recur'])) {
8a7b41d1
EM
1389 $financialType = new CRM_Financial_DAO_FinancialType();
1390 $financialType->id = $params['financial_type_id'];
1391 $financialType->find(TRUE);
ccb02c2d 1392 $this->_params = $formValues;
18135422 1393
ba013eea 1394 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
6a488035 1395 $paymentParams,
3febe800 1396 NULL,
be2fb01f 1397 [
f6261e9d 1398 'contact_id' => $this->_contributorContactID,
9b581f1d 1399 'line_item' => $lineItem,
f6261e9d 1400 'is_test' => $isTest,
1401 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams),
ccb02c2d 1402 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $formValues),
3febe800 1403 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1404 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $paymentParams),
18135422 1405 'payment_instrument_id' => $paymentInstrumentID,
be2fb01f 1406 ],
8a7b41d1 1407 $financialType,
4bd318e0 1408 FALSE,
449f4c90 1409 $this->_bltID,
1410 TRUE
6a488035 1411 );
133e2c99 1412
1413 //create new soft-credit record, CRM-13981
00c1cd97
CW
1414 if ($softParams) {
1415 $softParams['contribution_id'] = $contribution->id;
1416 $softParams['currency'] = $contribution->currency;
1417 $softParams['amount'] = $contribution->total_amount;
1418 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1419 }
133e2c99 1420
a22bd791 1421 $paymentParams['contactID'] = $this->_contactID;
6a488035 1422 $paymentParams['contributionID'] = $contribution->id;
b11c92be 1423 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
6a488035
TO
1424 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1425 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
f57cb50c 1426 $params['contribution_id'] = $paymentParams['contributionID'];
6a488035 1427 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
6a488035 1428 }
c26225d2 1429 $paymentStatus = NULL;
6a488035
TO
1430
1431 if ($params['total_amount'] > 0.0) {
ab30e033 1432 $payment = $this->_paymentProcessor['object'];
06d062ce
EM
1433 try {
1434 $result = $payment->doPayment($paymentParams);
ccb02c2d 1435 $formValues = array_merge($formValues, $result);
c26225d2 1436 $paymentStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
ab30e033
EM
1437 // Assign amount to template if payment was successful.
1438 $this->assign('amount', $params['total_amount']);
6a488035 1439 }
31176a73 1440 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
06d062ce 1441 if (!empty($paymentParams['contributionID'])) {
ab30e033
EM
1442 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID,
1443 $e->getMessage());
06d062ce
EM
1444 }
1445 if (!empty($paymentParams['contributionRecurID'])) {
1446 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1447 }
1448
63dd64f2 1449 CRM_Core_Session::singleton()->setStatus($e->getMessage());
06d062ce 1450 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
31176a73 1451 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
06d062ce 1452 ));
6a488035 1453
06d062ce 1454 }
6a488035
TO
1455 }
1456
c26225d2
MWMC
1457 if ($paymentStatus !== 'Completed') {
1458 $params['status_id'] = $pendingMembershipStatusId;
7d193e45
LS
1459 $params['skipStatusCal'] = TRUE;
1460 // unset send-receipt option, since receipt will be sent when ipn is received.
ccb02c2d 1461 unset($formValues['send_receipt'], $formValues['send_receipt']);
7d193e45 1462 //as membership is pending set dates to null.
be2fb01f 1463 $memberDates = [
7d193e45
LS
1464 'join_date' => 'joinDate',
1465 'start_date' => 'startDate',
1466 'end_date' => 'endDate',
be2fb01f 1467 ];
2e8b13d1 1468 foreach ($memberDates as $dv) {
7d193e45
LS
1469 $$dv = NULL;
1470 foreach ($this->_memTypeSelected as $memType) {
1471 $membershipTypeValues[$memType][$dv] = NULL;
1472 }
1473 }
1474 }
09108d7d 1475 $now = date('YmdHis');
553842be 1476 $params['receive_date'] = date('Y-m-d H:i:s');
ccb02c2d 1477 $params['invoice_id'] = $formValues['invoiceID'];
6a488035 1478 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
be2fb01f 1479 [1 => $membershipType, 2 => $userName]
6a488035
TO
1480 );
1481 $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
1482 $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
6a488035 1483 $params['is_test'] = ($this->_mode == 'live') ? 0 : 1;
ccb02c2d 1484 if (!empty($formValues['send_receipt'])) {
6a488035
TO
1485 $params['receipt_date'] = $now;
1486 }
1487 else {
1488 $params['receipt_date'] = NULL;
1489 }
1490
ccb02c2d 1491 $this->set('params', $formValues);
6a488035
TO
1492 $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
1493 $this->assign('receive_date',
1494 CRM_Utils_Date::mysqlToIso($params['receive_date'])
1495 );
1496
1497 // required for creating membership for related contacts
1498 $params['action'] = $this->_action;
1499
1500 //create membership record.
1501 $count = 0;
1502 foreach ($this->_memTypeSelected as $memType) {
1503 if ($count &&
1504 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1505 ) {
1506 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1507 }
1508
1509 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
87d0f881 1510 //CRM-15366
396e62d8 1511 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1512 $membershipParams['soft_credit'] = $softParams;
1513 }
77623a96 1514 if (isset($result['fee_amount'])) {
1515 $membershipParams['fee_amount'] = $result['fee_amount'];
1516 }
8a7b41d1
EM
1517 // This is required to trigger the recording of the membership contribution in the
1518 // CRM_Member_BAO_Membership::Create function.
1519 // @todo stop setting this & 'teach' the create function to respond to something
1520 // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
1521 // process -
1522 // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
1523 $membershipParams['contribution_status_id'] = CRM_Utils_Array::value('payment_status_id', $result);
ccb02c2d 1524 if (!empty($paymentParams['is_recur'])) {
1525 // The earlier process created the line items (although we want to get rid of the earlier one in favour
1526 // of a single path!
1527 unset($membershipParams['lineItems']);
1528 }
18135422 1529 $membershipParams['payment_instrument_id'] = $paymentInstrumentID;
f57cb50c 1530 // @todo stop passing $ids (membership and userId only are set above)
6a488035 1531 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
3e228d81
PN
1532 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
1533 unset($params['lineItems']);
6a488035
TO
1534 $this->_membershipIDs[] = $membership->id;
1535 $createdMemberships[$memType] = $membership;
1536 $count++;
1537 }
1538
6a488035
TO
1539 }
1540 else {
1541 $params['action'] = $this->_action;
8cc574cf 1542 if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
6a488035
TO
1543
1544 // update membership as well as contribution object, CRM-4395
1545 $params['contribution_id'] = $this->_onlinePendingContributionId;
1546 $params['componentId'] = $params['id'];
1547 $params['componentName'] = 'contribute';
1548 $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
8cc574cf 1549 if (!empty($result) && !empty($params['contribution_id'])) {
be2fb01f 1550 $lineItem = [];
77dbdcbc 1551 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution_id']);
b11c92be 1552 $itemId = key($lineItems);
1553 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
4aa7d844 1554
6a488035
TO
1555 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1556 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1557 $lineItems[$itemId]['id'] = $itemId;
1558 $lineItem[$priceSetId] = $lineItems;
8aa7457a
EM
1559 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1560 $contributionBAO->id = $params['contribution_id'];
7524682e 1561 $contributionBAO->contact_id = $params['contact_id'];
8aa7457a
EM
1562 $contributionBAO->find();
1563 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
133e2c99 1564
1565 //create new soft-credit record, CRM-13981
00c1cd97
CW
1566 if ($softParams) {
1567 $softParams['contribution_id'] = $params['contribution_id'];
1568 while ($contributionBAO->fetch()) {
1569 $softParams['currency'] = $contributionBAO->currency;
1570 $softParams['amount'] = $contributionBAO->total_amount;
1571 }
1572 CRM_Contribute_BAO_ContributionSoft::add($softParams);
133e2c99 1573 }
6a488035
TO
1574 }
1575
1576 //carry updated membership object.
1577 $membership = new CRM_Member_DAO_Membership();
1578 $membership->id = $this->_id;
1579 $membership->find(TRUE);
1580
1581 $cancelled = TRUE;
1582 if ($membership->end_date) {
1583 //display end date w/ status message.
1584 $endDate = $membership->end_date;
1585
be2fb01f 1586 if (!in_array($membership->status_id, [
7ff60806
PN
1587 // CRM-15475
1588 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1589 array_search('Expired', CRM_Member_PseudoConstant::membershipStatus()),
be2fb01f 1590 ])
b11c92be 1591 ) {
6a488035
TO
1592 $cancelled = FALSE;
1593 }
1594 }
1595 // suppress form values in template.
1596 $this->assign('cancelled', $cancelled);
1597
6a488035
TO
1598 $createdMemberships[] = $membership;
1599 }
1600 else {
1601 $count = 0;
1602 foreach ($this->_memTypeSelected as $memType) {
8cc574cf 1603 if ($count && !empty($formValues['record_contribution']) &&
6a488035
TO
1604 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1605 ) {
1606 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1607 }
1608
553842be
SL
1609 // @todo figure out why recieve_date isn't being set right here.
1610 if (empty($params['receive_date'])) {
1611 $params['receive_date'] = date('Y-m-d H:i:s');
1612 }
6a488035 1613 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
a7488080 1614 if (!empty($formValues['int_amount'])) {
be2fb01f 1615 $init_amount = [];
b11c92be 1616 foreach ($formValues as $key => $value) {
1617 if (strstr($key, 'txt-price')) {
6a488035
TO
1618 $init_amount[$key] = $value;
1619 }
1620 }
1621 $membershipParams['init_amount'] = $init_amount;
1622 }
d80dbc14 1623
1624 if (!empty($softParams)) {
1625 $membershipParams['soft_credit'] = $softParams;
1626 }
f57cb50c 1627 // @todo stop passing $ids (membership and userId only are set above)
6a488035 1628 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
3e228d81 1629 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
d5b95619 1630 unset($params['lineItems']);
fd706baa
PN
1631 // skip line item creation for next interation since line item(s) are already created.
1632 $params['skipLineItem'] = TRUE;
6a488035
TO
1633
1634 $this->_membershipIDs[] = $membership->id;
1635 $createdMemberships[$memType] = $membership;
1636 $count++;
1637 }
1638 }
1639 }
1bd1288b 1640 $isRecur = CRM_Utils_Array::value('is_recur', $params);
1641 if (($this->_action & CRM_Core_Action::UPDATE)) {
1642 $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
1643 }
1644 elseif (($this->_action & CRM_Core_Action::ADD)) {
1645 $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1646 $isRecur, $calcDates));
1647 }
6a488035 1648
ccb02c2d 1649 if (!empty($lineItem[$this->_priceSetId])) {
aaffa79f 1650 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae 1651 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
01604562 1652 $taxAmount = FALSE;
79d001a2 1653 $totalTaxAmount = 0;
ccb02c2d 1654 foreach ($lineItem[$this->_priceSetId] as & $priceFieldOp) {
a7488080 1655 if (!empty($priceFieldOp['membership_type_id'])) {
3b85fc04
PN
1656 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
1657 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
6a488035
TO
1658 }
1659 else {
1660 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1661 }
03b412ae 1662 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
01604562 1663 $taxAmount = TRUE;
79d001a2
PB
1664 $totalTaxAmount += $priceFieldOp['tax_amount'];
1665 }
1666 }
03b412ae 1667 if ($invoicing) {
be2fb01f 1668 $dataArray = [];
ccb02c2d 1669 foreach ($lineItem[$this->_priceSetId] as $key => $value) {
03b412ae
PB
1670 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1671 if (isset($dataArray[$value['tax_rate']])) {
1672 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
0db6c3e1
TO
1673 }
1674 else {
03b412ae
PB
1675 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1676 }
0e81467c 1677 }
03b412ae 1678 }
01604562
PB
1679 if ($taxAmount) {
1680 $this->assign('totalTaxAmount', $totalTaxAmount);
a6e29c95 1681 // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
1682 $this->assign('taxTerm', $this->getSalesTaxTerm());
01604562 1683 }
03b412ae 1684 $this->assign('dataArray', $dataArray);
6a488035
TO
1685 }
1686 }
1687 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1688
1689 $receiptSend = FALSE;
7d193e45
LS
1690 $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
1691 $membershipIds = $this->_membershipIDs;
1692 if ($contributionId && !empty($membershipIds)) {
1693 $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(
1694 CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
1695 if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
aadd21c2 1696 $receiptSend = TRUE;
7d193e45
LS
1697 }
1698 }
6a488035 1699
7e0c2ccd 1700 $receiptSent = FALSE;
7d193e45 1701 if (!empty($formValues['send_receipt']) && $receiptSend) {
b11c92be 1702 $formValues['contact_id'] = $this->_contactID;
7d193e45 1703 $formValues['contribution_id'] = $contributionId;
186a737c
EM
1704 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1705 // handled in the receipt. But by setting one we avoid breaking templates for now
1706 // although at some point we should switch in the templates.
1707 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
6a488035 1708 // send email receipt
09108d7d 1709 $this->assignBillingName();
efc0e24a 1710 $mailSend = $this->emailMembershipReceipt($formValues, $membership);
7e0c2ccd 1711 $receiptSent = TRUE;
6a488035 1712 }
6a488035 1713
7865d848
EM
1714 // finally set membership id if already not set
1715 if (!$this->_id) {
1716 $this->_id = $membership->id;
6a488035 1717 }
6a488035 1718
268a84f2 1719 $this->updateContributionOnMembershipTypeChange($params, $membership);
5ce8b943 1720 if ($receiptSent && $mailSend) {
be2fb01f 1721 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail]));
5ce8b943 1722 }
1723
1724 CRM_Core_Session::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1725 $this->setStatusMessage($membership);
7865d848
EM
1726 }
1727
268a84f2 1728 /**
1729 * Update related contribution of a membership if update_contribution_on_membership_type_change
1730 * contribution setting is enabled and type is changed on edit
1731 *
1732 * @param array $inputParams
1733 * submitted form values
1734 * @param CRM_Member_DAO_Membership $membership
1735 * Updated membership object
1736 *
1737 */
1738 protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
1739 if (Civi::settings()->get('update_contribution_on_membership_type_change') &&
971e129b
SL
1740 // on update
1741 ($this->_action & CRM_Core_Action::UPDATE) &&
1742 // if ID is present
1743 $this->_id &&
1744 // if selected membership doesn't match with earlier membership
1745 !in_array($this->_memType, $this->_memTypeSelected)
268a84f2 1746 ) {
de6c59ca 1747 if (!empty($inputParams['is_recur'])) {
268a84f2 1748 CRM_Core_Session::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
1749 return;
1750 }
1751
1752 // fetch lineitems by updated membership ID
1753 $lineItems = CRM_Price_BAO_LineItem::getLineItems($membership->id, 'membership');
1754 // retrieve the related contribution ID
1755 $contributionID = CRM_Core_DAO::getFieldValue(
1756 'CRM_Member_DAO_MembershipPayment',
1757 $membership->id,
1758 'contribution_id',
1759 'membership_id'
1760 );
1761 // get price fields of chosen price-set
1762 $priceSetDetails = CRM_Utils_Array::value(
1763 $this->_priceSetId,
1764 CRM_Price_BAO_PriceSet::getSetDetail(
1765 $this->_priceSetId,
1766 TRUE,
1767 TRUE
1768 )
1769 );
1770
1771 // add price field information in $inputParams
1772 self::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id);
6dde7f04 1773
268a84f2 1774 // update related contribution and financial records
1775 CRM_Price_BAO_LineItem::changeFeeSelections(
1776 $inputParams,
1777 $membership->id,
1778 'membership',
1779 $contributionID,
1780 $priceSetDetails['fields'],
6dde7f04 1781 $lineItems
268a84f2 1782 );
1783 CRM_Core_Session::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1784 }
1785 }
1786
1787 /**
1788 * Add selected price field information in $formValues
1789 *
1790 * @param array $formValues
1791 * submitted form values
1792 * @param array $priceFields
1793 * Price fields of selected Priceset ID
1794 * @param int $membershipTypeID
1795 * Selected membership type ID
1796 *
1797 */
1798 public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
1799 foreach ($priceFields as $priceFieldID => $priceField) {
1800 if (isset($priceField['options']) && count($priceField['options'])) {
1801 foreach ($priceField['options'] as $option) {
1802 if ($option['membership_type_id'] == $membershipTypeID) {
1803 $formValues["price_{$priceFieldID}"] = $option['id'];
1804 break;
1805 }
1806 }
1807 }
1808 }
1809 }
971e129b 1810
5e56c7a5 1811 /**
1812 * Set context in session.
1813 */
7865d848 1814 protected function setUserContext() {
6a488035 1815 $buttonName = $this->controller->getButtonName();
7865d848
EM
1816 $session = CRM_Core_Session::singleton();
1817
6a488035
TO
1818 if ($this->_context == 'standalone') {
1819 if ($buttonName == $this->getButtonName('upload', 'new')) {
1820 $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add',
b11c92be 1821 'reset=1&action=add&context=standalone'
1822 ));
6a488035
TO
1823 }
1824 else {
1825 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
b11c92be 1826 "reset=1&cid={$this->_contactID}&selectedChild=member"
1827 ));
6a488035
TO
1828 }
1829 }
1830 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1831 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership',
b11c92be 1832 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1833 ));
6a488035
TO
1834 }
1835 }
1836
1837 /**
5e56c7a5 1838 * Get status message for updating membership.
1839 *
1840 * @param CRM_Member_BAO_Membership $membership
1841 * @param string $endDate
5e56c7a5 1842 *
7865d848 1843 * @return string
6a488035 1844 */
6d5b9c63 1845 protected function getStatusMessageForUpdate($membership, $endDate) {
5e56c7a5 1846 // End date can be modified by hooks, so if end date is set then use it.
7865d848 1847 $endDate = ($membership->end_date) ? $membership->end_date : $endDate;
6a488035 1848
be2fb01f 1849 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName]);
7865d848
EM
1850 if ($endDate && $endDate !== 'null') {
1851 $endDate = CRM_Utils_Date::customFormat($endDate);
be2fb01f 1852 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
6a488035 1853 }
7865d848
EM
1854 return $statusMsg;
1855 }
6a488035 1856
7865d848 1857 /**
5e56c7a5 1858 * Get status message for create action.
1859 *
1860 * @param string $endDate
5e56c7a5 1861 * @param array $membershipTypes
1862 * @param array $createdMemberships
5b217d3f 1863 * @param bool $isRecur
5e56c7a5 1864 * @param array $calcDates
5e56c7a5 1865 *
7865d848
EM
1866 * @return array|string
1867 */
6d5b9c63 1868 protected function getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1869 $isRecur, $calcDates) {
7865d848
EM
1870 // FIX ME: fix status messages
1871
be2fb01f 1872 $statusMsg = [];
7865d848 1873 foreach ($membershipTypes as $memType => $membershipType) {
be2fb01f 1874 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', [
7865d848
EM
1875 1 => $membershipType,
1876 2 => $this->_memberDisplayName,
be2fb01f 1877 ]);
6a488035 1878
7865d848
EM
1879 $membership = $createdMemberships[$memType];
1880 $memEndDate = ($membership->end_date) ? $membership->end_date : $endDate;
6a488035 1881
7865d848 1882 //get the end date from calculated dates.
5b217d3f 1883 if (!$memEndDate && !$isRecur) {
7865d848 1884 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
35fa23f8 1885 }
6a488035 1886
7865d848
EM
1887 if ($memEndDate && $memEndDate !== 'null') {
1888 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
be2fb01f 1889 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
b11c92be 1890 }
6a488035 1891 }
7865d848 1892 $statusMsg = implode('<br/>', $statusMsg);
7865d848 1893 return $statusMsg;
6a488035 1894 }
96025800 1895
5b217d3f 1896 /**
1897 * @param $membership
5b217d3f 1898 */
5ce8b943 1899 protected function setStatusMessage($membership) {
5b217d3f 1900 //CRM-15187
1901 // display message when membership type is changed
1902 if (($this->_action & CRM_Core_Action::UPDATE) && $this->_id && !in_array($this->_memType, $this->_memTypeSelected)) {
0fedbc88
PN
1903 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'membership');
1904 $maxID = max(array_keys($lineItem));
1905 $lineItem = $lineItem[$maxID];
1906 $membershipTypeDetails = $this->allMembershipTypeDetails[$membership->membership_type_id];
1907 if ($membershipTypeDetails['financial_type_id'] != $lineItem['financial_type_id']) {
1908 CRM_Core_Session::setStatus(
1909 ts('The financial types associated with the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its financial type.'),
1910 ts('Warning')
1911 );
1912 }
1913 if ($membershipTypeDetails['minimum_fee'] != $lineItem['line_total']) {
1914 CRM_Core_Session::setStatus(
1915 ts('The cost of the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its amount.'),
1916 ts('Warning')
1917 );
1918 }
5b217d3f 1919 }
1920 }
1921
50b85bf9 1922 /**
1923 * @return bool
1924 */
1925 protected function isUpdateToExistingRecurringMembership() {
1926 $isRecur = FALSE;
1927 if ($this->_action & CRM_Core_Action::UPDATE
59c798c9 1928 && CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
50b85bf9 1929 'contribution_recur_id')
59c798c9 1930 && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->getEntityId())) {
50b85bf9 1931
1932 $isRecur = TRUE;
1933 }
1934 return $isRecur;
1935 }
1936
829df55e 1937 /**
1938 * Send a receipt for the membership.
1939 *
1940 * @param array $formValues
efc0e24a 1941 * @param \CRM_Member_BAO_Membership $membership
1942 *
1943 * @return bool
829df55e 1944 */
1945 protected function emailMembershipReceipt($formValues, $membership) {
efc0e24a 1946 $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
1947
1948 return self::emailReceipt($this, $formValues, $membership, $customValues);
1949 }
1950
1951 /**
1952 * Filter the custom values from the input parameters (for display in the email).
1953 *
1954 * @todo figure out why the scary code this calls does & document.
1955 *
1956 * @param array $formValues
1957 * @param \CRM_Member_BAO_Membership $membership
1958 * @return array
1959 */
1960 protected function getCustomValuesForReceipt($formValues, $membership) {
1961 $customFields = $customValues = [];
1962 if (property_exists($this, '_groupTree')
1963 && !empty($this->_groupTree)
1964 ) {
1965 foreach ($this->_groupTree as $groupID => $group) {
1966 if ($groupID == 'info') {
1967 continue;
1968 }
1969 foreach ($group['fields'] as $k => $field) {
1970 $field['title'] = $field['label'];
1971 $customFields["custom_{$k}"] = $field;
1972 }
1973 }
1974 }
1975
1976 $members = [['member_id', '=', $membership->id, 0, 0]];
1977 // check whether its a test drive
1978 if ($this->_mode == 'test') {
1979 $members[] = ['member_test', '=', 1, 0, 0];
1980 }
1981
1982 CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1983 return $customValues;
829df55e 1984 }
1985
6a488035 1986}