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
implements \Civi\Test\HookInterface
{
20 * Fetch object based on array of properties.
22 * @param array $params
23 * (reference ) an assoc array of name/value pairs.
24 * @param array $defaults
25 * (reference ) an assoc array to hold the flattened values.
27 * @return CRM_Financial_BAO_FinancialAccount
29 public static function retrieve(&$params, &$defaults = []) {
30 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
31 $financialAccount->copyValues($params);
32 if ($financialAccount->find(TRUE)) {
33 CRM_Core_DAO
::storeValues($financialAccount, $defaults);
34 return $financialAccount;
40 * Update the is_active flag in the db.
43 * Id of the database record.
44 * @param bool $is_active
45 * Value we want to set the is_active field.
48 * true if we found and updated the object, else false
50 public static function setIsActive($id, $is_active) {
51 return CRM_Core_DAO
::setFieldValue('CRM_Financial_DAO_FinancialAccount', $id, 'is_active', $is_active);
55 * Add the financial types.
57 * @param array $params
58 * Reference array contains the values submitted by the form.
60 * @return CRM_Financial_DAO_FinancialAccount
62 public static function add(&$params) {
63 if (empty($params['id'])) {
64 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
65 $params['is_deductible'] = CRM_Utils_Array
::value('is_deductible', $params, FALSE);
66 $params['is_tax'] = CRM_Utils_Array
::value('is_tax', $params, FALSE);
67 $params['is_header_account'] = CRM_Utils_Array
::value('is_header_account', $params, FALSE);
68 $params['is_default'] = CRM_Utils_Array
::value('is_default', $params, FALSE);
70 if (!empty($params['id'])
71 && !empty($params['financial_account_type_id'])
72 && CRM_Financial_BAO_FinancialAccount
::validateFinancialAccount(
74 $params['financial_account_type_id']
77 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.'));
79 if (!empty($params['is_default'])) {
80 $query = 'UPDATE civicrm_financial_account SET is_default = 0 WHERE financial_account_type_id = %1';
81 $queryParams = [1 => [$params['financial_account_type_id'], 'Integer']];
82 CRM_Core_DAO
::executeQuery($query, $queryParams);
85 // action is taken depending upon the mode
86 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
90 if (!empty($params['id'])) {
93 CRM_Utils_Hook
::pre($op, 'FinancialAccount', CRM_Utils_Array
::value('id', $params), $params);
95 if (!empty($params['id'])) {
96 $financialAccount->id
= $params['id'];
97 $financialAccount->find(TRUE);
100 $financialAccount->copyValues($params);
101 $financialAccount->save();
105 if (!empty($params['id'])) {
108 CRM_Utils_Hook
::post($op, 'FinancialAccount', $financialAccount->id
, $financialAccount);
109 CRM_Core_PseudoConstant
::flush();
111 return $financialAccount;
115 * Delete financial Types.
118 * @param int $financialAccountId
120 public static function del($financialAccountId) {
122 static::deleteRecord(['id' => $financialAccountId]);
125 catch (CRM_Core_Exception
$e) {
126 // FIXME: Setting status messages within a BAO CRUD function is bad bad bad. But this fn is deprecated so who cares.
127 CRM_Core_Session
::setStatus($e->getMessage(), ts('Delete Error'), 'error');
133 * Callback for hook_civicrm_pre().
134 * @param \Civi\Core\Event\PreEvent $event
135 * @throws CRM_Core_Exception
137 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent
$event) {
138 if ($event->action
=== 'delete') {
139 // Check dependencies before deleting
141 ['Core', 'FinancialTrxn', 'to_financial_account_id'],
142 ['Financial', 'FinancialTypeAccount', 'financial_account_id'],
143 ['Financial', 'FinancialItem', 'financial_account_id'],
145 foreach ($dependency as $name) {
146 $className = "CRM_{$name[0]}_BAO_{$name[1]}";
147 $bao = new $className();
148 $bao->{$name[2]} = $event->id
;
149 if ($bao->find(TRUE)) {
150 throw new CRM_Core_Exception(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.'));
157 * Get accounting code for a financial type with account relation Income Account is.
159 * @param int $financialTypeId
164 public static function getAccountingCode($financialTypeId) {
165 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
166 $query = "SELECT cfa.accounting_code
167 FROM civicrm_financial_type cft
168 LEFT JOIN civicrm_entity_financial_account cefa ON cefa.entity_id = cft.id AND cefa.entity_table = 'civicrm_financial_type'
169 LEFT JOIN civicrm_financial_account cfa ON cefa.financial_account_id = cfa.id
171 AND account_relationship = %2";
173 1 => [$financialTypeId, 'Integer'],
174 2 => [$relationTypeId, 'Integer'],
176 return CRM_Core_DAO
::singleValueQuery($query, $params);
182 * @param $financialAccountId
183 * Financial account id.
185 * @param $financialAccountTypeId
186 * Financial account type id.
188 * @param string $accountTypeCode
194 public static function getARAccounts($financialAccountId, $financialAccountTypeId = NULL, $accountTypeCode = 'ar') {
195 if (!$financialAccountTypeId) {
196 $financialAccountTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
198 $query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2
199 AND id != %3 AND is_active = 1;";
201 1 => [$financialAccountTypeId, 'Integer'],
202 2 => [strtolower($accountTypeCode), 'String'],
203 3 => [$financialAccountId, 'Integer'],
205 return CRM_Core_DAO
::singleValueQuery($query, $params);
209 * Get the Financial Account for a Financial Type Relationship Combo.
211 * Note that some relationships are optionally configured - so far
212 * Chargeback and Credit / Contra. Since these are the only 2 currently Income
213 * is an appropriate fallback. In future it might make sense to extend the logic.
215 * Note that we avoid the CRM_Core_PseudoConstant function as it stores one
216 * account per financial type and is unreliable.
217 * @todo Not sure what the above comment means, and the function uses the
218 * PseudoConstant twice. Three times if you count the for loop.
220 * @param int $financialTypeID
222 * @param string $relationshipType
226 public static function getFinancialAccountForFinancialTypeByRelationship($financialTypeID, $relationshipType) {
227 // This is keyed on the `value` column from civicrm_option_value
228 $accountRelationshipsByValue = CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, NULL, 'name');
229 // We look up by the name a couple times below, so flip it.
230 $accountRelationships = array_flip($accountRelationshipsByValue);
232 $relationTypeId = $accountRelationships[$relationshipType] ??
NULL;
234 if (!isset(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
235 $accounts = civicrm_api3('EntityFinancialAccount', 'get', [
236 'entity_id' => $financialTypeID,
237 'entity_table' => 'civicrm_financial_type',
240 foreach ($accounts['values'] as $account) {
241 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$account['account_relationship']] = $account['financial_account_id'];
244 $incomeAccountRelationshipID = $accountRelationships['Income Account is'] ??
FALSE;
245 $incomeAccountFinancialAccountID = Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$incomeAccountRelationshipID];
247 foreach (['Chargeback Account is', 'Credit/Contra Revenue Account is'] as $optionalAccountRelationship) {
249 $accountRelationshipID = $accountRelationships[$optionalAccountRelationship] ??
FALSE;
250 if (empty(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$accountRelationshipID])) {
251 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$accountRelationshipID] = $incomeAccountFinancialAccountID;
254 if (!isset(Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
255 Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId] = NULL;
258 return Civi
::$statics[__CLASS__
]['entity_financial_account'][$financialTypeID][$relationTypeId];
262 * Get the sales tax financial account id for the financial type id.
264 * This is a helper wrapper to make the function name more readable.
266 * @param int $financialAccountID
270 public static function getSalesTaxFinancialAccount($financialAccountID) {
271 return self
::getFinancialAccountForFinancialTypeByRelationship($financialAccountID, 'Sales Tax Account is');
275 * Get Financial Account type relations.
282 public static function getfinancialAccountRelations($flip = FALSE) {
283 $params = ['labelColumn' => 'name'];
284 $financialAccountType = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
285 $accountRelationships = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
287 'Expense Account is' => 'Expenses',
288 'Accounts Receivable Account is' => 'Asset',
289 'Income Account is' => 'Revenue',
290 'Asset Account is' => 'Asset',
291 'Cost of Sales Account is' => 'Cost of Sales',
292 'Premiums Inventory Account is' => 'Asset',
293 'Discounts Account is' => 'Revenue',
294 'Sales Tax Account is' => 'Liability',
295 'Deferred Revenue Account is' => 'Liability',
298 foreach ($Links as $accountRelation => $accountType) {
299 $financialAccountLinks[array_search($accountRelation, $accountRelationships)] = array_search($accountType, $financialAccountType);
303 foreach ($Links as $accountRelation => $accountType) {
304 $financialAccountLinks[array_search($accountType, $financialAccountType)][] = array_search($accountRelation, $accountRelationships);
307 return $financialAccountLinks;
311 * Get Deferred Financial type.
316 public static function getDeferredFinancialType() {
317 $deferredFinancialType = [];
318 $query = "SELECT ce.entity_id, cft.name FROM civicrm_entity_financial_account ce
319 INNER JOIN civicrm_financial_type cft ON ce.entity_id = cft.id
320 WHERE ce.entity_table = 'civicrm_financial_type' AND ce.account_relationship = %1 AND cft.is_active = 1";
321 $deferredAccountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
322 $queryParams = [1 => [$deferredAccountRel, 'Integer']];
323 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
324 while ($dao->fetch()) {
325 $deferredFinancialType[$dao->entity_id
] = $dao->name
;
327 return $deferredFinancialType;
331 * Check if financial account is referenced by financial item.
333 * @param int $financialAccountId
335 * @param int $financialAccountTypeID
340 public static function validateFinancialAccount($financialAccountId, $financialAccountTypeID = NULL) {
341 $sql = "SELECT f.financial_account_type_id FROM civicrm_financial_account f
342 INNER JOIN civicrm_financial_item fi ON fi.financial_account_id = f.id
343 WHERE f.id = %1 AND f.financial_account_type_id IN (%2)
345 $params = ['labelColumn' => 'name'];
346 $financialAccountType = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
348 1 => [$financialAccountId, 'Integer'],
352 array_search('Revenue', $financialAccountType),
353 array_search('Liability', $financialAccountType),
359 $result = CRM_Core_DAO
::singleValueQuery($sql, $params);
360 if ($result && $result != $financialAccountTypeID) {
367 * Validate Financial Type has Deferred Revenue account relationship
368 * with Financial Account.
370 * @param array $params
371 * Holds submitted formvalues and params from api for updating/adding contribution.
373 * @param int $contributionID
376 * @param array $orderLineItems
377 * The line items from the Order.
382 public static function checkFinancialTypeHasDeferred($params, $contributionID = NULL, $orderLineItems = []) {
383 if (!Civi
::settings()->get('deferred_revenue_enabled')) {
386 $recognitionDate = $params['revenue_recognition_date'] ??
NULL;
387 if (!(!CRM_Utils_System
::isNull($recognitionDate)
388 ||
($contributionID && isset($params['prevContribution'])
389 && !CRM_Utils_System
::isNull($params['prevContribution']->revenue_recognition_date
)))
394 $lineItems = $params['line_item'] ??
NULL;
395 $financialTypeID = $params['financial_type_id'] ??
NULL;
396 if (!$financialTypeID) {
397 $financialTypeID = $params['prevContribution']->financial_type_id
;
399 if (($contributionID ||
!empty($params['price_set_id'])) && empty($lineItems)) {
400 $lineItems[] = $orderLineItems;
402 $deferredFinancialType = self
::getDeferredFinancialType();
404 if (!empty($lineItems)) {
405 foreach ($lineItems as $lineItem) {
406 foreach ($lineItem as $items) {
407 if (!array_key_exists($items['financial_type_id'], $deferredFinancialType)) {
413 elseif (!array_key_exists($financialTypeID, $deferredFinancialType)) {
418 $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.');
419 throw new CRM_Core_Exception($error);
425 * Retrieve all Deferred Financial Accounts.
428 * @return array of Deferred Financial Account
431 public static function getAllDeferredFinancialAccount() {
432 $financialAccount = [];
433 $result = civicrm_api3('EntityFinancialAccount', 'get', [
435 'return' => ["financial_account_id.id", "financial_account_id.name", "financial_account_id.accounting_code"],
436 'entity_table' => "civicrm_financial_type",
437 'account_relationship' => "Deferred Revenue Account is",
439 if ($result['count'] > 0) {
440 foreach ($result['values'] as $key => $value) {
441 $financialAccount[$value['financial_account_id.id']] = $value['financial_account_id.name'] . ' (' . $value['financial_account_id.accounting_code'] . ')';
444 return $financialAccount;
448 * Get Organization Name associated with Financial Account.
450 * @param bool $checkPermissions
455 public static function getOrganizationNames($checkPermissions = TRUE) {
456 $result = civicrm_api3('FinancialAccount', 'get', [
457 'return' => ["contact_id.organization_name", "contact_id"],
458 'contact_id.is_deleted' => 0,
459 'options' => ['limit' => 0],
460 'check_permissions' => $checkPermissions,
462 $organizationNames = [];
463 foreach ($result['values'] as $values) {
464 $organizationNames[$values['contact_id']] = $values['contact_id.organization_name'];
466 return $organizationNames;