Merge pull request #11456 from jitendrapurohit/CRM-21598
[civicrm-core.git] / CRM / Financial / BAO / FinancialAccount.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33 class CRM_Financial_BAO_FinancialAccount extends CRM_Financial_DAO_FinancialAccount {
34
35 /**
36 * Static holder for the default LT.
37 */
38 static $_defaultContributionType = NULL;
39
40 /**
41 * Class constructor.
42 */
43 public function __construct() {
44 parent::__construct();
45 }
46
47 /**
48 * Fetch object based on array of properties.
49 *
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.
54 *
55 * @return CRM_Financial_BAO_FinancialAccount
56 */
57 public static function retrieve(&$params, &$defaults) {
58 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
59 $financialAccount->copyValues($params);
60 if ($financialAccount->find(TRUE)) {
61 CRM_Core_DAO::storeValues($financialAccount, $defaults);
62 return $financialAccount;
63 }
64 return NULL;
65 }
66
67 /**
68 * Update the is_active flag in the db.
69 *
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.
74 *
75 * @return CRM_Core_DAO|null
76 * DAO object on success, null otherwise
77 */
78 public static function setIsActive($id, $is_active) {
79 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_FinancialAccount', $id, 'is_active', $is_active);
80 }
81
82 /**
83 * Add the financial types.
84 *
85 * @param array $params
86 * Reference array contains the values submitted by the form.
87 *
88 * @return CRM_Financial_DAO_FinancialAccount
89 */
90 public static function add(&$params) {
91 if (empty($params['id'])) {
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 }
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 }
107 if (!empty($params['is_default'])) {
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);
111 }
112
113 // action is taken depending upon the mode
114 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
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
123 if (!empty($params['id'])) {
124 $financialAccount->id = $params['id'];
125 $financialAccount->find(TRUE);
126 }
127
128 $financialAccount->copyValues($params);
129 $financialAccount->save();
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
138 return $financialAccount;
139 }
140
141 /**
142 * Delete financial Types.
143 *
144 * @param int $financialAccountId
145 */
146 public static function del($financialAccountId) {
147 // checking if financial type is present
148 $check = FALSE;
149
150 //check dependencies
151 $dependency = array(
152 array('Core', 'FinancialTrxn', 'to_financial_account_id'),
153 array('Financial', 'FinancialTypeAccount', 'financial_account_id'),
154 array('Financial', 'FinancialItem', 'financial_account_id'),
155 );
156 foreach ($dependency as $name) {
157 require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_" . $name[0] . "_BAO_" . $name[1]) . ".php";
158 $className = "CRM_{$name[0]}_BAO_{$name[1]}";
159 $bao = new $className();
160 $bao->{$name[2]} = $financialAccountId;
161 if ($bao->find(TRUE)) {
162 $check = TRUE;
163 }
164 }
165
166 if ($check) {
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.'));
168 return FALSE;
169 }
170
171 // delete from financial Type table
172 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
173 $financialAccount->id = $financialAccountId;
174 $financialAccount->delete();
175 return TRUE;
176 }
177
178 /**
179 * Get accounting code for a financial type with account relation Income Account is.
180 *
181 * @param int $financialTypeId
182 *
183 * @return int
184 * accounting code
185 */
186 public static function getAccountingCode($financialTypeId) {
187 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
188 $query = "SELECT cfa.accounting_code
189 FROM civicrm_financial_type cft
190 LEFT JOIN civicrm_entity_financial_account cefa ON cefa.entity_id = cft.id AND cefa.entity_table = 'civicrm_financial_type'
191 LEFT JOIN civicrm_financial_account cfa ON cefa.financial_account_id = cfa.id
192 WHERE 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 }
200
201 /**
202 * Get AR account.
203 *
204 * @param $financialAccountId
205 * Financial account id.
206 *
207 * @param $financialAccountTypeId
208 * Financial account type id.
209 *
210 * @param string $accountTypeCode
211 * account type code
212 *
213 * @return int
214 * count
215 */
216 public static function getARAccounts($financialAccountId, $financialAccountTypeId = NULL, $accountTypeCode = 'ar') {
217 if (!$financialAccountTypeId) {
218 $financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
219 }
220 $query = "SELECT count(id) FROM civicrm_financial_account WHERE financial_account_type_id = %1 AND LCASE(account_type_code) = %2
221 AND id != %3 AND is_active = 1;";
222 $params = array(
223 1 => array($financialAccountTypeId, 'Integer'),
224 2 => array(strtolower($accountTypeCode), 'String'),
225 3 => array($financialAccountId, 'Integer'),
226 );
227 return CRM_Core_DAO::singleValueQuery($query, $params);
228 }
229
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])) {
268 Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$accountRelationshipID] = $incomeAccountFinancialAccountID;
269 }
270 }
271
272 }
273 return Civi::$statics[__CLASS__]['entity_financial_account'][$financialTypeID][$relationTypeId];
274 }
275
276 /**
277 * Get Financial Account type relations.
278 *
279 * @param $flip bool
280 *
281 * @return array
282 *
283 */
284 public static function getfinancialAccountRelations($flip = FALSE) {
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 }
309 return $financialAccountLinks;
310 }
311
312 /**
313 * Get Deferred Financial type.
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
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 = array(1 => array($deferredAccountRel, 'Integer'));
325 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
326 while ($dao->fetch()) {
327 $deferredFinancialType[$dao->entity_id] = $dao->name;
328 }
329 return $deferredFinancialType;
330 }
331
332 /**
333 * Check if financial account is referenced by financial item.
334 *
335 * @param int $financialAccountId
336 *
337 * @param int $financialAccountTypeID
338 *
339 * @return bool
340 *
341 */
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)
346 LIMIT 1";
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 ),
358 'Text',
359 ),
360 );
361 $result = CRM_Core_DAO::singleValueQuery($sql, $params);
362 if ($result && $result != $financialAccountTypeID) {
363 return TRUE;
364 }
365 return FALSE;
366 }
367
368 /**
369 * Validate Financial Type has Deferred Revenue account relationship
370 * with Financial Account.
371 *
372 * @param array $params
373 * Holds submitted formvalues and params from api for updating/adding contribution.
374 *
375 * @param int $contributionID
376 * Contribution ID
377 *
378 * @param array $priceSetFields
379 * Array of price fields of a price set.
380 *
381 * @return bool
382 *
383 */
384 public static function checkFinancialTypeHasDeferred($params, $contributionID = NULL, $priceSetFields = NULL) {
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)
390 || ($contributionID && isset($params['prevContribution'])
391 && !CRM_Utils_System::isNull($params['prevContribution']->revenue_recognition_date)))
392 ) {
393 return FALSE;
394 }
395
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) {
403 CRM_Price_BAO_PriceSet::processAmount($priceSetFields,
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();
414 $isError = FALSE;
415 if (!empty($lineItems)) {
416 foreach ($lineItems as $lineItem) {
417 foreach ($lineItem as $items) {
418 if (!array_key_exists($items['financial_type_id'], $deferredFinancialType)) {
419 $isError = TRUE;
420 }
421 }
422 }
423 }
424 elseif (!array_key_exists($financialTypeID, $deferredFinancialType)) {
425 $isError = TRUE;
426 }
427
428 if ($isError) {
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.');
430 throw new CRM_Core_Exception($error);
431 }
432 return $isError;
433 }
434
435 /**
436 * Retrieve all Deferred Financial Accounts.
437 *
438 *
439 * @return array of Deferred Financial Account
440 *
441 */
442 public static function getAllDeferredFinancialAccount() {
443 $financialAccount = array();
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 }
454 }
455 return $financialAccount;
456 }
457
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
480 }