Example #1
0
 static function create($params)
 {
     // FIXME Reconcile with CRM_Admin_Form_PaymentProcessor::updatePaymentProcessor
     $processor = new CRM_Financial_DAO_PaymentProcessor();
     $processor->copyValues($params);
     $ppTypeDAO = new CRM_Financial_DAO_PaymentProcessorType();
     $ppTypeDAO->id = $params['payment_processor_type_id'];
     if (!$ppTypeDAO->find(TRUE)) {
         CRM_Core_Error::fatal(ts('Could not find payment processor meta information'));
     }
     // also copy meta fields from the info DAO
     $processor->is_recur = $ppTypeDAO->is_recur;
     $processor->billing_mode = $ppTypeDAO->billing_mode;
     $processor->class_name = $ppTypeDAO->class_name;
     $processor->payment_type = $ppTypeDAO->payment_type;
     $processor->save();
     // CRM-11826, add entry in civicrm_entity_financial_account
     // if financial_account_id is not NULL
     if (CRM_Utils_Array::value('financial_account_id', $params)) {
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
         $values = array('entity_table' => 'civicrm_payment_processor', 'entity_id' => $processor->id, 'account_relationship' => $relationTypeId, 'financial_account_id' => $params['financial_account_id']);
         CRM_Financial_BAO_FinancialTypeAccount::add($values);
     }
     return $processor;
 }
Example #2
0
 /**
  * Get a 'complex' invoice.
  *
  * Only call this via the api... I made it public static because of the move away from 'real' BAO
  * classes in preparation for doctrine but the api is the way to go.
  *
  * @param array $params
  *
  * @return array
  */
 public static function getDerived($params)
 {
     try {
         // ok this chaining is a bit heavy but it would be good to work towards API returning this more efficiently
         // ie. not keen on the fact you can't easily get line items for contributions related to participants
         // & TBH the communication with Xero takes 90% of the script time ...
         // @todo - set return properties on contribution.get
         // @todo at the moment we use getsingle because we are only dealing with 1 but should alter to 'get'
         // as in theory any params could be passed in - resulting in many - there are some api
         // issues around getfields to resolve though - see notes on api
         $contribution = civicrm_api3('contribution', 'getsingle', array_merge(array('api.participant_payment.get' => array('return' => 'api.participant., participant_id', 'api.participant.get' => array('api.line_item.get' => 1, 'return' => 'participant_source, event_id, financial_type_id'))), $params));
         // There is a chaining bug on line item because chaining passes contribution_id along as entity_id.
         // CRM-16522.
         $contribution['api.line_item.get'] = civicrm_api3('line_item', 'get', array('contribution_id' => $contribution['id']));
         if ($contribution['api.line_item.get']['count']) {
             $contribution['line_items'] = $contribution['api.line_item.get']['values'];
         } else {
             //we'll keep the participant record for anyone trying to do hooks
             $contribution['participant'] = $contribution['api.participant_payment.get']['values'][0]['api.participant.get']['values'][0];
             $contribution['line_items'] = $contribution['participant']['api.line_item.get']['values'];
             //if multiple participants one line item each
             self::_getAdditionalParticipanLineItems($contribution);
         }
         foreach ($contribution['line_items'] as &$lineItem) {
             $lineItem['accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($lineItem['financial_type_id']);
             $lineItem['accounts_contact_id'] = self::getAccountsContact($lineItem['financial_type_id']);
             $contributionAccountsContactIDs[$lineItem['accounts_contact_id']] = TRUE;
             if (!isset($lineItem['contact_id'])) {
                 //this would have been set for a secondary participant above so we are ensuring primary ones have it
                 // for conformity & ease downstream
                 $lineItem['contact_id'] = $contribution['contact_id'];
             }
             if (!isset($lineItem['display_name'])) {
                 //this would have been set for a secondary participant above so we are ensuring primary ones have it
                 // for conformity & ease downstream
                 $lineItem['display_name'] = $contribution['display_name'];
             }
         }
         //@todo move the getAccountingCode to a fn that caches it
         $contribution['accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($contribution['financial_type_id']);
         $contribution['accounts_contact_id'] = array_keys($contributionAccountsContactIDs);
     } catch (Exception $e) {
         // probably shouldn't catch & let calling class catch
     }
     // In 4.6 this might be more reliable as Monish did some tidy up on BAO_Search stuff.
     // Relying on it being unique makes me nervous...
     if (empty($contribution['payment_instrument_id'])) {
         $paymentInstruments = civicrm_api3('contribution', 'getoptions', array('field' => 'payment_instrument_id'));
         $contribution['payment_instrument_id'] = array_search($contribution['payment_instrument'], $paymentInstruments['values']);
     }
     $instrumentFinancialAccounts = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount();
     $contribution['payment_instrument_financial_account_id'] = $instrumentFinancialAccounts[$contribution['payment_instrument_id']];
     try {
         $contribution['payment_instrument_accounting_code'] = civicrm_api3('financial_account', 'getvalue', array('id' => $contribution['payment_instrument_financial_account_id'], 'return' => 'accounting_code'));
     } catch (Exception $e) {
     }
     return array($contribution['id'] => $contribution);
 }
Example #3
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $fieldValues = array('option_group_id' => $this->_gid);
         $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
         if (CRM_Core_BAO_OptionValue::del($this->_id)) {
             if ($this->_gName == 'phone_type') {
                 CRM_Core_BAO_Phone::setOptionToNull(CRM_Utils_Array::value('value', $this->_defaultValues));
             }
             CRM_Core_Session::setStatus(ts('Selected %1 type has been deleted.', array(1 => $this->_gLabel)), ts('Record Deleted'), 'success');
         } else {
             CRM_Core_Session::setStatus(ts('Selected %1 type has not been deleted.', array(1 => $this->_gLabel)), ts('Sorry'), 'error');
             CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $fieldValues);
         }
     } else {
         $params = $ids = array();
         $params = $this->exportValues();
         // allow multiple defaults within group.
         $allowMultiDefaults = array('email_greeting', 'postal_greeting', 'addressee', 'from_email_address');
         if (in_array($this->_gName, $allowMultiDefaults)) {
             if ($this->_gName == 'from_email_address') {
                 $params['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
             } elseif ($filter = CRM_Utils_Array::value('contactOptions', $params)) {
                 $params['filter'] = $filter;
                 $params['reset_default_for'] = array('filter' => "0, " . $params['filter']);
             }
             //make sure we should has to have space, CRM-6977
             if ($this->_gName == 'from_email_address') {
                 $params['label'] = str_replace('"<', '" <', $params['label']);
             }
         }
         // set value of filter if not present in params
         if ($this->_id && !array_key_exists('filter', $params)) {
             if ($this->_gName == 'participant_role') {
                 $params['filter'] = 0;
             } else {
                 $params['filter'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'filter', 'id');
             }
         }
         $groupParams = array('name' => $this->_gName);
         $optionValue = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $this->_action, $this->_id);
         // CRM-11516
         if (!empty($params['financial_account_id'])) {
             $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
             $params = array('entity_table' => 'civicrm_option_value', 'entity_id' => $optionValue->id, 'account_relationship' => $relationTypeId, 'financial_account_id' => $params['financial_account_id']);
             CRM_Financial_BAO_FinancialTypeAccount::add($params);
         }
         CRM_Core_Session::setStatus(ts('The %1 \'%2\' has been saved.', array(1 => $this->_gLabel, 2 => $optionValue->label)), ts('Saved'), 'success');
     }
 }
