Merge pull request #4899 from colemanw/INFRA-132
[civicrm-core.git] / CRM / Financial / BAO / FinancialTypeAccount.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
6a488035
TO
35class CRM_Financial_BAO_FinancialTypeAccount extends CRM_Financial_DAO_EntityFinancialAccount {
36
37 /**
100fef9d 38 * Class constructor
6a488035 39 */
045f52a3 40 public function __construct() {
481a74f4 41 parent::__construct();
6a488035
TO
42 }
43
44 /**
100fef9d 45 * Financial account
6a488035
TO
46 * @var array
47 * @static
48 */
49 private static $financialAccount;
50
51 /**
c490a46a 52 * Fetch object based on array of properties
6a488035 53 *
ed5dd492
TO
54 * @param array $params
55 * (reference ) an assoc array of name/value pairs.
56 * @param array $defaults
57 * (reference ) an assoc array to hold the flattened values.
6a488035 58 *
6c8f6e67
EM
59 * @param array $allValues
60 *
c490a46a 61 * @return CRM_Contribute_BAO_ContributionType object
6a488035
TO
62 * @static
63 */
00be9182 64 public static function retrieve(&$params, &$defaults, &$allValues = array()) {
ecc1e0ef
PN
65 $financialTypeAccount = new CRM_Financial_DAO_EntityFinancialAccount();
66 $financialTypeAccount->copyValues($params);
67 $financialTypeAccount->find();
68 while ($financialTypeAccount->fetch()) {
69 CRM_Core_DAO::storeValues($financialTypeAccount, $defaults);
70 $allValues[] = $defaults;
6a488035 71 }
ecc1e0ef 72 return $defaults;
6a488035 73 }
03e04002 74
6a488035 75 /**
100fef9d 76 * Add the financial types
6a488035 77 *
ed5dd492
TO
78 * @param array $params
79 * Reference array contains the values submitted by the form.
80 * @param array $ids
81 * Reference array contains the id.
03e04002 82 *
03e04002 83 * @static
6a488035
TO
84 * @return object
85 */
00be9182 86 public static function add(&$params, &$ids = NULL) {
6a488035
TO
87 // action is taken depending upon the mode
88 $financialTypeAccount = new CRM_Financial_DAO_EntityFinancialAccount();
89 if ($params['entity_table'] != 'civicrm_financial_type') {
90 $financialTypeAccount->entity_id = $params['entity_id'];
91 $financialTypeAccount->entity_table = $params['entity_table'];
92 $financialTypeAccount->find(TRUE);
93 }
94 else {
95 $financialTypeAccount->id = CRM_Utils_Array::value('entityFinancialAccount', $ids);
96 }
a7488080 97 if (!empty($ids['entityFinancialAccount'])) {
6a488035
TO
98 $financialTypeAccount->id = $ids['entityFinancialAccount'];
99 }
100 $financialTypeAccount->copyValues($params);
101 $financialTypeAccount->save();
102 return $financialTypeAccount;
103 }
03e04002 104
6a488035 105 /**
100fef9d 106 * Delete financial Types
03e04002 107 *
c490a46a
CW
108 * @param int $financialTypeAccountId
109 * @param int $accountId
fd31fa4c 110 *
6a488035
TO
111 * @static
112 */
045f52a3 113 public static function del($financialTypeAccountId, $accountId = NULL) {
03e04002 114 //checking if financial type is present
045f52a3 115 $check = FALSE;
7611ae71 116 $relationValues = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
03e04002 117
481a74f4 118 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $financialTypeAccountId, 'entity_id');
6a488035
TO
119 //check dependencies
120 // FIXME more table containing financial_type_id to come
121 $dependancy = array(
122 array('Contribute', 'Contribution'),
123 array('Contribute', 'ContributionPage'),
124 array('Member', 'MembershipType'),
9f61848d 125 array('Price', 'PriceFieldValue'),
6a488035
TO
126 array('Grant', 'Grant'),
127 array('Contribute', 'PremiumsProduct'),
128 array('Contribute', 'Product'),
129 array('Price', 'LineItem'),
130 );
131
132 foreach ($dependancy as $name) {
4d5c2eb5 133 $daoString = 'CRM_' . $name[0] . '_DAO_' . $name[1];
134 $dao = new $daoString();
6a488035 135 $dao->financial_type_id = $financialTypeId;
045f52a3
TO
136 if ($dao->find(TRUE)) {
137 $check = TRUE;
6a488035
TO
138 break;
139 }
140 }
2efcf0c2 141
6a488035
TO
142 if ($check) {
143 if ($name[1] == 'PremiumsProduct' || $name[1] == 'Product') {
10a5be27 144 CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship while the Financial Type is used for a Premium.', array(1 => $relationValues[$financialTypeAccountId])));
6a488035
TO
145 }
146 else {
b2e6c21f 147 $accountRelationShipId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $financialTypeAccountId, 'account_relationship');
045f52a3 148 CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship because it is being referenced by one or more of the following types of records: Contributions, Contribution Pages, or Membership Types. Consider disabling this type instead if you no longer want it used.', array(1 => $relationValues[$accountRelationShipId])), NULL, 'error');
6a488035 149 }
481a74f4 150 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', "reset=1&action=browse&aid={$accountId}"));
6a488035 151 }
03e04002 152
6a488035 153 //delete from financial Type table
481a74f4 154 $financialType = new CRM_Financial_DAO_EntityFinancialAccount();
6a488035 155 $financialType->id = $financialTypeAccountId;
3b67ab13 156 $financialType->find(TRUE);
6a488035 157 $financialType->delete();
0161a899 158 CRM_Core_Session::setStatus(ts('Unbalanced transactions may be created if you delete the account of type: %1.', array(1 => $relationValues[$financialType->account_relationship])));
6a488035 159 }
03e04002 160
6a488035 161 /**
100fef9d 162 * Get Financial Account Name
03e04002 163 *
6a488035 164 * @param int $entityId
03e04002 165 *
166 * @param string $entityTable
167 *
ed5dd492
TO
168 * @param string $columnName
169 * Column to fetch.
77b97be7
EM
170 *
171 * @return null|string
6a488035
TO
172 * @static
173 */
00be9182 174 public static function getFinancialAccount($entityId, $entityTable, $columnName = 'name') {
6a488035
TO
175 $join = $columnName == 'name' ? 'LEFT JOIN civicrm_financial_account ON civicrm_entity_financial_account.financial_account_id = civicrm_financial_account.id' : NULL;
176 $query = "
177SELECT {$columnName}
178FROM civicrm_entity_financial_account
179{$join}
180WHERE entity_table = %1
181AND entity_id = %2";
182
183 $params = array(
184 1 => array($entityTable, 'String'),
185 2 => array($entityId, 'Integer'),
186 );
187 return CRM_Core_DAO::singleValueQuery($query, $params);
188 }
189
190 /**
100fef9d 191 * Financial Account for payment instrument
03e04002 192 *
ed5dd492
TO
193 * @param int $paymentInstrumentValue
194 * Payment instrument value.
03e04002 195 *
77b97be7 196 * @return array|null|string
6a488035
TO
197 * @static
198 */
00be9182 199 public static function getInstrumentFinancialAccount($paymentInstrumentValue = NULL) {
6a488035
TO
200 if (!self::$financialAccount) {
201 $query = "SELECT ceft.financial_account_id, cov.value
202FROM civicrm_entity_financial_account ceft
03e04002 203INNER JOIN civicrm_option_value cov ON cov.id = ceft.entity_id AND ceft.entity_table = 'civicrm_option_value'
204INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
6a488035
TO
205WHERE cog.name = 'payment_instrument' ";
206
207 if ($paymentInstrumentValue) {
208 $query .= " AND cov.value = '{$paymentInstrumentValue}' ";
209 return CRM_Core_DAO::singleValueQuery($query);
210 }
211 else {
212 $result = CRM_Core_DAO::executeQuery($query);
213 while ($result->fetch()) {
214 self::$financialAccount[$result->value] = $result->financial_account_id;
215 }
216 return self::$financialAccount;
217 }
218 }
219
220 return $paymentInstrumentValue ? self::$financialAccount[$paymentInstrumentValue] : self::$financialAccount;
221 }
ddaa8ef1
PN
222
223 /**
100fef9d 224 * Create default entity financial accounts
ddaa8ef1 225 * for financial type
8ef12e64 226 * CRM-12470
ddaa8ef1 227 *
77b97be7
EM
228 * @param $financialType
229 *
230 * @return array
ddaa8ef1
PN
231 * @static
232 */
00be9182 233 public static function createDefaultFinancialAccounts($financialType) {
ddaa8ef1
PN
234 $titles = array();
235 $financialAccountTypeID = CRM_Core_PseudoConstant::accountOptionValues('financial_account_type');
236 $accountRelationship = CRM_Core_PseudoConstant::accountOptionValues('account_relationship');
045f52a3 237 $relationships = array(
ddaa8ef1
PN
238 array_search('Accounts Receivable Account is', $accountRelationship) => array_search('Asset', $financialAccountTypeID),
239 array_search('Expense Account is', $accountRelationship) => array_search('Expenses', $financialAccountTypeID),
240 array_search('Cost of Sales Account is', $accountRelationship) => array_search('Cost of Sales', $financialAccountTypeID),
241 array_search('Income Account is', $accountRelationship) => array_search('Revenue', $financialAccountTypeID),
242 );
d75f2f47 243
045f52a3 244 $dao = CRM_Core_DAO::executeQuery('SELECT id, financial_account_type_id FROM civicrm_financial_account WHERE name LIKE %1',
77292b55 245 array(1 => array($financialType->name, 'String'))
ddaa8ef1 246 );
77292b55
PN
247 $dao->fetch();
248 $existingFinancialAccount = array();
249 if (!$dao->N) {
250 $params = array(
251 'name' => $financialType->name,
252 'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', CRM_Core_Config::domainID(), 'contact_id'),
253 'financial_account_type_id' => array_search('Revenue', $financialAccountTypeID),
254 'description' => $financialType->description,
255 'account_type_code' => 'INC',
256 'is_active' => 1,
257 );
258 $financialAccount = CRM_Financial_BAO_FinancialAccount::add($params, CRM_Core_DAO::$_nullArray);
259 }
260 else {
261 $existingFinancialAccount[$dao->financial_account_type_id] = $dao->id;
262 }
045f52a3 263 $params = array(
ddaa8ef1
PN
264 'entity_table' => 'civicrm_financial_type',
265 'entity_id' => $financialType->id,
266 );
267 foreach ($relationships as $key => $value) {
77292b55
PN
268 if (!array_key_exists($value, $existingFinancialAccount)) {
269 if ($accountRelationship[$key] == 'Accounts Receivable Account is') {
270 $params['financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', 'Accounts Receivable', 'id', 'name');
271 if (!empty($params['financial_account_id'])) {
272 $titles[] = 'Accounts Receivable';
273 }
274 else {
275 $query = "SELECT financial_account_id, name FROM civicrm_entity_financial_account
ddaa8ef1
PN
276 LEFT JOIN civicrm_financial_account ON civicrm_financial_account.id = civicrm_entity_financial_account.financial_account_id
277 WHERE account_relationship = {$key} AND entity_table = 'civicrm_financial_type' LIMIT 1";
77292b55
PN
278 $dao = CRM_Core_DAO::executeQuery($query);
279 $dao->fetch();
280 $params['financial_account_id'] = $dao->financial_account_id;
281 $titles[] = $dao->name;
282 }
283 }
284 elseif ($accountRelationship[$key] == 'Income Account is' && empty($existingFinancialAccount)) {
285 $params['financial_account_id'] = $financialAccount->id;
286 }
287 else {
288 $query = "SELECT id, name FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = {$value}";
ddaa8ef1
PN
289 $dao = CRM_Core_DAO::executeQuery($query);
290 $dao->fetch();
77292b55 291 $params['financial_account_id'] = $dao->id;
ddaa8ef1
PN
292 $titles[] = $dao->name;
293 }
294 }
ddaa8ef1 295 else {
045f52a3
TO
296 $params['financial_account_id'] = $existingFinancialAccount[$value];
297 $titles[] = $financialType->name;
ddaa8ef1
PN
298 }
299 $params['account_relationship'] = $key;
8ef12e64 300 self::add($params);
ddaa8ef1 301 }
77292b55
PN
302 if (!empty($existingFinancialAccount)) {
303 $titles = array();
304 }
ddaa8ef1
PN
305 return $titles;
306 }
6a488035 307}