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