3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
12 use Civi\Api4\ContributionRecur
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * This class generates form components for offline membership form.
23 class CRM_Member_Form_Membership
extends CRM_Member_Form
{
26 * IDs of relevant entities.
32 protected $_memType = NULL;
36 public $_contributeMode = 'direct';
38 protected $_recurMembershipTypes;
40 protected $_memTypeSelected;
43 * Display name of the member.
47 protected $_memberDisplayName = NULL;
50 * email of the person paying for the membership (used for receipts)
53 protected $_memberEmail = NULL;
56 * Contact ID of the member.
60 public $_contactID = NULL;
63 * Display name of the person paying for the membership (used for receipts)
67 protected $_contributorDisplayName = NULL;
70 * Email of the person paying for the membership (used for receipts).
74 protected $_contributorEmail;
77 * email of the person paying for the membership (used for receipts)
81 protected $_contributorContactID = NULL;
84 * ID of the person the receipt is to go to.
88 protected $_receiptContactId = NULL;
91 * Keep a class variable for ALL membership IDs so
92 * postProcess hook function can do something with it
96 protected $_membershipIDs = [];
99 * Membership created or edited on this form.
101 * If a price set creates multiple this will be the last one created.
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.
108 protected $membership = [];
111 * Set entity fields to be assigned to the form.
113 protected function setEntityFields() {
114 $this->entityFields
= [
116 'name' => 'join_date',
117 'description' => ts('Member Since'),
120 'name' => 'start_date',
121 'description' => ts('Start Date'),
124 'name' => 'end_date',
125 'description' => ts('End Date'),
131 * Set the delete message.
133 * We do this from the constructor in order to do a translation.
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.')
139 . ts('This action cannot be undone.')
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.')
143 . ts("Click 'Delete' if you want to continue.") . '</p>';
147 * Overriding this entity trait function as not yet tested.
149 * We continue to rely on legacy handling.
151 public function addCustomDataToForm() {}
154 * Overriding this entity trait function as not yet tested.
156 * We continue to rely on legacy handling.
158 public function addFormButtons() {}
161 * Get selected membership type from the form values.
163 * @param array $priceSet
164 * @param array $params
167 * @throws \CRM_Core_Exception
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]];
176 foreach ($priceFieldIDS as $priceFieldId) {
177 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
178 $memTypeSelected[$id] = $id;
182 return $memTypeSelected;
186 * Extract price set fields and values from $params.
188 * @param array $params
189 * @param array $priceSet
193 public static function getPriceFieldIDs($params, $priceSet) {
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) {
201 $priceFieldIDS[] = $priceFldVal;
205 elseif (!$field['is_enter_qty']) {
206 $priceFieldIDS[] = $params['price_' . $fieldId];
211 return $priceFieldIDS;
215 * Form preProcess function.
217 * @throws \CRM_Core_Exception
218 * @throws \CiviCRM_API3_Exception
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();
226 $this->_priceSetId
= $_GET['priceSetId'] ??
NULL;
227 $this->set('priceSetId', $this->_priceSetId
);
228 $this->assign('priceSetId', $this->_priceSetId
);
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."));
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);
245 foreach ($contactMemberships as $mem) {
246 $cMemTypes[] = $mem['membership_type_id'];
248 if (count($cMemTypes) > 0) {
249 foreach ($cMemTypes as $memTypeID) {
250 $memberorgs[$memTypeID] = CRM_Member_BAO_MembershipType
::getMembershipType($memTypeID)['member_of_contact_id'];
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']);
257 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
258 $mem['membership_type_id'],
261 $mem['membership_status'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
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' : '')
269 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
270 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
272 $mems_by_org[$mem['member_of_contact_id']] = $mem;
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');
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'),
285 $resources->addSetting(['existingMems' => $passthru]);
288 $this->assign('existingContactMemberships', $mems_by_org);
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];
297 // Add custom data to form
298 CRM_Custom_Form_CustomData
::addToForm($this, $this->_memType
);
299 $this->setPageTitle(ts('Membership'));
303 * Set default values for the form.
305 public function setDefaultValues() {
307 if ($this->_priceSetId
) {
308 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
311 $defaults = parent
::setDefaultValues();
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');
318 $defaults['num_terms'] = 1;
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
328 if ($contributionId) {
329 $defaults['record_contribution'] = $contributionId;
333 if ($this->_contactID
) {
334 $defaults['contact_id'] = $this->_contactID
;
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));
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'));
347 // User must explicitly choose to send a receipt in both add and update mode.
348 $defaults['send_receipt'] = 0;
350 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
351 // in this mode by default uncheck this checkbox
352 unset($defaults['record_contribution']);
355 $subscriptionCancelled = FALSE;
356 if (!empty($defaults['id'])) {
357 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
360 $alreadyAutoRenew = FALSE;
361 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
362 $defaults['auto_renew'] = 1;
363 $alreadyAutoRenew = TRUE;
365 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
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']));
372 $defaults = $this->getBillingDefaults($defaults);
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');
379 $this->assign('endDate', $defaults['membership_end_date'] ??
NULL);
385 * Build the form object.
387 * @throws \CRM_Core_Exception
389 public function buildQuickForm() {
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;
400 $getOnlyPriceSetElements = TRUE;
401 if (!$this->_priceSetId
) {
402 $this->_priceSetId
= $_POST['price_set_id'];
403 $getOnlyPriceSetElements = FALSE;
406 $this->set('priceSetId', $this->_priceSetId
);
407 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
409 $optionsMembershipTypes = [];
410 foreach ($this->_priceSet
['fields'] as $pField) {
411 if (empty($pField['options'])) {
414 foreach ($pField['options'] as $opId => $opValues) {
415 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
419 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
421 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
422 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
424 // get only price set form elements.
425 if ($getOnlyPriceSetElements) {
430 // use to build form during form rule.
431 $this->assign('buildPriceSet', $buildPriceSet);
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;
440 if ($buildPriceSet) {
441 $this->add('select', 'price_set_id', ts('Choose price set'),
443 '' => ts('Choose price set'),
445 NULL, ['onchange' => "buildAmount( this.value );"]
448 $this->assign('hasPriceSets', $buildPriceSet);
451 if ($this->_action
& CRM_Core_Action
::DELETE
) {
455 'name' => ts('Delete'),
456 'spacing' => ' ',
461 'name' => ts('Cancel'),
467 $contactField = $this->addEntityRef('contact_id', ts('Member'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
468 if ($this->_context
!== 'standalone') {
469 $contactField->freeze();
472 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
474 // Throw status bounce when no Membership type or priceset is present
475 if (empty($this->allMembershipTypeDetails
) && empty($priceSets)
477 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
479 // retrieve all memberships
480 $allMembershipInfo = [];
481 foreach ($this->allMembershipTypeDetails
as $key => $values) {
482 if ($this->_mode
&& empty($values['minimum_fee'])) {
486 $memberOfContactId = $values['member_of_contact_id'] ??
NULL;
487 if (empty($selMemTypeOrg[$memberOfContactId])) {
488 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
494 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
496 if (empty($selOrgMemType[$memberOfContactId][$key])) {
497 $selOrgMemType[$memberOfContactId][$key] = $values['name'] ??
NULL;
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,
515 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
517 // show organization by default, if only one organization in
519 if (count($selMemTypeOrg) == 2) {
520 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
522 //sort membership organization and type, CRM-6099
523 natcasesort($selMemTypeOrg);
524 foreach ($selOrgMemType as $index => $orgMembershipType) {
525 natcasesort($orgMembershipType);
526 $selOrgMemType[$index] = $orgMembershipType;
530 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
533 if (!empty($this->_recurPaymentProcessors
)) {
534 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
537 $this->add('text', 'max_related', ts('Max related'),
538 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
541 $sel = &$this->addElement('hierselect',
542 'membership_type_id',
543 ts('Membership Organization and Type'),
547 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
549 if ($this->_action
& CRM_Core_Action
::ADD
) {
550 $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
553 $this->add('text', 'source', ts('Source'),
554 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
557 //CRM-7362 --add campaigns.
560 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
562 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
565 $this->add('select', 'status_id', ts('Membership Status'),
566 ['' => ts('- select -')] + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
569 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
570 CRM_Member_StatusOverrideTypes
::getSelectOptions()
573 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => CRM_Utils_Time
::date('Y-m-d'), 'time' => FALSE]);
575 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
577 $this->add('text', 'total_amount', ts('Amount'));
578 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
580 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
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);"]
587 $this->add('text', 'trxn_id', ts('Transaction ID'));
588 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
590 'CRM_Contribute_DAO_Contribution',
596 $this->add('select', 'contribution_status_id',
597 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils
::getPendingAndCompleteStatuses()
599 $this->add('text', 'check_number', ts('Check Number'),
600 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
604 //add field for amount to allow an amount to be entered that differs from minimum
605 $this->add('text', 'total_amount', ts('Amount'));
607 $this->add('select', 'financial_type_id',
608 ts('Financial Type'),
609 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
)
612 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
614 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
615 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
617 $this->addElement('checkbox',
619 ts('Send Confirmation and Receipt?'), NULL,
620 ['onclick' => "showEmailOptions()"]
623 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
625 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
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
);
631 $this->assign('emailExists', $this->_memberEmail
);
632 $this->assign('displayName', $this->_memberDisplayName
);
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}")
640 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
642 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
643 $mailingInfo = Civi
::settings()->get('mailing_backend');
644 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
646 parent
::buildQuickForm();
652 * @param array $params
653 * (ref.) an assoc array of name/value pairs.
655 * @param array $files
656 * @param CRM_Member_Form_Membership $self
659 * mixed true or array of errors
661 * @throws \CRM_Core_Exception
662 * @throws CiviCRM_API3_Exception
664 public static function formRule($params, $files, $self) {
667 $priceSetId = $self->getPriceSetID($params);
668 $priceSetDetails = $self->getPriceSetDetails($params);
670 $selectedMemberships = self
::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
672 if (!empty($params['price_set_id'])) {
673 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
675 $priceFieldIDS = self
::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
677 if (!empty($priceFieldIDS)) {
678 $ids = implode(',', $priceFieldIDS);
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.');
687 // Return error if empty $self->_memTypeSelected
688 if (empty($errors) && empty($selectedMemberships)) {
689 $errors['_qf_default'] = ts('Select at least one membership option.');
691 if (!$self->_mode
&& empty($params['record_contribution'])) {
692 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
696 if (empty($params['membership_type_id'][1])) {
697 $errors['membership_type_id'] = ts('Please select a membership type.');
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.');
704 if (($self->_mode ||
isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
705 $errors['financial_type_id'] = ts('Please enter the financial Type.');
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.');
719 if (!empty($errors)) {
723 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
724 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
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');
731 if (empty($params['soft_credit_contact_id'])) {
732 $errors['soft_credit_contact_id'] = ts('Please select a contact');
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);
742 if (!empty($params['join_date'])) {
744 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
746 foreach ($selectedMemberships as $memType) {
748 if (!empty($params['start_date'])) {
749 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
752 // if end date is set, ensure that start date is also set
753 // and that end date is later than start date
755 if (!empty($params['end_date'])) {
756 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
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.');
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', [
772 'is_current_member' => 0,
774 $tmp_statuses = $result['values'];
776 foreach ($tmp_statuses as $cur_stat) {
777 $status_ids[] = $cur_stat['id'];
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.');
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"');
790 $errors['start_date'] = ts('Start date must be set if end date is set.');
792 if ($endDate < $startDate) {
793 $errors['end_date'] = ts('End date must be the same or later than start date.');
798 // Default values for start and end dates if not supplied on the form.
799 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
806 $startDate = CRM_Utils_Array
::value('start_date',
811 $endDate = CRM_Utils_Array
::value('end_date',
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,
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]);
831 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
833 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
839 $errors['join_date'] = ts('Please enter the Member Since.');
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.');
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.');
852 //total amount condition arise when membership type having no
854 if (isset($params['record_contribution'])) {
855 if (CRM_Utils_System
::isNull($params['total_amount'])) {
856 $errors['total_amount'] = ts('Please enter the contribution.');
860 return empty($errors) ?
TRUE : $errors;
864 * Process the form submission.
866 * @throws \CRM_Core_Exception
867 * @throws \CiviCRM_API3_Exception
869 public function postProcess() {
870 if ($this->_action
& CRM_Core_Action
::DELETE
) {
871 CRM_Member_BAO_Membership
::del($this->_id
);
874 // get the submitted form values.
875 $this->_params
= $this->controller
->exportValues($this->_name
);
876 $this->prepareStatusOverrideValues();
880 $this->setUserContext();
884 * Prepares the values related to status override.
886 private function prepareStatusOverrideValues() {
887 $this->setOverrideDateValue();
888 $this->convertIsOverrideValue();
892 * Sets status override end date to empty value if
893 * the selected override option is not 'until date'.
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'] = '';
902 * Convert the value of selected (status override?)
903 * option to TRUE if it indicate an overridden status
904 * or FALSE otherwise.
906 private function convertIsOverrideValue() {
907 $this->_params
['is_override'] = CRM_Member_StatusOverrideTypes
::isOverridden($this->_params
['is_override'] ?? CRM_Member_StatusOverrideTypes
::NO
);
911 * Send email receipt.
913 * @param CRM_Core_Form $form
915 * @param array $formValues
918 * true if mail was sent successfully
919 * @throws \CRM_Core_Exception
920 * @throws \CiviCRM_API3_Exception
923 * This function was shared with Batch_Entry which had limited overlap
924 * & needs rationalising.
927 protected function emailReceipt($form, &$formValues) {
928 $membership = $this->getMembership();
929 // retrieve 'from email id' for acknowledgement
930 $receiptFrom = $formValues['from_email_address'] ??
NULL;
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']];
938 $form->assign('module', 'Membership');
940 if (!empty($formValues['contribution_id'])) {
941 $form->assign('currency', CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $formValues['contribution_id'], 'currency'));
944 $form->assign('currency', CRM_Core_Config
::singleton()->defaultCurrency
);
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'));
952 if (!empty($formValues['is_renew'])) {
953 $form->assign('receiptType', 'membership renewal');
956 $form->assign('receiptType', 'membership signup');
958 $form->assign('receive_date', CRM_Utils_Array
::value('receive_date', $formValues));
959 $form->assign('formValues', $formValues);
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']));
965 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership['membership_type_id']));
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'];
980 CRM_Core_BAO_MessageTemplate
::sendTemplate(
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
),
990 'receiptText' => $this->getSubmittedValue('receipt_text'),
991 'contributionId' => $formValues['contribution_id'],
992 'contactId' => $form->_receiptContactId
,
993 'membershipId' => $this->getMembershipID(),
1004 * This is also accessed by unit tests.
1006 * @throws \CRM_Core_Exception
1007 * @throws \CiviCRM_API3_Exception
1008 * @throws \API_Exception
1010 public function submit(): void
{
1011 $this->storeContactFields($this->_params
);
1012 $this->beginPostProcess();
1014 $params = $softParams = $ids = [];
1017 $this->processBillingAddress();
1018 $formValues = $this->_params
;
1019 $formValues = $this->setPriceSetParameters($formValues);
1022 $ids['membership'] = $params['id'] = $this->_id
;
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);
1030 $this->_memTypeSelected
= self
::getSelectedMemberships(
1034 $formValues['financial_type_id'] = $this->getFinancialTypeID();
1036 $isQuickConfig = $this->_priceSet
['is_quick_config'];
1038 $lineItem = [$this->order
->getPriceSetID() => $this->order
->getLineItems()];
1040 $params['tax_amount'] = $this->order
->getTotalTaxAmount();
1041 $params['total_amount'] = $this->order
->getTotalAmount();
1042 $params['contact_id'] = $this->_contactID
;
1044 $params = array_merge($params, $this->getFormMembershipParams());
1045 $membershipTypeValues = $this->getMembershipParameters();
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
;
1056 $pendingMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1058 if (!empty($formValues['record_contribution'])) {
1059 $recordContribution = [
1061 'payment_instrument_id',
1063 'contribution_status_id',
1070 foreach ($recordContribution as $f) {
1071 $params[$f] = $formValues[$f] ??
NULL;
1073 $params['financial_type_id'] = $this->getFinancialTypeID();
1074 $params['campaign_id'] = $this->getSubmittedValue('campaign_id');
1076 $params['contribution_source'] = $this->getContributionSource();
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
1082 $params['status_id'] = $pendingMembershipStatusId;
1083 $params['skipStatusCal'] = TRUE;
1084 $params['is_pay_later'] = 1;
1085 $this->assign('is_pay_later', 1);
1088 if ($this->getSubmittedValue('send_receipt')) {
1089 $params['receipt_date'] = $formValues['receive_date'] ??
NULL;
1094 // process line items, until no previous line items.
1095 if (!empty($lineItem)) {
1096 $params['lineItems'] = $lineItem;
1097 $params['processPriceSet'] = TRUE;
1101 $params['total_amount'] = $this->order
->getTotalAmount();
1102 $params['financial_type_id'] = $this->getFinancialTypeID();
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');
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();
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();
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'];
1131 if ($this->getSubmittedValue('send_receipt')) {
1132 $paymentParams['email'] = $this->_contributorEmail
;
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.
1142 $this->_params
= $formValues;
1143 $contribution = civicrm_api3('Order', 'create',
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,
1162 $this->ids
['Contribution'] = $contribution['id'];
1163 $this->setMembershipIDsFromOrder($contribution);
1165 //create new soft-credit record, CRM-13981
1167 $softParams['contribution_id'] = $contribution['id'];
1168 $softParams['currency'] = $this->getCurrency();
1169 $softParams['amount'] = $this->order
->getTotalAmount();
1170 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1173 $paymentParams['contactID'] = $this->_contactID
;
1174 $paymentParams['contributionID'] = $contribution['id'];
1176 $paymentParams['contributionRecurID'] = $this->getContributionRecurID();
1177 $paymentParams['is_recur'] = $this->isCreateRecurringContribution();
1178 $params['contribution_id'] = $paymentParams['contributionID'];
1179 $params['contribution_recur_id'] = $this->getContributionRecurID();
1181 $paymentStatus = NULL;
1183 if ($this->order
->getTotalAmount() > 0.0) {
1184 $payment = $this->_paymentProcessor
['object'];
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(),
1202 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
1203 if (!empty($paymentParams['contributionID'])) {
1204 CRM_Contribute_BAO_Contribution
::failPayment($paymentParams['contributionID'], $this->_contactID
,
1207 if ($this->getContributionRecurID()) {
1208 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($this->getContributionRecurID());
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}"
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;
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
1241 $params['receipt_date'] = $now;
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'])
1250 // required for creating membership for related contacts
1251 $params['action'] = $this->_action
;
1253 //create membership record.
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'];
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
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']);
1278 $params['action'] = $this->_action
;
1279 foreach ($lineItem[$this->_priceSetId
] as $id => $lineItemValues) {
1280 if (empty($lineItemValues['membership_type_id'])) {
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');
1288 $membershipParams = array_merge($params, $membershipTypeValues[$lineItemValues['membership_type_id']]);
1290 if (!empty($softParams)) {
1291 $params['soft_credit'] = $softParams;
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';
1302 $params['lineItems'] = $lineItem;
1303 if (!empty($formValues['record_contribution'])) {
1304 CRM_Member_BAO_Membership
::recordMembershipContribution($params);
1308 $this->updateContributionOnMembershipTypeChange($params);
1310 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1311 $this->addStatusMessage($this->getStatusMessageForUpdate());
1313 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1314 $this->addStatusMessage($this->getStatusMessageForCreate());
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']) : '-';
1326 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1329 if (Civi
::settings()->get('invoicing')) {
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);
1337 $dataArray[$value['tax_rate']] = $value['tax_amount'] ??
NULL;
1342 $this->assign('dataArray', $dataArray);
1345 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
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;
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
1365 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1366 // send email receipt
1367 $this->assignBillingName();
1368 $mailSend = $this->emailMembershipReceipt($formValues);
1369 $receiptSent = TRUE;
1372 if ($receiptSent && $mailSend) {
1373 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail
]));
1376 CRM_Core_Session
::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1377 $this->setStatusMessage();
1379 // finally set membership id if already not set
1381 $this->_id
= $this->getMembershipID();
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
1389 * @param array $inputParams
1390 * submitted form values
1392 * @throws \CRM_Core_Exception
1393 * @throws \CiviCRM_API3_Exception
1395 protected function updateContributionOnMembershipTypeChange($inputParams) {
1396 if (Civi
::settings()->get('update_contribution_on_membership_type_change') &&
1398 ($this->_action
& CRM_Core_Action
::UPDATE
) &&
1401 // if selected membership doesn't match with earlier membership
1402 !in_array($this->_memType
, $this->_memTypeSelected
)
1404 if ($this->isCreateRecurringContribution()) {
1405 CRM_Core_Session
::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
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(),
1418 // get price fields of chosen price-set
1419 $priceSetDetails = CRM_Utils_Array
::value(
1421 CRM_Price_BAO_PriceSet
::getSetDetail(
1428 // add price field information in $inputParams
1429 self
::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $this->getMembership()['membership_type_id']);
1431 // update related contribution and financial records
1432 CRM_Price_BAO_LineItem
::changeFeeSelections(
1434 $this->getMembershipID(),
1437 $priceSetDetails['fields'],
1440 CRM_Core_Session
::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1445 * Add selected price field information in $formValues
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
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'];
1469 * Set context in session.
1471 protected function setUserContext() {
1472 $buttonName = $this->controller
->getButtonName();
1473 $session = CRM_Core_Session
::singleton();
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'
1482 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
1483 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1488 $url = CRM_Utils_System
::url('civicrm/contact/view',
1489 "reset=1&cid={$this->_contactID}&selectedChild=member"
1492 $session->replaceUserContext($url);
1496 * Get status message for updating membership.
1499 * @throws \CiviCRM_API3_Exception
1501 protected function getStatusMessageForUpdate(): string {
1502 foreach ($this->getCreatedMemberships() as $membership) {
1503 $endDate = $membership['end_date'] ??
NULL;
1505 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName
]);
1507 $endDate = CRM_Utils_Date
::customFormat($endDate);
1508 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
1514 * Get status message for create action.
1517 * @throws \CiviCRM_API3_Exception
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
,
1526 $memEndDate = $membership['end_date'] ??
NULL;
1529 $memEndDate = CRM_Utils_Date
::formatDateOnlyLong($memEndDate);
1530 $statusMsg[$membership['membership_type_id']] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
1533 $statusMsg = implode('<br/>', $statusMsg);
1534 return $statusMsg ??
'';
1539 protected function setStatusMessage() {
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.'),
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.'),
1564 * @throws \CRM_Core_Exception
1566 protected function isUpdateToExistingRecurringMembership() {
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())) {
1579 * Send a receipt for the membership.
1581 * @param array $formValues
1584 * @throws \CRM_Core_Exception
1585 * @throws \CiviCRM_API3_Exception
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());
1595 // @todo move this outside shared code as Batch entry just doesn't
1596 $this->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
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);
1606 //insert financial type name in receipt.
1607 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1608 $this->getFinancialTypeID()
1610 return $this->emailReceipt($this, $formValues);
1614 * Filter the custom values from the input parameters (for display in the email).
1616 * @todo figure out why the scary code this calls does & document.
1618 * @param array $formValues
1621 protected function getCustomValuesForReceipt($formValues): array {
1622 $customFields = $customValues = [];
1623 if (property_exists($this, '_groupTree')
1624 && !empty($this->_groupTree
)
1626 foreach ($this->_groupTree
as $groupID => $group) {
1627 if ($groupID === 'info') {
1630 foreach ($group['fields'] as $k => $field) {
1631 $field['title'] = $field['label'];
1632 $customFields["custom_{$k}"] = $field;
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];
1643 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1644 return $customValues;
1648 * Get the selected memberships as a string of labels.
1652 protected function getSelectedMembershipLabels(): string {
1654 foreach ($this->_memTypeSelected
as $membershipTypeID) {
1655 $return[] = $this->allMembershipTypeDetails
[$membershipTypeID]['name'];
1657 return implode(', ', $return);
1661 * Get the recurring contribution id, if one is applicable.
1663 * If the recurring contribution is applicable and not yet
1664 * created it will be created at this stage.
1668 * @throws \API_Exception
1669 * @throws \CiviCRM_API3_Exception
1671 protected function getContributionRecurID():?
int {
1672 if (!array_key_exists('ContributionRecur', $this->ids
)) {
1673 $this->createRecurringContribution();
1675 return $this->ids
['ContributionRecur'];
1679 * Create the recurring contribution record if the form submission requires it.
1681 * This function was copied from another form & needs cleanup.
1683 * @throws \API_Exception
1684 * @throws \CiviCRM_API3_Exception
1686 protected function createRecurringContribution(): void
{
1687 if (!$this->isCreateRecurringContribution()) {
1688 $this->ids
['ContributionRecur'] = NULL;
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'];
1715 * Is the form being submitted in test mode.
1719 protected function isTest(): bool {
1720 return ($this->_mode
=== 'test') ?
TRUE : FALSE;
1724 * Get the financial type id relevant to the contribution.
1726 * Financial type id is optional when price sets are in use.
1727 * Otherwise they are required for the form to submit.
1731 protected function getFinancialTypeID(): int {
1732 return (int) $this->getSubmittedValue('financial_type_id') ?
: $this->order
->getFinancialTypeID();
1736 * Get the membership type, if any, to be recurred.
1739 * @throws \CiviCRM_API3_Exception
1741 protected function getRecurMembershipType(): array {
1742 foreach ($this->order
->getRenewableMembershipTypes() as $type) {
1749 * Get the frequency interval.
1752 * @throws \CiviCRM_API3_Exception
1754 protected function getFrequencyInterval(): ?
int {
1755 $membershipType = $this->getRecurMembershipType();
1756 return empty($membershipType) ?
NULL : (int) $membershipType['duration_interval'];
1760 * Get the frequency interval.
1762 * @return string|null
1763 * @throws \CiviCRM_API3_Exception
1765 protected function getFrequencyUnit(): ?
string {
1766 $membershipType = $this->getRecurMembershipType();
1767 return empty($membershipType) ?
NULL : (string) $membershipType['duration_unit'];
1771 * Get values that should be passed to all membership create actions.
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.
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).
1782 * @throws \API_Exception
1783 * @throws \CiviCRM_API3_Exception
1785 protected function getFormMembershipParams(): array {
1786 $submittedValues = $this->controller
->exportValues($this->_name
);
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,
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(),
1807 * Is it necessary to create a recurring contribution.
1811 protected function isCreateRecurringContribution(): bool {
1812 return $this->_mode
&& $this->getSubmittedValue('auto_renew');
1816 * Get the payment processor ID.
1820 public function getPaymentProcessorID(): int {
1821 return (int) ($this->getSubmittedValue('payment_processor_id') ?
: $this->_paymentProcessor
['id']);
1825 * Get memberships submitted through the form submission.
1828 * @throws \CiviCRM_API3_Exception
1830 protected function getCreatedMemberships(): array {
1831 return civicrm_api3('Membership', 'get', ['id' => ['IN' => $this->_membershipIDs
]])['values'];
1835 * Get parameters for membership create for all memberships to be created.
1838 * @throws \CiviCRM_API3_Exception
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');
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'),
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'];
1865 return $membershipTypeValues;
1869 * Get the value for the contribution source.
1873 protected function getContributionSource(): string {
1874 [$userName] = CRM_Contact_BAO_Contact_Location
::getEmailDetails(CRM_Core_Session
::getLoggedInContactID());
1876 return ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1877 [1 => $this->getSelectedMembershipLabels(), 2 => $userName]
1880 if ($this->getSubmittedValue('source')) {
1881 return $this->getSubmittedValue('source');
1883 return ts('%1 Membership: Offline signup (by %2)', [
1884 1 => $this->getSelectedMembershipLabels(),
1890 * Get the receive date for the contribution.
1892 * @return string $receive_date
1894 protected function getReceiveDate(): string {
1895 return $this->getSubmittedValue('receive_date') ?
: date('YmdHis');
1899 * Set membership IDs.
1903 protected function setMembershipIDs(array $ids): void
{
1904 $this->_membershipIDs
= $ids;
1908 * Get the created or edited membership ID.
1910 * @return false|mixed
1912 protected function getMembershipID() {
1913 return reset($this->_membershipIDs
);
1917 * Get the membership (or last membership) created or edited on this form.
1920 * @throws \CiviCRM_API3_Exception
1922 protected function getMembership(): array {
1923 if (empty($this->membership
)) {
1924 $this->membership
= civicrm_api3('Membership', 'get', ['id' => $this->getMembershipID()])['values'][$this->getMembershipID()];
1926 return $this->membership
;
1930 * Setter for membership.
1932 * @param array $membership
1934 protected function setMembership(array $membership): void
{
1935 if (!in_array($membership['id'], $this->_membershipIDs
, TRUE)) {
1936 $this->_membershipIDs
[] = $membership['id'];
1938 $this->membership
= $membership;
1942 * Get line items formatted for the Order api.
1946 * @throws \CiviCRM_API3_Exception
1948 protected function getLineItemForOrderApi(): array {
1950 foreach ($this->order
->getLineItems() as $line) {
1952 if (!empty($line['membership_type_id'])) {
1953 $params = $this->getMembershipParamsForType((int) $line['membership_type_id']);
1956 'line_item' => [$line['price_field_value_id'] => $line],
1957 'params' => $params,
1964 * Get the parameters for the given membership type.
1966 * @param int $membershipTypeID
1969 * @throws \CiviCRM_API3_Exception
1971 protected function getMembershipParamsForType(int $membershipTypeID) {
1972 return array_merge($this->getFormMembershipParams(), $this->getMembershipParameters()[$membershipTypeID]);
1976 * @param array $contribution
1978 protected function setMembershipIDsFromOrder(array $contribution): void
{
1980 foreach ($contribution['values'][$contribution['id']]['line_item'] as $line) {
1981 if ($line['entity_table'] ??
'' === 'civicrm_membership') {
1982 $ids[] = $line['entity_id'];
1985 $this->setMembershipIDs($ids);