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 contact ID for the current row.
144 public function getCurrentRowContactID(): int {
145 return $this->currentRow
['contact_id'];
149 * Get the membership type ID for the current row.
153 public function getCurrentRowMembershipTypeID(): int {
154 return $this->currentRow
['membership_type_id'];
158 * Set the membership id for the current row.
160 * @param int $currentRowMembershipID
162 public function setCurrentRowMembershipID(int $currentRowMembershipID): void
{
163 $this->currentRowMembershipID
= $currentRowMembershipID;
169 protected $currentRowMembershipID;
172 * Monetary fields that may be submitted.
174 * These should get a standardised format in the beginPostProcess function.
176 * These fields are common to many forms. Some may override this.
179 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
182 * Build all the data structures needed to build the form.
184 * @throws \CRM_Core_Exception
186 public function preProcess() {
187 $this->_batchId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
189 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'browse');
191 if (empty($this->_batchInfo
)) {
192 $params = ['id' => $this->_batchId
];
193 CRM_Batch_BAO_Batch
::retrieve($params, $this->_batchInfo
);
195 $this->assign('batchTotal', !empty($this->_batchInfo
['total']) ?
$this->_batchInfo
['total'] : NULL);
196 $this->assign('batchType', $this->_batchInfo
['type_id']);
198 // get the profile id associted with this batch type
199 $this->_profileId
= CRM_Batch_BAO_Batch
::getProfileId($this->_batchInfo
['type_id']);
201 CRM_Core_Resources
::singleton()
202 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
203 ->addSetting(['batch' => ['type_id' => $this->_batchInfo
['type_id']]])
204 ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config
::singleton()->monetaryThousandSeparator
]])
205 ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config
::singleton()->monetaryDecimalPoint
]]);
207 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country
::defaultCurrencySymbol());
215 public function setBatchID($id) {
216 $this->_batchId
= $id;
220 * Build the form object.
222 * @throws \CRM_Core_Exception
224 public function buildQuickForm() {
225 if (!$this->_profileId
) {
226 CRM_Core_Error
::statusBounce(ts('Profile for bulk data entry is missing.'));
229 $this->addElement('hidden', 'batch_id', $this->_batchId
);
231 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
232 // get the profile information
233 if ($this->_batchInfo
['type_id'] == $batchTypes['Contribution']) {
234 $this->setTitle(ts('Batch Data Entry for Contributions'));
236 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
237 $this->setTitle(ts('Batch Data Entry for Memberships'));
239 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
240 $this->setTitle(ts('Batch Data Entry for Pledge Payments'));
243 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($this->_profileId
, FALSE, CRM_Core_Action
::VIEW
);
245 // remove file type field and then limit fields
246 $suppressFields = FALSE;
247 foreach ($this->_fields
as $name => $field) {
248 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name) && $this->_fields
[$name]['html_type'] == 'Autocomplete-Select') {
249 $suppressFields = TRUE;
250 unset($this->_fields
[$name]);
253 //fix to reduce size as we are using this field in grid
254 if (is_array($field['attributes']) && $this->_fields
[$name]['attributes']['size'] > 19) {
255 //shrink class to "form-text-medium"
256 $this->_fields
[$name]['attributes']['size'] = 19;
260 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
262 // add the force save button
263 $forceSave = $this->getButtonName('upload', 'force');
265 $this->addElement('xbutton',
267 ts('Ignore Mismatch & Process the Batch?'),
271 'class' => 'crm-button crm-button_qf_Entry_upload_force-save',
278 'name' => ts('Validate & Process the Batch'),
283 'name' => ts('Save & Continue Later'),
287 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
289 $preserveDefaultsArray = [
297 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
298 $contactReturnProperties = [];
300 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
301 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
303 'placeholder' => ts('- select -'),
306 // special field specific to membership batch udpate
307 if ($this->_batchInfo
['type_id'] == 2) {
309 1 => ts('Add Membership'),
310 2 => ts('Renew Membership'),
312 $this->add('select', "member_option[$rowNumber]", '', $options);
314 if ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
315 $options = ['' => '-select-'];
317 '1' => ts('Adjust Pledge Payment Schedule?'),
318 '2' => ts('Adjust Total Pledge Amount?'),
320 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
321 if (!empty($this->_batchId
) && !empty($this->_batchInfo
['data']) && !empty($rowNumber)) {
322 $dataValues = json_decode($this->_batchInfo
['data'], TRUE);
323 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
324 $pledgeIDs = CRM_Pledge_BAO_Pledge
::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
325 foreach ($pledgeIDs as $pledgeID) {
326 $pledgePayment = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeID);
327 $options +
= [$pledgeID => CRM_Utils_Date
::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
332 $this->add('select', "open_pledges[$rowNumber]", '', $options);
335 foreach ($this->_fields
as $name => $field) {
336 if (in_array($field['field_type'], $contactTypes)) {
337 $fld = explode('-', $field['name']);
338 $contactReturnProperties[$field['name']] = $fld[0];
340 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
342 if (in_array($field['name'], $preserveDefaultsArray)) {
343 $this->_preserveDefault
= FALSE;
348 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
349 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
350 // An offset value is set to deal with additional vars that are likely passed.
351 // There may be a more accurate way to do this...
352 // set an offset to account for other vars we are not counting
354 if ((count($this->_elementIndex
) +
$offset) > ini_get("max_input_vars")) {
355 // Avoiding 'ts' for obscure messages.
356 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")]));
359 $this->assign('fields', $this->_fields
);
360 CRM_Core_Resources
::singleton()
363 'return' => implode(',', $contactReturnProperties),
364 'fieldmap' => array_flip($contactReturnProperties),
368 // don't set the status message when form is submitted.
369 $buttonName = $this->controller
->getButtonName('submit');
371 if ($suppressFields && $buttonName != '_qf_Entry_next') {
372 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');
379 * @param array $params
380 * Posted values of the form.
381 * @param array $files
382 * List of errors to be posted back to the form.
383 * @param \CRM_Batch_Form_Entry $self
387 * list of errors to be posted back to the form
389 public static function formRule($params, $files, $self) {
391 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
393 'total_amount' => ts('Amount'),
394 'financial_type' => ts('Financial Type'),
395 'payment_instrument' => ts('Payment Method'),
398 //CRM-16480 if contact is selected, validate financial type and amount field.
399 foreach ($params['field'] as $key => $value) {
400 if (isset($value['trxn_id'])) {
401 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
402 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
405 foreach ($fields as $field => $label) {
406 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
407 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
412 if (!empty($params['_qf_Entry_upload_force'])) {
413 if (!empty($errors)) {
420 foreach ($params['field'] as $key => $value) {
421 $batchTotal +
= $value['total_amount'];
423 //validate for soft credit fields
424 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
425 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
427 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'])) {
428 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
431 //membership type is required for membership batch entry
432 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
433 if (empty($value['membership_type'][1])) {
434 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
438 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
439 foreach (array_unique($params["open_pledges"]) as $value) {
440 if (!empty($value)) {
441 $duplicateRows = array_keys($params["open_pledges"], $value);
443 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
444 foreach ($duplicateRows as $key) {
445 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
450 if ((string) $batchTotal != $self->_batchInfo
['total']) {
451 $self->assign('batchAmountMismatch', TRUE);
452 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
455 if (!empty($errors)) {
459 $self->assign('batchAmountMismatch', FALSE);
464 * Override default cancel action.
466 public function cancelAction() {
467 // redirect to batch listing
468 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
469 CRM_Utils_System
::civiExit();
473 * Set default values for the form.
475 * @throws \CRM_Core_Exception
477 public function setDefaultValues() {
478 if (empty($this->_fields
)) {
482 // for add mode set smart defaults
483 if ($this->_action
& CRM_Core_Action
::ADD
) {
484 $currentDate = date('Y-m-d H-i-s');
486 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
488 'membership_join_date' => date('Y-m-d'),
489 'receive_date' => $currentDate,
490 'contribution_status_id' => $completeStatus,
493 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
494 foreach ($specialFields as $key => $value) {
495 $defaults['field'][$rowNumber][$key] = $value;
500 // get the cached info from data column of civicrm_batch
501 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
502 $defaults = json_decode($data, TRUE);
503 $defaults = $defaults['values'];
510 * Process the form after the input has been submitted and validated.
512 * @throws \CRM_Core_Exception
513 * @throws \CiviCRM_API3_Exception
515 public function postProcess() {
516 $params = $this->controller
->exportValues($this->_name
);
517 $params['actualBatchTotal'] = 0;
519 // get the profile information
520 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
521 if (in_array($this->_batchInfo
['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
522 $this->processContribution($params);
524 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
525 $params['actualBatchTotal'] = $this->processMembership($params);
528 // update batch to close status
530 'id' => $this->_batchId
,
532 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
533 'total' => $params['actualBatchTotal'],
536 CRM_Batch_BAO_Batch
::create($paramValues);
538 // set success status
539 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
541 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
545 * Process contribution records.
547 * @param array $params
548 * Associated array of submitted values.
552 * @throws \CRM_Core_Exception
553 * @throws \CiviCRM_API3_Exception
555 private function processContribution(&$params) {
557 foreach ($this->submittableMoneyFields
as $moneyField) {
558 foreach ($params['field'] as $index => $fieldValues) {
559 if (isset($fieldValues[$moneyField])) {
560 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
564 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
565 // get the price set associated with offline contribution record.
566 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
567 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
568 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
569 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
571 if (isset($params['field'])) {
572 foreach ($params['field'] as $key => $value) {
573 // if contact is not selected we should skip the row
574 if (empty($params['primary_contact_id'][$key])) {
578 $value['contact_id'] = $params['primary_contact_id'][$key] ??
NULL;
580 // update contact information
581 $this->updateContactInfo($value);
583 //build soft credit params
584 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
585 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
586 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
588 //CRM-15350: if soft-credit-type profile field is disabled or removed then
589 //we choose configured SCT default value
590 if (!empty($params['soft_credit_type'][$key])) {
591 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
594 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
599 if (!empty($params['pcp_made_through_id'][$key])) {
600 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
601 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
602 if (!empty($params['pcp_roll_nickname'][$key])) {
603 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
605 if (!empty($params['pcp_personal_note'][$key])) {
606 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
610 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
615 if (!empty($value['send_receipt'])) {
616 $value['receipt_date'] = date('Y-m-d His');
618 // these translations & date handling are required because we are calling BAO directly rather than the api
619 $fieldTranslations = [
620 'financial_type' => 'financial_type_id',
621 'payment_instrument' => 'payment_instrument_id',
622 'contribution_source' => 'source',
623 'contribution_note' => 'note',
624 'contribution_check_number' => 'check_number',
626 foreach ($fieldTranslations as $formField => $baoField) {
627 if (isset($value[$formField])) {
628 $value[$baoField] = $value[$formField];
630 unset($value[$formField]);
633 $params['actualBatchTotal'] +
= $value['total_amount'];
634 $value['batch_id'] = $this->_batchId
;
635 $value['skipRecentView'] = TRUE;
637 // build line item params
638 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
639 $value['price_' . $priceFieldID] = 1;
642 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
644 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
645 // function to get correct amount level consistently. Remove setting of the amount level in
646 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
647 // to cover all variants.
648 unset($value['amount_level']);
650 //CRM-11529 for back office transactions
651 //when financial_type_id is passed in form, update the
652 //line items with the financial type selected in form
653 // @todo - create a price set or price field per financial type & simply choose the appropriate
654 // price field rather than working around the fact that each price_field is supposed to have a financial
655 // type & we are allowing that to be overridden.
656 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
657 foreach ($lineItem[$priceSetId] as &$values) {
658 $values['financial_type_id'] = $value['financial_type_id'];
661 $value['line_item'] = $lineItem;
663 //finally call contribution create for all the magic
664 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
665 // This code to retrieve the contribution has been moved here from the contribution create
666 // api. It may not be required.
673 $retrieveRequired = 0;
674 foreach ($titleFields as $titleField) {
675 if (!isset($contribution->$titleField)) {
676 $retrieveRequired = 1;
680 if ($retrieveRequired == 1) {
681 $contribution->find(TRUE);
683 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
684 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
685 $adjustTotalAmount = FALSE;
686 if (isset($params['option_type'][$key])) {
687 if ($params['option_type'][$key] == 2) {
688 $adjustTotalAmount = TRUE;
691 $pledgeId = $params['open_pledges'][$key];
692 if (is_numeric($pledgeId)) {
693 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
694 $pledgePaymentId = 0;
695 foreach ($result as $key => $values) {
696 if ($values['status'] != 'Completed') {
697 $pledgePaymentId = $values['id'];
701 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
702 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
704 $contribution->contribution_status_id
,
706 $contribution->total_amount
,
713 if (!empty($value['product_name'])) {
714 if ($value['product_name'][0] > 0) {
715 [$products, $options] = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
717 $value['hidden_Premium'] = 1;
718 $value['product_option'] = CRM_Utils_Array
::value(
719 $value['product_name'][1],
720 $options[$value['product_name'][0]]
724 'product_id' => $value['product_name'][0],
725 'contribution_id' => $contribution->id
,
726 'product_option' => $value['product_option'],
729 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
735 if ($contribution->id
&& !empty($value['send_receipt'])) {
736 $value['from_email_address'] = $this->getFromEmailAddress();
737 $value['contribution_id'] = $contribution->id
;
738 if (!empty($value['soft_credit'])) {
739 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
741 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
749 * Process membership records.
751 * @param array $params
752 * Array of submitted values.
755 * batch total monetary amount.
757 * @throws \CRM_Core_Exception
758 * @throws \CiviCRM_API3_Exception
759 * @throws \API_Exception
761 private function processMembership(array $params) {
763 // get the price set associated with offline membership
764 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
765 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
767 if (isset($params['field'])) {
768 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
769 foreach ($params['field'] as $key => $value) {
770 // if contact is not selected we should skip the row
771 if (empty($params['primary_contact_id'][$key])) {
774 $value['contact_id'] = $params['primary_contact_id'][$key];
775 $value = $this->standardiseRow($value);
776 $this->currentRow
= $value;
777 $this->currentRowExistingMembership
= NULL;
778 $this->currentRowIsRenewOption
= (int) ($params['member_option'][$key] ??
1);
780 // update contact information
781 $this->updateContactInfo($value);
783 //check for custom data
784 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
787 $value['membership_type_id']
790 // handle soft credit
791 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
792 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
793 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
795 //CRM-15350: if soft-credit-type profile field is disabled or removed then
796 //we choose Gift as default value as per Gift Membership rule
797 if (!empty($params['soft_credit_type'][$key])) {
798 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
801 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
804 $batchTotal +
= $value['total_amount'];
805 $value['batch_id'] = $this->_batchId
;
806 $value['skipRecentView'] = TRUE;
808 $order = new CRM_Financial_BAO_Order();
809 // We use the override total amount because we are dealing with a
810 // possibly tax_inclusive total, which is assumed for the override total.
811 $order->setOverrideTotalAmount((float) $value['total_amount']);
812 $order->setLineItem([
813 'membership_type_id' => $value['membership_type_id'],
814 'financial_type_id' => $value['financial_type_id'],
817 if (!empty($order->getLineItems())) {
818 $value['lineItems'] = [$order->getPriceSetID() => $order->getPriceFieldIndexedLineItems()];
819 $value['processPriceSet'] = TRUE;
821 // end of contribution related section
823 $membershipParams = $this->getMembershipParams();
825 if ($this->currentRowIsRenew()) {
826 // The following parameter setting may be obsolete.
827 $this->_params
= $params;
830 'end_date' => $value['membership_end_date'] ??
NULL,
831 'start_date' => $value['membership_start_date'] ??
NULL,
833 $membershipSource = $value['source'] ??
NULL;
834 $membership = $this->legacyProcessMembership($value['membership_type_id'],
835 $value['custom'], $membershipSource, ['campaign_id' => $value['member_campaign_id'] ??
NULL], $formDates
838 // make contribution entry
839 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id
]);
840 $contrbutionParams['skipCleanMoney'] = TRUE;
841 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
842 // This form should set the correct params & not call this fn directly.
843 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
844 $this->setCurrentRowMembershipID($membership->id
);
847 // @todo - specify the relevant fields - don't copy all over
848 $membershipParams = array_merge($value, $membershipParams);
849 $membership = CRM_Member_BAO_Membership
::create($membershipParams);
853 if (!empty($value['product_name'])) {
854 if ($value['product_name'][0] > 0) {
855 [$products, $options] = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
857 $value['hidden_Premium'] = 1;
858 $value['product_option'] = CRM_Utils_Array
::value(
859 $value['product_name'][1],
860 $options[$value['product_name'][0]]
864 'product_id' => $value['product_name'][0],
865 'contribution_id' => $this->getCurrentRowContributionID(),
866 'product_option' => $value['product_option'],
869 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
875 if ($membership->id
&& !empty($value['send_receipt'])) {
876 $value['membership_id'] = $membership->id
;
877 $this->emailReceipt($this, $value, $membership);
885 * Send email receipt.
887 * @param CRM_Core_Form $form
889 * @param array $formValues
890 * @param object $membership
894 * true if mail was sent successfully
895 * @throws \CRM_Core_Exception|\API_Exception
898 protected function emailReceipt($form, &$formValues, $membership): bool {
899 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
900 if (!empty($formValues['payment_instrument_id'])) {
901 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
902 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
905 $form->assign('module', 'Membership');
906 $form->assign('contactID', $formValues['contact_id']);
908 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
909 $this->assign('contributionID', $this->getCurrentRowContributionID());
911 if (!empty($formValues['contribution_status_id'])) {
912 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
913 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
916 $form->assign('receiptType', $this->currentRowIsRenew() ?
'membership renewal' : 'membership signup');
917 $form->assign('receive_date', CRM_Utils_Array
::value('receive_date', $formValues));
918 $form->assign('formValues', $formValues);
920 $form->assign('mem_start_date', CRM_Utils_Date
::formatDateOnlyLong($membership->start_date
));
921 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
922 $form->assign('mem_end_date', CRM_Utils_Date
::formatDateOnlyLong($membership->end_date
));
924 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
926 [$form->_contributorDisplayName
, $form->_contributorEmail
]
927 = CRM_Contact_BAO_Contact_Location
::getEmailDetails($formValues['contact_id']);
928 $form->_receiptContactId
= $formValues['contact_id'];
930 CRM_Core_BAO_MessageTemplate
::sendTemplate(
932 'groupName' => 'msg_tpl_workflow_membership',
933 'valueName' => 'membership_offline_receipt',
934 'contactId' => $form->_receiptContactId
,
935 'from' => $this->getFromEmailAddress(),
936 'toName' => $form->_contributorDisplayName
,
937 'toEmail' => $form->_contributorEmail
,
938 'PDFFilename' => ts('receipt') . '.pdf',
939 'isEmailPdf' => Civi
::settings()->get('invoice_is_email_pdf'),
940 'contributionId' => $this->getCurrentRowContributionID(),
941 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
945 Contribution
::update(FALSE)
946 ->addWhere('id', '=', $this->getCurrentRowContributionID())
947 ->setValues(['receipt_date', 'now'])
954 * Update contact information.
956 * @param array $value
957 * Associated array of submitted values.
959 private function updateContactInfo(array &$value) {
960 $value['preserveDBName'] = $this->_preserveDefault
;
962 //parse street address, CRM-7768
963 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
965 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
971 * Function exists purely for unit testing purposes.
973 * If you feel tempted to use this in live code then it probably means there is some functionality
974 * that needs to be moved out of the form layer
976 * @param array $params
980 public function testProcessMembership($params) {
981 return $this->processMembership($params);
985 * Function exists purely for unit testing purposes.
987 * If you feel tempted to use this in live code then it probably means there is some functionality
988 * that needs to be moved out of the form layer.
990 * @param array $params
994 * @throws \CRM_Core_Exception
995 * @throws \CiviCRM_API3_Exception
997 public function testProcessContribution($params) {
998 return $this->processContribution($params);
1002 * @param int $membershipTypeID
1003 * @param $customFieldsFormatted
1004 * @param $membershipSource
1005 * @param $isPayLater
1006 * @param array $memParams
1007 * @param array $formDates
1009 * @return CRM_Member_BAO_Membership
1011 * @throws \CRM_Core_Exception
1012 * @throws \CiviCRM_API3_Exception
1014 protected function legacyProcessMembership($membershipTypeID, $customFieldsFormatted, $membershipSource, $memParams = [], $formDates = []): CRM_Member_DAO_Membership
{
1015 $updateStatusId = FALSE;
1016 $changeToday = NULL;
1022 $currentMembership = $this->getCurrentMembership();
1023 // @todo - remove this if - still here for now to leave whitespace change out of commit.
1025 // Now Renew the membership
1026 if (!$currentMembership['is_current_member']) {
1027 // membership is not CURRENT
1029 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1030 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1036 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1037 foreach (['start_date', 'end_date'] as $dateType) {
1038 $currentMembership[$dateType] = $formDates[$dateType] ??
NULL;
1039 if (empty($currentMembership[$dateType])) {
1040 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1043 $currentMembership['is_test'] = $is_test;
1045 if (!empty($membershipSource)) {
1046 $currentMembership['source'] = $membershipSource;
1049 if (!empty($currentMembership['id'])) {
1050 $ids['membership'] = $currentMembership['id'];
1052 $memParams = array_merge($currentMembership, $memParams);
1053 $memParams['membership_type_id'] = $membershipTypeID;
1055 //set the log start date.
1056 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1060 // CURRENT Membership
1061 $membership = new CRM_Member_DAO_Membership();
1062 $membership->id
= $currentMembership['id'];
1063 $membership->find(TRUE);
1064 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1065 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1071 // Insert renewed dates for CURRENT membership
1072 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1073 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date
::isoToMysql($membership->start_date
);
1074 $memParams['end_date'] = $formDates['end_date'] ??
NULL;
1075 if (empty($memParams['end_date'])) {
1076 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1078 $memParams['membership_type_id'] = $membershipTypeID;
1080 //set the log start date.
1081 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1084 if (!empty($membershipSource)) {
1085 $memParams['source'] = $membershipSource;
1087 elseif (empty($membership->source
)) {
1088 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1089 $currentMembership['id'],
1094 if (!empty($currentMembership['id'])) {
1095 $ids['membership'] = $currentMembership['id'];
1097 $memParams['membership_activity_status'] = $isPayLater ?
'Scheduled' : 'Completed';
1102 //if we decided status here and want to skip status
1103 //calculation in create( ); then need to pass 'skipStatusCal'.
1104 if ($updateStatusId) {
1105 $memParams['status_id'] = $updateStatusId;
1106 $memParams['skipStatusCal'] = TRUE;
1109 //since we are renewing,
1110 //make status override false.
1111 $memParams['is_override'] = FALSE;
1112 $memParams['custom'] = $customFieldsFormatted;
1113 // Load all line items & process all in membership. Don't do in contribution.
1114 // Relevant tests in api_v3_ContributionPageTest.
1115 // @todo stop passing $ids (membership and userId may be set by this point)
1116 $membership = CRM_Member_BAO_Membership
::create($memParams, $ids);
1118 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1119 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1120 $membership->find(TRUE);
1127 * @throws \CRM_Core_Exception
1129 private function getFromEmailAddress(): string {
1130 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
1131 return "$domainEmail[0] <$domainEmail[1]>";
1135 * Standardise the values in the row from profile-weirdness to civi-standard.
1137 * The row uses odd field names such as financial_type rather than financial
1138 * type id. We standardise at this point.
1144 private function standardiseRow(array $row): array {
1145 foreach ($row as $fieldKey => $fieldValue) {
1146 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
1147 $row[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
1150 $renameFieldMapping = [
1151 'financial_type' => 'financial_type_id',
1152 'payment_instrument' => 'payment_instrument_id',
1153 'membership_source' => 'source',
1154 'membership_status' => 'status_id',
1156 foreach ($renameFieldMapping as $weirdProfileName => $betterName) {
1157 // Check if isset as some like payment instrument and source are optional.
1158 if (isset($row[$weirdProfileName]) && empty($row[$betterName])) {
1159 $row[$betterName] = $row[$weirdProfileName];
1160 unset($row[$weirdProfileName]);
1164 // The latter format would be normal here - it's unclear if it is sometimes in the former format.
1165 $row['membership_type_id'] = $row['membership_type_id'] ??
$row['membership_type'][1];
1166 unset($row['membership_type']);
1167 // total_amount is required.
1168 $row['total_amount'] = (float) $row['total_amount'];
1173 * Is the current row a renewal.
1177 * @throws \CRM_Core_Exception
1178 * @throws \CiviCRM_API3_Exception
1180 private function currentRowIsRenew(): bool {
1181 return $this->currentRowIsRenewOption
=== 2 && $this->getCurrentMembership();
1185 * Get any current membership for the current row contact, for the same member organization.
1187 * @return array|bool
1189 * @throws \CiviCRM_API3_Exception
1190 * @throws \CRM_Core_Exception
1192 protected function getCurrentMembership() {
1193 if (!isset($this->currentRowExistingMembership
)) {
1194 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1195 // is the same as the parent org of an existing membership of the contact
1196 $this->currentRowExistingMembership
= CRM_Member_BAO_Membership
::getContactMembership($this->getCurrentRowContactID(), $this->getCurrentRowMembershipTypeID(),
1199 // Check and fix the membership if it is STALE
1200 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($this->currentRowExistingMembership
);
1202 return $this->currentRowExistingMembership
;
1206 * Get the params as related to the membership entity.
1210 private function getMembershipParams(): array {
1212 'start_date' => $this->currentRow
['membership_start_date'] ??
NULL,
1213 'end_date' => $this->currentRow
['membership_end_date'] ??
NULL,
1214 'join_date' => $this->currentRow
['membership_join_date'] ??
NULL,
1215 'campaign_id' => $this->currentRow
['member_campaign_id'] ??
NULL,