3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class provides the functionality for batch entry for contributions/memberships.
37 class CRM_Batch_Form_Entry
extends CRM_Core_Form
{
40 * Maximum profile fields that will be displayed.
43 protected $_rowCount = 1;
55 protected $_batchInfo = [];
58 * Store the profile id associated with the batch type.
61 protected $_profileId;
70 * When not to reset sort_name.
73 protected $_preserveDefault = TRUE;
79 protected $_contactFields = [];
82 * Fields array of fields in the batch profile.
83 * (based on the uf_field table data)
84 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
85 * (although a future refactoring might hopefully change that so it uses the api & the function is not
92 * Monetary fields that may be submitted.
94 * These should get a standardised format in the beginPostProcess function.
96 * These fields are common to many forms. Some may override this.
99 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
102 * Build all the data structures needed to build the form.
104 public function preProcess() {
105 $this->_batchId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
107 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'browse');
109 if (empty($this->_batchInfo
)) {
110 $params = ['id' => $this->_batchId
];
111 CRM_Batch_BAO_Batch
::retrieve($params, $this->_batchInfo
);
113 $this->assign('batchTotal', !empty($this->_batchInfo
['total']) ?
$this->_batchInfo
['total'] : NULL);
114 $this->assign('batchType', $this->_batchInfo
['type_id']);
116 // get the profile id associted with this batch type
117 $this->_profileId
= CRM_Batch_BAO_Batch
::getProfileId($this->_batchInfo
['type_id']);
119 CRM_Core_Resources
::singleton()
120 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
121 ->addSetting(['batch' => ['type_id' => $this->_batchInfo
['type_id']]])
122 ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config
::singleton()->monetaryThousandSeparator
]])
123 ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config
::singleton()->monetaryDecimalPoint
]]);
125 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country
::defaultCurrencySymbol());
133 public function setBatchID($id) {
134 $this->_batchId
= $id;
138 * Build the form object.
140 public function buildQuickForm() {
141 if (!$this->_profileId
) {
142 CRM_Core_Error
::fatal(ts('Profile for bulk data entry is missing.'));
145 $this->addElement('hidden', 'batch_id', $this->_batchId
);
147 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
148 // get the profile information
149 if ($this->_batchInfo
['type_id'] == $batchTypes['Contribution']) {
150 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Contributions'));
151 $customFields = CRM_Core_BAO_CustomField
::getFields('Contribution');
153 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
154 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Memberships'));
156 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
157 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Pledge Payments'));
160 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($this->_profileId
, FALSE, CRM_Core_Action
::VIEW
);
162 // remove file type field and then limit fields
163 $suppressFields = FALSE;
164 foreach ($this->_fields
as $name => $field) {
165 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name) && $this->_fields
[$name]['html_type'] == 'Autocomplete-Select') {
166 $suppressFields = TRUE;
167 unset($this->_fields
[$name]);
170 //fix to reduce size as we are using this field in grid
171 if (is_array($field['attributes']) && $this->_fields
[$name]['attributes']['size'] > 19) {
172 //shrink class to "form-text-medium"
173 $this->_fields
[$name]['attributes']['size'] = 19;
177 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
179 // add the force save button
180 $forceSave = $this->getButtonName('upload', 'force');
182 $this->addElement('submit',
184 ts('Ignore Mismatch & Process the Batch?')
190 'name' => ts('Validate & Process the Batch'),
195 'name' => ts('Save & Continue Later'),
199 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
201 $preserveDefaultsArray = [
209 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
210 $contactReturnProperties = [];
212 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
213 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
215 'placeholder' => ts('- select -'),
218 // special field specific to membership batch udpate
219 if ($this->_batchInfo
['type_id'] == 2) {
221 1 => ts('Add Membership'),
222 2 => ts('Renew Membership'),
224 $this->add('select', "member_option[$rowNumber]", '', $options);
226 if ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
227 $options = ['' => '-select-'];
229 '1' => ts('Adjust Pledge Payment Schedule?'),
230 '2' => ts('Adjust Total Pledge Amount?'),
232 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
233 if (!empty($this->_batchId
) && !empty($this->_batchInfo
['data']) && !empty($rowNumber)) {
234 $dataValues = json_decode($this->_batchInfo
['data'], TRUE);
235 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
236 $pledgeIDs = CRM_Pledge_BAO_Pledge
::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
237 foreach ($pledgeIDs as $pledgeID) {
238 $pledgePayment = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeID);
239 $options +
= [$pledgeID => CRM_Utils_Date
::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
244 $this->add('select', "open_pledges[$rowNumber]", '', $options);
247 foreach ($this->_fields
as $name => $field) {
248 if (in_array($field['field_type'], $contactTypes)) {
249 $fld = explode('-', $field['name']);
250 $contactReturnProperties[$field['name']] = $fld[0];
252 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
254 if (in_array($field['name'], $preserveDefaultsArray)) {
255 $this->_preserveDefault
= FALSE;
260 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
261 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
262 // An offset value is set to deal with additional vars that are likely passed.
263 // There may be a more accurate way to do this...
264 // set an offset to account for other vars we are not counting
266 if ((count($this->_elementIndex
) +
$offset) > ini_get("max_input_vars")) {
267 // Avoiding 'ts' for obscure messages.
268 CRM_Core_Error
::fatal('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = ' . ini_get("max_input_vars") . ')');
271 $this->assign('fields', $this->_fields
);
272 CRM_Core_Resources
::singleton()
275 'return' => implode(',', $contactReturnProperties),
276 'fieldmap' => array_flip($contactReturnProperties),
280 // don't set the status message when form is submitted.
281 $buttonName = $this->controller
->getButtonName('submit');
283 if ($suppressFields && $buttonName != '_qf_Entry_next') {
284 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');
291 * @param array $params
292 * Posted values of the form.
293 * @param array $files
294 * List of errors to be posted back to the form.
295 * @param \CRM_Batch_Form_Entry $self
299 * list of errors to be posted back to the form
301 public static function formRule($params, $files, $self) {
303 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
305 'total_amount' => ts('Amount'),
306 'financial_type' => ts('Financial Type'),
307 'payment_instrument' => ts('Payment Method'),
310 //CRM-16480 if contact is selected, validate financial type and amount field.
311 foreach ($params['field'] as $key => $value) {
312 if (isset($value['trxn_id'])) {
313 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
314 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
317 foreach ($fields as $field => $label) {
318 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
319 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
324 if (!empty($params['_qf_Entry_upload_force'])) {
325 if (!empty($errors)) {
332 foreach ($params['field'] as $key => $value) {
333 $batchTotal +
= $value['total_amount'];
335 //validate for soft credit fields
336 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
337 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
339 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'])) {
340 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
343 //membership type is required for membership batch entry
344 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
345 if (empty($value['membership_type'][1])) {
346 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
350 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
351 foreach (array_unique($params["open_pledges"]) as $value) {
352 if (!empty($value)) {
353 $duplicateRows = array_keys($params["open_pledges"], $value);
355 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
356 foreach ($duplicateRows as $key) {
357 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
362 if ((string) $batchTotal != $self->_batchInfo
['total']) {
363 $self->assign('batchAmountMismatch', TRUE);
364 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
367 if (!empty($errors)) {
371 $self->assign('batchAmountMismatch', FALSE);
376 * Override default cancel action.
378 public function cancelAction() {
379 // redirect to batch listing
380 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
381 CRM_Utils_System
::civiExit();
385 * Set default values for the form.
387 public function setDefaultValues() {
388 if (empty($this->_fields
)) {
392 // for add mode set smart defaults
393 if ($this->_action
& CRM_Core_Action
::ADD
) {
394 $currentDate = date('Y-m-d H-i-s');
396 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
398 'join_date' => date('Y-m-d'),
399 'receive_date' => $currentDate,
400 'contribution_status_id' => $completeStatus,
403 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
404 foreach ($specialFields as $key => $value) {
405 $defaults['field'][$rowNumber][$key] = $value;
410 // get the cached info from data column of civicrm_batch
411 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
412 $defaults = json_decode($data, TRUE);
413 $defaults = $defaults['values'];
420 * Process the form after the input has been submitted and validated.
422 public function postProcess() {
423 $params = $this->controller
->exportValues($this->_name
);
424 $params['actualBatchTotal'] = 0;
426 // get the profile information
427 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
428 if (in_array($this->_batchInfo
['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
429 $this->processContribution($params);
431 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
432 $this->processMembership($params);
435 // update batch to close status
437 'id' => $this->_batchId
,
439 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
440 'total' => $params['actualBatchTotal'],
443 CRM_Batch_BAO_Batch
::create($paramValues);
445 // set success status
446 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
448 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
452 * Process contribution records.
454 * @param array $params
455 * Associated array of submitted values.
459 private function processContribution(&$params) {
461 foreach ($this->submittableMoneyFields
as $moneyField) {
462 foreach ($params['field'] as $index => $fieldValues) {
463 if (isset($fieldValues[$moneyField])) {
464 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
468 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
469 // get the price set associated with offline contribution record.
470 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
471 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
472 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
473 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
475 if (isset($params['field'])) {
476 foreach ($params['field'] as $key => $value) {
477 // if contact is not selected we should skip the row
478 if (empty($params['primary_contact_id'][$key])) {
482 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
484 // update contact information
485 $this->updateContactInfo($value);
487 //build soft credit params
488 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
489 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
490 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
492 //CRM-15350: if soft-credit-type profile field is disabled or removed then
493 //we choose configured SCT default value
494 if (!empty($params['soft_credit_type'][$key])) {
495 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
498 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
503 if (!empty($params['pcp_made_through_id'][$key])) {
504 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
505 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
506 if (!empty($params['pcp_roll_nickname'][$key])) {
507 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
509 if (!empty($params['pcp_personal_note'][$key])) {
510 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
514 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
519 if (!empty($value['send_receipt'])) {
520 $value['receipt_date'] = date('Y-m-d His');
522 // these translations & date handling are required because we are calling BAO directly rather than the api
523 $fieldTranslations = [
524 'financial_type' => 'financial_type_id',
525 'payment_instrument' => 'payment_instrument_id',
526 'contribution_source' => 'source',
527 'contribution_note' => 'note',
530 foreach ($fieldTranslations as $formField => $baoField) {
531 if (isset($value[$formField])) {
532 $value[$baoField] = $value[$formField];
534 unset($value[$formField]);
537 $params['actualBatchTotal'] +
= $value['total_amount'];
538 $value['batch_id'] = $this->_batchId
;
539 $value['skipRecentView'] = TRUE;
541 // build line item params
542 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
543 $value['price_' . $priceFieldID] = 1;
546 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
548 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
549 // function to get correct amount level consistently. Remove setting of the amount level in
550 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
551 // to cover all variants.
552 unset($value['amount_level']);
554 //CRM-11529 for back office transactions
555 //when financial_type_id is passed in form, update the
556 //line items with the financial type selected in form
557 // @todo - create a price set or price field per financial type & simply choose the appropriate
558 // price field rather than working around the fact that each price_field is supposed to have a financial
559 // type & we are allowing that to be overridden.
560 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
561 foreach ($lineItem[$priceSetId] as &$values) {
562 $values['financial_type_id'] = $value['financial_type_id'];
565 $value['line_item'] = $lineItem;
566 $value['skipCleanMoney'] = TRUE;
567 //finally call contribution create for all the magic
568 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
569 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
570 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
571 $adjustTotalAmount = FALSE;
572 if (isset($params['option_type'][$key])) {
573 if ($params['option_type'][$key] == 2) {
574 $adjustTotalAmount = TRUE;
577 $pledgeId = $params['open_pledges'][$key];
578 if (is_numeric($pledgeId)) {
579 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
580 $pledgePaymentId = 0;
581 foreach ($result as $key => $values) {
582 if ($values['status'] != 'Completed') {
583 $pledgePaymentId = $values['id'];
587 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
588 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
590 $contribution->contribution_status_id
,
592 $contribution->total_amount
,
599 if (!empty($value['product_name'])) {
600 if ($value['product_name'][0] > 0) {
601 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
603 $value['hidden_Premium'] = 1;
604 $value['product_option'] = CRM_Utils_Array
::value(
605 $value['product_name'][1],
606 $options[$value['product_name'][0]]
610 'product_id' => $value['product_name'][0],
611 'contribution_id' => $contribution->id
,
612 'product_option' => $value['product_option'],
615 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
621 if ($contribution->id
&& !empty($value['send_receipt'])) {
622 // add the domain email id
623 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
624 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
625 $value['from_email_address'] = $domainEmail;
626 $value['contribution_id'] = $contribution->id
;
627 if (!empty($value['soft_credit'])) {
628 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
630 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
638 * Process membership records.
640 * @param array $params
641 * Associated array of submitted values.
646 private function processMembership(&$params) {
648 // get the price set associated with offline membership
649 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
650 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
652 if (isset($params['field'])) {
653 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
655 foreach ($params['field'] as $key => $value) {
656 foreach ($value as $fieldKey => $fieldValue) {
657 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
658 $value[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
661 // if contact is not selected we should skip the row
662 if (empty($params['primary_contact_id'][$key])) {
666 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
668 // update contact information
669 $this->updateContactInfo($value);
671 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
673 if (!empty($value['send_receipt'])) {
674 $value['receipt_date'] = date('Y-m-d His');
677 if (!empty($value['membership_source'])) {
678 $value['source'] = $value['membership_source'];
681 unset($value['membership_source']);
683 //Get the membership status
684 if (!empty($value['membership_status'])) {
685 $value['status_id'] = $value['membership_status'];
686 unset($value['membership_status']);
689 if (empty($customFields)) {
690 // membership type custom data
691 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
693 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
694 CRM_Core_BAO_CustomField
::getFields('Membership',
695 FALSE, FALSE, NULL, NULL, TRUE
700 //check for custom data
701 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
707 if (!empty($value['financial_type'])) {
708 $value['financial_type_id'] = $value['financial_type'];
711 if (!empty($value['payment_instrument'])) {
712 $value['payment_instrument_id'] = $value['payment_instrument'];
715 // handle soft credit
716 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
717 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
718 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
720 //CRM-15350: if soft-credit-type profile field is disabled or removed then
721 //we choose Gift as default value as per Gift Membership rule
722 if (!empty($params['soft_credit_type'][$key])) {
723 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
726 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
729 if (!empty($value['total_amount'])) {
730 $value['total_amount'] = (float) $value['total_amount'];
733 $params['actualBatchTotal'] +
= $value['total_amount'];
735 unset($value['financial_type']);
736 unset($value['payment_instrument']);
738 $value['batch_id'] = $this->_batchId
;
739 $value['skipRecentView'] = TRUE;
741 // make entry in line item for contribution
743 $editedFieldParams = [
744 'price_set_id' => $priceSetId,
745 'name' => $value['membership_type'][0],
749 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
751 if (!empty($editedResults)) {
752 unset($this->_priceSet
['fields']);
753 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
754 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
755 $fid = $editedResults['id'];
756 $editedFieldParams = [
757 'price_field_id' => $editedResults['id'],
758 'membership_type_id' => $value['membership_type_id'],
762 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
763 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
764 if (!empty($value['total_amount'])) {
765 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
768 $fieldID = key($this->_priceSet
['fields']);
769 $value['price_' . $fieldID] = $editedResults['id'];
772 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
773 $value, $lineItem[$priceSetId]
776 //CRM-11529 for backoffice transactions
777 //when financial_type_id is passed in form, update the
778 //lineitems with the financial type selected in form
779 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
780 foreach ($lineItem[$priceSetId] as &$values) {
781 $values['financial_type_id'] = $value['financial_type_id'];
785 $value['lineItems'] = $lineItem;
786 $value['processPriceSet'] = TRUE;
788 // end of contribution related section
790 unset($value['membership_type']);
792 $value['is_renew'] = FALSE;
793 if (!empty($params['member_option']) && CRM_Utils_Array
::value($key, $params['member_option']) == 2) {
795 // The following parameter setting may be obsolete.
796 $this->_params
= $params;
797 $value['is_renew'] = TRUE;
798 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $params);
800 if (isset($this->_values
) && is_array($this->_values
) && !empty($this->_values
)) {
801 $campaignId = CRM_Utils_Array
::value('campaign_id', $this->_params
);
802 if (!array_key_exists('campaign_id', $this->_params
)) {
803 $campaignId = CRM_Utils_Array
::value('campaign_id', $this->_values
);
808 'end_date' => CRM_Utils_Array
::value('membership_end_date', $value),
809 'start_date' => CRM_Utils_Array
::value('membership_start_date', $value),
811 $membershipSource = CRM_Utils_Array
::value('source', $value);
812 list($membership) = CRM_Member_BAO_Membership
::processMembership(
813 $value['contact_id'], $value['membership_type_id'], FALSE,
814 //$numTerms should be default to 1.
815 NULL, NULL, $value['custom'], 1, NULL, FALSE,
816 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
819 // make contribution entry
820 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id
]);
821 $contrbutionParams['skipCleanMoney'] = TRUE;
822 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
823 // This form should set the correct params & not call this fn directly.
824 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
828 'join_date' => 'joinDate',
829 'membership_start_date' => 'startDate',
830 'membership_end_date' => 'endDate',
839 foreach ($dateTypes as $dateField => $dateVariable) {
840 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
841 $fDate[$dateField] = CRM_Utils_Array
::value($dateField, $value);
845 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
846 $joinDate, $startDate, $endDate
849 foreach ($calcDates as $memType => $calcDate) {
850 foreach ($dates as $d) {
851 //first give priority to form values then calDates.
852 $date = CRM_Utils_Array
::value($d, $value);
854 $date = CRM_Utils_Array
::value($d, $calcDate);
857 $value[$d] = CRM_Utils_Date
::processDate($date);
861 unset($value['membership_start_date']);
862 unset($value['membership_end_date']);
864 // @todo stop passing empty $ids
865 $membership = CRM_Member_BAO_Membership
::create($value, $ids);
869 if (!empty($value['product_name'])) {
870 if ($value['product_name'][0] > 0) {
871 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
873 $value['hidden_Premium'] = 1;
874 $value['product_option'] = CRM_Utils_Array
::value(
875 $value['product_name'][1],
876 $options[$value['product_name'][0]]
880 'product_id' => $value['product_name'][0],
881 'contribution_id' => CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id'),
882 'product_option' => $value['product_option'],
885 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
891 if ($membership->id
&& !empty($value['send_receipt'])) {
893 // add the domain email id
894 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
895 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
897 $value['from_email_address'] = $domainEmail;
898 $value['membership_id'] = $membership->id
;
899 $value['contribution_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id');
900 CRM_Member_Form_Membership
::emailReceipt($this, $value, $membership);
908 * Update contact information.
910 * @param array $value
911 * Associated array of submitted values.
913 private function updateContactInfo(&$value) {
914 $value['preserveDBName'] = $this->_preserveDefault
;
916 //parse street address, CRM-7768
917 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
919 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
925 * Function exists purely for unit testing purposes.
927 * If you feel tempted to use this in live code then it probably means there is some functionality
928 * that needs to be moved out of the form layer
930 * @param array $params
934 public function testProcessMembership($params) {
935 return $this->processMembership($params);
939 * Function exists purely for unit testing purposes.
941 * If you feel tempted to use this in live code then it probably means there is some functionality
942 * that needs to be moved out of the form layer.
944 * @param array $params
948 public function testProcessContribution($params) {
949 return $this->processContribution($params);