3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * This class provides the functionality for batch entry for contributions/memeberships
39 class CRM_Batch_Form_Entry
extends CRM_Core_Form
{
42 * maximum profile fields that will be displayed
45 protected $_rowCount = 1;
55 protected $_batchInfo = array();
58 * store the profile id associated with the batch type
60 protected $_profileId;
68 public $_membershipId = null;
70 * when not to reset sort_name
72 protected $_preserveDefault = TRUE;
77 protected $_contactFields = array();
80 * Fields array of fields in the batch profile
81 * (based on the uf_field table data)
82 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
83 * (although a future refactoring might hopefully change that so it uses the api & the function is not
87 public $_fields = array();
89 * build all the data structures needed to build the form
94 function preProcess() {
95 $this->_batchId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this, TRUE);
97 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this, FALSE, 'browse');
99 if (empty($this->_batchInfo
)) {
100 $params = array('id' => $this->_batchId
);
101 CRM_Batch_BAO_Batch
::retrieve($params, $this->_batchInfo
);
103 $this->assign('batchTotal', !empty($this->_batchInfo
['total']) ?
$this->_batchInfo
['total'] : NULL);
104 $this->assign('batchType', $this->_batchInfo
['type_id']);
106 // get the profile id associted with this batch type
107 $this->_profileId
= CRM_Batch_BAO_Batch
::getProfileId($this->_batchInfo
['type_id']);
109 CRM_Core_Resources
::singleton()
110 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js')
111 ->addSetting(array('batch' => array('type_id' => $this->_batchInfo
['type_id'])))
112 ->addSetting(array('setting' => array('monetaryThousandSeparator' => CRM_Core_Config
::singleton()->monetaryThousandSeparator
)))
113 ->addSetting(array('setting' => array('monetaryDecimalPoint' => CRM_Core_Config
::singleton()->monetaryDecimalPoint
)));
124 function buildQuickForm() {
125 if (!$this->_profileId
) {
126 CRM_Core_Error
::fatal(ts('Profile for bulk data entry is missing.'));
129 $this->addElement('hidden', 'batch_id', $this->_batchId
);
131 // get the profile information
132 if ($this->_batchInfo
['type_id'] == 1) {
133 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Contributions'));
134 $customFields = CRM_Core_BAO_CustomField
::getFields('Contribution');
137 CRM_Utils_System
::setTitle(ts('Batch Data Entry for Memberships'));
138 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership');
141 $this->_fields
= array();
142 $this->_fields
= CRM_Core_BAO_UFGroup
::getFields($this->_profileId
, FALSE, CRM_Core_Action
::VIEW
);
144 // remove file type field and then limit fields
145 $suppressFields = FALSE;
146 $removehtmlTypes = array('File', 'Autocomplete-Select');
147 foreach ($this->_fields
as $name => $field) {
148 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($name) &&
149 in_array($this->_fields
[$name]['html_type'], $removehtmlTypes)
151 $suppressFields = TRUE;
152 unset($this->_fields
[$name]);
155 //fix to reduce size as we are using this field in grid
156 if (is_array($field['attributes']) && $this->_fields
[$name]['attributes']['size'] > 19) {
157 //shrink class to "form-text-medium"
158 $this->_fields
[$name]['attributes']['size'] = 19;
162 $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this);
164 // add the force save button
165 $forceSave = $this->getButtonName('upload', 'force');
167 $this->addElement('submit',
169 ts('Ignore Mismatch & Process the Batch?')
172 $this->addButtons(array(
175 'name' => ts('Validate & Process the Batch'),
180 'name' => ts('Save & Continue Later'),
185 $this->assign('rowCount', $this->_batchInfo
['item_count'] +
1);
187 $fileFieldExists = FALSE;
188 $preserveDefaultsArray = array(
189 'first_name', 'last_name', 'middle_name',
194 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
195 $contactReturnProperties = array();
196 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
197 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array('create' => TRUE, 'placeholder' => ts('- select -')));
199 // special field specific to membership batch udpate
200 if ($this->_batchInfo
['type_id'] == 2) {
202 1 => ts('Add Membership'),
203 2 => ts('Renew Membership'),
205 $this->add('select', "member_option[$rowNumber]", '', $options);
208 foreach ($this->_fields
as $name => $field) {
209 if (in_array($field['field_type'], $contactTypes)) {
210 $fld = explode('-', $field['name']);
211 $contactReturnProperties[$field['name']] = $fld[0];
213 CRM_Core_BAO_UFGroup
::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
215 if (in_array($field['name'], $preserveDefaultsArray)) {
216 $this->_preserveDefault
= FALSE;
221 $this->assign('fields', $this->_fields
);
222 CRM_Core_Resources
::singleton()
223 ->addSetting(array('contact' => array(
224 'return' => implode(',', $contactReturnProperties),
225 'fieldmap' => array_flip($contactReturnProperties),
228 // don't set the status message when form is submitted.
229 $buttonName = $this->controller
->getButtonName('submit');
231 if ($suppressFields && $buttonName != '_qf_Entry_next') {
232 CRM_Core_Session
::setStatus(ts("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update."), ts("Some fields have been excluded."), "info");
239 * @param array $params posted values of the form
240 * @param array $files list of errors to be posted back to the form
241 * @param array $self form object
243 * @return array list of errors to be posted back to the form
247 static function formRule($params, $files, $self) {
250 if (!empty($params['_qf_Entry_upload_force'])) {
255 foreach ($params['field'] as $key => $value) {
256 $batchTotal +
= $value['total_amount'];
258 //validate for soft credit fields
259 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
260 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
262 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'])) {
263 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
266 //membership type is required for membership batch entry
267 if ( $self->_batchInfo
['type_id'] == 2 ) {
268 if (empty($value['membership_type'][1])) {
269 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
274 if ($batchTotal != $self->_batchInfo
['total']) {
275 $self->assign('batchAmountMismatch', TRUE);
276 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
279 if (!empty($errors)) {
283 $self->assign('batchAmountMismatch', FALSE);
288 * Override default cancel action
290 function cancelAction() {
291 // redirect to batch listing
292 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
293 CRM_Utils_System
::civiExit();
297 * This function sets the default values for the form.
303 function setDefaultValues() {
304 if (empty($this->_fields
)) {
308 // for add mode set smart defaults
309 if ( $this->_action
& CRM_Core_Action
::ADD
) {
310 list( $currentDate, $currentTime ) = CRM_Utils_Date
::setDateDefaults( NULL, 'activityDateTime' );
313 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
314 $completeStatus = array_search( 'Completed', $allStatus );
315 $specialFields = array(
316 'join_date' => $currentDate,
317 'receive_date' => $currentDate,
318 'receive_date_time' => $currentTime,
319 'contribution_status_id' => $completeStatus
322 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
323 foreach ($specialFields as $key => $value ) {
324 $defaults['field'][$rowNumber][$key] = $value;
329 // get the cached info from data column of civicrm_batch
330 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
331 $defaults = json_decode($data, TRUE);
332 $defaults = $defaults['values'];
339 * process the form after the input has been submitted and validated
345 public function postProcess() {
346 $params = $this->controller
->exportValues($this->_name
);
348 $params['actualBatchTotal'] = 0;
350 // get the profile information
351 if ($this->_batchInfo
['type_id'] == 1) {
352 $this->processContribution($params);
355 $this->processMembership($params);
358 // update batch to close status
359 $paramValues = array(
360 'id' => $this->_batchId
,
362 'status_id' => CRM_Core_OptionGroup
::getValue('batch_status', 'Closed', 'name'),
363 'total' => $params['actualBatchTotal'],
366 CRM_Batch_BAO_Batch
::create($paramValues);
368 // set success status
369 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
371 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
375 * process contribution records
377 * @param array $params associated array of submitted values
383 private function processContribution(&$params) {
391 // get the price set associated with offline contribution record.
392 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
393 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
394 $fieldID = key($this->_priceSet
['fields']);
396 if (isset($params['field'])) {
397 foreach ($params['field'] as $key => $value) {
398 // if contact is not selected we should skip the row
399 if (empty($params['primary_contact_id'][$key])) {
403 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
405 // update contact information
406 $this->updateContactInfo($value);
408 //build soft credit params
409 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
410 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
411 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
412 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['field'][$key]['soft_credit_type'];
415 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
416 CRM_Core_DAO
::$_nullObject,
421 foreach ($dates as $val) {
422 if (!empty($value[$val])) {
423 $value[$val] = CRM_Utils_Date
::processDate( $value[$val], $value[$val . '_time'], TRUE );
427 if (!empty($value['send_receipt'])) {
428 $value['receipt_date'] = date('Y-m-d His');
431 if ($value['financial_type']) {
432 $value['financial_type_id'] = $value['financial_type'];
435 if (!empty($value['payment_instrument'])) {
436 $value['payment_instrument_id'] = $value['payment_instrument'];
439 if (!empty($value['contribution_source'])) {
440 $value['source'] = $value['contribution_source'];
443 if (!empty($value['contribution_note'])) {
444 $value['note'] = $value['contribution_note'];
447 $params['actualBatchTotal'] +
= $value['total_amount'];
449 unset($value['contribution_note']);
450 unset($value['financial_type']);
451 unset($value['contribution_source']);
453 $value['batch_id'] = $this->_batchId
;
454 $value['skipRecentView'] = TRUE;
456 // build line item params
457 $this->_priceSet
['fields'][$fieldID]['options'][$fieldID]['amount'] = $value['total_amount'];
458 $value['price_'.$fieldID] = 1;
461 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
463 //unset amount level since we always use quick config price set
464 unset($value['amount_level']);
466 //CRM-11529 for backoffice transactions
467 //when financial_type_id is passed in form, update the
468 //lineitems with the financial type selected in form
469 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
470 foreach ($lineItem[$priceSetId] as &$values) {
471 $values['financial_type_id'] = $value['financial_type_id'];
474 $value['line_item'] = $lineItem;
476 //finally call contribution create for all the magic
477 $contribution = CRM_Contribute_BAO_Contribution
::create($value, CRM_Core_DAO
::$_nullArray);
480 if (!empty($value['product_name'])) {
481 if ($value['product_name'][0] > 0) {
482 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
484 $value['hidden_Premium'] = 1;
485 $value['product_option'] = CRM_Utils_Array
::value(
486 $value['product_name'][1],
487 $options[$value['product_name'][0]]
490 $premiumParams = array(
491 'product_id' => $value['product_name'][0],
492 'contribution_id' => $contribution->id
,
493 'product_option' => $value['product_option'],
496 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
502 if ( $contribution->id
&& !empty($value['send_receipt'])) {
503 // add the domain email id
504 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
505 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
507 $value['from_email_address'] = $domainEmail;
508 $value['contribution_id'] = $contribution->id
;
509 CRM_Contribute_Form_AdditionalInfo
::emailReceipt( $this, $value );
517 * process membership records
519 * @param array $params associated array of submitted values
525 private function processMembership(&$params) {
527 'join_date' => 'joinDate',
528 'membership_start_date' => 'startDate',
529 'membership_end_date' => 'endDate'
539 // get the price set associated with offline memebership
540 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
541 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
543 if (isset($params['field'])) {
544 $customFields = array();
545 foreach ($params['field'] as $key => $value) {
546 // if contact is not selected we should skip the row
547 if (empty($params['primary_contact_id'][$key])) {
551 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_id']);
553 // update contact information
554 $this->updateContactInfo($value);
556 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
558 foreach ($dateTypes as $dateField => $dateVariable) {
559 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
562 $calcDates = array();
563 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
564 $joinDate, $startDate, $endDate
567 foreach ($calcDates as $memType => $calcDate) {
568 foreach ($dates as $d) {
569 //first give priority to form values then calDates.
570 $date = CRM_Utils_Array
::value($d, $value);
572 $date = CRM_Utils_Array
::value($d, $calcDate);
575 $value[$d] = CRM_Utils_Date
::processDate($date);
579 if (!empty($value['send_receipt'])) {
580 $value['receipt_date'] = date('Y-m-d His');
583 if (!empty($value['membership_source'])) {
584 $value['source'] = $value['membership_source'];
587 unset($value['membership_source']);
589 //Get the membership status
590 if (!empty($value['membership_status'])) {
591 $value['status_id'] = $value['membership_status'];
592 unset($value['membership_status']);
595 if (empty($customFields)) {
596 // membership type custom data
597 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
599 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
600 CRM_Core_BAO_CustomField
::getFields('Membership',
601 FALSE, FALSE, NULL, NULL, TRUE
606 //check for custom data
607 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
614 if (!empty($value['financial_type'])) {
615 $value['financial_type_id'] = $value['financial_type'];
618 if (!empty($value['payment_instrument'])) {
619 $value['payment_instrument_id'] = $value['payment_instrument'];
622 // handle soft credit
623 if (is_array(CRM_Utils_Array
::value('soft_credit_contact_id', $params)) && !empty($params['soft_credit_contact_id'][$key]) && CRM_Utils_Array
::value($key, $params['soft_credit_amount'])) {
624 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
625 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
628 if (!empty($value['receive_date'])) {
629 $value['receive_date'] = CRM_Utils_Date
::processDate( $value['receive_date'], $value['receive_date_time'] , TRUE );
632 $params['actualBatchTotal'] +
= $value['total_amount'];
634 unset($value['financial_type']);
635 unset($value['payment_instrument']);
637 $value['batch_id'] = $this->_batchId
;
638 $value['skipRecentView'] = TRUE;
640 // make entry in line item for contribution
642 $editedFieldParams = array(
643 'price_set_id' => $priceSetId,
644 'name' => $value['membership_type'][0]
647 $editedResults = array();
648 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
650 if (!empty($editedResults)) {
651 unset($this->_priceSet
['fields']);
652 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
653 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
654 $fid = $editedResults['id'];
655 $editedFieldParams = array(
656 'price_field_id' => $editedResults['id'],
657 'membership_type_id' => $value['membership_type_id']
660 $editedResults = array();
661 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
662 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
663 if (!empty($value['total_amount'])) {
664 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
667 $fieldID = key($this->_priceSet
['fields']);
668 $value['price_' . $fieldID] = $editedResults['id'];
671 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
672 $value, $lineItem[$priceSetId]
675 //CRM-11529 for backoffice transactions
676 //when financial_type_id is passed in form, update the
677 //lineitems with the financial type selected in form
678 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
679 foreach ($lineItem[$priceSetId] as &$values) {
680 $values['financial_type_id'] = $value['financial_type_id'];
684 $value['lineItems'] = $lineItem;
685 $value['processPriceSet'] = TRUE;
687 // end of contribution related section
689 unset($value['membership_type']);
690 unset($value['membership_start_date']);
691 unset($value['membership_end_date']);
693 $value['is_renew'] = false;
694 if (!empty($params['member_option']) && CRM_Utils_Array
::value( $key, $params['member_option'] ) == 2 ) {
695 $this->_params
= $params;
696 $value['is_renew'] = true;
697 $membership = CRM_Member_BAO_Membership
::renewMembership(
698 $value['contact_id'],
699 $value['membership_type_id'],
700 FALSE, $this, NULL, NULL,
704 // make contribution entry
705 CRM_Member_BAO_Membership
::recordMembershipContribution( array_merge($value, array('membership_id' => $membership->id
)));
708 $membership = CRM_Member_BAO_Membership
::create($value, CRM_Core_DAO
::$_nullArray);
712 if (!empty($value['product_name'])) {
713 if ($value['product_name'][0] > 0) {
714 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
716 $value['hidden_Premium'] = 1;
717 $value['product_option'] = CRM_Utils_Array
::value(
718 $value['product_name'][1],
719 $options[$value['product_name'][0]]
722 $premiumParams = array(
723 'product_id' => $value['product_name'][0],
724 'contribution_id' => $value['contribution_id'],
725 'product_option' => $value['product_option'],
728 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
734 if ( $membership->id
&& !empty($value['send_receipt'])) {
736 // add the domain email id
737 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
738 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
740 $value['from_email_address'] = $domainEmail;
741 $value['membership_id'] = $membership->id
;
742 CRM_Member_Form_Membership
::emailReceipt( $this, $value, $membership );
750 * update contact information
752 * @param array $value associated array of submitted values
758 private function updateContactInfo(&$value) {
759 $value['preserveDBName'] = $this->_preserveDefault
;
761 //parse street address, CRM-7768
762 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
764 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
769 * Function exists purely for unit testing purposes. If you feel tempted to use this in live code
770 * then it probably means there is some functionality that needs to be moved
771 * out of the form layer
772 * @param unknown_type $params
774 function testProcessMembership($params) {
775 return $this->processMembership($params);