/**
  * Helper function to record participant with paid contribution.
  *
  * @param int $feeTotal
  * @param int $actualPaidAmt
  *
  * @return array
  * @throws Exception
  */
 protected function addParticipantWithPayment($feeTotal, $actualPaidAmt)
 {
     $priceSetId = $this->eventPriceSetCreate($feeTotal);
     CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_eventId, $priceSetId);
     // create participant record
     $eventId = $this->_eventId;
     $participantParams = array('send_receipt' => 1, 'is_test' => 0, 'is_pay_later' => 0, 'event_id' => $eventId, 'register_date' => date('Y-m-d') . " 00:00:00", 'role_id' => 1, 'status_id' => 14, 'source' => 'Event_' . $eventId, 'contact_id' => $this->_contactId, 'note' => 'Note added for Event_' . $eventId, 'fee_level' => 'Price_Field - 55');
     $participant = $this->callAPISuccess('participant', 'create', $participantParams);
     $this->callAPISuccessGetSingle('participant', array('id' => $participant['id']));
     // create participant contribution with partial payment
     $contributionParams = array('total_amount' => $actualPaidAmt, 'source' => 'Fall Fundraiser Dinner: Offline registration', 'currency' => 'USD', 'non_deductible_amount' => 'null', 'receipt_date' => date('Y-m-d') . " 00:00:00", 'contact_id' => $this->_contactId, 'financial_type_id' => 4, 'payment_instrument_id' => 4, 'contribution_status_id' => 1, 'receive_date' => date('Y-m-d') . " 00:00:00", 'skipLineItem' => 1, 'partial_payment_total' => $feeTotal, 'partial_amount_pay' => $actualPaidAmt);
     $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams);
     $contributionId = $contribution->id;
     $participant = $this->callAPISuccessGetSingle('participant', array('id' => $participant['id']));
     // add participant payment entry
     $this->callAPISuccess('participant_payment', 'create', array('participant_id' => $participant['id'], 'contribution_id' => $contributionId));
     // -- processing priceSet using the BAO
     $lineItem = array();
     $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId, TRUE, FALSE);
     $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
     $feeBlock = CRM_Utils_Array::value('fields', $priceSet);
     $params['price_2'] = $feeTotal;
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItem);
     $lineItemVal[$priceSetId] = $lineItem;
     CRM_Price_BAO_LineItem::processPriceSet($participant['id'], $lineItemVal, $contribution, 'civicrm_participant');
     return array($participant, $contribution);
 }
 /**
  * Process the form when submitted
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     if (CRM_Price_BAO_PriceSet::deleteSet($this->_sid)) {
         CRM_Core_Session::setStatus(ts('The Price Set \'%1\' has been deleted.', array(1 => $this->_title), ts('Deleted'), 'success'));
     } else {
         CRM_Core_Session::setStatus(ts('The Price Set \'%1\' has not been deleted! You must delete all price fields in this set prior to deleting the set.', array(1 => $this->_title)), 'Unable to Delete', 'error');
     }
 }
Example #3
0
 /**
  * Test the correct amount level is returned for an event which is not presented as a price set event.
  *
  * (these are denoted as 'quickConfig' in the code - but quickConfig is only supposed to refer to the
  * configuration interface - there should be no different post process.
  */
 public function testGetAmountLevelTextAmount()
 {
     $priceSetID = $this->eventPriceSetCreate(9);
     $priceSet = CRM_Price_BAO_PriceSet::getCachedPriceSetDetail($priceSetID);
     $field = reset($priceSet['fields']);
     $params = array('priceSetId' => $priceSetID, 'price_' . $field['id'] => 1);
     $amountLevel = CRM_Price_BAO_PriceSet::getAmountLevelText($params);
     $this->assertEquals(CRM_Core_DAO::VALUE_SEPARATOR . 'Price Field - 1' . CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel);
 }
Example #4
0
 /**
  * Pre processing work done here.
  *
  * gets session variables for group or field id
  *
  * @return void
  */
 public function preProcess()
 {
     // get the controller vars
     $groupId = $this->get('groupId');
     $fieldId = $this->get('fieldId');
     if ($fieldId) {
         $groupTree = CRM_Price_BAO_PriceSet::getSetDetail($groupId);
         $this->_groupTree[$groupId]['fields'][$fieldId] = $groupTree[$groupId]['fields'][$fieldId];
         $this->assign('preview_type', 'field');
         $url = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$groupId}");
         $breadCrumb = array(array('title' => ts('Price Set Fields'), 'url' => $url));
     } else {
         // group preview
         $this->_groupTree = CRM_Price_BAO_PriceSet::getSetDetail($groupId);
         $this->assign('preview_type', 'group');
         $this->assign('setTitle', CRM_Price_BAO_PriceSet::getTitle($groupId));
         $url = CRM_Utils_System::url('civicrm/admin/price', 'reset=1');
         $breadCrumb = array(array('title' => ts('Price Sets'), 'url' => $url));
     }
     CRM_Utils_System::appendBreadCrumb($breadCrumb);
 }
 function _addParticipantWithPayment($feeTotal, $actualPaidAmt)
 {
     // creating price set, price field
     $paramsSet['title'] = 'Price Set';
     $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
     $paramsSet['is_active'] = FALSE;
     $paramsSet['extends'] = 1;
     $priceset = CRM_Price_BAO_PriceSet::create($paramsSet);
     CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_eventId, $priceset->id);
     $priceSetId = $priceset->id;
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title', 'id', $paramsSet['title'], 'Check DB for created priceset');
     $paramsField = array('label' => 'Price Field', 'name' => CRM_Utils_String::titleToVar('Price Field'), 'html_type' => 'Text', 'price' => $feeTotal, 'option_label' => array('1' => 'Price Field'), 'option_value' => array('1' => $feeTotal), 'option_name' => array('1' => $feeTotal), 'option_weight' => array('1' => 1), 'option_amount' => array('1' => 1), 'is_display_amounts' => 1, 'weight' => 1, 'options_per_line' => 1, 'is_active' => array('1' => 1), 'price_set_id' => $priceset->id, 'is_enter_qty' => 1);
     $ids = array();
     $pricefield = CRM_Price_BAO_PriceField::create($paramsField, $ids);
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceField', $pricefield->id, 'label', 'id', $paramsField['label'], 'Check DB for created pricefield');
     // create participant record
     $eventId = $this->_eventId;
     $participantParams = array('send_receipt' => 1, 'is_test' => 0, 'is_pay_later' => 0, 'event_id' => $eventId, 'register_date' => date('Y-m-d') . " 00:00:00", 'role_id' => 1, 'status_id' => 14, 'source' => 'Event_' . $eventId, 'contact_id' => $this->_contactId, 'note' => 'Note added for Event_' . $eventId, 'fee_level' => 'Price_Field - 55');
     $participant = CRM_Event_BAO_Participant::add($participantParams);
     // create participant contribution with partial payment
     $contributionParams = array('total_amount' => $actualPaidAmt, 'source' => 'Fall Fundraiser Dinner: Offline registration', 'currency' => 'USD', 'non_deductible_amount' => 'null', 'receipt_date' => date('Y-m-d') . " 00:00:00", 'contact_id' => $this->_contactId, 'financial_type_id' => 4, 'payment_instrument_id' => 4, 'contribution_status_id' => 1, 'receive_date' => date('Y-m-d') . " 00:00:00", 'skipLineItem' => 1, 'partial_payment_total' => $feeTotal, 'partial_amount_pay' => $actualPaidAmt);
     $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, CRM_Core_DAO::$_nullArray);
     $contributionId = $contribution->id;
     // add participant payment entry
     $this->participantPaymentCreate($participant->id, $contributionId);
     // -- processing priceSet using the BAO
     $lineItem = array();
     $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId, TRUE, FALSE);
     $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
     $feeBlock = CRM_Utils_Array::value('fields', $priceSet);
     $params['price_2'] = $feeTotal;
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItem);
     $lineItemVal[$priceSetId] = $lineItem;
     CRM_Price_BAO_LineItem::processPriceSet($participant->id, $lineItemVal, $contribution, 'civicrm_participant');
     return array($participant, $contribution);
 }
Example #6
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Example #7
0
 /**
  * Get the details for the selected price set.
  *
  * @param array $params
  *   Parameters submitted to the form.
  *
  * @return array
  */
 protected static function getPriceSetDetails($params)
 {
     $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
     if ($priceSetID) {
         return CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
     } else {
         $priceSet = CRM_Price_BAO_PriceSet::getDefaultPriceSet('membership');
         $priceSet = reset($priceSet);
         return CRM_Price_BAO_PriceSet::getSetDetail($priceSet['setID']);
     }
 }
