Merge pull request #11727 from jitendrapurohit/CRM-21807
[civicrm-core.git] / CRM / Financial / BAO / FinancialAccount.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035 32 */
6a488035
TO
33class CRM_Financial_BAO_FinancialAccount extends CRM_Financial_DAO_FinancialAccount {
34
35 /**
fe482240 36 * Static holder for the default LT.
6a488035 37 */
ac7514c2 38 static $_defaultContributionType = NULL;
6a488035
TO
39
40 /**
fe482240 41 * Class constructor.
6a488035 42 */
00be9182 43 public function __construct() {
ac7514c2 44 parent::__construct();
6a488035 45 }
0e6e8724 46
6a488035 47 /**
fe482240 48 * Fetch object based on array of properties.
6a488035 49 *
ed5dd492
TO
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
52 * @param array $defaults
53 * (reference ) an assoc array to hold the flattened values.
6a488035 54 *
72b3a70c 55 * @return CRM_Financial_BAO_FinancialAccount
6a488035 56 */
00be9182 57 public static function retrieve(&$params, &$defaults) {
ac7514c2
PN
58 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
59 $financialAccount->copyValues($params);
60 if ($financialAccount->find(TRUE)) {
6a488035
TO
61 CRM_Core_DAO::storeValues($financialAccount, $defaults);
62 return $financialAccount;
63 }
ac7514c2 64 return NULL;
6a488035
TO
65 }
66
67 /**
fe482240 68 * Update the is_active flag in the db.
6a488035 69 *
ed5dd492
TO
70 * @param int $id
71 * Id of the database record.
72 * @param bool $is_active
73 * Value we want to set the is_active field.
6a488035 74 *
72b3a70c
CW
75 * @return CRM_Core_DAO|null
76 * DAO object on success, null otherwise
6a488035 77 */
00be9182 78 public static function setIsActive($id, $is_active) {
6a488035
TO
79 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_FinancialAccount', $id, 'is_active', $is_active);
80 }
81
82 /**
fe482240 83 * Add the financial types.
6a488035 84 *
ed5dd492
TO
85 * @param array $params
86 * Reference array contains the values submitted by the form.
0e6e8724 87 *
72b3a70c 88 * @return CRM_Financial_DAO_FinancialAccount
6a488035 89 */
235929d0 90 public static function add(&$params) {
22e263ad 91 if (empty($params['id'])) {
bc2bc079 92 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
93 $params['is_deductible'] = CRM_Utils_Array::value('is_deductible', $params, FALSE);
94 $params['is_tax'] = CRM_Utils_Array::value('is_tax', $params, FALSE);
95 $params['is_header_account'] = CRM_Utils_Array::value('is_header_account', $params, FALSE);
96 $params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
97 }
235929d0
PN
98 if (!empty($params['id'])
99 && !empty($params['financial_account_type_id'])
100 && CRM_Financial_BAO_FinancialAccount::validateFinancialAccount(
101 $params['id'],
102 $params['financial_account_type_id']
103 )
104 ) {
105 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.'));
106 }
a7488080 107 if (!empty($params['is_default'])) {
ac7514c2
PN
108 $query = 'UPDATE civicrm_financial_account SET is_default = 0 WHERE financial_account_type_id = %1';
109 $queryParams = array(1 => array($params['financial_account_type_id'], 'Integer'));
110 CRM_Core_DAO::executeQuery($query, $queryParams);
0e6e8724
DL
111 }
112
6a488035 113 // action is taken depending upon the mode
ac7514c2 114 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
afa09af7
PN
115
116 // invoke pre hook
117 $op = 'create';
118 if (!empty($params['id'])) {
119 $op = 'edit';
120 }
121 CRM_Utils_Hook::pre($op, 'FinancialAccount', CRM_Utils_Array::value('id', $params), $params);
122
235929d0
PN
123 if (!empty($params['id'])) {
124 $financialAccount->id = $params['id'];
125 $financialAccount->find(TRUE);
126 }
127
6a488035 128 $financialAccount->copyValues($params);
ac7514c2 129 $financialAccount->save();
afa09af7
PN
130
131 // invoke post hook
132 $op = 'create';
133 if (!empty($params['id'])) {
134 $op = 'edit';
135 }
136 CRM_Utils_Hook::post($op, 'FinancialAccount', $financialAccount->id, $financialAccount);
137
6a488035
TO
138 return $financialAccount;
139 }
0e6e8724 140
6a488035 141 /**
fe482240 142 * Delete financial Types.
0e6e8724 143 *
6a488035 144 * @param int $financialAccountId
6a488035 145 */
00be9182 146 public static function del($financialAccountId) {
cded2ebf 147 // checking if financial type is present
ac7514c2 148 $check = FALSE;
0e6e8724 149
6a488035 150 //check dependencies
b44e3f84 151 $dependency = array(
0e6e8724
DL
152 array('Core', 'FinancialTrxn', 'to_financial_account_id'),
153 array('Financial', 'FinancialTypeAccount', 'financial_account_id'),
f0d6e4c5 154 array('Financial', 'FinancialItem', 'financial_account_id'),
353ffa53 155 );
b44e3f84 156 foreach ($dependency as $name) {
045f52a3 157 require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_" . $name[0] . "_BAO_" . $name[1]) . ".php";
0e6e8724
DL
158 $className = "CRM_{$name[0]}_BAO_{$name[1]}";
159 $bao = new $className();
6ef04c72 160 $bao->{$name[2]} = $financialAccountId;
ac7514c2
PN
161 if ($bao->find(TRUE)) {
162 $check = TRUE;
6a488035
TO
163 }
164 }
0e6e8724 165
6a488035 166 if ($check) {
ac7514c2 167 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.'));
05b9ff02 168 return FALSE;
6a488035 169 }
0e6e8724 170
cded2ebf 171 // delete from financial Type table
ac7514c2 172 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
6a488035
TO
173 $financialAccount->id = $financialAccountId;
174 $financialAccount->delete();
05b9ff02 175 return TRUE;
6a488035 176 }
0e6e8724 177
6a488035 178 /**
fe482240 179 * Get accounting code for a financial type with account relation Income Account is.
6a488035 180 *
100fef9d 181 * @param int $financialTypeId
da6b46f4 182 *
72b3a70c
CW
183 * @return int
184 * accounting code
6a488035 185 */
00be9182 186 public static function getAccountingCode($financialTypeId) {
f743a6eb 187 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
6a488035
TO
188 $query = "SELECT cfa.accounting_code
189FROM civicrm_financial_type cft
190LEFT JOIN civicrm_entity_financial_account cefa ON cefa.entity_id = cft.id AND cefa.entity_table = 'civicrm_financial_type'
191LEFT JOIN civicrm_financial_account cfa ON cefa.financial_account_id = cfa.id
192WHERE cft.id = %1
193 AND account_relationship = %2";
194 $params = array(
195 1 => array($financialTypeId, 'Integer'),
196 2 => array($relationTypeId, 'Integer'),
197 );
198 return CRM_Core_DAO::singleValueQuery($query, $params);
199 }
0e6e8724 200
7d289724 201 /**
fe482240 202 * Get AR account.
7d289724 203 *
ed5dd492
TO
204 * @param $financialAccountId
205 * Financial account id.
7d289724 206 *
ed5dd492
TO
207 * @param $financialAccountTypeId
208 * Financial account type id.
7d289724 209 *
72b3a70c
CW
210 * @param string $accountTypeCode
211 * account type code
7d289724 212 *
df8d3074 213 * @return int
a6c01b45 214 * count
7d289724 215 */
00be9182 216 public static function getARAccounts($financialAccountId, $financialAccountTypeId = NULL, $accountTypeCode = 'ar') {
ddaa8ef1 217 if (!$financialAccountTypeId) {
7d45c236 218 $financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
ddaa8ef1 219 }
7d289724 220 $query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2
ddaa8ef1 221 AND id != %3 AND is_active = 1;";
7d289724
PN
222 $params = array(
223 1 => array($financialAccountTypeId, 'Integer'),
224 2 => array(strtolower($accountTypeCode), 'String'),
225 3 => array($financialAccountId, 'Integer'),
226 );
045f52a3 227 return CRM_Core_DAO::singleValueQuery($query, $params);
7d289724 228 }
96025800 229
bf2cf926 230 /**
231 * Get the Financial Account for a Financial Type Relationship Combo.
232 *
233 * Note that some relationships are optionally configured - so far
234 * Chargeback and Credit / Contra. Since these are the only 2 currently Income
235 * is an appropriate fallback. In future it might make sense to extend the logic.
236 *
237 * Note that we avoid the CRM_Core_PseudoConstant function as it stores one
238 * account per financial type and is unreliable.
239 *
240 * @param int $financialTypeID
241 *
242 * @param string $relationshipType
243 *
244 * @return int
245 */
246 public static function getFinancialAccountForFinancialTypeByRelationship($financialTypeID, $relationshipType) {
247 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationshipType}' "));
248
249 if (!isset(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId])) {
250 $accounts = civicrm_api3('EntityFinancialAccount', 'get', array(
251 'entity_id' => $financialTypeID,
252 'entity_table' => 'civicrm_financial_type',
253 ));
254
255 foreach ($accounts['values'] as $account) {
256 Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$account['account_relationship']] = $account['financial_account_id'];
257 }
258
259 $accountRelationships = CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL);
260
261 $incomeAccountRelationshipID = array_search('Income Account is', $accountRelationships);
262 $incomeAccountFinancialAccountID = Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$incomeAccountRelationshipID];
263
264 foreach (array('Chargeback Account is', 'Credit/Contra Revenue Account is') as $optionalAccountRelationship) {
265
266 $accountRelationshipID = array_search($optionalAccountRelationship, $accountRelationships);
267 if (empty(Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$accountRelationshipID])) {
52da5b1e 268 Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$accountRelationshipID] = $incomeAccountFinancialAccountID;
bf2cf926 269 }
270 }
271
272 }
273 return Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId];
274 }
275
e66512af 276 /**
871de167 277 * Get Financial Account type relations.
e66512af
PN
278 *
279 * @param $flip bool
280 *
281 * @return array
282 *
283 */
eac838e9 284 public static function getfinancialAccountRelations($flip = FALSE) {
e66512af
PN
285 $params = array('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);
288 $Links = array(
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',
298 );
299 if (!$flip) {
300 foreach ($Links as $accountRelation => $accountType) {
301 $financialAccountLinks[array_search($accountRelation, $accountRelationships)] = array_search($accountType, $financialAccountType);
302 }
303 }
304 else {
305 foreach ($Links as $accountRelation => $accountType) {
306 $financialAccountLinks[array_search($accountType, $financialAccountType)][] = array_search($accountRelation, $accountRelationships);
307 }
308 }
e66512af
PN
309 return $financialAccountLinks;
310 }
311
d9eeb0f4 312 /**
871de167 313 * Get Deferred Financial type.
d9eeb0f4
PN
314 *
315 * @return array
316 *
317 */
318 public static function getDeferredFinancialType() {
319 $deferredFinancialType = array();
320 $query = "SELECT ce.entity_id, cft.name FROM civicrm_entity_financial_account ce
d9eeb0f4 321INNER JOIN civicrm_financial_type cft ON ce.entity_id = cft.id
c5d6e9b5
PN
322WHERE 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 = array(1 => array($deferredAccountRel, 'Integer'));
325 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
d9eeb0f4
PN
326 while ($dao->fetch()) {
327 $deferredFinancialType[$dao->entity_id] = $dao->name;
328 }
329 return $deferredFinancialType;
330 }
331
e805833b 332 /**
b1b5303b 333 * Check if financial account is referenced by financial item.
e805833b 334 *
b1b5303b 335 * @param int $financialAccountId
e805833b 336 *
b1b5303b 337 * @param int $financialAccountTypeID
ea996660 338 *
e805833b 339 * @return bool
ea996660
PN
340 *
341 */
342 public static function validateFinancialAccount($financialAccountId, $financialAccountTypeID = NULL) {
e805833b 343 $sql = "SELECT f.financial_account_type_id FROM civicrm_financial_account f
fed4d93d 344INNER JOIN civicrm_financial_item fi ON fi.financial_account_id = f.id
b1b5303b 345WHERE f.id = %1 AND f.financial_account_type_id IN (%2)
e805833b 346LIMIT 1";
b1b5303b
PN
347 $params = array('labelColumn' => 'name');
348 $financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id', $params);
349 $params = array(
350 1 => array($financialAccountId, 'Integer'),
351 2 => array(
352 implode(',',
353 array(
354 array_search('Revenue', $financialAccountType),
355 array_search('Liability', $financialAccountType),
356 )
357 ),
7d68b2a3 358 'Text',
b1b5303b
PN
359 ),
360 );
e805833b 361 $result = CRM_Core_DAO::singleValueQuery($sql, $params);
fed4d93d 362 if ($result && $result != $financialAccountTypeID) {
e805833b
PN
363 return TRUE;
364 }
365 return FALSE;
366 }
367
b2ffc3e1
PN
368 /**
369 * Validate Financial Type has Deferred Revenue account relationship
ab6c306d 370 * with Financial Account.
b2ffc3e1
PN
371 *
372 * @param array $params
ab6c306d 373 * Holds submitted formvalues and params from api for updating/adding contribution.
b2ffc3e1
PN
374 *
375 * @param int $contributionID
c849d761 376 * Contribution ID
b2ffc3e1 377 *
ab6c306d
PN
378 * @param array $priceSetFields
379 * Array of price fields of a price set.
b2ffc3e1 380 *
52d479ee 381 * @return bool
b2ffc3e1
PN
382 *
383 */
ab6c306d 384 public static function checkFinancialTypeHasDeferred($params, $contributionID = NULL, $priceSetFields = NULL) {
b2ffc3e1
PN
385 if (!CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
386 return FALSE;
387 }
388 $recognitionDate = CRM_Utils_Array::value('revenue_recognition_date', $params);
389 if (!(!CRM_Utils_System::isNull($recognitionDate)
17d83f50 390 || ($contributionID && isset($params['prevContribution'])
391 && !CRM_Utils_System::isNull($params['prevContribution']->revenue_recognition_date)))
b2ffc3e1
PN
392 ) {
393 return FALSE;
394 }
395
b2ffc3e1
PN
396 $lineItems = CRM_Utils_Array::value('line_item', $params);
397 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params);
398 if (!$financialTypeID) {
399 $financialTypeID = $params['prevContribution']->financial_type_id;
400 }
401 if (($contributionID || !empty($params['price_set_id'])) && empty($lineItems)) {
402 if (!$contributionID) {
ab6c306d 403 CRM_Price_BAO_PriceSet::processAmount($priceSetFields,
b2ffc3e1
PN
404 $params, $items);
405 }
406 else {
407 $items = CRM_Price_BAO_LineItem::getLineItems($contributionID, 'contribution', TRUE, TRUE, TRUE);
408 }
409 if (!empty($items)) {
410 $lineItems[] = $items;
411 }
412 }
413 $deferredFinancialType = self::getDeferredFinancialType();
96039749 414 $isError = FALSE;
b2ffc3e1
PN
415 if (!empty($lineItems)) {
416 foreach ($lineItems as $lineItem) {
417 foreach ($lineItem as $items) {
418 if (!array_key_exists($items['financial_type_id'], $deferredFinancialType)) {
96039749 419 $isError = TRUE;
b2ffc3e1
PN
420 }
421 }
422 }
423 }
424 elseif (!array_key_exists($financialTypeID, $deferredFinancialType)) {
96039749 425 $isError = TRUE;
b2ffc3e1 426 }
96039749
PN
427
428 if ($isError) {
cebff547 429 $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
430 throw new CRM_Core_Exception($error);
431 }
432 return $isError;
b2ffc3e1
PN
433 }
434
fd633b30
PN
435 /**
436 * Retrieve all Deferred Financial Accounts.
437 *
438 *
439 * @return array of Deferred Financial Account
440 *
441 */
442 public static function getAllDeferredFinancialAccount() {
fd633b30 443 $financialAccount = array();
da345655
E
444 $result = civicrm_api3('EntityFinancialAccount', 'get', array(
445 'sequential' => 1,
446 'return' => array("financial_account_id.id", "financial_account_id.name", "financial_account_id.accounting_code"),
447 'entity_table' => "civicrm_financial_type",
448 'account_relationship' => "Deferred Revenue Account is",
449 ));
450 if ($result['count'] > 0) {
451 foreach ($result['values'] as $key => $value) {
452 $financialAccount[$value['financial_account_id.id']] = $value['financial_account_id.name'] . ' (' . $value['financial_account_id.accounting_code'] . ')';
453 }
fd633b30
PN
454 }
455 return $financialAccount;
456 }
457
16e4c0a3
PN
458 /**
459 * Get Organization Name associated with Financial Account.
460 *
461 * @param bool $checkPermissions
462 *
463 * @return array
464 *
465 */
466 public static function getOrganizationNames($checkPermissions = TRUE) {
467 $result = civicrm_api3('FinancialAccount', 'get', array(
468 'return' => array("contact_id.organization_name", "contact_id"),
469 'contact_id.is_deleted' => 0,
470 'options' => array('limit' => 0),
471 'check_permissions' => $checkPermissions,
472 ));
473 $organizationNames = array();
474 foreach ($result['values'] as $values) {
475 $organizationNames[$values['contact_id']] = $values['contact_id.organization_name'];
476 }
477 return $organizationNames;
478 }
479
6a488035 480}