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