Merge pull request #18779 from jaapjansma/dev_report_53
[civicrm-core.git] / CRM / Financial / Form / FinancialBatch.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for Accounting Batch
20 */
21 class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
22
23 /**
24 * Set variables up before form is built.
25 */
26 public function preProcess() {
27 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
28 $this->set("context", $context);
29 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
30 parent::preProcess();
31
32 if ($this->_id) {
33 $permissions = [
34 CRM_Core_Action::UPDATE => [
35 'permission' => [
36 'edit own manual batches',
37 'edit all manual batches',
38 ],
39 'actionName' => 'edit',
40 ],
41 CRM_Core_Action::DELETE => [
42 'permission' => [
43 'delete own manual batches',
44 'delete all manual batches',
45 ],
46 'actionName' => 'delete',
47 ],
48 ];
49
50 $createdID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'created_id');
51 if (!empty($permissions[$this->_action])) {
52 $this->checkPermissions($this->_action, $permissions[$this->_action]['permission'], $createdID, CRM_Core_Session::getLoggedInContactID(), $permissions[$this->_action]['actionName']);
53 }
54 }
55 }
56
57 /**
58 * Build the form object.
59 */
60 public function buildQuickForm() {
61 parent::buildQuickForm();
62 $this->setPageTitle(ts('Financial Batch'));
63 if (!empty($this->_id)) {
64 $this->_title = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'title');
65 CRM_Utils_System::setTitle($this->_title . ' - ' . ts('Accounting Batch'));
66 $this->assign('batchTitle', $this->_title);
67 $contactID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'created_id');
68 $contactName = CRM_Contact_BAO_Contact::displayName($contactID);
69 $this->assign('contactName', $contactName);
70 }
71
72 $this->applyFilter('__ALL__', 'trim');
73
74 $this->addButtons(
75 [
76 [
77 'type' => 'next',
78 'name' => ts('Save'),
79 'isDefault' => TRUE,
80 ],
81 [
82 'type' => 'next',
83 'name' => ts('Save and New'),
84 'subName' => 'new',
85 ],
86 [
87 'type' => 'cancel',
88 'name' => ts('Cancel'),
89 ],
90 ]
91 );
92
93 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
94 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_BAO_Batch', 'status_id');
95
96 // unset exported status
97 $exportedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Exported');
98 unset($batchStatus[$exportedStatusId]);
99 $this->add('select', 'status_id', ts('Batch Status'), ['' => ts('- select -')] + $batchStatus, TRUE);
100 $this->freeze(['status_id']);
101 }
102
103 $attributes = CRM_Core_DAO::getAttribute('CRM_Batch_DAO_Batch');
104
105 $this->add('text', 'title', ts('Batch Name'), $attributes['name'], TRUE);
106
107 $this->add('textarea', 'description', ts('Description'), $attributes['description']);
108
109 $this->add('select', 'payment_instrument_id', ts('Payment Method'),
110 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
111 FALSE
112 );
113
114 $this->add('text', 'total', ts('Total Amount'), $attributes['total']);
115
116 $this->add('text', 'item_count', ts('Number of Transactions'), $attributes['item_count']);
117 $this->addFormRule(['CRM_Financial_Form_FinancialBatch', 'formRule'], $this);
118 }
119
120 /**
121 * Set default values for the form. Note that in edit/view mode
122 * the default values are retrieved from the database.
123 */
124 public function setDefaultValues() {
125 $defaults = parent::setDefaultValues();
126
127 if ($this->_id) {
128 $this->assign('modified_date', $defaults['modified_date']);
129 $this->assign('created_date', $defaults['created_date']);
130 }
131 else {
132 // set batch name default
133 $defaults['title'] = CRM_Batch_BAO_Batch::generateBatchName();
134 }
135
136 return $defaults;
137 }
138
139 /**
140 * Global validation rules for the form.
141 *
142 * @param array $values
143 * @param $files
144 * @param $self
145 *
146 * @return array
147 * list of errors to be posted back to the form
148 */
149 public static function formRule($values, $files, $self) {
150 $errors = [];
151 if (!empty($values['contact_name']) && !is_numeric($values['created_id'])) {
152 $errors['contact_name'] = ts('Please select a valid contact.');
153 }
154 if ($values['item_count'] && (!is_numeric($values['item_count']) || $values['item_count'] < 1)) {
155 $errors['item_count'] = ts('Number of Transactions should a positive number');
156 }
157 if ($values['total'] && (!is_numeric($values['total']) || $values['total'] <= 0)) {
158 $errors['total'] = ts('Total Amount should be a positive number');
159 }
160 if (!empty($values['created_date']) && date('Y-m-d') < date('Y-m-d', strtotime($values['created_date']))) {
161 $errors['created_date'] = ts('Created date cannot be greater than current date');
162 }
163 $batchName = $values['title'];
164 if (!CRM_Core_DAO::objectExists($batchName, 'CRM_Batch_DAO_Batch', $self->_id)) {
165 $errors['title'] = ts('This name already exists in database. Batch names must be unique.');
166 }
167 return CRM_Utils_Array::crmIsEmptyArray($errors) ? TRUE : $errors;
168 }
169
170 /**
171 * Process the form submission.
172 *
173 * @throws \CRM_Core_Exception
174 */
175 public function postProcess() {
176 $session = CRM_Core_Session::singleton();
177 $params = $this->exportValues();
178 $closedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed');
179 if ($this->_id) {
180 $params['id'] = $this->_id;
181 }
182
183 // store the submitted values in an array
184 $params['modified_date'] = date('YmdHis');
185 $params['modified_id'] = CRM_Core_Session::getLoggedInContactID();
186 if (!empty($params['created_date'])) {
187 $params['created_date'] = CRM_Utils_Date::processDate($params['created_date']);
188 }
189
190 if ($this->_action & CRM_Core_Action::ADD) {
191 $params['mode_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'mode_id', 'Manual Batch');
192 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Open');
193 $params['created_date'] = date('YmdHis');
194 if (empty($params['created_id'])) {
195 $params['created_id'] = CRM_Core_Session::getLoggedInContactID();
196 }
197 $details = "{$params['title']} batch has been created by this contact.";
198 $activityTypeName = 'Create Batch';
199 }
200 elseif ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
201 $details = "{$params['title']} batch has been edited by this contact.";
202 if ($params['status_id'] === $closedStatusId) {
203 $details = "{$params['title']} batch has been closed by this contact.";
204 }
205 $activityTypeName = 'Edit Batch';
206 }
207
208 // FIXME: What happens if we get to here and no activityType is defined?
209
210 $batch = CRM_Batch_BAO_Batch::create($params);
211
212 //set batch id
213 $this->_id = $batch->id;
214
215 // create activity.
216 $activityParams = [
217 // activityTypeName - dev/core#1116-unknown-if-ok
218 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeName),
219 'subject' => $batch->title . "- Batch",
220 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed'),
221 'priority_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'priority_id', 'Normal'),
222 'activity_date_time' => date('YmdHis'),
223 'source_contact_id' => CRM_Core_Session::getLoggedInContactID(),
224 'source_contact_qid' => CRM_Core_Session::getLoggedInContactID(),
225 'details' => $details,
226 ];
227
228 CRM_Activity_BAO_Activity::create($activityParams);
229
230 $buttonName = $this->controller->getButtonName();
231
232 $context = $this->get("context");
233 if ($batch->title) {
234 CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", [1 => $batch->title]), ts('Saved'), 'success');
235 }
236 if ($buttonName == $this->getButtonName('next', 'new') & $this->_action == CRM_Core_Action::UPDATE) {
237 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
238 "reset=1&action=add&context=1"));
239 }
240 elseif ($buttonName == $this->getButtonName('next', 'new')) {
241 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
242 "reset=1&action=add"));
243 }
244 elseif ($batch->status_id === $closedStatusId) {
245 $session->replaceUserContext(CRM_Utils_System::url('civicrm', 'reset=1'));
246 }
247 elseif (($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::UPDATE) ||
248 ($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::ADD & $context == 1)
249 ) {
250 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/financialbatches',
251 "reset=1&batchStatus=1"));
252 }
253 else {
254 $session->replaceUserContext(CRM_Utils_System::url('civicrm/batchtransaction',
255 "reset=1&bid={$batch->id}"));
256 }
257 }
258
259 /**
260 * Global validation rules for the form.
261 *
262 * @param $action
263 * @param $permissions
264 * @param int $createdID
265 * @param int $userContactID
266 * @param string $actionName
267 *
268 * list of errors to be posted back to the form
269 */
270 public function checkPermissions($action, $permissions, $createdID, $userContactID, $actionName) {
271 if ((CRM_Core_Permission::check($permissions[0]) || CRM_Core_Permission::check($permissions[1]))) {
272 if (CRM_Core_Permission::check($permissions[0]) && $userContactID != $createdID && !CRM_Core_Permission::check($permissions[1])) {
273 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
274 }
275 }
276 else {
277 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
278 }
279 }
280
281 }