Example #4
0
 /**
  * Browse all financial types.
  */
 public function browse()
 {
     // Check permission for Financial Type when ACL-FT is enabled
     if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && !CRM_Core_Permission::check('administer CiviCRM Financial Types')) {
         CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
     }
     // get all financial types sorted by weight
     $financialType = array();
     $dao = new CRM_Financial_DAO_FinancialType();
     $dao->orderBy('name');
     $dao->find();
     while ($dao->fetch()) {
         $financialType[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $financialType[$dao->id]);
         $defaults = $financialAccountId = array();
         $financialAccounts = CRM_Contribute_PseudoConstant::financialAccount();
         $financialAccountIds = array();
         $params['entity_id'] = $dao->id;
         $params['entity_table'] = 'civicrm_financial_type';
         CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, CRM_Core_DAO::$_nullArray, $financialAccountIds);
         foreach ($financialAccountIds as $key => $values) {
             if (!empty($financialAccounts[$values['financial_account_id']])) {
                 $financialAccountId[$values['financial_account_id']] = CRM_Utils_Array::value($values['financial_account_id'], $financialAccounts);
             }
         }
         if (!empty($financialAccountId)) {
             $financialType[$dao->id]['financial_account'] = implode(',', $financialAccountId);
         }
         // form all action links
         $action = array_sum(array_keys($this->links()));
         // update enable/disable links depending on if it is is_reserved or is_active
         if ($dao->is_reserved) {
             $action -= CRM_Core_Action::ENABLE;
             $action -= CRM_Core_Action::DISABLE;
             $action -= CRM_Core_Action::DELETE;
         } else {
             if ($dao->is_active) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
         }
         $financialType[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id), ts('more'), FALSE, 'financialType.manage.action', 'FinancialType', $dao->id);
     }
     $this->assign('rows', $financialType);
 }
 private function addContributionFinancialItem()
 {
     $sql = " SELECT cc.id contribution_id, cli.id as line_item_id, cc.contact_id, cc.receive_date, cc.total_amount, cc.currency, cli.label, cli.financial_type_id,  cefa.financial_account_id, cc.payment_instrument_id, cc.check_number, cc.trxn_id\nFROM `civicrm_contribution` cc\nINNER JOIN civicrm_line_item cli ON cli.entity_id = cc.id and cli.entity_table = 'civicrm_contribution'\nINNER JOIN civicrm_entity_financial_account cefa ON cefa.entity_id =  cli.financial_type_id\nWHERE cefa.account_relationship = 1; ";
     $result = CRM_Core_DAO::executeQuery($sql);
     $financialAccountId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount();
     $this->addFinancialItem($result, $financialAccountId);
 }