Example #8
0
 /**
  * Submit function.
  *
  * This is the guts of the postProcess made also accessible to the test suite.
  *
  * @param array $params
  *   Submitted values.
  */
 public function submit($params)
 {
     //carry campaign from profile.
     if (array_key_exists('contribution_campaign_id', $params)) {
         $params['campaign_id'] = $params['contribution_campaign_id'];
     }
     $params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
     $is_quick_config = 0;
     if (!empty($params['priceSetId'])) {
         $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
         if ($is_quick_config) {
             $priceField = new CRM_Price_DAO_PriceField();
             $priceField->price_set_id = $params['priceSetId'];
             $priceField->orderBy('weight');
             $priceField->find();
             $priceOptions = array();
             while ($priceField->fetch()) {
                 CRM_Price_BAO_PriceFieldValue::getValues($priceField->id, $priceOptions);
                 if (($selectedPriceOptionID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) != FALSE && $selectedPriceOptionID > 0) {
                     switch ($priceField->name) {
                         case 'membership_amount':
                             $this->_params['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array::value('membership_type_id', $priceOptions[$selectedPriceOptionID]);
                             $this->set('selectMembership', $params['selectMembership']);
                         case 'contribution_amount':
                             $params['amount'] = $selectedPriceOptionID;
                             if ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount' && CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0) {
                                 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
                             }
                             $this->_values[$selectedPriceOptionID]['value'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
                             $this->_values[$selectedPriceOptionID]['label'] = CRM_Utils_Array::value('label', $priceOptions[$selectedPriceOptionID]);
                             $this->_values[$selectedPriceOptionID]['amount_id'] = CRM_Utils_Array::value('id', $priceOptions[$selectedPriceOptionID]);
                             $this->_values[$selectedPriceOptionID]['weight'] = CRM_Utils_Array::value('weight', $priceOptions[$selectedPriceOptionID]);
                             break;
                         case 'other_amount':
                             $params['amount_other'] = $selectedPriceOptionID;
                             break;
                     }
                 }
             }
         }
     }
     if (!empty($this->_ccid) && !empty($this->_pendingAmount)) {
         $params['amount'] = $this->_pendingAmount;
     } else {
         // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
         $params['amount'] = self::computeAmount($params, $this->_values);
     }
     $params['separate_amount'] = $params['amount'];
     $memFee = NULL;
     if (!empty($params['selectMembership'])) {
         if (empty($this->_membershipTypeValues)) {
             $this->_membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, (array) $params['selectMembership']);
         }
         $membershipTypeValues = $this->_membershipTypeValues[$params['selectMembership']];
         $memFee = $membershipTypeValues['minimum_fee'];
         if (!$params['amount'] && !$this->_separateMembershipPayment) {
             $params['amount'] = $memFee ? $memFee : 0;
         }
     }
     //If the membership & contribution is used in contribution page & not separate payment
     $fieldId = $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
     $proceFieldAmount = 0;
     if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment == 0) {
         $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
         if ($is_quick_config) {
             foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
                 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
                     $fieldId = $fieldVal['id'];
                     $fieldOption = $params['price_' . $fieldId];
                     $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
                     $memPresent = TRUE;
                 } else {
                     if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
                         $fieldId = $fieldVal['id'];
                         if ($fieldVal['name'] == 'other_amount') {
                             $proceFieldAmount += $this->_submitValues['price_' . $fieldId];
                         } elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues['price_' . $fieldId] > 0) {
                             $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
                         }
                         unset($params['price_' . $fieldId]);
                         break;
                     }
                 }
             }
         }
     }
     if (!isset($params['amount_other'])) {
         $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params));
     }
     if (!empty($this->_ccid)) {
         $this->set('lineItem', $this->_lineItem);
     } elseif ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
         $lineItem = array();
         $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         if ($is_quick_config) {
             foreach ($this->_values['fee'] as $key => &$val) {
                 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
                     // Clean out any currency symbols.
                     $params['price_' . $key] = CRM_Utils_Rule::cleanMoney($params['price_' . $key]);
                     if ($params['price_' . $key] != 0) {
                         foreach ($val['options'] as $optionKey => &$options) {
                             $options['amount'] = CRM_Utils_Array::value('price_' . $key, $params);
                             break;
                         }
                     }
                     $params['price_' . $key] = 1;
                     break;
                 }
             }
         }
         $component = '';
         if ($this->_membershipBlock) {
             $component = 'membership';
         }
         CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $component);
         if ($params['tax_amount']) {
             $this->set('tax_amount', $params['tax_amount']);
         }
         if ($proceFieldAmount) {
             $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
             $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
             if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
                 $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
             }
             if (!$this->_membershipBlock['is_separate_payment']) {
                 //require when separate membership not used
                 $params['amount'] = $proceFieldAmount;
             }
         }
         $this->set('lineItem', $lineItem);
     }
     if ($params['amount'] != 0 && ($this->_values['is_pay_later'] && empty($this->_paymentProcessor) && !array_key_exists('hidden_processor', $params) || CRM_Utils_Array::value('payment_processor_id', $params) == 0)) {
         $params['is_pay_later'] = 1;
     } else {
         $params['is_pay_later'] = 0;
     }
     // Would be nice to someday understand the point of this set.
     $this->set('is_pay_later', $params['is_pay_later']);
     // assign pay later stuff
     $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
     $this->assign('is_pay_later', $params['is_pay_later']);
     if ($params['is_pay_later']) {
         $this->assign('pay_later_text', $this->_values['pay_later_text']);
         $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
     }
     if ($this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
         $this->set('amount', $params['separate_amount']);
     } else {
         $this->set('amount', $params['amount']);
     }
     // generate and set an invoiceID for this transaction
     $invoiceID = md5(uniqid(rand(), TRUE));
     $this->set('invoiceID', $invoiceID);
     $params['invoiceID'] = $invoiceID;
     $params['description'] = ts('Online Contribution') . ': ' . (!empty($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $this->_values['title']);
     $params['button'] = $this->controller->getButtonName();
     // required only if is_monetary and valid positive amount
     // @todo it seems impossible for $memFee to be greater than 0 & $params['amount'] not to
     // be & by requiring $memFee down here we make it harder to do a sensible refactoring of the function
     // above (ie. extract the amount in a small function).
     if ($this->_values['is_monetary'] && !empty($this->_paymentProcessor) && ((double) $params['amount'] > 0.0 || $memFee > 0.0)) {
         // The concept of contributeMode is deprecated - as should be the 'is_monetary' setting.
         $this->setContributeMode();
         // Really this setting of $this->_params & params within it should be done earlier on in the function
         // probably the values determined here should be reused in confirm postProcess as there is no opportunity to alter anything
         // on the confirm page. However as we are dealing with a stable release we go as close to where it is used
         // as possible.
         // In general the form has a lack of clarity of the logic of why things are set on the form in some cases &
         // the logic around when $this->_params is used compared to other params arrays.
         $this->_params = array_merge($params, $this->_params);
         $this->setRecurringMembershipParams();
         if ($this->_paymentProcessor && $this->_paymentProcessor['object']->supports('preApproval')) {
             $this->handlePreApproval($this->_params);
         }
     }
 }
    /**
     * This function sets the default values for price set.
     *
     *
     * @param int $participantID
     * @param int $eventID
     * @param bool $includeQtyZero
     *
     * @return void
     */
    public static function setDefaultPriceSet($participantID, $eventID = NULL, $includeQtyZero = TRUE)
    {
        $defaults = array();
        if (!$eventID && $participantID) {
            $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'event_id');
        }
        if (!$participantID || !$eventID) {
            return $defaults;
        }
        // get price set ID.
        $priceSetID = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID);
        if (!$priceSetID) {
            return $defaults;
        }
        // use line items for setdefault price set fields, CRM-4090
        $lineItems[$participantID] = CRM_Price_BAO_LineItem::getLineItems($participantID, 'participant', NULL, $includeQtyZero);
        if (is_array($lineItems[$participantID]) && !CRM_Utils_System::isNull($lineItems[$participantID])) {
            $priceFields = $htmlTypes = $optionValues = array();
            foreach ($lineItems[$participantID] as $lineId => $items) {
                $priceFieldId = CRM_Utils_Array::value('price_field_id', $items);
                $priceOptionId = CRM_Utils_Array::value('price_field_value_id', $items);
                if ($priceFieldId && $priceOptionId) {
                    $priceFields[$priceFieldId][] = $priceOptionId;
                }
            }
            if (empty($priceFields)) {
                return $defaults;
            }
            // get all price set field html types.
            $sql = '
SELECT  id, html_type
  FROM  civicrm_price_field
 WHERE  id IN (' . implode(',', array_keys($priceFields)) . ')';
            $fieldDAO = CRM_Core_DAO::executeQuery($sql);
            while ($fieldDAO->fetch()) {
                $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
            }
            foreach ($lineItems[$participantID] as $lineId => $items) {
                $fieldId = $items['price_field_id'];
                $htmlType = CRM_Utils_Array::value($fieldId, $htmlTypes);
                if (!$htmlType) {
                    continue;
                }
                if ($htmlType == 'Text') {
                    $defaults["price_{$fieldId}"] = $items['qty'];
                } else {
                    $fieldOptValues = CRM_Utils_Array::value($fieldId, $priceFields);
                    if (!is_array($fieldOptValues)) {
                        continue;
                    }
                    foreach ($fieldOptValues as $optionId) {
                        if ($htmlType == 'CheckBox') {
                            $defaults["price_{$fieldId}"][$optionId] = TRUE;
                        } else {
                            $defaults["price_{$fieldId}"] = $optionId;
                            break;
                        }
                    }
                }
            }
        }
        return $defaults;
    }
Example #10
0
 /**
  * Get line items representing the default price set.
  *
  * @param int $membershipOrg
  * @param int $membershipTypeID
  * @param float $total_amount
  * @param int $priceSetId
  *
  * @return array
  */
 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId)
 {
     $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     // The name of the price field corresponds to the membership_type organization contact.
     $params = array('price_set_id' => $priceSetId, 'name' => $membershipOrg);
     $results = array();
     CRM_Price_BAO_PriceField::retrieve($params, $results);
     if (!empty($results)) {
         $fields[$results['id']] = $priceSets['fields'][$results['id']];
         $fid = $results['id'];
         $editedFieldParams = array('price_field_id' => $results['id'], 'membership_type_id' => $membershipTypeID);
         $results = array();
         CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $results);
         $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
         if (!empty($total_amount)) {
             $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
         }
     }
     $fieldID = key($fields);
     $returnParams = array('price_set_id' => $priceSetId, 'price_sets' => $priceSets, 'fields' => $fields, 'price_fields' => array('price_' . $fieldID => CRM_Utils_Array::value('id', $results)));
     return $returnParams;
 }
Example #11
0
 /**
  * Create price set with contribution test for test setup.
  *
  * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
  * on parent class at some point (fn is not in 4.4).
  *
  * @param $entity
  * @param array $params
  */
 public function createPriceSetWithPage($entity, $params = array())
 {
     $membershipTypeID = $this->membershipTypeCreate();
     $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array('title' => "Test Contribution Page", 'financial_type_id' => 1, 'currency' => 'NZD', 'goal_amount' => 50, 'is_pay_later' => 1, 'is_monetary' => TRUE, 'is_email_receipt' => FALSE));
     $priceSet = $this->callAPISuccess('price_set', 'create', array('is_quick_config' => 0, 'extends' => 'CiviMember', 'financial_type_id' => 1, 'title' => 'my Page'));
     $priceSetID = $priceSet['id'];
     CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
     $priceField = $this->callAPISuccess('price_field', 'create', array('price_set_id' => $priceSetID, 'label' => 'Goat Breed', 'html_type' => 'Radio'));
     $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array('price_set_id' => $priceSetID, 'price_field_id' => $priceField['id'], 'label' => 'Long Haired Goat', 'amount' => 20, 'financial_type_id' => 'Donation', 'membership_type_id' => $membershipTypeID, 'membership_num_terms' => 1));
     $this->_ids['price_field_value'] = array($priceFieldValue['id']);
     $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array('price_set_id' => $priceSetID, 'price_field_id' => $priceField['id'], 'label' => 'Shoe-eating Goat', 'amount' => 10, 'financial_type_id' => 'Donation', 'membership_type_id' => $membershipTypeID, 'membership_num_terms' => 2));
     $this->_ids['price_field_value'][] = $priceFieldValue['id'];
     $this->_ids['price_set'] = $priceSetID;
     $this->_ids['contribution_page'] = $contributionPageResult['id'];
     $this->_ids['price_field'] = array($priceField['id']);
     $this->_ids['membership_type'] = $membershipTypeID;
 }
Example #12
0
 /**
  * process membership records
  *
  * @param array $params associated array of submitted values
  *
  * @access public
  *
  * @return bool
  */
 private function processMembership(&$params)
 {
     $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate');
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     // get the price set associated with offline memebership
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
     $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             foreach ($dateTypes as $dateField => $dateVariable) {
                 ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]);
             }
             $calcDates = array();
             $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate);
             foreach ($calcDates as $memType => $calcDate) {
                 foreach ($dates as $d) {
                     //first give priority to form values then calDates.
                     $date = CRM_Utils_Array::value($d, $value);
                     if (!$date) {
                         $date = CRM_Utils_Array::value($d, $calcDate);
                     }
                     $value[$d] = CRM_Utils_Date::processDate($date);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             if (!empty($value['membership_status'])) {
                 $value['status_id'] = $value['membership_status'];
                 unset($value['membership_status']);
             }
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membershipTypeId);
             if (!empty($value['financial_type'])) {
                 $value['financial_type_id'] = $value['financial_type'];
             }
             if (!empty($value['payment_instrument'])) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             // handle soft credit
             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'])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
             }
             if (!empty($value['receive_date'])) {
                 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             unset($value['financial_type']);
             unset($value['payment_instrument']);
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // make entry in line item for contribution
             $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]);
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (!empty($editedResults)) {
                 unset($this->_priceSet['fields']);
                 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
                 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
                 $fid = $editedResults['id'];
                 $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']);
                 $editedResults = array();
                 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
                 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
                 if (!empty($value['total_amount'])) {
                     $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
                 }
                 $fieldID = key($this->_priceSet['fields']);
                 $value['price_' . $fieldID] = $editedResults['id'];
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
                 //CRM-11529 for backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                     foreach ($lineItem[$priceSetId] as &$values) {
                         $values['financial_type_id'] = $value['financial_type_id'];
                     }
                 }
                 $value['lineItems'] = $lineItem;
                 $value['processPriceSet'] = TRUE;
             }
             // end of contribution related section
             unset($value['membership_type']);
             unset($value['membership_start_date']);
             unset($value['membership_end_date']);
             $value['is_renew'] = false;
             if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
                 $this->_params = $params;
                 $value['is_renew'] = true;
                 $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($value['contact_id'], $value['membership_type_id'], FALSE, $this, NULL, NULL, $value['custom']);
                 // make contribution entry
                 CRM_Member_BAO_Membership::recordMembershipContribution(array_merge($value, array('membership_id' => $membership->id)));
             } else {
                 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $value['contribution_id'], 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($membership->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['membership_id'] = $membership->id;
                 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
             }
         }
     }
     return TRUE;
 }
