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);
116 CRM_Core_PseudoConstant
::flush();
118 return $financialAccount;
122 * Delete financial Types.
124 * @param int $financialAccountId
126 public static function del($financialAccountId) {
127 // checking if financial type is present
132 ['Core', 'FinancialTrxn', 'to_financial_account_id'],
133 ['Financial', 'FinancialTypeAccount', 'financial_account_id'],
134 ['Financial', 'FinancialItem', 'financial_account_id'],
136 foreach ($dependency as $name) {
137 require_once str_replace('_', DIRECTORY_SEPARATOR
, "CRM_" . $name[0] . "_BAO_" . $name[1]) . ".php";
138 $className = "CRM_{$name[0]}_BAO_{$name[1]}";
139 $bao = new $className();
140 $bao->{$name[2]} = $financialAccountId;
141 if ($bao->find(TRUE)) {
147 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.'));
151 // delete from financial Type table
152 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
153 $financialAccount->id
= $financialAccountId;
154 $financialAccount->delete();
159 * Get accounting code for a financial type with account relation Income Account is.
161 * @param int $financialTypeId
166 public static function getAccountingCode($financialTypeId) {
167 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
168 $query = "SELECT cfa.accounting_code
169 FROM civicrm_financial_type cft
170 LEFT JOIN civicrm_entity_financial_account cefa ON cefa.entity_id = cft.id AND cefa.entity_table = 'civicrm_financial_type'
171 LEFT JOIN civicrm_financial_account cfa ON cefa.financial_account_id = cfa.id
173 AND account_relationship = %2";
175 1 => [$financialTypeId, 'Integer'],
176 2 => [$relationTypeId, 'Integer'],
178 return CRM_Core_DAO
::singleValueQuery($query, $params);
184 * @param $financialAccountId
185 * Financial account id.
187 * @param $financialAccountTypeId
188 * Financial account type id.
190 * @param string $accountTypeCode
196 public static function getARAccounts($financialAccountId, $financialAccountTypeId = NULL, $accountTypeCode = 'ar') {
197 if (!$financialAccountTypeId) {
198 $financialAccountTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
200 $query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2
201 AND id != %3 AND is_active = 1;";
203 1 => [$financialAccountTypeId, 'Integer'],
204 2 => [strtolower($accountTypeCode), 'String'],
205 3 => [$financialAccountId, 'Integer'],
207 return CRM_Core_DAO
::singleValueQuery($query, $params);
211 * Get the Financial Account for a Financial Type Relationship Combo.
213 * Note that some relationships are optionally configured - so far
214 * Chargeback and Credit / Contra. Since these are the only 2 currently Income
215 * is an appropriate fallback. In future it might make sense to extend the logic.
217 * Note that we avoid the CRM_Core_PseudoConstant function as it stores one
218 * account per financial type and is unreliable.
219 * @todo Not sure what the above comment means, and the function uses the
220 * PseudoConstant twice. Three times if you count the for loop.
222 * @param int $financialTypeID
224 * @param string $relationshipType
228 public static function getFinancialAccountForFinancialTypeByRelationship($financialTypeID, $relationshipType) {
229 // This is keyed on the `value` column from civicrm_option_value
230 $accountRelationshipsByValue = CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, NULL, 'name');
231 // We look up by the name a couple times below, so flip it.
232 $accountRelationships = array_flip($accountRelationshipsByValue);
234 $relationTypeId = $accountRelationships[$relationshipType] ??
NULL;
236 if (!isset(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
237 $accounts = civicrm_api3('EntityFinancialAccount', 'get', [
238 'entity_id' => $financialTypeID,
239 'entity_table' => 'civicrm_financial_type',
242 foreach ($accounts['values'] as $account) {
243 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$account['account_relationship']] = $account['financial_account_id'];
246 $incomeAccountRelationshipID = $accountRelationships['Income Account is'] ??
FALSE;
247 $incomeAccountFinancialAccountID = Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$incomeAccountRelationshipID];
249 foreach (['Chargeback Account is', 'Credit/Contra Revenue Account is'] as $optionalAccountRelationship) {
251 $accountRelationshipID = $accountRelationships[$optionalAccountRelationship] ??
FALSE;
252 if (empty(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$accountRelationshipID])) {
253 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$accountRelationshipID] = $incomeAccountFinancialAccountID;
256 if (!isset(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
257 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId] = NULL;
260 return Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId];
264 * Get the sales tax financial account id for the financial type id.
266 * This is a helper wrapper to make the function name more readable.
268 * @param int $financialAccountID
272 public static function getSalesTaxFinancialAccount($financialAccountID) {
273 return self
::getFinancialAccountForFinancialTypeByRelationship($financialAccountID, 'Sales Tax Account is');
277 * Get Financial Account type relations.
284 public static function getfinancialAccountRelations($flip = FALSE) {
285 $params = ['labelColumn' => 'name'];
286 $financialAccountType = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
287 $accountRelationships = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
289 'Expense Account is' => 'Expenses',
290 'Accounts Receivable Account is' => 'Asset',
291 'Income Account is' => 'Revenue',
292 'Asset Account is' => 'Asset',
293 'Cost of Sales Account is' => 'Cost of Sales',
294 'Premiums Inventory Account is' => 'Asset',
295 'Discounts Account is' => 'Revenue',
296 'Sales Tax Account is' => 'Liability',
297 'Deferred Revenue Account is' => 'Liability',
300 foreach ($Links as $accountRelation => $accountType) {
301 $financialAccountLinks[array_search($accountRelation, $accountRelationships)] = array_search($accountType, $financialAccountType);
305 foreach ($Links as $accountRelation => $accountType) {
306 $financialAccountLinks[array_search($accountType, $financialAccountType)][] = array_search($accountRelation, $accountRelationships);
309 return $financialAccountLinks;
313 * Get Deferred Financial type.
318 public static function getDeferredFinancialType() {
319 $deferredFinancialType = [];
320 $query = "SELECT ce.entity_id, cft.name FROM civicrm_entity_financial_account ce
321 INNER JOIN civicrm_financial_type cft ON ce.entity_id = cft.id
322 WHERE ce.entity_table = 'civicrm_financial_type' AND ce.account_relationship = %1 AND cft.is_active = 1";
323 $deferredAccountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
324 $queryParams = [1 => [$deferredAccountRel, 'Integer']];
325 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
326 while ($dao->fetch()) {
327 $deferredFinancialType[$dao->entity_id
] = $dao->name
;
329 return $deferredFinancialType;
333 * Check if financial account is referenced by financial item.
335 * @param int $financialAccountId
337 * @param int $financialAccountTypeID
342 public static function validateFinancialAccount($financialAccountId, $financialAccountTypeID = NULL) {
343 $sql = "SELECT f.financial_account_type_id FROM civicrm_financial_account f
344 INNER JOIN civicrm_financial_item fi ON fi.financial_account_id = f.id
345 WHERE f.id = %1 AND f.financial_account_type_id IN (%2)
347 $params = ['labelColumn' => 'name'];
348 $financialAccountType = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
350 1 => [$financialAccountId, 'Integer'],
354 array_search('Revenue', $financialAccountType),
355 array_search('Liability', $financialAccountType),
361 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
362 if ($result && $result != $financialAccountTypeID) {
369 * Validate Financial Type has Deferred Revenue account relationship
370 * with Financial Account.
372 * @param array $params
373 * Holds submitted formvalues and params from api for updating/adding contribution.
375 * @param int $contributionID
378 * @param array $orderLineItems
379 * The line items from the Order.
384 public static function checkFinancialTypeHasDeferred($params, $contributionID = NULL, $orderLineItems = []) {
385 if (!Civi
::settings()->get('deferred_revenue_enabled')) {
388 $recognitionDate = $params['revenue_recognition_date'] ??
NULL;
389 if (!(!CRM_Utils_System
::isNull($recognitionDate)
390 ||
($contributionID && isset($params['prevContribution'])
391 && !CRM_Utils_System
::isNull($params['prevContribution']->revenue_recognition_date
)))
396 $lineItems = $params['line_item'] ??
NULL;
397 $financialTypeID = $params['financial_type_id'] ??
NULL;
398 if (!$financialTypeID) {
399 $financialTypeID = $params['prevContribution']->financial_type_id
;
401 if (($contributionID ||
!empty($params['price_set_id'])) && empty($lineItems)) {
402 $lineItems[] = $orderLineItems;
404 $deferredFinancialType = self
::getDeferredFinancialType();
406 if (!empty($lineItems)) {
407 foreach ($lineItems as $lineItem) {
408 foreach ($lineItem as $items) {
409 if (!array_key_exists($items['financial_type_id'], $deferredFinancialType)) {
415 elseif (!array_key_exists($financialTypeID, $deferredFinancialType)) {
420 $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.');
421 throw new CRM_Core_Exception($error);
427 * Retrieve all Deferred Financial Accounts.
430 * @return array of Deferred Financial Account
433 public static function getAllDeferredFinancialAccount() {
434 $financialAccount = [];
435 $result = civicrm_api3('EntityFinancialAccount', 'get', [
437 'return' => ["financial_account_id.id", "financial_account_id.name", "financial_account_id.accounting_code"],
438 'entity_table' => "civicrm_financial_type",
439 'account_relationship' => "Deferred Revenue Account is",
441 if ($result['count'] > 0) {
442 foreach ($result['values'] as $key => $value) {
443 $financialAccount[$value['financial_account_id.id']] = $value['financial_account_id.name'] . ' (' . $value['financial_account_id.accounting_code'] . ')';
446 return $financialAccount;
450 * Get Organization Name associated with Financial Account.
452 * @param bool $checkPermissions
457 public static function getOrganizationNames($checkPermissions = TRUE) {
458 $result = civicrm_api3('FinancialAccount', 'get', [
459 'return' => ["contact_id.organization_name", "contact_id"],
460 'contact_id.is_deleted' => 0,
461 'options' => ['limit' => 0],
462 'check_permissions' => $checkPermissions,
464 $organizationNames = [];
465 foreach ($result['values'] as $values) {
466 $organizationNames[$values['contact_id']] = $values['contact_id.organization_name'];
468 return $organizationNames;