Example #6
0
 /**
  * Get financial account id has 'Sales Tax Account is'
  * account relationship with financial type
  *
  * @param int $financialTypeId
  *
  * @return FinancialAccountId
  */
 public static function getFinancialAccountId($financialTypeId)
 {
     $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
     $searchParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $financialTypeId, 'account_relationship' => $accountRel);
     $result = array();
     CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
     return CRM_Utils_Array::value('financial_account_id', $result);
 }
 /**
  * Global validation rules for the form.
  *
  * @param array $values
  *   posted values of the form
  * @param $files
  * @param $self
  *
  * @return array
  *   list of errors to be posted back to the form
  */
 public static function formRule($values, $files, $self)
 {
     $errorMsg = array();
     $financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' "));
     if (isset($values['is_tax'])) {
         if ($values['financial_account_type_id'] != $financialAccountTypeId) {
             $errorMsg['financial_account_type_id'] = ts('Taxable accounts should have Financial Account Type set to Liability.');
         }
         if (CRM_Utils_Array::value('tax_rate', $values) == NULL) {
             $errorMsg['tax_rate'] = ts('Please enter value for tax rate');
         }
     }
     if (CRM_Utils_Array::value('tax_rate', $values) != NULL) {
         if ($values['tax_rate'] < 0 || $values['tax_rate'] >= 100) {
             $errorMsg['tax_rate'] = ts('Tax Rate Should be between 0 - 100');
         }
     }
     if ($self->_action & CRM_Core_Action::UPDATE) {
         if (!isset($values['is_tax'])) {
             $relationshipId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
             $params = array('financial_account_id' => $self->_id, 'account_relationship' => $relationshipId);
             $result = CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
             if ($result) {
                 $errorMsg['is_tax'] = ts('Is Tax? must be set for this financial account');
             }
         }
     }
     return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
 }
Example #8
0
 /**
  * Save a payment processor.
  *
  * @param $values
  * @param int $domainID
  * @param $test
  *
  * @return void
  */
 public function updatePaymentProcessor(&$values, $domainID, $test)
 {
     $dao = new CRM_Financial_DAO_PaymentProcessor();
     $dao->id = $test ? $this->_testID : $this->_id;
     $dao->domain_id = $domainID;
     $dao->is_test = $test;
     $dao->is_default = CRM_Utils_Array::value('is_default', $values, 0);
     $dao->is_active = CRM_Utils_Array::value('is_active', $values, 0);
     $dao->name = $values['name'];
     $dao->description = $values['description'];
     $dao->payment_processor_type_id = $values['payment_processor_type_id'];
     foreach ($this->_fields as $field) {
         $fieldName = $test ? "test_{$field['name']}" : $field['name'];
         $dao->{$field['name']} = trim(CRM_Utils_Array::value($fieldName, $values));
         if (empty($dao->{$field['name']})) {
             $dao->{$field['name']} = 'null';
         }
     }
     // also copy meta fields from the info DAO
     $dao->is_recur = $this->_ppDAO->is_recur;
     $dao->billing_mode = $this->_ppDAO->billing_mode;
     $dao->class_name = $this->_ppDAO->class_name;
     $dao->payment_type = $this->_ppDAO->payment_type;
     $dao->save();
     //CRM-11515
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
     $params = array('entity_table' => 'civicrm_payment_processor', 'entity_id' => $dao->id, 'account_relationship' => $relationTypeId, 'financial_account_id' => $values['financial_account_id']);
     CRM_Financial_BAO_FinancialTypeAccount::add($params);
 }
 /**
  * @return array
  */
 public function setDefaultValues()
 {
     $defaults = array();
     if (!$this->_id) {
         $defaults['is_active'] = $defaults['is_default'] = 1;
         $defaults['url_site'] = $this->_ppDAO->url_site_default;
         $defaults['url_api'] = $this->_ppDAO->url_api_default;
         $defaults['url_recur'] = $this->_ppDAO->url_recur_default;
         $defaults['url_button'] = $this->_ppDAO->url_button_default;
         $defaults['test_url_site'] = $this->_ppDAO->url_site_test_default;
         $defaults['test_url_api'] = $this->_ppDAO->url_api_test_default;
         $defaults['test_url_recur'] = $this->_ppDAO->url_recur_test_default;
         $defaults['test_url_button'] = $this->_ppDAO->url_button_test_default;
         $defaults['payment_instrument_id'] = $this->_ppDAO->payment_instrument_id;
         // When user changes payment processor type, it is passed in via $this->_ppType so update defaults array.
         if ($this->_ppType) {
             $defaults['payment_processor_type_id'] = $this->_ppType;
         }
         return $defaults;
     }
     $domainID = CRM_Core_Config::domainID();
     $dao = new CRM_Financial_DAO_PaymentProcessor();
     $dao->id = $this->_id;
     $dao->domain_id = $domainID;
     if (!$dao->find(TRUE)) {
         return $defaults;
     }
     CRM_Core_DAO::storeValues($dao, $defaults);
     // When user changes payment processor type, it is passed in via $this->_ppType so update defaults array.
     if ($this->_ppType) {
         $defaults['payment_processor_type_id'] = $this->_ppType;
     }
     $cards = json_decode(CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $this->_id, 'accepted_credit_cards'), TRUE);
     $acceptedCards = array();
     if (!empty($cards)) {
         foreach ($cards as $card => $val) {
             $acceptedCards[$card] = 1;
         }
     }
     $defaults['accept_credit_cards'] = $acceptedCards;
     unset($defaults['accepted_credit_cards']);
     // now get testID
     $testDAO = new CRM_Financial_DAO_PaymentProcessor();
     $testDAO->name = $dao->name;
     $testDAO->is_test = 1;
     $testDAO->domain_id = $domainID;
     if ($testDAO->find(TRUE)) {
         $this->_testID = $testDAO->id;
         foreach ($this->_fields as $field) {
             $testName = "test_{$field['name']}";
             $defaults[$testName] = $testDAO->{$field['name']};
         }
     }
     $defaults['financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($dao->id, 'civicrm_payment_processor', 'financial_account_id');
     return $defaults;
 }
 private function addAccountingEntries()
 {
     $components = array('contribution', 'membership', 'participant');
     $select = 'SELECT contribution.id contribution_id, cli.id as line_item_id, contribution.contact_id, contribution.receive_date, contribution.total_amount, contribution.currency, cli.label,
   cli.financial_type_id,  cefa.financial_account_id, contribution.payment_instrument_id, contribution.check_number, contribution.trxn_id';
     $where = 'WHERE cefa.account_relationship = 1';
     $financialAccountId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount();
     foreach ($components as $component) {
         if ($component == 'contribution') {
             $from = 'FROM `civicrm_contribution` contribution';
         } else {
             $from = " FROM `civicrm_{$component}` {$component}\n          INNER JOIN civicrm_{$component}_payment cpp ON cpp.{$component}_id = {$component}.id\n          INNER JOIN civicrm_contribution contribution on contribution.id = cpp.contribution_id";
         }
         $from .= " INNER JOIN civicrm_line_item cli ON cli.entity_id = {$component}.id and cli.entity_table = 'civicrm_{$component}'\n        INNER JOIN civicrm_entity_financial_account cefa ON cefa.entity_id =  cli.financial_type_id ";
         $sql = " {$select} {$from} {$where} ";
         $result = CRM_Core_DAO::executeQuery($sql);
         $this->addFinancialItem($result, $financialAccountId);
     }
 }
