Revert "Schema - Fix boolean fields in various tables"
[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();
f0c3f9bc 31
6a488035 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])) {
f0c3f9bc 52 $this->checkPermissions($this->_action, $permissions[$this->_action]['permission'], $createdID, CRM_Core_Session::getLoggedInContactID(), $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');
94fd9d17 65 $this->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 143 * @param $files
e8cf95b4 144 * @param self $self
fd31fa4c 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.
f0c3f9bc 172 *
173 * @throws \CRM_Core_Exception
6a488035
TO
174 */
175 public function postProcess() {
176 $session = CRM_Core_Session::singleton();
6a488035 177 $params = $this->exportValues();
b9a4cb6e 178 $closedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed');
6a488035 179 if ($this->_id) {
6a488035
TO
180 $params['id'] = $this->_id;
181 }
182
183 // store the submitted values in an array
184 $params['modified_date'] = date('YmdHis');
f0c3f9bc 185 $params['modified_id'] = CRM_Core_Session::getLoggedInContactID();
a7488080 186 if (!empty($params['created_date'])) {
6a488035
TO
187 $params['created_date'] = CRM_Utils_Date::processDate($params['created_date']);
188 }
189
190 if ($this->_action & CRM_Core_Action::ADD) {
b9a4cb6e
MW
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');
6a488035 193 $params['created_date'] = date('YmdHis');
d3d30c96 194 if (empty($params['created_id'])) {
f0c3f9bc 195 $params['created_id'] = CRM_Core_Session::getLoggedInContactID();
d3d30c96 196 }
6a488035 197 $details = "{$params['title']} batch has been created by this contact.";
03e04002 198 $activityTypeName = 'Create Batch';
6a488035
TO
199 }
200 elseif ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
201 $details = "{$params['title']} batch has been edited by this contact.";
b9a4cb6e 202 if ($params['status_id'] === $closedStatusId) {
6a488035
TO
203 $details = "{$params['title']} batch has been closed by this contact.";
204 }
205 $activityTypeName = 'Edit Batch';
206 }
207
b9a4cb6e
MW
208 // FIXME: What happens if we get to here and no activityType is defined?
209
92e088c9 210 $batch = CRM_Batch_BAO_Batch::create($params);
6a488035 211
d3d30c96
PN
212 //set batch id
213 $this->_id = $batch->id;
214
cded2ebf 215 // create activity.
be2fb01f 216 $activityParams = [
f3a784bb 217 // activityTypeName - dev/core#1116-unknown-if-ok
b9a4cb6e 218 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeName),
86bfa4f6 219 'subject' => $batch->title . "- Batch",
b9a4cb6e
MW
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'),
6a488035 222 'activity_date_time' => date('YmdHis'),
f0c3f9bc 223 'source_contact_id' => CRM_Core_Session::getLoggedInContactID(),
224 'source_contact_qid' => CRM_Core_Session::getLoggedInContactID(),
6a488035 225 'details' => $details,
be2fb01f 226 ];
6a488035
TO
227
228 CRM_Activity_BAO_Activity::create($activityParams);
229
230 $buttonName = $this->controller->getButtonName();
231
232 $context = $this->get("context");
233 if ($batch->title) {
be2fb01f 234 CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", [1 => $batch->title]), ts('Saved'), 'success');
6a488035
TO
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 }
b9a4cb6e 244 elseif ($batch->status_id === $closedStatusId) {
6a488035
TO
245 $session->replaceUserContext(CRM_Utils_System::url('civicrm', 'reset=1'));
246 }
247 elseif (($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::UPDATE) ||
353ffa53
TO
248 ($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::ADD & $context == 1)
249 ) {
6a488035
TO
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 /**
fe482240 260 * Global validation rules for the form.
6a488035 261 *
da6b46f4
EM
262 * @param $action
263 * @param $permissions
100fef9d
CW
264 * @param int $createdID
265 * @param int $userContactID
266 * @param string $actionName
da6b46f4 267 *
a6c01b45 268 * list of errors to be posted back to the form
6a488035 269 */
00be9182 270 public function checkPermissions($action, $permissions, $createdID, $userContactID, $actionName) {
6a488035
TO
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])) {
be2fb01f 273 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
6a488035
TO
274 }
275 }
276 else {
be2fb01f 277 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
6a488035
TO
278 }
279 }
e2046b33 280
6a488035 281}