Merge pull request #15421 from artfulrobot/queue-safety
[civicrm-core.git] / CRM / Financial / Form / FinancialAccount.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34 /**
35 * This class generates form components for Financial Account
36 */
37 class CRM_Financial_Form_FinancialAccount extends CRM_Contribute_Form {
38
39 /**
40 * Flag if its a AR account type.
41 *
42 * @var bool
43 */
44 protected $_isARFlag = FALSE;
45
46 /**
47 * Set variables up before form is built.
48 */
49 public function preProcess() {
50 parent::preProcess();
51
52 if ($this->_id) {
53 $params = [
54 'id' => $this->_id,
55 ];
56 $financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params);
57 $financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
58 if ($financialAccount->financial_account_type_id == $financialAccountTypeId
59 && strtolower($financialAccount->account_type_code) == 'ar'
60 && !CRM_Financial_BAO_FinancialAccount::getARAccounts($this->_id, $financialAccountTypeId)
61 ) {
62 $this->_isARFlag = TRUE;
63 if ($this->_action & CRM_Core_Action::DELETE) {
64 $msg = ts("The selected financial account cannot be deleted because at least one Accounts Receivable type account is required (to ensure that accounting transactions are in balance).");
65 CRM_Core_Error::statusBounce($msg);
66 }
67 }
68 }
69 }
70
71 /**
72 * Build the form object.
73 */
74 public function buildQuickForm() {
75 parent::buildQuickForm();
76 $this->setPageTitle(ts('Financial Account'));
77
78 if ($this->_action & CRM_Core_Action::DELETE) {
79 return;
80 }
81
82 $this->applyFilter('__ALL__', 'trim');
83 $attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialAccount');
84 $this->add('text', 'name', ts('Name'), $attributes['name'], TRUE);
85 $this->addRule('name', ts('A financial type with this name already exists. Please select another name.'),
86 'objectExists', ['CRM_Financial_DAO_FinancialAccount', $this->_id]);
87
88 $this->add('text', 'description', ts('Description'), $attributes['description']);
89 $this->add('text', 'accounting_code', ts('Accounting Code'), $attributes['accounting_code']);
90 $elementAccounting = $this->add('text', 'account_type_code', ts('Account Type Code'), $attributes['account_type_code']);
91 $this->addEntityRef('contact_id', ts('Owner'), [
92 'api' => ['params' => ['contact_type' => 'Organization']],
93 'create' => TRUE,
94 ]);
95 $this->add('text', 'tax_rate', ts('Tax Rate'), $attributes['tax_rate']);
96 $this->add('checkbox', 'is_deductible', ts('Tax-Deductible?'));
97 $elementActive = $this->add('checkbox', 'is_active', ts('Enabled?'));
98 $this->add('checkbox', 'is_tax', ts('Is Tax?'));
99
100 $element = $this->add('checkbox', 'is_default', ts('Default?'));
101 // CRM-12470 freeze is default if is_default is set
102 if ($this->_id && CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $this->_id, 'is_default')) {
103 $element->freeze();
104 }
105
106 $financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id');
107 if (!empty($financialAccountType)) {
108 $element = $this->add('select', 'financial_account_type_id', ts('Financial Account Type'),
109 ['' => '- select -'] + $financialAccountType, TRUE, ['class' => 'crm-select2 huge']);
110 if ($this->_isARFlag) {
111 $element->freeze();
112 $elementAccounting->freeze();
113 $elementActive->freeze();
114 }
115 elseif ($this->_id && CRM_Financial_BAO_FinancialAccount::validateFinancialAccount($this->_id)) {
116 $element->freeze();
117 }
118 }
119
120 if ($this->_action == CRM_Core_Action::UPDATE &&
121 CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $this->_id, 'is_reserved')
122 ) {
123 $this->freeze(['name', 'description', 'is_active']);
124 }
125 $this->addFormRule(['CRM_Financial_Form_FinancialAccount', 'formRule'], $this);
126 }
127
128 /**
129 * Global validation rules for the form.
130 *
131 * @param array $values
132 * posted values of the form
133 * @param $files
134 * @param $self
135 *
136 * @return array
137 * list of errors to be posted back to the form
138 */
139 public static function formRule($values, $files, $self) {
140 $errorMsg = [];
141 $financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' "));
142 if (isset($values['is_tax'])) {
143 if ($values['financial_account_type_id'] != $financialAccountTypeId) {
144 $errorMsg['financial_account_type_id'] = ts('Taxable accounts should have Financial Account Type set to Liability.');
145 }
146 if (!isset($values['tax_rate'])) {
147 $errorMsg['tax_rate'] = ts('Please enter value for tax rate');
148 }
149 }
150 if ((CRM_Utils_Array::value('tax_rate', $values) != NULL)) {
151 if ($values['tax_rate'] < 0 || $values['tax_rate'] >= 100) {
152 $errorMsg['tax_rate'] = ts('Tax Rate Should be between 0 - 100');
153 }
154 }
155 if ($self->_action & CRM_Core_Action::UPDATE) {
156 if (!(isset($values['is_tax']))) {
157 // @todo replace with call to CRM_Financial_BAO_FinancialAccount getSalesTaxFinancialAccount
158 $relationshipId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
159 $params = [
160 'financial_account_id' => $self->_id,
161 'account_relationship' => $relationshipId,
162 ];
163 $result = CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
164 if ($result) {
165 $errorMsg['is_tax'] = ts('Is Tax? must be set for this financial account');
166 }
167 }
168 }
169 return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
170 }
171
172 /**
173 * Set default values for the form.
174 * the default values are retrieved from the database.
175 */
176 public function setDefaultValues() {
177 $defaults = parent::setDefaultValues();
178 if ($this->_action & CRM_Core_Action::ADD) {
179 $defaults['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', CRM_Core_Config::domainID(), 'contact_id');
180 }
181 return $defaults;
182 }
183
184 /**
185 * Process the form submission.
186 */
187 public function postProcess() {
188 if ($this->_action & CRM_Core_Action::DELETE) {
189 if (CRM_Financial_BAO_FinancialAccount::del($this->_id)) {
190 CRM_Core_Session::setStatus(ts('Selected Financial Account has been deleted.'));
191 }
192 else {
193 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/financial/financialAccount', "reset=1&action=browse"));
194 }
195 }
196 else {
197 // store the submitted values in an array
198 $params = $this->exportValues();
199
200 if ($this->_action & CRM_Core_Action::UPDATE) {
201 $params['id'] = $this->_id;
202 }
203 foreach ([
204 'is_active',
205 'is_deductible',
206 'is_tax',
207 'is_default',
208 ] as $field) {
209 $params[$field] = CRM_Utils_Array::value($field, $params, FALSE);
210 }
211 $financialAccount = CRM_Financial_BAO_FinancialAccount::add($params);
212 CRM_Core_Session::setStatus(ts('The Financial Account \'%1\' has been saved.', [1 => $financialAccount->name]), ts('Saved'), 'success');
213 }
214 }
215
216 }