Example #11
0
 /**
  * Browse all options
  *
  *
  * @return void
  * @access public
  * @static
  */
 function browse()
 {
     if (!self::$_gName) {
         return parent::browse();
     }
     CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js');
     $groupParams = array('name' => self::$_gName);
     $optionValue = CRM_Core_OptionValue::getRows($groupParams, $this->links(), 'component_id,weight');
     $gName = self::$_gName;
     $returnURL = CRM_Utils_System::url("civicrm/admin/options/{$gName}", "reset=1&group={$gName}");
     $filter = "option_group_id = " . self::$_gId;
     CRM_Utils_Weight::addOrder($optionValue, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
     // retrieve financial account name for the payment instrument page
     if ($gName = "payment_instrument") {
         foreach ($optionValue as $key => $option) {
             $optionValue[$key]['financial_account'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($key, 'civicrm_option_value');
         }
     }
     $this->assign('includeWysiwygEditor', TRUE);
     $this->assign('rows', $optionValue);
 }
Example #12
0
 /**
  * Browse all options.
  *
  *
  * @return void
  */
 public function browse()
 {
     if (!self::$_gName) {
         return parent::browse();
     }
     $groupParams = array('name' => self::$_gName);
     $optionValue = CRM_Core_OptionValue::getRows($groupParams, $this->links(), 'component_id,weight');
     $gName = self::$_gName;
     $returnURL = CRM_Utils_System::url("civicrm/admin/options/{$gName}", "reset=1&group={$gName}");
     $filter = "option_group_id = " . self::$_gId;
     CRM_Utils_Weight::addOrder($optionValue, 'CRM_Core_DAO_OptionValue', 'id', $returnURL, $filter);
     // retrieve financial account name for the payment method page
     if ($gName = "payment_instrument") {
         foreach ($optionValue as $key => $option) {
             $optionValue[$key]['financial_account'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($key, 'civicrm_option_value');
         }
     }
     $this->assign('rows', $optionValue);
 }
 /**
  * @param $contributionId
  * @param $trxnsData
  * @param string $paymentType
  * @param null $participantId
  *
  * @return null|object
  */
 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL)
 {
     $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
     $getInfoOf['id'] = $contributionId;
     $defaults = array();
     $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
     if ($paymentType == 'owed') {
         // build params for recording financial trxn entry
         $params['contribution'] = $contributionDAO;
         $params = array_merge($defaults, $params);
         $params['skipLineItem'] = TRUE;
         $params['partial_payment_total'] = $contributionDAO->total_amount;
         $params['partial_amount_pay'] = $trxnsData['total_amount'];
         $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
         // record the entry
         $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
         $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
         if (!empty($trxnId)) {
             $trxnId = $trxnId['trxn_id'];
         } elseif (!empty($contributionDAO->payment_instrument_id)) {
             $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->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'));
             $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
         }
         // update statuses
         // criteria for updates contribution total_amount == financial_trxns of partial_payments
         $sql = "SELECT SUM(ft.total_amount) as sum_of_payments\nFROM civicrm_financial_trxn ft\nLEFT JOIN civicrm_entity_financial_trxn eft\n  ON (ft.id = eft.financial_trxn_id)\nWHERE eft.entity_table = 'civicrm_contribution'\n  AND eft.entity_id = {$contributionId}\n  AND ft.to_financial_account_id != {$toFinancialAccount}\n  AND ft.status_id = {$statusId}\n";
         $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql);
         // update statuses
         if ($contributionDAO->total_amount == $sumOfPayments) {
             // update contribution status and
             // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
             $contributionDAO->contribution_status_id = $statusId;
             $contributionDAO->cancel_date = 'null';
             $contributionDAO->cancel_reason = NULL;
             $contributionDAO->save();
             //Change status of financial record too
             $financialTrxn->status_id = $statusId;
             $financialTrxn->save();
             // note : not using the self::add method,
             // the reason because it performs 'status change' related code execution for financial records
             // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
             // are coded below i.e. just updating financial_item status to 'Paid'
             if ($participantId) {
                 // update participant status
                 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
                 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
                 foreach ($ids as $val) {
                     $participantUpdate['id'] = $val;
                     $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
                     CRM_Event_BAO_Participant::add($participantUpdate);
                 }
             }
             // update financial item statuses
             $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
             $paidStatus = array_search('Paid', $financialItemStatus);
             $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
             $sqlFinancialItemUpdate = "\nUPDATE civicrm_financial_item fi\n  LEFT JOIN civicrm_entity_financial_trxn eft\n    ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')\nSET status_id = {$paidStatus}\nWHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})\n";
             CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
         }
     } elseif ($paymentType == 'refund') {
         // build params for recording financial trxn entry
         $params['contribution'] = $contributionDAO;
         $params = array_merge($defaults, $params);
         $params['skipLineItem'] = TRUE;
         $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
         $trxnsData['total_amount'] = -$trxnsData['total_amount'];
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
         $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
         // record the entry
         $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
         // note : not using the self::add method,
         // the reason because it performs 'status change' related code execution for financial records
         // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
         // are coded below i.e. just updating financial_item status to 'Paid'
         $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
         // add financial item entry
         $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
         $getLine['entity_id'] = $contributionDAO->id;
         $getLine['entity_table'] = 'civicrm_contribution';
         $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
         if (!empty($lineItemId->id)) {
             $addFinancialEntry = array('transaction_date' => $financialTrxn->trxn_date, 'contact_id' => $contributionDAO->contact_id, 'amount' => $financialTrxn->total_amount, 'status_id' => array_search('Paid', $financialItemStatus), 'entity_id' => $lineItemId->id, 'entity_table' => 'civicrm_line_item');
             $trxnIds['id'] = $financialTrxn->id;
             CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
         }
         if ($participantId) {
             // update participant status
             $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
             $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
             foreach ($ids as $val) {
                 $participantUpdate['id'] = $val;
                 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
                 CRM_Event_BAO_Participant::add($participantUpdate);
             }
         }
     }
     // activity creation
     if (!empty($financialTrxn)) {
         if ($participantId) {
             $inputParams['id'] = $participantId;
             $values = array();
             $ids = array();
             $component = 'event';
             $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
             $entityObj = $entityObj[$participantId];
         }
         $activityType = $paymentType == 'refund' ? 'Refund' : 'Payment';
         self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
     }
     return $financialTrxn;
 }
 public function testGetTaxRates()
 {
     $contact = $this->createLoggedInUser();
     $financialType = $this->callAPISuccess('financial_type', 'create', array('name' => 'Test taxable financial Type', 'is_reserved' => 0, 'is_active' => 1));
     $financialAccount = $this->callAPISuccess('financial_account', 'create', array('name' => 'Test Tax financial account ', 'contact_id' => $contact, 'financial_account_type_id' => 2, 'is_tax' => 1, 'tax_rate' => 5.0, 'is_reserved' => 0, 'is_active' => 1, 'is_default' => 0));
     $financialTypeId = $financialType['id'];
     $financialAccountId = $financialAccount['id'];
     $financialAccountParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $financialTypeId, 'account_relationship' => 10, 'financial_account_id' => $financialAccountId);
     CRM_Financial_BAO_FinancialTypeAccount::add($financialAccountParams);
     $taxRates = CRM_Core_PseudoConstant::getTaxRates();
     $this->assertEquals('5.00', $taxRates[$financialType['id']]);
 }
 /**
  * Function to process the form
  *
  * @access public
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Financial_BAO_FinancialTypeAccount::del($this->_id, $this->_aid);
         CRM_Core_Session::setStatus(ts('Selected financial type account has been deleted.'));
     } else {
         $params = $ids = array();
         // store the submitted values in an array
         $params = $this->exportValues();
         if ($this->_action & CRM_Core_Action::UPDATE) {
             $ids['entityFinancialAccount'] = $this->_id;
         }
         if ($this->_action & CRM_Core_Action::ADD || $this->_action & CRM_Core_Action::UPDATE) {
             $params['financial_account_id'] = $this->_submitValues['financial_account_id'];
         }
         $params['entity_table'] = 'civicrm_financial_type';
         if ($this->_action & CRM_Core_Action::ADD) {
             $params['entity_id'] = $this->_aid;
         }
         $financialTypeAccount = CRM_Financial_BAO_FinancialTypeAccount::add($params, $ids);
         CRM_Core_Session::setStatus(ts('The financial type Account has been saved.'));
     }
     $buttonName = $this->controller->getButtonName();
     $session = CRM_Core_Session::singleton();
     if ($buttonName == $this->getButtonName('next', 'new')) {
         CRM_Core_Session::setStatus(ts(' You can add another Financial Account Type.'));
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', "reset=1&action=add&aid={$this->_aid}"));
     } else {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', "reset=1&action=browse&aid={$this->_aid}"));
     }
 }
 /**
  * check method getInstrumentFinancialAccount()
  */
 function testGetInstrumentFinancialAccount()
 {
     $paymentInstrumentValue = 1;
     $params = array('name' => 'Donations', 'is_deductible' => 0, 'is_active' => 1);
     $ids = array();
     $financialAccount = CRM_Financial_BAO_FinancialAccount::add($params, $ids);
     $optionParams = array('name' => 'Credit Card', 'value' => $paymentInstrumentValue);
     $optionValue = CRM_Core_BAO_OptionValue::retrieve($optionParams, $defaults);
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
     $financialParams = array('entity_table' => 'civicrm_option_value', 'entity_id' => $optionValue->id, 'account_relationship' => $relationTypeId, 'financial_account_id' => $financialAccount->id);
     CRM_Financial_BAO_FinancialTypeAccount::add($financialParams, $ids);
     $financialAccountId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($paymentInstrumentValue);
     $this->assertEquals($financialAccountId, $financialAccount->id, 'Verify Payment Instrument');
 }
