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
18 use Civi\Api4\Contribution
;
21 * This class provides the functionality for batch entry for contributions/memberships.
23 class CRM_Batch_Form_Entry
extends CRM_Core_Form
{
26 * Maximum profile fields that will be displayed.
30 protected $_rowCount = 1;
44 protected $_batchInfo = [];
47 * Store the profile id associated with the batch type.
50 protected $_profileId;
59 * When not to reset sort_name.
63 protected $_preserveDefault = TRUE;
70 protected $_contactFields = [];
73 * Fields array of fields in the batch profile.
75 * (based on the uf_field table data)
76 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
77 * (although a future refactoring might hopefully change that so it uses the api & the function is not
87 protected $currentRowContributionID;
90 * Get the contribution id for the current row.
93 * @throws \CRM_Core_Exception
95 public function getCurrentRowContributionID(): int {
96 if (!isset($this->currentRowContributionID
)) {
97 $this->currentRowContributionID
= CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $this->getCurrentRowMembershipID(), 'contribution_id', 'membership_id');
99 return $this->currentRowContributionID
;
103 * Set the contribution ID for the current row.
105 * @param int $currentRowContributionID
107 public function setCurrentRowContributionID(int $currentRowContributionID): void
{
108 $this->currentRowContributionID
= $currentRowContributionID;
114 public function getCurrentRowMembershipID() {
115 return $this->currentRowMembershipID
;
119 * Set the membership id for the current row.
121 * @param int $currentRowMembershipID
123 public function setCurrentRowMembershipID(int $currentRowMembershipID): void
{
124 $this->currentRowMembershipID
= $currentRowMembershipID;
130 protected $currentRowMembershipID;
133 * Monetary fields that may be submitted.
135 * These should get a standardised format in the beginPostProcess function.
137 * These fields are common to many forms. Some may override this.
140 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
143 * Build all the data structures needed to build the form.
145 * @throws \CRM_Core_Exception
147 public function preProcess() {
148 $this->_batchId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
150 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'browse');
152 if (empty($this->_batchInfo
)) {
153 $params = ['id' => $this->_batchId
];
154 CRM_Batch_BAO_Batch
::retrieve($params, $this->_batchInfo
);
156 $this->assign('batchTotal', !empty($this->_batchInfo
['total']) ?
$this->_batchInfo
['total'] : NULL);
157 $this->assign('batchType', $this->_batchInfo
['type_id']);
159 // get the profile id associted with this batch type
160 $this->_profileId
= CRM_Batch_BAO_Batch
::getProfileId($this->_batchInfo
['type_id']);
162 CRM_Core_Resources
::singleton()
163 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
164 ->addSetting(['batch' => ['type_id' => $this->_batchInfo
['type_id']]])
165 ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config
::singleton()->monetaryThousandSeparator
]])
166 ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config
::singleton()->monetaryDecimalPoint
]]);
168 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country
::defaultCurrencySymbol());
176 public function setBatchID($id) {
177 $this->_batchId
= $id;
181 * Build the form object.
183 * @throws \CRM_Core_Exception
185 public function buildQuickForm() {
186 if (!$this->_profileId
) {
187 CRM_Core_Error
::statusBounce(ts('Profile for bulk data entry is missing.'));
190 $this->addElement('hidden', 'batch_id', $this->_batchId
);
192 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
193 // get the profile information
194 if ($this->_batchInfo
['type_id'] == $batchTypes['Contribution']) {
195 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Contributions'));
197 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
198 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Memberships'));
200 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
201 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Pledge Payments'));
204 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($this->_profileId
, FALSE, CRM_Core_Action
::VIEW
);
206 // remove file type field and then limit fields
207 $suppressFields = FALSE;
208 foreach ($this->_fields
as $name => $field) {
209 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name) && $this->_fields
[$name]['html_type'] == 'Autocomplete-Select') {
210 $suppressFields = TRUE;
211 unset($this->_fields
[$name]);
214 //fix to reduce size as we are using this field in grid
215 if (is_array($field['attributes']) && $this->_fields
[$name]['attributes']['size'] > 19) {
216 //shrink class to "form-text-medium"
217 $this->_fields
[$name]['attributes']['size'] = 19;
221 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
223 // add the force save button
224 $forceSave = $this->getButtonName('upload', 'force');
226 $this->addElement('xbutton',
228 ts('Ignore Mismatch & Process the Batch?'),
232 'class' => 'crm-button crm-button_qf_Entry_upload_force-save',
239 'name' => ts('Validate & Process the Batch'),
244 'name' => ts('Save & Continue Later'),
248 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
250 $preserveDefaultsArray = [
258 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
259 $contactReturnProperties = [];
261 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
262 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
264 'placeholder' => ts('- select -'),
267 // special field specific to membership batch udpate
268 if ($this->_batchInfo
['type_id'] == 2) {
270 1 => ts('Add Membership'),
271 2 => ts('Renew Membership'),
273 $this->add('select', "member_option[$rowNumber]", '', $options);
275 if ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
276 $options = ['' => '-select-'];
278 '1' => ts('Adjust Pledge Payment Schedule?'),
279 '2' => ts('Adjust Total Pledge Amount?'),
281 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
282 if (!empty($this->_batchId
) && !empty($this->_batchInfo
['data']) && !empty($rowNumber)) {
283 $dataValues = json_decode($this->_batchInfo
['data'], TRUE);
284 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
285 $pledgeIDs = CRM_Pledge_BAO_Pledge
::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
286 foreach ($pledgeIDs as $pledgeID) {
287 $pledgePayment = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeID);
288 $options +
= [$pledgeID => CRM_Utils_Date
::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
293 $this->add('select', "open_pledges[$rowNumber]", '', $options);
296 foreach ($this->_fields
as $name => $field) {
297 if (in_array($field['field_type'], $contactTypes)) {
298 $fld = explode('-', $field['name']);
299 $contactReturnProperties[$field['name']] = $fld[0];
301 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
303 if (in_array($field['name'], $preserveDefaultsArray)) {
304 $this->_preserveDefault
= FALSE;
309 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
310 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
311 // An offset value is set to deal with additional vars that are likely passed.
312 // There may be a more accurate way to do this...
313 // set an offset to account for other vars we are not counting
315 if ((count($this->_elementIndex
) +
$offset) > ini_get("max_input_vars")) {
316 // Avoiding 'ts' for obscure messages.
317 CRM_Core_Error
::statusBounce('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = ' . ini_get("max_input_vars") . ')');
320 $this->assign('fields', $this->_fields
);
321 CRM_Core_Resources
::singleton()
324 'return' => implode(',', $contactReturnProperties),
325 'fieldmap' => array_flip($contactReturnProperties),
329 // don't set the status message when form is submitted.
330 $buttonName = $this->controller
->getButtonName('submit');
332 if ($suppressFields && $buttonName != '_qf_Entry_next') {
333 CRM_Core_Session
::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple records."), ts('Some Fields Excluded'), 'info');
340 * @param array $params
341 * Posted values of the form.
342 * @param array $files
343 * List of errors to be posted back to the form.
344 * @param \CRM_Batch_Form_Entry $self
348 * list of errors to be posted back to the form
350 public static function formRule($params, $files, $self) {
352 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
354 'total_amount' => ts('Amount'),
355 'financial_type' => ts('Financial Type'),
356 'payment_instrument' => ts('Payment Method'),
359 //CRM-16480 if contact is selected, validate financial type and amount field.
360 foreach ($params['field'] as $key => $value) {
361 if (isset($value['trxn_id'])) {
362 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
363 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
366 foreach ($fields as $field => $label) {
367 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
368 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
373 if (!empty($params['_qf_Entry_upload_force'])) {
374 if (!empty($errors)) {
381 foreach ($params['field'] as $key => $value) {
382 $batchTotal +
= $value['total_amount'];
384 //validate for soft credit fields
385 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
386 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
388 if (!empty($params['soft_credit_amount']) && !empty($params['soft_credit_amount'][$key]) && CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value($key, $params['soft_credit_amount'])) > CRM_Utils_Rule
::cleanMoney($value['total_amount'])) {
389 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
392 //membership type is required for membership batch entry
393 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
394 if (empty($value['membership_type'][1])) {
395 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
399 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
400 foreach (array_unique($params["open_pledges"]) as $value) {
401 if (!empty($value)) {
402 $duplicateRows = array_keys($params["open_pledges"], $value);
404 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
405 foreach ($duplicateRows as $key) {
406 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
411 if ((string) $batchTotal != $self->_batchInfo
['total']) {
412 $self->assign('batchAmountMismatch', TRUE);
413 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
416 if (!empty($errors)) {
420 $self->assign('batchAmountMismatch', FALSE);
425 * Override default cancel action.
427 public function cancelAction() {
428 // redirect to batch listing
429 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
430 CRM_Utils_System
::civiExit();
434 * Set default values for the form.
436 * @throws \CRM_Core_Exception
438 public function setDefaultValues() {
439 if (empty($this->_fields
)) {
443 // for add mode set smart defaults
444 if ($this->_action
& CRM_Core_Action
::ADD
) {
445 $currentDate = date('Y-m-d H-i-s');
447 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
449 'membership_join_date' => date('Y-m-d'),
450 'receive_date' => $currentDate,
451 'contribution_status_id' => $completeStatus,
454 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
455 foreach ($specialFields as $key => $value) {
456 $defaults['field'][$rowNumber][$key] = $value;
461 // get the cached info from data column of civicrm_batch
462 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
463 $defaults = json_decode($data, TRUE);
464 $defaults = $defaults['values'];
471 * Process the form after the input has been submitted and validated.
473 * @throws \CRM_Core_Exception
474 * @throws \CiviCRM_API3_Exception
476 public function postProcess() {
477 $params = $this->controller
->exportValues($this->_name
);
478 $params['actualBatchTotal'] = 0;
480 // get the profile information
481 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
482 if (in_array($this->_batchInfo
['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
483 $this->processContribution($params);
485 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
486 $params['actualBatchTotal'] = $this->processMembership($params);
489 // update batch to close status
491 'id' => $this->_batchId
,
493 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
494 'total' => $params['actualBatchTotal'],
497 CRM_Batch_BAO_Batch
::create($paramValues);
499 // set success status
500 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
502 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
506 * Process contribution records.
508 * @param array $params
509 * Associated array of submitted values.
513 * @throws \CRM_Core_Exception
514 * @throws \CiviCRM_API3_Exception
516 private function processContribution(&$params) {
518 foreach ($this->submittableMoneyFields
as $moneyField) {
519 foreach ($params['field'] as $index => $fieldValues) {
520 if (isset($fieldValues[$moneyField])) {
521 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
525 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
526 // get the price set associated with offline contribution record.
527 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
528 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
529 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
530 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
532 if (isset($params['field'])) {
533 foreach ($params['field'] as $key => $value) {
534 // if contact is not selected we should skip the row
535 if (empty($params['primary_contact_id'][$key])) {
539 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
541 // update contact information
542 $this->updateContactInfo($value);
544 //build soft credit params
545 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
546 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
547 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
549 //CRM-15350: if soft-credit-type profile field is disabled or removed then
550 //we choose configured SCT default value
551 if (!empty($params['soft_credit_type'][$key])) {
552 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
555 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
560 if (!empty($params['pcp_made_through_id'][$key])) {
561 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
562 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
563 if (!empty($params['pcp_roll_nickname'][$key])) {
564 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
566 if (!empty($params['pcp_personal_note'][$key])) {
567 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
571 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
576 if (!empty($value['send_receipt'])) {
577 $value['receipt_date'] = date('Y-m-d His');
579 // these translations & date handling are required because we are calling BAO directly rather than the api
580 $fieldTranslations = [
581 'financial_type' => 'financial_type_id',
582 'payment_instrument' => 'payment_instrument_id',
583 'contribution_source' => 'source',
584 'contribution_note' => 'note',
585 'contribution_check_number' => 'check_number',
587 foreach ($fieldTranslations as $formField => $baoField) {
588 if (isset($value[$formField])) {
589 $value[$baoField] = $value[$formField];
591 unset($value[$formField]);
594 $params['actualBatchTotal'] +
= $value['total_amount'];
595 $value['batch_id'] = $this->_batchId
;
596 $value['skipRecentView'] = TRUE;
598 // build line item params
599 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
600 $value['price_' . $priceFieldID] = 1;
603 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
605 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
606 // function to get correct amount level consistently. Remove setting of the amount level in
607 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
608 // to cover all variants.
609 unset($value['amount_level']);
611 //CRM-11529 for back office transactions
612 //when financial_type_id is passed in form, update the
613 //line items with the financial type selected in form
614 // @todo - create a price set or price field per financial type & simply choose the appropriate
615 // price field rather than working around the fact that each price_field is supposed to have a financial
616 // type & we are allowing that to be overridden.
617 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
618 foreach ($lineItem[$priceSetId] as &$values) {
619 $values['financial_type_id'] = $value['financial_type_id'];
622 $value['line_item'] = $lineItem;
624 //finally call contribution create for all the magic
625 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
626 // This code to retrieve the contribution has been moved here from the contribution create
627 // api. It may not be required.
634 $retrieveRequired = 0;
635 foreach ($titleFields as $titleField) {
636 if (!isset($contribution->$titleField)) {
637 $retrieveRequired = 1;
641 if ($retrieveRequired == 1) {
642 $contribution->find(TRUE);
644 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
645 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
646 $adjustTotalAmount = FALSE;
647 if (isset($params['option_type'][$key])) {
648 if ($params['option_type'][$key] == 2) {
649 $adjustTotalAmount = TRUE;
652 $pledgeId = $params['open_pledges'][$key];
653 if (is_numeric($pledgeId)) {
654 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
655 $pledgePaymentId = 0;
656 foreach ($result as $key => $values) {
657 if ($values['status'] != 'Completed') {
658 $pledgePaymentId = $values['id'];
662 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
663 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
665 $contribution->contribution_status_id
,
667 $contribution->total_amount
,
674 if (!empty($value['product_name'])) {
675 if ($value['product_name'][0] > 0) {
676 [$products, $options] = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
678 $value['hidden_Premium'] = 1;
679 $value['product_option'] = CRM_Utils_Array
::value(
680 $value['product_name'][1],
681 $options[$value['product_name'][0]]
685 'product_id' => $value['product_name'][0],
686 'contribution_id' => $contribution->id
,
687 'product_option' => $value['product_option'],
690 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
696 if ($contribution->id
&& !empty($value['send_receipt'])) {
697 $value['from_email_address'] = $this->getFromEmailAddress();
698 $value['contribution_id'] = $contribution->id
;
699 if (!empty($value['soft_credit'])) {
700 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
702 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
710 * Process membership records.
712 * @param array $params
713 * Array of submitted values.
716 * batch total monetary amount.
718 * @throws \CRM_Core_Exception
719 * @throws \CiviCRM_API3_Exception
720 * @throws \API_Exception
722 private function processMembership(array $params) {
724 // get the price set associated with offline membership
725 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
726 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
728 if (isset($params['field'])) {
729 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
730 foreach ($params['field'] as $key => $value) {
731 // if contact is not selected we should skip the row
732 if (empty($params['primary_contact_id'][$key])) {
735 $value['contact_id'] = $params['primary_contact_id'][$key];
736 foreach ($value as $fieldKey => $fieldValue) {
737 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
738 $value[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
741 $value = $this->standardiseRow($value);
743 // update contact information
744 $this->updateContactInfo($value);
746 //check for custom data
747 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
750 $value['membership_type_id']
753 // handle soft credit
754 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
755 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
756 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
758 //CRM-15350: if soft-credit-type profile field is disabled or removed then
759 //we choose Gift as default value as per Gift Membership rule
760 if (!empty($params['soft_credit_type'][$key])) {
761 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
764 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
767 $batchTotal +
= $value['total_amount'];
768 $value['batch_id'] = $this->_batchId
;
769 $value['skipRecentView'] = TRUE;
771 $order = new CRM_Financial_BAO_Order();
772 // We use the override total amount because we are dealing with a
773 // possibly tax_inclusive total, which is assumed for the override total.
774 $order->setOverrideTotalAmount($value['total_amount']);
775 $order->setLineItem([
776 'membership_type_id' => $value['membership_type_id'],
777 'financial_type_id' => $value['financial_type_id'],
780 if (!empty($order->getLineItems())) {
781 $value['lineItems'] = [$order->getPriceSetID() => $order->getPriceFieldIndexedLineItems()];
782 $value['processPriceSet'] = TRUE;
784 // end of contribution related section
786 $membershipParams = [
787 'start_date' => $value['membership_start_date'] ??
NULL,
788 'end_date' => $value['membership_end_date'] ??
NULL,
789 'join_date' => $value['membership_join_date'] ??
NULL,
790 'campaign_id' => $value['member_campaign_id'] ??
NULL,
792 $value['is_renew'] = FALSE;
793 if (!empty($params['member_option']) && CRM_Utils_Array
::value($key, $params['member_option']) == 2) {
795 // The following parameter setting may be obsolete.
796 $this->_params
= $params;
797 $value['is_renew'] = TRUE;
800 'end_date' => $value['membership_end_date'] ??
NULL,
801 'start_date' => $value['membership_start_date'] ??
NULL,
803 $membershipSource = $value['source'] ??
NULL;
804 $membership = $this->legacyProcessMembership(
805 $value['contact_id'], $value['membership_type_id'],
806 $value['custom'], $membershipSource, ['campaign_id' => $value['member_campaign_id'] ??
NULL], $formDates
809 // make contribution entry
810 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id
]);
811 $contrbutionParams['skipCleanMoney'] = TRUE;
812 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
813 // This form should set the correct params & not call this fn directly.
814 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
815 $this->setCurrentRowMembershipID($membership->id
);
818 // @todo - specify the relevant fields - don't copy all over
819 $membershipParams = array_merge($value, $membershipParams);
820 $membership = CRM_Member_BAO_Membership
::create($membershipParams);
824 if (!empty($value['product_name'])) {
825 if ($value['product_name'][0] > 0) {
826 [$products, $options] = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
828 $value['hidden_Premium'] = 1;
829 $value['product_option'] = CRM_Utils_Array
::value(
830 $value['product_name'][1],
831 $options[$value['product_name'][0]]
835 'product_id' => $value['product_name'][0],
836 'contribution_id' => $this->getCurrentRowContributionID(),
837 'product_option' => $value['product_option'],
840 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
846 if ($membership->id
&& !empty($value['send_receipt'])) {
847 $value['membership_id'] = $membership->id
;
848 $this->emailReceipt($this, $value, $membership);
856 * Send email receipt.
858 * @param CRM_Core_Form $form
860 * @param array $formValues
861 * @param object $membership
865 * true if mail was sent successfully
866 * @throws \CRM_Core_Exception|\API_Exception
869 * This function is shared with Batch_Entry which has limited overlap
870 * & needs rationalising.
873 protected function emailReceipt($form, &$formValues, $membership): bool {
874 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
875 if (!empty($formValues['payment_instrument_id'])) {
876 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
877 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
880 $form->assign('module', 'Membership');
881 $form->assign('contactID', $formValues['contact_id']);
883 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
884 $this->assign('contributionID', $this->getCurrentRowContributionID());
886 if (!empty($formValues['contribution_status_id'])) {
887 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
888 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
891 if (!empty($formValues['is_renew'])) {
892 $form->assign('receiptType', 'membership renewal');
895 $form->assign('receiptType', 'membership signup');
897 $form->assign('receive_date', CRM_Utils_Array
::value('receive_date', $formValues));
898 $form->assign('formValues', $formValues);
900 $form->assign('mem_start_date', CRM_Utils_Date
::formatDateOnlyLong($membership->start_date
));
901 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
902 $form->assign('mem_end_date', CRM_Utils_Date
::formatDateOnlyLong($membership->end_date
));
904 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
906 [$form->_contributorDisplayName
, $form->_contributorEmail
]
907 = CRM_Contact_BAO_Contact_Location
::getEmailDetails($formValues['contact_id']);
908 $form->_receiptContactId
= $formValues['contact_id'];
910 CRM_Core_BAO_MessageTemplate
::sendTemplate(
912 'groupName' => 'msg_tpl_workflow_membership',
913 'valueName' => 'membership_offline_receipt',
914 'contactId' => $form->_receiptContactId
,
915 'from' => $this->getFromEmailAddress(),
916 'toName' => $form->_contributorDisplayName
,
917 'toEmail' => $form->_contributorEmail
,
918 'PDFFilename' => ts('receipt') . '.pdf',
919 'isEmailPdf' => Civi
::settings()->get('invoicing') && Civi
::settings()->get('invoice_is_email_pdf'),
920 'contributionId' => $this->getCurrentRowContributionID(),
921 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
925 Contribution
::update(FALSE)
926 ->addWhere('id', '=', $this->getCurrentRowContributionID())
927 ->setValues(['receipt_date', 'now'])
934 * Update contact information.
936 * @param array $value
937 * Associated array of submitted values.
939 private function updateContactInfo(array &$value) {
940 $value['preserveDBName'] = $this->_preserveDefault
;
942 //parse street address, CRM-7768
943 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
945 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
951 * Function exists purely for unit testing purposes.
953 * If you feel tempted to use this in live code then it probably means there is some functionality
954 * that needs to be moved out of the form layer
956 * @param array $params
960 public function testProcessMembership($params) {
961 return $this->processMembership($params);
965 * Function exists purely for unit testing purposes.
967 * If you feel tempted to use this in live code then it probably means there is some functionality
968 * that needs to be moved out of the form layer.
970 * @param array $params
974 * @throws \CRM_Core_Exception
975 * @throws \CiviCRM_API3_Exception
977 public function testProcessContribution($params) {
978 return $this->processContribution($params);
982 * @param int $contactID
983 * @param int $membershipTypeID
984 * @param $customFieldsFormatted
985 * @param $membershipSource
987 * @param array $memParams
988 * @param array $formDates
990 * @return CRM_Member_BAO_Membership
992 * @throws \CRM_Core_Exception
993 * @throws \CiviCRM_API3_Exception
995 protected function legacyProcessMembership($contactID, $membershipTypeID, $customFieldsFormatted, $membershipSource, $memParams = [], $formDates = []): CRM_Member_BAO_Membership
{
996 $updateStatusId = FALSE;
1001 $membershipID = NULL;
1003 $contributionRecurID = NULL;
1004 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1006 $statusFormat = '%Y-%m-%d';
1007 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1011 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1012 // is the same as the parent org of an existing membership of the contact
1013 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1014 $is_test, $membershipID, TRUE
1016 if ($currentMembership) {
1018 // Do NOT do anything.
1019 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1020 //2. Paylater/IPN renew. CRM-4556.
1021 if ($pending ||
in_array($currentMembership['status_id'], [
1022 array_search('Pending', $allStatus),
1024 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1027 $memParams = array_merge([
1028 'id' => $currentMembership['id'],
1029 'status_id' => $currentMembership['status_id'],
1030 'start_date' => $currentMembership['start_date'],
1031 'end_date' => $currentMembership['end_date'],
1032 'join_date' => $currentMembership['join_date'],
1033 'membership_type_id' => $membershipTypeID,
1034 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1035 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1037 if ($contributionRecurID) {
1038 $memParams['contribution_recur_id'] = $contributionRecurID;
1041 return CRM_Member_BAO_Membership
::create($memParams);
1044 // Check and fix the membership if it is STALE
1045 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1047 // Now Renew the membership
1048 if (!$currentMembership['is_current_member']) {
1049 // membership is not CURRENT
1051 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1052 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1058 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1059 foreach (['start_date', 'end_date'] as $dateType) {
1060 $currentMembership[$dateType] = $formDates[$dateType] ??
NULL;
1061 if (empty($currentMembership[$dateType])) {
1062 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1065 $currentMembership['is_test'] = $is_test;
1067 if (!empty($membershipSource)) {
1068 $currentMembership['source'] = $membershipSource;
1071 if (!empty($currentMembership['id'])) {
1072 $ids['membership'] = $currentMembership['id'];
1074 $memParams = array_merge($currentMembership, $memParams);
1075 $memParams['membership_type_id'] = $membershipTypeID;
1077 //set the log start date.
1078 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1082 // CURRENT Membership
1083 $membership = new CRM_Member_DAO_Membership();
1084 $membership->id
= $currentMembership['id'];
1085 $membership->find(TRUE);
1086 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1087 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1093 // Insert renewed dates for CURRENT membership
1094 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1095 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date
::isoToMysql($membership->start_date
);
1096 $memParams['end_date'] = $formDates['end_date'] ??
NULL;
1097 if (empty($memParams['end_date'])) {
1098 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1100 $memParams['membership_type_id'] = $membershipTypeID;
1102 //set the log start date.
1103 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1106 if (!empty($membershipSource)) {
1107 $memParams['source'] = $membershipSource;
1109 elseif (empty($membership->source
)) {
1110 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1111 $currentMembership['id'],
1116 if (!empty($currentMembership['id'])) {
1117 $ids['membership'] = $currentMembership['id'];
1119 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1124 $memParams = array_merge([
1125 'contact_id' => $contactID,
1126 'membership_type_id' => $membershipTypeID,
1130 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1132 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1133 $memParams[$dateType] = $formDates[$dateType] ??
NULL;
1134 if (empty($memParams[$dateType])) {
1135 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1139 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1142 CRM_Utils_Date
::customFormat($dates['end_date'],
1145 CRM_Utils_Date
::customFormat($dates['join_date'],
1153 $updateStatusId = $status['id'] ??
NULL;
1156 // if IPN/Pay-Later set status to: PENDING
1157 $updateStatusId = array_search('Pending', $allStatus);
1160 if (!empty($membershipSource)) {
1161 $memParams['source'] = $membershipSource;
1163 $memParams['is_test'] = $is_test;
1164 $memParams['is_pay_later'] = $isPayLater;
1166 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1167 // perhaps shouldn't be?
1168 if ($contributionRecurID) {
1169 $memParams['contribution_recur_id'] = $contributionRecurID;
1172 //if we decided status here and want to skip status
1173 //calculation in create( ); then need to pass 'skipStatusCal'.
1174 if ($updateStatusId) {
1175 $memParams['status_id'] = $updateStatusId;
1176 $memParams['skipStatusCal'] = TRUE;
1179 //since we are renewing,
1180 //make status override false.
1181 $memParams['is_override'] = FALSE;
1183 //CRM-4027, create log w/ individual contact.
1185 // @todo this param is likely unused now.
1186 $memParams['is_for_organization'] = TRUE;
1188 $params['modified_id'] = $modifiedID ??
$contactID;
1190 $memParams['custom'] = $customFieldsFormatted;
1191 // Load all line items & process all in membership. Don't do in contribution.
1192 // Relevant tests in api_v3_ContributionPageTest.
1193 // @todo stop passing $ids (membership and userId may be set by this point)
1194 $membership = CRM_Member_BAO_Membership
::create($memParams, $ids);
1196 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1197 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1198 $membership->find(TRUE);
1205 * @throws \CRM_Core_Exception
1207 private function getFromEmailAddress(): string {
1208 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
1209 return "$domainEmail[0] <$domainEmail[1]>";
1213 * Standardise the values in the row from profile-weirdness to civi-standard.
1215 * The row uses odd field names such as financial_type rather than financial
1216 * type id. We standardise at this point.
1222 private function standardiseRow(array $row): array {
1223 $renameFieldMapping = [
1224 'financial_type' => 'financial_type_id',
1225 'payment_instrument' => 'payment_instrument_id',
1226 'membership_source' => 'source',
1227 'membership_status' => 'status_id',
1229 foreach ($renameFieldMapping as $weirdProfileName => $betterName) {
1230 // Check if isset as some like payment instrument and source are optional.
1231 if (isset($row[$weirdProfileName]) && empty($row[$betterName])) {
1232 $row[$betterName] = $row[$weirdProfileName];
1233 unset($row[$weirdProfileName]);
1237 // The latter format would be normal here - it's unclear if it is sometimes in the former format.
1238 $row['membership_type_id'] = $row['membership_type_id'] ??
$row['membership_type'][1];
1239 unset($row['membership_type']);
1240 // total_amount is required.
1241 $row['total_amount'] = (float) $row['total_amount'];