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 provides the functionality for batch entry for contributions/memberships.
21 class CRM_Batch_Form_Entry
extends CRM_Core_Form
{
24 * Maximum profile fields that will be displayed.
28 protected $_rowCount = 1;
42 protected $_batchInfo = [];
45 * Store the profile id associated with the batch type.
48 protected $_profileId;
57 * When not to reset sort_name.
61 protected $_preserveDefault = TRUE;
68 protected $_contactFields = [];
71 * Fields array of fields in the batch profile.
73 * (based on the uf_field table data)
74 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
75 * (although a future refactoring might hopefully change that so it uses the api & the function is not
83 * Monetary fields that may be submitted.
85 * These should get a standardised format in the beginPostProcess function.
87 * These fields are common to many forms. Some may override this.
90 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
93 * Build all the data structures needed to build the form.
95 * @throws \CRM_Core_Exception
97 public function preProcess() {
98 $this->_batchId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
100 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'browse');
102 if (empty($this->_batchInfo
)) {
103 $params = ['id' => $this->_batchId
];
104 CRM_Batch_BAO_Batch
::retrieve($params, $this->_batchInfo
);
106 $this->assign('batchTotal', !empty($this->_batchInfo
['total']) ?
$this->_batchInfo
['total'] : NULL);
107 $this->assign('batchType', $this->_batchInfo
['type_id']);
109 // get the profile id associted with this batch type
110 $this->_profileId
= CRM_Batch_BAO_Batch
::getProfileId($this->_batchInfo
['type_id']);
112 CRM_Core_Resources
::singleton()
113 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
114 ->addSetting(['batch' => ['type_id' => $this->_batchInfo
['type_id']]])
115 ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config
::singleton()->monetaryThousandSeparator
]])
116 ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config
::singleton()->monetaryDecimalPoint
]]);
118 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country
::defaultCurrencySymbol());
126 public function setBatchID($id) {
127 $this->_batchId
= $id;
131 * Build the form object.
133 * @throws \CRM_Core_Exception
135 public function buildQuickForm() {
136 if (!$this->_profileId
) {
137 CRM_Core_Error
::statusBounce(ts('Profile for bulk data entry is missing.'));
140 $this->addElement('hidden', 'batch_id', $this->_batchId
);
142 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
143 // get the profile information
144 if ($this->_batchInfo
['type_id'] == $batchTypes['Contribution']) {
145 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Contributions'));
147 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
148 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Memberships'));
150 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
151 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Pledge Payments'));
154 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($this->_profileId
, FALSE, CRM_Core_Action
::VIEW
);
156 // remove file type field and then limit fields
157 $suppressFields = FALSE;
158 foreach ($this->_fields
as $name => $field) {
159 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name) && $this->_fields
[$name]['html_type'] == 'Autocomplete-Select') {
160 $suppressFields = TRUE;
161 unset($this->_fields
[$name]);
164 //fix to reduce size as we are using this field in grid
165 if (is_array($field['attributes']) && $this->_fields
[$name]['attributes']['size'] > 19) {
166 //shrink class to "form-text-medium"
167 $this->_fields
[$name]['attributes']['size'] = 19;
171 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
173 // add the force save button
174 $forceSave = $this->getButtonName('upload', 'force');
176 $this->addElement('xbutton',
178 ts('Ignore Mismatch & Process the Batch?'),
188 'name' => ts('Validate & Process the Batch'),
193 'name' => ts('Save & Continue Later'),
197 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
199 $preserveDefaultsArray = [
207 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
208 $contactReturnProperties = [];
210 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
211 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
213 'placeholder' => ts('- select -'),
216 // special field specific to membership batch udpate
217 if ($this->_batchInfo
['type_id'] == 2) {
219 1 => ts('Add Membership'),
220 2 => ts('Renew Membership'),
222 $this->add('select', "member_option[$rowNumber]", '', $options);
224 if ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
225 $options = ['' => '-select-'];
227 '1' => ts('Adjust Pledge Payment Schedule?'),
228 '2' => ts('Adjust Total Pledge Amount?'),
230 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
231 if (!empty($this->_batchId
) && !empty($this->_batchInfo
['data']) && !empty($rowNumber)) {
232 $dataValues = json_decode($this->_batchInfo
['data'], TRUE);
233 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
234 $pledgeIDs = CRM_Pledge_BAO_Pledge
::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
235 foreach ($pledgeIDs as $pledgeID) {
236 $pledgePayment = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeID);
237 $options +
= [$pledgeID => CRM_Utils_Date
::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
242 $this->add('select', "open_pledges[$rowNumber]", '', $options);
245 foreach ($this->_fields
as $name => $field) {
246 if (in_array($field['field_type'], $contactTypes)) {
247 $fld = explode('-', $field['name']);
248 $contactReturnProperties[$field['name']] = $fld[0];
250 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
252 if (in_array($field['name'], $preserveDefaultsArray)) {
253 $this->_preserveDefault
= FALSE;
258 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
259 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
260 // An offset value is set to deal with additional vars that are likely passed.
261 // There may be a more accurate way to do this...
262 // set an offset to account for other vars we are not counting
264 if ((count($this->_elementIndex
) +
$offset) > ini_get("max_input_vars")) {
265 // Avoiding 'ts' for obscure messages.
266 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") . ')');
269 $this->assign('fields', $this->_fields
);
270 CRM_Core_Resources
::singleton()
273 'return' => implode(',', $contactReturnProperties),
274 'fieldmap' => array_flip($contactReturnProperties),
278 // don't set the status message when form is submitted.
279 $buttonName = $this->controller
->getButtonName('submit');
281 if ($suppressFields && $buttonName != '_qf_Entry_next') {
282 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');
289 * @param array $params
290 * Posted values of the form.
291 * @param array $files
292 * List of errors to be posted back to the form.
293 * @param \CRM_Batch_Form_Entry $self
297 * list of errors to be posted back to the form
299 public static function formRule($params, $files, $self) {
301 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
303 'total_amount' => ts('Amount'),
304 'financial_type' => ts('Financial Type'),
305 'payment_instrument' => ts('Payment Method'),
308 //CRM-16480 if contact is selected, validate financial type and amount field.
309 foreach ($params['field'] as $key => $value) {
310 if (isset($value['trxn_id'])) {
311 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
312 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
315 foreach ($fields as $field => $label) {
316 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
317 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
322 if (!empty($params['_qf_Entry_upload_force'])) {
323 if (!empty($errors)) {
330 foreach ($params['field'] as $key => $value) {
331 $batchTotal +
= $value['total_amount'];
333 //validate for soft credit fields
334 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
335 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
337 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'])) {
338 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
341 //membership type is required for membership batch entry
342 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
343 if (empty($value['membership_type'][1])) {
344 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
348 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
349 foreach (array_unique($params["open_pledges"]) as $value) {
350 if (!empty($value)) {
351 $duplicateRows = array_keys($params["open_pledges"], $value);
353 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
354 foreach ($duplicateRows as $key) {
355 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
360 if ((string) $batchTotal != $self->_batchInfo
['total']) {
361 $self->assign('batchAmountMismatch', TRUE);
362 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
365 if (!empty($errors)) {
369 $self->assign('batchAmountMismatch', FALSE);
374 * Override default cancel action.
376 public function cancelAction() {
377 // redirect to batch listing
378 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
379 CRM_Utils_System
::civiExit();
383 * Set default values for the form.
385 * @throws \CRM_Core_Exception
387 public function setDefaultValues() {
388 if (empty($this->_fields
)) {
392 // for add mode set smart defaults
393 if ($this->_action
& CRM_Core_Action
::ADD
) {
394 $currentDate = date('Y-m-d H-i-s');
396 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
398 'membership_join_date' => date('Y-m-d'),
399 'receive_date' => $currentDate,
400 'contribution_status_id' => $completeStatus,
403 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
404 foreach ($specialFields as $key => $value) {
405 $defaults['field'][$rowNumber][$key] = $value;
410 // get the cached info from data column of civicrm_batch
411 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
412 $defaults = json_decode($data, TRUE);
413 $defaults = $defaults['values'];
420 * Process the form after the input has been submitted and validated.
422 * @throws \CRM_Core_Exception
423 * @throws \CiviCRM_API3_Exception
425 public function postProcess() {
426 $params = $this->controller
->exportValues($this->_name
);
427 $params['actualBatchTotal'] = 0;
429 // get the profile information
430 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
431 if (in_array($this->_batchInfo
['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
432 $this->processContribution($params);
434 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
435 $this->processMembership($params);
438 // update batch to close status
440 'id' => $this->_batchId
,
442 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
443 'total' => $params['actualBatchTotal'],
446 CRM_Batch_BAO_Batch
::create($paramValues);
448 // set success status
449 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
451 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
455 * Process contribution records.
457 * @param array $params
458 * Associated array of submitted values.
462 * @throws \CRM_Core_Exception
463 * @throws \CiviCRM_API3_Exception
465 private function processContribution(&$params) {
467 foreach ($this->submittableMoneyFields
as $moneyField) {
468 foreach ($params['field'] as $index => $fieldValues) {
469 if (isset($fieldValues[$moneyField])) {
470 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
474 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
475 // get the price set associated with offline contribution record.
476 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
477 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
478 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
479 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
481 if (isset($params['field'])) {
482 foreach ($params['field'] as $key => $value) {
483 // if contact is not selected we should skip the row
484 if (empty($params['primary_contact_id'][$key])) {
488 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
490 // update contact information
491 $this->updateContactInfo($value);
493 //build soft credit params
494 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
495 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
496 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
498 //CRM-15350: if soft-credit-type profile field is disabled or removed then
499 //we choose configured SCT default value
500 if (!empty($params['soft_credit_type'][$key])) {
501 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
504 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
509 if (!empty($params['pcp_made_through_id'][$key])) {
510 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
511 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
512 if (!empty($params['pcp_roll_nickname'][$key])) {
513 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
515 if (!empty($params['pcp_personal_note'][$key])) {
516 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
520 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
525 if (!empty($value['send_receipt'])) {
526 $value['receipt_date'] = date('Y-m-d His');
528 // these translations & date handling are required because we are calling BAO directly rather than the api
529 $fieldTranslations = [
530 'financial_type' => 'financial_type_id',
531 'payment_instrument' => 'payment_instrument_id',
532 'contribution_source' => 'source',
533 'contribution_note' => 'note',
534 'contribution_check_number' => 'check_number',
536 foreach ($fieldTranslations as $formField => $baoField) {
537 if (isset($value[$formField])) {
538 $value[$baoField] = $value[$formField];
540 unset($value[$formField]);
543 $params['actualBatchTotal'] +
= $value['total_amount'];
544 $value['batch_id'] = $this->_batchId
;
545 $value['skipRecentView'] = TRUE;
547 // build line item params
548 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
549 $value['price_' . $priceFieldID] = 1;
552 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
554 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
555 // function to get correct amount level consistently. Remove setting of the amount level in
556 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
557 // to cover all variants.
558 unset($value['amount_level']);
560 //CRM-11529 for back office transactions
561 //when financial_type_id is passed in form, update the
562 //line items with the financial type selected in form
563 // @todo - create a price set or price field per financial type & simply choose the appropriate
564 // price field rather than working around the fact that each price_field is supposed to have a financial
565 // type & we are allowing that to be overridden.
566 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
567 foreach ($lineItem[$priceSetId] as &$values) {
568 $values['financial_type_id'] = $value['financial_type_id'];
571 $value['line_item'] = $lineItem;
573 //finally call contribution create for all the magic
574 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
575 // This code to retrieve the contribution has been moved here from the contribution create
576 // api. It may not be required.
583 $retrieveRequired = 0;
584 foreach ($titleFields as $titleField) {
585 if (!isset($contribution->$titleField)) {
586 $retrieveRequired = 1;
590 if ($retrieveRequired == 1) {
591 $contribution->find(TRUE);
593 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
594 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
595 $adjustTotalAmount = FALSE;
596 if (isset($params['option_type'][$key])) {
597 if ($params['option_type'][$key] == 2) {
598 $adjustTotalAmount = TRUE;
601 $pledgeId = $params['open_pledges'][$key];
602 if (is_numeric($pledgeId)) {
603 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
604 $pledgePaymentId = 0;
605 foreach ($result as $key => $values) {
606 if ($values['status'] != 'Completed') {
607 $pledgePaymentId = $values['id'];
611 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
612 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
614 $contribution->contribution_status_id
,
616 $contribution->total_amount
,
623 if (!empty($value['product_name'])) {
624 if ($value['product_name'][0] > 0) {
625 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
627 $value['hidden_Premium'] = 1;
628 $value['product_option'] = CRM_Utils_Array
::value(
629 $value['product_name'][1],
630 $options[$value['product_name'][0]]
634 'product_id' => $value['product_name'][0],
635 'contribution_id' => $contribution->id
,
636 'product_option' => $value['product_option'],
639 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
645 if ($contribution->id
&& !empty($value['send_receipt'])) {
646 // add the domain email id
647 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
648 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
649 $value['from_email_address'] = $domainEmail;
650 $value['contribution_id'] = $contribution->id
;
651 if (!empty($value['soft_credit'])) {
652 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
654 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
662 * Process membership records.
664 * @param array $params
665 * Associated array of submitted values.
670 private function processMembership(&$params) {
672 // get the price set associated with offline membership
673 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
674 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
676 if (isset($params['field'])) {
677 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
679 foreach ($params['field'] as $key => $value) {
680 foreach ($value as $fieldKey => $fieldValue) {
681 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
682 $value[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
685 // if contact is not selected we should skip the row
686 if (empty($params['primary_contact_id'][$key])) {
690 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
692 // update contact information
693 $this->updateContactInfo($value);
695 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
697 if (!empty($value['send_receipt'])) {
698 $value['receipt_date'] = date('Y-m-d His');
701 if (!empty($value['membership_source'])) {
702 $value['source'] = $value['membership_source'];
705 unset($value['membership_source']);
707 //Get the membership status
708 if (!empty($value['membership_status'])) {
709 $value['status_id'] = $value['membership_status'];
710 unset($value['membership_status']);
713 if (empty($customFields)) {
714 // membership type custom data
715 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
717 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
718 CRM_Core_BAO_CustomField
::getFields('Membership',
719 FALSE, FALSE, NULL, NULL, TRUE
724 //check for custom data
725 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
731 if (!empty($value['financial_type'])) {
732 $value['financial_type_id'] = $value['financial_type'];
735 if (!empty($value['payment_instrument'])) {
736 $value['payment_instrument_id'] = $value['payment_instrument'];
739 // handle soft credit
740 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
741 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
742 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
744 //CRM-15350: if soft-credit-type profile field is disabled or removed then
745 //we choose Gift as default value as per Gift Membership rule
746 if (!empty($params['soft_credit_type'][$key])) {
747 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
750 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
753 if (!empty($value['total_amount'])) {
754 $value['total_amount'] = (float) $value['total_amount'];
757 $params['actualBatchTotal'] +
= $value['total_amount'];
759 unset($value['financial_type']);
760 unset($value['payment_instrument']);
762 $value['batch_id'] = $this->_batchId
;
763 $value['skipRecentView'] = TRUE;
765 // make entry in line item for contribution
767 $editedFieldParams = [
768 'price_set_id' => $priceSetId,
769 'name' => $value['membership_type'][0],
773 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
775 if (!empty($editedResults)) {
776 unset($this->_priceSet
['fields']);
777 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
778 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
779 $fid = $editedResults['id'];
780 $editedFieldParams = [
781 'price_field_id' => $editedResults['id'],
782 'membership_type_id' => $value['membership_type_id'],
786 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
787 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
788 if (!empty($value['total_amount'])) {
789 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
792 $fieldID = key($this->_priceSet
['fields']);
793 $value['price_' . $fieldID] = $editedResults['id'];
796 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
797 $value, $lineItem[$priceSetId]
800 //CRM-11529 for backoffice transactions
801 //when financial_type_id is passed in form, update the
802 //lineitems with the financial type selected in form
803 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
804 foreach ($lineItem[$priceSetId] as &$values) {
805 $values['financial_type_id'] = $value['financial_type_id'];
809 $value['lineItems'] = $lineItem;
810 $value['processPriceSet'] = TRUE;
812 // end of contribution related section
814 unset($value['membership_type']);
816 $value['is_renew'] = FALSE;
817 if (!empty($params['member_option']) && CRM_Utils_Array
::value($key, $params['member_option']) == 2) {
819 // The following parameter setting may be obsolete.
820 $this->_params
= $params;
821 $value['is_renew'] = TRUE;
822 $isPayLater = $params['is_pay_later'] ??
NULL;
824 if (isset($this->_values
) && is_array($this->_values
) && !empty($this->_values
)) {
825 $campaignId = $this->_params
['campaign_id'] ??
NULL;
826 if (!array_key_exists('campaign_id', $this->_params
)) {
827 $campaignId = $this->_values
['campaign_id'] ??
NULL;
832 'end_date' => $value['membership_end_date'] ??
NULL,
833 'start_date' => $value['membership_start_date'] ??
NULL,
835 $membershipSource = $value['source'] ??
NULL;
836 list($membership) = CRM_Member_BAO_Membership
::processMembership(
837 $value['contact_id'], $value['membership_type_id'], FALSE,
838 //$numTerms should be default to 1.
839 NULL, NULL, $value['custom'], 1, NULL, FALSE,
840 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
843 // make contribution entry
844 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id
]);
845 $contrbutionParams['skipCleanMoney'] = TRUE;
846 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
847 // This form should set the correct params & not call this fn directly.
848 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
852 'membership_join_date' => 'joinDate',
853 'membership_start_date' => 'startDate',
854 'membership_end_date' => 'endDate',
863 foreach ($dateTypes as $dateField => $dateVariable) {
864 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
865 $fDate[$dateField] = $value[$dateField] ??
NULL;
869 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
870 $joinDate, $startDate, $endDate
873 foreach ($calcDates as $memType => $calcDate) {
874 foreach ($dates as $d) {
875 //first give priority to form values then calDates.
876 $date = $value[$d] ??
NULL;
878 $date = $calcDate[$d] ??
NULL;
881 $value[$d] = CRM_Utils_Date
::processDate($date);
885 unset($value['membership_start_date']);
886 unset($value['membership_end_date']);
888 // @todo stop passing empty $ids
889 $membership = CRM_Member_BAO_Membership
::create($value, $ids);
893 if (!empty($value['product_name'])) {
894 if ($value['product_name'][0] > 0) {
895 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
897 $value['hidden_Premium'] = 1;
898 $value['product_option'] = CRM_Utils_Array
::value(
899 $value['product_name'][1],
900 $options[$value['product_name'][0]]
904 'product_id' => $value['product_name'][0],
905 'contribution_id' => CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id'),
906 'product_option' => $value['product_option'],
909 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
915 if ($membership->id
&& !empty($value['send_receipt'])) {
917 // add the domain email id
918 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
919 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
921 $value['from_email_address'] = $domainEmail;
922 $value['membership_id'] = $membership->id
;
923 $value['contribution_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id');
924 CRM_Member_Form_Membership
::emailReceipt($this, $value, $membership);
932 * Update contact information.
934 * @param array $value
935 * Associated array of submitted values.
937 private function updateContactInfo(&$value) {
938 $value['preserveDBName'] = $this->_preserveDefault
;
940 //parse street address, CRM-7768
941 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
943 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
949 * Function exists purely for unit testing purposes.
951 * If you feel tempted to use this in live code then it probably means there is some functionality
952 * that needs to be moved out of the form layer
954 * @param array $params
958 public function testProcessMembership($params) {
959 return $this->processMembership($params);
963 * Function exists purely for unit testing purposes.
965 * If you feel tempted to use this in live code then it probably means there is some functionality
966 * that needs to be moved out of the form layer.
968 * @param array $params
972 * @throws \CRM_Core_Exception
973 * @throws \CiviCRM_API3_Exception
975 public function testProcessContribution($params) {
976 return $this->processContribution($params);