Example #17
0
 /**
  * Add the financial types.
  *
  * @param array $params
  *   Reference array contains the values submitted by the form.
  * @param array $ids
  *   Reference array contains the id.
  *
  * @return object
  */
 public static function add(&$params, &$ids = array())
 {
     if (empty($params['id'])) {
         $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
         $params['is_deductible'] = CRM_Utils_Array::value('is_deductible', $params, FALSE);
         $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
     }
     // action is taken depending upon the mode
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->copyValues($params);
     if (!empty($ids['financialType'])) {
         $financialType->id = CRM_Utils_Array::value('financialType', $ids);
         if (self::isACLFinancialTypeStatus()) {
             $prevName = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $financialType->id, 'name');
             if ($prevName != $params['name']) {
                 CRM_Core_Session::setStatus(ts("Changing the name of a Financial Type will result in losing the current permissions associated with that Financial Type.\n            Before making this change you should likely note the existing permissions at Administer > Users and Permissions > Permissions (Access Control),\n            then clicking the Access Control link for your Content Management System, then noting down the permissions for 'CiviCRM: {financial type name} view', etc.\n            Then after making the change of name, reset the permissions to the way they were."), ts('Warning'), 'warning');
             }
         }
     }
     $financialType->save();
     // CRM-12470
     if (empty($ids['financialType']) && empty($params['id'])) {
         $titles = CRM_Financial_BAO_FinancialTypeAccount::createDefaultFinancialAccounts($financialType);
         $financialType->titles = $titles;
     }
     return $financialType;
 }