Example #13
0
 /**
  * This is sometimes called in a loop (during event search)
  * hence we cache the values to prevent repeated calls to the db
  */
 static function usesPriceSet($id)
 {
     static $usesPriceSet = array();
     if (!array_key_exists($id, $usesPriceSet)) {
         $usesPriceSet[$id] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $id);
     }
     return $usesPriceSet[$id];
 }
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     //get the button name.
     $button = substr($this->controller->getButtonName(), -4);
     //take the participant instance.
     $addParticipantNum = substr($this->_name, 12);
     //user submitted params.
     $params = $this->controller->exportValues($this->_name);
     if (!$this->_allowConfirmation) {
         // check if the participant is already registered
         $params['contact_id'] = CRM_Event_Form_Registration_Register::checkRegistration($params, $this, TRUE, TRUE);
     }
     //carry campaign to partcipants.
     if (array_key_exists('participant_campaign_id', $params)) {
         $params['campaign_id'] = $params['participant_campaign_id'];
     } else {
         $params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
     }
     // if waiting is enabled
     if (!$this->_allowConfirmation && is_numeric($this->_availableRegistrations)) {
         $this->_allowWaitlist = FALSE;
         //get the current page count.
         $currentCount = self::getParticipantCount($this, $params);
         if ($button == 'skip') {
             $currentCount = 'skip';
         }
         //get the total count.
         $previousCount = self::getParticipantCount($this, $this->_params, TRUE);
         $totalParticipants = $previousCount;
         if (is_numeric($currentCount)) {
             $totalParticipants += $currentCount;
         }
         if (!empty($this->_values['event']['has_waitlist']) && $totalParticipants > $this->_availableRegistrations) {
             $this->_allowWaitlist = TRUE;
         }
         $this->set('allowWaitlist', $this->_allowWaitlist);
         $this->_lineItemParticipantsCount[$addParticipantNum] = $currentCount;
     }
     if ($button == 'skip') {
         //hack for free/zero amount event.
         if ($this->_resetAllowWaitlist) {
             $this->_allowWaitlist = FALSE;
             $this->set('allowWaitlist', FALSE);
             if ($this->_requireApproval) {
                 $status = ts("You have skipped last participant and which result into event having enough spaces, but your registration require approval, Once your registration has been reviewed, you will receive an email with a link to a web page where you can complete the registration process.");
             } else {
                 $status = ts("You have skipped last participant and which result into event having enough spaces, hence your group become as register participants though you selected on wait list.");
             }
             CRM_Core_Session::setStatus($status);
         }
         $this->_params[$addParticipantNum] = 'skip';
         if (isset($this->_lineItem)) {
             $this->_lineItem[$addParticipantNum] = 'skip';
             $this->_lineItemParticipantsCount[$addParticipantNum] = 'skip';
         }
     } else {
         $config = CRM_Core_Config::singleton();
         $params['currencyID'] = $config->defaultCurrency;
         if ($this->_values['event']['is_monetary']) {
             //added for discount
             $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
             if (!empty($this->_values['discount'][$discountId])) {
                 $params['discount_id'] = $discountId;
                 $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
                 $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             } elseif (empty($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
             } else {
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
                 //build line item array..
                 //if requireApproval/waitlist is enabled we hide fees for primary participant
                 // (and not for additional participant which might be is a bug)
                 //lineItem are not correctly build for primary participant
                 //this results in redundancy since now lineItems for additional participant will be build against primary participantNum
                 //therefore lineItems must always be build against current participant No
                 $this->_lineItem[$addParticipantNum] = $lineItem;
             }
         }
         if (array_key_exists('participant_role', $params)) {
             $params['participant_role_id'] = $params['participant_role'];
         }
         if (empty($params['participant_role_id']) && $this->_values['event']['default_role_id']) {
             $params['participant_role_id'] = $this->_values['event']['default_role_id'];
         }
         if (!empty($this->_params[0]['is_pay_later'])) {
             $params['is_pay_later'] = 1;
         }
         //carry additional participant id, contact id if pre-registered.
         if ($this->_allowConfirmation && $this->_additionalParticipantId) {
             $params['contact_id'] = $this->_contactId;
             $params['participant_id'] = $this->_additionalParticipantId;
         }
         //build the params array.
         $this->_params[$addParticipantNum] = $params;
     }
     //finally set the params.
     $this->set('params', $this->_params);
     //set the line item.
     if ($this->_lineItem) {
         $this->set('lineItem', $this->_lineItem);
         $this->set('lineItemParticipantsCount', $this->_lineItemParticipantsCount);
     }
     $participantNo = count($this->_params);
     if ($button != 'skip') {
         $statusMsg = ts('Registration information for participant %1 has been saved.', array(1 => $participantNo));
         CRM_Core_Session::setStatus($statusMsg, ts('Registration Saved'), 'success');
     }
     // Check whether to process the registration now, calling processRegistration()
     if (!$this->_values['event']['is_confirm_enabled'] && !$this->_values['event']['is_monetary'] && CRM_Utils_Array::value('additional_participants', $this->_params[0]) && $this->isLastParticipant()) {
         CRM_Event_Form_Registration_Register::processRegistration($this->_params, NULL);
     }
 }
Example #15
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     // current contribution page id
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     if (!$this->_id) {
         // seems like the session is corrupted and/or we lost the id trail
         // lets just bump this to a regular session error and redirect user to main page
         $this->controller->invalidKeyRedirect();
     }
     // this was used prior to the cleverer this_>getContactID - unsure now
     $this->_userID = $session->get('userID');
     $this->_contactID = $this->_membershipContactID = $this->getContactID();
     $this->_mid = NULL;
     if ($this->_contactID) {
         $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
         if ($this->_mid) {
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_mid;
             if ($membership->find(TRUE)) {
                 $this->_defaultMemTypeId = $membership->membership_type_id;
                 if ($membership->contact_id != $this->_contactID) {
                     $validMembership = FALSE;
                     $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID);
                     if (!empty($employers) && array_key_exists($membership->contact_id, $employers)) {
                         $this->_membershipContactID = $membership->contact_id;
                         $this->assign('membershipContactID', $this->_membershipContactID);
                         $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']);
                         $validMembership = TRUE;
                     } else {
                         $membershipType = new CRM_Member_BAO_MembershipType();
                         $membershipType->id = $membership->membership_type_id;
                         if ($membershipType->find(TRUE)) {
                             // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
                             // Convert to commma separated list.
                             $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
                             $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
                             if (array_key_exists($membership->contact_id, $permContacts)) {
                                 $this->_membershipContactID = $membership->contact_id;
                                 $validMembership = TRUE;
                             }
                         }
                     }
                     if (!$validMembership) {
                         CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
                     }
                 }
             } else {
                 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
             }
             unset($membership);
         }
     }
     // we do not want to display recently viewed items, so turn off
     $this->assign('displayRecent', FALSE);
     // Contribution page values are cleared from session, so can't use normal Printer Friendly view.
     // Use Browser Print instead.
     $this->assign('browserPrint', TRUE);
     // action
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
     $this->assign('action', $this->_action);
     // current mode
     $this->_mode = $this->_action == 1024 ? 'test' : 'live';
     $this->_values = $this->get('values');
     $this->_fields = $this->get('fields');
     $this->_bltID = $this->get('bltID');
     $this->_paymentProcessor = $this->get('paymentProcessor');
     $this->_priceSetId = $this->get('priceSetId');
     $this->_priceSet = $this->get('priceSet');
     if (!$this->_values) {
         // get all the values from the dao object
         $this->_values = array();
         $this->_fields = array();
         CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
         // check if form is active
         if (!CRM_Utils_Array::value('is_active', $this->_values)) {
             // form is inactive, die a fatal death
             CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
         }
         // also check for billing informatin
         // get the billing location type
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
         // CRM-8108 remove ts around Billing location type
         //$this->_bltID = array_search( ts('Billing'),  $locationTypes );
         $this->_bltID = array_search('Billing', $locationTypes);
         if (!$this->_bltID) {
             CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
         }
         $this->set('bltID', $this->_bltID);
         // check for is_monetary status
         $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values);
         $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values);
         //FIXME: to support multiple payment processors
         if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor', $this->_values))) {
             $ppID = CRM_Utils_Array::value('payment_processor', $this->_values);
             if (!$ppID) {
                 CRM_Core_Error::fatal(ts('A payment processor must be selected for this contribution page (contact the site administrator for assistance).'));
             }
             $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID);
             $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds, $this->_mode);
             $this->set('paymentProcessors', $this->_paymentProcessors);
             //set default payment processor
             if (!empty($this->_paymentProcessors) && empty($this->_paymentProcessor)) {
                 foreach ($this->_paymentProcessors as $ppId => $values) {
                     if ($values['is_default'] == 1 || count($this->_paymentProcessors) == 1) {
                         $defaultProcessorId = $ppId;
                         break;
                     }
                 }
             }
             if (isset($defaultProcessorId)) {
                 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($defaultProcessorId, $this->_mode);
                 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
             }
             if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
                 foreach ($this->_paymentProcessors as $eachPaymentProcessor) {
                     // check selected payment processor is active
                     if (empty($eachPaymentProcessor)) {
                         CRM_Core_Error::fatal(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
                     }
                     // ensure that processor has a valid config
                     $this->_paymentObject =& CRM_Core_Payment::singleton($this->_mode, $eachPaymentProcessor, $this);
                     $error = $this->_paymentObject->checkConfig();
                     if (!empty($error)) {
                         CRM_Core_Error::fatal($error);
                     }
                 }
             }
         }
         // get price info
         // CRM-5095
         CRM_Price_BAO_PriceSet::initSet($this, $this->_id, 'civicrm_contribution_page');
         // this avoids getting E_NOTICE errors in php
         $setNullFields = array('amount_block_is_active', 'honor_block_is_active', 'is_allow_other_amount', 'footer_text');
         foreach ($setNullFields as $f) {
             if (!isset($this->_values[$f])) {
                 $this->_values[$f] = NULL;
             }
         }
         //check if Membership Block is enabled, if Membership Fields are included in profile
         //get membership section for this contribution page
         $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
         $this->set('membershipBlock', $this->_membershipBlock);
         if ($this->_values['custom_pre_id']) {
             $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
         }
         if ($this->_values['custom_post_id']) {
             $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
         }
         if ((isset($postProfileType) && $postProfileType == 'Membership' || isset($preProfileType) && $preProfileType == 'Membership') && !$this->_membershipBlock['is_active']) {
             CRM_Core_Error::fatal(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.'));
         }
         $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
         if ($pledgeBlock) {
             $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock);
             $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock);
             $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock);
             $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock);
             //set pledge id in values
             $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
             //authenticate pledge user for pledge payment.
             if ($pledgeId) {
                 $this->_values['pledge_id'] = $pledgeId;
                 //lets override w/ pledge campaign.
                 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'campaign_id');
                 self::authenticatePledgeUser();
             }
         }
         $this->set('values', $this->_values);
         $this->set('fields', $this->_fields);
     }
     // Handle PCP
     $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
     if ($pcpId) {
         $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
         $this->_pcpId = $pcp['pcpId'];
         $this->_pcpBlock = $pcp['pcpBlock'];
         $this->_pcpInfo = $pcp['pcpInfo'];
     }
     // Link (button) for users to create their own Personal Campaign page
     if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
         $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign', "action=add&reset=1&pageId={$this->_id}&component=contribute", FALSE, NULL, TRUE);
         $this->assign('linkTextUrl', $linkTextUrl);
         $this->assign('linkText', $linkText);
     }
     //set pledge block if block id is set
     if (CRM_Utils_Array::value('pledge_block_id', $this->_values)) {
         $this->assign('pledgeBlock', TRUE);
     }
     // check if one of the (amount , membership)  bloks is active or not
     $this->_membershipBlock = $this->get('membershipBlock');
     if (!$this->_values['amount_block_is_active'] && !$this->_membershipBlock['is_active'] && !$this->_priceSetId) {
         CRM_Core_Error::fatal(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.'));
     }
     if ($this->_values['amount_block_is_active']) {
         $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
     }
     $this->_contributeMode = $this->get('contributeMode');
     $this->assign('contributeMode', $this->_contributeMode);
     //assigning is_monetary and is_email_receipt to template
     $this->assign('is_monetary', $this->_values['is_monetary']);
     $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
     $this->assign('bltID', $this->_bltID);
     //assign cancelSubscription URL to templates
     $this->assign('cancelSubscriptionUrl', CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values));
     // assigning title to template in case someone wants to use it, also setting CMS page title
     if ($this->_pcpId) {
         $this->assign('title', $this->_pcpInfo['title']);
         CRM_Utils_System::setTitle($this->_pcpInfo['title']);
     } else {
         $this->assign('title', $this->_values['title']);
         CRM_Utils_System::setTitle($this->_values['title']);
     }
     $this->_defaults = array();
     $this->_amount = $this->get('amount');
     //CRM-6907
     $config = CRM_Core_Config::singleton();
     $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency);
     //lets allow user to override campaign.
     $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
     if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
         $this->_values['campaign_id'] = $campID;
     }
     //do check for cancel recurring and clean db, CRM-7696
     if (CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject)) {
         self::cancelRecurring();
     }
 }
