/**
  * Set default values.
  *
  * @return array
  */
 public function setDefaultValues()
 {
     $defaults = $period = array();
     $period = Civi::settings()->get('closing_date');
     if (empty($period)) {
         $prior = CRM_Contribute_BAO_Contribution::checkContributeSettings('prior_financial_period');
     } else {
         $defaults['closing_date'] = $period;
         return $defaults;
     }
     if (!empty($prior)) {
         $period = array('M' => date('n', strtotime($prior)), 'd' => date('j', strtotime($prior)));
         if ($period['M'] == 1) {
             $period['M'] = 12;
         } else {
             $period['M']--;
         }
         $defaults['closing_date'] = $period;
     } else {
         $defaults['closing_date'] = array('M' => date('n', strtotime("-1 month")), 'd' => date('j'));
     }
     return $defaults;
 }
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Beispiel #3
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     // FIXME: This probably needs to be done in preprocess
     if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && $this->_action & CRM_Core_Action::UPDATE && CRM_Utils_Array::value('financial_type_id', $this->_values)) {
         $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
         CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
         if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
             CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
         }
     }
     $allPanes = array();
     $recurJs = NULL;
     //tax rate from financialType
     $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
     $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
     // build price set form.
     $buildPriceSet = FALSE;
     $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
     $this->assign('invoicing', $invoicing);
     // display tax amount on edit contribution page
     if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
         $this->assign('totalTaxAmount', $this->_values['tax_amount']);
     }
     if (empty($this->_lineItems) && ($this->_priceSetId || !empty($_POST['price_set_id']))) {
         $buildPriceSet = TRUE;
         $getOnlyPriceSetElements = TRUE;
         if (!$this->_priceSetId) {
             $this->_priceSetId = $_POST['price_set_id'];
             $getOnlyPriceSetElements = FALSE;
         }
         $this->set('priceSetId', $this->_priceSetId);
         CRM_Price_BAO_PriceSet::buildPriceSet($this);
         // get only price set form elements.
         if ($getOnlyPriceSetElements) {
             return;
         }
     }
     // use to build form during form rule.
     $this->assign('buildPriceSet', $buildPriceSet);
     $defaults = $this->_values;
     $additionalDetailFields = array('note', 'thankyou_date', 'invoice_id', 'non_deductible_amount', 'fee_amount', 'net_amount');
     foreach ($additionalDetailFields as $key) {
         if (!empty($defaults[$key])) {
             $defaults['hidden_AdditionalDetail'] = 1;
             break;
         }
     }
     if ($this->_productDAO) {
         if ($this->_productDAO->product_id) {
             $defaults['hidden_Premium'] = 1;
         }
     }
     if ($this->_noteID && isset($this->_values['note'])) {
         $defaults['hidden_AdditionalDetail'] = 1;
     }
     $paneNames = array();
     if (empty($this->_payNow)) {
         $paneNames[ts('Additional Details')] = 'AdditionalDetail';
     }
     //Add Premium pane only if Premium is exists.
     $dao = new CRM_Contribute_DAO_Product();
     $dao->is_active = 1;
     if ($dao->find(TRUE) && empty($this->_payNow)) {
         $paneNames[ts('Premium Information')] = 'Premium';
     }
     if ($this->_mode) {
         if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE) == TRUE) {
             if (!empty($this->_recurPaymentProcessors)) {
                 $buildRecurBlock = TRUE;
                 if ($this->_ppID) {
                     // ppID denotes a pledge payment.
                     foreach ($this->_paymentProcessors as $processor) {
                         if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
                             $buildRecurBlock = TRUE;
                             break;
                         }
                         $buildRecurBlock = FALSE;
                     }
                 }
                 if ($buildRecurBlock) {
                     CRM_Contribute_Form_Contribution_Main::buildRecur($this);
                     $this->setDefaults(array('is_recur' => 0));
                     $this->assign('buildRecurBlock', TRUE);
                     $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
                 }
             }
         }
     }
     foreach ($paneNames as $name => $type) {
         $allPanes[$name] = $this->generatePane($type, $defaults);
     }
     $qfKey = $this->controller->_key;
     $this->assign('qfKey', $qfKey);
     $this->assign('allPanes', $allPanes);
     $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
     if ($this->_formType) {
         $this->assign('formType', $this->_formType);
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     //need to assign custom data type and subtype to the template
     $this->assign('customDataType', 'Contribution');
     $this->assign('customDataSubType', $this->_contributionType);
     $this->assign('entityID', $this->_id);
     if ($this->_context == 'standalone') {
         $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
     }
     $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
     // Check permissions for financial type first
     CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
     if (empty($financialTypes)) {
         CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
     }
     $financialType = $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + $financialTypes, TRUE, array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );"));
     $paymentInstrument = FALSE;
     if (!$this->_mode) {
         $paymentInstrument = $this->add('select', 'payment_instrument_id', ts('Payment Method'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"));
     }
     $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
     //add receipt for offline contribution
     $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
     $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
     $status = CRM_Contribute_PseudoConstant::contributionStatus();
     // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
     $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     if ($this->_ppID) {
         foreach (array('Cancelled', 'Failed', 'In Progress') as $suppress) {
             unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
         }
     } elseif (!$this->_ppID && $this->_id || !$this->_id) {
         $suppressFlag = FALSE;
         if ($this->_id) {
             $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
                 $suppressFlag = TRUE;
             }
         }
         if (!$suppressFlag) {
             foreach (array('Overdue', 'In Progress') as $suppress) {
                 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
             }
         } else {
             unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
         }
     }
     // define the status IDs that show the cancellation info, see CRM-17589
     $cancelInfo_show_ids = array();
     foreach (array_keys($statusName) as $status_id) {
         if (CRM_Contribute_BAO_Contribution::isContributionStatusNegative($status_id)) {
             $cancelInfo_show_ids[] = "'{$status_id}'";
         }
     }
     $this->assign('cancelInfo_show_ids', implode(',', $cancelInfo_show_ids));
     if ($this->_id) {
         $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
         $name = CRM_Utils_Array::value($contributionStatus, $statusName);
         switch ($name) {
             case 'Completed':
                 // [CRM-17498] Removing unsupported status change options.
                 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
                 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
                 unset($status[CRM_Utils_Array::key('Partially paid', $statusName)]);
                 unset($status[CRM_Utils_Array::key('Pending refund', $statusName)]);
             case 'Cancelled':
             case 'Chargeback':
             case 'Refunded':
                 unset($status[CRM_Utils_Array::key('In Progress', $statusName)]);
                 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
                 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
                 break;
             case 'Pending':
             case 'In Progress':
                 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
                 unset($status[CRM_Utils_Array::key('Chargeback', $statusName)]);
                 break;
             case 'Failed':
                 foreach (array('Pending', 'Refunded', 'Chargeback', 'Completed', 'In Progress', 'Cancelled') as $suppress) {
                     unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
                 }
                 break;
         }
     } else {
         unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
         unset($status[CRM_Utils_Array::key('Chargeback', $statusName)]);
     }
     $statusElement = $this->add('select', 'contribution_status_id', ts('Contribution Status'), $status, FALSE);
     $currencyFreeze = FALSE;
     if (!empty($this->_payNow) && $this->_action & CRM_Core_Action::UPDATE) {
         $statusElement->freeze();
         $currencyFreeze = TRUE;
         $attributes['total_amount']['readonly'] = TRUE;
     }
     // CRM-16189, add Revenue Recognition Date
     if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
         $revenueDate = $this->add('date', 'revenue_recognition_date', ts('Revenue Recognition Date'), CRM_Core_SelectValues::date(NULL, 'M Y', NULL, 5));
         if ($this->_id && !CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($this->_id)) {
             $revenueDate->freeze();
         }
     }
     // add various dates
     $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
     if ($this->_online) {
         $this->assign('hideCalender', TRUE);
     }
     $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
     $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
     $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
     $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
     $this->add('text', 'refund_trxn_id', ts('Transaction ID for the refund payment'));
     $element = $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL, $recurJs);
     if ($this->_online) {
         $element->freeze();
     }
     $totalAmount = NULL;
     if (empty($this->_lineItems)) {
         $buildPriceSet = FALSE;
         $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
         if (!empty($priceSets) && !$this->_ppID) {
             $buildPriceSet = TRUE;
         }
         // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
         // and if we already have line items for that participant. CRM-5095
         if ($buildPriceSet && $this->_id) {
             $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
             $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_id, 'id', 'contribution_id');
             if ($pledgePaymentId) {
                 $buildPriceSet = FALSE;
             }
             if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
                 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
                 if (!CRM_Utils_System::isNull($participantLI)) {
                     $buildPriceSet = FALSE;
                 }
             }
         }
         $hasPriceSets = FALSE;
         if ($buildPriceSet) {
             $hasPriceSets = TRUE;
             // CRM-16451: set financial type of 'Price Set' in back office contribution
             // instead of selecting manually
             $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
             $element = $this->add('select', 'price_set_id', ts('Choose price set'), array('' => ts('Choose price set')) + $priceSets, NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");"));
             if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
                 $element->freeze();
             }
         }
         $this->assign('hasPriceSets', $hasPriceSets);
         if (!($this->_action & CRM_Core_Action::UPDATE)) {
             if ($this->_online || $this->_ppID) {
                 $attributes['total_amount'] = array_merge($attributes['total_amount'], array('READONLY' => TRUE, 'style' => "background-color:#EBECE4"));
                 $optionTypes = array('1' => ts('Adjust Pledge Payment Schedule?'), '2' => ts('Adjust Total Pledge Amount?'));
                 $this->addRadio('option_type', NULL, $optionTypes, array(), '<br/>');
                 $currencyFreeze = TRUE;
             }
         }
         $totalAmount = $this->addMoney('total_amount', ts('Total Amount'), $hasPriceSets ? FALSE : TRUE, $attributes['total_amount'], TRUE, 'currency', NULL, $currencyFreeze);
     }
     $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
     // CRM-7362 --add campaigns.
     CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
     if (empty($this->_payNow)) {
         CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
     }
     $js = NULL;
     if (!$this->_mode) {
         $js = array('onclick' => "return verify( );");
     }
     $mailingInfo = Civi::settings()->get('mailing_backend');
     $this->assign('outBound_option', $mailingInfo['outBound_option']);
     $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save'), 'js' => $js, 'isDefault' => TRUE), array('type' => 'upload', 'name' => ts('Save and New'), 'js' => $js, 'subName' => 'new'), array('type' => 'cancel', 'name' => ts('Cancel'))));
     // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
     // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
     if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
         if ($totalAmount) {
             $totalAmount->freeze();
         }
         $checkNumber->freeze();
         $paymentInstrument->freeze();
         $trxnId->freeze();
         $financialType->freeze();
     }
     // if contribution is related to membership or participant freeze Financial Type, Amount
     if ($this->_id && isset($this->_values['tax_amount'])) {
         $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
         if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
             if ($totalAmount) {
                 $totalAmount->freeze();
             }
             $financialType->freeze();
             $this->assign('freezeFinancialType', TRUE);
         }
     }
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->freeze();
     }
 }
