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 CRM_Core_Error
::fatal(ts('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = ' . ini_get("max_input_vars") . ')'));
270 $this->assign('fields', $this->_fields
);
271 CRM_Core_Resources
::singleton()
274 'return' => implode(',', $contactReturnProperties),
275 'fieldmap' => array_flip($contactReturnProperties),
279 // don't set the status message when form is submitted.
280 $buttonName = $this->controller
->getButtonName('submit');
282 if ($suppressFields && $buttonName != '_qf_Entry_next') {
283 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');
290 * @param array $params
291 * Posted values of the form.
292 * @param array $files
293 * List of errors to be posted back to the form.
294 * @param \CRM_Batch_Form_Entry $self
298 * list of errors to be posted back to the form
300 public static function formRule($params, $files, $self) {
302 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
304 'total_amount' => ts('Amount'),
305 'financial_type' => ts('Financial Type'),
306 'payment_instrument' => ts('Payment Method'),
309 //CRM-16480 if contact is selected, validate financial type and amount field.
310 foreach ($params['field'] as $key => $value) {
311 if (isset($value['trxn_id'])) {
312 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
313 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
316 foreach ($fields as $field => $label) {
317 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
318 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
323 if (!empty($params['_qf_Entry_upload_force'])) {
324 if (!empty($errors)) {
331 foreach ($params['field'] as $key => $value) {
332 $batchTotal +
= $value['total_amount'];
334 //validate for soft credit fields
335 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
336 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
338 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'])) {
339 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
342 //membership type is required for membership batch entry
343 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
344 if (empty($value['membership_type'][1])) {
345 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
349 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
350 foreach (array_unique($params["open_pledges"]) as $value) {
351 if (!empty($value)) {
352 $duplicateRows = array_keys($params["open_pledges"], $value);
354 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
355 foreach ($duplicateRows as $key) {
356 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
361 if ((string) $batchTotal != $self->_batchInfo
['total']) {
362 $self->assign('batchAmountMismatch', TRUE);
363 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
366 if (!empty($errors)) {
370 $self->assign('batchAmountMismatch', FALSE);
375 * Override default cancel action.
377 public function cancelAction() {
378 // redirect to batch listing
379 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
380 CRM_Utils_System
::civiExit();
384 * Set default values for the form.
386 public function setDefaultValues() {
387 if (empty($this->_fields
)) {
391 // for add mode set smart defaults
392 if ($this->_action
& CRM_Core_Action
::ADD
) {
393 $currentDate = date('Y-m-d H-i-s');
395 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
397 'join_date' => date('Y-m-d'),
398 'receive_date' => $currentDate,
399 'contribution_status_id' => $completeStatus,
402 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
403 foreach ($specialFields as $key => $value) {
404 $defaults['field'][$rowNumber][$key] = $value;
409 // get the cached info from data column of civicrm_batch
410 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
411 $defaults = json_decode($data, TRUE);
412 $defaults = $defaults['values'];
419 * Process the form after the input has been submitted and validated.
421 public function postProcess() {
422 $params = $this->controller
->exportValues($this->_name
);
423 $params['actualBatchTotal'] = 0;
425 // get the profile information
426 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
427 if (in_array($this->_batchInfo
['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
428 $this->processContribution($params);
430 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
431 $this->processMembership($params);
434 // update batch to close status
436 'id' => $this->_batchId
,
438 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
439 'total' => $params['actualBatchTotal'],
442 CRM_Batch_BAO_Batch
::create($paramValues);
444 // set success status
445 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
447 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
451 * Process contribution records.
453 * @param array $params
454 * Associated array of submitted values.
458 private function processContribution(&$params) {
460 foreach ($this->submittableMoneyFields
as $moneyField) {
461 foreach ($params['field'] as $index => $fieldValues) {
462 if (isset($fieldValues[$moneyField])) {
463 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
467 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
468 // get the price set associated with offline contribution record.
469 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
470 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
471 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
472 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
474 if (isset($params['field'])) {
475 foreach ($params['field'] as $key => $value) {
476 // if contact is not selected we should skip the row
477 if (empty($params['primary_contact_id'][$key])) {
481 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
483 // update contact information
484 $this->updateContactInfo($value);
486 //build soft credit params
487 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
488 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
489 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
491 //CRM-15350: if soft-credit-type profile field is disabled or removed then
492 //we choose configured SCT default value
493 if (!empty($params['soft_credit_type'][$key])) {
494 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
497 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
502 if (!empty($params['pcp_made_through_id'][$key])) {
503 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
504 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
505 if (!empty($params['pcp_roll_nickname'][$key])) {
506 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
508 if (!empty($params['pcp_personal_note'][$key])) {
509 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
513 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
518 if (!empty($value['send_receipt'])) {
519 $value['receipt_date'] = date('Y-m-d His');
521 // these translations & date handling are required because we are calling BAO directly rather than the api
522 $fieldTranslations = [
523 'financial_type' => 'financial_type_id',
524 'payment_instrument' => 'payment_instrument_id',
525 'contribution_source' => 'source',
526 'contribution_note' => 'note',
529 foreach ($fieldTranslations as $formField => $baoField) {
530 if (isset($value[$formField])) {
531 $value[$baoField] = $value[$formField];
533 unset($value[$formField]);
536 $params['actualBatchTotal'] +
= $value['total_amount'];
537 $value['batch_id'] = $this->_batchId
;
538 $value['skipRecentView'] = TRUE;
540 // build line item params
541 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
542 $value['price_' . $priceFieldID] = 1;
545 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
547 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
548 // function to get correct amount level consistently. Remove setting of the amount level in
549 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
550 // to cover all variants.
551 unset($value['amount_level']);
553 //CRM-11529 for back office transactions
554 //when financial_type_id is passed in form, update the
555 //line items with the financial type selected in form
556 // @todo - create a price set or price field per financial type & simply choose the appropriate
557 // price field rather than working around the fact that each price_field is supposed to have a financial
558 // type & we are allowing that to be overridden.
559 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
560 foreach ($lineItem[$priceSetId] as &$values) {
561 $values['financial_type_id'] = $value['financial_type_id'];
564 $value['line_item'] = $lineItem;
565 $value['skipCleanMoney'] = TRUE;
566 //finally call contribution create for all the magic
567 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
568 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
569 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
570 $adjustTotalAmount = FALSE;
571 if (isset($params['option_type'][$key])) {
572 if ($params['option_type'][$key] == 2) {
573 $adjustTotalAmount = TRUE;
576 $pledgeId = $params['open_pledges'][$key];
577 if (is_numeric($pledgeId)) {
578 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
579 $pledgePaymentId = 0;
580 foreach ($result as $key => $values) {
581 if ($values['status'] != 'Completed') {
582 $pledgePaymentId = $values['id'];
586 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
587 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
589 $contribution->contribution_status_id
,
591 $contribution->total_amount
,
598 if (!empty($value['product_name'])) {
599 if ($value['product_name'][0] > 0) {
600 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
602 $value['hidden_Premium'] = 1;
603 $value['product_option'] = CRM_Utils_Array
::value(
604 $value['product_name'][1],
605 $options[$value['product_name'][0]]
609 'product_id' => $value['product_name'][0],
610 'contribution_id' => $contribution->id
,
611 'product_option' => $value['product_option'],
614 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
620 if ($contribution->id
&& !empty($value['send_receipt'])) {
621 // add the domain email id
622 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
623 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
624 $value['from_email_address'] = $domainEmail;
625 $value['contribution_id'] = $contribution->id
;
626 if (!empty($value['soft_credit'])) {
627 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
629 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
637 * Process membership records.
639 * @param array $params
640 * Associated array of submitted values.
645 private function processMembership(&$params) {
647 // get the price set associated with offline membership
648 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
649 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
651 if (isset($params['field'])) {
652 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
654 foreach ($params['field'] as $key => $value) {
655 foreach ($value as $fieldKey => $fieldValue) {
656 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
657 $value[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
660 // if contact is not selected we should skip the row
661 if (empty($params['primary_contact_id'][$key])) {
665 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
667 // update contact information
668 $this->updateContactInfo($value);
670 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
672 if (!empty($value['send_receipt'])) {
673 $value['receipt_date'] = date('Y-m-d His');
676 if (!empty($value['membership_source'])) {
677 $value['source'] = $value['membership_source'];
680 unset($value['membership_source']);
682 //Get the membership status
683 if (!empty($value['membership_status'])) {
684 $value['status_id'] = $value['membership_status'];
685 unset($value['membership_status']);
688 if (empty($customFields)) {
689 // membership type custom data
690 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
692 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
693 CRM_Core_BAO_CustomField
::getFields('Membership',
694 FALSE, FALSE, NULL, NULL, TRUE
699 //check for custom data
700 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
706 if (!empty($value['financial_type'])) {
707 $value['financial_type_id'] = $value['financial_type'];
710 if (!empty($value['payment_instrument'])) {
711 $value['payment_instrument_id'] = $value['payment_instrument'];
714 // handle soft credit
715 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
716 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
717 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
719 //CRM-15350: if soft-credit-type profile field is disabled or removed then
720 //we choose Gift as default value as per Gift Membership rule
721 if (!empty($params['soft_credit_type'][$key])) {
722 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
725 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
728 if (!empty($value['total_amount'])) {
729 $value['total_amount'] = (float) $value['total_amount'];
732 $params['actualBatchTotal'] +
= $value['total_amount'];
734 unset($value['financial_type']);
735 unset($value['payment_instrument']);
737 $value['batch_id'] = $this->_batchId
;
738 $value['skipRecentView'] = TRUE;
740 // make entry in line item for contribution
742 $editedFieldParams = [
743 'price_set_id' => $priceSetId,
744 'name' => $value['membership_type'][0],
748 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
750 if (!empty($editedResults)) {
751 unset($this->_priceSet
['fields']);
752 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
753 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
754 $fid = $editedResults['id'];
755 $editedFieldParams = [
756 'price_field_id' => $editedResults['id'],
757 'membership_type_id' => $value['membership_type_id'],
761 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
762 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
763 if (!empty($value['total_amount'])) {
764 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
767 $fieldID = key($this->_priceSet
['fields']);
768 $value['price_' . $fieldID] = $editedResults['id'];
771 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
772 $value, $lineItem[$priceSetId]
775 //CRM-11529 for backoffice transactions
776 //when financial_type_id is passed in form, update the
777 //lineitems with the financial type selected in form
778 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
779 foreach ($lineItem[$priceSetId] as &$values) {
780 $values['financial_type_id'] = $value['financial_type_id'];
784 $value['lineItems'] = $lineItem;
785 $value['processPriceSet'] = TRUE;
787 // end of contribution related section
789 unset($value['membership_type']);
791 $value['is_renew'] = FALSE;
792 if (!empty($params['member_option']) && CRM_Utils_Array
::value($key, $params['member_option']) == 2) {
794 // The following parameter setting may be obsolete.
795 $this->_params
= $params;
796 $value['is_renew'] = TRUE;
797 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $params);
799 if (isset($this->_values
) && is_array($this->_values
) && !empty($this->_values
)) {
800 $campaignId = CRM_Utils_Array
::value('campaign_id', $this->_params
);
801 if (!array_key_exists('campaign_id', $this->_params
)) {
802 $campaignId = CRM_Utils_Array
::value('campaign_id', $this->_values
);
807 'end_date' => CRM_Utils_Array
::value('membership_end_date', $value),
808 'start_date' => CRM_Utils_Array
::value('membership_start_date', $value),
810 $membershipSource = CRM_Utils_Array
::value('source', $value);
811 list($membership) = CRM_Member_BAO_Membership
::processMembership(
812 $value['contact_id'], $value['membership_type_id'], FALSE,
813 //$numTerms should be default to 1.
814 NULL, NULL, $value['custom'], 1, NULL, FALSE,
815 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
818 // make contribution entry
819 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id
]);
820 $contrbutionParams['skipCleanMoney'] = TRUE;
821 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
822 // This form should set the correct params & not call this fn directly.
823 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
827 'join_date' => 'joinDate',
828 'membership_start_date' => 'startDate',
829 'membership_end_date' => 'endDate',
838 foreach ($dateTypes as $dateField => $dateVariable) {
839 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
840 $fDate[$dateField] = CRM_Utils_Array
::value($dateField, $value);
844 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
845 $joinDate, $startDate, $endDate
848 foreach ($calcDates as $memType => $calcDate) {
849 foreach ($dates as $d) {
850 //first give priority to form values then calDates.
851 $date = CRM_Utils_Array
::value($d, $value);
853 $date = CRM_Utils_Array
::value($d, $calcDate);
856 $value[$d] = CRM_Utils_Date
::processDate($date);
860 unset($value['membership_start_date']);
861 unset($value['membership_end_date']);
863 // @todo stop passing empty $ids
864 $membership = CRM_Member_BAO_Membership
::create($value, $ids);
868 if (!empty($value['product_name'])) {
869 if ($value['product_name'][0] > 0) {
870 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
872 $value['hidden_Premium'] = 1;
873 $value['product_option'] = CRM_Utils_Array
::value(
874 $value['product_name'][1],
875 $options[$value['product_name'][0]]
879 'product_id' => $value['product_name'][0],
880 'contribution_id' => CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id'),
881 'product_option' => $value['product_option'],
884 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
890 if ($membership->id
&& !empty($value['send_receipt'])) {
892 // add the domain email id
893 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
894 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
896 $value['from_email_address'] = $domainEmail;
897 $value['membership_id'] = $membership->id
;
898 $value['contribution_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id');
899 CRM_Member_Form_Membership
::emailReceipt($this, $value, $membership);
907 * Update contact information.
909 * @param array $value
910 * Associated array of submitted values.
912 private function updateContactInfo(&$value) {
913 $value['preserveDBName'] = $this->_preserveDefault
;
915 //parse street address, CRM-7768
916 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
918 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
924 * Function exists purely for unit testing purposes.
926 * If you feel tempted to use this in live code then it probably means there is some functionality
927 * that needs to be moved out of the form layer
929 * @param array $params
933 public function testProcessMembership($params) {
934 return $this->processMembership($params);
938 * Function exists purely for unit testing purposes.
940 * If you feel tempted to use this in live code then it probably means there is some functionality
941 * that needs to be moved out of the form layer.
943 * @param array $params
947 public function testProcessContribution($params) {
948 return $this->processContribution($params);