Example #16
0
 /**
  * Run the page.
  *
  * This method is called after the page is created. It checks for the
  * type of action and executes that action.
  *
  * @param null
  *
  * @return void
  * @access public
  */
 function run()
 {
     // get the group id
     $this->_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this);
     $fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this, FALSE, 0);
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
     if ($this->_sid) {
         $usedBy = CRM_Price_BAO_PriceSet::getUsedBy($this->_sid);
         $this->assign('usedBy', $usedBy);
         $this->_isSetReserved = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'is_reserved');
         $this->assign('isReserved', $this->_isSetReserved);
         CRM_Price_BAO_PriceSet::checkPermission($this->_sid);
         $comps = array('Event' => 'civicrm_event', 'Contribution' => 'civicrm_contribution_page', 'EventTemplate' => 'civicrm_event_template');
         $priceSetContexts = array();
         foreach ($comps as $name => $table) {
             if (array_key_exists($table, $usedBy)) {
                 $priceSetContexts[] = $name;
             }
         }
         $this->assign('contexts', $priceSetContexts);
     }
     if ($action & CRM_Core_Action::DELETE && !$this->_isSetReserved) {
         if (empty($usedBy)) {
             // prompt to delete
             $session = CRM_Core_Session::singleton();
             $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid));
             $controller = new CRM_Core_Controller_Simple('CRM_Price_Form_DeleteField', 'Delete Price Field', '');
             $controller->set('fid', $fid);
             $controller->setEmbedded(TRUE);
             $controller->process();
             $controller->run();
         } else {
             // add breadcrumb
             $url = CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1');
             CRM_Utils_System::appendBreadCrumb(ts('Price'), $url);
             $this->assign('usedPriceSetTitle', CRM_Price_BAO_PriceField::getTitle($fid));
         }
     }
     if ($this->_sid) {
         $groupTitle = CRM_Price_BAO_PriceSet::getTitle($this->_sid);
         $this->assign('sid', $this->_sid);
         $this->assign('groupTitle', $groupTitle);
         CRM_Utils_System::setTitle(ts('%1 - Price Fields', array(1 => $groupTitle)));
     }
     // assign vars to templates
     $this->assign('action', $action);
     // what action to take ?
     if ($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD) && !$this->_isSetReserved) {
         // no browse for edit/update/view
         $this->edit($action);
     } elseif ($action & CRM_Core_Action::PREVIEW) {
         $this->preview($fid);
     } else {
         $this->browse();
     }
     // Call the parents run method
     return parent::run();
 }
 /**
  * Determine if recurring parameters need to be added to the form parameters.
  *
  *  - is_recur
  *  - frequency_interval
  *  - frequency_unit
  *
  * For membership this is based on the membership type.
  *
  * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
  *
  * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
  */
 protected function setRecurringMembershipParams()
 {
     $selectedMembershipTypeID = CRM_Utils_Array::value('selectMembership', $this->_params);
     if ($selectedMembershipTypeID) {
         // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
         // 'selectMembership' and calculate from the price_x fields so we have one method that always works
         // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
         // this with an else (calculate for price set).
         $membershipTypes = CRM_Price_BAO_PriceSet::getMembershipTypesFromPriceSet($this->_priceSetId);
         if (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_required']) || in_array($selectedMembershipTypeID, $membershipTypes['autorenew_optional']) && !empty($this->_params['is_recur'])) {
             $this->_params['auto_renew'] = TRUE;
         }
     }
     if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId'])) && !empty($this->_paymentProcessor['is_recur']) && CRM_Utils_Array::value('auto_renew', $this->_params) && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])) {
         $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
         // check if price set is not quick config
         if (!empty($this->_params['priceSetId']) && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config')) {
             list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
         } else {
             // FIXME: set interval and unit based on selected membership type
             $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_interval');
             $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_unit');
         }
     }
 }
 /**
  * Process the form.
  *
  * @return void
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     $deletePriceSet = 0;
     if ($params['membership_type']) {
         // we do this in case the user has hit the forward/back button
         $dao = new CRM_Member_DAO_MembershipBlock();
         $dao->entity_table = 'civicrm_contribution_page';
         $dao->entity_id = $this->_id;
         $dao->find(TRUE);
         $membershipID = $dao->id;
         if ($membershipID) {
             $params['id'] = $membershipID;
         }
         $membershipTypes = array();
         if (is_array($params['membership_type'])) {
             foreach ($params['membership_type'] as $k => $v) {
                 if ($v) {
                     $membershipTypes[$k] = CRM_Utils_Array::value("auto_renew_{$k}", $params);
                 }
             }
         }
         if ($this->_id && !empty($params['member_price_set_id'])) {
             CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'amount_block_is_active', 0);
         }
         // check for price set.
         $priceSetID = CRM_Utils_Array::value('member_price_set_id', $params);
         if (!empty($params['member_is_active']) && is_array($membershipTypes) && !$priceSetID) {
             $usedPriceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 2);
             if (empty($params['mem_price_field_id']) && !$usedPriceSetId) {
                 $pageTitle = strtolower(CRM_Utils_String::munge($this->_values['title'], '_', 245));
                 $setParams['title'] = $this->_values['title'];
                 if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle, 'id', 'name')) {
                     $setParams['name'] = $pageTitle;
                 } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle . '_' . $this->_id, 'id', 'name')) {
                     $setParams['name'] = $pageTitle . '_' . $this->_id;
                 } else {
                     $timeSec = explode(".", microtime(TRUE));
                     $setParams['name'] = $pageTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
                 }
                 $setParams['is_quick_config'] = 1;
                 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviMember');
                 $setParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_values);
                 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                 $priceSetID = $priceSet->id;
                 $fieldParams['price_set_id'] = $priceSet->id;
             } elseif ($usedPriceSetId) {
                 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviMember');
                 $setParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_values);
                 $setParams['id'] = $usedPriceSetId;
                 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                 $priceSetID = $priceSet->id;
                 $fieldParams['price_set_id'] = $priceSet->id;
             } else {
                 $fieldParams['id'] = CRM_Utils_Array::value('mem_price_field_id', $params);
                 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('mem_price_field_id', $params), 'price_set_id');
             }
             $editedFieldParams = array('price_set_id' => $priceSetID, 'name' => 'membership_amount');
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (empty($editedResults['id'])) {
                 $fieldParams['name'] = strtolower(CRM_Utils_String::munge('Membership Amount', '_', 245));
                 if (empty($params['mem_price_field_id'])) {
                     CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', 0, 1, array('price_set_id' => $priceSetID));
                 }
                 $fieldParams['weight'] = 1;
             } else {
                 $fieldParams['id'] = CRM_Utils_Array::value('id', $editedResults);
             }
             $fieldParams['label'] = !empty($params['membership_type_label']) ? $params['membership_type_label'] : ts('Membership');
             $fieldParams['is_active'] = 1;
             $fieldParams['html_type'] = 'Radio';
             $fieldParams['is_required'] = !empty($params['is_required']) ? 1 : 0;
             $fieldParams['is_display_amounts'] = !empty($params['display_min_fee']) ? 1 : 0;
             $rowCount = 1;
             $options = array();
             if (!empty($fieldParams['id'])) {
                 CRM_Core_PseudoConstant::populate($options, 'CRM_Price_DAO_PriceFieldValue', TRUE, 'membership_type_id', NULL, " price_field_id = {$fieldParams['id']} ");
             }
             foreach ($membershipTypes as $memType => $memAutoRenew) {
                 if ($priceFieldID = CRM_Utils_Array::key($memType, $options)) {
                     $fieldParams['option_id'][$rowCount] = $priceFieldID;
                     unset($options[$priceFieldID]);
                 }
                 $membetype = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($memType);
                 $fieldParams['option_label'][$rowCount] = CRM_Utils_Array::value('name', $membetype);
                 $fieldParams['option_amount'][$rowCount] = CRM_Utils_Array::value('minimum_fee', $membetype, 0);
                 $fieldParams['option_weight'][$rowCount] = CRM_Utils_Array::value('weight', $membetype);
                 $fieldParams['option_description'][$rowCount] = CRM_Utils_Array::value('description', $membetype);
                 $fieldParams['default_option'] = CRM_Utils_Array::value('membership_type_default', $params);
                 $fieldParams['option_financial_type_id'][$rowCount] = CRM_Utils_Array::value('financial_type_id', $membetype);
                 $fieldParams['membership_type_id'][$rowCount] = $memType;
                 // [$rowCount] = $membetype[''];
                 $rowCount++;
             }
             foreach ($options as $priceFieldID => $memType) {
                 CRM_Price_BAO_PriceFieldValue::setIsActive($priceFieldID, '0');
             }
             $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
         } elseif (!$priceSetID) {
             $deletePriceSet = 1;
         }
         $params['is_required'] = CRM_Utils_Array::value('is_required', $params, FALSE);
         $params['is_active'] = CRM_Utils_Array::value('member_is_active', $params, FALSE);
         if ($priceSetID) {
             $params['membership_types'] = 'null';
             $params['membership_type_default'] = CRM_Utils_Array::value('membership_type_default', $params, 'null');
             $params['membership_types'] = serialize($membershipTypes);
             $params['display_min_fee'] = CRM_Utils_Array::value('display_min_fee', $params, FALSE);
             $params['is_separate_payment'] = CRM_Utils_Array::value('is_separate_payment', $params, FALSE);
         }
         $params['entity_table'] = 'civicrm_contribution_page';
         $params['entity_id'] = $this->_id;
         $dao = new CRM_Member_DAO_MembershipBlock();
         $dao->copyValues($params);
         $dao->save();
         if ($priceSetID && $params['is_active']) {
             CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $this->_id, $priceSetID);
         }
         if ($deletePriceSet || !CRM_Utils_Array::value('member_is_active', $params, FALSE)) {
             if ($this->_memPriceSetId) {
                 $pFIDs = array();
                 $conditionParams = array('price_set_id' => $this->_memPriceSetId, 'html_type' => 'radio', 'name' => 'contribution_amount');
                 CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $conditionParams, $pFIDs);
                 if (empty($pFIDs['id'])) {
                     CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution_page', $this->_id);
                     CRM_Price_BAO_PriceSet::setIsQuickConfig($this->_memPriceSetId, '0');
                 } else {
                     CRM_Price_BAO_PriceField::setIsActive($params['mem_price_field_id'], '0');
                 }
             }
         }
     }
     parent::endPostProcess();
 }
Example #19
0
/**
 * Returns array of price_sets matching a set of one or more group properties.
 *
 * @param array $params
 *   Array of one or more valid property_name=>value pairs. If $params is set.
 *   as null, all price_sets will be returned (default limit is 25)
 *
 * @return array
 *   Array of matching price_sets
 */
