APIv3 - Don't handle custom data already handled by BAO
[civicrm-core.git] / CRM / Member / Form / Membership.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 use Civi\Api4\ContributionRecur;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19
20 /**
21 * This class generates form components for offline membership form.
22 */
23 class CRM_Member_Form_Membership extends CRM_Member_Form {
24
25 /**
26 * IDs of relevant entities.
27 *
28 * @var array
29 */
30 protected $ids = [];
31
32 protected $_memType = NULL;
33
34 public $_mode;
35
36 public $_contributeMode = 'direct';
37
38 protected $_recurMembershipTypes;
39
40 protected $_memTypeSelected;
41
42 /**
43 * Display name of the member.
44 *
45 * @var string
46 */
47 protected $_memberDisplayName = NULL;
48
49 /**
50 * email of the person paying for the membership (used for receipts)
51 * @var string
52 */
53 protected $_memberEmail = NULL;
54
55 /**
56 * Contact ID of the member.
57 *
58 * @var int
59 */
60 public $_contactID = NULL;
61
62 /**
63 * Display name of the person paying for the membership (used for receipts)
64 *
65 * @var string
66 */
67 protected $_contributorDisplayName = NULL;
68
69 /**
70 * Email of the person paying for the membership (used for receipts).
71 *
72 * @var string
73 */
74 protected $_contributorEmail;
75
76 /**
77 * email of the person paying for the membership (used for receipts)
78 *
79 * @var int
80 */
81 protected $_contributorContactID = NULL;
82
83 /**
84 * ID of the person the receipt is to go to.
85 *
86 * @var int
87 */
88 protected $_receiptContactId = NULL;
89
90 /**
91 * Keep a class variable for ALL membership IDs so
92 * postProcess hook function can do something with it
93 *
94 * @var array
95 */
96 protected $_membershipIDs = [];
97
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
110 /**
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.
132 *
133 * We do this from the constructor in order to do a translation.
134 */
135 public function setDeleteMessage() {
136 $this->deleteMessage = '<span class="font-red bold">'
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>';
144 }
145
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
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
160 /**
161 * Get selected membership type from the form values.
162 *
163 * @param array $priceSet
164 * @param array $params
165 *
166 * @return array
167 * @throws \CRM_Core_Exception
168 */
169 public static function getSelectedMemberships($priceSet, $params) {
170 $memTypeSelected = [];
171 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSet);
172 if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
173 $memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
174 }
175 else {
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 }
182 return $memTypeSelected;
183 }
184
185 /**
186 * Extract price set fields and values from $params.
187 *
188 * @param array $params
189 * @param array $priceSet
190 *
191 * @return array
192 */
193 public static function getPriceFieldIDs($params, $priceSet) {
194 $priceFieldIDS = [];
195 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
196 foreach ($priceSet['fields'] as $fieldId => $field) {
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 }
203 }
204 }
205 elseif (!$field['is_enter_qty']) {
206 $priceFieldIDS[] = $params['price_' . $fieldId];
207 }
208 }
209 }
210 }
211 return $priceFieldIDS;
212 }
213
214 /**
215 * Form preProcess function.
216 *
217 * @throws \CRM_Core_Exception
218 * @throws \CiviCRM_API3_Exception
219 */
220 public function preProcess() {
221 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
222 $this->assign('formClass', 'membership');
223 parent::preProcess();
224
225 // get price set id.
226 $this->_priceSetId = $_GET['priceSetId'] ?? NULL;
227 $this->set('priceSetId', $this->_priceSetId);
228 $this->assign('priceSetId', $this->_priceSetId);
229
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)) {
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."));
235 }
236 }
237 $mems_by_org = [];
238 if ($this->_action & CRM_Core_Action::ADD) {
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
241 $contactMemberships = [];
242 $memParams = ['contact_id' => $this->_contactID];
243 CRM_Member_BAO_Membership::getValues($memParams, $contactMemberships, TRUE);
244 $cMemTypes = [];
245 foreach ($contactMemberships as $mem) {
246 $cMemTypes[] = $mem['membership_type_id'];
247 }
248 if (count($cMemTypes) > 0) {
249 foreach ($cMemTypes as $memTypeID) {
250 $memberorgs[$memTypeID] = CRM_Member_BAO_MembershipType::getMembershipType($memTypeID)['member_of_contact_id'];
251 }
252 foreach ($contactMemberships as $mem) {
253 $mem['member_of_contact_id'] = $memberorgs[$mem['membership_type_id']] ?? NULL;
254 if (!empty($mem['membership_end_date'])) {
255 $mem['membership_end_date'] = CRM_Utils_Date::customFormat($mem['membership_end_date']);
256 }
257 $mem['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
258 $mem['membership_type_id'],
259 'name', 'id'
260 );
261 $mem['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
262 $mem['status_id'],
263 'label', 'id'
264 );
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 );
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;
273 }
274 }
275 }
276 else {
277 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
278 $resources = CRM_Core_Resources::singleton();
279 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
280 $passthru = [
281 'typeorgs' => CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(),
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'),
284 ];
285 $resources->addSetting(['existingMems' => $passthru]);
286 }
287 }
288 $this->assign('existingContactMemberships', $mems_by_org);
289
290 if (!$this->_memType) {
291 $params = CRM_Utils_Request::exportValues();
292 if (!empty($params['membership_type_id'][1])) {
293 $this->_memType = $params['membership_type_id'][1];
294 }
295 }
296
297 // Add custom data to form
298 CRM_Custom_Form_CustomData::addToForm($this, $this->_memType);
299 $this->setPageTitle(ts('Membership'));
300 }
301
302 /**
303 * Set default values for the form.
304 */
305 public function setDefaultValues() {
306
307 if ($this->_priceSetId) {
308 return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults);
309 }
310
311 $defaults = parent::setDefaultValues();
312
313 //setting default join date and receive date
314 if ($this->_action == CRM_Core_Action::ADD) {
315 $defaults['receive_date'] = CRM_Utils_Time::date('Y-m-d H:i:s');
316 }
317
318 $defaults['num_terms'] = 1;
319
320 if (!empty($defaults['id'])) {
321 $contributionId = CRM_Core_DAO::singleValueQuery("
322 SELECT contribution_id
323 FROM civicrm_membership_payment
324 WHERE membership_id = $this->_id
325 ORDER BY contribution_id
326 DESC limit 1");
327
328 if ($contributionId) {
329 $defaults['record_contribution'] = $contributionId;
330 }
331 }
332 else {
333 if ($this->_contactID) {
334 $defaults['contact_id'] = $this->_contactID;
335 }
336 }
337
338 //set Soft Credit Type to Gift by default
339 $scTypes = CRM_Core_OptionGroup::values('soft_credit_type');
340 $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
341
342 //CRM-13420
343 if (empty($defaults['payment_instrument_id'])) {
344 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
345 }
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
355 $subscriptionCancelled = FALSE;
356 if (!empty($defaults['id'])) {
357 $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id);
358 }
359
360 $alreadyAutoRenew = FALSE;
361 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
362 $defaults['auto_renew'] = 1;
363 $alreadyAutoRenew = TRUE;
364 }
365 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
366
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']));
370
371 if ($this->_mode) {
372 $defaults = $this->getBillingDefaults($defaults);
373 }
374
375 //setting default join date if there is no join date
376 if (empty($defaults['join_date'])) {
377 $defaults['join_date'] = CRM_Utils_Time::date('Y-m-d');
378 }
379 $this->assign('endDate', $defaults['membership_end_date'] ?? NULL);
380
381 return $defaults;
382 }
383
384 /**
385 * Build the form object.
386 *
387 * @throws \CRM_Core_Exception
388 */
389 public function buildQuickForm() {
390
391 $this->buildQuickEntityForm();
392 $this->assign('currency_symbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
393 $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
394 // build price set form.
395 $buildPriceSet = FALSE;
396 if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
397 if (!empty($_POST['price_set_id'])) {
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);
407 CRM_Price_BAO_PriceSet::buildPriceSet($this);
408
409 $optionsMembershipTypes = [];
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
419 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
420
421 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
422 $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
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;
435 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
436 if (!empty($priceSets)) {
437 $buildPriceSet = TRUE;
438 }
439
440 if ($buildPriceSet) {
441 $this->add('select', 'price_set_id', ts('Choose price set'),
442 [
443 '' => ts('Choose price set'),
444 ] + $priceSets,
445 NULL, ['onchange' => "buildAmount( this.value );"]
446 );
447 }
448 $this->assign('hasPriceSets', $buildPriceSet);
449 }
450
451 if ($this->_action & CRM_Core_Action::DELETE) {
452 $this->addButtons([
453 [
454 'type' => 'next',
455 'name' => ts('Delete'),
456 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
457 'isDefault' => TRUE,
458 ],
459 [
460 'type' => 'cancel',
461 'name' => ts('Cancel'),
462 ],
463 ]);
464 return;
465 }
466
467 $contactField = $this->addEntityRef('contact_id', ts('Member'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
468 if ($this->_context !== 'standalone') {
469 $contactField->freeze();
470 }
471
472 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
473
474 // Throw status bounce when no Membership type or priceset is present
475 if (empty($this->allMembershipTypeDetails) && empty($priceSets)
476 ) {
477 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
478 }
479 // retrieve all memberships
480 $allMembershipInfo = [];
481 foreach ($this->allMembershipTypeDetails as $key => $values) {
482 if ($this->_mode && empty($values['minimum_fee'])) {
483 continue;
484 }
485 else {
486 $memberOfContactId = $values['member_of_contact_id'] ?? NULL;
487 if (empty($selMemTypeOrg[$memberOfContactId])) {
488 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
489 $memberOfContactId,
490 'display_name',
491 'id'
492 );
493
494 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
495 }
496 if (empty($selOrgMemType[$memberOfContactId][$key])) {
497 $selOrgMemType[$memberOfContactId][$key] = $values['name'] ?? NULL;
498 }
499 }
500 $totalAmount = $values['minimum_fee'] ?? NULL;
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
504 $allMembershipInfo[$key] = [
505 'financial_type_id' => $values['financial_type_id'] ?? NULL,
506 'total_amount' => CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($totalAmount),
507 'total_amount_numeric' => $totalAmount,
508 'auto_renew' => $values['auto_renew'] ?? NULL,
509 'tax_rate' => $values['tax_rate'],
510 'has_related' => isset($values['relationship_type_id']),
511 'max_related' => $values['max_related'] ?? NULL,
512 ];
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
529 $memTypeJs = [
530 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
531 ];
532
533 if (!empty($this->_recurPaymentProcessors)) {
534 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
535 }
536
537 $this->add('text', 'max_related', ts('Max related'),
538 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related')
539 );
540
541 $sel = &$this->addElement('hierselect',
542 'membership_type_id',
543 ts('Membership Organization and Type'),
544 $memTypeJs
545 );
546
547 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
548
549 if ($this->_action & CRM_Core_Action::ADD) {
550 $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
551 }
552
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'),
566 ['' => ts('- select -')] + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
567 );
568
569 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
570 CRM_Member_StatusOverrideTypes::getSelectOptions()
571 );
572
573 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => CRM_Utils_Time::date('Y-m-d'), 'time' => FALSE]);
574
575 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
576
577 $this->add('text', 'total_amount', ts('Amount'));
578 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
579
580 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
581
582 $this->add('select', 'payment_instrument_id',
583 ts('Payment Method'),
584 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
585 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
586 );
587 $this->add('text', 'trxn_id', ts('Transaction ID'));
588 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
589 'objectExists', [
590 'CRM_Contribute_DAO_Contribution',
591 $this->_id,
592 'trxn_id',
593 ]
594 );
595
596 $this->add('select', 'contribution_status_id',
597 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getPendingAndCompleteStatuses()
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 }
607 $this->add('select', 'financial_type_id',
608 ts('Financial Type'),
609 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action)
610 );
611
612 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
613
614 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
615 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
616
617 $this->addElement('checkbox',
618 'send_receipt',
619 ts('Send Confirmation and Receipt?'), NULL,
620 ['onclick' => "showEmailOptions()"]
621 );
622
623 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
624
625 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
626
627 // Retrieve the name and email of the contact - this will be the TO for receipt email
628 if ($this->_contactID) {
629 [$this->_memberDisplayName, $this->_memberEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
630 }
631 $this->assign('emailExists', $this->_memberEmail);
632 $this->assign('displayName', $this->_memberDisplayName);
633
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 }
639
640 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
641
642 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
643 $mailingInfo = Civi::settings()->get('mailing_backend');
644 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
645
646 parent::buildQuickForm();
647 }
648
649 /**
650 * Validation.
651 *
652 * @param array $params
653 * (ref.) an assoc array of name/value pairs.
654 *
655 * @param array $files
656 * @param CRM_Member_Form_Membership $self
657 *
658 * @return bool|array
659 * mixed true or array of errors
660 *
661 * @throws \CRM_Core_Exception
662 * @throws CiviCRM_API3_Exception
663 */
664 public static function formRule($params, $files, $self) {
665 $errors = [];
666
667 $priceSetId = $self->getPriceSetID($params);
668 $priceSetDetails = $self->getPriceSetDetails($params);
669
670 $selectedMemberships = self::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
671
672 if (!empty($params['price_set_id'])) {
673 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
674
675 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
676
677 if (!empty($priceFieldIDS)) {
678 $ids = implode(',', $priceFieldIDS);
679
680 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
681 foreach ($count as $occurrence) {
682 if ($occurrence > 1) {
683 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
684 }
685 }
686 }
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 }
694 }
695 else {
696 if (empty($params['membership_type_id'][1])) {
697 $errors['membership_type_id'] = ts('Please select a membership type.');
698 }
699 $numterms = $params['num_terms'] ?? NULL;
700 if ($numterms && intval($numterms) != $numterms) {
701 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
702 }
703
704 if (($self->_mode || isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
705 $errors['financial_type_id'] = ts('Please enter the financial Type.');
706 }
707 }
708
709 if (!empty($errors) && (count($selectedMemberships) > 1)) {
710 $memberOfContacts = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($selectedMemberships);
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
719 if (!empty($errors)) {
720 return $errors;
721 }
722
723 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
724 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
725 }
726
727 if (!empty($params['is_different_contribution_contact'])) {
728 if (empty($params['soft_credit_type_id'])) {
729 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
730 }
731 if (empty($params['soft_credit_contact_id'])) {
732 $errors['soft_credit_contact_id'] = ts('Please select a contact');
733 }
734 }
735
736 if (!empty($params['payment_processor_id'])) {
737 // validate payment instrument (e.g. credit card number)
738 CRM_Core_Payment_Form::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
739 }
740
741 $joinDate = NULL;
742 if (!empty($params['join_date'])) {
743
744 $joinDate = CRM_Utils_Date::processDate($params['join_date']);
745
746 foreach ($selectedMemberships as $memType) {
747 $startDate = NULL;
748 if (!empty($params['start_date'])) {
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
754 $endDate = NULL;
755 if (!empty($params['end_date'])) {
756 $endDate = CRM_Utils_Date::processDate($params['end_date']);
757 }
758
759 $membershipDetails = CRM_Member_BAO_MembershipType::getMembershipType($memType);
760 if ($startDate && CRM_Utils_Array::value('period_type', $membershipDetails) === 'rolling') {
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) {
767 if ($membershipDetails['duration_unit'] === 'lifetime') {
768 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
769 // process to update status based on end-date. The user must change the status now.
770 $result = civicrm_api3('MembershipStatus', 'get', [
771 'sequential' => 1,
772 'is_current_member' => 0,
773 ]);
774 $tmp_statuses = $result['values'];
775 $status_ids = [];
776 foreach ($tmp_statuses as $cur_stat) {
777 $status_ids[] = $cur_stat['id'];
778 }
779
780 if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
781 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
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"');
786 }
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
798 // Default values for start and end dates if not supplied on the form.
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.
817 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
818 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
819 $endDate,
820 $joinDate,
821 'now',
822 TRUE,
823 $memType,
824 $params
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.');
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]);
830 if (!$self->_mode) {
831 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
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
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 }
850 }
851
852 //total amount condition arise when membership type having no
853 //minimum fee
854 if (isset($params['record_contribution'])) {
855 if (CRM_Utils_System::isNull($params['total_amount'])) {
856 $errors['total_amount'] = ts('Please enter the contribution.');
857 }
858 }
859
860 return empty($errors) ? TRUE : $errors;
861 }
862
863 /**
864 * Process the form submission.
865 *
866 * @throws \CRM_Core_Exception
867 * @throws \CiviCRM_API3_Exception
868 */
869 public function postProcess() {
870 if ($this->_action & CRM_Core_Action::DELETE) {
871 CRM_Member_BAO_Membership::del($this->_id);
872 return;
873 }
874 // get the submitted form values.
875 $this->_params = $this->controller->exportValues($this->_name);
876 $this->prepareStatusOverrideValues();
877
878 $this->submit();
879
880 $this->setUserContext();
881 }
882
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() {
896 if (!CRM_Member_StatusOverrideTypes::isUntilDate(CRM_Utils_Array::value('is_override', $this->_params))) {
897 $this->_params['status_override_end_date'] = '';
898 }
899 }
900
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() {
907 $this->_params['is_override'] = CRM_Member_StatusOverrideTypes::isOverridden($this->_params['is_override'] ?? CRM_Member_StatusOverrideTypes::NO);
908 }
909
910 /**
911 * Send email receipt.
912 *
913 * @param CRM_Core_Form $form
914 * Form object.
915 * @param array $formValues
916 *
917 * @return bool
918 * true if mail was sent successfully
919 * @throws \CRM_Core_Exception
920 * @throws \CiviCRM_API3_Exception
921 *
922 * @deprecated
923 * This function was shared with Batch_Entry which had limited overlap
924 * & needs rationalising.
925 *
926 */
927 protected function emailReceipt($form, &$formValues) {
928 $membership = $this->getMembership();
929 // retrieve 'from email id' for acknowledgement
930 $receiptFrom = $formValues['from_email_address'] ?? NULL;
931
932 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
933 if (!empty($formValues['payment_instrument_id'])) {
934 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
935 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
936 }
937
938 $form->assign('module', 'Membership');
939
940 if (!empty($formValues['contribution_id'])) {
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);
945 }
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 }
958 $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
959 $form->assign('formValues', $formValues);
960
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']));
964 }
965 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership['membership_type_id']));
966
967 if ((empty($form->_contributorDisplayName) || empty($form->_contributorEmail))) {
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
973 [$form->_contributorDisplayName, $form->_contributorEmail]
974 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
975 if (empty($form->_receiptContactId)) {
976 $form->_receiptContactId = $formValues['contact_id'];
977 }
978 }
979
980 CRM_Core_BAO_MessageTemplate::sendTemplate(
981 [
982 'workflow' => 'membership_offline_receipt',
983 'from' => $receiptFrom,
984 'toName' => $form->_contributorDisplayName,
985 'toEmail' => $form->_contributorEmail,
986 'PDFFilename' => ts('receipt') . '.pdf',
987 'isEmailPdf' => Civi::settings()->get('invoice_is_email_pdf'),
988 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
989 'modelProps' => [
990 'receiptText' => $this->getSubmittedValue('receipt_text'),
991 'contributionId' => $formValues['contribution_id'],
992 'contactId' => $form->_receiptContactId,
993 'membershipId' => $this->getMembershipID(),
994 ],
995 ]
996 );
997
998 return TRUE;
999 }
1000
1001 /**
1002 * Submit function.
1003 *
1004 * This is also accessed by unit tests.
1005 *
1006 * @throws \CRM_Core_Exception
1007 * @throws \CiviCRM_API3_Exception
1008 * @throws \API_Exception
1009 */
1010 public function submit(): void {
1011 $this->storeContactFields($this->_params);
1012 $this->beginPostProcess();
1013
1014 $params = $softParams = $ids = [];
1015
1016 $mailSend = FALSE;
1017 $this->processBillingAddress();
1018 $formValues = $this->_params;
1019 $formValues = $this->setPriceSetParameters($formValues);
1020
1021 if ($this->_id) {
1022 $ids['membership'] = $params['id'] = $this->_id;
1023 }
1024
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);
1029
1030 $this->_memTypeSelected = self::getSelectedMemberships(
1031 $this->_priceSet,
1032 $formValues
1033 );
1034 $formValues['financial_type_id'] = $this->getFinancialTypeID();
1035
1036 $isQuickConfig = $this->_priceSet['is_quick_config'];
1037
1038 $lineItem = [$this->order->getPriceSetID() => $this->order->getLineItems()];
1039
1040 $params['tax_amount'] = $this->order->getTotalTaxAmount();
1041 $params['total_amount'] = $this->order->getTotalAmount();
1042 $params['contact_id'] = $this->_contactID;
1043
1044 $params = array_merge($params, $this->getFormMembershipParams());
1045 $membershipTypeValues = $this->getMembershipParameters();
1046
1047 //CRM-13981, allow different person as a soft-contributor of chosen type
1048 if ($this->_contributorContactID != $this->_contactID) {
1049 $params['contribution_contact_id'] = $this->_contributorContactID;
1050 if (!empty($formValues['soft_credit_type_id'])) {
1051 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1052 $softParams['contact_id'] = $this->_contactID;
1053 }
1054 }
1055
1056 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1057
1058 if (!empty($formValues['record_contribution'])) {
1059 $recordContribution = [
1060 'total_amount',
1061 'payment_instrument_id',
1062 'trxn_id',
1063 'contribution_status_id',
1064 'check_number',
1065 'receive_date',
1066 'card_type_id',
1067 'pan_truncation',
1068 ];
1069
1070 foreach ($recordContribution as $f) {
1071 $params[$f] = $formValues[$f] ?? NULL;
1072 }
1073 $params['financial_type_id'] = $this->getFinancialTypeID();
1074 $params['campaign_id'] = $this->getSubmittedValue('campaign_id');
1075
1076 $params['contribution_source'] = $this->getContributionSource();
1077
1078 $completedContributionStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1079 if (empty($params['is_override']) &&
1080 CRM_Utils_Array::value('contribution_status_id', $params) != $completedContributionStatusId
1081 ) {
1082 $params['status_id'] = $pendingMembershipStatusId;
1083 $params['skipStatusCal'] = TRUE;
1084 $params['is_pay_later'] = 1;
1085 $this->assign('is_pay_later', 1);
1086 }
1087
1088 if ($this->getSubmittedValue('send_receipt')) {
1089 $params['receipt_date'] = $formValues['receive_date'] ?? NULL;
1090 }
1091
1092 }
1093
1094 // process line items, until no previous line items.
1095 if (!empty($lineItem)) {
1096 $params['lineItems'] = $lineItem;
1097 $params['processPriceSet'] = TRUE;
1098 }
1099
1100 if ($this->_mode) {
1101 $params['total_amount'] = $this->order->getTotalAmount();
1102 $params['financial_type_id'] = $this->getFinancialTypeID();
1103
1104 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
1105 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->getPaymentProcessorID();
1106 $params['register_date'] = CRM_Utils_Time::date('YmdHis');
1107
1108 // add all the additional payment params we need
1109 $formValues['amount'] = $this->order->getTotalAmount();
1110 $formValues['currencyID'] = $this->getCurrency();
1111 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1112 $formValues['invoiceID'] = $this->getInvoiceID();
1113 $formValues['financial_type_id'] = $this->getFinancialTypeID();
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.
1118 $paymentParams = $formValues;
1119 $paymentParams['frequency_unit'] = $this->getFrequencyUnit();
1120 $paymentParams['frequency_interval'] = $this->getFrequencyInterval();
1121
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
1125 if ($this->_contributorContactID != $this->_contactID) {
1126 if (!empty($formValues['soft_credit_type_id'])) {
1127 $softParams['contact_id'] = $params['contact_id'];
1128 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1129 }
1130 }
1131 if ($this->getSubmittedValue('send_receipt')) {
1132 $paymentParams['email'] = $this->_contributorEmail;
1133 }
1134
1135 // This is a candidate for shared beginPostProcess function.
1136 // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
1137 CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
1138 // CRM-7137 -for recurring membership,
1139 // we do need contribution and recurring records.
1140 $result = NULL;
1141
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);
1171 }
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
1181 $paymentStatus = NULL;
1182
1183 if ($this->order->getTotalAmount() > 0.0) {
1184 $payment = $this->_paymentProcessor['object'];
1185 try {
1186 $result = $payment->doPayment($paymentParams);
1187 $formValues = array_merge($formValues, $result);
1188 $paymentStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
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,
1197 'card_type_id' => $this->getCardTypeID(),
1198 'pan_truncation' => $this->getPanTruncation(),
1199 ]);
1200 }
1201 }
1202 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
1203 if (!empty($paymentParams['contributionID'])) {
1204 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID,
1205 $e->getMessage());
1206 }
1207 if ($this->getContributionRecurID()) {
1208 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($this->getContributionRecurID());
1209 }
1210
1211 CRM_Core_Session::singleton()->setStatus($e->getMessage());
1212 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
1213 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
1214 ));
1215
1216 }
1217 }
1218
1219 if ($paymentStatus !== 'Completed') {
1220 $params['status_id'] = $pendingMembershipStatusId;
1221 $params['skipStatusCal'] = TRUE;
1222 //as membership is pending set dates to null.
1223 foreach ($this->_memTypeSelected as $memType) {
1224 $membershipTypeValues[$memType]['joinDate'] = NULL;
1225 $membershipTypeValues[$memType]['startDate'] = NULL;
1226 $membershipTypeValues[$memType]['endDate'] = NULL;
1227 }
1228 $startDate = NULL;
1229 }
1230 $now = CRM_Utils_Time::date('YmdHis');
1231 $params['receive_date'] = CRM_Utils_Time::date('Y-m-d H:i:s');
1232 $params['invoice_id'] = $this->getInvoiceID();
1233 $params['contribution_source'] = $this->getContributionSource();
1234 $params['source'] = $formValues['source'] ?: $params['contribution_source'];
1235 $params['trxn_id'] = $result['trxn_id'] ?? NULL;
1236 $params['is_test'] = $this->isTest();
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.
1241 $params['receipt_date'] = $now;
1242 }
1243
1244 $this->set('params', $formValues);
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) {
1256 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1257 if (isset($result['fee_amount'])) {
1258 $membershipParams['fee_amount'] = $result['fee_amount'];
1259 }
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
1266 $membershipParams['contribution_status_id'] = $result['payment_status_id'] ?? NULL;
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']);
1270 $membershipParams['payment_instrument_id'] = $this->getPaymentInstrumentID();
1271 // @todo stop passing $ids (membership and userId only are set above)
1272 $params['contribution'] = $membershipParams['contribution'] ?? NULL;
1273 unset($params['lineItems']);
1274 }
1275
1276 }
1277 else {
1278 $params['action'] = $this->_action;
1279 foreach ($lineItem[$this->_priceSetId] as $id => $lineItemValues) {
1280 if (empty($lineItemValues['membership_type_id'])) {
1281 continue;
1282 }
1283
1284 // @todo figure out why recieve_date isn't being set right here.
1285 if (empty($params['receive_date'])) {
1286 $params['receive_date'] = CRM_Utils_Time::date('Y-m-d H:i:s');
1287 }
1288 $membershipParams = array_merge($params, $membershipTypeValues[$lineItemValues['membership_type_id']]);
1289
1290 if (!empty($softParams)) {
1291 $params['soft_credit'] = $softParams;
1292 }
1293 unset($membershipParams['contribution_status_id']);
1294 $membershipParams['skipLineItem'] = TRUE;
1295 unset($membershipParams['lineItems']);
1296 // @todo stop passing $ids (membership and userId only are set above)
1297 $this->setMembership((array) CRM_Member_BAO_Membership::create($membershipParams, $ids));
1298 $lineItem[$this->_priceSetId][$id]['entity_id'] = $this->membership['id'];
1299 $lineItem[$this->_priceSetId][$id]['entity_table'] = 'civicrm_membership';
1300
1301 }
1302 $params['lineItems'] = $lineItem;
1303 if (!empty($formValues['record_contribution'])) {
1304 CRM_Member_BAO_Membership::recordMembershipContribution($params);
1305 }
1306 }
1307
1308 $this->updateContributionOnMembershipTypeChange($params);
1309
1310 if (($this->_action & CRM_Core_Action::UPDATE)) {
1311 $this->addStatusMessage($this->getStatusMessageForUpdate());
1312 }
1313 elseif (($this->_action & CRM_Core_Action::ADD)) {
1314 $this->addStatusMessage($this->getStatusMessageForCreate());
1315 }
1316
1317 // This would always be true as we always add price set id into both
1318 // quick config & non quick config price sets.
1319 if (!empty($lineItem[$this->_priceSetId])) {
1320 foreach ($lineItem[$this->_priceSetId] as & $priceFieldOp) {
1321 if (!empty($priceFieldOp['membership_type_id'])) {
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']) : '-';
1324 }
1325 else {
1326 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1327 }
1328 }
1329 if (Civi::settings()->get('invoicing')) {
1330 $dataArray = [];
1331 foreach ($lineItem[$this->_priceSetId] as $key => $value) {
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);
1335 }
1336 else {
1337 $dataArray[$value['tax_rate']] = $value['tax_amount'] ?? NULL;
1338 }
1339 }
1340 }
1341
1342 $this->assign('dataArray', $dataArray);
1343 }
1344 }
1345 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1346
1347 $receiptSend = FALSE;
1348 $contributionId = $this->ids['Contribution'] ?? CRM_Member_BAO_Membership::getMembershipContributionId($this->getMembershipID());
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);
1353 if ($contributionDetails[$this->getMembershipID()]['contribution_status'] === 'Completed') {
1354 $receiptSend = TRUE;
1355 }
1356 }
1357
1358 $receiptSent = FALSE;
1359 if ($this->getSubmittedValue('send_receipt') && $receiptSend) {
1360 $formValues['contact_id'] = $this->_contactID;
1361 $formValues['contribution_id'] = $contributionId;
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.
1365 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1366 // send email receipt
1367 $this->assignBillingName();
1368 $mailSend = $this->emailMembershipReceipt($formValues);
1369 $receiptSent = TRUE;
1370 }
1371
1372 if ($receiptSent && $mailSend) {
1373 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail]));
1374 }
1375
1376 CRM_Core_Session::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1377 $this->setStatusMessage();
1378
1379 // finally set membership id if already not set
1380 if (!$this->_id) {
1381 $this->_id = $this->getMembershipID();
1382 }
1383 }
1384
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
1391 *
1392 * @throws \CRM_Core_Exception
1393 * @throws \CiviCRM_API3_Exception
1394 */
1395 protected function updateContributionOnMembershipTypeChange($inputParams) {
1396 if (Civi::settings()->get('update_contribution_on_membership_type_change') &&
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)
1403 ) {
1404 if ($this->isCreateRecurringContribution()) {
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
1410 $lineItems = CRM_Price_BAO_LineItem::getLineItems($this->getMembershipID(), 'membership');
1411 // retrieve the related contribution ID
1412 $contributionID = CRM_Core_DAO::getFieldValue(
1413 'CRM_Member_DAO_MembershipPayment',
1414 $this->getMembershipID(),
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
1429 self::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $this->getMembership()['membership_type_id']);
1430
1431 // update related contribution and financial records
1432 CRM_Price_BAO_LineItem::changeFeeSelections(
1433 $inputParams,
1434 $this->getMembershipID(),
1435 'membership',
1436 $contributionID,
1437 $priceSetDetails['fields'],
1438 $lineItems
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 }
1467
1468 /**
1469 * Set context in session.
1470 */
1471 protected function setUserContext() {
1472 $buttonName = $this->controller->getButtonName();
1473 $session = CRM_Core_Session::singleton();
1474
1475 if ($buttonName == $this->getButtonName('upload', 'new')) {
1476 if ($this->_context === 'standalone') {
1477 $url = CRM_Utils_System::url('civicrm/member/add',
1478 'reset=1&action=add&context=standalone'
1479 );
1480 }
1481 else {
1482 $url = CRM_Utils_System::url('civicrm/contact/view/membership',
1483 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1484 );
1485 }
1486 }
1487 else {
1488 $url = CRM_Utils_System::url('civicrm/contact/view',
1489 "reset=1&cid={$this->_contactID}&selectedChild=member"
1490 );
1491 }
1492 $session->replaceUserContext($url);
1493 }
1494
1495 /**
1496 * Get status message for updating membership.
1497 *
1498 * @return string
1499 * @throws \CiviCRM_API3_Exception
1500 */
1501 protected function getStatusMessageForUpdate(): string {
1502 foreach ($this->getCreatedMemberships() as $membership) {
1503 $endDate = $membership['end_date'] ?? NULL;
1504 }
1505 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName]);
1506 if ($endDate) {
1507 $endDate = CRM_Utils_Date::customFormat($endDate);
1508 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
1509 }
1510 return $statusMsg;
1511 }
1512
1513 /**
1514 * Get status message for create action.
1515 *
1516 * @return string
1517 * @throws \CiviCRM_API3_Exception
1518 */
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'],
1523 2 => $this->_memberDisplayName,
1524 ]);
1525
1526 $memEndDate = $membership['end_date'] ?? NULL;
1527
1528 if ($memEndDate) {
1529 $memEndDate = CRM_Utils_Date::formatDateOnlyLong($memEndDate);
1530 $statusMsg[$membership['membership_type_id']] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
1531 }
1532 }
1533 $statusMsg = implode('<br/>', $statusMsg);
1534 return $statusMsg ?? '';
1535 }
1536
1537 /**
1538 */
1539 protected function setStatusMessage() {
1540 //CRM-15187
1541 // display message when membership type is changed
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');
1544 $maxID = max(array_keys($lineItem));
1545 $lineItem = $lineItem[$maxID];
1546 $membershipTypeDetails = $this->allMembershipTypeDetails[$this->getMembership()['membership_type_id']];
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 }
1559 }
1560 }
1561
1562 /**
1563 * @return bool
1564 * @throws \CRM_Core_Exception
1565 */
1566 protected function isUpdateToExistingRecurringMembership() {
1567 $isRecur = FALSE;
1568 if ($this->_action & CRM_Core_Action::UPDATE
1569 && CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
1570 'contribution_recur_id')
1571 && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->getEntityId())) {
1572
1573 $isRecur = TRUE;
1574 }
1575 return $isRecur;
1576 }
1577
1578 /**
1579 * Send a receipt for the membership.
1580 *
1581 * @param array $formValues
1582 *
1583 * @return bool
1584 * @throws \CRM_Core_Exception
1585 * @throws \CiviCRM_API3_Exception
1586 */
1587 protected function emailMembershipReceipt($formValues) {
1588 $customValues = $this->getCustomValuesForReceipt($formValues);
1589 $this->assign('customValues', $customValues);
1590 $this->assign('total_amount', $this->order->getTotalAmount());
1591 $this->assign('totalTaxAmount', $this->order->getTotalTaxAmount());
1592 $this->assign('taxTerm', $this->getSalesTaxTerm());
1593
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 }
1606 //insert financial type name in receipt.
1607 $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1608 $this->getFinancialTypeID()
1609 );
1610 return $this->emailReceipt($this, $formValues);
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
1619 * @return array
1620 */
1621 protected function getCustomValuesForReceipt($formValues): array {
1622 $customFields = $customValues = [];
1623 if (property_exists($this, '_groupTree')
1624 && !empty($this->_groupTree)
1625 ) {
1626 foreach ($this->_groupTree as $groupID => $group) {
1627 if ($groupID === 'info') {
1628 continue;
1629 }
1630 foreach ($group['fields'] as $k => $field) {
1631 $field['title'] = $field['label'];
1632 $customFields["custom_{$k}"] = $field;
1633 }
1634 }
1635 }
1636
1637 $members = [['member_id', '=', $this->getMembershipID(), 0, 0]];
1638 // check whether its a test drive
1639 if ($this->_mode === 'test') {
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;
1645 }
1646
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
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
1678 /**
1679 * Create the recurring contribution record if the form submission requires it.
1680 *
1681 * This function was copied from another form & needs cleanup.
1682 *
1683 * @throws \API_Exception
1684 * @throws \CiviCRM_API3_Exception
1685 */
1686 protected function createRecurringContribution(): void {
1687 if (!$this->isCreateRecurringContribution()) {
1688 $this->ids['ContributionRecur'] = NULL;
1689 return;
1690 }
1691 $recurParams = ['contact_id' => $this->getContributionContactID()];
1692 $recurParams['amount'] = $this->order->getTotalAmount();
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();
1697 $recurParams['financial_type_id'] = $this->getFinancialTypeID();
1698 $recurParams['currency'] = $this->getCurrency();
1699 $recurParams['payment_instrument_id'] = $this->getPaymentInstrumentID();
1700 $recurParams['is_test'] = $this->isTest();
1701 $recurParams['create_date'] = $recurParams['modified_date'] = CRM_Utils_Time::date('YmdHis');
1702 $recurParams['start_date'] = $this->getReceiveDate();
1703 $recurParams['invoice_id'] = $this->getInvoiceID();
1704 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1705 $recurParams['payment_processor_id'] = $this->getPaymentProcessorID();
1706 $recurParams['is_email_receipt'] = (bool) $this->getSubmittedValue('send_receipt');
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
1709 $recurParams['trxn_id'] = $this->getInvoiceID();
1710 $recurParams['campaign_id'] = $this->getSubmittedValue('campaign_id');
1711 $this->ids['ContributionRecur'] = ContributionRecur::create(FALSE)->setValues($recurParams)->execute()->first()['id'];
1712 }
1713
1714 /**
1715 * Is the form being submitted in test mode.
1716 *
1717 * @return bool
1718 */
1719 protected function isTest(): bool {
1720 return ($this->_mode === 'test') ? TRUE : FALSE;
1721 }
1722
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
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
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
1782 * @throws \API_Exception
1783 * @throws \CiviCRM_API3_Exception
1784 */
1785 protected function getFormMembershipParams(): array {
1786 $submittedValues = $this->controller->exportValues($this->_name);
1787 return [
1788 'status_id' => $this->getSubmittedValue('status_id'),
1789 'source' => $this->getSubmittedValue('source') ?? $this->getContributionSource(),
1790 'contact_id' => $this->getMembershipContactID(),
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'),
1802 'contribution_recur_id' => $this->getContributionRecurID(),
1803 ];
1804 }
1805
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
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
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
1834 /**
1835 * Get parameters for membership create for all memberships to be created.
1836 *
1837 * @return array
1838 * @throws \CiviCRM_API3_Exception
1839 */
1840 protected function getMembershipParameters(): array {
1841 $membershipTypeValues = [];
1842 foreach ($this->_memTypeSelected as $memType) {
1843 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
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 }
1849 }
1850
1851 foreach ($this->order->getMembershipLineItems() as $membershipLineItem) {
1852 $memTypeNumTerms = $this->getSubmittedValue('num_terms') ?: $membershipLineItem['membership_num_terms'];
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
1859 );
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'];
1863 }
1864
1865 return $membershipTypeValues;
1866 }
1867
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
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
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)) {
1924 $this->membership = civicrm_api3('Membership', 'get', ['id' => $this->getMembershipID()])['values'][$this->getMembershipID()];
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
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
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
1988 }