Example #18
0
 /**
  * @return mixed
  */
 public function _addPaymentInstrument()
 {
     $gId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
     $optionParams = array('option_group_id' => $gId, 'label' => 'Test Card', 'name' => 'Test Card', 'value' => '6', 'weight' => '6', 'is_active' => 1);
     $optionValue = $this->callAPISuccess('option_value', 'create', $optionParams);
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
     $financialParams = array('entity_table' => 'civicrm_option_value', 'entity_id' => $optionValue['id'], 'account_relationship' => $relationTypeId, 'financial_account_id' => 7);
     CRM_Financial_BAO_FinancialTypeAccount::add($financialParams, CRM_Core_DAO::$_nullArray);
     $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
     return $optionValue['values'][$optionValue['id']]['value'];
 }
 /**
  * Function to create Financial Account.
  *
  * @param string $financialAccountType
  *
  * @param string $relationType
  *
  * @return array
  *   obj CRM_Financial_DAO_FinancialAccount, obj CRM_Financial_DAO_FinancialType, obj CRM_Financial_DAO_EntityFinancialAccount
  */
 public function createFinancialAccount($financialAccountType, $relationType = NULL)
 {
     $params = array('labelColumn' => 'name');
     $relationTypes = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
     $financialAccountTypes = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
     $params = array('name' => 'TestFinancialAccount_' . rand(), 'contact_id' => 1, 'is_deductible' => 0, 'is_active' => 1, 'is_reserved' => 0, 'financial_account_type_id' => array_search($financialAccountType, $financialAccountTypes));
     $financialAccount = CRM_Financial_BAO_FinancialAccount::add($params);
     $financialType = $financialAccountType = NULL;
     if ($relationType) {
         $params['name'] = 'test_financialType1';
         $financialType = CRM_Financial_BAO_FinancialType::add($params);
         $financialParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $financialType->id, 'account_relationship' => array_search($relationType, $relationTypes), 'financial_account_id' => $financialAccount->id);
         $financialAccountType = CRM_Financial_BAO_FinancialTypeAccount::add($financialParams);
     }
     return array($financialAccount, $financialType, $financialAccountType);
 }