function civicrm_api3_price_set_get($params)
{
    // hack to make getcount work. - not sure the best approach here
    // as creating an alternate getcount function also feels a bit hacky
    if (isset($params['options']) && isset($params['options']['is_count'])) {
        return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
    }
    $result = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, FALSE);
    // Fetch associated entities
    foreach ($result as &$item) {
        $item['entity'] = CRM_Price_BAO_PriceSet::getUsedBy($item['id'], 'entity');
    }
    return civicrm_api3_create_success($result, $params);
}
Example #20
0
 /**
  * FixEventLevel() method (Setting ',' values), resolveDefaults(assinging value to array) method
  */
 public function testfixEventLevel()
 {
     $paramsSet['title'] = 'Price Set';
     $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
     $paramsSet['is_active'] = FALSE;
     $paramsSet['extends'] = 1;
     $priceset = CRM_Price_BAO_PriceSet::create($paramsSet);
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceset->id, 'title', 'id', $paramsSet['title'], 'Check DB for created priceset');
     $paramsField = array('label' => 'Price Field', 'name' => CRM_Utils_String::titleToVar('Price Field'), 'html_type' => 'Text', 'price' => 10, 'option_label' => array('1' => 'Price Field'), 'option_value' => array('1' => 10), 'option_name' => array('1' => 10), 'option_weight' => array('1' => 1), 'is_display_amounts' => 1, 'weight' => 1, 'options_per_line' => 1, 'is_active' => array('1' => 1), 'price_set_id' => $priceset->id, 'is_enter_qty' => 1);
     $ids = array();
     $pricefield = CRM_Price_BAO_PriceField::create($paramsField, $ids);
     //Checking for priceset added in the table.
     $this->assertDBCompareValue('CRM_Price_BAO_PriceField', $pricefield->id, 'label', 'id', $paramsField['label'], 'Check DB for created pricefield');
     $eventId = $this->_eventId;
     $participantParams = array('send_receipt' => 1, 'is_test' => 0, 'is_pay_later' => 0, 'event_id' => $eventId, 'register_date' => date('Y-m-d') . " 00:00:00", 'role_id' => 1, 'status_id' => 1, 'source' => 'Event_' . $eventId, 'contact_id' => $this->_contactId, 'note' => 'Note added for Event_' . $eventId, 'fee_level' => 'Price_Field - 55');
     $participant = CRM_Event_BAO_Participant::add($participantParams);
     //Checking for participant added in the table.
     $this->assertDBCompareValue('CRM_Event_BAO_Participant', $this->_contactId, 'id', 'contact_id', $participant->id, 'Check DB for created participant');
     $values = array();
     $ids = array();
     $params = array('id' => $participant->id);
     CRM_Event_BAO_Participant::getValues($params, $values, $ids);
     $this->assertNotEquals(count($values), 0, 'Checking for empty array.');
     CRM_Event_BAO_Participant::resolveDefaults($values[$participant->id]);
     if ($values[$participant->id]['fee_level']) {
         CRM_Event_BAO_Participant::fixEventLevel($values[$participant->id]['fee_level']);
     }
     $deletePricefield = CRM_Price_BAO_PriceField::deleteField($pricefield->id);
     $this->assertDBNull('CRM_Price_BAO_PriceField', $pricefield->id, 'name', 'id', 'Check DB for non-existence of Price Field.');
     $deletePriceset = CRM_Price_BAO_PriceSet::deleteSet($priceset->id);
     $this->assertDBNull('CRM_Price_BAO_PriceSet', $priceset->id, 'title', 'id', 'Check DB for non-existence of Price Set.');
     Participant::delete($participant->id);
     Contact::delete($this->_contactId);
     Event::delete($eventId);
 }
Example #21
0
 /**
  * Run the page.
  *
  * This method is called after the page is created. It checks for the
  * type of action and executes that action.
  *
  * @param null
  *
  * @return void
  * @access public
  */
 function run()
 {
     // get the field id
     $this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this, FALSE, 0);
     //get the price set id
     if (!$this->_sid) {
         $this->_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this);
     }
     if ($this->_sid) {
         CRM_Price_BAO_PriceSet::checkPermission($this->_sid);
         $this->_isSetReserved = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'is_reserved');
         $this->assign('isReserved', $this->_isSetReserved);
     }
     //as url contain $sid so append breadcrumb dynamically.
     $breadcrumb = array(array('title' => ts('Price Fields'), 'url' => CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&sid=' . $this->_sid)));
     CRM_Utils_System::appendBreadCrumb($breadcrumb);
     if ($this->_fid) {
         $fieldTitle = CRM_Price_BAO_PriceField::getTitle($this->_fid);
         $this->assign('fid', $this->_fid);
         $this->assign('fieldTitle', $fieldTitle);
         CRM_Utils_System::setTitle(ts('%1 - Price Options', array(1 => $fieldTitle)));
         $htmlType = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $this->_fid, 'html_type');
         $this->assign('addMoreFields', TRUE);
         //for text price field only single option present
         if ($htmlType == 'Text') {
             $this->assign('addMoreFields', FALSE);
         }
     }
     // get the requested action
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
     // assign vars to templates
     $this->assign('action', $action);
     $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, FALSE, 0);
     // what action to take ?
     if ($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::VIEW | CRM_Core_Action::DELETE) && !$this->_isSetReserved) {
         // no browse for edit/update/view
         $this->edit($action);
     } else {
         $this->browse();
     }
     // Call the parents run method
     return parent::run();
 }
Example #22
0
 /**
  * Global validation rules for the form.
  *
  * @param array $fields
  *   Posted values of the form.
  *
  * @param $files
  * @param CRM_Core_Form $form
  *
  * @return array
  *   if errors then list of errors to be posted back to the form,
  *                  true otherwise
  */
 public static function formRule($fields, $files, $form)
 {
     // all option fields are of type "money"
     $errors = array();
     /** Check the option values entered
      *  Appropriate values are required for the selected datatype
      *  Incomplete row checking is also required.
      */
     if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['price'] == NULL) {
         $errors['price'] = ts('Price is a required field');
     }
     if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['financial_type_id'] == '') {
         $errors['financial_type_id'] = ts('Financial Type is a required field');
     }
     //avoid the same price field label in Within PriceSet
     $priceFieldLabel = new CRM_Price_DAO_PriceField();
     $priceFieldLabel->label = $fields['label'];
     $priceFieldLabel->price_set_id = $form->_sid;
     $dupeLabel = FALSE;
     if ($priceFieldLabel->find(TRUE) && $form->_fid != $priceFieldLabel->id) {
         $dupeLabel = TRUE;
     }
     if ($dupeLabel) {
         $errors['label'] = ts('Name already exists in Database.');
     }
     if (is_numeric(CRM_Utils_Array::value('count', $fields)) && CRM_Utils_Array::value('count', $fields) == 0 && CRM_Utils_Array::value('html_type', $fields) == 'Text') {
         $errors['count'] = ts('Participant Count must be greater than zero.');
     }
     if ($form->_action & CRM_Core_Action::ADD) {
         if ($fields['html_type'] != 'Text') {
             $countemptyrows = 0;
             $_flagOption = $_rowError = 0;
             $_showHide = new CRM_Core_ShowHideBlocks('', '');
             for ($index = 1; $index <= self::NUM_OPTION; $index++) {
                 $noLabel = $noAmount = $noWeight = 1;
                 if (!empty($fields['option_label'][$index])) {
                     $noLabel = 0;
                     $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index], $fields['option_label']);
                     if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) {
                         $errors["option_label[{$index}]"] = ts('Duplicate label value');
                         $_flagOption = 1;
                     }
                 }
                 if ($form->_useForMember) {
                     if (!empty($fields['membership_type_id'][$index])) {
                         $memTypesIDS[] = $fields['membership_type_id'][$index];
                     }
                 }
                 // allow for 0 value.
                 if (!empty($fields['option_amount'][$index]) || strlen($fields['option_amount'][$index]) > 0) {
                     $noAmount = 0;
                 }
                 if (!empty($fields['option_weight'][$index])) {
                     $noWeight = 0;
                     $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index], $fields['option_weight']);
                     if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) {
                         $errors["option_weight[{$index}]"] = ts('Duplicate weight value');
                         $_flagOption = 1;
                     }
                 }
                 if (!$noLabel && !$noAmount && !empty($fields['option_financial_type_id']) && $fields['option_financial_type_id'][$index] == '' && $fields['html_type'] != 'Text') {
                     $errors["option_financial_type_id[{$index}]"] = ts('Financial Type is a Required field.');
                 }
                 if ($noLabel && !$noAmount) {
                     $errors["option_label[{$index}]"] = ts('Label cannot be empty.');
                     $_flagOption = 1;
                 }
                 if (!$noLabel && $noAmount) {
                     $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.');
                     $_flagOption = 1;
                 }
                 if ($noLabel && $noAmount) {
                     $countemptyrows++;
                     $_emptyRow = 1;
                 } elseif (!empty($fields['option_max_value'][$index]) && !empty($fields['option_count'][$index]) && $fields['option_count'][$index] > $fields['option_max_value'][$index]) {
                     $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.');
                     $_flagOption = 1;
                 }
                 $showBlocks = 'optionField_' . $index;
                 if ($_flagOption) {
                     $_showHide->addShow($showBlocks);
                     $_rowError = 1;
                 }
                 if (!empty($_emptyRow)) {
                     $_showHide->addHide($showBlocks);
                 } else {
                     $_showHide->addShow($showBlocks);
                 }
                 if ($index == self::NUM_OPTION) {
                     $hideBlock = 'additionalOption';
                     $_showHide->addHide($hideBlock);
                 }
                 $_flagOption = $_emptyRow = 0;
             }
             if (!empty($memTypesIDS)) {
                 // check for checkboxes allowing user to select multiple memberships from same membership organization
                 if ($fields['html_type'] == 'CheckBox') {
                     $foundDuplicate = FALSE;
                     $orgIds = array();
                     foreach ($memTypesIDS as $key => $val) {
                         $org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val);
                         if (in_array($org[$val], $orgIds)) {
                             $foundDuplicate = TRUE;
                             break;
                         }
                         $orgIds[$val] = $org[$val];
                     }
                     if ($foundDuplicate) {
                         $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity.');
                     }
                 }
                 // CRM-10390 - Only one price field in a set can include auto-renew membership options
                 $foundAutorenew = FALSE;
                 foreach ($memTypesIDS as $key => $val) {
                     // see if any price field option values in this price field are for memberships with autorenew
                     $memTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($val);
                     if (!empty($memTypeDetails['auto_renew'])) {
                         $foundAutorenew = TRUE;
                         break;
                     }
                 }
                 if ($foundAutorenew) {
                     // if so, check for other fields in this price set which also have auto-renew membership options
                     $otherFieldAutorenew = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($form->_sid);
                     if ($otherFieldAutorenew) {
                         $errors['_qf_default'] = ts('You can include auto-renew membership choices for only one price field in a price set. Another field in this set already contains one or more auto-renew membership options.');
                     }
                 }
             }
             $_showHide->addToTemplate();
             if ($countemptyrows == 15) {
                 $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
                 $_flagOption = 1;
             }
         } elseif (!empty($fields['max_value']) && !empty($fields['count']) && $fields['count'] > $fields['max_value']) {
             $errors['max_value'] = ts('Participant count can not be greater than max participants.');
         }
         // do not process if no option rows were submitted
         if (empty($fields['option_amount']) && empty($fields['option_label'])) {
             return TRUE;
         }
         if (empty($fields['option_name'])) {
             $fields['option_amount'] = array();
         }
         if (empty($fields['option_label'])) {
             $fields['option_label'] = array();
         }
     }
     return empty($errors) ? TRUE : $errors;
 }
