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('submit',
178 ts('Ignore Mismatch & Process the Batch?')
184 'name' => ts('Validate & Process the Batch'),
189 'name' => ts('Save & Continue Later'),
193 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
195 $preserveDefaultsArray = [
203 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
204 $contactReturnProperties = [];
206 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
207 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
209 'placeholder' => ts('- select -'),
212 // special field specific to membership batch udpate
213 if ($this->_batchInfo
['type_id'] == 2) {
215 1 => ts('Add Membership'),
216 2 => ts('Renew Membership'),
218 $this->add('select', "member_option[$rowNumber]", '', $options);
220 if ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
221 $options = ['' => '-select-'];
223 '1' => ts('Adjust Pledge Payment Schedule?'),
224 '2' => ts('Adjust Total Pledge Amount?'),
226 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
227 if (!empty($this->_batchId
) && !empty($this->_batchInfo
['data']) && !empty($rowNumber)) {
228 $dataValues = json_decode($this->_batchInfo
['data'], TRUE);
229 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
230 $pledgeIDs = CRM_Pledge_BAO_Pledge
::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
231 foreach ($pledgeIDs as $pledgeID) {
232 $pledgePayment = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeID);
233 $options +
= [$pledgeID => CRM_Utils_Date
::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
238 $this->add('select', "open_pledges[$rowNumber]", '', $options);
241 foreach ($this->_fields
as $name => $field) {
242 if (in_array($field['field_type'], $contactTypes)) {
243 $fld = explode('-', $field['name']);
244 $contactReturnProperties[$field['name']] = $fld[0];
246 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
248 if (in_array($field['name'], $preserveDefaultsArray)) {
249 $this->_preserveDefault
= FALSE;
254 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
255 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
256 // An offset value is set to deal with additional vars that are likely passed.
257 // There may be a more accurate way to do this...
258 // set an offset to account for other vars we are not counting
260 if ((count($this->_elementIndex
) +
$offset) > ini_get("max_input_vars")) {
261 // Avoiding 'ts' for obscure messages.
262 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") . ')');
265 $this->assign('fields', $this->_fields
);
266 CRM_Core_Resources
::singleton()
269 'return' => implode(',', $contactReturnProperties),
270 'fieldmap' => array_flip($contactReturnProperties),
274 // don't set the status message when form is submitted.
275 $buttonName = $this->controller
->getButtonName('submit');
277 if ($suppressFields && $buttonName != '_qf_Entry_next') {
278 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');
285 * @param array $params
286 * Posted values of the form.
287 * @param array $files
288 * List of errors to be posted back to the form.
289 * @param \CRM_Batch_Form_Entry $self
293 * list of errors to be posted back to the form
295 public static function formRule($params, $files, $self) {
297 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
299 'total_amount' => ts('Amount'),
300 'financial_type' => ts('Financial Type'),
301 'payment_instrument' => ts('Payment Method'),
304 //CRM-16480 if contact is selected, validate financial type and amount field.
305 foreach ($params['field'] as $key => $value) {
306 if (isset($value['trxn_id'])) {
307 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
308 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
311 foreach ($fields as $field => $label) {
312 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
313 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
318 if (!empty($params['_qf_Entry_upload_force'])) {
319 if (!empty($errors)) {
326 foreach ($params['field'] as $key => $value) {
327 $batchTotal +
= $value['total_amount'];
329 //validate for soft credit fields
330 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
331 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
333 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'])) {
334 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
337 //membership type is required for membership batch entry
338 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
339 if (empty($value['membership_type'][1])) {
340 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
344 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
345 foreach (array_unique($params["open_pledges"]) as $value) {
346 if (!empty($value)) {
347 $duplicateRows = array_keys($params["open_pledges"], $value);
349 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
350 foreach ($duplicateRows as $key) {
351 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
356 if ((string) $batchTotal != $self->_batchInfo
['total']) {
357 $self->assign('batchAmountMismatch', TRUE);
358 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
361 if (!empty($errors)) {
365 $self->assign('batchAmountMismatch', FALSE);
370 * Override default cancel action.
372 public function cancelAction() {
373 // redirect to batch listing
374 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
375 CRM_Utils_System
::civiExit();
379 * Set default values for the form.
381 * @throws \CRM_Core_Exception
383 public function setDefaultValues() {
384 if (empty($this->_fields
)) {
388 // for add mode set smart defaults
389 if ($this->_action
& CRM_Core_Action
::ADD
) {
390 $currentDate = date('Y-m-d H-i-s');
392 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
394 'membership_join_date' => date('Y-m-d'),
395 'receive_date' => $currentDate,
396 'contribution_status_id' => $completeStatus,
399 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
400 foreach ($specialFields as $key => $value) {
401 $defaults['field'][$rowNumber][$key] = $value;
406 // get the cached info from data column of civicrm_batch
407 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
408 $defaults = json_decode($data, TRUE);
409 $defaults = $defaults['values'];
416 * Process the form after the input has been submitted and validated.
418 * @throws \CRM_Core_Exception
419 * @throws \CiviCRM_API3_Exception
421 public function postProcess() {
422 $params = $this->controller
->exportValues($this->_name
);
423 $params['actualBatchTotal'] = 0;
425 // get the profile information
426 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
427 if (in_array($this->_batchInfo
['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
428 $this->processContribution($params);
430 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
431 $this->processMembership($params);
434 // update batch to close status
436 'id' => $this->_batchId
,
438 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
439 'total' => $params['actualBatchTotal'],
442 CRM_Batch_BAO_Batch
::create($paramValues);
444 // set success status
445 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
447 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
451 * Process contribution records.
453 * @param array $params
454 * Associated array of submitted values.
458 * @throws \CRM_Core_Exception
459 * @throws \CiviCRM_API3_Exception
461 private function processContribution(&$params) {
463 foreach ($this->submittableMoneyFields
as $moneyField) {
464 foreach ($params['field'] as $index => $fieldValues) {
465 if (isset($fieldValues[$moneyField])) {
466 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
470 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
471 // get the price set associated with offline contribution record.
472 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
473 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
474 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
475 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
477 if (isset($params['field'])) {
478 foreach ($params['field'] as $key => $value) {
479 // if contact is not selected we should skip the row
480 if (empty($params['primary_contact_id'][$key])) {
484 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
486 // update contact information
487 $this->updateContactInfo($value);
489 //build soft credit params
490 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
491 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
492 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
494 //CRM-15350: if soft-credit-type profile field is disabled or removed then
495 //we choose configured SCT default value
496 if (!empty($params['soft_credit_type'][$key])) {
497 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
500 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
505 if (!empty($params['pcp_made_through_id'][$key])) {
506 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
507 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
508 if (!empty($params['pcp_roll_nickname'][$key])) {
509 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
511 if (!empty($params['pcp_personal_note'][$key])) {
512 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
516 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
521 if (!empty($value['send_receipt'])) {
522 $value['receipt_date'] = date('Y-m-d His');
524 // these translations & date handling are required because we are calling BAO directly rather than the api
525 $fieldTranslations = [
526 'financial_type' => 'financial_type_id',
527 'payment_instrument' => 'payment_instrument_id',
528 'contribution_source' => 'source',
529 'contribution_note' => 'note',
530 'contribution_check_number' => 'check_number',
532 foreach ($fieldTranslations as $formField => $baoField) {
533 if (isset($value[$formField])) {
534 $value[$baoField] = $value[$formField];
536 unset($value[$formField]);
539 $params['actualBatchTotal'] +
= $value['total_amount'];
540 $value['batch_id'] = $this->_batchId
;
541 $value['skipRecentView'] = TRUE;
543 // build line item params
544 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
545 $value['price_' . $priceFieldID] = 1;
548 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
550 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
551 // function to get correct amount level consistently. Remove setting of the amount level in
552 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
553 // to cover all variants.
554 unset($value['amount_level']);
556 //CRM-11529 for back office transactions
557 //when financial_type_id is passed in form, update the
558 //line items with the financial type selected in form
559 // @todo - create a price set or price field per financial type & simply choose the appropriate
560 // price field rather than working around the fact that each price_field is supposed to have a financial
561 // type & we are allowing that to be overridden.
562 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
563 foreach ($lineItem[$priceSetId] as &$values) {
564 $values['financial_type_id'] = $value['financial_type_id'];
567 $value['line_item'] = $lineItem;
568 $value['skipCleanMoney'] = TRUE;
569 //finally call contribution create for all the magic
570 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
571 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
572 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
573 $adjustTotalAmount = FALSE;
574 if (isset($params['option_type'][$key])) {
575 if ($params['option_type'][$key] == 2) {
576 $adjustTotalAmount = TRUE;
579 $pledgeId = $params['open_pledges'][$key];
580 if (is_numeric($pledgeId)) {
581 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
582 $pledgePaymentId = 0;
583 foreach ($result as $key => $values) {
584 if ($values['status'] != 'Completed') {
585 $pledgePaymentId = $values['id'];
589 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
590 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
592 $contribution->contribution_status_id
,
594 $contribution->total_amount
,
601 if (!empty($value['product_name'])) {
602 if ($value['product_name'][0] > 0) {
603 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
605 $value['hidden_Premium'] = 1;
606 $value['product_option'] = CRM_Utils_Array
::value(
607 $value['product_name'][1],
608 $options[$value['product_name'][0]]
612 'product_id' => $value['product_name'][0],
613 'contribution_id' => $contribution->id
,
614 'product_option' => $value['product_option'],
617 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
623 if ($contribution->id
&& !empty($value['send_receipt'])) {
624 // add the domain email id
625 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
626 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
627 $value['from_email_address'] = $domainEmail;
628 $value['contribution_id'] = $contribution->id
;
629 if (!empty($value['soft_credit'])) {
630 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
632 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
640 * Process membership records.
642 * @param array $params
643 * Associated array of submitted values.
648 private function processMembership(&$params) {
650 // get the price set associated with offline membership
651 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
652 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
654 if (isset($params['field'])) {
655 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
657 foreach ($params['field'] as $key => $value) {
658 foreach ($value as $fieldKey => $fieldValue) {
659 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
660 $value[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
663 // if contact is not selected we should skip the row
664 if (empty($params['primary_contact_id'][$key])) {
668 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
670 // update contact information
671 $this->updateContactInfo($value);
673 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
675 if (!empty($value['send_receipt'])) {
676 $value['receipt_date'] = date('Y-m-d His');
679 if (!empty($value['membership_source'])) {
680 $value['source'] = $value['membership_source'];
683 unset($value['membership_source']);
685 //Get the membership status
686 if (!empty($value['membership_status'])) {
687 $value['status_id'] = $value['membership_status'];
688 unset($value['membership_status']);
691 if (empty($customFields)) {
692 // membership type custom data
693 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
695 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
696 CRM_Core_BAO_CustomField
::getFields('Membership',
697 FALSE, FALSE, NULL, NULL, TRUE
702 //check for custom data
703 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
709 if (!empty($value['financial_type'])) {
710 $value['financial_type_id'] = $value['financial_type'];
713 if (!empty($value['payment_instrument'])) {
714 $value['payment_instrument_id'] = $value['payment_instrument'];
717 // handle soft credit
718 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
719 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
720 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
722 //CRM-15350: if soft-credit-type profile field is disabled or removed then
723 //we choose Gift as default value as per Gift Membership rule
724 if (!empty($params['soft_credit_type'][$key])) {
725 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
728 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
731 if (!empty($value['total_amount'])) {
732 $value['total_amount'] = (float) $value['total_amount'];
735 $params['actualBatchTotal'] +
= $value['total_amount'];
737 unset($value['financial_type']);
738 unset($value['payment_instrument']);
740 $value['batch_id'] = $this->_batchId
;
741 $value['skipRecentView'] = TRUE;
743 // make entry in line item for contribution
745 $editedFieldParams = [
746 'price_set_id' => $priceSetId,
747 'name' => $value['membership_type'][0],
751 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
753 if (!empty($editedResults)) {
754 unset($this->_priceSet
['fields']);
755 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
756 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
757 $fid = $editedResults['id'];
758 $editedFieldParams = [
759 'price_field_id' => $editedResults['id'],
760 'membership_type_id' => $value['membership_type_id'],
764 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
765 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
766 if (!empty($value['total_amount'])) {
767 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
770 $fieldID = key($this->_priceSet
['fields']);
771 $value['price_' . $fieldID] = $editedResults['id'];
774 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
775 $value, $lineItem[$priceSetId]
778 //CRM-11529 for backoffice transactions
779 //when financial_type_id is passed in form, update the
780 //lineitems with the financial type selected in form
781 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
782 foreach ($lineItem[$priceSetId] as &$values) {
783 $values['financial_type_id'] = $value['financial_type_id'];
787 $value['lineItems'] = $lineItem;
788 $value['processPriceSet'] = TRUE;
790 // end of contribution related section
792 unset($value['membership_type']);
794 $value['is_renew'] = FALSE;
795 if (!empty($params['member_option']) && CRM_Utils_Array
::value($key, $params['member_option']) == 2) {
797 // The following parameter setting may be obsolete.
798 $this->_params
= $params;
799 $value['is_renew'] = TRUE;
800 $isPayLater = $params['is_pay_later'] ??
NULL;
802 if (isset($this->_values
) && is_array($this->_values
) && !empty($this->_values
)) {
803 $campaignId = $this->_params
['campaign_id'] ??
NULL;
804 if (!array_key_exists('campaign_id', $this->_params
)) {
805 $campaignId = $this->_values
['campaign_id'] ??
NULL;
810 'end_date' => $value['membership_end_date'] ??
NULL,
811 'start_date' => $value['membership_start_date'] ??
NULL,
813 $membershipSource = $value['source'] ??
NULL;
814 list($membership) = CRM_Member_BAO_Membership
::processMembership(
815 $value['contact_id'], $value['membership_type_id'], FALSE,
816 //$numTerms should be default to 1.
817 NULL, NULL, $value['custom'], 1, NULL, FALSE,
818 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
821 // make contribution entry
822 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id
]);
823 $contrbutionParams['skipCleanMoney'] = TRUE;
824 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
825 // This form should set the correct params & not call this fn directly.
826 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
830 'membership_join_date' => 'joinDate',
831 'membership_start_date' => 'startDate',
832 'membership_end_date' => 'endDate',
841 foreach ($dateTypes as $dateField => $dateVariable) {
842 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
843 $fDate[$dateField] = $value[$dateField] ??
NULL;
847 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
848 $joinDate, $startDate, $endDate
851 foreach ($calcDates as $memType => $calcDate) {
852 foreach ($dates as $d) {
853 //first give priority to form values then calDates.
854 $date = $value[$d] ??
NULL;
856 $date = $calcDate[$d] ??
NULL;
859 $value[$d] = CRM_Utils_Date
::processDate($date);
863 unset($value['membership_start_date']);
864 unset($value['membership_end_date']);
866 // @todo stop passing empty $ids
867 $membership = CRM_Member_BAO_Membership
::create($value, $ids);
871 if (!empty($value['product_name'])) {
872 if ($value['product_name'][0] > 0) {
873 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
875 $value['hidden_Premium'] = 1;
876 $value['product_option'] = CRM_Utils_Array
::value(
877 $value['product_name'][1],
878 $options[$value['product_name'][0]]
882 'product_id' => $value['product_name'][0],
883 'contribution_id' => CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id'),
884 'product_option' => $value['product_option'],
887 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
893 if ($membership->id
&& !empty($value['send_receipt'])) {
895 // add the domain email id
896 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
897 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
899 $value['from_email_address'] = $domainEmail;
900 $value['membership_id'] = $membership->id
;
901 $value['contribution_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id');
902 CRM_Member_Form_Membership
::emailReceipt($this, $value, $membership);
910 * Update contact information.
912 * @param array $value
913 * Associated array of submitted values.
915 private function updateContactInfo(&$value) {
916 $value['preserveDBName'] = $this->_preserveDefault
;
918 //parse street address, CRM-7768
919 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
921 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
927 * Function exists purely for unit testing purposes.
929 * If you feel tempted to use this in live code then it probably means there is some functionality
930 * that needs to be moved out of the form layer
932 * @param array $params
936 public function testProcessMembership($params) {
937 return $this->processMembership($params);
941 * Function exists purely for unit testing purposes.
943 * If you feel tempted to use this in live code then it probably means there is some functionality
944 * that needs to be moved out of the form layer.
946 * @param array $params
950 * @throws \CRM_Core_Exception
951 * @throws \CiviCRM_API3_Exception
953 public function testProcessContribution($params) {
954 return $this->processContribution($params);