Example #20
0
 /**
  * Add the financial items and financial trxn.
  *
  * @param object $lineItem
  *   Line item object.
  * @param object $contribution
  *   Contribution object.
  * @param bool $taxTrxnID
  *
  * @return void
  */
 public static function add($lineItem, $contribution, $taxTrxnID = FALSE, $trxnId = NULL)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
     $itemStatus = NULL;
     if ($contribution->contribution_status_id == array_search('Completed', $contributionStatuses) || $contribution->contribution_status_id == array_search('Pending refund', $contributionStatuses)) {
         $itemStatus = array_search('Paid', $financialItemStatus);
     } elseif ($contribution->contribution_status_id == array_search('Pending', $contributionStatuses) || $contribution->contribution_status_id == array_search('In Progress', $contributionStatuses)) {
         $itemStatus = array_search('Unpaid', $financialItemStatus);
     } elseif ($contribution->contribution_status_id == array_search('Partially paid', $contributionStatuses)) {
         $itemStatus = array_search('Partially paid', $financialItemStatus);
     }
     $params = array('transaction_date' => CRM_Utils_Date::isoToMysql($contribution->receive_date), 'contact_id' => $contribution->contact_id, 'amount' => $lineItem->line_total, 'currency' => $contribution->currency, 'entity_table' => 'civicrm_line_item', 'entity_id' => $lineItem->id, 'description' => ($lineItem->qty != 1 ? $lineItem->qty . ' of ' : '') . ' ' . $lineItem->label, 'status_id' => $itemStatus);
     if ($taxTrxnID) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
         $params['amount'] = $lineItem->tax_amount;
         $params['description'] = $taxTerm;
         $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
     } else {
         $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
     }
     if ($lineItem->financial_type_id) {
         $searchParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $lineItem->financial_type_id, 'account_relationship' => $accountRel);
         $result = array();
         CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
         $params['financial_account_id'] = CRM_Utils_Array::value('financial_account_id', $result);
     }
     if (empty($trxnId)) {
         $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution->id, 'ASC', TRUE);
         $trxnId['id'] = $trxn['financialTrxnId'];
     }
     return self::create($params, NULL, $trxnId);
 }
 /**
  * Function to create all financial accounts entry
  *
  * @param array $params contribution object, line item array and params for trxn
  *
  *
  * @access public
  * @static
  */
 static function recordFinancialAccounts(&$params)
 {
     $skipRecords = $update = 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);
     } else {
         $entityId = $params['contribution']->id;
         $entityTable = 'civicrm_contribution';
     }
     $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 (!CRM_Utils_Array::value('prevContribution', $params)) {
         $entityID = NULL;
     } else {
         $update = TRUE;
     }
     // build line item array if its not set in $params
     if (!CRM_Utils_Array::value('line_item', $params) || $additionalParticipantId) {
         CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
     }
     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 (CRM_Utils_Array::value('payment_processor', $params)) {
             $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
         } elseif (CRM_Utils_Array::value('payment_instrument_id', $params)) {
             $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) && CRM_Utils_Array::value('prevContribution', $params)) {
             $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' => date('YmdHis'), 'total_amount' => $totalAmount, 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), 'net_amount' => CRM_Utils_Array::value('net_amount', $params), 'currency' => $params['contribution']->currency, 'trxn_id' => $params['contribution']->trxn_id, 'status_id' => $params['contribution']->contribution_status_id, 'payment_instrument_id' => $params['contribution']->payment_instrument_id, 'check_number' => CRM_Utils_Array::value('check_number', $params));
         if (CRM_Utils_Array::value('payment_processor', $params)) {
             $trxnParams['payment_processor_id'] = $params['payment_processor'];
         }
         $params['trxnParams'] = $trxnParams;
         if (CRM_Utils_Array::value('prevContribution', $params)) {
             $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;
             $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
             $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
             //if financial type is changed
             if (CRM_Utils_Array::value('financial_type_id', $params) && $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 (CRM_Utils_Array::value('financialTrxnId', $lastFinancialTrxnId)) {
                             $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;
             if (CRM_Utils_Array::value('contribution_status_id', $params) && $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');
                     }
                 } else {
                     if ((!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');
                     } else {
                         if (!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
             $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
             $params['entity_id'] = $financialTxn->id;
         }
     }
     // record line items and finacial items
     if (!CRM_Utils_Array::value('skipLineItem', $params)) {
         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
     if (CRM_Utils_Array::value('batch_id', $params)) {
         $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 (CRM_Utils_Array::value('fee_amount', $params) && (!CRM_Utils_Array::value('prevContribution', $params) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
         CRM_Core_BAO_FinancialTrxn::recordFees($params);
     }
     if (CRM_Utils_Array::value('prevContribution', $params) && $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']);
 }
Example #22
0
 /**
  * function to add the financial types
  *
  * @param array $params reference array contains the values submitted by the form
  * @param array $ids    reference array contains the id
  *
  * @access public
  * @static
  * @return object
  */
 static function add(&$params, &$ids)
 {
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, false);
     $params['is_deductible'] = CRM_Utils_Array::value('is_deductible', $params, false);
     $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, false);
     // action is taken depending upon the mode
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->copyValues($params);
     if (CRM_Utils_Array::value('financialType', $ids)) {
         $financialType->id = CRM_Utils_Array::value('financialType', $ids);
     }
     $financialType->save();
     // CRM-12470
     if (!CRM_Utils_Array::value('financialType', $ids)) {
         $titles = CRM_Financial_BAO_FinancialTypeAccount::createDefaultFinancialAccounts($financialType);
         $financialType->titles = $titles;
     }
     return $financialType;
 }
 /**
  * Browse all payment processors.
  *
  * @param null $action
  *
  * @return void
  * @access public
  * @static
  */
 function browse($action = NULL)
 {
     // get all custom groups sorted by weight
     $paymentProcessor = array();
     $dao = new CRM_Financial_DAO_PaymentProcessor();
     $dao->is_test = 0;
     $dao->domain_id = CRM_Core_Config::domainID();
     $dao->orderBy('name');
     $dao->find();
     while ($dao->fetch()) {
         $paymentProcessor[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $paymentProcessor[$dao->id]);
         $paymentProcessor[$dao->id]['payment_processor_type'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor[$dao->id]['payment_processor_type_id']);
         // form all action links
         $action = array_sum(array_keys($this->links()));
         // update enable/disable links.
         if ($dao->is_active) {
             $action -= CRM_Core_Action::ENABLE;
         } else {
             $action -= CRM_Core_Action::DISABLE;
         }
         $paymentProcessor[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id), ts('more'), FALSE, 'paymentProcessor.manage.action', 'PaymentProcessor', $dao->id);
         $paymentProcessor[$dao->id]['financialAccount'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($dao->id, 'civicrm_payment_processor');
     }
     $this->assign('rows', $paymentProcessor);
 }
 /**
  * function to add the financial items and financial trxn
  *
  * @param object $lineItem     line item object
  * @param object $contribution contribution object
  *
  * @access public
  * @static
  * @return void
  */
 static function add($lineItem, $contribution)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
     $itemStatus = NULL;
     if ($contribution->contribution_status_id == array_search('Completed', $contributionStatuses)) {
         $itemStatus = array_search('Paid', $financialItemStatus);
     } elseif ($contribution->contribution_status_id == array_search('Pending', $contributionStatuses) || $contribution->contribution_status_id == array_search('In Progress', $contributionStatuses)) {
         $itemStatus = array_search('Unpaid', $financialItemStatus);
     } elseif ($contribution->contribution_status_id == array_search('Partially paid', $contributionStatuses)) {
         $itemStatus = array_search('Partially paid', $financialItemStatus);
     }
     $params = array('transaction_date' => CRM_Utils_Date::isoToMysql($contribution->receive_date), 'contact_id' => $contribution->contact_id, 'amount' => $lineItem->line_total, 'currency' => $contribution->currency, 'entity_table' => 'civicrm_line_item', 'entity_id' => $lineItem->id, 'description' => ($lineItem->qty != 1 ? $lineItem->qty . ' of ' : '') . ' ' . $lineItem->label, 'status_id' => $itemStatus);
     if ($lineItem->financial_type_id) {
         $searchParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $lineItem->financial_type_id, 'account_relationship' => 1);
         $result = array();
         CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
         $params['financial_account_id'] = CRM_Utils_Array::value('financial_account_id', $result);
     }
     $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution->id, 'ASC', TRUE);
     $trxnId['id'] = $trxn['financialTrxnId'];
     return self::create($params, NULL, $trxnId);
 }
Example #25
0
 /**
  * This function is used to record partial payments for contribution
  *
  * @param array $contribution
  *
  * @param array $params
  *
  * @return object
  */
 public static function recordPartialPayment($contribution, $params)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
     $statusId = array_search('Completed', $contributionStatuses);
     if (in_array(CRM_Utils_Array::value('contribution_status_id', $contribution), $pendingStatus)) {
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contribution['financial_type_id'], $relationTypeId);
     } elseif (!empty($params['payment_processor'])) {
         $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
     } elseif (!empty($params['payment_instrument_id'])) {
         $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['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'));
         $balanceTrxnParams['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);
     }
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
     $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($contribution['financial_type_id'], $relationTypeId);
     $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
     $balanceTrxnParams['total_amount'] = $params['total_amount'];
     $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('total_amount', $params);
     $balanceTrxnParams['currency'] = $contribution['currency'];
     $balanceTrxnParams['trxn_id'] = CRM_Utils_Array::value('contribution_trxn_id', $params, NULL);
     $balanceTrxnParams['status_id'] = $statusId;
     $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
     $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
     if ($fromFinancialAccountId != NULL && ($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'];
     }
     return CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
 }
Example #26
0
 /**
  * Browse all financial types
  *
  *
  * @return void
  * @access public
  * @static
  */
 function browse()
 {
     // get all financial types sorted by weight
     $financialType = array();
     $dao = new CRM_Financial_DAO_FinancialType();
     $dao->orderBy('name');
     $dao->find();
     while ($dao->fetch()) {
         $financialType[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $financialType[$dao->id]);
         $defaults = $financialAccountId = array();
         $financialAccounts = CRM_Contribute_PseudoConstant::financialAccount();
         $financialAccountIds = array();
         $params['entity_id'] = $dao->id;
         $params['entity_table'] = 'civicrm_financial_type';
         CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, CRM_Core_DAO::$_nullArray, $financialAccountIds);
         foreach ($financialAccountIds as $key => $values) {
             if (CRM_Utils_Array::value($values['financial_account_id'], $financialAccounts)) {
                 $financialAccountId[$values['financial_account_id']] = CRM_Utils_Array::value($values['financial_account_id'], $financialAccounts);
             }
         }
         if (!empty($financialAccountId)) {
             $financialType[$dao->id]['financial_account'] = implode(',', $financialAccountId);
         }
         // form all action links
         $action = array_sum(array_keys($this->links()));
         // update enable/disable links depending on if it is is_reserved or is_active
         if ($dao->is_reserved) {
             $action -= CRM_Core_Action::ENABLE;
             $action -= CRM_Core_Action::DISABLE;
             $action -= CRM_Core_Action::DELETE;
             //continue;
         } else {
             if ($dao->is_active) {
                 $action -= CRM_Core_Action::ENABLE;
             } else {
                 $action -= CRM_Core_Action::DISABLE;
             }
         }
         $financialType[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id));
     }
     $this->assign('rows', $financialType);
 }
