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;
569 //finally call contribution create for all the magic
570 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
571 // This code to retrieve the contribution has been moved here from the contribution create
572 // api. It may not be required.
579 $retrieveRequired = 0;
580 foreach ($titleFields as $titleField) {
581 if (!isset($contribution->$titleField)) {
582 $retrieveRequired = 1;
586 if ($retrieveRequired == 1) {
587 $contribution->find(TRUE);
589 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
590 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
591 $adjustTotalAmount = FALSE;
592 if (isset($params['option_type'][$key])) {
593 if ($params['option_type'][$key] == 2) {
594 $adjustTotalAmount = TRUE;
597 $pledgeId = $params['open_pledges'][$key];
598 if (is_numeric($pledgeId)) {
599 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
600 $pledgePaymentId = 0;
601 foreach ($result as $key => $values) {
602 if ($values['status'] != 'Completed') {
603 $pledgePaymentId = $values['id'];
607 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
608 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
610 $contribution->contribution_status_id
,
612 $contribution->total_amount
,
619 if (!empty($value['product_name'])) {
620 if ($value['product_name'][0] > 0) {
621 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
623 $value['hidden_Premium'] = 1;
624 $value['product_option'] = CRM_Utils_Array
::value(
625 $value['product_name'][1],
626 $options[$value['product_name'][0]]
630 'product_id' => $value['product_name'][0],
631 'contribution_id' => $contribution->id
,
632 'product_option' => $value['product_option'],
635 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
641 if ($contribution->id
&& !empty($value['send_receipt'])) {
642 // add the domain email id
643 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
644 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
645 $value['from_email_address'] = $domainEmail;
646 $value['contribution_id'] = $contribution->id
;
647 if (!empty($value['soft_credit'])) {
648 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
650 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
658 * Process membership records.
660 * @param array $params
661 * Associated array of submitted values.
666 private function processMembership(&$params) {
668 // get the price set associated with offline membership
669 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
670 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
672 if (isset($params['field'])) {
673 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
675 foreach ($params['field'] as $key => $value) {
676 foreach ($value as $fieldKey => $fieldValue) {
677 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
678 $value[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
681 // if contact is not selected we should skip the row
682 if (empty($params['primary_contact_id'][$key])) {
686 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
688 // update contact information
689 $this->updateContactInfo($value);
691 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
693 if (!empty($value['send_receipt'])) {
694 $value['receipt_date'] = date('Y-m-d His');
697 if (!empty($value['membership_source'])) {
698 $value['source'] = $value['membership_source'];
701 unset($value['membership_source']);
703 //Get the membership status
704 if (!empty($value['membership_status'])) {
705 $value['status_id'] = $value['membership_status'];
706 unset($value['membership_status']);
709 if (empty($customFields)) {
710 // membership type custom data
711 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
713 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
714 CRM_Core_BAO_CustomField
::getFields('Membership',
715 FALSE, FALSE, NULL, NULL, TRUE
720 //check for custom data
721 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
727 if (!empty($value['financial_type'])) {
728 $value['financial_type_id'] = $value['financial_type'];
731 if (!empty($value['payment_instrument'])) {
732 $value['payment_instrument_id'] = $value['payment_instrument'];
735 // handle soft credit
736 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
737 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
738 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
740 //CRM-15350: if soft-credit-type profile field is disabled or removed then
741 //we choose Gift as default value as per Gift Membership rule
742 if (!empty($params['soft_credit_type'][$key])) {
743 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
746 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
749 if (!empty($value['total_amount'])) {
750 $value['total_amount'] = (float) $value['total_amount'];
753 $params['actualBatchTotal'] +
= $value['total_amount'];
755 unset($value['financial_type']);
756 unset($value['payment_instrument']);
758 $value['batch_id'] = $this->_batchId
;
759 $value['skipRecentView'] = TRUE;
761 // make entry in line item for contribution
763 $editedFieldParams = [
764 'price_set_id' => $priceSetId,
765 'name' => $value['membership_type'][0],
769 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
771 if (!empty($editedResults)) {
772 unset($this->_priceSet
['fields']);
773 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
774 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
775 $fid = $editedResults['id'];
776 $editedFieldParams = [
777 'price_field_id' => $editedResults['id'],
778 'membership_type_id' => $value['membership_type_id'],
782 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
783 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
784 if (!empty($value['total_amount'])) {
785 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
788 $fieldID = key($this->_priceSet
['fields']);
789 $value['price_' . $fieldID] = $editedResults['id'];
792 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
793 $value, $lineItem[$priceSetId]
796 //CRM-11529 for backoffice transactions
797 //when financial_type_id is passed in form, update the
798 //lineitems with the financial type selected in form
799 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
800 foreach ($lineItem[$priceSetId] as &$values) {
801 $values['financial_type_id'] = $value['financial_type_id'];
805 $value['lineItems'] = $lineItem;
806 $value['processPriceSet'] = TRUE;
808 // end of contribution related section
810 unset($value['membership_type']);
812 $value['is_renew'] = FALSE;
813 if (!empty($params['member_option']) && CRM_Utils_Array
::value($key, $params['member_option']) == 2) {
815 // The following parameter setting may be obsolete.
816 $this->_params
= $params;
817 $value['is_renew'] = TRUE;
818 $isPayLater = $params['is_pay_later'] ??
NULL;
820 if (isset($this->_values
) && is_array($this->_values
) && !empty($this->_values
)) {
821 $campaignId = $this->_params
['campaign_id'] ??
NULL;
822 if (!array_key_exists('campaign_id', $this->_params
)) {
823 $campaignId = $this->_values
['campaign_id'] ??
NULL;
828 'end_date' => $value['membership_end_date'] ??
NULL,
829 'start_date' => $value['membership_start_date'] ??
NULL,
831 $membershipSource = $value['source'] ??
NULL;
832 list($membership) = CRM_Member_BAO_Membership
::processMembership(
833 $value['contact_id'], $value['membership_type_id'], FALSE,
834 //$numTerms should be default to 1.
835 NULL, NULL, $value['custom'], 1, NULL, FALSE,
836 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
839 // make contribution entry
840 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id
]);
841 $contrbutionParams['skipCleanMoney'] = TRUE;
842 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
843 // This form should set the correct params & not call this fn directly.
844 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
848 'membership_join_date' => 'joinDate',
849 'membership_start_date' => 'startDate',
850 'membership_end_date' => 'endDate',
859 foreach ($dateTypes as $dateField => $dateVariable) {
860 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
861 $fDate[$dateField] = $value[$dateField] ??
NULL;
865 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
866 $joinDate, $startDate, $endDate
869 foreach ($calcDates as $memType => $calcDate) {
870 foreach ($dates as $d) {
871 //first give priority to form values then calDates.
872 $date = $value[$d] ??
NULL;
874 $date = $calcDate[$d] ??
NULL;
877 $value[$d] = CRM_Utils_Date
::processDate($date);
881 unset($value['membership_start_date']);
882 unset($value['membership_end_date']);
884 // @todo stop passing empty $ids
885 $membership = CRM_Member_BAO_Membership
::create($value, $ids);
889 if (!empty($value['product_name'])) {
890 if ($value['product_name'][0] > 0) {
891 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
893 $value['hidden_Premium'] = 1;
894 $value['product_option'] = CRM_Utils_Array
::value(
895 $value['product_name'][1],
896 $options[$value['product_name'][0]]
900 'product_id' => $value['product_name'][0],
901 'contribution_id' => CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id'),
902 'product_option' => $value['product_option'],
905 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
911 if ($membership->id
&& !empty($value['send_receipt'])) {
913 // add the domain email id
914 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
915 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
917 $value['from_email_address'] = $domainEmail;
918 $value['membership_id'] = $membership->id
;
919 $value['contribution_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id');
920 CRM_Member_Form_Membership
::emailReceipt($this, $value, $membership);
928 * Update contact information.
930 * @param array $value
931 * Associated array of submitted values.
933 private function updateContactInfo(&$value) {
934 $value['preserveDBName'] = $this->_preserveDefault
;
936 //parse street address, CRM-7768
937 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
939 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
945 * Function exists purely for unit testing purposes.
947 * If you feel tempted to use this in live code then it probably means there is some functionality
948 * that needs to be moved out of the form layer
950 * @param array $params
954 public function testProcessMembership($params) {
955 return $this->processMembership($params);
959 * Function exists purely for unit testing purposes.
961 * If you feel tempted to use this in live code then it probably means there is some functionality
962 * that needs to be moved out of the form layer.
964 * @param array $params
968 * @throws \CRM_Core_Exception
969 * @throws \CiviCRM_API3_Exception
971 public function testProcessContribution($params) {
972 return $this->processContribution($params);