Merge pull request #21865 from colemanw/SearchKitTags
[civicrm-core.git] / CRM / Financial / BAO / FinancialAccount.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035 16 */
e8036f52 17class CRM_Financial_BAO_FinancialAccount extends CRM_Financial_DAO_FinancialAccount implements \Civi\Test\HookInterface {
6a488035 18
6a488035 19 /**
fe482240 20 * Fetch object based on array of properties.
6a488035 21 *
ed5dd492
TO
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.
6a488035 26 *
72b3a70c 27 * @return CRM_Financial_BAO_FinancialAccount
6a488035 28 */
7fe6ecaf 29 public static function retrieve(&$params, &$defaults = []) {
ac7514c2
PN
30 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
31 $financialAccount->copyValues($params);
32 if ($financialAccount->find(TRUE)) {
6a488035
TO
33 CRM_Core_DAO::storeValues($financialAccount, $defaults);
34 return $financialAccount;
35 }
ac7514c2 36 return NULL;
6a488035
TO
37 }
38
39 /**
fe482240 40 * Update the is_active flag in the db.
6a488035 41 *
ed5dd492
TO
42 * @param int $id
43 * Id of the database record.
44 * @param bool $is_active
45 * Value we want to set the is_active field.
6a488035 46 *
8a4fede3 47 * @return bool
48 * true if we found and updated the object, else false
6a488035 49 */
00be9182 50 public static function setIsActive($id, $is_active) {
6a488035
TO
51 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_FinancialAccount', $id, 'is_active', $is_active);
52 }
53
54 /**
fe482240 55 * Add the financial types.
6a488035 56 *
ed5dd492
TO
57 * @param array $params
58 * Reference array contains the values submitted by the form.
0e6e8724 59 *
72b3a70c 60 * @return CRM_Financial_DAO_FinancialAccount
6a488035 61 */
235929d0 62 public static function add(&$params) {
22e263ad 63 if (empty($params['id'])) {
bc2bc079 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);
69 }
235929d0
PN
70 if (!empty($params['id'])
71 && !empty($params['financial_account_type_id'])
72 && CRM_Financial_BAO_FinancialAccount::validateFinancialAccount(
73 $params['id'],
74 $params['financial_account_type_id']
75 )
76 ) {
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.'));
78 }
a7488080 79 if (!empty($params['is_default'])) {
ac7514c2 80 $query = 'UPDATE civicrm_financial_account SET is_default = 0 WHERE financial_account_type_id = %1';
019cd518 81 $queryParams = [1 => [$params['financial_account_type_id'], 'Integer']];
ac7514c2 82 CRM_Core_DAO::executeQuery($query, $queryParams);
0e6e8724
DL
83 }
84
6a488035 85 // action is taken depending upon the mode
ac7514c2 86 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
afa09af7
PN
87
88 // invoke pre hook
89 $op = 'create';
90 if (!empty($params['id'])) {
91 $op = 'edit';
92 }
93 CRM_Utils_Hook::pre($op, 'FinancialAccount', CRM_Utils_Array::value('id', $params), $params);
94
235929d0
PN
95 if (!empty($params['id'])) {
96 $financialAccount->id = $params['id'];
97 $financialAccount->find(TRUE);
98 }
99
6a488035 100 $financialAccount->copyValues($params);
ac7514c2 101 $financialAccount->save();
afa09af7
PN
102
103 // invoke post hook
104 $op = 'create';
105 if (!empty($params['id'])) {
106 $op = 'edit';
107 }
108 CRM_Utils_Hook::post($op, 'FinancialAccount', $financialAccount->id, $financialAccount);
6228fa17 109 CRM_Core_PseudoConstant::flush();
afa09af7 110
6a488035
TO
111 return $financialAccount;
112 }
0e6e8724 113
6a488035 114 /**
fe482240 115 * Delete financial Types.
0e6e8724 116 *
e8036f52 117 * @deprecated
6a488035 118 * @param int $financialAccountId
6a488035 119 */
00be9182 120 public static function del($financialAccountId) {
e8036f52
CW
121 try {
122 static::deleteRecord(['id' => $financialAccountId]);
123 return TRUE;
6a488035 124 }
e8036f52
CW
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');
05b9ff02 128 return FALSE;
6a488035 129 }
e8036f52 130 }
0e6e8724 131
e8036f52
CW
132 /**
133 * Callback for hook_civicrm_pre().
134 * @param \Civi\Core\Event\PreEvent $event
135 * @throws CRM_Core_Exception
136 */
137 public static function self_hook_civicrm_pre(\Civi\Core\Event\PreEvent $event) {
138 if ($event->action === 'delete') {
139 // Check dependencies before deleting
140 $dependency = [
141 ['Core', 'FinancialTrxn', 'to_financial_account_id'],
142 ['Financial', 'FinancialTypeAccount', 'financial_account_id'],
143 ['Financial', 'FinancialItem', 'financial_account_id'],
144 ];
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.'));
151 }
152 }
153 }
6a488035 154 }
0e6e8724 155
6a488035 156 /**
fe482240 157 * Get accounting code for a financial type with account relation Income Account is.
6a488035 158 *
100fef9d 159 * @param int $financialTypeId
da6b46f4 160 *
72b3a70c
CW
161 * @return int
162 * accounting code
6a488035 163 */
00be9182 164 public static function getAccountingCode($financialTypeId) {
f743a6eb 165 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
6a488035
TO
166 $query = "SELECT cfa.accounting_code
167FROM civicrm_financial_type cft
168LEFT JOIN civicrm_entity_financial_account cefa ON cefa.entity_id = cft.id AND cefa.entity_table = 'civicrm_financial_type'
169LEFT JOIN civicrm_financial_account cfa ON cefa.financial_account_id = cfa.id
170WHERE cft.id = %1
171 AND account_relationship = %2";
019cd518 172 $params = [
173 1 => [$financialTypeId, 'Integer'],
174 2 => [$relationTypeId, 'Integer'],
175 ];
6a488035
TO
176 return CRM_Core_DAO::singleValueQuery($query, $params);
177 }
0e6e8724 178
7d289724 179 /**
fe482240 180 * Get AR account.
7d289724 181 *
ed5dd492
TO
182 * @param $financialAccountId
183 * Financial account id.
7d289724 184 *
ed5dd492
TO
185 * @param $financialAccountTypeId
186 * Financial account type id.
7d289724 187 *
72b3a70c
CW
188 * @param string $accountTypeCode
189 * account type code
7d289724 190 *
df8d3074 191 * @return int
a6c01b45 192 * count
7d289724 193 */
00be9182 194 public static function getARAccounts($financialAccountId, $financialAccountTypeId = NULL, $accountTypeCode = 'ar') {
ddaa8ef1 195 if (!$financialAccountTypeId) {
7d45c236 196 $financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
ddaa8ef1 197 }
7d289724 198 $query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2
ddaa8ef1 199 AND id != %3 AND is_active = 1;";
019cd518 200 $params = [
201 1 => [$financialAccountTypeId, 'Integer'],
202 2 => [strtolower($accountTypeCode), 'String'],
203 3 => [$financialAccountId, 'Integer'],
204 ];
045f52a3 205 return CRM_Core_DAO::singleValueQuery($query, $params);
7d289724 206 }
96025800 207
bf2cf926 208 /**
209 * Get the Financial Account for a Financial Type Relationship Combo.
210 *
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.
214 *
215 * Note that we avoid the CRM_Core_PseudoConstant function as it stores one
216 * account per financial type and is unreliable.
bbaf615e 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.
bf2cf926 219 *
220 * @param int $financialTypeID
221 *
222 * @param string $relationshipType
223 *
224 * @return int
225 */
226 public static function getFinancialAccountForFinancialTypeByRelationship($financialTypeID, $relationshipType) {
bbaf615e 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);
231
232 $relationTypeId = $accountRelationships[$relationshipType] ?? NULL;
bf2cf926 233
234 if (!isset(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
019cd518 235 $accounts = civicrm_api3('EntityFinancialAccount', 'get', [
bf2cf926 236 'entity_id' => $financialTypeID,
237 'entity_table' => 'civicrm_financial_type',
019cd518 238 ]);
bf2cf926 239
240 foreach ($accounts['values'] as $account) {
241 Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$account['account_relationship']] = $account['financial_account_id'];
242 }
243
bbaf615e 244 $incomeAccountRelationshipID = $accountRelationships['Income Account is'] ?? FALSE;
bf2cf926 245 $incomeAccountFinancialAccountID = Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$incomeAccountRelationshipID];
246
019cd518 247 foreach (['Chargeback Account is', 'Credit/Contra Revenue Account is'] as $optionalAccountRelationship) {
bf2cf926 248
bbaf615e 249 $accountRelationshipID = $accountRelationships[$optionalAccountRelationship] ?? FALSE;
bf2cf926 250 if (empty(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$accountRelationshipID])) {
52da5b1e 251 Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$accountRelationshipID] = $incomeAccountFinancialAccountID;
bf2cf926 252 }
253 }
928a340b 254 if (!isset(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
255 Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId] = NULL;
256 }
bf2cf926 257 }
258 return Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId];
259 }
260
07376a08 261 /**
262 * Get the sales tax financial account id for the financial type id.
263 *
264 * This is a helper wrapper to make the function name more readable.
265 *
266 * @param int $financialAccountID
267 *
268 * @return int
269 */
270 public static function getSalesTaxFinancialAccount($financialAccountID) {
271 return self::getFinancialAccountForFinancialTypeByRelationship($financialAccountID, 'Sales Tax Account is');
272 }
273
e66512af 274 /**
871de167 275 * Get Financial Account type relations.
e66512af 276 *
a2f24340 277 * @param bool $flip
e66512af
PN
278 *
279 * @return array
280 *
281 */
eac838e9 282 public static function getfinancialAccountRelations($flip = FALSE) {
019cd518 283 $params = ['labelColumn' => 'name'];
e66512af
PN
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);
019cd518 286 $Links = [
e66512af
PN
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',
019cd518 296 ];
e66512af
PN
297 if (!$flip) {
298 foreach ($Links as $accountRelation => $accountType) {
299 $financialAccountLinks[array_search($accountRelation, $accountRelationships)] = array_search($accountType, $financialAccountType);
300 }
301 }
302 else {
303 foreach ($Links as $accountRelation => $accountType) {
304 $financialAccountLinks[array_search($accountType, $financialAccountType)][] = array_search($accountRelation, $accountRelationships);
305 }
306 }
e66512af
PN
307 return $financialAccountLinks;
308 }
309
d9eeb0f4 310 /**
871de167 311 * Get Deferred Financial type.
d9eeb0f4
PN
312 *
313 * @return array
314 *
315 */
316 public static function getDeferredFinancialType() {
019cd518 317 $deferredFinancialType = [];
d9eeb0f4 318 $query = "SELECT ce.entity_id, cft.name FROM civicrm_entity_financial_account ce
d9eeb0f4 319INNER JOIN civicrm_financial_type cft ON ce.entity_id = cft.id
c5d6e9b5
PN
320WHERE 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' "));
019cd518 322 $queryParams = [1 => [$deferredAccountRel, 'Integer']];
c5d6e9b5 323 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
d9eeb0f4
PN
324 while ($dao->fetch()) {
325 $deferredFinancialType[$dao->entity_id] = $dao->name;
326 }
327 return $deferredFinancialType;
328 }
329
e805833b 330 /**
b1b5303b 331 * Check if financial account is referenced by financial item.
e805833b 332 *
b1b5303b 333 * @param int $financialAccountId
e805833b 334 *
b1b5303b 335 * @param int $financialAccountTypeID
ea996660 336 *
e805833b 337 * @return bool
ea996660
PN
338 *
339 */
340 public static function validateFinancialAccount($financialAccountId, $financialAccountTypeID = NULL) {
e805833b 341 $sql = "SELECT f.financial_account_type_id FROM civicrm_financial_account f
fed4d93d 342INNER JOIN civicrm_financial_item fi ON fi.financial_account_id = f.id
b1b5303b 343WHERE f.id = %1 AND f.financial_account_type_id IN (%2)
e805833b 344LIMIT 1";
019cd518 345 $params = ['labelColumn' => 'name'];
b1b5303b 346 $financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
019cd518 347 $params = [
348 1 => [$financialAccountId, 'Integer'],
349 2 => [
b1b5303b 350 implode(',',
019cd518 351 [
b1b5303b
PN
352 array_search('Revenue', $financialAccountType),
353 array_search('Liability', $financialAccountType),
019cd518 354 ]
b1b5303b 355 ),
7d68b2a3 356 'Text',
019cd518 357 ],
358 ];
e805833b 359 $result = CRM_Core_DAO::singleValueQuery($sql, $params);
fed4d93d 360 if ($result && $result != $financialAccountTypeID) {
e805833b
PN
361 return TRUE;
362 }
363 return FALSE;
364 }
365
b2ffc3e1
PN
366 /**
367 * Validate Financial Type has Deferred Revenue account relationship
ab6c306d 368 * with Financial Account.
b2ffc3e1
PN
369 *
370 * @param array $params
ab6c306d 371 * Holds submitted formvalues and params from api for updating/adding contribution.
b2ffc3e1
PN
372 *
373 * @param int $contributionID
c849d761 374 * Contribution ID
b2ffc3e1 375 *
bd4fe93c 376 * @param array $orderLineItems
377 * The line items from the Order.
b2ffc3e1 378 *
52d479ee 379 * @return bool
b2ffc3e1
PN
380 *
381 */
bd4fe93c 382 public static function checkFinancialTypeHasDeferred($params, $contributionID = NULL, $orderLineItems = []) {
a17bec97 383 if (!Civi::settings()->get('deferred_revenue_enabled')) {
b2ffc3e1
PN
384 return FALSE;
385 }
9c1bc317 386 $recognitionDate = $params['revenue_recognition_date'] ?? NULL;
b2ffc3e1 387 if (!(!CRM_Utils_System::isNull($recognitionDate)
17d83f50 388 || ($contributionID && isset($params['prevContribution'])
019cd518 389 && !CRM_Utils_System::isNull($params['prevContribution']->revenue_recognition_date)))
b2ffc3e1
PN
390 ) {
391 return FALSE;
392 }
393
9c1bc317
CW
394 $lineItems = $params['line_item'] ?? NULL;
395 $financialTypeID = $params['financial_type_id'] ?? NULL;
b2ffc3e1
PN
396 if (!$financialTypeID) {
397 $financialTypeID = $params['prevContribution']->financial_type_id;
398 }
399 if (($contributionID || !empty($params['price_set_id'])) && empty($lineItems)) {
bd4fe93c 400 $lineItems[] = $orderLineItems;
b2ffc3e1
PN
401 }
402 $deferredFinancialType = self::getDeferredFinancialType();
96039749 403 $isError = FALSE;
b2ffc3e1
PN
404 if (!empty($lineItems)) {
405 foreach ($lineItems as $lineItem) {
406 foreach ($lineItem as $items) {
407 if (!array_key_exists($items['financial_type_id'], $deferredFinancialType)) {
96039749 408 $isError = TRUE;
b2ffc3e1
PN
409 }
410 }
411 }
412 }
413 elseif (!array_key_exists($financialTypeID, $deferredFinancialType)) {
96039749 414 $isError = TRUE;
b2ffc3e1 415 }
96039749
PN
416
417 if ($isError) {
cebff547 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.');
96039749
PN
419 throw new CRM_Core_Exception($error);
420 }
421 return $isError;
b2ffc3e1
PN
422 }
423
fd633b30
PN
424 /**
425 * Retrieve all Deferred Financial Accounts.
426 *
427 *
428 * @return array of Deferred Financial Account
429 *
430 */
431 public static function getAllDeferredFinancialAccount() {
019cd518 432 $financialAccount = [];
433 $result = civicrm_api3('EntityFinancialAccount', 'get', [
da345655 434 'sequential' => 1,
019cd518 435 'return' => ["financial_account_id.id", "financial_account_id.name", "financial_account_id.accounting_code"],
da345655
E
436 'entity_table' => "civicrm_financial_type",
437 'account_relationship' => "Deferred Revenue Account is",
019cd518 438 ]);
da345655
E
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'] . ')';
442 }
fd633b30
PN
443 }
444 return $financialAccount;
445 }
446
16e4c0a3
PN
447 /**
448 * Get Organization Name associated with Financial Account.
449 *
450 * @param bool $checkPermissions
451 *
452 * @return array
453 *
454 */
455 public static function getOrganizationNames($checkPermissions = TRUE) {
019cd518 456 $result = civicrm_api3('FinancialAccount', 'get', [
457 'return' => ["contact_id.organization_name", "contact_id"],
16e4c0a3 458 'contact_id.is_deleted' => 0,
019cd518 459 'options' => ['limit' => 0],
16e4c0a3 460 'check_permissions' => $checkPermissions,
019cd518 461 ]);
462 $organizationNames = [];
16e4c0a3
PN
463 foreach ($result['values'] as $values) {
464 $organizationNames[$values['contact_id']] = $values['contact_id.organization_name'];
465 }
466 return $organizationNames;
467 }
468
6a488035 469}