Example #27
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     CRM_Utils_System::flushCache();
     $params = $this->exportValues();
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Core_BAO_OptionValue::del($this->_id);
         CRM_Core_Session::setStatus(ts('Selected option value has been deleted.'), ts('Record Deleted'), 'success');
     } else {
         $params = $ids = array();
         // store the submitted values in an array
         $params = $this->exportValues();
         $params['option_group_id'] = $this->_gid;
         if ($this->_action & CRM_Core_Action::UPDATE) {
             $ids['optionValue'] = $this->_id;
         }
         //set defaultGreeting option in params to save default value as per contactOption-defaultValue mapping
         if (CRM_Utils_Array::value('contactOptions', $params)) {
             $params['filter'] = CRM_Utils_Array::value('contactOptions', $params);
             $params['defaultGreeting'] = 1;
         }
         $optionValue = CRM_Core_BAO_OptionValue::add($params, $ids);
         // CRM-11516
         if (CRM_Utils_Array::value('financial_account_id', $params)) {
             $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
             $params = array('entity_table' => 'civicrm_option_value', 'entity_id' => $optionValue->id, 'account_relationship' => $relationTypeId, 'financial_account_id' => $params['financial_account_id']);
             CRM_Financial_BAO_FinancialTypeAccount::add($params);
         }
         CRM_Core_Session::setStatus(ts('The Option Value \'%1\' has been saved.', array(1 => $optionValue->label)), ts('Saved'), 'success');
     }
 }