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