Example #23
0
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::del($this->_id);
         return;
     }
     $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
     $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     $isTest = $this->_mode == 'test' ? 1 : 0;
     $lineItems = NULL;
     if (!empty($this->_lineItem)) {
         $lineItems = $this->_lineItem;
     }
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $this->convertDateFieldsToMySQL($formValues);
     $params = $softParams = $ids = array();
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($this->_params['auto_renew'])) {
         $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = NULL;
     if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) {
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     $termsByType = array();
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
             $params['tax_amount'] = $this->_params['tax_amount'];
         }
         $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
         if (!empty($lineItem[$priceSetId])) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 if (!empty($li['membership_type_id'])) {
                     if (!empty($li['membership_num_terms'])) {
                         $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                     }
                 }
                 ///CRM-11529 for quick config backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if ($isQuickConfig && $submittedFinancialType) {
                     $li['financial_type_id'] = $submittedFinancialType;
                 }
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         if (empty($memTypeNumTerms)) {
             $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
         }
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
             //$params[$d] = CRM_Utils_Date::processDate( $date );
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     foreach ($this->_memTypeSelected as $memType) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     }
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-13981, allow different person as a soft-contributor of chosen type
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($this->_params['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             $softParams['contact_id'] = $this->_contactID;
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             if (empty($formValues['source'])) {
                 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
             } else {
                 $params['contribution_source'] = $formValues['source'];
             }
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         if (empty($formValues['total_amount']) && !$priceSetId) {
             // if total amount not provided minimum for membership type is used
             $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee');
         } else {
             $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         }
         if ($priceSetId && !$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $fields["email-{$this->_bltID}"] = 1;
         }
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         }
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['description'] = ts('Office Credit Card Membership Signup Contribution');
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         $this->_params['financial_type_id'] = $params['financial_type_id'];
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id'];
             }
         }
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recuring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $contributionType = new CRM_Financial_DAO_FinancialType();
             $contributionType->id = $params['financial_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, TRUE, FALSE, $isTest, $lineItems);
             //create new soft-credit record, CRM-13981
             if ($softParams) {
                 $softParams['contribution_id'] = $contribution->id;
                 $softParams['currency'] = $contribution->currency;
                 $softParams['amount'] = $contribution->total_amount;
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             $paymentParams['contactID'] = $this->_contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
         }
         if ($params['total_amount'] > 0.0) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $result = $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (!empty($paymentParams['contributionID'])) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (!empty($paymentParams['contributionRecurID'])) {
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
             //assign amount to template if payment was successful
             $this->assign('amount', $params['total_amount']);
         }
         // if the payment processor returns a contribution_status_id -> use it!
         if (isset($result['contribution_status_id'])) {
             $result['payment_status_id'] = $result['contribution_status_id'];
         }
         if (isset($result['payment_status_id'])) {
             // CRM-16737 $result['contribution_status_id'] is deprecated in favour
             // of payment_status_id as the payment processor only knows whether the payment is complete
             // not whether payment completes the contribution
             $params['contribution_status_id'] = $result['payment_status_id'];
         } else {
             $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1;
         }
         if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             // unset send-receipt option, since receipt will be sent when ipn is received.
             unset($this->_params['send_receipt'], $formValues['send_receipt']);
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dp => $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($this->_params['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             //CRM-15366
             if (!empty($softParams) && empty($paymentParams['is_recur'])) {
                 $membershipParams['soft_credit'] = $softParams;
             }
             if (!empty($paymentParams['is_recur']) && CRM_Utils_Array::value('payment_status_id', $result) == 1) {
                 // CRM-16993 we have a situation where line items have already been created.
                 unset($membershipParams['lineItems']);
             }
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
             unset($params['lineItems']);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $fieldType = NULL;
                 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
                     $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'html_type');
                 }
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 $contributionBAO = new CRM_Contribute_BAO_Contribution();
                 $contributionBAO->id = $params['contribution_id'];
                 $contributionBAO->contact_id = $params['contact_id'];
                 $contributionBAO->find();
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
                 //create new soft-credit record, CRM-13981
                 if ($softParams) {
                     $softParams['contribution_id'] = $params['contribution_id'];
                     while ($contributionBAO->fetch()) {
                         $softParams['currency'] = $contributionBAO->currency;
                         $softParams['amount'] = $contributionBAO->total_amount;
                     }
                     CRM_Contribute_BAO_ContributionSoft::add($softParams);
                 }
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             // FIX ME: need to recheck this
             // here we might updated dates, so get from object.
             foreach ($calcDates[$membership->membership_type_id] as $date => &$val) {
                 if ($membership->{$date}) {
                     $val = $membership->{$date};
                 }
             }
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 if (!empty($softParams)) {
                     $membershipParams['soft_credit'] = $softParams;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
                 unset($params['lineItems']);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$priceSetId])) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $taxAmount = FALSE;
         $totalTaxAmount = 0;
         foreach ($lineItem[$priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
             if ($invoicing && isset($priceFieldOp['tax_amount'])) {
                 $taxAmount = TRUE;
                 $totalTaxAmount += $priceFieldOp['tax_amount'];
             }
         }
         if ($invoicing) {
             $dataArray = array();
             foreach ($lineItem[$priceSetId] as $key => $value) {
                 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                     if (isset($dataArray[$value['tax_rate']])) {
                         $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                     } else {
                         $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                     }
                 }
             }
             if ($taxAmount) {
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
             }
             $this->assign('dataArray', $dataArray);
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
     $membershipIds = $this->_membershipIDs;
     if ($contributionId && !empty($membershipIds)) {
         $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
         if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
             $receiptSend = TRUE;
         }
     }
     if (!empty($formValues['send_receipt']) && $receiptSend) {
         $formValues['contact_id'] = $this->_contactID;
         $formValues['contribution_id'] = $contributionId;
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         //end date can be modified by hooks, so if end date is set then use it.
         $endDate = $membership->end_date ? $membership->end_date : $endDate;
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
         if ($endDate && $endDate !== 'null') {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // FIX ME: fix status messages
         $statusMsg = array();
         foreach ($membershipTypes as $memType => $membershipType) {
             $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName));
             $membership = $createdMemberships[$memType];
             $memEndDate = $membership->end_date ? $membership->end_date : $endDate;
             //get the end date from calculated dates.
             if (!$memEndDate && empty($params['is_recur'])) {
                 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
             }
             if ($memEndDate && $memEndDate !== 'null') {
                 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
                 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
             }
         }
         $statusMsg = implode('<br/>', $statusMsg);
         if ($receiptSend && !empty($mailSend)) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
     }
 }
Example #24
0
 /**
  * Helper function for static submit function.
  *
  * Set relevant params - help us to build up an array that we can pass in.
  *
  * @param int $id
  * @param array $params
  *
  * @return array
  * @throws CiviCRM_API3_Exception
  */
 public static function getFormParams($id, array $params)
 {
     if (!isset($params['is_pay_later'])) {
         if (!empty($params['payment_processor_id'])) {
             $params['is_pay_later'] = 0;
         } else {
             $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', array('id' => $id, 'return' => 'is_pay_later'));
         }
     }
     if (empty($params['price_set_id'])) {
         $params['price_set_id'] = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id']);
     }
     return $params;
 }
