示例#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;
 }
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     parent::preProcess();
     if ($this->_id) {
         $params = array('id' => $this->_id);
         $financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params, CRM_Core_DAO::$_nullArray);
         $financialAccountType = CRM_Core_PseudoConstant::accountOptionValues('financial_account_type');
         if ($financialAccount->financial_account_type_id == array_search('Asset', $financialAccountType) && strtolower($financialAccount->account_type_code) == 'ar' && !CRM_Financial_BAO_FinancialAccount::getARAccounts($this->_id, array_search('Asset', $financialAccountType))) {
             $this->_isARFlag = TRUE;
             if ($this->_action & CRM_Core_Action::DELETE) {
                 $msg = ts("The selected financial account cannot be deleted because at least one Accounts Receivable type account is required (to ensure that accounting transactions are in balance).");
                 CRM_Core_Error::statusBounce($msg);
             }
         }
     }
 }
示例#3
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     parent::preProcess();
     if ($this->_id) {
         $params = array('id' => $this->_id);
         $financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params, CRM_Core_DAO::$_nullArray);
         $financialAccountType = CRM_Core_PseudoConstant::accountOptionValues('financial_account_type');
         if ($financialAccount->financial_account_type_id == array_search('Asset', $financialAccountType) && strtolower($financialAccount->account_type_code) == 'ar' && !CRM_Financial_BAO_FinancialAccount::getARAccounts($this->_id, array_search('Asset', $financialAccountType))) {
             $this->_isARFlag = TRUE;
             if ($this->_action & CRM_Core_Action::DELETE) {
                 CRM_Core_Session::setStatus(ts("The selected financial account cannot be deleted because at least one Accounts Receivable type account is required (to ensure that accounting transactions are in balance)."), '', 'error');
                 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/financial/financialAccount', "reset=1&action=browse"));
             }
         }
     }
 }
示例#4
0
 /**
  * create financial trxn and items when fee is charged
  *
  * @params params to create trxn entries
  *
  * @access public
  * @static
  */
 static function recordFees($params)
 {
     $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
     $domainId = CRM_Core_Config::domainID();
     $amount = 0;
     if (CRM_Utils_Array::value('prevContribution', $params)) {
         $amount = $params['prevContribution']->fee_amount;
     }
     $amount = $params['fee_amount'] - $amount;
     if (!$amount) {
         return FALSE;
     }
     $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $expenseTypeId);
     $params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
     $params['trxnParams']['to_financial_account_id'] = $financialAccount;
     $params['trxnParams']['total_amount'] = $amount;
     $params['trxnParams']['fee_amount'] = $params['trxnParams']['net_amount'] = 0;
     $params['trxnParams']['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
     $params['trxnParams']['contribution_id'] = isset($params['contribution']->id) ? $params['contribution']->id : $params['contribution_id'];
     $trxn = self::create($params['trxnParams']);
     if (!CRM_Utils_Array::value('entity_id', $params)) {
         $financialTrxnID = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['trxnParams']['contribution_id'], 'DESC');
         $params['entity_id'] = $financialTrxnID['financialTrxnId'];
     }
     $fItemParams = array('financial_account_id' => $financialAccount, 'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'), 'created_date' => date('YmdHis'), 'transaction_date' => date('YmdHis'), 'amount' => $amount, 'description' => 'Fee', 'status_id' => CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'entity_table' => 'civicrm_financial_trxn', 'entity_id' => $params['entity_id'], 'currency' => $params['trxnParams']['currency']);
     $trxnIDS['id'] = $trxn->id;
     $financialItem = CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
 }
示例#5
0
 /**
  * Record adjusted amount.
  *
  * @param int $updatedAmount
  * @param int $paidAmount
  * @param int $contributionId
  *
  * @param int $taxAmount
  * @param bool $updateAmountLevel
  *
  * @return bool|\CRM_Core_BAO_FinancialTrxn
  */
 public static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL)
 {
     $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
     $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
     $balanceAmt = $updatedAmount - $paidAmount;
     if ($paidAmount != $pendingAmount) {
         $balanceAmt -= $pendingAmount;
     }
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendingRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $completedStatusId = array_search('Completed', $contributionStatuses);
     $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
     $adjustedTrxn = $skip = FALSE;
     if ($balanceAmt) {
         if ($balanceAmt > 0 && $paidAmount != 0) {
             $contributionStatusVal = $partiallyPaidStatusId;
         } elseif ($balanceAmt < 0 && $paidAmount != 0) {
             $contributionStatusVal = $pendingRefundStatusId;
         } elseif ($paidAmount == 0) {
             //skip updating the contribution status if no payment is made
             $skip = TRUE;
             $updatedContributionDAO->cancel_date = 'null';
             $updatedContributionDAO->cancel_reason = NULL;
         }
         // update contribution status and total amount without trigger financial code
         // as this is handled in current BAO function used for change selection
         $updatedContributionDAO->id = $contributionId;
         if (!$skip) {
             $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
         }
         $updatedContributionDAO->total_amount = $updatedContributionDAO->net_amount = $updatedAmount;
         $updatedContributionDAO->fee_amount = 0;
         $updatedContributionDAO->tax_amount = $taxAmount;
         if (!empty($updateAmountLevel)) {
             $updatedContributionDAO->amount_level = $updateAmountLevel;
         }
         $updatedContributionDAO->save();
         // adjusted amount financial_trxn creation
         $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contributionId), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId);
         $adjustedTrxnValues = array('from_financial_account_id' => NULL, 'to_financial_account_id' => $toFinancialAccount, 'total_amount' => $balanceAmt, 'status_id' => $completedStatusId, 'payment_instrument_id' => $updatedContribution->payment_instrument_id, 'contribution_id' => $updatedContribution->id, 'trxn_date' => date('YmdHis'), 'currency' => $updatedContribution->currency);
         $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
     }
     return $adjustedTrxn;
 }
示例#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;
 }
示例#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);
 }
