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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components for offline membership form.
21 class CRM_Member_Form_Membership
extends CRM_Member_Form
{
23 protected $_memType = NULL;
27 public $_contributeMode = 'direct';
29 protected $_recurMembershipTypes;
31 protected $_memTypeSelected;
34 * Display name of the member.
38 protected $_memberDisplayName = NULL;
41 * email of the person paying for the membership (used for receipts)
44 protected $_memberEmail = NULL;
47 * Contact ID of the member.
51 public $_contactID = NULL;
54 * Display name of the person paying for the membership (used for receipts)
58 protected $_contributorDisplayName = NULL;
61 * Email of the person paying for the membership (used for receipts).
65 protected $_contributorEmail;
68 * email of the person paying for the membership (used for receipts)
72 protected $_contributorContactID = NULL;
75 * ID of the person the receipt is to go to.
79 protected $_receiptContactId = NULL;
82 * Keep a class variable for ALL membership IDs so
83 * postProcess hook function can do something with it
87 protected $_membershipIDs = [];
90 * Set entity fields to be assigned to the form.
92 protected function setEntityFields() {
93 $this->entityFields
= [
95 'name' => 'join_date',
96 'description' => ts('Member Since'),
99 'name' => 'start_date',
100 'description' => ts('Start Date'),
103 'name' => 'end_date',
104 'description' => ts('End Date'),
110 * Set the delete message.
112 * We do this from the constructor in order to do a translation.
114 public function setDeleteMessage() {
115 $this->deleteMessage
= '<span class="font-red bold">'
116 . ts('WARNING: Deleting this membership will also delete any related payment (contribution) records.' . ts('This action cannot be undone.')
118 . 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.')
120 . ts("Click 'Delete' if you want to continue.") . '</p>');
124 * Overriding this entity trait function as not yet tested.
126 * We continue to rely on legacy handling.
128 public function addCustomDataToForm() {}
131 * Overriding this entity trait function as not yet tested.
133 * We continue to rely on legacy handling.
135 public function addFormButtons() {}
138 * Get selected membership type from the form values.
140 * @param array $priceSet
141 * @param array $params
144 * @throws \CRM_Core_Exception
146 public static function getSelectedMemberships($priceSet, $params) {
147 $memTypeSelected = [];
148 $priceFieldIDS = self
::getPriceFieldIDs($params, $priceSet);
149 if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
150 $memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
153 foreach ($priceFieldIDS as $priceFieldId) {
154 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
155 $memTypeSelected[$id] = $id;
159 return $memTypeSelected;
163 * Extract price set fields and values from $params.
165 * @param array $params
166 * @param array $priceSet
170 public static function getPriceFieldIDs($params, $priceSet) {
172 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
173 foreach ($priceSet['fields'] as $fieldId => $field) {
174 if (!empty($params['price_' . $fieldId])) {
175 if (is_array($params['price_' . $fieldId])) {
176 foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
178 $priceFieldIDS[] = $priceFldVal;
182 elseif (!$field['is_enter_qty']) {
183 $priceFieldIDS[] = $params['price_' . $fieldId];
188 return $priceFieldIDS;
192 * Form preProcess function.
194 * @throws \CRM_Core_Exception
195 * @throws \CiviCRM_API3_Exception
197 public function preProcess() {
198 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
199 $this->assign('formClass', 'membership');
200 parent
::preProcess();
203 $this->_priceSetId
= $_GET['priceSetId'] ??
NULL;
204 $this->set('priceSetId', $this->_priceSetId
);
205 $this->assign('priceSetId', $this->_priceSetId
);
207 if ($this->_action
& CRM_Core_Action
::DELETE
) {
208 $contributionID = CRM_Member_BAO_Membership
::getMembershipContributionId($this->_id
);
209 // check delete permission for contribution
210 if ($this->_id
&& $contributionID && !CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
211 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."));
215 if ($this->_action
& CRM_Core_Action
::ADD
) {
216 if ($this->_contactID
) {
217 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
218 $contactMemberships = [];
219 $memParams = ['contact_id' => $this->_contactID
];
220 CRM_Member_BAO_Membership
::getValues($memParams, $contactMemberships, TRUE);
222 foreach ($contactMemberships as $mem) {
223 $cMemTypes[] = $mem['membership_type_id'];
225 if (count($cMemTypes) > 0) {
226 foreach ($cMemTypes as $memTypeID) {
227 $memberorgs[$memTypeID] = CRM_Member_BAO_MembershipType
::getMembershipType($memTypeID)['member_of_contact_id'];
230 foreach ($contactMemberships as $mem) {
231 $mem['member_of_contact_id'] = $memberorgs[$mem['membership_type_id']] ??
NULL;
232 if (!empty($mem['membership_end_date'])) {
233 $mem['membership_end_date'] = CRM_Utils_Date
::customFormat($mem['membership_end_date']);
235 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
236 $mem['membership_type_id'],
239 $mem['membership_status'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
243 $mem['renewUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
244 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
245 . ($this->_mode ?
'&mode=live' : '')
247 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
248 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
250 $mems_by_org[$mem['member_of_contact_id']] = $mem;
252 $this->assign('existingContactMemberships', $mems_by_org);
256 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
257 $resources = CRM_Core_Resources
::singleton();
258 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
260 'typeorgs' => CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization(),
261 'memtypes' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'membership_type_id'),
262 'statuses' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'status_id'),
264 $resources->addSetting(['existingMems' => $passthru]);
268 if (!$this->_memType
) {
269 $params = CRM_Utils_Request
::exportValues();
270 if (!empty($params['membership_type_id'][1])) {
271 $this->_memType
= $params['membership_type_id'][1];
275 // Add custom data to form
276 CRM_Custom_Form_CustomData
::addToForm($this, $this->_memType
);
277 $this->setPageTitle(ts('Membership'));
281 * Set default values for the form.
283 public function setDefaultValues() {
285 if ($this->_priceSetId
) {
286 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
289 $defaults = parent
::setDefaultValues();
291 //setting default join date and receive date
292 if ($this->_action
== CRM_Core_Action
::ADD
) {
293 $defaults['receive_date'] = CRM_Utils_Time
::date('Y-m-d H:i:s');
296 $defaults['num_terms'] = 1;
298 if (!empty($defaults['id'])) {
299 $contributionId = CRM_Core_DAO
::singleValueQuery("
300 SELECT contribution_id
301 FROM civicrm_membership_payment
302 WHERE membership_id = $this->_id
303 ORDER BY contribution_id
306 if ($contributionId) {
307 $defaults['record_contribution'] = $contributionId;
311 if ($this->_contactID
) {
312 $defaults['contact_id'] = $this->_contactID
;
316 //set Soft Credit Type to Gift by default
317 $scTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
318 $defaults['soft_credit_type_id'] = CRM_Utils_Array
::value(ts('Gift'), array_flip($scTypes));
321 if (empty($defaults['payment_instrument_id'])) {
322 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
325 // User must explicitly choose to send a receipt in both add and update mode.
326 $defaults['send_receipt'] = 0;
328 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
329 // in this mode by default uncheck this checkbox
330 unset($defaults['record_contribution']);
333 $subscriptionCancelled = FALSE;
334 if (!empty($defaults['id'])) {
335 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
338 $alreadyAutoRenew = FALSE;
339 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
340 $defaults['auto_renew'] = 1;
341 $alreadyAutoRenew = TRUE;
343 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
345 $this->assign('member_is_test', $defaults['member_is_test'] ??
NULL);
346 $this->assign('membership_status_id', $defaults['status_id'] ??
NULL);
347 $this->assign('is_pay_later', !empty($defaults['is_pay_later']));
350 $defaults = $this->getBillingDefaults($defaults);
353 //setting default join date if there is no join date
354 if (empty($defaults['join_date'])) {
355 $defaults['join_date'] = CRM_Utils_Time
::date('Y-m-d');
358 if (!empty($defaults['membership_end_date'])) {
359 $this->assign('endDate', $defaults['membership_end_date']);
366 * Build the form object.
368 * @throws \CRM_Core_Exception
370 public function buildQuickForm() {
372 $this->buildQuickEntityForm();
373 $this->assign('currency_symbol', CRM_Core_BAO_Country
::defaultCurrencySymbol());
374 $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
375 // build price set form.
376 $buildPriceSet = FALSE;
377 if ($this->_priceSetId ||
!empty($_POST['price_set_id'])) {
378 if (!empty($_POST['price_set_id'])) {
379 $buildPriceSet = TRUE;
381 $getOnlyPriceSetElements = TRUE;
382 if (!$this->_priceSetId
) {
383 $this->_priceSetId
= $_POST['price_set_id'];
384 $getOnlyPriceSetElements = FALSE;
387 $this->set('priceSetId', $this->_priceSetId
);
388 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
390 $optionsMembershipTypes = [];
391 foreach ($this->_priceSet
['fields'] as $pField) {
392 if (empty($pField['options'])) {
395 foreach ($pField['options'] as $opId => $opValues) {
396 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
400 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
402 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
403 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
405 // get only price set form elements.
406 if ($getOnlyPriceSetElements) {
411 // use to build form during form rule.
412 $this->assign('buildPriceSet', $buildPriceSet);
414 if ($this->_action
& CRM_Core_Action
::ADD
) {
415 $buildPriceSet = FALSE;
416 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
417 if (!empty($priceSets)) {
418 $buildPriceSet = TRUE;
421 if ($buildPriceSet) {
422 $this->add('select', 'price_set_id', ts('Choose price set'),
424 '' => ts('Choose price set'),
426 NULL, ['onchange' => "buildAmount( this.value );"]
429 $this->assign('hasPriceSets', $buildPriceSet);
432 if ($this->_action
& CRM_Core_Action
::DELETE
) {
436 'name' => ts('Delete'),
437 'spacing' => ' ',
442 'name' => ts('Cancel'),
448 $contactField = $this->addEntityRef('contact_id', ts('Member'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
449 if ($this->_context
!== 'standalone') {
450 $contactField->freeze();
453 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
455 // Throw status bounce when no Membership type or priceset is present
456 if (empty($this->allMembershipTypeDetails
) && empty($priceSets)
458 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
460 // retrieve all memberships
461 $allMembershipInfo = [];
462 foreach ($this->allMembershipTypeDetails
as $key => $values) {
463 if ($this->_mode
&& empty($values['minimum_fee'])) {
467 $memberOfContactId = $values['member_of_contact_id'] ??
NULL;
468 if (empty($selMemTypeOrg[$memberOfContactId])) {
469 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
475 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
477 if (empty($selOrgMemType[$memberOfContactId][$key])) {
478 $selOrgMemType[$memberOfContactId][$key] = $values['name'] ??
NULL;
481 $totalAmount = $values['minimum_fee'] ??
NULL;
482 //CRM-18827 - override the default value if total_amount is submitted
483 if (!empty($this->_submitValues
['total_amount'])) {
484 $totalAmount = CRM_Utils_Rule
::cleanMoney($this->_submitValues
['total_amount']);
486 // build membership info array, which is used when membership type is selected to:
487 // - set the payment information block
488 // - set the max related block
489 $allMembershipInfo[$key] = [
490 'financial_type_id' => $values['financial_type_id'] ??
NULL,
491 'total_amount' => CRM_Utils_Money
::format($totalAmount, NULL, '%a'),
492 'total_amount_numeric' => $totalAmount,
493 'auto_renew' => $values['auto_renew'] ??
NULL,
494 'has_related' => isset($values['relationship_type_id']),
495 'max_related' => $values['max_related'] ??
NULL,
499 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
501 // show organization by default, if only one organization in
503 if (count($selMemTypeOrg) == 2) {
504 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
506 //sort membership organization and type, CRM-6099
507 natcasesort($selMemTypeOrg);
508 foreach ($selOrgMemType as $index => $orgMembershipType) {
509 natcasesort($orgMembershipType);
510 $selOrgMemType[$index] = $orgMembershipType;
514 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
517 if (!empty($this->_recurPaymentProcessors
)) {
518 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
521 $this->add('text', 'max_related', ts('Max related'),
522 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
525 $sel = &$this->addElement('hierselect',
526 'membership_type_id',
527 ts('Membership Organization and Type'),
531 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
533 if ($this->_action
& CRM_Core_Action
::ADD
) {
534 $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
537 $this->add('text', 'source', ts('Source'),
538 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
541 //CRM-7362 --add campaigns.
544 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
546 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
549 $this->add('select', 'status_id', ts('Membership Status'),
550 ['' => ts('- select -')] + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
553 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
554 CRM_Member_StatusOverrideTypes
::getSelectOptions()
557 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => CRM_Utils_Time
::date('Y-m-d'), 'time' => FALSE]);
559 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
561 $this->add('text', 'total_amount', ts('Amount'));
562 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
564 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
566 $this->add('select', 'payment_instrument_id',
567 ts('Payment Method'),
568 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
569 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
571 $this->add('text', 'trxn_id', ts('Transaction ID'));
572 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
574 'CRM_Contribute_DAO_Contribution',
580 $this->add('select', 'contribution_status_id',
581 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses('membership')
583 $this->add('text', 'check_number', ts('Check Number'),
584 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
588 //add field for amount to allow an amount to be entered that differs from minimum
589 $this->add('text', 'total_amount', ts('Amount'));
591 $this->add('select', 'financial_type_id',
592 ts('Financial Type'),
593 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
)
596 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
598 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
599 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
601 $this->addElement('checkbox',
603 ts('Send Confirmation and Receipt?'), NULL,
604 ['onclick' => "showEmailOptions()"]
607 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
609 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
611 // Retrieve the name and email of the contact - this will be the TO for receipt email
612 if ($this->_contactID
) {
613 [$this->_memberDisplayName
, $this->_memberEmail
] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
615 $this->assign('emailExists', $this->_memberEmail
);
616 $this->assign('displayName', $this->_memberDisplayName
);
619 if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
620 $this->assign('cancelAutoRenew',
621 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
625 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
627 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
628 $mailingInfo = Civi
::settings()->get('mailing_backend');
629 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
631 parent
::buildQuickForm();
637 * @param array $params
638 * (ref.) an assoc array of name/value pairs.
640 * @param array $files
641 * @param CRM_Member_Form_Membership $self
644 * mixed true or array of errors
646 * @throws \CRM_Core_Exception
647 * @throws CiviCRM_API3_Exception
649 public static function formRule($params, $files, $self) {
652 $priceSetId = $self->getPriceSetID($params);
653 $priceSetDetails = $self->getPriceSetDetails($params);
655 $selectedMemberships = self
::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
657 if (!empty($params['price_set_id'])) {
658 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
660 $priceFieldIDS = self
::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
662 if (!empty($priceFieldIDS)) {
663 $ids = implode(',', $priceFieldIDS);
665 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
666 foreach ($count as $occurrence) {
667 if ($occurrence > 1) {
668 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
672 // Return error if empty $self->_memTypeSelected
673 if (empty($errors) && empty($selectedMemberships)) {
674 $errors['_qf_default'] = ts('Select at least one membership option.');
676 if (!$self->_mode
&& empty($params['record_contribution'])) {
677 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
681 if (empty($params['membership_type_id'][1])) {
682 $errors['membership_type_id'] = ts('Please select a membership type.');
684 $numterms = $params['num_terms'] ??
NULL;
685 if ($numterms && intval($numterms) != $numterms) {
686 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
689 if (($self->_mode ||
isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
690 $errors['financial_type_id'] = ts('Please enter the financial Type.');
694 if (!empty($errors) && (count($selectedMemberships) > 1)) {
695 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($selectedMemberships);
696 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
697 foreach ($duplicateMemberOfContacts as $countDuplicate) {
698 if ($countDuplicate > 1) {
699 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
704 if (!empty($errors)) {
708 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
709 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
712 if (!empty($params['is_different_contribution_contact'])) {
713 if (empty($params['soft_credit_type_id'])) {
714 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
716 if (empty($params['soft_credit_contact_id'])) {
717 $errors['soft_credit_contact_id'] = ts('Please select a contact');
721 if (!empty($params['payment_processor_id'])) {
722 // validate payment instrument (e.g. credit card number)
723 CRM_Core_Payment_Form
::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
727 if (!empty($params['join_date'])) {
729 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
731 foreach ($selectedMemberships as $memType) {
733 if (!empty($params['start_date'])) {
734 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
737 // if end date is set, ensure that start date is also set
738 // and that end date is later than start date
740 if (!empty($params['end_date'])) {
741 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
744 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipType($memType);
745 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) === 'rolling') {
746 if ($startDate < $joinDate) {
747 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
752 if ($membershipDetails['duration_unit'] === 'lifetime') {
753 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
754 // process to update status based on end-date. The user must change the status now.
755 $result = civicrm_api3('MembershipStatus', 'get', [
757 'is_current_member' => 0,
759 $tmp_statuses = $result['values'];
761 foreach ($tmp_statuses as $cur_stat) {
762 $status_ids[] = $cur_stat['id'];
765 if (empty($params['status_id']) ||
in_array($params['status_id'], $status_ids) == FALSE) {
766 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
769 if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes
::isPermanent($params['is_override'])) {
770 $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
775 $errors['start_date'] = ts('Start date must be set if end date is set.');
777 if ($endDate < $startDate) {
778 $errors['end_date'] = ts('End date must be the same or later than start date.');
783 // Default values for start and end dates if not supplied on the form.
784 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
791 $startDate = CRM_Utils_Array
::value('start_date',
796 $endDate = CRM_Utils_Array
::value('end_date',
801 //CRM-3724, check for availability of valid membership status.
802 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes
::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
803 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
811 if (empty($calcStatus)) {
812 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
813 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
814 $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]);
816 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
818 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
824 $errors['join_date'] = ts('Please enter the Member Since.');
827 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes
::isOverridden($params['is_override']) && empty($params['status_id'])) {
828 $errors['status_id'] = ts('Please enter the Membership status.');
831 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes
::isUntilDate($params['is_override'])) {
832 if (empty($params['status_override_end_date'])) {
833 $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
837 //total amount condition arise when membership type having no
839 if (isset($params['record_contribution'])) {
840 if (CRM_Utils_System
::isNull($params['total_amount'])) {
841 $errors['total_amount'] = ts('Please enter the contribution.');
845 return empty($errors) ?
TRUE : $errors;
849 * Process the form submission.
851 * @throws \CRM_Core_Exception
852 * @throws \CiviCRM_API3_Exception
854 public function postProcess() {
855 if ($this->_action
& CRM_Core_Action
::DELETE
) {
856 CRM_Member_BAO_Membership
::del($this->_id
);
859 // get the submitted form values.
860 $this->_params
= $this->controller
->exportValues($this->_name
);
861 $this->prepareStatusOverrideValues();
865 $this->setUserContext();
869 * Prepares the values related to status override.
871 private function prepareStatusOverrideValues() {
872 $this->setOverrideDateValue();
873 $this->convertIsOverrideValue();
877 * Sets status override end date to empty value if
878 * the selected override option is not 'until date'.
880 private function setOverrideDateValue() {
881 if (!CRM_Member_StatusOverrideTypes
::isUntilDate(CRM_Utils_Array
::value('is_override', $this->_params
))) {
882 $this->_params
['status_override_end_date'] = '';
887 * Convert the value of selected (status override?)
888 * option to TRUE if it indicate an overridden status
889 * or FALSE otherwise.
891 private function convertIsOverrideValue() {
892 $this->_params
['is_override'] = CRM_Member_StatusOverrideTypes
::isOverridden($this->_params
['is_override'] ?? CRM_Member_StatusOverrideTypes
::NO
);
896 * Send email receipt.
898 * @param CRM_Core_Form $form
900 * @param array $formValues
901 * @param object $membership
905 * true if mail was sent successfully
906 * @throws \CRM_Core_Exception
909 * This function is shared with Batch_Entry which has limited overlap
910 * & needs rationalising.
913 public static function emailReceipt($form, &$formValues, $membership) {
914 // retrieve 'from email id' for acknowledgement
915 $receiptFrom = $formValues['from_email_address'] ??
NULL;
917 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
918 if (!empty($formValues['payment_instrument_id'])) {
919 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
920 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
924 // @todo move this outside shared code as Batch entry just doesn't
925 $form->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
930 $valuesForForm = CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($form->_params
);
931 $form->assignVariables($valuesForForm, ['credit_card_exp_date', 'credit_card_type', 'credit_card_number']);
932 $form->assign('is_pay_later', 0);
933 $form->assign('isPrimary', 1);
936 $form->assign('module', 'Membership');
937 $form->assign('contactID', $formValues['contact_id']);
939 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
941 if (!empty($formValues['contribution_id'])) {
942 $form->assign('contributionID', $formValues['contribution_id']);
945 if (!empty($formValues['contribution_status_id'])) {
946 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
947 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
950 if (!empty($formValues['is_renew'])) {
951 $form->assign('receiptType', 'membership renewal');
954 $form->assign('receiptType', 'membership signup');
956 $form->assign('receive_date', CRM_Utils_Array
::value('receive_date', $formValues));
957 $form->assign('formValues', $formValues);
959 $form->assign('mem_start_date', CRM_Utils_Date
::formatDateOnlyLong($membership->start_date
));
960 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
961 $form->assign('mem_end_date', CRM_Utils_Date
::formatDateOnlyLong($membership->end_date
));
963 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
965 // @todo - if we have to figure out if this is for batch processing it doesn't belong in the shared function.
966 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
967 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
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
) ||
$isBatchProcess) {
976 $form->_receiptContactId
= $formValues['contact_id'];
980 CRM_Core_BAO_MessageTemplate
::sendTemplate(
982 'groupName' => 'msg_tpl_workflow_membership',
983 'valueName' => 'membership_offline_receipt',
984 'contactId' => $form->_receiptContactId
,
985 'from' => $receiptFrom,
986 'toName' => $form->_contributorDisplayName
,
987 'toEmail' => $form->_contributorEmail
,
988 'PDFFilename' => ts('receipt') . '.pdf',
989 'isEmailPdf' => Civi
::settings()->get('invoicing') && Civi
::settings()->get('is_email_pdf'),
990 'contributionId' => $formValues['contribution_id'],
991 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
1001 * This is also accessed by unit tests.
1003 * @throws \CRM_Core_Exception
1004 * @throws \CiviCRM_API3_Exception
1006 public function submit(): void
{
1007 $this->storeContactFields($this->_params
);
1008 $this->beginPostProcess();
1010 $membership = $calcDate = [];
1012 $paymentInstrumentID = $this->_paymentProcessor
['object']->getPaymentInstrumentID();
1013 $params = $softParams = $ids = [];
1016 $this->processBillingAddress();
1017 $formValues = $this->_params
;
1018 $formValues = $this->setPriceSetParameters($formValues);
1021 $ids['membership'] = $params['id'] = $this->_id
;
1024 // Set variables that we normally get from context.
1025 // In form mode these are set in preProcess.
1026 //TODO: set memberships, fixme
1027 $this->setContextVariables($formValues);
1029 $this->_memTypeSelected
= self
::getSelectedMemberships(
1033 if (empty($formValues['financial_type_id'])) {
1034 $formValues['financial_type_id'] = $this->_priceSet
['financial_type_id'];
1037 $membershipTypeValues = [];
1038 foreach ($this->_memTypeSelected
as $memType) {
1039 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1042 //take the required membership recur values.
1043 if ($this->_mode
&& !empty($formValues['auto_renew'])) {
1044 $params['is_recur'] = $formValues['is_recur'] = TRUE;
1047 foreach ($this->_memTypeSelected
as $memType) {
1048 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1049 $this->allMembershipTypeDetails
, []
1051 if (!$recurMembershipTypeValues['auto_renew']) {
1055 'frequency_interval' => 'duration_interval',
1056 'frequency_unit' => 'duration_unit',
1057 ] as $mapVal => $mapParam) {
1058 $membershipTypeValues[$memType][$mapVal] = $recurMembershipTypeValues[$mapParam];
1061 $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1062 $recurMembershipTypeValues
1070 $isQuickConfig = $this->_priceSet
['is_quick_config'];
1074 $lineItem = [$this->_priceSetId
=> []];
1076 // BEGIN Fix for dev/core/issues/860
1077 // Prepare fee block and call buildAmount hook - based on CRM_Price_BAO_PriceSet::buildPriceSet().
1078 CRM_Utils_Hook
::buildAmount('membership', $this, $this->_priceSet
['fields']);
1079 // END Fix for dev/core/issues/860
1081 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1082 $formValues, $lineItem[$this->_priceSetId
], $this->_priceSetId
);
1084 if (!empty($formValues['tax_amount'])) {
1085 $params['tax_amount'] = $formValues['tax_amount'];
1087 $params['total_amount'] = $formValues['amount'] ??
NULL;
1088 if (!empty($lineItem[$this->_priceSetId
])) {
1089 foreach ($lineItem[$this->_priceSetId
] as &$li) {
1090 if (!empty($li['membership_type_id'])) {
1091 if (!empty($li['membership_num_terms'])) {
1092 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1096 ///CRM-11529 for quick config backoffice transactions
1097 //when financial_type_id is passed in form, update the
1098 //lineitems with the financial type selected in form
1099 $submittedFinancialType = $formValues['financial_type_id'] ??
NULL;
1100 if ($isQuickConfig && $submittedFinancialType) {
1101 $li['financial_type_id'] = $submittedFinancialType;
1106 $params['contact_id'] = $this->_contactID
;
1112 'status_override_end_date',
1116 foreach ($fields as $f) {
1117 $params[$f] = $formValues[$f] ??
NULL;
1121 // when is_override false ignore is_admin statuses during membership
1122 // status calculation. similarly we did fix for import in CRM-3570.
1123 if (empty($params['is_override'])) {
1124 $params['exclude_is_admin'] = TRUE;
1127 $joinDate = $formValues['join_date'];
1128 $startDate = $formValues['start_date'];
1129 $endDate = $formValues['end_date'];
1131 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array
::value('num_terms', $formValues) : NULL;
1134 foreach ($this->_memTypeSelected
as $memType) {
1135 if (empty($memTypeNumTerms)) {
1136 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, 1);
1138 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1139 $joinDate, $startDate, $endDate, $memTypeNumTerms
1143 foreach ($calcDates as $memType => $calcDate) {
1144 foreach (['join_date', 'start_date', 'end_date'] as $d) {
1145 //first give priority to form values then calDates.
1146 $date = $formValues[$d] ??
NULL;
1148 $date = $calcDate[$d] ??
NULL;
1151 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1155 foreach ($this->_memTypeSelected
as $memType) {
1156 if (array_key_exists('max_related', $formValues)) {
1157 // max related memberships - take from form or inherit from membership type
1158 $membershipTypeValues[$memType]['max_related'] = $formValues['max_related'] ??
NULL;
1160 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1166 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1167 [$userName] = CRM_Contact_BAO_Contact_Location
::getEmailDetails(CRM_Core_Session
::getLoggedInContactID());
1169 //CRM-13981, allow different person as a soft-contributor of chosen type
1170 if ($this->_contributorContactID
!= $this->_contactID
) {
1171 $params['contribution_contact_id'] = $this->_contributorContactID
;
1172 if (!empty($formValues['soft_credit_type_id'])) {
1173 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1174 $softParams['contact_id'] = $this->_contactID
;
1178 $pendingMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1180 if (!empty($formValues['record_contribution'])) {
1181 $recordContribution = [
1183 'financial_type_id',
1184 'payment_instrument_id',
1186 'contribution_status_id',
1194 foreach ($recordContribution as $f) {
1195 $params[$f] = $formValues[$f] ??
NULL;
1198 if (empty($formValues['source'])) {
1199 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', [
1200 1 => $this->getSelectedMembershipLabels(),
1205 $params['contribution_source'] = $formValues['source'];
1208 $completedContributionStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1209 if (empty($params['is_override']) &&
1210 CRM_Utils_Array
::value('contribution_status_id', $params) != $completedContributionStatusId
1212 $params['status_id'] = $pendingMembershipStatusId;
1213 $params['skipStatusCal'] = TRUE;
1214 $params['is_pay_later'] = 1;
1215 $this->assign('is_pay_later', 1);
1218 if (!empty($formValues['send_receipt'])) {
1219 $params['receipt_date'] = $formValues['receive_date'] ??
NULL;
1222 //insert financial type name in receipt.
1223 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1224 $formValues['financial_type_id']
1228 // process line items, until no previous line items.
1229 if (!empty($lineItem)) {
1230 $params['lineItems'] = $lineItem;
1231 $params['processPriceSet'] = TRUE;
1233 $createdMemberships = [];
1235 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1237 //CRM-20264 : Store CC type and number (last 4 digit) during backoffice or online payment
1238 $params['card_type_id'] = $this->_params
['card_type_id'] ??
NULL;
1239 $params['pan_truncation'] = $this->_params
['pan_truncation'] ??
NULL;
1241 if (!$isQuickConfig) {
1242 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1248 $params['financial_type_id'] = $formValues['financial_type_id'] ??
NULL;
1251 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
1252 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1253 $params['register_date'] = CRM_Utils_Time
::date('YmdHis');
1255 // add all the additional payment params we need
1256 $formValues['amount'] = $params['total_amount'];
1257 // @todo this is a candidate for beginPostProcessFunction.
1258 $formValues['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1259 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1260 $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
1261 $formValues['financial_type_id'] = $params['financial_type_id'];
1263 // at this point we've created a contact and stored its address etc
1264 // all the payment processors expect the name and address to be in the
1265 // so we copy stuff over to first_name etc.
1266 $paymentParams = $formValues;
1267 $paymentParams['contactID'] = $this->_contributorContactID
;
1268 //CRM-10377 if payment is by an alternate contact then we need to set that person
1269 // as the contact in the payment params
1270 if ($this->_contributorContactID
!= $this->_contactID
) {
1271 if (!empty($formValues['soft_credit_type_id'])) {
1272 $softParams['contact_id'] = $params['contact_id'];
1273 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1276 if (!empty($formValues['send_receipt'])) {
1277 $paymentParams['email'] = $this->_contributorEmail
;
1280 // This is a candidate for shared beginPostProcess function.
1281 // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
1282 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $formValues, $paymentParams, TRUE);
1283 // CRM-7137 -for recurring membership,
1284 // we do need contribution and recurring records.
1286 if (!empty($paymentParams['is_recur'])) {
1287 $this->_params
= $formValues;
1289 $contribution = $this->processContribution(
1292 'contact_id' => $this->_contributorContactID
,
1293 'line_item' => $lineItem,
1294 'is_test' => $this->isTest(),
1295 'campaign_id' => $paymentParams['campaign_id'] ??
NULL,
1296 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1297 'payment_instrument_id' => $paymentInstrumentID,
1298 'financial_type_id' => $params['financial_type_id'],
1302 //create new soft-credit record, CRM-13981
1304 $softParams['contribution_id'] = $contribution->id
;
1305 $softParams['currency'] = $contribution->currency
;
1306 $softParams['amount'] = $contribution->total_amount
;
1307 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1310 $paymentParams['contactID'] = $this->_contactID
;
1311 $paymentParams['contributionID'] = $contribution->id
;
1312 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1313 $params['contribution_id'] = $paymentParams['contributionID'];
1314 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1316 $paymentStatus = NULL;
1318 if ($params['total_amount'] > 0.0) {
1319 $payment = $this->_paymentProcessor
['object'];
1321 $result = $payment->doPayment($paymentParams);
1322 $formValues = array_merge($formValues, $result);
1323 $paymentStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
1324 // Assign amount to template if payment was successful.
1325 $this->assign('amount', $params['total_amount']);
1327 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
1328 if (!empty($paymentParams['contributionID'])) {
1329 CRM_Contribute_BAO_Contribution
::failPayment($paymentParams['contributionID'], $this->_contactID
,
1332 if (!empty($paymentParams['contributionRecurID'])) {
1333 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1336 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
1337 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1338 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
1344 if ($paymentStatus !== 'Completed') {
1345 $params['status_id'] = $pendingMembershipStatusId;
1346 $params['skipStatusCal'] = TRUE;
1347 // unset send-receipt option, since receipt will be sent when ipn is received.
1348 unset($formValues['send_receipt'], $formValues['send_receipt']);
1349 //as membership is pending set dates to null.
1350 foreach ($this->_memTypeSelected
as $memType) {
1351 $membershipTypeValues[$memType]['joinDate'] = NULL;
1352 $membershipTypeValues[$memType]['startDate'] = NULL;
1353 $membershipTypeValues[$memType]['endDate'] = NULL;
1355 $endDate = $startDate = NULL;
1357 $now = CRM_Utils_Time
::date('YmdHis');
1358 $params['receive_date'] = CRM_Utils_Time
::date('Y-m-d H:i:s');
1359 $params['invoice_id'] = $formValues['invoiceID'];
1360 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1361 [1 => $this->getSelectedMembershipLabels(), 2 => $userName]
1363 $params['source'] = $formValues['source'] ?
: $params['contribution_source'];
1364 $params['trxn_id'] = $result['trxn_id'] ??
NULL;
1365 $params['is_test'] = $this->isTest();
1366 if (!empty($formValues['send_receipt'])) {
1367 $params['receipt_date'] = $now;
1370 $params['receipt_date'] = NULL;
1373 $this->set('params', $formValues);
1374 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1375 $this->assign('receive_date',
1376 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1379 // required for creating membership for related contacts
1380 $params['action'] = $this->_action
;
1382 //create membership record.
1384 foreach ($this->_memTypeSelected
as $memType) {
1386 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1388 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1391 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1393 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1394 $membershipParams['soft_credit'] = $softParams;
1396 if (isset($result['fee_amount'])) {
1397 $membershipParams['fee_amount'] = $result['fee_amount'];
1399 // This is required to trigger the recording of the membership contribution in the
1400 // CRM_Member_BAO_Membership::Create function.
1401 // @todo stop setting this & 'teach' the create function to respond to something
1402 // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
1404 // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
1405 $membershipParams['contribution_status_id'] = $result['payment_status_id'] ??
NULL;
1406 if (!empty($paymentParams['is_recur'])) {
1407 // The earlier process created the line items (although we want to get rid of the earlier one in favour
1408 // of a single path!
1409 unset($membershipParams['lineItems']);
1411 $membershipParams['payment_instrument_id'] = $paymentInstrumentID;
1412 // @todo stop passing $ids (membership and userId only are set above)
1413 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1414 $params['contribution'] = $membershipParams['contribution'] ??
NULL;
1415 unset($params['lineItems']);
1416 $this->_membershipIDs
[] = $membership->id
;
1417 $createdMemberships[$memType] = $membership;
1423 $params['action'] = $this->_action
;
1424 foreach ($lineItem[$this->_priceSetId
] as $id => $lineItemValues) {
1425 if (empty($lineItemValues['membership_type_id'])) {
1429 // @todo figure out why recieve_date isn't being set right here.
1430 if (empty($params['receive_date'])) {
1431 $params['receive_date'] = CRM_Utils_Time
::date('Y-m-d H:i:s');
1433 $membershipParams = array_merge($params, $membershipTypeValues[$lineItemValues['membership_type_id']]);
1435 if (!empty($softParams)) {
1436 $membershipParams['soft_credit'] = $softParams;
1438 unset($membershipParams['contribution_status_id']);
1439 $membershipParams['skipLineItem'] = TRUE;
1440 unset($membershipParams['lineItems']);
1441 // @todo stop passing $ids (membership and userId only are set above)
1442 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1443 $lineItem[$this->_priceSetId
][$id]['entity_id'] = $membership->id
;
1444 $lineItem[$this->_priceSetId
][$id]['entity_table'] = 'civicrm_membership';
1446 $this->_membershipIDs
[] = $membership->id
;
1447 $createdMemberships[$membership->membership_type_id
] = $membership;
1449 $params['lineItems'] = $lineItem;
1450 if (!empty($formValues['record_contribution'])) {
1451 CRM_Member_BAO_Membership
::recordMembershipContribution($params);
1454 $isRecur = $params['is_recur'] ??
NULL;
1455 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1456 $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
1458 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1459 $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $createdMemberships,
1460 $isRecur, $calcDates));
1463 // This would always be true as we always add price set id into both
1464 // quick config & non quick config price sets.
1465 if (!empty($lineItem[$this->_priceSetId
])) {
1466 $invoicing = Civi
::settings()->get('invoicing');
1468 $totalTaxAmount = 0;
1469 foreach ($lineItem[$this->_priceSetId
] as & $priceFieldOp) {
1470 if (!empty($priceFieldOp['membership_type_id'])) {
1471 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date
::formatDateOnlyLong($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date']) : '-';
1472 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date
::formatDateOnlyLong($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date']) : '-';
1475 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1477 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1479 $totalTaxAmount +
= $priceFieldOp['tax_amount'];
1484 foreach ($lineItem[$this->_priceSetId
] as $key => $value) {
1485 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1486 if (isset($dataArray[$value['tax_rate']])) {
1487 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1490 $dataArray[$value['tax_rate']] = $value['tax_amount'] ??
NULL;
1495 $this->assign('totalTaxAmount', $totalTaxAmount);
1496 // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
1497 $this->assign('taxTerm', $this->getSalesTaxTerm());
1499 $this->assign('dataArray', $dataArray);
1502 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1504 $receiptSend = FALSE;
1505 $contributionId = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
);
1506 $membershipIds = $this->_membershipIDs
;
1507 if ($contributionId && !empty($membershipIds)) {
1508 $contributionDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails(
1509 CRM_Export_Form_Select
::MEMBER_EXPORT
, $this->_membershipIDs
);
1510 if ($contributionDetails[$membership->id
]['contribution_status'] === 'Completed') {
1511 $receiptSend = TRUE;
1515 $receiptSent = FALSE;
1516 if (!empty($formValues['send_receipt']) && $receiptSend) {
1517 $formValues['contact_id'] = $this->_contactID
;
1518 $formValues['contribution_id'] = $contributionId;
1519 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1520 // handled in the receipt. But by setting one we avoid breaking templates for now
1521 // although at some point we should switch in the templates.
1522 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1523 // send email receipt
1524 $this->assignBillingName();
1525 $mailSend = $this->emailMembershipReceipt($formValues, $membership);
1526 $receiptSent = TRUE;
1529 // finally set membership id if already not set
1531 $this->_id
= $membership->id
;
1534 $this->updateContributionOnMembershipTypeChange($params, $membership);
1535 if ($receiptSent && $mailSend) {
1536 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail
]));
1539 CRM_Core_Session
::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1540 $this->setStatusMessage($membership);
1544 * Update related contribution of a membership if update_contribution_on_membership_type_change
1545 * contribution setting is enabled and type is changed on edit
1547 * @param array $inputParams
1548 * submitted form values
1549 * @param CRM_Member_DAO_Membership $membership
1550 * Updated membership object
1552 * @throws \CRM_Core_Exception
1553 * @throws \CiviCRM_API3_Exception
1555 protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
1556 if (Civi
::settings()->get('update_contribution_on_membership_type_change') &&
1558 ($this->_action
& CRM_Core_Action
::UPDATE
) &&
1561 // if selected membership doesn't match with earlier membership
1562 !in_array($this->_memType
, $this->_memTypeSelected
)
1564 if (!empty($inputParams['is_recur'])) {
1565 CRM_Core_Session
::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
1569 // fetch lineitems by updated membership ID
1570 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($membership->id
, 'membership');
1571 // retrieve the related contribution ID
1572 $contributionID = CRM_Core_DAO
::getFieldValue(
1573 'CRM_Member_DAO_MembershipPayment',
1578 // get price fields of chosen price-set
1579 $priceSetDetails = CRM_Utils_Array
::value(
1581 CRM_Price_BAO_PriceSet
::getSetDetail(
1588 // add price field information in $inputParams
1589 self
::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id
);
1591 // update related contribution and financial records
1592 CRM_Price_BAO_LineItem
::changeFeeSelections(
1597 $priceSetDetails['fields'],
1600 CRM_Core_Session
::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1605 * Add selected price field information in $formValues
1607 * @param array $formValues
1608 * submitted form values
1609 * @param array $priceFields
1610 * Price fields of selected Priceset ID
1611 * @param int $membershipTypeID
1612 * Selected membership type ID
1615 public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
1616 foreach ($priceFields as $priceFieldID => $priceField) {
1617 if (isset($priceField['options']) && count($priceField['options'])) {
1618 foreach ($priceField['options'] as $option) {
1619 if ($option['membership_type_id'] == $membershipTypeID) {
1620 $formValues["price_{$priceFieldID}"] = $option['id'];
1629 * Set context in session.
1631 protected function setUserContext() {
1632 $buttonName = $this->controller
->getButtonName();
1633 $session = CRM_Core_Session
::singleton();
1635 if ($buttonName == $this->getButtonName('upload', 'new')) {
1636 if ($this->_context
=== 'standalone') {
1637 $url = CRM_Utils_System
::url('civicrm/member/add',
1638 'reset=1&action=add&context=standalone'
1642 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
1643 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1648 $url = CRM_Utils_System
::url('civicrm/contact/view',
1649 "reset=1&cid={$this->_contactID}&selectedChild=member"
1652 $session->replaceUserContext($url);
1656 * Get status message for updating membership.
1658 * @param CRM_Member_BAO_Membership $membership
1659 * @param string $endDate
1663 protected function getStatusMessageForUpdate($membership, $endDate) {
1664 // End date can be modified by hooks, so if end date is set then use it.
1665 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1667 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName
]);
1668 if ($endDate && $endDate !== 'null') {
1669 $endDate = CRM_Utils_Date
::customFormat($endDate);
1670 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
1676 * Get status message for create action.
1678 * @param string $endDate
1679 * @param array $createdMemberships
1680 * @param bool $isRecur
1681 * @param array $calcDates
1683 * @return array|string
1685 protected function getStatusMessageForCreate($endDate, $createdMemberships,
1686 $isRecur, $calcDates) {
1687 // FIX ME: fix status messages
1690 foreach ($this->_memTypeSelected
as $membershipTypeID) {
1691 $statusMsg[$membershipTypeID] = ts('%1 membership for %2 has been added.', [
1692 1 => $this->allMembershipTypeDetails
[$membershipTypeID]['name'],
1693 2 => $this->_memberDisplayName
,
1696 $membership = $createdMemberships[$membershipTypeID];
1697 $memEndDate = $membership->end_date ?
: $endDate;
1699 //get the end date from calculated dates.
1700 if (!$memEndDate && !$isRecur) {
1701 $memEndDate = $calcDates[$membershipTypeID]['end_date'] ??
NULL;
1704 if ($memEndDate && $memEndDate !== 'null') {
1705 $memEndDate = CRM_Utils_Date
::formatDateOnlyLong($memEndDate);
1706 $statusMsg[$membershipTypeID] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
1709 $statusMsg = implode('<br/>', $statusMsg);
1714 * @param $membership
1716 protected function setStatusMessage($membership) {
1718 // display message when membership type is changed
1719 if (($this->_action
& CRM_Core_Action
::UPDATE
) && $this->_id
&& !in_array($this->_memType
, $this->_memTypeSelected
)) {
1720 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'membership');
1721 $maxID = max(array_keys($lineItem));
1722 $lineItem = $lineItem[$maxID];
1723 $membershipTypeDetails = $this->allMembershipTypeDetails
[$membership->membership_type_id
];
1724 if ($membershipTypeDetails['financial_type_id'] != $lineItem['financial_type_id']) {
1725 CRM_Core_Session
::setStatus(
1726 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.'),
1730 if ($membershipTypeDetails['minimum_fee'] != $lineItem['line_total']) {
1731 CRM_Core_Session
::setStatus(
1732 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.'),
1741 * @throws \CRM_Core_Exception
1743 protected function isUpdateToExistingRecurringMembership() {
1745 if ($this->_action
& CRM_Core_Action
::UPDATE
1746 && CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
1747 'contribution_recur_id')
1748 && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->getEntityId())) {
1756 * Send a receipt for the membership.
1758 * @param array $formValues
1759 * @param \CRM_Member_BAO_Membership $membership
1762 * @throws \CRM_Core_Exception
1764 protected function emailMembershipReceipt($formValues, $membership) {
1765 $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
1766 $this->assign('customValues', $customValues);
1768 return self
::emailReceipt($this, $formValues, $membership);
1772 * Filter the custom values from the input parameters (for display in the email).
1774 * @todo figure out why the scary code this calls does & document.
1776 * @param array $formValues
1777 * @param \CRM_Member_BAO_Membership $membership
1780 protected function getCustomValuesForReceipt($formValues, $membership) {
1781 $customFields = $customValues = [];
1782 if (property_exists($this, '_groupTree')
1783 && !empty($this->_groupTree
)
1785 foreach ($this->_groupTree
as $groupID => $group) {
1786 if ($groupID === 'info') {
1789 foreach ($group['fields'] as $k => $field) {
1790 $field['title'] = $field['label'];
1791 $customFields["custom_{$k}"] = $field;
1796 $members = [['member_id', '=', $membership->id
, 0, 0]];
1797 // check whether its a test drive
1798 if ($this->_mode
=== 'test') {
1799 $members[] = ['member_test', '=', 1, 0, 0];
1802 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1803 return $customValues;
1807 * Get the selected memberships as a string of labels.
1811 protected function getSelectedMembershipLabels(): string {
1813 foreach ($this->_memTypeSelected
as $membershipTypeID) {
1814 $return[] = $this->allMembershipTypeDetails
[$membershipTypeID]['name'];
1816 return implode(', ', $return);
1820 * Legacy contribution processing function.
1822 * This is copied from a shared function in order to clean it up. Most of the
1823 * stuff in it, maybe all except the ContributionRecur create is
1824 * not applicable to this form & can be removed in follow up cleanup.
1826 * It's like the contribution create being done here is actively bad and
1827 * being fixed later.
1829 * @param array $params
1830 * @param array $contributionParams
1831 * Parameters to be passed to contribution create action.
1832 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1833 * passed consistently & 2) documenting them here.
1841 * @return \CRM_Contribute_DAO_Contribution
1843 * @throws \CRM_Core_Exception
1844 * @throws \CiviCRM_API3_Exception
1846 protected function processContribution(
1851 $transaction = new CRM_Core_Transaction();
1852 $contactID = $contributionParams['contact_id'];
1854 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
1856 // add these values for the recurringContrib function ,CRM-10188
1857 $params['financial_type_id'] = $contributionParams['financial_type_id'];
1859 //@todo - this is being set from the form to resolve CRM-10188 - an
1860 // eNotice caused by it not being set @ the front end
1861 // however, we then get it being over-written with null for backend contributions
1862 // a better fix would be to set the values in the respective forms rather than require
1863 // a function being shared by two forms to deal with their respective values
1864 // moving it to the BAO & not taking the $form as a param would make sense here.
1865 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1866 $params['is_email_receipt'] = $isEmailReceipt;
1868 $params['is_recur'] = TRUE;
1869 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ??
NULL;
1870 $recurringContributionID = $this->legacyProcessRecurringContribution($params, $contactID);
1872 $now = CRM_Utils_Time
::date('YmdHis');
1873 $receiptDate = $params['receipt_date'] ??
NULL;
1874 if ($isEmailReceipt) {
1875 $receiptDate = $now;
1878 if (isset($params['amount'])) {
1879 $contributionParams = array_merge([
1880 'receive_date' => !empty($params['receive_date']) ? CRM_Utils_Date
::processDate($params['receive_date']) : CRM_Utils_Time
::date('YmdHis'),
1881 'tax_amount' => $params['tax_amount'] ??
NULL,
1882 'invoice_id' => $params['invoiceID'],
1883 'currency' => $params['currencyID'],
1884 'is_pay_later' => $params['is_pay_later'] ??
0,
1885 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
1886 'skipLineItem' => $params['skipLineItem'] ??
0,
1887 ], $contributionParams);
1889 if (!empty($params["is_email_receipt"])) {
1890 $contributionParams +
= [
1891 'receipt_date' => $receiptDate,
1895 if ($recurringContributionID) {
1896 $contributionParams['contribution_recur_id'] = $recurringContributionID;
1899 $contributionParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1901 // @todo this is the wrong place for this - it should be done as close to form submission
1903 $contributionParams['total_amount'] = $params['amount'];
1904 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
1906 // lets store it in the form variable so postProcess hook can get to this and use it
1907 $form->_contributionID
= $contribution->id
;
1910 // process soft credit / pcp params first
1911 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
1913 //CRM-13981, processing honor contact into soft-credit contribution
1914 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
1916 $transaction->commit();
1917 return $contribution;
1921 * Create the recurring contribution record.
1923 * This function was copied from another form & needs cleanup.
1925 * @param array $params
1926 * @param int $contactID
1930 protected function legacyProcessRecurringContribution(array $params, $contactID): int {
1932 $recurParams = ['contact_id' => $contactID];
1933 $recurParams['amount'] = $params['amount'] ??
NULL;
1934 $recurParams['auto_renew'] = $params['auto_renew'] ??
NULL;
1935 $recurParams['frequency_unit'] = $params['frequency_unit'] ??
NULL;
1936 $recurParams['frequency_interval'] = $params['frequency_interval'] ??
NULL;
1937 $recurParams['installments'] = $params['installments'] ??
NULL;
1938 $recurParams['financial_type_id'] = $params['financial_type_id'];
1939 $recurParams['currency'] = $params['currency'] ??
NULL;
1940 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1942 $recurParams['is_test'] = $this->isTest();
1944 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = CRM_Utils_Time
::date('YmdHis');
1945 if (!empty($params['receive_date'])) {
1946 $recurParams['start_date'] = date('YmdHis', CRM_Utils_Time
::strtotime($params['receive_date']));
1948 $recurParams['invoice_id'] = $params['invoiceID'] ??
NULL;
1949 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1950 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ??
NULL;
1951 $recurParams['is_email_receipt'] = (bool) ($params['is_email_receipt'] ??
FALSE);
1952 // we need to add a unique trxn_id to avoid a unique key error
1953 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1954 $recurParams['trxn_id'] = $params['trxn_id'] ??
$params['invoiceID'];
1956 $campaignId = $params['campaign_id'] ??
$this->_values
['campaign_id'] ??
NULL;
1957 $recurParams['campaign_id'] = $campaignId;
1958 return CRM_Contribute_BAO_ContributionRecur
::add($recurParams)->id
;
1962 * Is the form being submitted in test mode.
1966 protected function isTest(): int {
1967 return ($this->_mode
=== 'test') ?
TRUE : FALSE;