3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 CRM_Contact_Form_NewContact
::buildQuickForm($this, $rowNumber, NULL, TRUE, 'primary_', ts('Contact'));
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_select_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 contact name is set for a row using autocomplete widget then make sure contact id exists, CRM-13078
275 // I was not able to replicate this on my local but adding this check and hopefully it will fix the issue.
276 if (!empty($params['primary_contact'])) {
277 foreach($params['primary_contact'] as $rowIndex => $contactName) {
278 if (empty($params['primary_contact_select_id'][$rowIndex])) {
279 $errors['primary_contact['.$rowIndex.']'] = ts('Please select a valid contact.');
284 if ($batchTotal != $self->_batchInfo
['total']) {
285 $self->assign('batchAmountMismatch', TRUE);
286 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
289 if (!empty($errors)) {
293 $self->assign('batchAmountMismatch', FALSE);
298 * Override default cancel action
300 function cancelAction() {
301 // redirect to batch listing
302 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
303 CRM_Utils_System
::civiExit();
307 * This function sets the default values for the form.
313 function setDefaultValues() {
314 if (empty($this->_fields
)) {
318 // for add mode set smart defaults
319 if ( $this->_action
& CRM_Core_Action
::ADD
) {
320 list( $currentDate, $currentTime ) = CRM_Utils_Date
::setDateDefaults( NULL, 'activityDateTime' );
323 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
324 $completeStatus = array_search( 'Completed', $allStatus );
325 $specialFields = array(
326 'join_date' => $currentDate,
327 'receive_date' => $currentDate,
328 'receive_date_time' => $currentTime,
329 'contribution_status_id' => $completeStatus
332 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo
['item_count']; $rowNumber++
) {
333 foreach ($specialFields as $key => $value ) {
334 $defaults['field'][$rowNumber][$key] = $value;
339 // get the cached info from data column of civicrm_batch
340 $data = CRM_Core_DAO
::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId
, 'data');
341 $defaults = json_decode($data, TRUE);
342 $defaults = $defaults['values'];
349 * process the form after the input has been submitted and validated
355 public function postProcess() {
356 $params = $this->controller
->exportValues($this->_name
);
358 $params['actualBatchTotal'] = 0;
360 // get the profile information
361 if ($this->_batchInfo
['type_id'] == 1) {
362 $this->processContribution($params);
365 $this->processMembership($params);
368 // update batch to close status
369 $paramValues = array(
370 'id' => $this->_batchId
,
373 'total' => $params['actualBatchTotal'],
376 CRM_Batch_BAO_Batch
::create($paramValues);
378 // set success status
379 CRM_Core_Session
::setStatus("", ts("Batch Processed."), "success");
381 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/batch', 'reset=1'));
385 * process contribution records
387 * @param array $params associated array of submitted values
393 private function processContribution(&$params) {
401 // get the price set associated with offline contribution record.
402 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
403 $this->_priceSet
= current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
404 $fieldID = key($this->_priceSet
['fields']);
406 if (isset($params['field'])) {
407 foreach ($params['field'] as $key => $value) {
408 // if contact is not selected we should skip the row
409 if (empty($params['primary_contact_select_id'][$key])) {
413 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_select_id']);
415 // update contact information
416 $this->updateContactInfo($value);
418 //build soft credit params
419 if (!empty($params['soft_credit_contact_select_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
420 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_select_id'][$key];
421 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
422 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['field'][$key]['soft_credit_type'];
425 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($value,
426 CRM_Core_DAO
::$_nullObject,
431 foreach ($dates as $val) {
432 if (!empty($value[$val])) {
433 $value[$val] = CRM_Utils_Date
::processDate( $value[$val], $value[$val . '_time'], TRUE );
437 if (!empty($value['send_receipt'])) {
438 $value['receipt_date'] = date('Y-m-d His');
441 if ($value['financial_type']) {
442 $value['financial_type_id'] = $value['financial_type'];
445 if (!empty($value['payment_instrument'])) {
446 $value['payment_instrument_id'] = $value['payment_instrument'];
449 if (!empty($value['contribution_source'])) {
450 $value['source'] = $value['contribution_source'];
453 if (!empty($value['contribution_note'])) {
454 $value['note'] = $value['contribution_note'];
457 $params['actualBatchTotal'] +
= $value['total_amount'];
459 unset($value['contribution_note']);
460 unset($value['financial_type']);
461 unset($value['contribution_source']);
463 $value['batch_id'] = $this->_batchId
;
464 $value['skipRecentView'] = TRUE;
466 // build line item params
467 $this->_priceSet
['fields'][$fieldID]['options'][$fieldID]['amount'] = $value['total_amount'];
468 $value['price_'.$fieldID] = 1;
471 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'], $value, $lineItem[$priceSetId]);
473 //unset amount level since we always use quick config price set
474 unset($value['amount_level']);
476 //CRM-11529 for backoffice transactions
477 //when financial_type_id is passed in form, update the
478 //lineitems with the financial type selected in form
479 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
480 foreach ($lineItem[$priceSetId] as &$values) {
481 $values['financial_type_id'] = $value['financial_type_id'];
484 $value['line_item'] = $lineItem;
486 //finally call contribution create for all the magic
487 $contribution = CRM_Contribute_BAO_Contribution
::create($value, CRM_Core_DAO
::$_nullArray);
490 if (!empty($value['product_name'])) {
491 if ($value['product_name'][0] > 0) {
492 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
494 $value['hidden_Premium'] = 1;
495 $value['product_option'] = CRM_Utils_Array
::value(
496 $value['product_name'][1],
497 $options[$value['product_name'][0]]
500 $premiumParams = array(
501 'product_id' => $value['product_name'][0],
502 'contribution_id' => $contribution->id
,
503 'product_option' => $value['product_option'],
506 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
512 if ( $contribution->id
&& !empty($value['send_receipt'])) {
513 // add the domain email id
514 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
515 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
517 $value['from_email_address'] = $domainEmail;
518 $value['contribution_id'] = $contribution->id
;
519 CRM_Contribute_Form_AdditionalInfo
::emailReceipt( $this, $value );
527 * process membership records
529 * @param array $params associated array of submitted values
535 private function processMembership(&$params) {
537 'join_date' => 'joinDate',
538 'membership_start_date' => 'startDate',
539 'membership_end_date' => 'endDate'
549 // get the price set associated with offline memebership
550 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
551 $this->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
553 if (isset($params['field'])) {
554 $customFields = array();
555 foreach ($params['field'] as $key => $value) {
556 // if contact is not selected we should skip the row
557 if (empty($params['primary_contact_select_id'][$key])) {
561 $value['contact_id'] = CRM_Utils_Array
::value($key, $params['primary_contact_select_id']);
563 // update contact information
564 $this->updateContactInfo($value);
566 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
568 foreach ($dateTypes as $dateField => $dateVariable) {
569 $
$dateVariable = CRM_Utils_Date
::processDate($value[$dateField]);
572 $calcDates = array();
573 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeId,
574 $joinDate, $startDate, $endDate
577 foreach ($calcDates as $memType => $calcDate) {
578 foreach ($dates as $d) {
579 //first give priority to form values then calDates.
580 $date = CRM_Utils_Array
::value($d, $value);
582 $date = CRM_Utils_Array
::value($d, $calcDate);
585 $value[$d] = CRM_Utils_Date
::processDate($date);
589 if (!empty($value['send_receipt'])) {
590 $value['receipt_date'] = date('Y-m-d His');
593 if (!empty($value['membership_source'])) {
594 $value['source'] = $value['membership_source'];
597 unset($value['membership_source']);
599 //Get the membership status
600 if (!empty($value['membership_status'])) {
601 $value['status_id'] = $value['membership_status'];
602 unset($value['membership_status']);
605 if (empty($customFields)) {
606 // membership type custom data
607 $customFields = CRM_Core_BAO_CustomField
::getFields('Membership', FALSE, FALSE, $membershipTypeId);
609 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
610 CRM_Core_BAO_CustomField
::getFields('Membership',
611 FALSE, FALSE, NULL, NULL, TRUE
616 //check for custom data
617 $value['custom'] = CRM_Core_BAO_CustomField
::postProcess($params['field'][$key],
624 if (!empty($value['financial_type'])) {
625 $value['financial_type_id'] = $value['financial_type'];
628 if (!empty($value['payment_instrument'])) {
629 $value['payment_instrument_id'] = $value['payment_instrument'];
632 // handle soft credit
633 if (is_array(CRM_Utils_Array
::value('soft_credit_contact_select_id', $params)) && !empty($params['soft_credit_contact_select_id'][$key]) && CRM_Utils_Array
::value($key, $params['soft_credit_amount'])) {
634 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_select_id'][$key];
635 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule
::cleanMoney($params['soft_credit_amount'][$key]);
638 if (!empty($value['receive_date'])) {
639 $value['receive_date'] = CRM_Utils_Date
::processDate( $value['receive_date'], $value['receive_date_time'] , TRUE );
642 $params['actualBatchTotal'] +
= $value['total_amount'];
644 unset($value['financial_type']);
645 unset($value['payment_instrument']);
647 $value['batch_id'] = $this->_batchId
;
648 $value['skipRecentView'] = TRUE;
650 // make entry in line item for contribution
652 $editedFieldParams = array(
653 'price_set_id' => $priceSetId,
654 'name' => $value['membership_type'][0]
657 $editedResults = array();
658 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
660 if (!empty($editedResults)) {
661 unset($this->_priceSet
['fields']);
662 $this->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
663 unset($this->_priceSet
['fields'][$editedResults['id']]['options']);
664 $fid = $editedResults['id'];
665 $editedFieldParams = array(
666 'price_field_id' => $editedResults['id'],
667 'membership_type_id' => $value['membership_type_id']
670 $editedResults = array();
671 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
672 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
673 if (!empty($value['total_amount'])) {
674 $this->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
677 $fieldID = key($this->_priceSet
['fields']);
678 $value['price_' . $fieldID] = $editedResults['id'];
681 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
682 $value, $lineItem[$priceSetId]
685 //CRM-11529 for backoffice transactions
686 //when financial_type_id is passed in form, update the
687 //lineitems with the financial type selected in form
688 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
689 foreach ($lineItem[$priceSetId] as &$values) {
690 $values['financial_type_id'] = $value['financial_type_id'];
694 $value['lineItems'] = $lineItem;
695 $value['processPriceSet'] = TRUE;
697 // end of contribution related section
699 unset($value['membership_type']);
700 unset($value['membership_start_date']);
701 unset($value['membership_end_date']);
703 $value['is_renew'] = false;
704 if (!empty($params['member_option']) && CRM_Utils_Array
::value( $key, $params['member_option'] ) == 2 ) {
705 $this->_params
= $params;
706 $value['is_renew'] = true;
707 $membership = CRM_Member_BAO_Membership
::renewMembership(
708 $value['contact_id'],
709 $value['membership_type_id'],
710 FALSE, $this, NULL, NULL,
714 // make contribution entry
715 CRM_Member_BAO_Membership
::recordMembershipContribution( array_merge($value, array('membership_id' => $membership->id
)));
718 $membership = CRM_Member_BAO_Membership
::create($value, CRM_Core_DAO
::$_nullArray);
722 if (!empty($value['product_name'])) {
723 if ($value['product_name'][0] > 0) {
724 list($products, $options) = CRM_Contribute_BAO_Premium
::getPremiumProductInfo();
726 $value['hidden_Premium'] = 1;
727 $value['product_option'] = CRM_Utils_Array
::value(
728 $value['product_name'][1],
729 $options[$value['product_name'][0]]
732 $premiumParams = array(
733 'product_id' => $value['product_name'][0],
734 'contribution_id' => $value['contribution_id'],
735 'product_option' => $value['product_option'],
738 CRM_Contribute_BAO_Contribution
::addPremium($premiumParams);
744 if ( $membership->id
&& !empty($value['send_receipt'])) {
746 // add the domain email id
747 $domainEmail = CRM_Core_BAO_Domain
::getNameAndEmail();
748 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
750 $value['from_email_address'] = $domainEmail;
751 $value['membership_id'] = $membership->id
;
752 CRM_Member_Form_Membership
::emailReceipt( $this, $value, $membership );
760 * update contact information
762 * @param array $value associated array of submitted values
768 private function updateContactInfo(&$value) {
769 $value['preserveDBName'] = $this->_preserveDefault
;
771 //parse street address, CRM-7768
772 CRM_Contact_Form_Task_Batch
::parseStreetAddress($value, $this);
774 CRM_Contact_BAO_Contact
::createProfileContact($value, $this->_fields
,
779 * Function exists purely for unit testing purposes. If you feel tempted to use this in live code
780 * then it probably means there is some functionality that needs to be moved
781 * out of the form layer
782 * @param unknown_type $params
784 function testProcessMembership($params) {
785 return $this->processMembership($params);