Merge pull request #17068 from colemanw/currentPath
[civicrm-core.git] / CRM / Financial / Form / FinancialBatch.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * This class generates form components for Accounting Batch
6a488035
TO
20 */
21class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
22
6a488035 23 /**
fe482240 24 * Set variables up before form is built.
6a488035
TO
25 */
26 public function preProcess() {
edc80cda 27 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
6a488035
TO
28 $this->set("context", $context);
29 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
30 parent::preProcess();
31 $session = CRM_Core_Session::singleton();
32 if ($this->_id) {
be2fb01f
CW
33 $permissions = [
34 CRM_Core_Action::UPDATE => [
35 'permission' => [
6a488035
TO
36 'edit own manual batches',
37 'edit all manual batches',
be2fb01f 38 ],
317fceb4 39 'actionName' => 'edit',
be2fb01f
CW
40 ],
41 CRM_Core_Action::DELETE => [
42 'permission' => [
6a488035
TO
43 'delete own manual batches',
44 'delete all manual batches',
be2fb01f 45 ],
317fceb4 46 'actionName' => 'delete',
be2fb01f
CW
47 ],
48 ];
6a488035
TO
49
50 $createdID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'created_id');
a7488080 51 if (!empty($permissions[$this->_action])) {
481a74f4 52 $this->checkPermissions($this->_action, $permissions[$this->_action]['permission'], $createdID, $session->get('userID'), $permissions[$this->_action]['actionName']);
6a488035
TO
53 }
54 }
55 }
56
57 /**
fe482240 58 * Build the form object.
6a488035
TO
59 */
60 public function buildQuickForm() {
61 parent::buildQuickForm();
e2046b33 62 $this->setPageTitle(ts('Financial Batch'));
18cb89ba 63 if (!empty($this->_id)) {
6a488035 64 $this->_title = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'title');
86bfa4f6 65 CRM_Utils_System::setTitle($this->_title . ' - ' . ts('Accounting Batch'));
6a488035
TO
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(
be2fb01f
CW
75 [
76 [
6a488035
TO
77 'type' => 'next',
78 'name' => ts('Save'),
045f52a3 79 'isDefault' => TRUE,
be2fb01f
CW
80 ],
81 [
6a488035
TO
82 'type' => 'next',
83 'name' => ts('Save and New'),
84 'subName' => 'new',
be2fb01f
CW
85 ],
86 [
6a488035
TO
87 'type' => 'cancel',
88 'name' => ts('Cancel'),
be2fb01f
CW
89 ],
90 ]
6a488035
TO
91 );
92
93 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
b9a4cb6e 94 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_BAO_Batch', 'status_id');
03e04002 95
cded2ebf 96 // unset exported status
b9a4cb6e 97 $exportedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Exported');
6a488035 98 unset($batchStatus[$exportedStatusId]);
be2fb01f
CW
99 $this->add('select', 'status_id', ts('Batch Status'), ['' => ts('- select -')] + $batchStatus, TRUE);
100 $this->freeze(['status_id']);
6a488035
TO
101 }
102
103 $attributes = CRM_Core_DAO::getAttribute('CRM_Batch_DAO_Batch');
104
045f52a3 105 $this->add('text', 'title', ts('Batch Name'), $attributes['name'], TRUE);
6a488035
TO
106
107 $this->add('textarea', 'description', ts('Description'), $attributes['description']);
108
536f0e02 109 $this->add('select', 'payment_instrument_id', ts('Payment Method'),
be2fb01f 110 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
045f52a3 111 FALSE
6a488035
TO
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']);
be2fb01f 117 $this->addFormRule(['CRM_Financial_Form_FinancialBatch', 'formRule'], $this);
6a488035
TO
118 }
119
120 /**
c490a46a 121 * Set default values for the form. Note that in edit/view mode
cded2ebf 122 * the default values are retrieved from the database.
6a488035 123 */
00be9182 124 public function setDefaultValues() {
6a488035
TO
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 /**
fe482240 140 * Global validation rules for the form.
6a488035 141 *
c490a46a 142 * @param array $values
fd31fa4c
EM
143 * @param $files
144 * @param $self
145 *
a6c01b45
CW
146 * @return array
147 * list of errors to be posted back to the form
6a488035 148 */
00be9182 149 public static function formRule($values, $files, $self) {
be2fb01f 150 $errors = [];
a7488080 151 if (!empty($values['contact_name']) && !is_numeric($values['created_id'])) {
6a488035
TO
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 }
a7488080 160 if (!empty($values['created_date']) && date('Y-m-d') < date('Y-m-d', strtotime($values['created_date']))) {
6a488035
TO
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 }
045f52a3 167 return CRM_Utils_Array::crmIsEmptyArray($errors) ? TRUE : $errors;
6a488035
TO
168 }
169
170 /**
fe482240 171 * Process the form submission.
6a488035
TO
172 */
173 public function postProcess() {
174 $session = CRM_Core_Session::singleton();
6a488035 175 $params = $this->exportValues();
b9a4cb6e 176 $closedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed');
6a488035 177 if ($this->_id) {
6a488035
TO
178 $params['id'] = $this->_id;
179 }
180
181 // store the submitted values in an array
182 $params['modified_date'] = date('YmdHis');
183 $params['modified_id'] = $session->get('userID');
a7488080 184 if (!empty($params['created_date'])) {
6a488035
TO
185 $params['created_date'] = CRM_Utils_Date::processDate($params['created_date']);
186 }
187
188 if ($this->_action & CRM_Core_Action::ADD) {
b9a4cb6e
MW
189 $params['mode_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'mode_id', 'Manual Batch');
190 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Open');
6a488035 191 $params['created_date'] = date('YmdHis');
d3d30c96
PN
192 if (empty($params['created_id'])) {
193 $params['created_id'] = $session->get('userID');
194 }
6a488035 195 $details = "{$params['title']} batch has been created by this contact.";
03e04002 196 $activityTypeName = 'Create Batch';
6a488035
TO
197 }
198 elseif ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
199 $details = "{$params['title']} batch has been edited by this contact.";
b9a4cb6e 200 if ($params['status_id'] === $closedStatusId) {
6a488035
TO
201 $details = "{$params['title']} batch has been closed by this contact.";
202 }
203 $activityTypeName = 'Edit Batch';
204 }
205
b9a4cb6e
MW
206 // FIXME: What happens if we get to here and no activityType is defined?
207
92e088c9 208 $batch = CRM_Batch_BAO_Batch::create($params);
6a488035 209
d3d30c96
PN
210 //set batch id
211 $this->_id = $batch->id;
212
cded2ebf 213 // create activity.
be2fb01f 214 $activityParams = [
f3a784bb 215 // activityTypeName - dev/core#1116-unknown-if-ok
b9a4cb6e 216 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeName),
86bfa4f6 217 'subject' => $batch->title . "- Batch",
b9a4cb6e
MW
218 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed'),
219 'priority_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'priority_id', 'Normal'),
6a488035
TO
220 'activity_date_time' => date('YmdHis'),
221 'source_contact_id' => $session->get('userID'),
222 'source_contact_qid' => $session->get('userID'),
223 'details' => $details,
be2fb01f 224 ];
6a488035
TO
225
226 CRM_Activity_BAO_Activity::create($activityParams);
227
228 $buttonName = $this->controller->getButtonName();
229
230 $context = $this->get("context");
231 if ($batch->title) {
be2fb01f 232 CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", [1 => $batch->title]), ts('Saved'), 'success');
6a488035
TO
233 }
234 if ($buttonName == $this->getButtonName('next', 'new') & $this->_action == CRM_Core_Action::UPDATE) {
235 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
236 "reset=1&action=add&context=1"));
237 }
238 elseif ($buttonName == $this->getButtonName('next', 'new')) {
239 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
240 "reset=1&action=add"));
241 }
b9a4cb6e 242 elseif ($batch->status_id === $closedStatusId) {
6a488035
TO
243 $session->replaceUserContext(CRM_Utils_System::url('civicrm', 'reset=1'));
244 }
245 elseif (($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::UPDATE) ||
353ffa53
TO
246 ($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::ADD & $context == 1)
247 ) {
6a488035
TO
248 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/financialbatches',
249 "reset=1&batchStatus=1"));
250 }
251 else {
252 $session->replaceUserContext(CRM_Utils_System::url('civicrm/batchtransaction',
253 "reset=1&bid={$batch->id}"));
254 }
255 }
256
257 /**
fe482240 258 * Global validation rules for the form.
6a488035 259 *
da6b46f4
EM
260 * @param $action
261 * @param $permissions
100fef9d
CW
262 * @param int $createdID
263 * @param int $userContactID
264 * @param string $actionName
da6b46f4 265 *
a6c01b45 266 * list of errors to be posted back to the form
6a488035 267 */
00be9182 268 public function checkPermissions($action, $permissions, $createdID, $userContactID, $actionName) {
6a488035
TO
269 if ((CRM_Core_Permission::check($permissions[0]) || CRM_Core_Permission::check($permissions[1]))) {
270 if (CRM_Core_Permission::check($permissions[0]) && $userContactID != $createdID && !CRM_Core_Permission::check($permissions[1])) {
be2fb01f 271 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
6a488035
TO
272 }
273 }
274 else {
be2fb01f 275 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
6a488035
TO
276 }
277 }
e2046b33 278
6a488035 279}