/** * Set variables up before form is built. */ public function preProcess() { $this->_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE); $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE); //CRM-4320 $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this); // 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'); $this->_lineItem = $this->get('lineItem'); $this->_isEventFull = $this->get('isEventFull'); $this->_lineItemParticipantsCount = $this->get('lineItemParticipants'); if (!is_array($this->_lineItem)) { $this->_lineItem = array(); } if (!is_array($this->_lineItemParticipantsCount)) { $this->_lineItemParticipantsCount = array(); } $this->_availableRegistrations = $this->get('availableRegistrations'); $this->_participantIDS = $this->get('participantIDs'); //check if participant allow to walk registration wizard. $this->_allowConfirmation = $this->get('allowConfirmation'); // check for Approval $this->_requireApproval = $this->get('requireApproval'); // check for waitlisting. $this->_allowWaitlist = $this->get('allowWaitlist'); $this->_forcePayement = $this->get('forcePayement'); //get the additional participant ids. $this->_additionalParticipantIds = $this->get('additionalParticipantIds'); $config = CRM_Core_Config::singleton(); if (!$this->_values) { // create redirect URL to send folks back to event info page is registration not available $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}", FALSE, NULL, FALSE, TRUE); // this is the first time we are hitting this, so check for permissions here if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId, 'register for events')) { CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $infoUrl); } // get all the values from the dao object $this->_values = $this->_fields = array(); $this->_forcePayement = FALSE; //retrieve event information $params = array('id' => $this->_eventId); CRM_Event_BAO_Event::retrieve($params, $this->_values['event']); // check for is_monetary status $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']); // check for ability to add contributions of type if ($isMonetary && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && !CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($this->_values['event']['financial_type_id']))) { CRM_Core_Error::fatal(ts('You do not have permission to access this page.')); } $this->checkValidEvent($infoUrl); // get the participant values, CRM-4320 $this->_allowConfirmation = FALSE; if ($this->_participantId) { $this->processFirstParticipant($this->_participantId); } //check for additional participants. if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) { $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId); $cnt = 1; foreach ($additionalParticipantIds as $additionalParticipantId) { $this->_additionalParticipantIds[$cnt] = $additionalParticipantId; $cnt++; } $this->set('additionalParticipantIds', $this->_additionalParticipantIds); } $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $this->_values['event'])); $this->_allowWaitlist = $this->_isEventFull = FALSE; if ($eventFull && !$this->_allowConfirmation) { $this->_isEventFull = TRUE; //lets redirecting to info only when to waiting list. $this->_allowWaitlist = CRM_Utils_Array::value('has_waitlist', $this->_values['event']); if (!$this->_allowWaitlist) { CRM_Utils_System::redirect($infoUrl); } } $this->set('isEventFull', $this->_isEventFull); $this->set('allowWaitlist', $this->_allowWaitlist); //check for require requires approval. $this->_requireApproval = FALSE; if (!empty($this->_values['event']['requires_approval']) && !$this->_allowConfirmation) { $this->_requireApproval = TRUE; } $this->set('requireApproval', $this->_requireApproval); if (isset($this->_values['event']['default_role_id'])) { $participant_role = CRM_Core_OptionGroup::values('participant_role'); $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"]; } $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'is_pay_later'); //check for various combinations for paylater, payment //process with paid event. if ($isMonetary && (!$isPayLater || !empty($this->_values['event']['payment_processor']))) { $this->_paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('payment_processor', $this->_values['event'])); $this->assignPaymentProcessor($isPayLater); } //init event fee. self::initEventFee($this, $this->_eventId); // get the profile ids $ufJoinParams = array('entity_table' => 'civicrm_event', 'module' => 'CiviEvent', 'entity_id' => $this->_eventId); list($this->_values['custom_pre_id'], $this->_values['custom_post_id']) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); // set profiles for additional participants if ($this->_values['event']['is_multiple_registrations']) { // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants $ufJoinParams['module'] = 'CiviEvent_Additional'; list($this->_values['additional_custom_pre_id'], $this->_values['additional_custom_post_id'], $preActive, $postActive) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact // set same profile for additional contacts. if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) { $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id']; } if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) { $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id']; } // now check for no profile condition, in that case is_active = 0 if (isset($preActive) && !$preActive) { unset($this->_values['additional_custom_pre_id']); } if (isset($postActive) && !$postActive) { unset($this->_values['additional_custom_post_id']); } } $this->assignBillingType(); if ($this->_values['event']['is_monetary']) { CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor); } $params = array('entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event'); $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE); $this->set('values', $this->_values); $this->set('fields', $this->_fields); $this->_availableRegistrations = CRM_Event_BAO_Participant::eventFull($this->_values['event']['id'], TRUE, CRM_Utils_Array::value('has_waitlist', $this->_values['event'])); $this->set('availableRegistrations', $this->_availableRegistrations); } $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor); // check if this is a paypal auto return and redirect accordingly if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) { $url = CRM_Utils_System::url('civicrm/event/register', "_qf_ThankYou_display=1&qfKey={$this->controller->_key}"); CRM_Utils_System::redirect($url); } // The concept of contributeMode is deprecated. $this->_contributeMode = $this->get('contributeMode'); $this->assign('contributeMode', $this->_contributeMode); // setting CMS page title CRM_Utils_System::setTitle($this->_values['event']['title']); $this->assign('title', $this->_values['event']['title']); $this->assign('paidEvent', $this->_values['event']['is_monetary']); // we do not want to display recently viewed items on Registration pages $this->assign('displayRecent', FALSE); // Registration page values are cleared from session, so can't use normal Printer Friendly view. // Use Browser Print instead. $this->assign('browserPrint', TRUE); $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']); $this->assign('isShowLocation', $isShowLocation); // Handle PCP $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this); if ($pcpId) { $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'event', $this->_values['event']); $this->_pcpId = $pcp['pcpId']; $this->_values['event']['intro_text'] = CRM_Utils_Array::value('intro_text', $pcp['pcpInfo']); } // assign all event properties so wizard templates can display event info. $this->assign('event', $this->_values['event']); $this->assign('location', $this->_values['location']); $this->assign('bltID', $this->_bltID); $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']); $this->assign('isShowLocation', $isShowLocation); //CRM-6907 $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values['event'], $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['event']['campaign_id'] = $campID; } // Set the same value for is_billing_required as contribution page so code can be shared. $this->_values['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $this->_values['event']); // check if billing block is required for pay later // note that I have started removing the use of isBillingAddressRequiredForPayLater in favour of letting // the CRM_Core_Payment_Manual class handle it - but there are ~300 references to it in the code base so only // removing in very limited cases. if (CRM_Utils_Array::value('is_pay_later', $this->_values['event'])) { $this->_isBillingAddressRequiredForPayLater = CRM_Utils_Array::value('is_billing_required', $this->_values['event']); $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater); } }
/** * 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(' ', '', $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}")); } }
/** * Function to process the form * * @access public * * @return void */ public function postProcess() { //get the button. $buttonName = $this->controller->getButtonName(); $participantId = $this->_participantId; if ($buttonName == '_qf_ParticipantConfirm_next') { //lets get contact id in session. $session = CRM_Core_Session::singleton(); $session->set('userID', $this->_csContactID); $this->postProcessHook(); //check user registration status is from pending class $url = CRM_Utils_System::url('civicrm/event/register', "reset=1&id={$this->_eventId}&participantId={$participantId}"); CRM_Utils_System::redirect($url); } elseif ($buttonName == '_qf_ParticipantConfirm_submit') { //need to registration status to 'cancelled'. $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")); $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId); $participantIds = array_merge(array($participantId), $additionalParticipantIds); $results = CRM_Event_BAO_Participant::transitionParticipants($participantIds, $cancelledId, NULL, TRUE); if (count($participantIds) > 1) { $statusMessage = ts("%1 Event registration(s) have been cancelled.", array(1 => count($participantIds))); } else { $statusMessage = ts("Your event registration has been cancelled."); } if (!empty($results['mailedParticipants'])) { foreach ($results['mailedParticipants'] as $key => $displayName) { $statusMessage .= "<br />" . ts("Email has been sent to : %1", array(1 => $displayName)); } } $this->postProcessHook(); CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}&noFullMsg=1", FALSE, NULL, FALSE, TRUE)); } }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { $params = $this->controller->exportValues($this->_name); if (CRM_Utils_Array::value('delete_participant', $params) == 2) { $links = array(); foreach ($this->_participantIds as $participantId) { $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId); $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId); } } $deletedParticipants = $additionalCount = 0; foreach ($this->_participantIds as $participantId) { if (CRM_Utils_Array::value('delete_participant', $params) == 1) { if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantId)) { $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId); $additionalCount = count($additionalIds); foreach ($additionalIds as $value) { CRM_Event_BAO_Participant::deleteParticipant($value); } CRM_Event_BAO_Participant::deleteParticipant($participantId); } $deletedParticipants++; } else { CRM_Event_BAO_Participant::deleteParticipant($participantId); $deletedParticipants++; } } if ($additionalCount) { $deletedParticipants += $additionalCount; } $status = array(ts('Participant(s) Deleted: %1', array(1 => $deletedParticipants)), ts('Total Selected Participant(s): %1', array(1 => $deletedParticipants))); 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); }
/** * Create all financial accounts entry. * * @param array $params * Contribution object, line item array and params for trxn. * * * @param array $financialTrxnValues * * @return null|object */ public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) { $skipRecords = $update = $return = $isRelatedId = FALSE; $additionalParticipantId = array(); $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') { $entityId = $params['participant_id']; $entityTable = 'civicrm_participant'; $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId); } elseif (!empty($params['membership_id'])) { //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships // are created off one contribution should be handled elsewhere $entityId = $params['membership_id']; $entityTable = 'civicrm_membership'; } else { $entityId = $params['contribution']->id; $entityTable = 'civicrm_contribution'; } if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') { $isRelatedId = TRUE; } $entityID[] = $entityId; if (!empty($additionalParticipantId)) { $entityID += $additionalParticipantId; } // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated if (empty($params['prevContribution'])) { $entityID = NULL; } else { $update = TRUE; } $statusId = $params['contribution']->contribution_status_id; // CRM-13964 partial payment if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses) && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) { $partialAmtPay = $params['partial_amount_pay']; $partialAmtTotal = $params['partial_payment_total']; $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); $params['total_amount'] = $partialAmtPay; $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']); if (empty($balanceTrxnInfo['trxn_id'])) { // create new balance transaction record $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); $balanceTrxnParams['total_amount'] = $partialAmtTotal; $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount; $balanceTrxnParams['contribution_id'] = $params['contribution']->id; $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'); $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params); $balanceTrxnParams['currency'] = $params['contribution']->currency; $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id; $balanceTrxnParams['status_id'] = $statusId; $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id; $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params); if (!empty($params['payment_processor'])) { $balanceTrxnParams['payment_processor_id'] = $params['payment_processor']; } $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams); } } // build line item array if its not set in $params if (empty($params['line_item']) || $additionalParticipantId) { CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId); } if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) && !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)) { $skipRecords = TRUE; $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses)); if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) { $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); } elseif (!empty($params['payment_processor'])) { $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id'); } elseif (!empty($params['payment_instrument_id'])) { $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']); } else { $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); $queryParams = array(1 => array($relationTypeId, 'Integer')); $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams); } $totalAmount = CRM_Utils_Array::value('total_amount', $params); if (!isset($totalAmount) && !empty($params['prevContribution'])) { $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount; } //build financial transaction params $trxnParams = array('contribution_id' => $params['contribution']->id, 'to_financial_account_id' => $params['to_financial_account_id'], 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'), 'total_amount' => $totalAmount, 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount), 'currency' => $params['contribution']->currency, 'trxn_id' => $params['contribution']->trxn_id, 'status_id' => $statusId, 'payment_instrument_id' => $params['contribution']->payment_instrument_id, 'check_number' => CRM_Utils_Array::value('check_number', $params)); if (!empty($params['payment_processor'])) { $trxnParams['payment_processor_id'] = $params['payment_processor']; } if (isset($fromFinancialAccountId)) { $trxnParams['from_financial_account_id'] = $fromFinancialAccountId; } // consider external values passed for recording transaction entry if (!empty($financialTrxnValues)) { $trxnParams = array_merge($trxnParams, $financialTrxnValues); } $params['trxnParams'] = $trxnParams; if (!empty($params['prevContribution'])) { $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount; $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount; $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount; $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id; $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id; if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses)) && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))) { $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; } //if financial type is changed if (!empty($params['financial_type_id']) && $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id) { $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' ")); $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId); $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId); if ($oldFinancialAccount != $newFinancialAccount) { $params['total_amount'] = 0; if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) { $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $relationTypeId); } else { $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); if (!empty($lastFinancialTrxnId['financialTrxnId'])) { $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); } } self::updateFinancialAccounts($params, 'changeFinancialType'); /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */ $params['financial_account_id'] = $newFinancialAccount; $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params); $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; } } //Update contribution status $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id; $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; if (!empty($params['contribution_status_id']) && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) { //Update Financial Records self::updateFinancialAccounts($params, 'changedStatus'); } // change Payment Instrument for a Completed contribution // first handle special case when contribution is changed from Pending to Completed status when initial payment // instrument is null and now new payment instrument is added along with the payment $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params); if (array_key_exists('payment_instrument_id', $params)) { $params['trxnParams']['total_amount'] = -$trxnParams['total_amount']; if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) && !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)) { //check if status is changed from Pending to Completed // do not update payment instrument changes for Pending to Completed if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) && in_array($params['prevContribution']->contribution_status_id, $pendingStatus))) { // for all other statuses create new financial records self::updateFinancialAccounts($params, 'changePaymentInstrument'); $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params, 'changePaymentInstrument'); } } elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) || !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) && $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id) { // for any other payment instrument changes create new financial records self::updateFinancialAccounts($params, 'changePaymentInstrument'); $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params, 'changePaymentInstrument'); } elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) && $params['contribution']->check_number != $params['prevContribution']->check_number) { // another special case when check number is changed, create new financial records // create financial trxn with negative amount $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; self::updateFinancialAccounts($params, 'changePaymentInstrument'); // create financial trxn with positive amount $params['trxnParams']['check_number'] = $params['contribution']->check_number; $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params, 'changePaymentInstrument'); } } //if Change contribution amount $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params); $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount; $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; if (isset($totalAmount) && $totalAmount != $params['prevContribution']->total_amount) { //Update Financial Records $params['trxnParams']['from_financial_account_id'] = NULL; self::updateFinancialAccounts($params, 'changedAmount'); } } if (!$update) { // records finanical trxn and entity financial trxn // also make it available as return value $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); $params['entity_id'] = $financialTxn->id; } } // record line items and financial items if (empty($params['skipLineItem'])) { CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update); } // create batch entry if batch_id is passed and // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611 if (!empty($params['batch_id']) && !empty($financialTxn)) { $entityParams = array('batch_id' => $params['batch_id'], 'entity_table' => 'civicrm_financial_trxn', 'entity_id' => $financialTxn->id); CRM_Batch_BAO_Batch::addBatchEntity($entityParams); } // when a fee is charged if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) { CRM_Core_BAO_FinancialTrxn::recordFees($params); } if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant' && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) { $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id'); $feeLevel[] = str_replace('', '', $params['prevContribution']->amount_level); CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel); } unset($params['line_item']); return $return; }
public function updateParticipantStatus() { require_once 'CRM/Event/PseudoConstant.php'; $participantRole = CRM_Event_PseudoConstant::participantRole(); $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'"); $expiredStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"); $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'"); //build the required status ids. $statusIds = '(' . implode(',', array_merge(array_keys($pendingStatuses), array_keys($waitingStatuses))) . ')'; $participantDetails = $fullEvents = array(); $expiredParticipantCount = $waitingConfirmCount = $waitingApprovalCount = 0; //get all participant who's status in class pending and waiting $query = "SELECT * FROM civicrm_participant WHERE status_id IN {$statusIds} ORDER BY register_date"; $query = "\n SELECT participant.id,\n participant.contact_id,\n participant.status_id,\n participant.register_date,\n participant.registered_by_id,\n participant.event_id,\n event.title as eventTitle,\n event.registration_start_date,\n event.registration_end_date,\n event.end_date,\n event.expiration_time,\n event.requires_approval\n FROM civicrm_participant participant\nLEFT JOIN civicrm_event event ON ( event.id = participant.event_id )\n WHERE participant.status_id IN {$statusIds}\n AND (event.end_date > now() OR event.end_date IS NULL)\n AND event.is_active = 1 \n ORDER BY participant.register_date, participant.id \n"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $participantDetails[$dao->id] = array('id' => $dao->id, 'event_id' => $dao->event_id, 'status_id' => $dao->status_id, 'contact_id' => $dao->contact_id, 'register_date' => $dao->register_date, 'registered_by_id' => $dao->registered_by_id, 'eventTitle' => $dao->eventTitle, 'registration_start_date' => $dao->registration_start_date, 'registration_end_date' => $dao->registration_end_date, 'end_date' => $dao->end_date, 'expiration_time' => $dao->expiration_time, 'requires_approval' => $dao->requires_approval); } if (!empty($participantDetails)) { //cron 1. move participant from pending to expire if needed foreach ($participantDetails as $participantId => $values) { //process the additional participant at the time of //primary participant, don't process separately. if (CRM_Utils_Array::value('registered_by_id', $values)) { continue; } $expirationTime = CRM_Utils_Array::value('expiration_time', $values); if ($expirationTime && array_key_exists($values['status_id'], $pendingStatuses)) { //get the expiration and registration pending time. $expirationSeconds = $expirationTime * 3600; $registrationPendingSeconds = CRM_Utils_Date::unixTime($values['register_date']); // expired registration since registration cross allow confirmation time. if ($expirationSeconds + $registrationPendingSeconds < time()) { //lets get the transaction mechanism. require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); require_once 'CRM/Event/BAO/Participant.php'; $ids = array($participantId); $expiredId = array_search('Expired', $expiredStatuses); $results = CRM_Event_BAO_Participant::transitionParticipants($ids, $expiredId, $values['status_id'], TRUE, TRUE); $transaction->commit(); if (!empty($results)) { //diaplay updated participants if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) { foreach ($results['updatedParticipantIds'] as $processedId) { $expiredParticipantCount += 1; echo "<br /><br />- status updated to: Expired"; //mailed participants. if (is_array($results['mailedParticipants']) && array_key_exists($processedId, $results['mailedParticipants'])) { echo "<br />Expiration Mail sent to: {$results['mailedParticipants'][$processedId]}"; } } } } } } } //cron 1 end. //cron 2. lets move participants from waiting list to pending status foreach ($participantDetails as $participantId => $values) { //process the additional participant at the time of //primary participant, don't process separately. if (CRM_Utils_Array::value('registered_by_id', $values)) { continue; } if (array_key_exists($values['status_id'], $waitingStatuses) && !array_key_exists($values['event_id'], $fullEvents)) { if ($waitingStatuses[$values['status_id']] == 'On waitlist' && CRM_Event_BAO_Event::validRegistrationDate($values)) { //check the target event having space. require_once 'CRM/Event/BAO/Participant.php'; $eventOpenSpaces = CRM_Event_BAO_Participant::eventFull($values['event_id'], TRUE, FALSE); if ($eventOpenSpaces && is_numeric($eventOpenSpaces) || $eventOpenSpaces === NULL) { //get the additional participant if any. $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId); $allIds = array($participantId); if (!empty($additionalIds)) { $allIds = array_merge($allIds, $additionalIds); } $pClause = ' participant.id IN ( ' . implode(' , ', $allIds) . ' )'; $requiredSpaces = CRM_Event_BAO_Event::eventTotalSeats($values['event_id'], $pClause); //need to check as to see if event has enough speces if ($requiredSpaces <= $eventOpenSpaces || $eventOpenSpaces === NULL) { require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); require_once 'CRM/Event/BAO/Participant.php'; $ids = array($participantId); $updateStatusId = array_search('Pending from waitlist', $pendingStatuses); //lets take a call to make pending or need approval if ($values['requires_approval']) { $updateStatusId = array_search('Awaiting approval', $waitingStatuses); } $results = CRM_Event_BAO_Participant::transitionParticipants($ids, $updateStatusId, $values['status_id'], TRUE, TRUE); //commit the transaction. $transaction->commit(); if (!empty($results)) { //diaplay updated participants if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) { foreach ($results['updatedParticipantIds'] as $processedId) { if ($values['requires_approval']) { $waitingApprovalCount += 1; echo "<br /><br />- status updated to: Awaiting approval"; echo "<br />Will send you Confirmation Mail when registration get approved."; } else { $waitingConfirmCount += 1; echo "<br /><br />- status updated to: Pending from waitlist"; if (is_array($results['mailedParticipants']) && array_key_exists($processedId, $results['mailedParticipants'])) { echo "<br />Confirmation Mail sent to: {$results['mailedParticipants'][$processedId]}"; } } } } } } else { //target event is full. $fullEvents[$values['event_id']] = $values['eventTitle']; } } else { //target event is full. $fullEvents[$values['event_id']] = $values['eventTitle']; } } } } //cron 2 ends. } echo "<br /><br />Number of Expired registration(s) = {$expiredParticipantCount}"; echo "<br />Number of registration(s) require approval = {$waitingApprovalCount}"; echo "<br />Number of registration changed to Pending from waitlist = {$waitingConfirmCount}<br /><br />"; if (!empty($fullEvents)) { foreach ($fullEvents as $eventId => $title) { echo "Full Event : {$title}<br />"; } } }
/** * Given a participant id/contribution id, * return contribution/fee line items * * @param int $entityId * participant/contribution id. * @param string $entity * participant/contribution. * * @param null $isQuick * @param bool $isQtyZero * @param bool $relatedEntity * * @param string $overrideWhereClause * E.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper. * this function precedes the convenience of the contribution id but since it does quite a bit more than just a db retrieval we need to be able to use it even * when we don't want it's entity-id magix * * @param bool $invoice * @return array * Array of line items */ public static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL, $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '', $invoice = FALSE) { $whereClause = $fromClause = NULL; $selectClause = "\n SELECT li.id,\n li.label,\n li.contribution_id,\n li.qty,\n li.unit_price,\n li.line_total,\n li.entity_table,\n li.entity_id,\n pf.label as field_title,\n pf.html_type,\n pfv.membership_type_id,\n pfv.membership_num_terms,\n li.price_field_id,\n li.participant_count,\n li.price_field_value_id,\n li.financial_type_id,\n li.tax_amount,\n pfv.description"; $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'"; if ($relatedEntity) { $condition = "li.contribution_id = %2.id "; } $fromClause = "\n FROM civicrm_%2 as %2\n LEFT JOIN civicrm_line_item li ON ({$condition})\n LEFT JOIN civicrm_price_field_value pfv ON ( pfv.id = li.price_field_value_id )\n LEFT JOIN civicrm_price_field pf ON (pf.id = li.price_field_id )"; $whereClause = "\n WHERE %2.id = %1"; // CRM-16250 get additional participant's fee selection details only for invoice PDF (if any) if ($entity == 'participant' && $invoice) { $additionalParticipantIDs = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId); if (!empty($additionalParticipantIDs)) { $whereClause = "WHERE %2.id IN (%1, " . implode(', ', $additionalParticipantIDs) . ")"; } } $orderByClause = " ORDER BY pf.weight, pfv.weight"; if ($isQuick) { $fromClause .= " LEFT JOIN civicrm_price_set cps on cps.id = pf.price_set_id "; $whereClause .= " and cps.is_quick_config = 0"; } if (!$isQtyZero) { $whereClause .= " and li.qty != 0"; } $lineItems = array(); if (!$entityId || !$entity || !$fromClause) { return $lineItems; } $params = array(1 => array($entityId, 'Integer'), 2 => array($entity, 'Text')); $getTaxDetails = FALSE; $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); if ($overrideWhereClause) { $whereClause = $overrideWhereClause; } $dao = CRM_Core_DAO::executeQuery("{$selectClause} {$fromClause} {$whereClause} {$orderByClause}", $params); while ($dao->fetch()) { if (!$dao->id) { continue; } $lineItems[$dao->id] = array('qty' => (double) $dao->qty, 'label' => $dao->label, 'unit_price' => $dao->unit_price, 'line_total' => $dao->line_total, 'price_field_id' => $dao->price_field_id, 'participant_count' => $dao->participant_count, 'price_field_value_id' => $dao->price_field_value_id, 'field_title' => $dao->field_title, 'html_type' => $dao->html_type, 'description' => $dao->description, 'entity_id' => empty($overrideWhereClause) ? $entityId : $dao->entity_id, 'entity_table' => $dao->entity_table, 'contribution_id' => $dao->contribution_id, 'financial_type_id' => $dao->financial_type_id, 'membership_type_id' => $dao->membership_type_id, 'membership_num_terms' => $dao->membership_num_terms, 'tax_amount' => $dao->tax_amount); $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]); $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price']; if ($lineItems[$dao->id]['tax_amount'] != '') { $getTaxDetails = TRUE; } } if ($invoicing) { $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings); $smarty = CRM_Core_Smarty::singleton(); $smarty->assign('taxTerm', $taxTerm); $smarty->assign('getTaxDetails', $getTaxDetails); } return $lineItems; }
/** * Create all financial accounts entry. * * @param array $params * Contribution object, line item array and params for trxn. * * * @param array $financialTrxnValues * * @return null|object */ public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) { $skipRecords = $update = $return = $isRelatedId = FALSE; $additionalParticipantId = array(); $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']]; if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') { $entityId = $params['participant_id']; $entityTable = 'civicrm_participant'; $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId); } elseif (!empty($params['membership_id'])) { //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships // are created off one contribution should be handled elsewhere $entityId = $params['membership_id']; $entityTable = 'civicrm_membership'; } else { $entityId = $params['contribution']->id; $entityTable = 'civicrm_contribution'; } if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') { $isRelatedId = TRUE; } $entityID[] = $entityId; if (!empty($additionalParticipantId)) { $entityID += $additionalParticipantId; } // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated if (empty($params['prevContribution'])) { $entityID = NULL; } else { $update = TRUE; } $statusId = $params['contribution']->contribution_status_id; // CRM-13964 partial payment if ($contributionStatus == 'Partially paid' && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) { $partialAmtPay = $params['partial_amount_pay']; $partialAmtTotal = $params['partial_payment_total']; $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); $params['total_amount'] = $partialAmtPay; $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']); if (empty($balanceTrxnInfo['trxn_id'])) { // create new balance transaction record $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); $balanceTrxnParams['total_amount'] = $partialAmtTotal; $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount; $balanceTrxnParams['contribution_id'] = $params['contribution']->id; $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'); $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params); $balanceTrxnParams['currency'] = $params['contribution']->currency; $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id; $balanceTrxnParams['status_id'] = $statusId; $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id; $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params); if (!empty($balanceTrxnParams['from_financial_account_id']) && ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses))) { $balanceTrxnParams['is_payment'] = 1; } if (!empty($params['payment_processor'])) { $balanceTrxnParams['payment_processor_id'] = $params['payment_processor']; } $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams); } } // build line item array if its not set in $params if (empty($params['line_item']) || $additionalParticipantId) { CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId); } if ($contributionStatus != 'Failed' && !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later)) { $skipRecords = TRUE; $pendingStatus = array('Pending', 'In Progress'); if (in_array($contributionStatus, $pendingStatus)) { $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); } elseif (!empty($params['payment_processor'])) { $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id'); } elseif (!empty($params['payment_instrument_id'])) { $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']); } else { $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); $queryParams = array(1 => array($relationTypeId, 'Integer')); $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams); } $totalAmount = CRM_Utils_Array::value('total_amount', $params); if (!isset($totalAmount) && !empty($params['prevContribution'])) { $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount; } //build financial transaction params $trxnParams = array('contribution_id' => $params['contribution']->id, 'to_financial_account_id' => $params['to_financial_account_id'], 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'), 'total_amount' => $totalAmount, 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount), 'currency' => $params['contribution']->currency, 'trxn_id' => $params['contribution']->trxn_id, 'status_id' => $statusId, 'payment_instrument_id' => $params['contribution']->payment_instrument_id, 'check_number' => CRM_Utils_Array::value('check_number', $params)); if ($contributionStatus == 'Refunded') { $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis'); if (isset($params['refund_trxn_id'])) { // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form. $trxnParams['trxn_id'] = $params['refund_trxn_id']; } } //CRM-16259, set is_payment flag for non pending status if (!in_array($contributionStatus, $pendingStatus)) { $trxnParams['is_payment'] = 1; } if (!empty($params['payment_processor'])) { $trxnParams['payment_processor_id'] = $params['payment_processor']; } if (isset($fromFinancialAccountId)) { $trxnParams['from_financial_account_id'] = $fromFinancialAccountId; } // consider external values passed for recording transaction entry if (!empty($financialTrxnValues)) { $trxnParams = array_merge($trxnParams, $financialTrxnValues); } $params['trxnParams'] = $trxnParams; if (!empty($params['prevContribution'])) { $updated = FALSE; $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount; $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount; $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount; if (!isset($params['trxnParams']['trxn_id'])) { // Actually I have no idea why we are overwriting any values from the previous contribution. // (filling makes sense to me). However, only protecting this value as I really really know we // don't want this one overwritten. // CRM-17751. $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id; } $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id; if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses)) && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))) { $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; } //if financial type is changed if (!empty($params['financial_type_id']) && $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id) { $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' ")); $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId); $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId); if ($oldFinancialAccount != $newFinancialAccount) { $params['total_amount'] = 0; if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) { $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $relationTypeId); } else { $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); if (!empty($lastFinancialTrxnId['financialTrxnId'])) { $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); } } self::updateFinancialAccounts($params, 'changeFinancialType'); /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */ $params['financial_account_id'] = $newFinancialAccount; $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params); $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; $updated = TRUE; } } //Update contribution status $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id; if (!isset($params['refund_trxn_id'])) { // CRM-17751 This has previously been deliberately set. No explanation as to why one variant // gets preference over another so I am only 'protecting' a very specific tested flow // and letting natural justice take care of the rest. $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; } if (!empty($params['contribution_status_id']) && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) { //Update Financial Records self::updateFinancialAccounts($params, 'changedStatus'); $updated = TRUE; } // change Payment Instrument for a Completed contribution // first handle special case when contribution is changed from Pending to Completed status when initial payment // instrument is null and now new payment instrument is added along with the payment $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params); if (array_key_exists('payment_instrument_id', $params)) { $params['trxnParams']['total_amount'] = -$trxnParams['total_amount']; if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) && !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)) { //check if status is changed from Pending to Completed // do not update payment instrument changes for Pending to Completed if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) && in_array($params['prevContribution']->contribution_status_id, $pendingStatus))) { // for all other statuses create new financial records self::updateFinancialAccounts($params, 'changePaymentInstrument'); $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params, 'changePaymentInstrument'); $updated = TRUE; } } elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) || !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) && $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id) { // for any other payment instrument changes create new financial records self::updateFinancialAccounts($params, 'changePaymentInstrument'); $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params, 'changePaymentInstrument'); $updated = TRUE; } elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) && $params['contribution']->check_number != $params['prevContribution']->check_number) { // another special case when check number is changed, create new financial records // create financial trxn with negative amount $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; self::updateFinancialAccounts($params, 'changePaymentInstrument'); // create financial trxn with positive amount $params['trxnParams']['check_number'] = $params['contribution']->check_number; $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; self::updateFinancialAccounts($params, 'changePaymentInstrument'); $updated = TRUE; } } //if Change contribution amount $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params); $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount; $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; if (isset($totalAmount) && $totalAmount != $params['prevContribution']->total_amount) { //Update Financial Records $params['trxnParams']['from_financial_account_id'] = NULL; self::updateFinancialAccounts($params, 'changedAmount'); $updated = TRUE; } if (!$updated) { // Looks like we might have a data correction update. // This would be a case where a transaction id has been entered but it is incorrect & // the person goes back in & fixes it, as opposed to a new transaction. // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting // the data fix scenario. // CRM-17751. if (isset($params['refund_trxn_id'])) { $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']); if ($refundIDs['trxn_id'] != $params['refund_trxn_id']) { civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id'])); } } } } if (!$update) { // records finanical trxn and entity financial trxn // also make it available as return value $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); $params['entity_id'] = $financialTxn->id; } } // record line items and financial items if (empty($params['skipLineItem'])) { CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update); } // create batch entry if batch_id is passed and // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611 if (!empty($params['batch_id']) && !empty($financialTxn)) { $entityParams = array('batch_id' => $params['batch_id'], 'entity_table' => 'civicrm_financial_trxn', 'entity_id' => $financialTxn->id); CRM_Batch_BAO_Batch::addBatchEntity($entityParams); } // when a fee is charged if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) { CRM_Core_BAO_FinancialTrxn::recordFees($params); } if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant' && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id) { $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id'); $feeLevel[] = str_replace('', '', $params['prevContribution']->amount_level); CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel); } unset($params['line_item']); return $return; }
/** * Function to process the form * * @access public */ public function postProcess() { // get the submitted form values. $params = $this->controller->exportValues($this->_name); if ($this->_action & CRM_Core_Action::DELETE) { require_once "CRM/Event/BAO/Participant.php"; 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); 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; } else { $status = "Selected Participants was deleted sucessfully."; } CRM_Core_Session::setStatus($status); return; } // set the contact, when contact is selected if (CRM_Utils_Array::value('contact_select_id', $params)) { $this->_contactId = $params['contact_select_id'][1]; } if ($this->_id) { $params['id'] = $this->_id; } $config = CRM_Core_Config::singleton(); if ($this->_isPaidEvent) { $contributionParams = array(); $lineItem = array(); $additionalParticipantDetails = array(); 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'])) { require_once 'CRM/Price/BAO/LineItem.php'; $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 (CRM_Utils_Array::value('discount_id', $params)) { $discountId = $params['discount_id']; } else { $discountId = $params['discount_id'] = 'null'; } //lets carry currency, CRM-4453 $params['fee_currency'] = $config->defaultCurrency; // fix for CRM-3088 if ($discountId && !empty($this->_values['discount'][$discountId])) { $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label']; $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value']; } else { if (!isset($params['priceSetId']) && CRM_Utils_Array::value('amount', $params)) { $params['amount_level'] = $this->_values['fee'][$params['amount']]['label']; $params['amount'] = $this->_values['fee'][$params['amount']]['value']; } else { CRM_Price_BAO_Set::processAmount($this->_values['fee'], $params, $lineItem[0]); } } $params['fee_level'] = $params['amount_level']; $contributionParams['total_amount'] = $params['amount']; //fix for CRM-3086 $params['fee_amount'] = $params['amount']; } if (isset($params['priceSetId'])) { $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 ($participantCount) { $this->assign('pricesetFieldsCount', $participantCount); } $this->assign('lineItem', empty($lineItem[0]) ? false : $lineItem); } else { $this->assign('amount_level', $params['amount_level']); } } $this->_params = $params; 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)); $params['contact_id'] = $this->_contactId; // overwrite actual payment amount if entered if (CRM_Utils_Array::value('total_amount', $params)) { $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params); } require_once 'CRM/Contact/BAO/Contact.php'; // Retrieve the name and email of the current user - this will be the FROM for the receipt email $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); require_once "CRM/Event/BAO/Participant.php"; if ($this->_mode) { if (!$this->_isPaidEvent) { CRM_Core_Error::fatal(ts('Selected Event is not Paid Event ')); } //modify params according to parameter used in create //participant method (addParticipant) $this->_params['participant_status_id'] = $params['status_id']; $this->_params['participant_role_id'] = $params['role_id']; $this->_params['participant_register_date'] = $params['register_date']; $this->_params['participant_source'] = $params['source']; require_once 'CRM/Core/BAO/PaymentProcessor.php'; $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode); require_once "CRM/Contact/BAO/Contact.php"; $now = date('YmdHis'); $fields = array(); // set email for primary location. $fields["email-Primary"] = 1; list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId); $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); } $roleAllIds = CRM_Utils_Array::value('role_id', $params); if ($roleAllIds) { foreach ($roleAllIds as $rkey => $rvalue) { $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, $rkey, $this->_roleCustomDataTypeID); $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, $customFields, $this->_id, 'Participant'); } } if ($this->_mode) { // add all the additioanl 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'] = $this->_params['credit_card_exp_date']['Y']; $this->_params['month'] = $this->_params['credit_card_exp_date']['M']; $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['payment_action'] = 'Sale'; $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 (CRM_Utils_Array::value('send_receipt', $this->_params)) { $paymentParams['email'] = $this->_contributorEmail; } require_once 'CRM/Core/Payment/Form.php'; CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true); $payment =& CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this); $result =& $payment->doDirectPayment($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 (CRM_Utils_Array::value('send_receipt', $this->_params)) { $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'])); // set source if not set $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName)); require_once 'CRM/Event/Form/Registration/Confirm.php'; require_once 'CRM/Event/Form/Registration.php'; //add contribution record $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id'); $this->_params['mode'] = $this->_mode; //add contribution reocord $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false); // add participant record $participants = array(); if (CRM_Utils_Array::value('participant_role_id', $this->_params) && is_array($this->_params['participant_role_id'])) { $this->_params['participant_role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($this->_params['participant_role_id'])); } $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID); //add custom data for participant require_once 'CRM/Core/BAO/CustomValueTable.php'; CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant'); //add participant payment require_once 'CRM/Event/BAO/ParticipantPayment.php'; $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id); $ids = array(); CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids); $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title'); $this->_contactIds[] = $this->_contactId; } else { $participants = array(); // fix note if deleted if (!$params['note']) { $params['note'] = 'null'; } if ($this->_single) { if ($params['role_id']) { foreach ($params['role_id'] as $k => $v) { $rolesIDS[] = $k; } require_once 'CRM/Core/DAO.php'; $seperator = CRM_Core_DAO::VALUE_SEPARATOR; $params['role_id'] = implode($seperator, $rolesIDS); } 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']) { $rolesIDS = array(); foreach ($commonParams['role_id'] as $k => $v) { $rolesIDS[] = $k; } require_once 'CRM/Core/DAO.php'; $seperator = CRM_Core_DAO::VALUE_SEPARATOR; $commonParams['role_id'] = implode($seperator, $rolesIDS); $commonParams['participant_role_id'] = implode($seperator, $rolesIDS); } 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; } if (CRM_Utils_Array::value('record_contribution', $params)) { if (CRM_Utils_Array::value('id', $params)) { 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) { $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})"; } $contributionParams['currency'] = $config->defaultCurrency; $contributionParams['non_deductible_amount'] = 'null'; $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null'; $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number'); foreach ($recordContribution as $f) { $contributionParams[$f] = CRM_Utils_Array::value($f, $params); if ($f == 'trxn_id') { $this->assign('trxn_id', $contributionParams[$f]); } } //insert contribution type name in receipt. $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id'])); require_once 'CRM/Contribute/BAO/Contribution.php'; $contributions = array(); if ($this->_single) { $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 (!$ids['contribution']) { require_once 'CRM/Event/DAO/ParticipantPayment.php'; 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(); } } } } //do cleanup line items if participant edit the Event Fee. if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId) { require_once 'CRM/Price/BAO/LineItem.php'; CRM_Price_BAO_LineItem::deleteLineItems($params['participant_id'], 'civicrm_participant'); } // also store lineitem stuff here if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) { require_once 'CRM/Price/BAO/LineItem.php'; foreach ($this->_contactIds as $num => $contactID) { foreach ($this->_lineItem as $key => $value) { if (is_array($value) && $value != 'skip') { foreach ($value as $line) { $line['entity_table'] = 'civicrm_participant'; $line['entity_id'] = $participants[$num]->id; CRM_Price_BAO_LineItem::create($line); } } } } } $updateStatusMsg = null; //send mail when participant status changed, CRM-4326 if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) { require_once "CRM/Event/BAO/Participant.php"; $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId); } if (CRM_Utils_Array::value('send_receipt', $params)) { $receiptFrom = CRM_Utils_Array::value($params['from_email_address'], $this->_fromEmails['name']); $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(); if (is_array($params['role_id'])) { $selectedRoles = array(); foreach (array_keys($params['role_id']) as $roleId) { $selectedRoles[] = $role[$roleId]; } $event['participant_role'] = implode(', ', $selectedRoles); } else { $event['participant_role'] = $role[$params['role_id']]; } $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'); require_once 'CRM/Core/BAO/Location.php'; $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) { $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument)); } $this->assign('totalAmount', $contributionParams['total_amount']); $this->assign('isPrimary', 1); $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params)); } if ($this->_mode) { if (CRM_Utils_Array::value('billing_first_name', $params)) { $name = $params['billing_first_name']; } if (CRM_Utils_Array::value('billing_middle_name', $params)) { $name .= " {$params['billing_middle_name']}"; } if (CRM_Utils_Array::value('billing_last_name', $params)) { $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]; } } require_once 'CRM/Utils/Address.php'; $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']); $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 (CRM_Utils_Array::value('is_test', $this->_defaultValues)) { $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) { $customValue = array('data' => $fieldValue['value']); $customFields[$fieldID]['id'] = $fieldID; $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID], true); $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace(' ', '', $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; $this->assign('customGroup', $customGroup); $this->assign('contactID', $contactID); $this->assign('participantID', $participants[$num]->id); if ($this->_isPaidEvent) { // fix amount for each of participants ( for bulk mode ) $eventAmount = array(); if (!empty($additionalParticipantDetails)) { $params['amount_level'] = $params['amount_level'] . ' - ' . $this->_contributorDisplayName; } $eventAmount[$num] = array('label' => $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' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues)); // 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); } require_once 'CRM/Core/BAO/MessageTemplates.php'; list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams); if ($mailSent) { $sent[] = $contactID; require_once 'CRM/Activity/BAO/Activity.php'; foreach ($participants as $ids => $values) { CRM_Activity_BAO_Activity::addActivity($values, 'Email'); } } else { $notSent[] = $contactID; } } } if ($this->_action & CRM_Core_Action::UPDATE) { $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName)); if (CRM_Utils_Array::value('send_receipt', $params) && 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 (CRM_Utils_Array::value('send_receipt', $params) && 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'); } } } require_once "CRM/Core/Session.php"; CRM_Core_Session::setStatus("{$statusMsg}"); $buttonName = $this->controller->getButtonName(); if ($this->_context == 'standalone') { if ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone')); } else { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant")); } } else { if ($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}")); } } }
/** * Function to set variables up before form is built * * @return void * @access public */ function preProcess() { $this->_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE); $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE); //CRM-4320 $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this); // 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'); $this->_lineItem = $this->get('lineItem'); $this->_isEventFull = $this->get('isEventFull'); $this->_lineItemParticipantsCount = $this->get('lineItemParticipants'); if (!is_array($this->_lineItem)) { $this->_lineItem = array(); } if (!is_array($this->_lineItemParticipantsCount)) { $this->_lineItemParticipantsCount = array(); } $this->_availableRegistrations = $this->get('availableRegistrations'); $this->_participantIDS = $this->get('participantIDs'); //check if participant allow to walk registration wizard. $this->_allowConfirmation = $this->get('allowConfirmation'); // check for Approval $this->_requireApproval = $this->get('requireApproval'); // check for waitlisting. $this->_allowWaitlist = $this->get('allowWaitlist'); $this->_forcePayement = $this->get('forcePayement'); //get the additional participant ids. $this->_additionalParticipantIds = $this->get('additionalParticipantIds'); $config = CRM_Core_Config::singleton(); if (!$this->_values) { // create redirect URL to send folks back to event info page is registration not available $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}", FALSE, NULL, FALSE, TRUE); // this is the first time we are hitting this, so check for permissions here if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId, 'register for events')) { CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $infoUrl); } // get all the values from the dao object $this->_values = $this->_fields = array(); $this->_forcePayement = FALSE; //retrieve event information $params = array('id' => $this->_eventId); CRM_Event_BAO_Event::retrieve($params, $this->_values['event']); $this->checkValidEvent($infoUrl); // get the participant values, CRM-4320 $this->_allowConfirmation = FALSE; if ($this->_participantId) { $this->processFirstParticipant($this->_participantId); } //check for additional participants. if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) { $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId); $cnt = 1; foreach ($additionalParticipantIds as $additionalParticipantId) { $this->_additionalParticipantIds[$cnt] = $additionalParticipantId; $cnt++; } $this->set('additionalParticipantIds', $this->_additionalParticipantIds); } $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $this->_values['event'])); $this->_allowWaitlist = $this->_isEventFull = FALSE; if ($eventFull && !$this->_allowConfirmation) { $this->_isEventFull = TRUE; //lets redirecting to info only when to waiting list. $this->_allowWaitlist = CRM_Utils_Array::value('has_waitlist', $this->_values['event']); if (!$this->_allowWaitlist) { CRM_Utils_System::redirect($infoUrl); } } $this->set('isEventFull', $this->_isEventFull); $this->set('allowWaitlist', $this->_allowWaitlist); //check for require requires approval. $this->_requireApproval = FALSE; if (!empty($this->_values['event']['requires_approval']) && !$this->_allowConfirmation) { $this->_requireApproval = TRUE; } $this->set('requireApproval', $this->_requireApproval); if (isset($this->_values['event']['default_role_id'])) { $participant_role = CRM_Core_OptionGroup::values('participant_role'); $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"]; } // check for is_monetary status $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']); $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'is_pay_later'); //check for variour combination for paylater, payment //process with paid event. if ($isMonetary && (!$isPayLater || !empty($this->_values['event']['payment_processor']))) { $ppID = CRM_Utils_Array::value('payment_processor', $this->_values['event']); if (!$ppID) { CRM_Core_Error::statusBounce(ts('A payment processor must be selected for this event registration page, or the event must be configured to give users the option to pay later (contact the site administrator for assistance).'), $infoUrl); } $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); } // make sure we have a valid payment class, else abort if ($this->_values['event']['is_monetary']) { if (!CRM_Utils_System::isNull($this->_paymentProcessors)) { foreach ($this->_paymentProcessors as $eachPaymentProcessor) { // check selected payment processor is active if (!$eachPaymentProcessor) { CRM_Core_Error::fatal(ts('The site administrator must set a Payment Processor for this event in order to use online registration.')); } // ensure that processor has a valid config $payment = CRM_Core_Payment::singleton($this->_mode, $eachPaymentProcessor, $this); $error = $payment->checkConfig(); if (!empty($error)) { CRM_Core_Error::fatal($error); } } } } } //init event fee. self::initEventFee($this, $this->_eventId); // get the profile ids $ufJoinParams = array('entity_table' => 'civicrm_event', 'module' => 'CiviEvent', 'entity_id' => $this->_eventId); list($this->_values['custom_pre_id'], $this->_values['custom_post_id']) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); // set profiles for additional participants if ($this->_values['event']['is_multiple_registrations']) { // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants $ufJoinParams['module'] = 'CiviEvent_Additional'; list($this->_values['additional_custom_pre_id'], $this->_values['additional_custom_post_id'], $preActive, $postActive) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact // set same profile for additional contacts. if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) { $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id']; } if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) { $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id']; } // now check for no profile condition, in that case is_active = 0 if (isset($preActive) && !$preActive) { unset($this->_values['additional_custom_pre_id']); } if (isset($postActive) && !$postActive) { unset($this->_values['additional_custom_post_id']); } } // get the billing location type $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); // CRM-8108 remove ts from Billing as the location type can not be translated in CiviCRM! //$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); if ($this->_values['event']['is_monetary'] && $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { CRM_Core_Payment_Form::setCreditCardFields($this); } $params = array('entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event'); $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE); $this->set('values', $this->_values); $this->set('fields', $this->_fields); $this->_availableRegistrations = CRM_Event_BAO_Participant::eventFull($this->_values['event']['id'], TRUE, CRM_Utils_Array::value('has_waitlist', $this->_values['event'])); $this->set('availableRegistrations', $this->_availableRegistrations); } $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor); // check if this is a paypal auto return and redirect accordingly if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) { $url = CRM_Utils_System::url('civicrm/event/register', "_qf_ThankYou_display=1&qfKey={$this->controller->_key}"); CRM_Utils_System::redirect($url); } $this->_contributeMode = $this->get('contributeMode'); $this->assign('contributeMode', $this->_contributeMode); // setting CMS page title CRM_Utils_System::setTitle($this->_values['event']['title']); $this->assign('title', $this->_values['event']['title']); $this->assign('paidEvent', $this->_values['event']['is_monetary']); // we do not want to display recently viewed items on Registration pages $this->assign('displayRecent', FALSE); // Registration page values are cleared from session, so can't use normal Printer Friendly view. // Use Browser Print instead. $this->assign('browserPrint', TRUE); $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']); $this->assign('isShowLocation', $isShowLocation); // Handle PCP $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this); if ($pcpId) { $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'event', $this->_values['event']); $this->_pcpId = $pcp['pcpId']; $this->_values['event']['intro_text'] = CRM_Utils_Array::value('intro_text', $pcp['pcpInfo']); } // assign all event properties so wizard templates can display event info. $this->assign('event', $this->_values['event']); $this->assign('location', $this->_values['location']); $this->assign('bltID', $this->_bltID); $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']); $this->assign('isShowLocation', $isShowLocation); //CRM-6907 $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values['event'], $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['event']['campaign_id'] = $campID; } }
/** * Process the form after the input has been submitted and validated. * * * @return void */ public function postProcess() { $params = $this->controller->exportValues($this->_name); $participantLinks = NULL; if (CRM_Utils_Array::value('delete_participant', $params) == 2) { $links = array(); foreach ($this->_participantIds as $participantId) { $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId); $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId); } } $deletedParticipants = $additionalCount = 0; foreach ($this->_participantIds as $participantId) { if (CRM_Utils_Array::value('delete_participant', $params) == 1) { $primaryParticipantId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'registered_by_id', 'id'); if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantId)) { $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId); $additionalCount += count($additionalIds); foreach ($additionalIds as $value) { CRM_Event_BAO_Participant::deleteParticipant($value); } CRM_Event_BAO_Participant::deleteParticipant($participantId); $deletedParticipants++; } elseif (empty($primaryParticipantId) || !in_array($primaryParticipantId, $this->_participantIds)) { CRM_Event_BAO_Participant::deleteParticipant($participantId); $deletedParticipants++; } } else { CRM_Event_BAO_Participant::deleteParticipant($participantId); $deletedParticipants++; } } if ($additionalCount) { $deletedParticipants += $additionalCount; } $status = ts('%count participant deleted.', array('plural' => '%count participants deleted.', 'count' => $deletedParticipants)); if ($participantLinks) { $status .= '<p>' . 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:') . '</p>' . $participantLinks; } CRM_Core_Session::setStatus($status, ts('Removed'), 'info'); }
/** * Function to set variables up before form is built * * @return void * @access public */ function preProcess() { $this->_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, true); $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, false); //CRM-4320 $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this); // 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'); //check if participant allow to walk registration wizard. $this->_allowConfirmation = $this->get('allowConfirmation'); // check for Approval $this->_requireApproval = $this->get('requireApproval'); // check for waitlisting. $this->_allowWaitlist = $this->get('allowWaitlist'); //get the additional participant ids. $this->_additionalParticipantIds = $this->get('additionalParticipantIds'); $config =& CRM_Core_Config::singleton(); if (!$this->_values) { // create redirect URL to send folks back to event info page is registration not available $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}", false, null, false, true); // this is the first time we are hitting this, so check for permissions here if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId)) { CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $infoUrl); } // get all the values from the dao object $this->_values = array(); $this->_fields = array(); // get the participant values, CRM-4320 $this->_allowConfirmation = false; if ($this->_participantId) { require_once 'CRM/Event/BAO/Event.php'; $ids = $participantValues = array(); $participantParams = array('id' => $this->_participantId); require_once 'CRM/Event/BAO/Participant.php'; CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids); $this->_values['participant'] = $participantValues[$this->_participantId]; //allow pending status class walk registration wizard. require_once 'CRM/Core/PseudoConstant.php'; if (array_key_exists($participantValues[$this->_participantId]['status_id'], CRM_Event_PseudoConstant::participantStatus(null, "class = 'Pending'"))) { $this->_allowConfirmation = true; $this->set('allowConfirmation', true); } } //retrieve event information require_once 'CRM/Event/BAO/Event.php'; $params = array('id' => $this->_eventId); CRM_Event_BAO_Event::retrieve($params, $this->_values['event']); require_once 'CRM/Event/BAO/Participant.php'; //check for additional participants. if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) { $this->_additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId); $this->set('additionalParticipantIds', $this->_additionalParticipantIds); } $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId); $this->_allowWaitlist = false; if ($eventFull && !$this->_allowConfirmation) { //lets redirecting to info only when to waiting list. $this->_allowWaitlist = CRM_Utils_Array::value('has_waitlist', $this->_values['event']); if (!$this->_allowWaitlist) { CRM_Utils_System::redirect($infoUrl); } } $this->set('allowWaitlist', $this->_allowWaitlist); //check for require requires approval. $this->_requireApproval = false; if (CRM_Utils_Array::value('requires_approval', $this->_values['event']) && !$this->_allowConfirmation) { $this->_requireApproval = true; } $this->set('requireApproval', $this->_requireApproval); // also get the accounting code if (CRM_Utils_Array::value('contribution_type_id', $this->_values['event'])) { $this->_values['event']['accountingCode'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $this->_values['event']['contribution_type_id'], 'accounting_code'); } if (isset($this->_values['event']['default_role_id'])) { require_once 'CRM/Core/OptionGroup.php'; $participant_role = CRM_Core_OptionGroup::values('participant_role'); $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"]; } // is the event active (enabled)? if (!$this->_values['event']['is_active']) { // form is inactive, die a fatal death CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).')); } // is online registration is enabled? if (!$this->_values['event']['is_online_registration']) { CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $infoUrl); } // is this an event template ? if (CRM_Utils_Array::value('is_template', $this->_values['event'])) { CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $infoUrl); } $now = date('YmdHis'); $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])); if ($startDate && $startDate >= $now) { CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $infoUrl); } $endDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date', $this->_values['event'])); if ($endDate && $endDate < $now) { CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event'])))), $infoUrl); } // check for is_monetary status $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']); //retrieve custom information $eventID = $this->_eventId; $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'is_pay_later'); //check for variour combination for paylater, payment //process with paid event. if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor_id', $this->_values['event']))) { $ppID = CRM_Utils_Array::value('payment_processor_id', $this->_values['event']); if (!$ppID) { CRM_Core_Error::statusBounce(ts('A payment processor must be selected for this event registration page, or the event must be configured to give users the option to pay later (contact the site administrator for assistance).'), $infoUrl); } require_once 'CRM/Core/BAO/PaymentProcessor.php'; $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $this->_mode); // make sure we have a valid payment class, else abort if ($this->_values['event']['is_monetary']) { if (!$this->_paymentProcessor) { CRM_Core_Error::fatal(ts('The site administrator must set a Payment Processor for this event in order to use online registration.')); } // ensure that processor has a valid config $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this); $error = $payment->checkConfig(); if (!empty($error)) { CRM_Core_Error::fatal($error); } } $this->_paymentProcessor['processorName'] = $payment->_processorName; $this->set('paymentProcessor', $this->_paymentProcessor); } // get price info $price = self::initPriceSet($this, $eventID); if ($price == false) { if (!isset($this->_values['fee'])) { $this->_values['fee'] = array(); } require_once 'CRM/Core/OptionGroup.php'; CRM_Core_OptionGroup::getAssoc("civicrm_event.amount.{$eventID}", $this->_values['fee'], true); //fix for non-upgraded price sets.CRM-4256. if ($isMonetary && empty($this->_values['fee'])) { 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', 'reset=1&action=update&subPage=Fee&id=' . $this->_eventId)))); } } // get the profile ids require_once 'CRM/Core/BAO/UFJoin.php'; $ufJoinParams = array('entity_table' => 'civicrm_event', 'module' => 'CiviEvent', 'entity_id' => $this->_eventId); list($this->_values['custom_pre_id'], $this->_values['custom_post_id']) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); // set profiles for additional participants if ($this->_values['event']['is_multiple_registrations']) { require_once 'CRM/Core/BAO/UFJoin.php'; $ufJoinParams = array('entity_table' => 'civicrm_event', 'module' => 'CiviEvent_Additional', 'entity_id' => $this->_eventId); list($this->_values['additional_custom_pre_id'], $this->_values['additional_custom_post_id'], $preActive, $postActive) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact // set same profile for additional contacts. if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) { $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id']; } if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) { $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id']; } // now check for no profile condition, in that case is_active = 0 if (isset($preActive) && !$preActive) { unset($this->_values['additional_custom_pre_id']); } if (isset($postActive) && !$postActive) { unset($this->_values['additional_custom_post_id']); } } $params = array('id' => $this->_eventId); // get the billing location type $locationTypes =& CRM_Core_PseudoConstant::locationType(); $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); if ($this->_values['event']['is_monetary'] && $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { require_once 'CRM/Core/Payment/Form.php'; CRM_Core_Payment_Form::setCreditCardFields($this); } $params = array('entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event'); require_once 'CRM/Core/BAO/Location.php'; $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, true); $this->set('values', $this->_values); $this->set('fields', $this->_fields); } $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor); // check if this is a paypal auto return and redirect accordingly if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) { $url = CRM_Utils_System::url('civicrm/event/register', "_qf_ThankYou_display=1&qfKey={$this->controller->_key}"); CRM_Utils_System::redirect($url); } $this->_contributeMode = $this->get('contributeMode'); $this->assign('contributeMode', $this->_contributeMode); // setting CMS page title CRM_Utils_System::setTitle($this->_values['event']['title']); $this->assign('title', $this->_values['event']['title']); $this->assign('paidEvent', $this->_values['event']['is_monetary']); // we do not want to display recently viewed items on Registration pages $this->assign('displayRecent', false); // Registration page values are cleared from session, so can't use normal Printer Friendly view. // Use Browser Print instead. $this->assign('browserPrint', true); // assign all event properties so wizard templates can display event info. $this->assign('event', $this->_values['event']); $this->assign('location', $this->_values['location']); $this->assign('bltID', $this->_bltID); $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']); $this->assign('isShowLocation', $isShowLocation); }