Beispiel #4
0
 /**
  * Process the contribution.
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param array $result
  * @param int $contactID
  * @param bool $pending
  * @param bool $isAdditionalAmount
  *
  * @return \CRM_Contribute_BAO_Contribution
  */
 public static function processContribution(&$form, $params, $result, $contactID, $pending = FALSE, $isAdditionalAmount = FALSE)
 {
     $transaction = new CRM_Core_Transaction();
     $now = date('YmdHis');
     $receiptDate = NULL;
     if (!empty($form->_values['event']['is_email_confirm'])) {
         $receiptDate = $now;
     }
     //CRM-4196
     if ($isAdditionalAmount) {
         $params['amount_level'] = $params['amount_level'] . ts(' (multiple participants)') . CRM_Core_DAO::VALUE_SEPARATOR;
     }
     $contribParams = array('contact_id' => $contactID, 'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'], 'receive_date' => $now, 'total_amount' => $params['amount'], 'tax_amount' => $params['tax_amount'], 'amount_level' => $params['amount_level'], 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !empty($params['participant_source']) ? $params['participant_source'] : $params['description'], 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params));
     if (empty($params['is_pay_later'])) {
         $contribParams['payment_instrument_id'] = 1;
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate);
     }
     $allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $contribParams['contribution_status_id'] = array_search('Completed', $allStatuses);
     if ($pending) {
         $contribParams['contribution_status_id'] = array_search('Pending', $allStatuses);
     }
     $contribParams['is_test'] = 0;
     if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
         $contribParams['is_test'] = 1;
     }
     $contribID = NULL;
     if (!empty($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
     }
     $ids = array();
     if ($contribID) {
         $ids['contribution'] = $contribID;
         $contribParams['id'] = $contribID;
     }
     if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
         $eventStartDate = CRM_Utils_Array::value('start_date', CRM_Utils_Array::value('event', $form->_values));
         if ($eventStartDate) {
             $contribParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
         }
     }
     //create an contribution address
     // The concept of contributeMode is deprecated. Elsewhere we use the function processBillingAddress() - although
     // currently that is only inherited by back-office forms.
     if ($form->_contributeMode != 'notify' && empty($params['is_pay_later'])) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     $contribParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $params);
     $contribParams['skipLineItem'] = 1;
     // create contribution record
     $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
     // CRM-11124
     CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($params));
     // process soft credit / pcp pages
     if (!empty($params['pcp_made_through_id'])) {
         CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
         CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
     }
     $transaction->commit();
     return $contribution;
 }