Example #25
0
 /**
  * @param array $params
  * @param int $participantId
  * @param int $contributionId
  * @param $feeBlock
  * @param array $lineItems
  * @param $paidAmount
  * @param int $priceSetId
  */
 public static function changeFeeSelections($params, $participantId, $contributionId, $feeBlock, $lineItems, $paidAmount, $priceSetId)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $previousLineItems = CRM_Price_BAO_LineItem::getLineItems($participantId, 'participant');
     CRM_Price_BAO_PriceSet::processAmount($feeBlock, $params, $lineItems);
     // get the submitted
     foreach ($feeBlock as $id => $values) {
         CRM_Price_BAO_LineItem::format($id, $params, $values, $submittedLineItems);
         $submittedFieldId[] = CRM_Utils_Array::retrieveValueRecursive($submittedLineItems, 'price_field_id');
     }
     if (!empty($submittedLineItems)) {
         $insertLines = $submittedLineItems;
         $submittedFieldValueIds = array_keys($submittedLineItems);
         $updateLines = array();
         foreach ($previousLineItems as $id => $previousLineItem) {
             // check through the submitted items if the previousItem exists,
             // if found in submitted items, do not use it for new item creations
             if (in_array($previousLineItem['price_field_value_id'], $submittedFieldValueIds)) {
                 // if submitted line items are existing don't fire INSERT query
                 unset($insertLines[$previousLineItem['price_field_value_id']]);
                 // for updating the line items i.e. use-case - once deselect-option selecting again
                 if ($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] || $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1 || $previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty']) {
                     $updateLines[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
                     $updateLines[$previousLineItem['price_field_value_id']]['id'] = $id;
                 }
             }
         }
         $submittedFields = implode(', ', $submittedFieldId);
         $submittedFieldValues = implode(', ', $submittedFieldValueIds);
     }
     if (!empty($submittedFields) && !empty($submittedFieldValues)) {
         $updateLineItem = "UPDATE civicrm_line_item li\nINNER JOIN civicrm_financial_item fi\n   ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nSET li.qty = 0,\n    li.line_total = 0.00,\n    li.tax_amount = NULL\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n       (price_field_value_id NOT IN ({$submittedFieldValues}))\n";
         CRM_Core_DAO::executeQuery($updateLineItem);
         // gathering necessary info to record negative (deselected) financial_item
         $updateFinancialItem = "\n  SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount\n    FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})\nGROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id\n";
         $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
         $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId, 'DESC', TRUE);
         $trxnId['id'] = $trxn['financialTrxnId'];
         $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
         $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
         $updateFinancialItemInfoValues = array();
         $financialItemsArray = array();
         while ($updateFinancialItemInfoDAO->fetch()) {
             $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
             $updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
             // the below params are not needed
             unset($updateFinancialItemInfoValues['id']);
             unset($updateFinancialItemInfoValues['created_date']);
             // if not submitted and difference is not 0 make it negative
             if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
                 // INSERT negative financial_items
                 $updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
                 if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
                     $updateFinancialItemInfoValues['tax']['amount'] = -$previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'];
                     $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
                     if ($updateFinancialItemInfoValues['financial_type_id']) {
                         $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
                     }
                 }
                 // INSERT negative financial_items for tax amount
                 $financialItemsArray[] = $updateFinancialItemInfoValues;
             } elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedFieldValueIds) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
                 $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
                 // INSERT financial_items for tax amount
                 if ($updateFinancialItemInfoValues['entity_id'] == $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['id'] && isset($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])) {
                     $updateFinancialItemInfoValues['tax']['amount'] = $updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
                     $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
                     if ($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
                         $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateLines[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
                     }
                 }
                 $financialItemsArray[] = $updateFinancialItemInfoValues;
             }
         }
     } elseif (empty($submittedFields) && empty($submittedFieldValues)) {
         $updateLineItem = "UPDATE civicrm_line_item li\n        INNER JOIN civicrm_financial_item fi\n        ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')\n        SET li.qty = 0,\n        li.line_total = 0.00,\n        li.tax_amount = NULL\n        WHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId})";
         CRM_Core_DAO::executeQuery($updateLineItem);
     }
     $amountLevel = array();
     $totalParticipant = $participantCount = 0;
     if (!empty($updateLines)) {
         foreach ($updateLines as $valueId => $vals) {
             $taxAmount = "NULL";
             if (isset($vals['tax_amount'])) {
                 $taxAmount = $vals['tax_amount'];
             }
             $amountLevel[] = $vals['label'] . ' - ' . (double) $vals['qty'];
             if (isset($vals['participant_count'])) {
                 $participantCount = $vals['participant_count'];
                 $totalParticipant += $vals['participant_count'];
             }
             $updateLineItem = "\nUPDATE civicrm_line_item li\nSET li.qty = {$vals['qty']},\n    li.line_total = {$vals['line_total']},\n    li.tax_amount = {$taxAmount},\n    li.unit_price = {$vals['unit_price']},\n    li.participant_count = {$participantCount},\n    li.label = %1\nWHERE (li.entity_table = 'civicrm_participant' AND li.entity_id = {$participantId}) AND\n      (price_field_value_id = {$valueId})\n";
             CRM_Core_DAO::executeQuery($updateLineItem, array(1 => array($vals['label'], 'String')));
         }
     }
     // insert new 'adjusted amount' transaction entry and update contribution entry.
     // ensure entity_financial_trxn table has a linking of it.
     // insert new line items
     if (!empty($insertLines)) {
         foreach ($insertLines as $valueId => $lineParams) {
             $lineParams['entity_table'] = 'civicrm_participant';
             $lineParams['entity_id'] = $participantId;
             $lineParams['contribution_id'] = $contributionId;
             $lineObj = CRM_Price_BAO_LineItem::create($lineParams);
         }
     }
     // the recordAdjustedAmt code would execute over here
     $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
     if (count($ids) > 1) {
         $total = 0;
         foreach ($ids as $val) {
             $total += CRM_Price_BAO_LineItem::getLineTotal($val, 'civicrm_participant');
         }
         $updatedAmount = $total;
     } else {
         $updatedAmount = $params['amount'];
     }
     if (strlen($params['tax_amount']) != 0) {
         $taxAmount = $params['tax_amount'];
     } else {
         $taxAmount = "NULL";
     }
     $displayParticipantCount = '';
     if ($totalParticipant > 0) {
         $displayParticipantCount = ' Participant Count -' . $totalParticipant;
     }
     $updateAmountLevel = NULL;
     if (!empty($amountLevel)) {
         $updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
     }
     $trxn = self::recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
     $trxnId = array();
     if ($trxn) {
         $trxnId['id'] = $trxn->id;
         foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
             CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             if (!empty($updateFinancialItemInfoValues['tax'])) {
                 $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
                 $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
                 if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
                     $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
                 }
                 CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues, NULL, $trxnId);
             }
         }
     }
     $fetchCon = array('id' => $contributionId);
     $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     // insert financial items
     if (!empty($insertLines)) {
         foreach ($insertLines as $valueId => $lineParams) {
             $lineParams['entity_table'] = 'civicrm_participant';
             $lineParams['entity_id'] = $participantId;
             $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
             // insert financial items
             // ensure entity_financial_trxn table has a linking of it.
             $prevItem = CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $trxnId);
             if (isset($lineObj->tax_amount)) {
                 CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $trxnId);
             }
         }
     }
     // update participant fee_amount column
     $partUpdateFeeAmt['id'] = $participantId;
     $getUpdatedLineItems = "SELECT *\nFROM civicrm_line_item\nWHERE (entity_table = 'civicrm_participant' AND entity_id = {$participantId} AND qty > 0)";
     $getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
     while ($getUpdatedLineItemsDAO->fetch()) {
         $line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (double) $getUpdatedLineItemsDAO->qty;
     }
     $partUpdateFeeAmt['fee_level'] = implode(', ', $line);
     $partUpdateFeeAmt['fee_amount'] = $params['amount'];
     self::add($partUpdateFeeAmt);
     //activity creation
     self::addActivityForSelection($participantId, 'Change Registration');
 }
Example #26
0
 /**
  * Delete the indirect records associated with this contribution first.
  *
  * @param int $id
  *
  * @return mixed|null
  *   $results no of deleted Contribution on success, false otherwise
  */
 public static function deleteContribution($id)
 {
     CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
     $transaction = new CRM_Core_Transaction();
     $results = NULL;
     //delete activity record
     $params = array('source_record_id' => $id, 'activity_type_id' => 6);
     CRM_Activity_BAO_Activity::deleteActivity($params);
     //delete billing address if exists for this contribution.
     self::deleteAddress($id);
     //update pledge and pledge payment, CRM-3961
     CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
     // remove entry from civicrm_price_set_entity, CRM-5095
     if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
         CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
     }
     // cleanup line items.
     $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
     // delete any related entity_financial_trxn, financial_trxn and financial_item records.
     CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
     if ($participantId) {
         CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
     } else {
         CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
     }
     //delete note.
     $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
     $noteId = key($note);
     if ($noteId) {
         CRM_Core_BAO_Note::del($noteId, FALSE);
     }
     $dao = new CRM_Contribute_DAO_Contribution();
     $dao->id = $id;
     $results = $dao->delete();
     $transaction->commit();
     CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
     // delete the recently created Contribution
     $contributionRecent = array('id' => $id, 'type' => 'Contribution');
     CRM_Utils_Recent::del($contributionRecent);
     return $results;
 }
Example #27
0
 /**
  * Process the form.
  */
 public function postProcess()
 {
     $eventTitle = '';
     $params = $this->exportValues();
     $this->set('discountSection', 0);
     if (!empty($_POST['_qf_Fee_submit'])) {
         $this->buildAmountLabel();
         $this->set('discountSection', 2);
         return;
     }
     if (!empty($params['payment_processor'])) {
         $params['payment_processor'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
     } else {
         $params['payment_processor'] = 'null';
     }
     $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, 0);
     $params['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $params, 0);
     if ($this->_id) {
         // delete all the prior label values or discounts in the custom options table
         // and delete a price set if one exists
         //@todo note that this removes the reference from existing participants -
         // even where there is not change - redress?
         // note that a more tentative form of this is invoked by passing price_set_id as an array
         // to event.create see CRM-14069
         // @todo get all of this logic out of form layer (currently partially in BAO/api layer)
         if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $this->_id)) {
             CRM_Core_BAO_Discount::del($this->_id, 'civicrm_event');
         }
     }
     if ($params['is_monetary']) {
         if (!empty($params['price_set_id'])) {
             //@todo this is now being done in the event BAO if passed price_set_id as an array
             // per notes on that fn - looking at the api converting to an array
             // so calling via the api may cause this to be done in the api
             CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $params['price_set_id']);
             if (!empty($params['price_field_id'])) {
                 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
                 CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
             }
         } else {
             // if there are label / values, create custom options for them
             $labels = CRM_Utils_Array::value('label', $params);
             $values = CRM_Utils_Array::value('value', $params);
             $default = CRM_Utils_Array::value('default', $params);
             $options = array();
             if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (!empty($labels[$i]) && !CRM_Utils_System::isNull($values[$i])) {
                         $options[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                     }
                 }
                 if (!empty($options)) {
                     $params['default_fee_id'] = NULL;
                     if (empty($params['price_set_id'])) {
                         if (empty($params['price_field_id'])) {
                             $setParams['title'] = $eventTitle = $this->_isTemplate ? $this->_defaultValues['template_title'] : $this->_defaultValues['title'];
                             $eventTitle = strtolower(CRM_Utils_String::munge($eventTitle, '_', 245));
                             if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle, 'id', 'name')) {
                                 $setParams['name'] = $eventTitle;
                             } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $this->_id, 'id', 'name')) {
                                 $setParams['name'] = $eventTitle . '_' . $this->_id;
                             } else {
                                 $timeSec = explode('.', microtime(TRUE));
                                 $setParams['name'] = $eventTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
                             }
                             $setParams['is_quick_config'] = 1;
                             $setParams['financial_type_id'] = $params['financial_type_id'];
                             $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
                             $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                             $fieldParams['name'] = strtolower(CRM_Utils_String::munge($params['fee_label'], '_', 245));
                             $fieldParams['price_set_id'] = $priceSet->id;
                         } else {
                             foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
                                 if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
                                     CRM_Price_BAO_PriceFieldValue::setIsActive($fieldValueID, '0');
                                     unset($params['price_field_value'][$arrayID]);
                                 }
                             }
                             $fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
                             $fieldParams['option_id'] = $params['price_field_value'];
                             $priceSet = new CRM_Price_BAO_PriceSet();
                             $priceSet->id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $params), 'price_set_id');
                             if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
                                 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $priceSet->id, 'financial_type_id', $params['financial_type_id']);
                             }
                         }
                         $fieldParams['label'] = $params['fee_label'];
                         $fieldParams['html_type'] = 'Radio';
                         CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $priceSet->id);
                         $fieldParams['option_label'] = $params['label'];
                         $fieldParams['option_amount'] = $params['value'];
                         $fieldParams['financial_type_id'] = $params['financial_type_id'];
                         foreach ($options as $value) {
                             $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                         }
                         $fieldParams['default_option'] = $params['default'];
                         $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
                     }
                 }
             }
             $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : array();
             $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : array();
             if (CRM_Utils_Array::value('is_discount', $params) == 1) {
                 // if there are discounted set of label / values,
                 // create custom options for them
                 $labels = CRM_Utils_Array::value('discounted_label', $params);
                 $values = CRM_Utils_Array::value('discounted_value', $params);
                 $default = CRM_Utils_Array::value('discounted_default', $params);
                 if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
                     for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
                         $discountOptions = array();
                         for ($i = 1; $i < self::NUM_OPTION; $i++) {
                             if (!empty($labels[$i]) && !CRM_Utils_System::isNull(CRM_Utils_Array::value($j, $values[$i]))) {
                                 $discountOptions[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i][$j])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                             }
                         }
                         if (!empty($discountOptions)) {
                             $fieldParams = array();
                             $params['default_discount_fee_id'] = NULL;
                             $keyCheck = $j - 1;
                             $setParams = array();
                             if (empty($discountPriceSets[$keyCheck])) {
                                 if (!$eventTitle) {
                                     $eventTitle = strtolower(CRM_Utils_String::munge($this->_defaultValues['title'], '_', 200));
                                 }
                                 $setParams['title'] = $params['discount_name'][$j];
                                 if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j], 'id', 'name')) {
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j];
                                 } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id, 'id', 'name')) {
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id;
                                 } else {
                                     $timeSec = explode('.', microtime(TRUE));
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . date('is', $timeSec[0]) . $timeSec[1];
                                 }
                                 $setParams['is_quick_config'] = 1;
                                 $setParams['financial_type_id'] = $params['financial_type_id'];
                                 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
                                 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                                 $priceSetID = $priceSet->id;
                             } else {
                                 $priceSetID = $discountPriceSets[$j - 1];
                                 $setParams = array('title' => $params['discount_name'][$j], 'id' => $priceSetID);
                                 if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
                                     $setParams['financial_type_id'] = $params['financial_type_id'];
                                 }
                                 CRM_Price_BAO_PriceSet::create($setParams);
                                 unset($discountPriceSets[$j - 1]);
                                 $fieldParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $priceSetID, 'id', 'price_set_id');
                             }
                             $fieldParams['name'] = $fieldParams['label'] = $params['fee_label'];
                             $fieldParams['is_required'] = 1;
                             $fieldParams['price_set_id'] = $priceSetID;
                             $fieldParams['html_type'] = 'Radio';
                             $fieldParams['financial_type_id'] = $params['financial_type_id'];
                             foreach ($discountOptions as $value) {
                                 $fieldParams['option_label'][$value['weight']] = $value['label'];
                                 $fieldParams['option_amount'][$value['weight']] = $value['value'];
                                 $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                                 if (!empty($value['is_default'])) {
                                     $fieldParams['default_option'] = $value['weight'];
                                 }
                                 if (!empty($discountFieldIDs[$j]) && !empty($discountFieldIDs[$j][$value['weight']])) {
                                     $fieldParams['option_id'][$value['weight']] = $discountFieldIDs[$j][$value['weight']];
                                     unset($discountFieldIDs[$j][$value['weight']]);
                                 }
                             }
                             //create discount priceset
                             $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
                             if (!empty($discountFieldIDs[$j])) {
                                 foreach ($discountFieldIDs[$j] as $fID) {
                                     CRM_Price_BAO_PriceFieldValue::setIsActive($fID, '0');
                                 }
                             }
                             $discountParams = array('entity_table' => 'civicrm_event', 'entity_id' => $this->_id, 'price_set_id' => $priceSetID, 'start_date' => CRM_Utils_Date::processDate($params['discount_start_date'][$j]), 'end_date' => CRM_Utils_Date::processDate($params['discount_end_date'][$j]));
                             CRM_Core_BAO_Discount::add($discountParams);
                         }
                     }
                 }
             }
             if (!empty($discountPriceSets)) {
                 foreach ($discountPriceSets as $setId) {
                     CRM_Price_BAO_PriceSet::setIsQuickConfig($setId, 0);
                 }
             }
         }
     } else {
         if (!empty($params['price_field_id'])) {
             $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
             CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
         }
         $params['financial_type_id'] = '';
         $params['is_pay_later'] = 0;
         $params['is_billing_required'] = 0;
     }
     //update 'is_billing_required'
     if (empty($params['is_pay_later'])) {
         $params['is_billing_required'] = FALSE;
     }
     //update events table
     $params['id'] = $this->_id;
     // skip update of financial type in price set
     $params['skipFinancialType'] = TRUE;
     CRM_Event_BAO_Event::add($params);
     // Update tab "disabled" css class
     $this->ajaxResponse['tabValid'] = !empty($params['is_monetary']);
     parent::endPostProcess();
 }
