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;
66 * Renew option for current row.
68 * This is as set on the form.
72 protected $currentRowIsRenewOption;
79 protected $_contactFields = [];
82 * Fields array of fields in the batch profile.
84 * (based on the uf_field table data)
85 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
86 * (although a future refactoring might hopefully change that so it uses the api & the function is not
96 protected $currentRowContributionID;
99 * Row being processed.
103 protected $currentRow = [];
108 protected $currentRowExistingMembership;
111 * Get the contribution id for the current row.
114 * @throws \CRM_Core_Exception
116 public function getCurrentRowContributionID(): int {
117 if (!isset($this->currentRowContributionID
)) {
118 $this->currentRowContributionID
= CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $this->getCurrentRowMembershipID(), 'contribution_id', 'membership_id');
120 return $this->currentRowContributionID
;
124 * Set the contribution ID for the current row.
126 * @param int $currentRowContributionID
128 public function setCurrentRowContributionID(int $currentRowContributionID): void
{
129 $this->currentRowContributionID
= $currentRowContributionID;
135 public function getCurrentRowMembershipID() {
136 return $this->currentRowMembershipID
;
140 * Get the order (contribution) status for the current row.
142 protected function getCurrentRowPaymentStatus() {
143 return CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $this->currentRow
['contribution_status_id']);
147 * Get the contact ID for the current row.
151 public function getCurrentRowContactID(): int {
152 return $this->currentRow
['contact_id'];
156 * Get the membership type ID for the current row.
160 public function getCurrentRowMembershipTypeID(): int {
161 return $this->currentRow
['membership_type_id'];
165 * Set the membership id for the current row.
167 * @param int $currentRowMembershipID
169 public function setCurrentRowMembershipID(int $currentRowMembershipID): void
{
170 $this->currentRowMembershipID
= $currentRowMembershipID;
176 protected $currentRowMembershipID;
179 * Monetary fields that may be submitted.
181 * These should get a standardised format in the beginPostProcess function.
183 * These fields are common to many forms. Some may override this.
186 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
189 * Build all the data structures needed to build the form.
191 * @throws \CRM_Core_Exception
193 public function preProcess() {
194 $this->_batchId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
196 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'browse');
198 if (empty($this->_batchInfo
)) {
199 $params = ['id' => $this->_batchId
];
200 CRM_Batch_BAO_Batch
::retrieve($params, $this->_batchInfo
);
202 $this->assign('batchTotal', !empty($this->_batchInfo
['total']) ?
$this->_batchInfo
['total'] : NULL);
203 $this->assign('batchType', $this->_batchInfo
['type_id']);
205 // get the profile id associted with this batch type
206 $this->_profileId
= CRM_Batch_BAO_Batch
::getProfileId($this->_batchInfo
['type_id']);
208 CRM_Core_Resources
::singleton()
209 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
210 ->addSetting(['batch' => ['type_id' => $this->_batchInfo
['type_id']]])
211 ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config
::singleton()->monetaryThousandSeparator
]])
212 ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config
::singleton()->monetaryDecimalPoint
]]);
214 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country
::defaultCurrencySymbol());
222 public function setBatchID($id) {
223 $this->_batchId
= $id;
227 * Build the form object.
229 * @throws \CRM_Core_Exception
231 public function buildQuickForm() {
232 if (!$this->_profileId
) {
233 CRM_Core_Error
::statusBounce(ts('Profile for bulk data entry is missing.'));
236 $this->addElement('hidden', 'batch_id', $this->_batchId
);
238 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
239 // get the profile information
240 if ($this->_batchInfo
['type_id'] == $batchTypes['Contribution']) {
241 $this->setTitle(ts('Batch Data Entry for Contributions'));
243 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
244 $this->setTitle(ts('Batch Data Entry for Memberships'));
246 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
247 $this->setTitle(ts('Batch Data Entry for Pledge Payments'));
250 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($this->_profileId
, FALSE, CRM_Core_Action
::VIEW
);
252 // remove file type field and then limit fields
253 $suppressFields = FALSE;
254 foreach ($this->_fields
as $name => $field) {
255 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name) && $this->_fields
[$name]['html_type'] == 'Autocomplete-Select') {
256 $suppressFields = TRUE;
257 unset($this->_fields
[$name]);
260 //fix to reduce size as we are using this field in grid
261 if (is_array($field['attributes']) && $this->_fields
[$name]['attributes']['size'] > 19) {
262 //shrink class to "form-text-medium"
263 $this->_fields
[$name]['attributes']['size'] = 19;
267 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
269 // add the force save button
270 $forceSave = $this->getButtonName('upload', 'force');
272 $this->addElement('xbutton',
274 ts('Ignore Mismatch & Process the Batch?'),
278 'class' => 'crm-button crm-button_qf_Entry_upload_force-save',
285 'name' => ts('Validate & Process the Batch'),
290 'name' => ts('Save & Continue Later'),
294 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
296 $preserveDefaultsArray = [
304 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
305 $contactReturnProperties = [];
307 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
308 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
310 'placeholder' => ts('- select -'),
313 // special field specific to membership batch udpate
314 if ($this->_batchInfo
['type_id'] == 2) {
316 1 => ts('Add Membership'),
317 2 => ts('Renew Membership'),
319 $this->add('select', "member_option[$rowNumber]", '', $options);
321 if ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
322 $options = ['' => '-select-'];
324 '1' => ts('Adjust Pledge Payment Schedule?'),
325 '2' => ts('Adjust Total Pledge Amount?'),
327 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
328 if (!empty($this->_batchId
) && !empty($this->_batchInfo
['data']) && !empty($rowNumber)) {
329 $dataValues = json_decode($this->_batchInfo
['data'], TRUE);
330 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
331 $pledgeIDs = CRM_Pledge_BAO_Pledge
::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
332 foreach ($pledgeIDs as $pledgeID) {
333 $pledgePayment = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeID);
334 $options +
= [$pledgeID => CRM_Utils_Date
::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
339 $this->add('select', "open_pledges[$rowNumber]", '', $options);
342 foreach ($this->_fields
as $name => $field) {
343 if (in_array($field['field_type'], $contactTypes)) {
344 $fld = explode('-', $field['name']);
345 $contactReturnProperties[$field['name']] = $fld[0];
347 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
349 if (in_array($field['name'], $preserveDefaultsArray)) {
350 $this->_preserveDefault
= FALSE;
355 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
356 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
357 // An offset value is set to deal with additional vars that are likely passed.
358 // There may be a more accurate way to do this...
359 // set an offset to account for other vars we are not counting
361 if ((count($this->_elementIndex
) +
$offset) > ini_get("max_input_vars")) {
362 // Avoiding 'ts' for obscure messages.
363 CRM_Core_Error
::statusBounce(ts('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = %1)', [1 => ini_get("max_input_vars")]));
366 $this->assign('fields', $this->_fields
);
367 CRM_Core_Resources
::singleton()
370 'return' => implode(',', $contactReturnProperties),
371 'fieldmap' => array_flip($contactReturnProperties),
375 // don't set the status message when form is submitted.
376 $buttonName = $this->controller
->getButtonName('submit');
378 if ($suppressFields && $buttonName != '_qf_Entry_next') {
379 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');
386 * @param array $params
387 * Posted values of the form.
388 * @param array $files
389 * List of errors to be posted back to the form.
390 * @param \CRM_Batch_Form_Entry $self
394 * list of errors to be posted back to the form
396 public static function formRule($params, $files, $self) {
398 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
400 'total_amount' => ts('Amount'),
401 'financial_type' => ts('Financial Type'),
402 'payment_instrument' => ts('Payment Method'),
405 //CRM-16480 if contact is selected, validate financial type and amount field.
406 foreach ($params['field'] as $key => $value) {
407 if (isset($value['trxn_id'])) {
408 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
409 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
412 foreach ($fields as $field => $label) {
413 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
414 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
419 if (!empty($params['_qf_Entry_upload_force'])) {
420 if (!empty($errors)) {
427 foreach ($params['field'] as $key => $value) {
428 $batchTotal +
= $value['total_amount'];
430 //validate for soft credit fields
431 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
432 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
434 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'])) {
435 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
438 //membership type is required for membership batch entry
439 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
440 if (empty($value['membership_type'][1])) {
441 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
445 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
446 foreach (array_unique($params["open_pledges"]) as $value) {
447 if (!empty($value)) {
448 $duplicateRows = array_keys($params["open_pledges"], $value);
450 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
451 foreach ($duplicateRows as $key) {
452 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
457 if ((string) $batchTotal != $self->_batchInfo
['total']) {
458 $self->assign('batchAmountMismatch', TRUE);
459 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
462 if (!empty($errors)) {
466 $self->assign('batchAmountMismatch', FALSE);
471 * Override default cancel action.
473 public function cancelAction() {
474 // redirect to batch listing
475 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
476 CRM_Utils_System
::civiExit();
480 * Set default values for the form.
482 * @throws \CRM_Core_Exception
484 public function setDefaultValues() {
485 if (empty($this->_fields
)) {
489 // for add mode set smart defaults
490 if ($this->_action
& CRM_Core_Action
::ADD
) {
491 $currentDate = date('Y-m-d H-i-s');
493 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
495 'membership_join_date' => date('Y-m-d'),
496 'receive_date' => $currentDate,
497 'contribution_status_id' => $completeStatus,
500 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
501 foreach ($specialFields as $key => $value) {
502 $defaults['field'][$rowNumber][$key] = $value;
507 // get the cached info from data column of civicrm_batch
508 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
509 $defaults = json_decode($data, TRUE);
510 $defaults = $defaults['values'];
517 * Process the form after the input has been submitted and validated.
519 * @throws \CRM_Core_Exception
520 * @throws \CiviCRM_API3_Exception
522 public function postProcess() {
523 $params = $this->controller
->exportValues($this->_name
);
524 $params['actualBatchTotal'] = 0;
526 // get the profile information
527 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
528 if (in_array($this->_batchInfo
['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
529 $this->processContribution($params);
531 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
532 $params['actualBatchTotal'] = $this->processMembership($params);
535 // update batch to close status
537 'id' => $this->_batchId
,
539 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
540 'total' => $params['actualBatchTotal'],
543 CRM_Batch_BAO_Batch
::create($paramValues);
545 // set success status
546 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
548 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
552 * Process contribution records.
554 * @param array $params
555 * Associated array of submitted values.
559 * @throws \CRM_Core_Exception
560 * @throws \CiviCRM_API3_Exception
562 private function processContribution(&$params) {
564 foreach ($this->submittableMoneyFields
as $moneyField) {
565 foreach ($params['field'] as $index => $fieldValues) {
566 if (isset($fieldValues[$moneyField])) {
567 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
571 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
572 // get the price set associated with offline contribution record.
573 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
574 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
575 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
576 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
578 if (isset($params['field'])) {
579 foreach ($params['field'] as $key => $value) {
580 // if contact is not selected we should skip the row
581 if (empty($params['primary_contact_id'][$key])) {
585 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
587 // update contact information
588 $this->updateContactInfo($value);
590 //build soft credit params
591 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
592 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
593 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
595 //CRM-15350: if soft-credit-type profile field is disabled or removed then
596 //we choose configured SCT default value
597 if (!empty($params['soft_credit_type'][$key])) {
598 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
601 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
606 if (!empty($params['pcp_made_through_id'][$key])) {
607 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
608 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
609 if (!empty($params['pcp_roll_nickname'][$key])) {
610 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
612 if (!empty($params['pcp_personal_note'][$key])) {
613 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
617 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
622 if (!empty($value['send_receipt'])) {
623 $value['receipt_date'] = date('Y-m-d His');
625 // these translations & date handling are required because we are calling BAO directly rather than the api
626 $fieldTranslations = [
627 'financial_type' => 'financial_type_id',
628 'payment_instrument' => 'payment_instrument_id',
629 'contribution_source' => 'source',
630 'contribution_note' => 'note',
631 'contribution_check_number' => 'check_number',
633 foreach ($fieldTranslations as $formField => $baoField) {
634 if (isset($value[$formField])) {
635 $value[$baoField] = $value[$formField];
637 unset($value[$formField]);
640 $params['actualBatchTotal'] +
= $value['total_amount'];
641 $value['batch_id'] = $this->_batchId
;
642 $value['skipRecentView'] = TRUE;
644 // build line item params
645 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
646 $value['price_' . $priceFieldID] = 1;
649 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
651 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
652 // function to get correct amount level consistently. Remove setting of the amount level in
653 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
654 // to cover all variants.
655 unset($value['amount_level']);
657 //CRM-11529 for back office transactions
658 //when financial_type_id is passed in form, update the
659 //line items with the financial type selected in form
660 // @todo - create a price set or price field per financial type & simply choose the appropriate
661 // price field rather than working around the fact that each price_field is supposed to have a financial
662 // type & we are allowing that to be overridden.
663 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
664 foreach ($lineItem[$priceSetId] as &$values) {
665 $values['financial_type_id'] = $value['financial_type_id'];
668 $value['line_item'] = $lineItem;
670 //finally call contribution create for all the magic
671 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
672 // This code to retrieve the contribution has been moved here from the contribution create
673 // api. It may not be required.
680 $retrieveRequired = 0;
681 foreach ($titleFields as $titleField) {
682 if (!isset($contribution->$titleField)) {
683 $retrieveRequired = 1;
687 if ($retrieveRequired == 1) {
688 $contribution->find(TRUE);
690 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
691 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
692 $adjustTotalAmount = FALSE;
693 if (isset($params['option_type'][$key])) {
694 if ($params['option_type'][$key] == 2) {
695 $adjustTotalAmount = TRUE;
698 $pledgeId = $params['open_pledges'][$key];
699 if (is_numeric($pledgeId)) {
700 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
701 $pledgePaymentId = 0;
702 foreach ($result as $key => $values) {
703 if ($values['status'] != 'Completed') {
704 $pledgePaymentId = $values['id'];
708 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
709 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
711 $contribution->contribution_status_id
,
713 $contribution->total_amount
,
720 if (!empty($value['product_name'])) {
721 if ($value['product_name'][0] > 0) {
722 [$products, $options] = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
724 $value['hidden_Premium'] = 1;
725 $value['product_option'] = CRM_Utils_Array
::value(
726 $value['product_name'][1],
727 $options[$value['product_name'][0]]
731 'product_id' => $value['product_name'][0],
732 'contribution_id' => $contribution->id
,
733 'product_option' => $value['product_option'],
736 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
742 if ($contribution->id
&& !empty($value['send_receipt'])) {
743 $value['from_email_address'] = $this->getFromEmailAddress();
744 $value['contribution_id'] = $contribution->id
;
745 if (!empty($value['soft_credit'])) {
746 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
748 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
756 * Process membership records.
758 * @param array $params
759 * Array of submitted values.
762 * batch total monetary amount.
764 * @throws \CRM_Core_Exception
765 * @throws \CiviCRM_API3_Exception
766 * @throws \API_Exception
768 private function processMembership(array $params) {
770 // get the price set associated with offline membership
771 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
772 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
774 if (isset($params['field'])) {
775 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
776 foreach ($params['field'] as $key => $value) {
777 // if contact is not selected we should skip the row
778 if (empty($params['primary_contact_id'][$key])) {
781 $value['contact_id'] = $params['primary_contact_id'][$key];
782 $value = $this->standardiseRow($value);
783 $this->currentRow
= $value;
784 $this->currentRowExistingMembership
= NULL;
785 $this->currentRowIsRenewOption
= (int) ($params['member_option'][$key] ??
1);
787 // update contact information
788 $this->updateContactInfo($value);
790 //check for custom data
791 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($this->currentRow
,
794 $value['membership_type_id']
797 // handle soft credit
798 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
799 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
800 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
802 //CRM-15350: if soft-credit-type profile field is disabled or removed then
803 //we choose Gift as default value as per Gift Membership rule
804 if (!empty($params['soft_credit_type'][$key])) {
805 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
808 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
811 $batchTotal +
= $value['total_amount'];
812 $value['batch_id'] = $this->_batchId
;
813 $value['skipRecentView'] = TRUE;
815 $order = new CRM_Financial_BAO_Order();
816 // We use the override total amount because we are dealing with a
817 // possibly tax_inclusive total, which is assumed for the override total.
818 $order->setOverrideTotalAmount((float) $value['total_amount']);
819 $order->setLineItem([
820 'membership_type_id' => $value['membership_type_id'],
821 'financial_type_id' => $value['financial_type_id'],
823 $order->setEntityParameters($this->getCurrentRowMembershipParams(), $key);
825 if (!empty($order->getLineItems())) {
826 $value['lineItems'] = [$order->getPriceSetID() => $order->getPriceFieldIndexedLineItems()];
827 $value['processPriceSet'] = TRUE;
829 // end of contribution related section
830 if ($this->currentRowIsRenew()) {
831 // The following parameter setting may be obsolete.
832 $this->_params
= $params;
835 'end_date' => $value['membership_end_date'] ??
NULL,
836 'start_date' => $value['membership_start_date'] ??
NULL,
839 $membership = $this->legacyProcessMembership(
840 $value['custom'], $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);
849 $this->setCurrentRowMembershipID($membership->id
);
852 $createdOrder = civicrm_api3('Order', 'create', [
853 'line_items' => $order->getLineItemForV3OrderApi(),
854 'receive_date' => $this->currentRow
['receive_date'],
855 'check_number' => $this->currentRow
['check_number'] ??
'',
856 'contact_id' => $this->getCurrentRowContactID(),
857 'batch_id' => $this->_batchId
,
858 'financial_type_id' => $this->currentRow
['financial_type_id'],
859 'payment_instrument_id' => $this->currentRow
['payment_instrument_id'],
861 $this->currentRowContributionID
= $createdOrder['id'];
863 $this->setCurrentRowMembershipID($createdOrder['values'][$this->getCurrentRowContributionID()]['line_item'][0]['entity_id']);
864 if ($this->getCurrentRowPaymentStatus() === 'Completed') {
865 civicrm_api3('Payment', 'create', [
866 'total_amount' => $order->getTotalAmount() +
$order->getTotalTaxAmount(),
867 'check_number' => $this->currentRow
['check_number'] ??
'',
868 'trxn_date' => $this->currentRow
['receive_date'],
869 'trxn_id' => $this->currentRow
['trxn_id'],
870 'payment_instrument_id' => $this->currentRow
['payment_instrument_id'],
871 'contribution_id' => $this->getCurrentRowContributionID(),
872 'is_send_contribution_notification' => FALSE,
876 if (in_array($this->getCurrentRowPaymentStatus(), ['Failed', 'Cancelled'])) {
877 Contribution
::update()
878 ->addValue('contribution_status_id', $this->currentRow
['contribution_status_id'])
879 ->addWhere('id', '=', $this->getCurrentRowContributionID())
884 if (!empty($value['product_name'])) {
885 if ($value['product_name'][0] > 0) {
886 [$products, $options] = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
888 $value['hidden_Premium'] = 1;
889 $value['product_option'] = CRM_Utils_Array
::value(
890 $value['product_name'][1],
891 $options[$value['product_name'][0]]
895 'product_id' => $value['product_name'][0],
896 'contribution_id' => $this->getCurrentRowContributionID(),
897 'product_option' => $value['product_option'],
900 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
906 if ($this->getCurrentRowMembershipID() && !empty($value['send_receipt'])) {
907 $value['membership_id'] = $this->getCurrentRowMembershipID();
908 $this->emailReceipt($this, $value);
916 * Send email receipt.
918 * @param CRM_Core_Form $form
920 * @param array $formValues
923 * true if mail was sent successfully
924 * @throws \CRM_Core_Exception|\API_Exception
927 protected function emailReceipt($form, &$formValues): bool {
928 $membership = new CRM_Member_BAO_Membership();
929 $membership->id
= $this->getCurrentRowMembershipID();
930 $membership->fetch();
931 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
932 if (!empty($formValues['payment_instrument_id'])) {
933 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
934 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
937 $form->assign('module', 'Membership');
938 $form->assign('contactID', $formValues['contact_id']);
940 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
941 $this->assign('contributionID', $this->getCurrentRowContributionID());
943 if (!empty($formValues['contribution_status_id'])) {
944 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
945 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
948 $form->assign('receiptType', $this->currentRowIsRenew() ?
'membership renewal' : 'membership signup');
949 $form->assign('receive_date', CRM_Utils_Array
::value('receive_date', $formValues));
950 $form->assign('formValues', $formValues);
952 $form->assign('mem_start_date', CRM_Utils_Date
::formatDateOnlyLong($membership->start_date
));
953 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
954 $form->assign('mem_end_date', CRM_Utils_Date
::formatDateOnlyLong($membership->end_date
));
956 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
958 [$form->_contributorDisplayName
, $form->_contributorEmail
]
959 = CRM_Contact_BAO_Contact_Location
::getEmailDetails($formValues['contact_id']);
960 $form->_receiptContactId
= $formValues['contact_id'];
962 CRM_Core_BAO_MessageTemplate
::sendTemplate(
964 'groupName' => 'msg_tpl_workflow_membership',
965 'valueName' => 'membership_offline_receipt',
966 'contactId' => $form->_receiptContactId
,
967 'from' => $this->getFromEmailAddress(),
968 'toName' => $form->_contributorDisplayName
,
969 'toEmail' => $form->_contributorEmail
,
970 'PDFFilename' => ts('receipt') . '.pdf',
971 'isEmailPdf' => Civi
::settings()->get('invoice_is_email_pdf'),
972 'contributionId' => $this->getCurrentRowContributionID(),
973 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
977 Contribution
::update(FALSE)
978 ->addWhere('id', '=', $this->getCurrentRowContributionID())
979 ->setValues(['receipt_date', 'now'])
986 * Update contact information.
988 * @param array $value
989 * Associated array of submitted values.
991 private function updateContactInfo(array &$value) {
992 $value['preserveDBName'] = $this->_preserveDefault
;
994 //parse street address, CRM-7768
995 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
997 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
1003 * Function exists purely for unit testing purposes.
1005 * If you feel tempted to use this in live code then it probably means there is some functionality
1006 * that needs to be moved out of the form layer
1008 * @param array $params
1012 public function testProcessMembership($params) {
1013 return $this->processMembership($params);
1017 * Function exists purely for unit testing purposes.
1019 * If you feel tempted to use this in live code then it probably means there is some functionality
1020 * that needs to be moved out of the form layer.
1022 * @param array $params
1026 * @throws \CRM_Core_Exception
1027 * @throws \CiviCRM_API3_Exception
1029 public function testProcessContribution($params) {
1030 return $this->processContribution($params);
1034 * @param $customFieldsFormatted
1035 * @param array $formDates
1037 * @return CRM_Member_BAO_Membership
1039 * @throws \CRM_Core_Exception
1040 * @throws \CiviCRM_API3_Exception
1042 protected function legacyProcessMembership($customFieldsFormatted, $formDates = []): CRM_Member_DAO_Membership
{
1043 $updateStatusId = FALSE;
1044 $changeToday = NULL;
1049 $memParams = $this->getCurrentRowMembershipParams();
1050 $currentMembership = $this->getCurrentMembership();
1052 // Now Renew the membership
1053 if (!$currentMembership['is_current_member']) {
1054 // membership is not CURRENT
1056 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1057 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1059 $this->getCurrentRowMembershipTypeID(),
1063 foreach (['start_date', 'end_date'] as $dateType) {
1064 $memParams[$dateType] = $memParams[$dateType] ?
: ($dates[$dateType] ??
NULL);
1067 $ids['membership'] = $currentMembership['id'];
1069 //set the log start date.
1070 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1074 // CURRENT Membership
1075 $membership = new CRM_Member_DAO_Membership();
1076 $membership->id
= $currentMembership['id'];
1077 $membership->find(TRUE);
1078 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1079 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1081 $this->getCurrentRowMembershipTypeID(),
1085 // Insert renewed dates for CURRENT membership
1086 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1087 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date
::isoToMysql($membership->start_date
);
1088 $memParams['end_date'] = $formDates['end_date'] ??
NULL;
1089 if (empty($memParams['end_date'])) {
1090 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1093 //set the log start date.
1094 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1096 if (!empty($currentMembership['id'])) {
1097 $ids['membership'] = $currentMembership['id'];
1099 $memParams['membership_activity_status'] = $isPayLater ?
'Scheduled' : 'Completed';
1103 //if we decided status here and want to skip status
1104 //calculation in create( ); then need to pass 'skipStatusCal'.
1105 if ($updateStatusId) {
1106 $memParams['status_id'] = $updateStatusId;
1107 $memParams['skipStatusCal'] = TRUE;
1110 //since we are renewing,
1111 //make status override false.
1112 $memParams['is_override'] = FALSE;
1113 $memParams['custom'] = $customFieldsFormatted;
1114 // Load all line items & process all in membership. Don't do in contribution.
1115 // Relevant tests in api_v3_ContributionPageTest.
1116 // @todo stop passing $ids (membership and userId may be set by this point)
1117 $membership = CRM_Member_BAO_Membership
::create($memParams, $ids);
1119 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1120 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1121 $membership->find(TRUE);
1128 * @throws \CRM_Core_Exception
1130 private function getFromEmailAddress(): string {
1131 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
1132 return "$domainEmail[0] <$domainEmail[1]>";
1136 * Standardise the values in the row from profile-weirdness to civi-standard.
1138 * The row uses odd field names such as financial_type rather than financial
1139 * type id. We standardise at this point.
1145 private function standardiseRow(array $row): array {
1146 foreach ($row as $fieldKey => $fieldValue) {
1147 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
1148 $row[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
1151 $renameFieldMapping = [
1152 'financial_type' => 'financial_type_id',
1153 'payment_instrument' => 'payment_instrument_id',
1154 'membership_source' => 'source',
1155 'membership_status' => 'status_id',
1157 foreach ($renameFieldMapping as $weirdProfileName => $betterName) {
1158 // Check if isset as some like payment instrument and source are optional.
1159 if (isset($row[$weirdProfileName]) && empty($row[$betterName])) {
1160 $row[$betterName] = $row[$weirdProfileName];
1161 unset($row[$weirdProfileName]);
1165 // The latter format would be normal here - it's unclear if it is sometimes in the former format.
1166 $row['membership_type_id'] = $row['membership_type_id'] ??
$row['membership_type'][1];
1167 unset($row['membership_type']);
1168 // total_amount is required.
1169 $row['total_amount'] = (float) $row['total_amount'];
1174 * Is the current row a renewal.
1178 * @throws \CRM_Core_Exception
1179 * @throws \CiviCRM_API3_Exception
1181 private function currentRowIsRenew(): bool {
1182 return $this->currentRowIsRenewOption
=== 2 && $this->getCurrentMembership();
1186 * Get any current membership for the current row contact, for the same member organization.
1188 * @return array|bool
1190 * @throws \CiviCRM_API3_Exception
1191 * @throws \CRM_Core_Exception
1193 protected function getCurrentMembership() {
1194 if (!isset($this->currentRowExistingMembership
)) {
1195 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1196 // is the same as the parent org of an existing membership of the contact
1197 $this->currentRowExistingMembership
= CRM_Member_BAO_Membership
::getContactMembership($this->getCurrentRowContactID(), $this->getCurrentRowMembershipTypeID(),
1200 if ($this->currentRowExistingMembership
) {
1201 // Check and fix the membership if it is STALE
1202 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($this->currentRowExistingMembership
);
1205 return $this->currentRowExistingMembership
;
1209 * Get the params as related to the membership entity.
1213 private function getCurrentRowMembershipParams(): array {
1214 return array_merge($this->getCurrentRowCustomParams(), [
1215 'start_date' => $this->currentRow
['membership_start_date'] ??
NULL,
1216 'end_date' => $this->currentRow
['membership_end_date'] ??
NULL,
1217 'join_date' => $this->currentRow
['membership_join_date'] ??
NULL,
1218 'campaign_id' => $this->currentRow
['member_campaign_id'] ??
NULL,
1219 'source' => $this->currentRow
['source'] ??
(!$this->currentRowIsRenew() ?
ts('Batch entry') : ''),
1220 'membership_type_id' => $this->currentRow
['membership_type_id'],
1221 'contact_id' => $this->getCurrentRowContactID(),
1226 * Get the custom value parameters from the current row.
1230 private function getCurrentRowCustomParams(): array {
1232 foreach ($this->currentRow
as $field => $value) {
1233 if (strpos($field, 'custom_') === 0) {
1234 $return[$field] = $value;