示例#9
0
 /**
  * Build select for Pledge.
  *
  * @param $query
  *
  * @return void
  */
 public static function select(&$query)
 {
     $statusId = implode(',', array_keys(CRM_Core_PseudoConstant::accountOptionValues("contribution_status", NULL, " AND v.name IN  ('Pending', 'Overdue')")));
     if ($query->_mode & CRM_Contact_BAO_Query::MODE_PLEDGE || !empty($query->_returnProperties['pledge_id'])) {
         $query->_select['pledge_id'] = 'civicrm_pledge.id as pledge_id';
         $query->_element['pledge_id'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     //add pledge select
     if (!empty($query->_returnProperties['pledge_amount'])) {
         $query->_select['pledge_amount'] = 'civicrm_pledge.amount as pledge_amount';
         $query->_element['pledge_amount'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_create_date'])) {
         $query->_select['pledge_create_date'] = 'civicrm_pledge.create_date as pledge_create_date';
         $query->_element['pledge_create_date'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_start_date'])) {
         $query->_select['pledge_start_date'] = 'civicrm_pledge.start_date as pledge_start_date';
         $query->_element['pledge_start_date'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_status_id'])) {
         $query->_select['pledge_status_id'] = 'pledge_status.value as pledge_status_id';
         $query->_element['pledge_status'] = 1;
         $query->_tables['pledge_status'] = $query->_whereTables['pledge_status'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_status'])) {
         $query->_select['pledge_status'] = 'pledge_status.label as pledge_status';
         $query->_element['pledge_status'] = 1;
         $query->_tables['pledge_status'] = $query->_whereTables['pledge_status'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_total_paid'])) {
         $query->_select['pledge_total_paid'] = ' (SELECT sum(civicrm_pledge_payment.actual_amount) FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id = 1 ) as pledge_total_paid';
         $query->_element['pledge_total_paid'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_next_pay_date'])) {
         $query->_select['pledge_next_pay_date'] = " (SELECT civicrm_pledge_payment.scheduled_date FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id IN ({$statusId}) ORDER BY civicrm_pledge_payment.scheduled_date ASC LIMIT 0, 1) as pledge_next_pay_date";
         $query->_element['pledge_next_pay_date'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_next_pay_amount'])) {
         $query->_select['pledge_next_pay_amount'] = " (SELECT civicrm_pledge_payment.scheduled_amount FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id IN ({$statusId}) ORDER BY civicrm_pledge_payment.scheduled_date ASC LIMIT 0, 1) as pledge_next_pay_amount";
         $query->_element['pledge_next_pay_amount'] = 1;
         $query->_select['pledge_outstanding_amount'] = " (SELECT sum(civicrm_pledge_payment.scheduled_amount) FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id = 6 ) as pledge_outstanding_amount";
         $query->_element['pledge_outstanding_amount'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_financial_type'])) {
         $query->_select['pledge_financial_type'] = "(SELECT civicrm_financial_type.name FROM civicrm_financial_type WHERE civicrm_financial_type.id = civicrm_pledge.financial_type_id) as pledge_financial_type";
         $query->_element['pledge_financial_type'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_contribution_page_id'])) {
         $query->_select['pledge_contribution_page_id'] = 'civicrm_pledge.contribution_page_id as pledge_contribution_page_id';
         $query->_element['pledge_contribution_page_id'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_id'])) {
         $query->_select['pledge_payment_id'] = 'civicrm_pledge_payment.id as pledge_payment_id';
         $query->_element['pledge_payment_id'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_scheduled_amount'])) {
         $query->_select['pledge_payment_scheduled_amount'] = 'civicrm_pledge_payment.scheduled_amount as pledge_payment_scheduled_amount';
         $query->_element['pledge_payment_scheduled_amount'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_scheduled_date'])) {
         $query->_select['pledge_payment_scheduled_date'] = 'civicrm_pledge_payment.scheduled_date as pledge_payment_scheduled_date';
         $query->_element['pledge_payment_scheduled_date'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_paid_amount'])) {
         $query->_select['pledge_payment_paid_amount'] = 'civicrm_pledge_payment.actual_amount as pledge_payment_paid_amount';
         $query->_element['pledge_payment_paid_amount'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_paid_date'])) {
         $query->_select['pledge_payment_paid_date'] = 'payment_contribution.receive_date as pledge_payment_paid_date';
         $query->_element['pledge_payment_paid_date'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
         $query->_tables['payment_contribution'] = $query->_whereTables['payment_contribution'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_reminder_date'])) {
         $query->_select['pledge_payment_reminder_date'] = 'civicrm_pledge_payment.reminder_date as pledge_payment_reminder_date';
         $query->_element['pledge_payment_reminder_date'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_reminder_count'])) {
         $query->_select['pledge_payment_reminder_count'] = 'civicrm_pledge_payment.reminder_count as pledge_payment_reminder_count';
         $query->_element['pledge_payment_reminder_count'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_status_id'])) {
         $query->_select['pledge_payment_status_id'] = 'payment_status.name as pledge_payment_status_id';
         $query->_element['pledge_payment_status_id'] = 1;
         $query->_tables['payment_status'] = $query->_whereTables['payment_status'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_payment_status'])) {
         $query->_select['pledge_payment_status'] = 'payment_status.label as pledge_payment_status';
         $query->_element['pledge_payment_status'] = 1;
         $query->_tables['payment_status'] = $query->_whereTables['payment_status'] = 1;
         $query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_frequency_interval'])) {
         $query->_select['pledge_frequency_interval'] = 'civicrm_pledge.frequency_interval as pledge_frequency_interval';
         $query->_element['pledge_frequency_interval'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_frequency_unit'])) {
         $query->_select['pledge_frequency_unit'] = 'civicrm_pledge.frequency_unit as pledge_frequency_unit';
         $query->_element['pledge_frequency_unit'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_is_test'])) {
         $query->_select['pledge_is_test'] = 'civicrm_pledge.is_test as pledge_is_test';
         $query->_element['pledge_is_test'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_campaign_id'])) {
         $query->_select['pledge_campaign_id'] = 'civicrm_pledge.campaign_id as pledge_campaign_id';
         $query->_element['pledge_campaign_id'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
     if (!empty($query->_returnProperties['pledge_currency'])) {
         $query->_select['pledge_currency'] = 'civicrm_pledge.currency as pledge_currency';
         $query->_element['pledge_currency'] = 1;
         $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
     }
 }
示例#10
0
 /**
  * Build the form object.
  *
  * @param bool $check
  */
 public function buildQuickForm($check = FALSE)
 {
     parent::buildQuickForm();
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_PaymentProcessor');
     $this->add('text', 'name', ts('Name'), $attributes['name'], TRUE);
     $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', array('CRM_Financial_DAO_PaymentProcessor', $this->_id, 'name', CRM_Core_Config::domainID()));
     $this->add('text', 'description', ts('Description'), $attributes['description']);
     $types = CRM_Core_PseudoConstant::paymentProcessorType();
     $this->add('select', 'payment_processor_type_id', ts('Payment Processor Type'), $types, TRUE, array('onchange' => "reload(true)"));
     // Financial Account of account type asset CRM-11515
     $accountType = CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name = 'Asset' ");
     $financialAccount = CRM_Contribute_PseudoConstant::financialAccount(NULL, key($accountType));
     if ($fcount = count($financialAccount)) {
         $this->assign('financialAccount', $fcount);
     }
     $this->add('select', 'financial_account_id', ts('Financial Account'), array('' => ts('- select -')) + $financialAccount, TRUE);
     $this->addSelect('payment_instrument_id', array('entity' => 'contribution', 'label' => ts('Payment Method'), 'placeholder' => NULL));
     // is this processor active ?
     $this->add('checkbox', 'is_active', ts('Is this Payment Processor active?'));
     $this->add('checkbox', 'is_default', ts('Is this Payment Processor the default?'));
     $creditCardTypes = CRM_Contribute_PseudoConstant::creditCard();
     $this->addCheckBox('accept_credit_cards', ts('Accepted Credit Card Type(s)'), $creditCardTypes, NULL, NULL, NULL, NULL, '&nbsp;&nbsp;&nbsp;');
     foreach ($this->_fields as $field) {
         if (empty($field['label'])) {
             continue;
         }
         $this->add('text', $field['name'], $field['label'], $attributes[$field['name']]);
         $this->add('text', "test_{$field['name']}", $field['label'], $attributes[$field['name']]);
         if (!empty($field['rule'])) {
             $this->addRule($field['name'], $field['msg'], $field['rule']);
             $this->addRule("test_{$field['name']}", $field['msg'], $field['rule']);
         }
     }
     $this->addFormRule(array('CRM_Admin_Form_PaymentProcessor', 'formRule'));
 }
 /**
  * Browse all Financial Type Account data
  *
  * @return void
  * @access public
  * @static
  */
 function browse()
 {
     // get all Financial Type Account data sorted by weight
     $financialType = array();
     $params = array();
     $dao = new CRM_Financial_DAO_EntityFinancialAccount();
     $params['entity_id'] = $this->_aid;
     $params['entity_table'] = 'civicrm_financial_type';
     if ($this->_aid) {
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $this->_title = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_aid, 'name');
         CRM_Utils_System::setTitle($this->_title . ' - ' . ts('Assigned Financial Accounts'));
         $financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id');
         $accountRelationship = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
         $dao->copyValues($params);
         $dao->find();
         while ($dao->fetch()) {
             $financialType[$dao->id] = array();
             CRM_Core_DAO::storeValues($dao, $financialType[$dao->id]);
             $params = array('id' => $dao->financial_account_id);
             $defaults = array();
             $financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params, $defaults);
             if (!empty($financialAccount)) {
                 $financialType[$dao->id]['financial_account'] = $financialAccount->name;
                 $financialType[$dao->id]['accounting_code'] = $financialAccount->accounting_code;
                 $financialType[$dao->id]['account_type_code'] = $financialAccount->account_type_code;
                 $financialType[$dao->id]['is_active'] = $financialAccount->is_active;
                 if (!empty($financialAccount->contact_id)) {
                     $financialType[$dao->id]['owned_by'] = CRM_Contact_BAO_Contact::displayName($financialAccount->contact_id);
                 }
                 if (!empty($financialAccount->financial_account_type_id)) {
                     $optionGroupName = 'financial_account_type';
                     $financialType[$dao->id]['financial_account_type'] = CRM_Utils_Array::value($financialAccount->financial_account_type_id, $financialAccountType);
                 }
                 if (!empty($dao->account_relationship)) {
                     $optionGroupName = 'account_relationship';
                     $financialType[$dao->id]['account_relationship'] = CRM_Utils_Array::value($dao->account_relationship, $accountRelationship);
                 }
             }
             // form all action links
             $action = array_sum(array_keys($this->links()));
             $links = self::links();
             //CRM-12492
             if ($dao->account_relationship == $relationTypeId) {
                 unset($links[CRM_Core_Action::DELETE]);
             }
             $financialType[$dao->id]['action'] = CRM_Core_Action::formLink($links, $action, array('id' => $dao->id, 'aid' => $dao->entity_id), ts('more'), FALSE, 'financialTypeAccount.manage.action', 'FinancialTypeAccount', $dao->id);
         }
         $this->assign('rows', $financialType);
         $this->assign('aid', $this->_aid);
         $this->assign('financialTypeTitle', $this->_title);
     } else {
         CRM_Core_Error::fatal();
         return null;
     }
 }
示例#12
0
 /**
  * fetch financial type having relationship as Income Account is.
  *
  *
  * @return array
  *   all financial type with income account is relationship
  */
 public static function getIncomeFinancialType()
 {
     // Financial Type
     $financialType = CRM_Contribute_PseudoConstant::financialType();
     $revenueFinancialType = array();
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
     CRM_Core_PseudoConstant::populate($revenueFinancialType, 'CRM_Financial_DAO_EntityFinancialAccount', $all = TRUE, $retrieve = 'entity_id', $filter = NULL, "account_relationship = {$relationTypeId} AND entity_table = 'civicrm_financial_type' ");
     foreach ($financialType as $key => $financialTypeName) {
         if (!in_array($key, $revenueFinancialType) || CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && !CRM_Core_Permission::check('add contributions of type ' . $financialTypeName)) {
             unset($financialType[$key]);
         }
     }
     return $financialType;
 }
 /**
  * Helper function to create deferred financial account.
  */
 public function _createDeferredFinancialAccount()
 {
     $params = array('name' => 'TestFinancialAccount_1', 'accounting_code' => 4800, 'contact_id' => 1, 'is_deductible' => 0, 'is_active' => 1, 'is_reserved' => 0);
     $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', $params);
     $params['name'] = 'test_financialType1';
     $financialType = $this->callAPISuccess('FinancialType', 'create', $params);
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
     $financialParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $financialType['id'], 'account_relationship' => $relationTypeId, 'financial_account_id' => $financialAccount['id']);
     $this->callAPISuccess('EntityFinancialAccount', 'create', $financialParams);
     $result = $this->assertDBNotNull('CRM_Financial_DAO_EntityFinancialAccount', $financialAccount['id'], 'entity_id', 'financial_account_id', 'Database check on added financial type record.');
     $this->assertEquals($result, $financialType['id'], 'Verify Account Type');
     return $result;
 }
示例#14
0
 /**
  * @param $updatedAmount
  * @param $paidAmount
  * @param $contributionId
  */
 static function recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId)
 {
     $balanceAmt = $updatedAmount - $paidAmount;
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
     $pendngRefundStatusId = array_search('Pending refund', $contributionStatuses);
     $completedStatusId = array_search('Completed', $contributionStatuses);
     $updatedContributionDAO = new CRM_Contribute_BAO_Contribution();
     if ($balanceAmt) {
         if ($balanceAmt > 0 && $paidAmount != 0) {
             $contributionStatusVal = $partiallyPaidStatusId;
         } elseif ($balanceAmt < 0 && $paidAmount != 0) {
             $contributionStatusVal = $pendngRefundStatusId;
         } elseif ($paidAmount == 0) {
             $contributionStatusVal = $completedStatusId;
             $updatedContributionDAO->cancel_date = 'null';
             $updatedContributionDAO->cancel_reason = NULL;
         }
         // update contribution status and total amount without trigger financial code
         // as this is handled in current BAO function used for change selection
         $updatedContributionDAO->id = $contributionId;
         $updatedContributionDAO->contribution_status_id = $contributionStatusVal;
         $updatedContributionDAO->total_amount = $updatedAmount;
         $updatedContributionDAO->save();
         $ftDetail = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
         // adjusted amount financial_trxn creation
         if (empty($ftDetail['trxn_id'])) {
             $updatedContribution = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contributionId), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
             $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
             $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($updatedContribution->financial_type_id, $relationTypeId);
             $adjustedTrxnValues = array('from_financial_account_id' => NULL, 'to_financial_account_id' => $toFinancialAccount, 'total_amount' => $balanceAmt, 'status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'), 'payment_instrument_id' => $updatedContribution->payment_instrument_id, 'contribution_id' => $updatedContribution->id, 'trxn_date' => date('YmdHis'), 'currency' => $updatedContribution->currency);
             $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
         } else {
             // update the financial trxn amount as well, as the fee selections has been updated
             if ($balanceAmt != $ftDetail['total_amount']) {
                 CRM_Core_DAO::setFieldValue('CRM_Core_BAO_FinancialTrxn', $ftDetail['trxn_id'], 'total_amount', $balanceAmt);
             }
         }
     }
 }
示例#15
0
 /**
  * Get AR account.
  *
  * @param $financialAccountId
  *   Financial account id.
  *
  * @param $financialAccountTypeId
  *   Financial account type id.
  *
  * @param string $accountTypeCode
  *   account type code
  *
  * @return int
  *   count
  */
 public static function getARAccounts($financialAccountId, $financialAccountTypeId = NULL, $accountTypeCode = 'ar')
 {
     if (!$financialAccountTypeId) {
         $financialAccountType = CRM_Core_PseudoConstant::accountOptionValues('financial_account_type');
         $financialAccountTypeId = array_search('Asset', $financialAccountType);
     }
     $query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2\n      AND id != %3 AND is_active = 1;";
     $params = array(1 => array($financialAccountTypeId, 'Integer'), 2 => array(strtolower($accountTypeCode), 'String'), 3 => array($financialAccountId, 'Integer'));
     return CRM_Core_DAO::singleValueQuery($query, $params);
 }
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 public function preProcess()
 {
     $this->_aid = CRM_Utils_Request::retrieve('aid', 'Positive', $this);
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     if (!$this->_id && $this->_action & CRM_Core_Action::UPDATE) {
         $this->_id = CRM_Utils_Type::escape($this->_id, 'Positive');
     }
     $url = CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', "reset=1&action=browse&aid={$this->_aid}");
     $this->_BAOName = 'CRM_Financial_BAO_FinancialTypeAccount';
     if ($this->_aid && $this->_action & CRM_Core_Action::ADD) {
         $this->_title = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_aid, 'name');
         CRM_Utils_System::setTitle($this->_title . ' - ' . ts('Financial Accounts'));
         $session = CRM_Core_Session::singleton();
         $session->pushUserContext($url);
     }
     // CRM-12492
     if (!($this->_action & CRM_Core_Action::ADD)) {
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $accountRelationship = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $this->_id, 'account_relationship');
         if ($accountRelationship == $relationTypeId) {
             $this->_isARFlag = TRUE;
             if ($this->_action & CRM_Core_Action::DELETE) {
                 CRM_Core_Session::setStatus(ts("Selected financial type account with 'Accounts Receivable Account is' account relationship cannot be deleted."), '', 'error');
                 CRM_Utils_System::redirect($url);
             }
         }
     }
     if ($this->_id) {
         $financialAccount = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $this->_id, 'financial_account_id');
         $fieldTitle = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $financialAccount, 'name');
         CRM_Utils_System::setTitle($fieldTitle . ' - ' . ts('Financial Type Accounts'));
     }
     $breadCrumb = array(array('title' => ts('Financial Type Accounts'), 'url' => $url));
     CRM_Utils_System::appendBreadCrumb($breadCrumb);
 }
 /**
  * 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');
 }
 /**
  * Function to validate financial type
  *
  * CRM-13231
  *
  * @param integer $financialTypeId Financial Type id
  *
  * @access public
  * @static
  */
 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is')
 {
     $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
     $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
     if (!$financialAccount) {
         return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
     }
     return FALSE;
 }
示例#19
0
 /**
  * checks db values for financial item
  */
 public function checkItemValues($contribution)
 {
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
     $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType(4, $relationTypeId);
     $query = "SELECT eft1.entity_id, ft.total_amount, eft1.amount FROM civicrm_financial_trxn ft INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution') \nINNER JOIN civicrm_entity_financial_trxn eft1 ON (eft1.financial_trxn_id = eft.financial_trxn_id AND eft1.entity_table = 'civicrm_financial_item')\nWHERE eft.entity_id = %1 AND ft.to_financial_account_id <> %2";
     $queryParams[1] = array($contribution->id, 'Integer');
     $queryParams[2] = array($toFinancialAccount, 'Integer');
     $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
     $amounts = array(100.0, 50.0);
     while ($dao->fetch()) {
         $this->assertEquals(150.0, $dao->total_amount, 'Mismatch of total amount paid.');
         $this->assertEquals($dao->amount, array_pop($amounts), 'Mismatch of amount proportionally assigned to financial item');
     }
     Contact::delete($this->_contactId);
     Event::delete($this->_eventId);
 }
示例#20
0
 /**
  * Function to create default entity financial accounts
  * for financial type
  * CRM-12470
  *
  * @param int $financialTypeId financial type id
  *
  * @static
  */
 static function createDefaultFinancialAccounts($financialType)
 {
     $titles = array();
     $financialAccountTypeID = CRM_Core_PseudoConstant::accountOptionValues('financial_account_type');
     $accountRelationship = CRM_Core_PseudoConstant::accountOptionValues('account_relationship');
     $relationships = array(array_search('Accounts Receivable Account is', $accountRelationship) => array_search('Asset', $financialAccountTypeID), array_search('Expense Account is', $accountRelationship) => array_search('Expenses', $financialAccountTypeID), array_search('Cost of Sales Account is', $accountRelationship) => array_search('Cost of Sales', $financialAccountTypeID), array_search('Income Account is', $accountRelationship) => array_search('Revenue', $financialAccountTypeID));
     $params = array('name' => $financialType->name, 'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', CRM_Core_Config::domainID(), 'contact_id'), 'financial_account_type_id' => array_search('Revenue', $financialAccountTypeID), 'description' => $financialType->description, 'account_type_code' => 'INC', 'is_active' => 1);
     $financialAccount = CRM_Financial_BAO_FinancialAccount::add($params, CRM_Core_DAO::$_nullArray);
     $params = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $financialType->id);
     foreach ($relationships as $key => $value) {
         if ($accountRelationship[$key] == 'Accounts Receivable Account is') {
             $params['financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', 'Accounts Receivable', 'id', 'name');
             if (!empty($params['financial_account_id'])) {
                 $titles[] = 'Accounts Receivable';
             } else {
                 $query = "SELECT financial_account_id, name FROM civicrm_entity_financial_account\n            LEFT JOIN civicrm_financial_account ON civicrm_financial_account.id = civicrm_entity_financial_account.financial_account_id\n            WHERE account_relationship = {$key} AND entity_table = 'civicrm_financial_type' LIMIT 1";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 $dao->fetch();
                 $params['financial_account_id'] = $dao->financial_account_id;
                 $titles[] = $dao->name;
             }
         } elseif ($accountRelationship[$key] == 'Income Account is') {
             $params['financial_account_id'] = $financialAccount->id;
         } else {
             $query = "SELECT id, name FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = {$value}";
             $dao = CRM_Core_DAO::executeQuery($query);
             $dao->fetch();
             $params['financial_account_id'] = $dao->id;
             $titles[] = $dao->name;
         }
         $params['account_relationship'] = $key;
         self::add($params);
     }
     return $titles;
 }
示例#21
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'];
 }
示例#22
0
 public function postProcess()
 {
     $this->beginPostProcess();
     // get the acl clauses built before we assemble the query
     $this->buildACLClause($this->_aliases['civicrm_contact']);
     $sql = $this->buildQuery();
     $rows = $payment = array();
     $dao = CRM_Core_DAO::executeQuery($sql);
     // Set pager for the Main Query only which displays basic information
     $this->setPager();
     $this->assign('columnHeaders', $this->_columnHeaders);
     while ($dao->fetch()) {
         $pledgeID = $dao->civicrm_pledge_id;
         foreach ($this->_columnHeaders as $columnHeadersKey => $columnHeadersValue) {
             $row = array();
             if (property_exists($dao, $columnHeadersKey)) {
                 $display[$pledgeID][$columnHeadersKey] = $dao->{$columnHeadersKey};
             }
         }
         $pledgeIDArray[] = $pledgeID;
     }
     // Add Special headers
     $this->_columnHeaders['scheduled_date'] = array('type' => CRM_Utils_Type::T_DATE, 'title' => 'Next Payment Due');
     $this->_columnHeaders['scheduled_amount'] = array('type' => CRM_Utils_Type::T_MONEY, 'title' => 'Next Payment Amount');
     $this->_columnHeaders['status_id'] = NULL;
     /*
      * this is purely about ordering the total paid & balance due fields off to the end
      * of the table in case custom or address fields cause them to fall in the middle
      * (arguably the pledge amount should be moved to after these fields too)
      *
      */
     $tableHeaders = array('civicrm_pledge_payment_total_paid', 'civicrm_pledge_payment_balance_due');
     foreach ($tableHeaders as $header) {
         //per above, unset & reset them so they move to the end
         if (isset($this->_columnHeaders[$header])) {
             $headervalue = $this->_columnHeaders[$header];
             unset($this->_columnHeaders[$header]);
             $this->_columnHeaders[$header] = $headervalue;
         }
     }
     // To Display Payment Details of pledged amount
     // for pledge payments In Progress
     if (!empty($display)) {
         $statusId = array_keys(CRM_Core_PseudoConstant::accountOptionValues("contribution_status", NULL, " AND v.name IN  ('Pending', 'Overdue')"));
         $statusId = implode(',', $statusId);
         $sqlPayment = "\n                 SELECT min(payment.scheduled_date) as scheduled_date,\n                        payment.pledge_id,\n                        payment.scheduled_amount,\n                        pledge.contact_id\n\n                  FROM civicrm_pledge_payment payment\n                       LEFT JOIN civicrm_pledge pledge\n                                 ON pledge.id = payment.pledge_id\n\n                  WHERE payment.status_id IN ({$statusId})\n\n                  GROUP BY payment.pledge_id";
         $daoPayment = CRM_Core_DAO::executeQuery($sqlPayment);
         while ($daoPayment->fetch()) {
             foreach ($pledgeIDArray as $key => $val) {
                 if ($val == $daoPayment->pledge_id) {
                     $display[$daoPayment->pledge_id]['scheduled_date'] = $daoPayment->scheduled_date;
                     $display[$daoPayment->pledge_id]['scheduled_amount'] = $daoPayment->scheduled_amount;
                 }
             }
         }
     }
     // Displaying entire data on the form
     if (!empty($display)) {
         foreach ($display as $key => $value) {
             $row = array();
             foreach ($this->_columnHeaders as $columnKey => $columnValue) {
                 if (array_key_exists($columnKey, $value)) {
                     $row[$columnKey] = !empty($value[$columnKey]) ? $value[$columnKey] : '';
                 }
             }
             $rows[] = $row;
         }
     }
     unset($this->_columnHeaders['status_id']);
     unset($this->_columnHeaders['civicrm_pledge_id']);
     unset($this->_columnHeaders['civicrm_pledge_contact_id']);
     $this->formatDisplay($rows, FALSE);
     $this->doTemplateAssignment($rows);
     $this->endPostProcess($rows);
 }
示例#23
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);
 }
 /**
  * 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();
     $errorFlag = FALSE;
     if ($self->_action == CRM_Core_Action::DELETE) {
         $relationValues = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
         if (CRM_Utils_Array::value('financial_account_id', $values) != 'select') {
             if ($relationValues[$values['account_relationship']] == 'Premiums Inventory Account is' || $relationValues[$values['account_relationship']] == 'Cost of Sales Account is') {
                 $premiumsProduct = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PremiumsProduct', $values['financial_type_id'], 'product_id', 'financial_type_id');
                 $product = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Product', $values['financial_type_id'], 'name', 'financial_type_id');
                 if (!empty($premiumsProduct) || !empty($product)) {
                     $errorMsg['account_relationship'] = 'You cannot remove ' . $relationValues[$values['account_relationship']] . ' relationship while the Financial Type is used for a Premium.';
                 }
             }
         }
     }
     if (CRM_Utils_Array::value('account_relationship', $values) == 'select') {
         $errorMsg['account_relationship'] = 'Financial Account relationship is a required field.';
     }
     if (CRM_Utils_Array::value('financial_account_id', $values) == 'select') {
         $errorMsg['financial_account_id'] = 'Financial Account is a required field.';
     }
     if (!empty($values['account_relationship']) && !empty($values['financial_account_id'])) {
         $params = array('account_relationship' => $values['account_relationship'], 'entity_id' => $self->_aid);
         $defaults = array();
         if ($self->_action == CRM_Core_Action::ADD) {
             $relationshipId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
             $isTax = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $values['financial_account_id'], 'is_tax');
             if ($values['account_relationship'] == $relationshipId) {
                 if (!$isTax) {
                     $errorMsg['financial_account_id'] = ts('Is Tax? must be set for respective financial account');
                 }
             }
             $result = CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
             if ($result) {
                 $errorFlag = TRUE;
             }
         }
         if ($self->_action == CRM_Core_Action::UPDATE) {
             if ($values['account_relationship'] == $self->_defaultValues['account_relationship'] && $values['financial_account_id'] == $self->_defaultValues['financial_account_id']) {
                 $errorFlag = FALSE;
             } else {
                 $params['financial_account_id'] = $values['financial_account_id'];
                 $result = CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
                 if ($result) {
                     $errorFlag = TRUE;
                 }
             }
         }
         if ($errorFlag) {
             $errorMsg['account_relationship'] = ts('This account relationship already exits');
         }
     }
     return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
 }
示例#25
0
 /**
  * to fetch financial type having relationship as Income Account is
  *
  *
  * @return array  all financial type with income account is relationship
  * @static
  */
 static function getIncomeFinancialType()
 {
     // Financial Type
     $financialType = CRM_Contribute_PseudoConstant::financialType();
     $revenueFinancialType = array();
     $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
     CRM_Core_PseudoConstant::populate($revenueFinancialType, 'CRM_Financial_DAO_EntityFinancialAccount', $all = True, $retrieve = 'entity_id', $filter = null, "account_relationship = {$relationTypeId} AND entity_table = 'civicrm_financial_type' ");
     foreach ($financialType as $key => $financialTypeName) {
         if (!in_array($key, $revenueFinancialType)) {
             unset($financialType[$key]);
         }
     }
     return $financialType;
 }
示例#26
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);
 }
示例#27
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');
     }
 }
 /**
  * @return bool
  */
 public function createFinancialRecords()
 {
     $upgrade = new CRM_Upgrade_Form();
     // update civicrm_entity_financial_trxn.amount = civicrm_financial_trxn.total_amount
     $query = "\nUPDATE    civicrm_entity_financial_trxn ceft\nLEFT JOIN civicrm_financial_trxn cft ON cft.id = ceft.financial_trxn_id\nSET       ceft.amount = total_amount\nWHERE     cft.net_amount IS NOT NULL\nAND       ceft.entity_table = 'civicrm_contribution'\n";
     CRM_Core_DAO::executeQuery($query);
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $completedStatus = array_search('Completed', $contributionStatus);
     $pendingStatus = array_search('Pending', $contributionStatus);
     $cancelledStatus = array_search('Cancelled', $contributionStatus);
     $queryParams = array(1 => array($completedStatus, 'Integer'), 2 => array($pendingStatus, 'Integer'), 3 => array($cancelledStatus, 'Integer'));
     $accountType = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name = 'Asset' "));
     $query = "\nSELECT id\nFROM   civicrm_financial_account\nWHERE  is_default = 1\nAND    financial_account_type_id = {$accountType}\n";
     $financialAccountId = CRM_Core_DAO::singleValueQuery($query);
     $accountRelationsips = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', CRM_Core_DAO::$_nullArray, 'validate');
     $accountsReceivableAccount = array_search('Accounts Receivable Account is', $accountRelationsips);
     $incomeAccountIs = array_search('Income Account is', $accountRelationsips);
     $assetAccountIs = array_search('Asset Account is', $accountRelationsips);
     $expenseAccountIs = array_search('Expense Account is', $accountRelationsips);
     $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id', CRM_Core_DAO::$_nullArray, 'validate');
     $unpaidStatus = array_search('Unpaid', $financialItemStatus);
     $paidStatus = array_search('Paid', $financialItemStatus);
     $validCurrencyCodes = CRM_Core_PseudoConstant::currencyCode();
     $validCurrencyCodes = implode("','", $validCurrencyCodes);
     $config = CRM_Core_Config::singleton();
     $defaultCurrency = $config->defaultCurrency;
     $now = date('YmdHis');
     //adding financial_trxn records and entity_financial_trxn records related to contribution
     //Add temp column for easy entry in entity_financial_trxn
     $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN contribution_id INT DEFAULT NULL";
     CRM_Core_DAO::executeQuery($sql);
     //pending pay later status handling
     $sql = "\nINSERT INTO civicrm_financial_trxn\n       (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id,\n       check_number, to_financial_account_id, from_financial_account_id, trxn_date)\nSELECT con.id as contribution_id, con.payment_instrument_id,\n       IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,\n       con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,\n       con.check_number, efa.financial_account_id as to_financial_account_id, NULL as from_financial_account_id,\n        REPLACE(REPLACE(REPLACE(\n          CASE\n            WHEN con.receive_date IS NOT NULL THEN\n                con.receive_date\n            WHEN con.receipt_date IS NOT NULL THEN\n                con.receipt_date\n            ELSE\n                {$now}\n          END\n        , '-', ''), ':', ''), ' ', '') as trxn_date\nFROM  civicrm_contribution con\n      LEFT JOIN civicrm_entity_financial_account efa\n             ON (con.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'\n                 AND efa.account_relationship = {$accountsReceivableAccount})\nWHERE con.is_pay_later = 1\nAND   con.contribution_status_id = {$pendingStatus}\n";
     CRM_Core_DAO::executeQuery($sql);
     //create a temp table to hold financial account id related to payment instruments
     $tempTableName1 = CRM_Core_DAO::createTempTableName();
     $sql = "\nCREATE TEMPORARY TABLE {$tempTableName1}\nSELECT     ceft.financial_account_id financial_account_id, cov.value as instrument_id\nFROM       civicrm_entity_financial_account ceft\nINNER JOIN civicrm_option_value cov ON cov.id = ceft.entity_id AND ceft.entity_table = 'civicrm_option_value'\nINNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id\nWHERE      cog.name = 'payment_instrument'\n";
     CRM_Core_DAO::executeQuery($sql);
     //CRM-12141
     $sql = "ALTER TABLE {$tempTableName1} ADD INDEX index_instrument_id (instrument_id(200));";
     CRM_Core_DAO::executeQuery($sql);
     //create temp table to process completed / cancelled contribution
     $tempTableName2 = CRM_Core_DAO::createTempTableName();
     $sql = "\nCREATE TEMPORARY TABLE {$tempTableName2}\nSELECT con.id as contribution_id, con.payment_instrument_id,\n       IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,\n       con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,\n       con.check_number, NULL as from_financial_account_id,\n       REPLACE(REPLACE(REPLACE(\n          CASE\n            WHEN con.receive_date IS NOT NULL THEN\n                con.receive_date\n            WHEN con.receipt_date IS NOT NULL THEN\n                con.receipt_date\n            ELSE\n                {$now}\n          END\n       , '-', ''), ':', ''), ' ', '') as trxn_date,\n       CASE\n         WHEN con.payment_instrument_id IS NULL THEN\n              {$financialAccountId}\n         WHEN con.payment_instrument_id IS NOT NULL THEN\n              tpi.financial_account_id\n       END as to_financial_account_id,\n       IF(eft.financial_trxn_id IS NULL, 'insert', eft.financial_trxn_id) as action\nFROM      civicrm_contribution con\nLEFT JOIN civicrm_entity_financial_trxn eft\n       ON (eft.entity_table = 'civicrm_contribution' AND eft.entity_id = con.id)\nLEFT JOIN {$tempTableName1} tpi\n       ON con.payment_instrument_id = tpi.instrument_id\nWHERE     con.contribution_status_id IN ({$completedStatus}, {$cancelledStatus})\n";
     CRM_Core_DAO::executeQuery($sql);
     // CRM-12141
     $sql = "ALTER TABLE {$tempTableName2} ADD INDEX index_action (action);";
     CRM_Core_DAO::executeQuery($sql);
     //handling for completed contribution and cancelled contribution
     //insertion of new records
     $sql = "\nINSERT INTO civicrm_financial_trxn\n            (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,\n            to_financial_account_id, from_financial_account_id, trxn_date)\nSELECT   tempI.contribution_id, tempI.payment_instrument_id, tempI.currency, tempI.total_amount, tempI.net_amount,\n         tempI.fee_amount,    tempI.trxn_id,   tempI.contribution_status_id, tempI.check_number,\n         tempI.to_financial_account_id, tempI.from_financial_account_id, tempI.trxn_date\nFROM {$tempTableName2} tempI\nWHERE tempI.action = 'insert'\n";
     CRM_Core_DAO::executeQuery($sql);
     //update of existing records
     $sql = "\nUPDATE civicrm_financial_trxn ft\n       INNER JOIN {$tempTableName2} tempU\n               ON (tempU.action != 'insert' AND ft.id = tempU.action)\nSET   ft.from_financial_account_id  = NULL,\n      ft.to_financial_account_id    = tempU.to_financial_account_id,\n      ft.status_id                  = tempU.contribution_status_id,\n      ft.payment_instrument_id      = tempU.payment_instrument_id,\n      ft.check_number               = tempU.check_number,\n      ft.contribution_id            = tempU.contribution_id;";
     CRM_Core_DAO::executeQuery($sql);
     //insert the -ve transaction rows for cancelled contributions
     $sql = "\nINSERT INTO civicrm_financial_trxn\n            (contribution_id, payment_instrument_id, currency, total_amount,     net_amount, fee_amount, trxn_id, status_id,\n            check_number,    to_financial_account_id, from_financial_account_id, trxn_date)\nSELECT ft.contribution_id, ft.payment_instrument_id, ft.currency, -ft.total_amount, ft.net_amount, ft.fee_amount, ft.trxn_id,\n       ft.status_id, ft.check_number, ft.to_financial_account_id, ft.from_financial_account_id, ft.trxn_date\nFROM   civicrm_financial_trxn ft\nWHERE  ft.status_id = {$cancelledStatus};";
     CRM_Core_DAO::executeQuery($sql);
     //inserting entity financial trxn entries if its not present in entity_financial_trxn for completed and pending contribution statuses
     //this also handles +ve and -ve both transaction entries for a cancelled contribution
     $sql = "\nINSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)\nSELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount as amount\nFROM   civicrm_financial_trxn ft\nWHERE  contribution_id IS NOT NULL AND\n       ft.id NOT IN (SELECT financial_trxn_id\n                     FROM civicrm_entity_financial_trxn\n                     WHERE entity_table = 'civicrm_contribution'\n                     AND entity_id      = ft.contribution_id)";
     CRM_Core_DAO::executeQuery($sql);
     //end of adding financial_trxn records and entity_financial_trxn records related to contribution
     //update all linked line_item rows
     // set line_item.financial_type_id = contribution.financial_type_id if contribution page id is null and not participant line item
     // set line_item.financial_type_id = price_field_value.financial_type_id if contribution page id is set and not participant line item
     // set line_item.financial_type_id = event.financial_type_id if its participant line item and line_item.price_field_value_id is null
     // set line_item.financial_type_id = price_field_value.financial_type_id if its participant line item and line_item.price_field_value_id is set
     $updateLineItemSql = "\nUPDATE civicrm_line_item li\n       LEFT JOIN civicrm_contribution con\n              ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')\n       LEFT JOIN civicrm_price_field_value cpfv\n              ON li.price_field_value_id = cpfv.id\n       LEFT JOIN civicrm_participant cp\n              ON (li.entity_id = cp.id AND li.entity_table = 'civicrm_participant')\n       LEFT JOIN civicrm_event ce\n              ON ce.id = cp.event_id\nSET    li.financial_type_id = CASE\n         WHEN (con.contribution_page_id IS NULL || li.price_field_value_id IS NULL) AND cp.id IS NULL THEN\n           con.financial_type_id\n         WHEN (con.contribution_page_id IS NOT NULL AND cp.id IS NULL) || (cp.id IS NOT NULL AND  li.price_field_value_id IS NOT NULL) THEN\n           cpfv.financial_type_id\n         WHEN cp.id IS NOT NULL AND  li.price_field_value_id IS NULL THEN\n           ce.financial_type_id\n       END";
     CRM_Core_DAO::executeQuery($updateLineItemSql, $queryParams);
     //add the financial_item entries
     //add a temp column so that inserting entity_financial_trxn entries gets easy
     $sql = "ALTER TABLE civicrm_financial_item ADD COLUMN f_trxn_id INT DEFAULT NULL";
     CRM_Core_DAO::executeQuery($sql);
     //add financial_item entries for contribution  completed / pending pay later / cancelled
     $contributionlineItemSql = "\nINSERT INTO civicrm_financial_item\n           (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)\n\nSELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,\n       IF(ft.total_amount < 0 AND con.contribution_status_id = %3, -li.line_total, li.line_total) as line_total, con.currency, 'civicrm_line_item',\n       li.id as line_item_id, li.label as line_item_label,\n       IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id, efa.financial_account_id as financial_account_id,\n       ft.id as f_trxn_id\nFROM  civicrm_line_item li\n      INNER JOIN civicrm_contribution con\n              ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')\n      INNER JOIN civicrm_financial_trxn ft\n              ON (con.id = ft.contribution_id)\n      LEFT  JOIN civicrm_entity_financial_account efa\n              ON (li.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'\n                  AND efa.account_relationship = {$incomeAccountIs})\nWHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
     CRM_Core_DAO::executeQuery($contributionlineItemSql, $queryParams);
     //add financial_item entries for event
     $participantLineItemSql = "\nINSERT INTO civicrm_financial_item\n           (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)\n\nSELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,\n       IF(ft.total_amount < 0 AND con.contribution_status_id = %3, -li.line_total, li.line_total) as line_total,\n         con.currency, 'civicrm_line_item', li.id as line_item_id, li.label as line_item_label,\n       IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id,\n          efa.financial_account_id as financial_account_id, ft.id as f_trxn_id\nFROM  civicrm_line_item li\n      INNER JOIN civicrm_participant par\n              ON (li.entity_id = par.id AND li.entity_table = 'civicrm_participant')\n      INNER JOIN civicrm_participant_payment pp\n              ON (pp.participant_id = par.id)\n      INNER JOIN civicrm_contribution con\n              ON (pp.contribution_id = con.id)\n      INNER JOIN civicrm_financial_trxn ft\n              ON (con.id = ft.contribution_id)\n      LEFT  JOIN civicrm_entity_financial_account efa\n              ON (li.financial_type_id = efa.entity_id AND\n                  efa.entity_table = 'civicrm_financial_type' AND efa.account_relationship = {$incomeAccountIs})\nWHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
     CRM_Core_DAO::executeQuery($participantLineItemSql, $queryParams);
     //fee handling for contributions
     //insert fee entries in financial_trxn for contributions
     $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN is_fee TINYINT DEFAULT NULL";
     CRM_Core_DAO::executeQuery($sql);
     $sql = "\nINSERT INTO civicrm_financial_trxn\n            (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,\n             to_financial_account_id, from_financial_account_id, trxn_date, payment_processor_id, is_fee)\n\nSELECT con.id, ft.payment_instrument_id, ft.currency, ft.fee_amount, NULL, NULL, ft.trxn_id, %1 as status_id,\n       ft.check_number, efaFT.financial_account_id as to_financial_account_id, CASE\n         WHEN efaPP.financial_account_id IS NOT NULL THEN\n              efaPP.financial_account_id\n         WHEN tpi.financial_account_id   IS NOT NULL THEN\n              tpi.financial_account_id\n         ELSE\n              {$financialAccountId}\n       END    as from_financial_account_id, ft.trxn_date, ft.payment_processor_id, 1 as is_fee\nFROM   civicrm_contribution con\n       INNER JOIN civicrm_financial_trxn ft\n               ON (ft.contribution_id = con.id)\n       LEFT  JOIN civicrm_entity_financial_account efaFT\n               ON (con.financial_type_id = efaFT.entity_id AND efaFT.entity_table = 'civicrm_financial_type'\n                   AND efaFT.account_relationship = {$expenseAccountIs})\n       LEFT  JOIN civicrm_entity_financial_account efaPP\n               ON (ft.payment_processor_id = efaPP.entity_id AND efaPP.entity_table = 'civicrm_payment_processor'\n                   AND efaPP.account_relationship = {$assetAccountIs})\n       LEFT  JOIN {$tempTableName1} tpi\n               ON ft.payment_instrument_id = tpi.instrument_id\nWHERE  ft.fee_amount IS NOT NULL AND ft.fee_amount != 0 AND (con.contribution_status_id IN (%1, %3) OR (con.contribution_status_id =%2 AND con.is_pay_later = 1))\nGROUP  BY con.id";
     CRM_Core_DAO::executeQuery($sql, $queryParams);
     //link financial_trxn to contribution
     $sql = "\nINSERT INTO civicrm_entity_financial_trxn\n            (entity_table, entity_id, financial_trxn_id, amount)\nSELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount\nFROM   civicrm_financial_trxn ft\nWHERE ft.is_fee = 1";
     CRM_Core_DAO::executeQuery($sql);
     //add fee related entries to financial item table
     $domainId = CRM_Core_Config::domainID();
     $domainContactId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id');
     $sql = "\nINSERT INTO civicrm_financial_item\n            (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)\nSELECT ft.trxn_date, {$domainContactId} as contact_id, ft.total_amount, ft.currency, 'civicrm_financial_trxn', ft.id,\n       'Fee', {$paidStatus} as status_id, ft.to_financial_account_id as financial_account_id, ft.id as f_trxn_id\nFROM   civicrm_financial_trxn ft\nWHERE  ft.is_fee = 1;";
     CRM_Core_DAO::executeQuery($sql);
     //add entries to entity_financial_trxn table
     $sql = "\nINSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)\nSELECT 'civicrm_financial_item' as entity_table, fi.id as entity_id, fi.f_trxn_id as financial_trxn_id, fi.amount\nFROM   civicrm_financial_item fi";
     CRM_Core_DAO::executeQuery($sql);
     //drop the temparory columns
     $sql = "ALTER TABLE civicrm_financial_trxn\n                  DROP COLUMN contribution_id,\n                  DROP COLUMN  is_fee;";
     CRM_Core_DAO::executeQuery($sql);
     $sql = "ALTER TABLE civicrm_financial_item DROP f_trxn_id";
     CRM_Core_DAO::executeQuery($sql);
     return TRUE;
 }
 static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL)
 {
     $value = NULL;
     if (empty($entityName)) {
         return $value;
     }
     if ($entityName == 'participant') {
         $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
         $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
         if ($contributionId && $financialTypeId) {
             $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
             $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
             $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $relationTypeId);
             if (empty($lineItemTotal)) {
                 $lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($entityId, 'civicrm_participant');
             }
             $sqlFtTotalAmt = "\nSELECT SUM(ft.total_amount)\nFROM civicrm_financial_trxn ft\n  LEFT JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution')\n  LEFT JOIN civicrm_contribution c ON (eft.entity_id = c.id)\n  LEFT JOIN civicrm_participant_payment pp ON (pp.contribution_id = c.id)\nWHERE pp.participant_id = {$entityId} AND ft.to_financial_account_id != {$toFinancialAccount}\n  AND ft.status_id = {$statusId}\n";
             $ftTotalAmt = CRM_Core_DAO::singleValueQuery($sqlFtTotalAmt);
             $value = 0;
             if ($ftTotalAmt) {
                 $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
             }
             if ($returnType) {
                 $value = array();
                 if ($paymentVal < 0) {
                     $value['refund_due'] = $paymentVal;
                 } elseif ($paymentVal > 0) {
                     $value['amount_owed'] = $paymentVal;
                 } elseif ($lineItemTotal == $ftTotalAmt) {
                     $value['full_paid'] = $ftTotalAmt;
                 }
             }
         }
     }
     return $value;
 }
 static function recordAdditionPayment($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);
         $trxnId = $trxnId['trxn_id'];
         // 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
             $contributionUpdate['id'] = $contributionId;
             $contributionUpdate['contribution_status_id'] = $statusId;
             $contributionUpdate['skipLineItem'] = TRUE;
             // 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'
             $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
             if ($participantId) {
                 // update participant status
                 $participantUpdate['id'] = $participantId;
                 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
                 $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);
             $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 = {$trxnId}\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'];
         $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);
         $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
             $participantUpdate['id'] = $participantId;
             $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
             $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';
         // creation of activity
         $activity = new CRM_Activity_DAO_Activity();
         $activity->source_record_id = $financialTrxn->id;
         $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name');
         if (!$activity->find(TRUE)) {
             self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component);
         }
     }
     return $financialTrxn;
 }