3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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.
42 protected $_rowCount = 1;
52 protected $_batchInfo = array();
55 * Store the profile id associated with the batch type.
57 protected $_profileId;
66 * When not to reset sort_name.
68 protected $_preserveDefault = TRUE;
73 protected $_contactFields = array();
76 * Fields array of fields in the batch profile.
77 * (based on the uf_field table data)
78 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
79 * (although a future refactoring might hopefully change that so it uses the api & the function is not
83 public $_fields = array();
86 * Monetary fields that may be submitted.
88 * These should get a standardised format in the beginPostProcess function.
90 * These fields are common to many forms. Some may override this.
92 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
95 * Build all the data structures needed to build the form.
97 public function preProcess() {
98 $this->_batchId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
100 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'browse');
102 if (empty($this->_batchInfo
)) {
103 $params = array('id' => $this->_batchId
);
104 CRM_Batch_BAO_Batch
::retrieve($params, $this->_batchInfo
);
106 $this->assign('batchTotal', !empty($this->_batchInfo
['total']) ?
$this->_batchInfo
['total'] : NULL);
107 $this->assign('batchType', $this->_batchInfo
['type_id']);
109 // get the profile id associted with this batch type
110 $this->_profileId
= CRM_Batch_BAO_Batch
::getProfileId($this->_batchInfo
['type_id']);
112 CRM_Core_Resources
::singleton()
113 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
114 ->addSetting(array('batch' => array('type_id' => $this->_batchInfo
['type_id'])))
115 ->addSetting(array('setting' => array('monetaryThousandSeparator' => CRM_Core_Config
::singleton()->monetaryThousandSeparator
)))
116 ->addSetting(array('setting' => array('monetaryDecimalPoint' => CRM_Core_Config
::singleton()->monetaryDecimalPoint
)));
125 public function setBatchID($id) {
126 $this->_batchId
= $id;
130 * Build the form object.
132 public function buildQuickForm() {
133 if (!$this->_profileId
) {
134 CRM_Core_Error
::fatal(ts('Profile for bulk data entry is missing.'));
137 $this->addElement('hidden', 'batch_id', $this->_batchId
);
139 $batchTypes = CRM_Core_Pseudoconstant
::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
140 // get the profile information
141 if ($this->_batchInfo
['type_id'] == $batchTypes['Contribution']) {
142 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Contributions'));
143 $customFields = CRM_Core_BAO_CustomField
::getFields('Contribution');
145 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
146 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Memberships'));
148 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
149 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Pledge Payments'));
151 $this->_fields
= array();
152 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($this->_profileId
, FALSE, CRM_Core_Action
::VIEW
);
154 // remove file type field and then limit fields
155 $suppressFields = FALSE;
156 foreach ($this->_fields
as $name => $field) {
157 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name) && $this->_fields
[$name]['html_type'] == 'Autocomplete-Select') {
158 $suppressFields = TRUE;
159 unset($this->_fields
[$name]);
162 //fix to reduce size as we are using this field in grid
163 if (is_array($field['attributes']) && $this->_fields
[$name]['attributes']['size'] > 19) {
164 //shrink class to "form-text-medium"
165 $this->_fields
[$name]['attributes']['size'] = 19;
169 $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this);
171 // add the force save button
172 $forceSave = $this->getButtonName('upload', 'force');
174 $this->addElement('submit',
176 ts('Ignore Mismatch & Process the Batch?')
179 $this->addButtons(array(
182 'name' => ts('Validate & Process the Batch'),
187 'name' => ts('Save & Continue Later'),
192 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
194 $preserveDefaultsArray = array(
202 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
203 $contactReturnProperties = array();
205 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
206 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array(
208 'placeholder' => ts('- select -'),
211 // special field specific to membership batch udpate
212 if ($this->_batchInfo
['type_id'] == 2) {
214 1 => ts('Add Membership'),
215 2 => ts('Renew Membership'),
217 $this->add('select', "member_option[$rowNumber]", '', $options);
219 if ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
220 $options = array('' => '-select-');
221 $optionTypes = array(
222 '1' => ts('Adjust Pledge Payment Schedule?'),
223 '2' => ts('Adjust Total Pledge Amount?'),
225 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
226 if (!empty($this->_batchId
) && !empty($this->_batchInfo
['data']) && !empty($rowNumber)) {
227 $dataValues = json_decode($this->_batchInfo
['data'], TRUE);
228 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
229 $pledgeIDs = CRM_Pledge_BAO_Pledge
::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
230 foreach ($pledgeIDs as $pledgeID) {
231 $pledgePayment = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeID);
232 $options +
= array($pledgeID => CRM_Utils_Date
::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']);
237 $this->add('select', "open_pledges[$rowNumber]", '', $options);
240 foreach ($this->_fields
as $name => $field) {
241 if (in_array($field['field_type'], $contactTypes)) {
242 $fld = explode('-', $field['name']);
243 $contactReturnProperties[$field['name']] = $fld[0];
245 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
247 if (in_array($field['name'], $preserveDefaultsArray)) {
248 $this->_preserveDefault
= FALSE;
253 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
254 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
255 // An offset value is set to deal with additional vars that are likely passed.
256 // There may be a more accurate way to do this...
257 $offset = 50; // set an offset to account for other vars we are not counting
258 if ((count($this->_elementIndex
) +
$offset) > ini_get("max_input_vars")) {
259 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") . ')'));
262 $this->assign('fields', $this->_fields
);
263 CRM_Core_Resources
::singleton()
266 'return' => implode(',', $contactReturnProperties),
267 'fieldmap' => array_flip($contactReturnProperties),
271 // don't set the status message when form is submitted.
272 $buttonName = $this->controller
->getButtonName('submit');
274 if ($suppressFields && $buttonName != '_qf_Entry_next') {
275 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');
282 * @param array $params
283 * Posted values of the form.
284 * @param array $files
285 * List of errors to be posted back to the form.
286 * @param \CRM_Batch_Form_Entry $self
290 * list of errors to be posted back to the form
292 public static function formRule($params, $files, $self) {
294 $batchTypes = CRM_Core_Pseudoconstant
::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
296 'total_amount' => ts('Amount'),
297 'financial_type' => ts('Financial Type'),
298 'payment_instrument' => ts('Payment Method'),
301 //CRM-16480 if contact is selected, validate financial type and amount field.
302 foreach ($params['field'] as $key => $value) {
303 if (isset($value['trxn_id'])) {
304 if (0 < CRM_Core_DAO
::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', array(1 => array($value['trxn_id'], 'String')))) {
305 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
308 foreach ($fields as $field => $label) {
309 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
310 $errors["field[$key][$field]"] = ts('%1 is a required field.', array(1 => $label));
315 if (!empty($params['_qf_Entry_upload_force'])) {
316 if (!empty($errors)) {
323 foreach ($params['field'] as $key => $value) {
324 $batchTotal +
= $value['total_amount'];
326 //validate for soft credit fields
327 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
328 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
330 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'])) {
331 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
334 //membership type is required for membership batch entry
335 if ($self->_batchInfo
['type_id'] == $batchTypes['Membership']) {
336 if (empty($value['membership_type'][1])) {
337 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
341 if ($self->_batchInfo
['type_id'] == $batchTypes['Pledge Payment']) {
342 foreach (array_unique($params["open_pledges"]) as $value) {
343 if (!empty($value)) {
344 $duplicateRows = array_keys($params["open_pledges"], $value);
346 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
347 foreach ($duplicateRows as $key) {
348 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
353 if ((string) $batchTotal != $self->_batchInfo
['total']) {
354 $self->assign('batchAmountMismatch', TRUE);
355 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
358 if (!empty($errors)) {
362 $self->assign('batchAmountMismatch', FALSE);
367 * Override default cancel action.
369 public function cancelAction() {
370 // redirect to batch listing
371 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
372 CRM_Utils_System
::civiExit();
376 * Set default values for the form.
378 public function setDefaultValues() {
379 if (empty($this->_fields
)) {
383 // for add mode set smart defaults
384 if ($this->_action
& CRM_Core_Action
::ADD
) {
385 $currentDate = date('Y-m-d H-i-s');
387 $completeStatus = CRM_Contribute_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
388 $specialFields = array(
389 'join_date' => date('Y-m-d'),
390 'receive_date' => $currentDate,
391 'contribution_status_id' => $completeStatus,
394 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
395 foreach ($specialFields as $key => $value) {
396 $defaults['field'][$rowNumber][$key] = $value;
401 // get the cached info from data column of civicrm_batch
402 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
403 $defaults = json_decode($data, TRUE);
404 $defaults = $defaults['values'];
411 * Process the form after the input has been submitted and validated.
413 public function postProcess() {
414 $params = $this->controller
->exportValues($this->_name
);
415 $params['actualBatchTotal'] = 0;
417 // get the profile information
418 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
419 if (in_array($this->_batchInfo
['type_id'], array($batchTypes['Pledge Payment'], $batchTypes['Contribution']))) {
420 $this->processContribution($params);
422 elseif ($this->_batchInfo
['type_id'] == $batchTypes['Membership']) {
423 $this->processMembership($params);
426 // update batch to close status
427 $paramValues = array(
428 'id' => $this->_batchId
,
430 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
431 'total' => $params['actualBatchTotal'],
434 CRM_Batch_BAO_Batch
::create($paramValues);
436 // set success status
437 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
439 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
443 * Process contribution records.
445 * @param array $params
446 * Associated array of submitted values.
450 private function processContribution(&$params) {
452 foreach ($this->submittableMoneyFields
as $moneyField) {
453 foreach ($params['field'] as $index => $fieldValues) {
454 if (isset($fieldValues[$moneyField])) {
455 $params['field'][$index][$moneyField] = CRM_Utils_Rule
::cleanMoney($params['field'][$index][$moneyField]);
459 $params['actualBatchTotal'] = CRM_Utils_Rule
::cleanMoney($params['actualBatchTotal']);
460 // get the price set associated with offline contribution record.
461 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
462 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
463 $priceFieldID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldID($this->_priceSet
);
464 $priceFieldValueID = CRM_Price_BAO_PriceSet
::getOnlyPriceFieldValueID($this->_priceSet
);
466 if (isset($params['field'])) {
467 foreach ($params['field'] as $key => $value) {
468 // if contact is not selected we should skip the row
469 if (empty($params['primary_contact_id'][$key])) {
473 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
475 // update contact information
476 $this->updateContactInfo($value);
478 //build soft credit params
479 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
480 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
481 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
483 //CRM-15350: if soft-credit-type profile field is disabled or removed then
484 //we choose configured SCT default value
485 if (!empty($params['soft_credit_type'][$key])) {
486 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
489 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type");
494 if (!empty($params['pcp_made_through_id'][$key])) {
495 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
496 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
497 if (!empty($params['pcp_roll_nickname'][$key])) {
498 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
500 if (!empty($params['pcp_personal_note'][$key])) {
501 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
505 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
510 if (!empty($value['send_receipt'])) {
511 $value['receipt_date'] = date('Y-m-d His');
513 // these translations & date handling are required because we are calling BAO directly rather than the api
514 $fieldTranslations = array(
515 'financial_type' => 'financial_type_id',
516 'payment_instrument' => 'payment_instrument_id',
517 'contribution_source' => 'source',
518 'contribution_note' => 'note',
521 foreach ($fieldTranslations as $formField => $baoField) {
522 if (isset($value[$formField])) {
523 $value[$baoField] = $value[$formField];
525 unset($value[$formField]);
528 $params['actualBatchTotal'] +
= $value['total_amount'];
529 $value['batch_id'] = $this->_batchId
;
530 $value['skipRecentView'] = TRUE;
532 // build line item params
533 $this->_priceSet
['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
534 $value['price_' . $priceFieldID] = 1;
537 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
539 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
540 // function to get correct amount level consistently. Remove setting of the amount level in
541 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
542 // to cover all variants.
543 unset($value['amount_level']);
545 //CRM-11529 for back office transactions
546 //when financial_type_id is passed in form, update the
547 //line items with the financial type selected in form
548 // @todo - create a price set or price field per financial type & simply choose the appropriate
549 // price field rather than working around the fact that each price_field is supposed to have a financial
550 // type & we are allowing that to be overridden.
551 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
552 foreach ($lineItem[$priceSetId] as &$values) {
553 $values['financial_type_id'] = $value['financial_type_id'];
556 $value['line_item'] = $lineItem;
557 $value['skipCleanMoney'] = TRUE;
558 //finally call contribution create for all the magic
559 $contribution = CRM_Contribute_BAO_Contribution
::create($value);
560 $batchTypes = CRM_Core_Pseudoconstant
::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
561 if (!empty($this->_batchInfo
['type_id']) && ($this->_batchInfo
['type_id'] == $batchTypes['Pledge Payment'])) {
562 $adjustTotalAmount = FALSE;
563 if (isset($params['option_type'][$key])) {
564 if ($params['option_type'][$key] == 2) {
565 $adjustTotalAmount = TRUE;
568 $pledgeId = $params['open_pledges'][$key];
569 if (is_numeric($pledgeId)) {
570 $result = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($pledgeId);
571 $pledgePaymentId = 0;
572 foreach ($result as $key => $values) {
573 if ($values['status'] != 'Completed') {
574 $pledgePaymentId = $values['id'];
578 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id
);
579 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId,
580 array($pledgePaymentId),
581 $contribution->contribution_status_id
,
583 $contribution->total_amount
,
590 if (!empty($value['product_name'])) {
591 if ($value['product_name'][0] > 0) {
592 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
594 $value['hidden_Premium'] = 1;
595 $value['product_option'] = CRM_Utils_Array
::value(
596 $value['product_name'][1],
597 $options[$value['product_name'][0]]
600 $premiumParams = array(
601 'product_id' => $value['product_name'][0],
602 'contribution_id' => $contribution->id
,
603 'product_option' => $value['product_option'],
606 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
612 if ($contribution->id
&& !empty($value['send_receipt'])) {
613 // add the domain email id
614 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
615 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
616 $value['from_email_address'] = $domainEmail;
617 $value['contribution_id'] = $contribution->id
;
618 if (!empty($value['soft_credit'])) {
619 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($contribution->id
));
621 CRM_Contribute_Form_AdditionalInfo
::emailReceipt($this, $value);
629 * Process membership records.
631 * @param array $params
632 * Associated array of submitted values.
637 private function processMembership(&$params) {
639 // get the price set associated with offline membership
640 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
641 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
643 if (isset($params['field'])) {
644 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
645 $customFields = array();
646 foreach ($params['field'] as $key => $value) {
647 foreach ($value as $fieldKey => $fieldValue) {
648 if (isset($this->_fields
[$fieldKey]) && $this->_fields
[$fieldKey]['data_type'] === 'Money') {
649 $value[$fieldKey] = CRM_Utils_Rule
::cleanMoney($fieldValue);
652 // if contact is not selected we should skip the row
653 if (empty($params['primary_contact_id'][$key])) {
657 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
659 // update contact information
660 $this->updateContactInfo($value);
662 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
664 if (!empty($value['send_receipt'])) {
665 $value['receipt_date'] = date('Y-m-d His');
668 if (!empty($value['membership_source'])) {
669 $value['source'] = $value['membership_source'];
672 unset($value['membership_source']);
674 //Get the membership status
675 if (!empty($value['membership_status'])) {
676 $value['status_id'] = $value['membership_status'];
677 unset($value['membership_status']);
680 if (empty($customFields)) {
681 // membership type custom data
682 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
684 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
685 CRM_Core_BAO_CustomField
::getFields('Membership',
686 FALSE, FALSE, NULL, NULL, TRUE
691 //check for custom data
692 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
698 if (!empty($value['financial_type'])) {
699 $value['financial_type_id'] = $value['financial_type'];
702 if (!empty($value['payment_instrument'])) {
703 $value['payment_instrument_id'] = $value['payment_instrument'];
706 // handle soft credit
707 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
708 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
709 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
711 //CRM-15350: if soft-credit-type profile field is disabled or removed then
712 //we choose Gift as default value as per Gift Membership rule
713 if (!empty($params['soft_credit_type'][$key])) {
714 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
717 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
720 if (!empty($value['total_amount'])) {
721 $value['total_amount'] = (float) $value['total_amount'];
724 $params['actualBatchTotal'] +
= $value['total_amount'];
726 unset($value['financial_type']);
727 unset($value['payment_instrument']);
729 $value['batch_id'] = $this->_batchId
;
730 $value['skipRecentView'] = TRUE;
732 // make entry in line item for contribution
734 $editedFieldParams = array(
735 'price_set_id' => $priceSetId,
736 'name' => $value['membership_type'][0],
739 $editedResults = array();
740 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
742 if (!empty($editedResults)) {
743 unset($this->_priceSet
['fields']);
744 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
745 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
746 $fid = $editedResults['id'];
747 $editedFieldParams = array(
748 'price_field_id' => $editedResults['id'],
749 'membership_type_id' => $value['membership_type_id'],
752 $editedResults = array();
753 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
754 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
755 if (!empty($value['total_amount'])) {
756 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
759 $fieldID = key($this->_priceSet
['fields']);
760 $value['price_' . $fieldID] = $editedResults['id'];
763 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
764 $value, $lineItem[$priceSetId]
767 //CRM-11529 for backoffice transactions
768 //when financial_type_id is passed in form, update the
769 //lineitems with the financial type selected in form
770 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
771 foreach ($lineItem[$priceSetId] as &$values) {
772 $values['financial_type_id'] = $value['financial_type_id'];
776 $value['lineItems'] = $lineItem;
777 $value['processPriceSet'] = TRUE;
779 // end of contribution related section
781 unset($value['membership_type']);
783 $value['is_renew'] = FALSE;
784 if (!empty($params['member_option']) && CRM_Utils_Array
::value($key, $params['member_option']) == 2) {
786 // The following parameter setting may be obsolete.
787 $this->_params
= $params;
788 $value['is_renew'] = TRUE;
789 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $params);
791 if (isset($this->_values
) && is_array($this->_values
) && !empty($this->_values
)) {
792 $campaignId = CRM_Utils_Array
::value('campaign_id', $this->_params
);
793 if (!array_key_exists('campaign_id', $this->_params
)) {
794 $campaignId = CRM_Utils_Array
::value('campaign_id', $this->_values
);
799 'end_date' => CRM_Utils_Array
::value('membership_end_date', $value),
800 'start_date' => CRM_Utils_Array
::value('membership_start_date', $value),
802 $membershipSource = CRM_Utils_Array
::value('source', $value);
803 list($membership) = CRM_Member_BAO_Membership
::processMembership(
804 $value['contact_id'], $value['membership_type_id'], FALSE,
805 //$numTerms should be default to 1.
806 NULL, NULL, $value['custom'], 1, NULL, FALSE,
807 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
810 // make contribution entry
811 $contrbutionParams = array_merge($value, array('membership_id' => $membership->id
));
812 $contrbutionParams['skipCleanMoney'] = TRUE;
813 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
814 // This form should set the correct params & not call this fn directly.
815 CRM_Member_BAO_Membership
::recordMembershipContribution($contrbutionParams);
819 'join_date' => 'joinDate',
820 'membership_start_date' => 'startDate',
821 'membership_end_date' => 'endDate',
830 foreach ($dateTypes as $dateField => $dateVariable) {
831 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
832 $fDate[$dateField] = CRM_Utils_Array
::value($dateField, $value);
835 $calcDates = array();
836 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
837 $joinDate, $startDate, $endDate
840 foreach ($calcDates as $memType => $calcDate) {
841 foreach ($dates as $d) {
842 //first give priority to form values then calDates.
843 $date = CRM_Utils_Array
::value($d, $value);
845 $date = CRM_Utils_Array
::value($d, $calcDate);
848 $value[$d] = CRM_Utils_Date
::processDate($date);
852 unset($value['membership_start_date']);
853 unset($value['membership_end_date']);
855 $membership = CRM_Member_BAO_Membership
::create($value, $ids);
859 if (!empty($value['product_name'])) {
860 if ($value['product_name'][0] > 0) {
861 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
863 $value['hidden_Premium'] = 1;
864 $value['product_option'] = CRM_Utils_Array
::value(
865 $value['product_name'][1],
866 $options[$value['product_name'][0]]
869 $premiumParams = array(
870 'product_id' => $value['product_name'][0],
871 'contribution_id' => CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id'),
872 'product_option' => $value['product_option'],
875 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
881 if ($membership->id
&& !empty($value['send_receipt'])) {
883 // add the domain email id
884 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
885 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
887 $value['from_email_address'] = $domainEmail;
888 $value['membership_id'] = $membership->id
;
889 $value['contribution_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id
, 'contribution_id', 'membership_id');
890 CRM_Member_Form_Membership
::emailReceipt($this, $value, $membership);
898 * Update contact information.
900 * @param array $value
901 * Associated array of submitted values.
903 private function updateContactInfo(&$value) {
904 $value['preserveDBName'] = $this->_preserveDefault
;
906 //parse street address, CRM-7768
907 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
909 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
915 * Function exists purely for unit testing purposes.
917 * If you feel tempted to use this in live code then it probably means there is some functionality
918 * that needs to be moved out of the form layer
920 * @param array $params
924 public function testProcessMembership($params) {
925 return $this->processMembership($params);
929 * Function exists purely for unit testing purposes.
931 * If you feel tempted to use this in live code then it probably means there is some functionality
932 * that needs to be moved out of the form layer.
934 * @param array $params
938 public function testProcessContribution($params) {
939 return $this->processContribution($params);