Merge pull request #821 from dlobo/CRM-12674
[civicrm-core.git] / CRM / Financial / Form / FinancialBatch.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.3 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2013
33 * $Id$
34 *
35 */
36
37 /**
38 * This class generates form components for Accounting Batch
39 *
40 */
41 class CRM_Financial_Form_FinancialBatch extends CRM_Contribute_Form {
42
43 /**
44 * The financial batch id, used when editing the field
45 *
46 * @var int
47 * @access protected
48 */
49 protected $_id;
50
51 /**
52 * Function to set variables up before form is built
53 *
54 * @return void
55 * @access public
56 */
57 public function preProcess() {
58 $context = CRM_Utils_Request::retrieve('context', 'String', $this);
59 $this->set("context", $context);
60 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
61 parent::preProcess();
62 $session = CRM_Core_Session::singleton();
63 if ($this->_id) {
64 $permissions = array(
65 CRM_Core_Action::UPDATE => array(
66 'permission' => array(
67 'edit own manual batches',
68 'edit all manual batches',
69 ),
70 'actionName' => 'edit'),
71 CRM_Core_Action::DELETE => array(
72 'permission' => array(
73 'delete own manual batches',
74 'delete all manual batches',
75 ),
76 'actionName' => 'delete'),
77 );
78
79 $createdID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'created_id');
80 if (CRM_Utils_Array::value($this->_action, $permissions)) {
81 $this->checkPermissions($this->_action, $permissions[$this->_action]['permission'], $createdID, $session->get('userID'), $permissions[$this->_action]['actionName'] );
82 }
83 }
84 }
85
86 /**
87 * Function to build the form
88 *
89 * @return None
90 * @access public
91 */
92 public function buildQuickForm() {
93 parent::buildQuickForm();
94 if (isset( $this->_id)) {
95 $this->_title = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'title');
96 CRM_Utils_System::setTitle($this->_title .' - '.ts( 'Accounting Batch'));
97 $this->assign('batchTitle', $this->_title);
98 $contactID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'created_id');
99 $contactName = CRM_Contact_BAO_Contact::displayName($contactID);
100 $this->assign('contactName', $contactName);
101 }
102
103 $this->applyFilter('__ALL__', 'trim');
104
105 $this->addButtons(
106 array(
107 array(
108 'type' => 'next',
109 'name' => ts('Save'),
110 'isDefault' => true,
111 ),
112 array(
113 'type' => 'next',
114 'name' => ts('Save and New'),
115 'subName' => 'new',
116 ),
117 array(
118 'type' => 'cancel',
119 'name' => ts('Cancel'),
120 ),
121 )
122 );
123
124 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
125 $batchStatus = CRM_Core_PseudoConstant::accountOptionValues('batch_status');
126
127 //unset exported status
128 $exportedStatusId = CRM_Utils_Array::key('Exported', $batchStatus );
129 unset($batchStatus[$exportedStatusId]);
130 $this->add('select', 'status_id', ts('Batch Status'), array('' => ts('- select -')) + $batchStatus, true);
131 $this->freeze(array('status_id'));
132 }
133
134 $attributes = CRM_Core_DAO::getAttribute('CRM_Batch_DAO_Batch');
135
136 $this->add('text', 'title', ts('Batch Name'), $attributes['name'], true);
137
138 $this->add('textarea', 'description', ts('Description'), $attributes['description']);
139
140 $this->add('select', 'payment_instrument_id', ts('Payment Instrument'),
141 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
142 false
143 );
144
145 $this->add('text', 'total', ts('Total Amount'), $attributes['total']);
146
147 $this->add('text', 'item_count', ts('Number of Transactions'), $attributes['item_count']);
148 $this->addFormRule(array('CRM_Financial_Form_FinancialBatch', 'formRule'), $this);
149 }
150
151 /**
152 * This function sets the default values for the form. Note that in edit/view mode
153 * the default values are retrieved from the database
154 *
155 * @access public
156 *
157 * @return void
158 */
159 function setDefaultValues() {
160 $defaults = parent::setDefaultValues();
161
162 if ($this->_id) {
163 $this->assign('modified_date', $defaults['modified_date']);
164 $this->assign('created_date', $defaults['created_date']);
165 }
166 else {
167 // set batch name default
168 $defaults['title'] = CRM_Batch_BAO_Batch::generateBatchName();
169 }
170
171 return $defaults;
172 }
173
174 /**
175 * global validation rules for the form
176 *
177 * @param array $fields posted values of the form
178 *
179 * @return array list of errors to be posted back to the form
180 * @static
181 * @access public
182 */
183 static function formRule($values, $files, $self) {
184 $errors = array();
185 if (CRM_Utils_Array::value('contact_name', $values) && !is_numeric($values['created_id'])) {
186 $errors['contact_name'] = ts('Please select a valid contact.');
187 }
188 if ($values['item_count'] && (!is_numeric($values['item_count']) || $values['item_count'] < 1)) {
189 $errors['item_count'] = ts('Number of Transactions should a positive number');
190 }
191 if ($values['total'] && (!is_numeric($values['total']) || $values['total'] <= 0)) {
192 $errors['total'] = ts('Total Amount should be a positive number');
193 }
194 if (CRM_Utils_Array::value('created_date', $values) && date('Y-m-d') < date('Y-m-d', strtotime($values['created_date']))) {
195 $errors['created_date'] = ts('Created date cannot be greater than current date');
196 }
197 $batchName = $values['title'];
198 if (!CRM_Core_DAO::objectExists($batchName, 'CRM_Batch_DAO_Batch', $self->_id)) {
199 $errors['title'] = ts('This name already exists in database. Batch names must be unique.');
200 }
201 return CRM_Utils_Array::crmIsEmptyArray($errors) ? true : $errors;
202 }
203
204 /**
205 * Function to process the form
206 *
207 * @access public
208 * @return None
209 */
210 public function postProcess() {
211 $session = CRM_Core_Session::singleton();
212 $ids = array();
213 $params = $this->exportValues();
214 $batchStatus = CRM_Core_PseudoConstant::accountOptionValues('batch_status');
215 if ($this->_id) {
216 $ids['batchID'] = $this->_id;
217 $params['id'] = $this->_id;
218 }
219
220 // store the submitted values in an array
221 $params['modified_date'] = date('YmdHis');
222 $params['modified_id'] = $session->get('userID');
223 if (CRM_Utils_Array::value('created_date', $params)) {
224 $params['created_date'] = CRM_Utils_Date::processDate($params['created_date']);
225 }
226
227 if ($this->_action & CRM_Core_Action::ADD) {
228 $batchMode = CRM_Core_PseudoConstant::getBatchMode('name');
229 $params['mode_id'] = CRM_Utils_Array::key('Manual Batch', $batchMode);
230 $params['status_id'] = CRM_Utils_Array::key('Open', $batchStatus);
231 $params['created_date'] = date('YmdHis');
232 $params['created_id'] = $session->get('userID');
233 $details = "{$params['title']} batch has been created by this contact.";
234 $activityTypeName = 'Create Batch';
235 }
236 elseif ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
237 $details = "{$params['title']} batch has been edited by this contact.";
238 if (CRM_Utils_Array::value($params['status_id'], $batchStatus) == 'Closed') {
239 $details = "{$params['title']} batch has been closed by this contact.";
240 }
241 $activityTypeName = 'Edit Batch';
242 }
243
244 $batch = CRM_Batch_BAO_Batch::create($params, $ids, 'financialBatch');
245
246 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
247
248 //create activity.
249 $activityParams = array(
250 'activity_type_id' => array_search($activityTypeName, $activityTypes),
251 'subject' => $batch->title ."- Batch",
252 'status_id' => 2,
253 'priority_id' => 2,
254 'activity_date_time' => date('YmdHis'),
255 'source_contact_id' => $session->get('userID'),
256 'source_contact_qid' => $session->get('userID'),
257 'details' => $details,
258 );
259
260 CRM_Activity_BAO_Activity::create($activityParams);
261
262 $buttonName = $this->controller->getButtonName();
263
264 $context = $this->get("context");
265 if ($batch->title) {
266 CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", array(1 => $batch->title)), ts('Saved'), 'success');
267 }
268 if ($buttonName == $this->getButtonName('next', 'new') & $this->_action == CRM_Core_Action::UPDATE) {
269 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
270 "reset=1&action=add&context=1"));
271 }
272 elseif ($buttonName == $this->getButtonName('next', 'new')) {
273 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
274 "reset=1&action=add"));
275 }
276 elseif (CRM_Utils_Array::value($batch->status_id, $batchStatus) == 'Closed') {
277 $session->replaceUserContext(CRM_Utils_System::url('civicrm', 'reset=1'));
278 }
279 elseif (($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::UPDATE) ||
280 ($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::ADD & $context == 1 )) {
281 $session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/financialbatches',
282 "reset=1&batchStatus=1"));
283 }
284 else {
285 $session->replaceUserContext(CRM_Utils_System::url('civicrm/batchtransaction',
286 "reset=1&bid={$batch->id}"));
287 }
288 }
289
290 /**
291 * global validation rules for the form
292 *
293 * @param array $fields posted values of the form
294 *
295 * @return array list of errors to be posted back to the form
296 * @static
297 * @access public
298 */
299 function checkPermissions($action, $permissions, $createdID, $userContactID, $actionName) {
300 if ((CRM_Core_Permission::check($permissions[0]) || CRM_Core_Permission::check($permissions[1]))) {
301 if (CRM_Core_Permission::check($permissions[0]) && $userContactID != $createdID && !CRM_Core_Permission::check($permissions[1])) {
302 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), array(1 => $actionName));
303 }
304 }
305 else {
306 CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), array(1 => $actionName));
307 }
308 }
309 }
310
311