Beispiel #5
0
 /**
  * Set default values for the form.
  *
  * default values are retrieved from the database
  */
 public function setDefaultValues()
 {
     $defaults = Civi::settings()->get('contribution_invoice_settings');
     //CRM-16691: Changes made related to settings of 'CVV'.
     foreach (array('cvv_backoffice_required') as $setting) {
         $settingMetaData = civicrm_api3('setting', 'getfields', array('name' => $setting));
         $defaults[$setting] = civicrm_api3('setting', 'getvalue', array('name' => $setting, 'group' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'default_value' => CRM_Utils_Array::value('default', $settingMetaData['values'][$setting])));
     }
     $defaults['fiscalYearStart'] = Civi::settings()->get('fiscalYearStart');
     $period = CRM_Contribute_BAO_Contribution::checkContributeSettings('prior_financial_period');
     $this->assign('priorFinancialPeriod', $period);
     return $defaults;
 }
 /**
  * Check if financial type has Deferred Revenue Account is relationship
  * with Financial Account.
  *
  * @param int $financialTypeId
  *   Financial Type Id.
  *
  * @param int $entityID
  *   Holds id for PriceSet/PriceField/PriceFieldValue.
  *
  * @param string $entity
  *   Entity like PriceSet/PriceField/PriceFieldValue.
  *
  * @return bool
  *
  */
 public static function validateFinancialType($financialTypeId, $entityID = NULL, $entity = NULL)
 {
     if (!CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
         return FALSE;
     }
     if ($entityID) {
         $query = ' SELECT ps.extends FROM civicrm_price_set ps';
         $params = array(1 => array('ps', 'Text'), 2 => array($entityID, 'Integer'));
         if ($entity == 'PriceField') {
             $params[1] = array('pf', 'Text');
             $query .= ' INNER JOIN civicrm_price_field pf ON pf.price_set_id = ps.id ';
         }
         $query .= ' WHERE %1.id = %2';
         $extends = CRM_Core_DAO::singleValueQuery($query, $params);
         $extends = explode('', $extends);
         if (!(in_array(CRM_Core_Component::getComponentID('CiviEvent'), $extends) || in_array(CRM_Core_Component::getComponentID('CiviMember'), $extends))) {
             return FALSE;
         }
     }
     $deferredFinancialType = self::getDeferredFinancialType();
     if (!array_key_exists($financialTypeId, $deferredFinancialType)) {
         throw new CRM_Core_Exception(ts('Deferred revenue account is not configured for selected financial type. Please have an administrator set up the deferred revenue account at Administer > CiviContribute > Financial Accounts, then configure it for financial types at Administer > CiviContribution > Financial Types, Accounts'));
     }
     return FALSE;
 }
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     $this->setPageTitle(ts('Financial Account'));
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     $attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialAccount');
     $this->add('text', 'name', ts('Name'), $attributes['name'], TRUE);
     $this->addRule('name', ts('A financial type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Financial_DAO_FinancialAccount', $this->_id));
     $this->add('text', 'description', ts('Description'), $attributes['description']);
     $this->add('text', 'accounting_code', ts('Accounting Code'), $attributes['accounting_code']);
     $elementAccounting = $this->add('text', 'account_type_code', ts('Account Type Code'), $attributes['account_type_code']);
     $this->addEntityRef('contact_id', ts('Owner'), array('api' => array('params' => array('contact_type' => 'Organization')), 'create' => TRUE));
     $this->add('text', 'tax_rate', ts('Tax Rate'), $attributes['tax_rate']);
     $this->add('checkbox', 'is_deductible', ts('Tax-Deductible?'));
     $elementActive = $this->add('checkbox', 'is_active', ts('Enabled?'));
     $this->add('checkbox', 'is_tax', ts('Is Tax?'));
     $element = $this->add('checkbox', 'is_default', ts('Default?'));
     // CRM-12470 freeze is default if is_default is set
     if ($this->_id && CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $this->_id, 'is_default')) {
         $element->freeze();
     }
     //CRM-16189
     if (CRM_Contribute_BAO_Contribution::checkContributeSettings('financial_account_bal_enable')) {
         $this->add('text', 'opening_balance', ts('Opening Balance'), $attributes['opening_balance']);
         $this->add('text', 'current_period_opening_balance', ts('Current Period Opening Balance'), $attributes['current_period_opening_balance']);
         $financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', array('labelColumn' => 'name'));
         $limitedAccount = array(array_search('Asset', $financialAccountType), array_search('Liability', $financialAccountType));
         $this->assign('limitedAccount', json_encode($limitedAccount));
     }
     $financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id');
     if (!empty($financialAccountType)) {
         $element = $this->add('select', 'financial_account_type_id', ts('Financial Account Type'), array('' => '- select -') + $financialAccountType, TRUE, array('class' => 'crm-select2 huge'));
         if ($this->_isARFlag) {
             $element->freeze();
             $elementAccounting->freeze();
             $elementActive->freeze();
         } elseif ($this->_id && CRM_Financial_BAO_FinancialAccount::validateFinancialAccount($this->_id)) {
             $element->freeze();
         }
     }
     if ($this->_action == CRM_Core_Action::UPDATE && CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $this->_id, 'is_reserved')) {
         $this->freeze(array('name', 'description', 'is_active'));
     }
     $this->addFormRule(array('CRM_Financial_Form_FinancialAccount', 'formRule'), $this);
 }
 public function testStandaloneContributeAdd()
 {
     $this->webtestLogin();
     // Create a contact to be used as soft creditor
     $softCreditFname = substr(sha1(rand()), 0, 7);
     $softCreditLname = substr(sha1(rand()), 0, 7);
     $this->webtestAddContact($softCreditFname, $softCreditLname, FALSE);
     //financial account for check
     $this->openCiviPage("admin/options/payment_instrument", "reset=1");
     $financialAccount = $this->getText("xpath=//div[@id='payment_instrument']/table/tbody//tr/td[1]/div[text()='Check']/../../td[3]");
     // Add new Financial Account
     $orgName = 'Alberta ' . substr(sha1(rand()), 0, 7);
     $financialAccountTitle = 'Financial Account ' . substr(sha1(rand()), 0, 4);
     $financialAccountDescription = "{$financialAccountTitle} Description";
     $accountingCode = 1033;
     $financialAccountType = 'Asset';
     $taxDeductible = FALSE;
     $isActive = FALSE;
     $isTax = TRUE;
     $taxRate = 9;
     $isDefault = FALSE;
     //Add new organisation
     if ($orgName) {
         $this->webtestAddOrganization($orgName);
     }
     $this->_testAddFinancialAccount($financialAccountTitle, $financialAccountDescription, $accountingCode, $orgName, $financialAccountType, $taxDeductible, $isActive, $isTax, $taxRate, $isDefault);
     $firstName = 'John' . substr(sha1(rand()), 0, 7);
     $lastName = 'Dsouza' . substr(sha1(rand()), 0, 7);
     $this->webtestAddContact($firstName, $lastName);
     $this->waitForElementPresent("css=li#tab_contribute a");
     $this->click("css=li#tab_contribute a");
     $this->waitForElementPresent("link=Record Contribution (Check, Cash, EFT ...)");
     $this->clickLink("link=Record Contribution (Check, Cash, EFT ...)", "_qf_Contribution_cancel-bottom", FALSE);
     // select financial type
     $this->select("financial_type_id", "value=1");
     // fill in Received Date
     $this->webtestFillDate('receive_date');
     // source
     $this->type("source", "Mailer 1");
     // total amount
     $this->type("total_amount", "100");
     // revenue recognition date (CRM-16189)
     if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
         $this->webtestFillDate('revenue_recognition_date', 'now+4');
     }
     // select payment instrument type = Check and enter chk number
     $this->select("payment_instrument_id", "value=4");
     $this->waitForElementPresent("check_number");
     $this->type("check_number", "check #1041");
     $this->type("trxn_id", "P20901X1" . rand(100, 10000));
     // create first soft credit
     $this->click("softCredit");
     $this->waitForElementPresent("soft_credit_amount_1");
     $this->webtestFillAutocomplete("{$softCreditLname}, {$softCreditFname}", 's2id_soft_credit_contact_id_1');
     $this->type("soft_credit_amount_1", "50");
     // add second soft credit field
     $this->click("addMoreSoftCredit");
     $this->waitForElementPresent("soft_credit_amount_2");
     // create new individual via soft credit
     $softCreditSecondFname = substr(sha1(rand()), 0, 7);
     $softCreditSecondLname = substr(sha1(rand()), 0, 7);
     $this->webtestNewDialogContact($softCreditSecondFname, $softCreditSecondLname, NULL, 4, 's2id_soft_credit_contact_id_2', 'soft_credit_1');
     // enter the second soft credit
     $this->verifyText("soft_credit_amount_2", "");
     // it should be blank cause first soft credit != total_amount
     $this->type("soft_credit_amount_2", "100");
     //the sum of the soft credit amounts can exceed total_amount
     $this->select("soft_credit_type[2]", "In Honor of");
     //Custom Data
     // $this->click('CIVICRM_QFID_3_6');
     //Additional Detail section
     $this->click("AdditionalDetail");
     $this->waitForElementPresent("thankyou_date");
     $this->type("note", "This is a test note.");
     $this->type("non_deductible_amount", "10.00");
     $this->type("fee_amount", "0");
     $this->type("net_amount", "0");
     $this->type("invoice_id", time());
     $this->webtestFillDate('thankyou_date');
     //Premium section
     $this->click("Premium");
     $this->waitForElementPresent("fulfilled_date");
     $this->select("product_name[0]", "label=Coffee Mug ( MUG-101 )");
     $this->select("product_name[1]", "label=Black");
     $this->webtestFillDate('fulfilled_date');
     // Clicking save.
     $this->click("_qf_Contribution_upload");
     // Is status message correct?
     //$this->assertTrue($this->isTextPresent("The contribution record has been saved."), "Status message didn't show up after saving!");
     // verify if Contribution is created
     $this->waitForElementPresent("xpath=//div[@class='view-content']//table[@class='selector row-highlight']//tbody/tr[1]/td[8]/span/a[text()='View']");
     //click through to the Contribution view screen
     $this->click("xpath=//div[@class='view-content']//table[@class='selector row-highlight']//tbody/tr[1]/td[8]/span/a[text()='View']");
     $this->waitForElementPresent("_qf_ContributionView_cancel-bottom");
     $expected = array('Financial Type' => 'Donation', 'Total Amount' => '100.00', 'Contribution Status' => 'Completed', 'Payment Method' => 'Check', 'Check Number' => 'check #1041', 'Non-deductible Amount' => '10.00', 'Received Into' => $financialAccount);
     $this->waitForElementPresent("xpath=//*[@id='ContributionView']/div[2]");
     foreach ($expected as $value) {
         $this->assertElementContainsText("xpath=//*[@id='ContributionView']/div[2]", $value);
     }
     // verify if soft credit was created successfully
     $expected = array('Soft Credit To 1' => "{$softCreditFname} {$softCreditLname}", 'Soft Credit To 2' => "{$softCreditSecondFname} {$softCreditSecondLname}", 'Amount (Soft Credit Type)' => '100.00 (In Honor of)');
     foreach ($expected as $value) {
         $this->assertElementContainsText("css=table.crm-soft-credit-listing", $value);
     }
     // go to first soft creditor contact view page
     $this->clickLink("xpath=//*[@id='ContributionView']/div[2]/div[2]/div[2]/table/tbody/tr[1]/td[1]/a", "css=li#tab_contribute a");
     // go to contribution tab
     $this->click("css=li#tab_contribute a");
     $this->waitForElementPresent("link=Record Contribution (Check, Cash, EFT ...)");
     // verify soft credit details
     $expected = array(3 => 'Solicited', 4 => 'Donation', 2 => '50.00', 6 => 'Completed', 1 => "{$firstName} {$lastName}");
     foreach ($expected as $value => $label) {
         $this->assertElementContainsText("xpath=//div[@class='view-content']//table[@class='selector row-highlight']//tbody/tr[2]/td[{$value}]", $label);
     }
 }
 /**
  * Test checkContributeSettings.
  */
 public function testCheckContributeSettings()
 {
     $settings = CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled');
     $this->assertNull($settings);
     $params = array('contribution_invoice_settings' => array('deferred_revenue_enabled' => '1'));
     $this->callAPISuccess('Setting', 'create', $params);
     $settings = CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled');
     $this->assertEquals($settings, 1, 'Check for settings has failed');
 }