3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Financial_BAO_FinancialAccount
extends CRM_Financial_DAO_FinancialAccount
{
22 public function __construct() {
23 parent
::__construct();
27 * Fetch object based on array of properties.
29 * @param array $params
30 * (reference ) an assoc array of name/value pairs.
31 * @param array $defaults
32 * (reference ) an assoc array to hold the flattened values.
34 * @return CRM_Financial_BAO_FinancialAccount
36 public static function retrieve(&$params, &$defaults = []) {
37 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
38 $financialAccount->copyValues($params);
39 if ($financialAccount->find(TRUE)) {
40 CRM_Core_DAO
::storeValues($financialAccount, $defaults);
41 return $financialAccount;
47 * Update the is_active flag in the db.
50 * Id of the database record.
51 * @param bool $is_active
52 * Value we want to set the is_active field.
55 * true if we found and updated the object, else false
57 public static function setIsActive($id, $is_active) {
58 return CRM_Core_DAO
::setFieldValue('CRM_Financial_DAO_FinancialAccount', $id, 'is_active', $is_active);
62 * Add the financial types.
64 * @param array $params
65 * Reference array contains the values submitted by the form.
67 * @return CRM_Financial_DAO_FinancialAccount
69 public static function add(&$params) {
70 if (empty($params['id'])) {
71 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
72 $params['is_deductible'] = CRM_Utils_Array
::value('is_deductible', $params, FALSE);
73 $params['is_tax'] = CRM_Utils_Array
::value('is_tax', $params, FALSE);
74 $params['is_header_account'] = CRM_Utils_Array
::value('is_header_account', $params, FALSE);
75 $params['is_default'] = CRM_Utils_Array
::value('is_default', $params, FALSE);
77 if (!empty($params['id'])
78 && !empty($params['financial_account_type_id'])
79 && CRM_Financial_BAO_FinancialAccount
::validateFinancialAccount(
81 $params['financial_account_type_id']
84 throw new CRM_Core_Exception(ts('You cannot change the account type since this financial account refers to a financial item having an account type of Revenue/Liability.'));
86 if (!empty($params['is_default'])) {
87 $query = 'UPDATE civicrm_financial_account SET is_default = 0 WHERE financial_account_type_id = %1';
88 $queryParams = [1 => [$params['financial_account_type_id'], 'Integer']];
89 CRM_Core_DAO
::executeQuery($query, $queryParams);
92 // action is taken depending upon the mode
93 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
97 if (!empty($params['id'])) {
100 CRM_Utils_Hook
::pre($op, 'FinancialAccount', CRM_Utils_Array
::value('id', $params), $params);
102 if (!empty($params['id'])) {
103 $financialAccount->id
= $params['id'];
104 $financialAccount->find(TRUE);
107 $financialAccount->copyValues($params);
108 $financialAccount->save();
112 if (!empty($params['id'])) {
115 CRM_Utils_Hook
::post($op, 'FinancialAccount', $financialAccount->id
, $financialAccount);
117 return $financialAccount;
121 * Delete financial Types.
123 * @param int $financialAccountId
125 public static function del($financialAccountId) {
126 // checking if financial type is present
131 ['Core', 'FinancialTrxn', 'to_financial_account_id'],
132 ['Financial', 'FinancialTypeAccount', 'financial_account_id'],
133 ['Financial', 'FinancialItem', 'financial_account_id'],
135 foreach ($dependency as $name) {
136 require_once str_replace('_', DIRECTORY_SEPARATOR
, "CRM_" . $name[0] . "_BAO_" . $name[1]) . ".php";
137 $className = "CRM_{$name[0]}_BAO_{$name[1]}";
138 $bao = new $className();
139 $bao->{$name[2]} = $financialAccountId;
140 if ($bao->find(TRUE)) {
146 CRM_Core_Session
::setStatus(ts('This financial account cannot be deleted since it is being used as a header account. Please remove it from being a header account before trying to delete it again.'));
150 // delete from financial Type table
151 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
152 $financialAccount->id
= $financialAccountId;
153 $financialAccount->delete();
158 * Get accounting code for a financial type with account relation Income Account is.
160 * @param int $financialTypeId
165 public static function getAccountingCode($financialTypeId) {
166 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
167 $query = "SELECT cfa.accounting_code
168 FROM civicrm_financial_type cft
169 LEFT JOIN civicrm_entity_financial_account cefa ON cefa.entity_id = cft.id AND cefa.entity_table = 'civicrm_financial_type'
170 LEFT JOIN civicrm_financial_account cfa ON cefa.financial_account_id = cfa.id
172 AND account_relationship = %2";
174 1 => [$financialTypeId, 'Integer'],
175 2 => [$relationTypeId, 'Integer'],
177 return CRM_Core_DAO
::singleValueQuery($query, $params);
183 * @param $financialAccountId
184 * Financial account id.
186 * @param $financialAccountTypeId
187 * Financial account type id.
189 * @param string $accountTypeCode
195 public static function getARAccounts($financialAccountId, $financialAccountTypeId = NULL, $accountTypeCode = 'ar') {
196 if (!$financialAccountTypeId) {
197 $financialAccountTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
199 $query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2
200 AND id != %3 AND is_active = 1;";
202 1 => [$financialAccountTypeId, 'Integer'],
203 2 => [strtolower($accountTypeCode), 'String'],
204 3 => [$financialAccountId, 'Integer'],
206 return CRM_Core_DAO
::singleValueQuery($query, $params);
210 * Get the Financial Account for a Financial Type Relationship Combo.
212 * Note that some relationships are optionally configured - so far
213 * Chargeback and Credit / Contra. Since these are the only 2 currently Income
214 * is an appropriate fallback. In future it might make sense to extend the logic.
216 * Note that we avoid the CRM_Core_PseudoConstant function as it stores one
217 * account per financial type and is unreliable.
219 * @param int $financialTypeID
221 * @param string $relationshipType
225 public static function getFinancialAccountForFinancialTypeByRelationship($financialTypeID, $relationshipType) {
226 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationshipType}' "));
228 if (!isset(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
229 $accounts = civicrm_api3('EntityFinancialAccount', 'get', [
230 'entity_id' => $financialTypeID,
231 'entity_table' => 'civicrm_financial_type',
234 foreach ($accounts['values'] as $account) {
235 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$account['account_relationship']] = $account['financial_account_id'];
238 $accountRelationships = CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL);
240 $incomeAccountRelationshipID = array_search('Income Account is', $accountRelationships);
241 $incomeAccountFinancialAccountID = Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$incomeAccountRelationshipID];
243 foreach (['Chargeback Account is', 'Credit/Contra Revenue Account is'] as $optionalAccountRelationship) {
245 $accountRelationshipID = array_search($optionalAccountRelationship, $accountRelationships);
246 if (empty(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$accountRelationshipID])) {
247 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$accountRelationshipID] = $incomeAccountFinancialAccountID;
250 if (!isset(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
251 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId] = NULL;
254 return Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId];
258 * Get the sales tax financial account id for the financial type id.
260 * This is a helper wrapper to make the function name more readable.
262 * @param int $financialAccountID
266 public static function getSalesTaxFinancialAccount($financialAccountID) {
267 return self
::getFinancialAccountForFinancialTypeByRelationship($financialAccountID, 'Sales Tax Account is');
271 * Get Financial Account type relations.
278 public static function getfinancialAccountRelations($flip = FALSE) {
279 $params = ['labelColumn' => 'name'];
280 $financialAccountType = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
281 $accountRelationships = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
283 'Expense Account is' => 'Expenses',
284 'Accounts Receivable Account is' => 'Asset',
285 'Income Account is' => 'Revenue',
286 'Asset Account is' => 'Asset',
287 'Cost of Sales Account is' => 'Cost of Sales',
288 'Premiums Inventory Account is' => 'Asset',
289 'Discounts Account is' => 'Revenue',
290 'Sales Tax Account is' => 'Liability',
291 'Deferred Revenue Account is' => 'Liability',
294 foreach ($Links as $accountRelation => $accountType) {
295 $financialAccountLinks[array_search($accountRelation, $accountRelationships)] = array_search($accountType, $financialAccountType);
299 foreach ($Links as $accountRelation => $accountType) {
300 $financialAccountLinks[array_search($accountType, $financialAccountType)][] = array_search($accountRelation, $accountRelationships);
303 return $financialAccountLinks;
307 * Get Deferred Financial type.
312 public static function getDeferredFinancialType() {
313 $deferredFinancialType = [];
314 $query = "SELECT ce.entity_id, cft.name FROM civicrm_entity_financial_account ce
315 INNER JOIN civicrm_financial_type cft ON ce.entity_id = cft.id
316 WHERE ce.entity_table = 'civicrm_financial_type' AND ce.account_relationship = %1 AND cft.is_active = 1";
317 $deferredAccountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
318 $queryParams = [1 => [$deferredAccountRel, 'Integer']];
319 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
320 while ($dao->fetch()) {
321 $deferredFinancialType[$dao->entity_id
] = $dao->name
;
323 return $deferredFinancialType;
327 * Check if financial account is referenced by financial item.
329 * @param int $financialAccountId
331 * @param int $financialAccountTypeID
336 public static function validateFinancialAccount($financialAccountId, $financialAccountTypeID = NULL) {
337 $sql = "SELECT f.financial_account_type_id FROM civicrm_financial_account f
338 INNER JOIN civicrm_financial_item fi ON fi.financial_account_id = f.id
339 WHERE f.id = %1 AND f.financial_account_type_id IN (%2)
341 $params = ['labelColumn' => 'name'];
342 $financialAccountType = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
344 1 => [$financialAccountId, 'Integer'],
348 array_search('Revenue', $financialAccountType),
349 array_search('Liability', $financialAccountType),
355 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
356 if ($result && $result != $financialAccountTypeID) {
363 * Validate Financial Type has Deferred Revenue account relationship
364 * with Financial Account.
366 * @param array $params
367 * Holds submitted formvalues and params from api for updating/adding contribution.
369 * @param int $contributionID
372 * @param array $priceSetFields
373 * Array of price fields of a price set.
378 public static function checkFinancialTypeHasDeferred($params, $contributionID = NULL, $priceSetFields = NULL) {
379 if (!Civi
::settings()->get('deferred_revenue_enabled')) {
382 $recognitionDate = $params['revenue_recognition_date'] ??
NULL;
383 if (!(!CRM_Utils_System
::isNull($recognitionDate)
384 ||
($contributionID && isset($params['prevContribution'])
385 && !CRM_Utils_System
::isNull($params['prevContribution']->revenue_recognition_date
)))
390 $lineItems = $params['line_item'] ??
NULL;
391 $financialTypeID = $params['financial_type_id'] ??
NULL;
392 if (!$financialTypeID) {
393 $financialTypeID = $params['prevContribution']->financial_type_id
;
395 if (($contributionID ||
!empty($params['price_set_id'])) && empty($lineItems)) {
396 if (!$contributionID) {
397 CRM_Price_BAO_PriceSet
::processAmount($priceSetFields,
401 $items = CRM_Price_BAO_LineItem
::getLineItems($contributionID, 'contribution', TRUE, TRUE, TRUE);
403 if (!empty($items)) {
404 $lineItems[] = $items;
407 $deferredFinancialType = self
::getDeferredFinancialType();
409 if (!empty($lineItems)) {
410 foreach ($lineItems as $lineItem) {
411 foreach ($lineItem as $items) {
412 if (!array_key_exists($items['financial_type_id'], $deferredFinancialType)) {
418 elseif (!array_key_exists($financialTypeID, $deferredFinancialType)) {
423 $error = ts('Revenue Recognition Date cannot be processed unless there is a Deferred Revenue account setup for the Financial Type. Please remove Revenue Recognition Date, select a different Financial Type with a Deferred Revenue account setup for it, or setup a Deferred Revenue account for this Financial Type.');
424 throw new CRM_Core_Exception($error);
430 * Retrieve all Deferred Financial Accounts.
433 * @return array of Deferred Financial Account
436 public static function getAllDeferredFinancialAccount() {
437 $financialAccount = [];
438 $result = civicrm_api3('EntityFinancialAccount', 'get', [
440 'return' => ["financial_account_id.id", "financial_account_id.name", "financial_account_id.accounting_code"],
441 'entity_table' => "civicrm_financial_type",
442 'account_relationship' => "Deferred Revenue Account is",
444 if ($result['count'] > 0) {
445 foreach ($result['values'] as $key => $value) {
446 $financialAccount[$value['financial_account_id.id']] = $value['financial_account_id.name'] . ' (' . $value['financial_account_id.accounting_code'] . ')';
449 return $financialAccount;
453 * Get Organization Name associated with Financial Account.
455 * @param bool $checkPermissions
460 public static function getOrganizationNames($checkPermissions = TRUE) {
461 $result = civicrm_api3('FinancialAccount', 'get', [
462 'return' => ["contact_id.organization_name", "contact_id"],
463 'contact_id.is_deleted' => 0,
464 'options' => ['limit' => 0],
465 'check_permissions' => $checkPermissions,
467 $organizationNames = [];
468 foreach ($result['values'] as $values) {
469 $organizationNames[$values['contact_id']] = $values['contact_id.organization_name'];
471 return $organizationNames;