Example #28
0
 /**
  * @param CRM_Core_Form $form
  * @param int $eventID
  *
  * @throws Exception
  */
 public static function initEventFee(&$form, $eventID)
 {
     // get price info
     // retrive all active price set fields.
     $discountId = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
     if (property_exists($form, '_discountId') && $form->_discountId) {
         $discountId = $form->_discountId;
     }
     //CRM-16456 get all price field including expired one.
     $getAllPriceField = TRUE;
     $className = CRM_Utils_System::getClassName($form);
     if ($className == 'CRM_Event_Form_ParticipantFeeSelection' && $form->_action == CRM_Core_Action::UPDATE) {
         $getAllPriceField = FALSE;
     }
     if ($discountId) {
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
         $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', $getAllPriceField, $priceSetId);
     } else {
         $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', $getAllPriceField);
     }
     if (property_exists($form, '_context') && ($form->_context == 'standalone' || $form->_context == 'participant')) {
         $discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($eventID, 'civicrm_event');
         if (is_array($discountedEvent)) {
             foreach ($discountedEvent as $key => $priceSetId) {
                 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId);
                 $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
                 $form->_values['discount'][$key] = CRM_Utils_Array::value('fields', $priceSet);
                 $fieldID = key($form->_values['discount'][$key]);
                 $form->_values['discount'][$key][$fieldID]['name'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'title');
             }
         }
     }
     $eventFee = CRM_Utils_Array::value('fee', $form->_values);
     if (!is_array($eventFee) || empty($eventFee)) {
         $form->_values['fee'] = array();
     }
     //fix for non-upgraded price sets.CRM-4256.
     if (isset($form->_isPaidEvent)) {
         $isPaidEvent = $form->_isPaidEvent;
     } else {
         $isPaidEvent = CRM_Utils_Array::value('is_monetary', $form->_values['event']);
     }
     if ($isPaidEvent && empty($form->_values['fee'])) {
         if (CRM_Utils_System::getClassName($form) != 'CRM_Event_Form_Participant') {
             CRM_Core_Error::fatal(ts('No Fee Level(s) or Price Set is configured for this event.<br />Click <a href=\'%1\'>CiviEvent >> Manage Event >> Configure >> Event Fees</a> to configure the Fee Level(s) or Price Set for this event.', array(1 => CRM_Utils_System::url('civicrm/event/manage/fee', 'reset=1&action=update&id=' . $form->_eventId))));
         }
     }
 }
Example #29
0
 /**
  * Get the amount level for the event payment.
  *
  * The amount level is the string stored on the contribution record that describes the purchase.
  *
  * @param array $params
  * @param int|null $discountID
  *
  * @return string
  */
 protected function getAmountLevel($params, $discountID)
 {
     // @todo move handling of discount ID to the BAO function - preferably by converting it to a price_set with
     // time settings.
     if (!empty($this->_values['discount'][$discountID])) {
         return $this->_values['discount'][$discountID][$params['amount']]['label'];
     }
     return CRM_Price_BAO_PriceSet::getAmountLevelText($params);
 }
Example #30
0
 /**
  * @param array $submittedValues
  *
  * @param int $action
  *   Action constant
  *    - CRM_Core_Action::UPDATE
  *
  * @param $pledgePaymentID
  *
  * @return array
  * @throws \Exception
  */
 protected function submit($submittedValues, $action, $pledgePaymentID)
 {
     $softParams = $softIDs = array();
     $pId = $contribution = $isRelatedId = FALSE;
     $this->_params = $submittedValues;
     $this->beginPostProcess();
     if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
         // config should be treated the same.
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // Process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
     // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
     // as a point of fragility rather than a logical 'if' clause.
     if ($priceSetId) {
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         // Unset tax amount for offline 'is_quick_config' contribution.
         // @todo WHY  - quick config was conceived as a quick way to configure contribution forms.
         // this is an example of 'other' functionality being hung off it.
         if ($this->_priceSet['is_quick_config'] && !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())) {
             unset($submittedValues['tax_amount']);
         }
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if ($this->_id) {
         if ($this->_compId) {
             if ($this->_context == 'participant') {
                 $pId = $this->_compId;
             } elseif ($this->_context == 'membership') {
                 $isRelatedId = TRUE;
             } else {
                 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
             }
         } else {
             $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (array_key_exists('membership', $contributionDetails)) {
                 $isRelatedId = TRUE;
             } elseif (array_key_exists('participant', $contributionDetails)) {
                 $pId = $contributionDetails['participant'];
             }
         }
     }
     if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
         // CRM-10117 update the line items for participants.
         // @todo - if we are completing a contribution then the api call
         // civicrm_api3('Contribution', 'completetransaction') should take care of
         // all associated updates rather than replicating them on the form layer.
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $isRelatedId = FALSE;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
         foreach (array_keys($lineItems) as $id) {
             $lineItems[$id]['id'] = $id;
         }
         $itemId = key($lineItems);
         if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
             $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         }
         // @todo see above - new functionality has been inappropriately added to the quick config concept
         // and new functionality has been added onto the form layer rather than the BAO :-(
         if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
             //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
             $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
                 if (!($this->_action & CRM_Core_Action::UPDATE && $this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])) {
                     $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
                 }
             }
             // Update line total and total amount with tax on edit.
             $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
             if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
                 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
             } else {
                 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
                 $submittedValues['tax_amount'] = 'null';
             }
             if ($lineItems[$itemId]['tax_rate']) {
                 $lineItems[$itemId]['tax_amount'] = $lineItems[$itemId]['tax_rate'] / 100 * $lineItems[$itemId]['line_total'];
                 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
                 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
             }
         }
         // CRM-10117 update the line items for participants.
         if (!empty($lineItems[$itemId]['price_field_id'])) {
             $lineItem[$this->_priceSetId] = $lineItems;
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     //CRM-11529 for quick config back office transactions
     //when financial_type_id is passed in form, update the
     //line items with the financial type selected in form
     // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
     // we should look at having a price field per contribution type & then there would be little reason
     // for the back-office contribution form postProcess to know if it is a quick-config form.
     if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)) {
         foreach ($lineItem[$this->_priceSetId] as &$values) {
             $values['financial_type_id'] = $submittedValues['financial_type_id'];
         }
     }
     if (!isset($submittedValues['total_amount'])) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
     if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
         //Delete existing soft credit records if soft credit list is empty on update
         CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
     }
     // set the contact, when contact is selected
     if (!empty($submittedValues['contact_id'])) {
         $this->_contactID = $submittedValues['contact_id'];
     }
     $formValues = $submittedValues;
     // Credit Card Contribution.
     if ($this->_mode) {
         $paramsSetByPaymentProcessingSubsystem = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             if (isset($formValues[$key])) {
                 unset($formValues[$key]);
             }
         }
         $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
         foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
             $formValues[$key] = $contribution->{$key};
         }
     } else {
         // Offline Contribution.
         $submittedValues = $this->unsetCreditCardFields($submittedValues);
         // get the required field value only.
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $this->getCurrency($submittedValues);
         //format soft-credit/pcp param first
         CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
         $params = array_merge($params, $submittedValues);
         $fields = array('financial_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         // CRM-5740 if priceset is used, no need to cleanup money.
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (!empty($formValues['is_email_receipt'])) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name') || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date('YmdHis');
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         } elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
             $params['is_pay_later'] = 0;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         // Add Additional common information to formatted params.
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
         if ($pId) {
             $params['contribution_mode'] = 'participant';
             $params['participant_id'] = $pId;
             $params['skipLineItem'] = 1;
         } elseif ($isRelatedId) {
             $params['contribution_mode'] = 'membership';
         }
         $params['line_item'] = $lineItem;
         $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
         if (isset($submittedValues['tax_amount'])) {
             $params['tax_amount'] = $submittedValues['tax_amount'];
         }
         //create contribution.
         if ($isQuickConfig) {
             $params['is_quick_config'] = 1;
         }
         $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
         // we are already handling note below, so to avoid duplicate notes against $contribution
         if (!empty($params['note']) && !empty($submittedValues['note'])) {
             unset($params['note']);
         }
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process associated membership / participant, CRM-4395
         if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
             $this->statusMessage[] = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values), $contribution->receive_date);
         }
         array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
         $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
         //send receipt mail.
         if ($contribution->id && !empty($formValues['is_email_receipt'])) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
                 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
             }
         }
         $this->statusMessageTitle = ts('Saved');
     }
     if ($contribution->id && isset($formValues['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id, $this->_premiumID, $this->_options);
     }
     if ($contribution->id && !empty($submittedValues['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
     }
     CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
     CRM_Contribute_BAO_Contribution::updateRelatedPledge($action, $pledgePaymentID, $contribution->id, CRM_Utils_Array::value('option_type', $formValues) == 2 ? TRUE : FALSE, $formValues['total_amount'], CRM_Utils_Array::value('total_amount', $this->_defaults), $formValues['contribution_status_id'], CRM_Utils_Array::value('contribution_status_id', $this->_defaults));
     return $contribution;
 }