redirection fixes after email invoice and code cleanup
[civicrm-core.git] / CRM / Financial / Page / AJAX.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
33 * $Id$
34 *
35 */
36
37 /**
38 * This class contains all the function that are called using AJAX
39 */
40 class CRM_Financial_Page_AJAX {
41 /*
42 * Function to get financial accounts of required account relationship
43 * $financialAccountType array with key account relationship and value financial account type option groups
44 *
45 */
46 /**
47 * @param $config
48 */
49 static function jqFinancial($config) {
50 if (!isset($_GET['_value']) ||
51 empty($_GET['_value'])) {
52 CRM_Utils_System::civiExit();
53 }
54 $defaultId = NULL;
55 if ($_GET['_value'] == 'select') {
56 $result = CRM_Contribute_PseudoConstant::financialAccount();
57 }
58 else {
59 $financialAccountType = array(
60 '5' => 5, //expense
61 '3' => 1, //AR relation
62 '1' => 3, //revenue
63 '6' => 1, // asset
64 '7' => 4, //cost of sales
65 '8' => 1, //premium inventory
66 '9' => 3, //discount account is
67 '10' => 2, //sales tax liability
68 );
69 $financialAccountType = CRM_Utils_Array::value($_GET['_value'], $financialAccountType);
70 $result = CRM_Contribute_PseudoConstant::financialAccount(NULL, $financialAccountType);
71 if ($financialAccountType) {
72 $defaultId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = $financialAccountType");
73 }
74 }
75 $elements = array(
76 array(
77 'name' => ts('- select -'),
78 'value' => 'select',
79 )
80 );
81
82 if (!empty($result)){
83 foreach ($result as $id => $name) {
84 $selectedArray = array();
85 if ($id == $defaultId) {
86 $selectedArray['selected'] = 'Selected';
87 }
88 $elements[] = array(
89 'name' => $name,
90 'value' => $id,
91 ) + $selectedArray;
92 }
93 }
94 echo json_encode($elements);
95 CRM_Utils_System::civiExit();
96 }
97
98 /**
99 * @param $config
100 */
101 static function jqFinancialRelation($config) {
102 if (!isset($_GET['_value']) ||
103 empty($_GET['_value'])) {
104 CRM_Utils_System::civiExit();
105 }
106
107 if ($_GET['_value'] == 'select') {
108 $result = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
109 }
110 else {
111 $financialAccountType = array(
112 '5' => array(5), //expense
113 '1' => array(3, 6, 8), //Asset
114 '3' => array(1, 9), //revenue
115 '4' => array(7), //cost of sales
116 );
117 $financialAccountTypeId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $_GET['_value'], 'financial_account_type_id');
118 $result = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
119 }
120
121 $elements = array(
122 array(
123 'name' => ts('- Select Financial Account Relationship -'),
124 'value' => 'select',
125 )
126 );
127
128 $countResult = count($financialAccountType[$financialAccountTypeId]);
129 if (!empty($result)) {
130 foreach ($result as $id => $name) {
131 if (in_array($id, $financialAccountType[$financialAccountTypeId]) && $_GET['_value'] != 'select') {
132 if ($countResult != 1){
133 $elements[] = array(
134 'name' => $name,
135 'value' => $id,
136 );
137 }
138 else {
139 $elements[] = array(
140 'name' => $name,
141 'value' => $id,
142 'selected' => 'Selected',
143 );
144 }
145 }
146 elseif ($_GET['_value'] == 'select'){
147 $elements[] = array(
148 'name' => $name,
149 'value' => $id,
150 );
151 }
152 }
153 }
154 echo json_encode($elements);
155 CRM_Utils_System::civiExit();
156 }
157
158 /**
159 * @param $config
160 */
161 static function jqFinancialType($config) {
162 if (! isset($_GET['_value']) ||
163 empty($_GET['_value'])) {
164 CRM_Utils_System::civiExit();
165 }
166
167 $elements = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Product', $_GET['_value'], 'financial_type_id');
168 echo json_encode($elements);
169 CRM_Utils_System::civiExit();
170 }
171
172 /**
173 * Callback to perform action on batch records.
174 */
175 static function assignRemove() {
176 $op = CRM_Utils_Type::escape($_POST['op'], 'String');
177 $recordBAO = CRM_Utils_Type::escape($_POST['recordBAO'], 'String');
178 foreach ($_POST['records'] as $record) {
179 $recordID = CRM_Utils_Type::escape($record, 'Positive', FALSE);
180 if ($recordID) {
181 $records[] = $recordID;
182 }
183 }
184
185 $entityID = CRM_Utils_Array::value('entityID', $_POST);
186 $methods = array(
187 'assign' => 'addBatchEntity',
188 'remove' => 'removeBatchEntity',
189 'reopen' => 'create',
190 'close' => 'create',
191 'delete' => 'deleteBatch',
192 );
193 if ($op == 'close') {
194 $totals = CRM_Batch_BAO_Batch::batchTotals($records);
195 }
196 $response = array('status' => 'record-updated-fail');
197 // first munge and clean the recordBAO and get rid of any non alpha numeric characters
198 $recordBAO = CRM_Utils_String::munge($recordBAO);
199 $recordClass = explode('_', $recordBAO);
200 // make sure recordClass is in the CRM namespace and
201 // at least 3 levels deep
202 if ($recordClass[0] == 'CRM' && count($recordClass) >= 3) {
203 foreach ($records as $recordID) {
204 $params = array();
205 $ids = null;
206 switch ($op) {
207 case 'assign':
208 case 'remove':
209 $recordPID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $recordID, 'payment_instrument_id');
210 $batchPID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $entityID, 'payment_instrument_id');
211 $paymentInstrument = CRM_Core_OptionGroup::getLabel('payment_instrument',$batchPID);
212 if ($op == 'remove' || ($recordPID == $batchPID && $op == 'assign') || !isset($batchPID)) {
213 $params = array(
214 'entity_id' => $recordID,
215 'entity_table' => 'civicrm_financial_trxn',
216 'batch_id' => $entityID,
217 );
218 }
219 else {
220 $response = array('status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", array( 1 => $paymentInstrument)));
221 }
222 break;
223 case 'close':
224 // Update totals when closing a batch
225 $params = $totals[$recordID];
226 case 'reopen':
227 $status = $op == 'close' ? 'Closed' : 'Reopened';
228 $ids['batchID'] = $recordID;
229 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
230 $params['status_id'] = CRM_Utils_Array::key($status, $batchStatus);
231 $session = CRM_Core_Session::singleton();
232 $params['modified_date'] = date('YmdHis');
233 $params['modified_id'] = $session->get('userID');
234 $params['id'] = $recordID;
235 $context = "financialBatch";
236 break;
237
238 case 'export':
239 CRM_Utils_System::redirect("civicrm/financial/batch/export?reset=1&id=$recordID");
240 break;
241
242 case 'delete':
243 $params = $recordID;
244 $context = "financialBatch";
245 break;
246 }
247
248 if (method_exists($recordBAO, $methods[$op]) & !empty($params)) {
249 if (isset($context)) {
250 $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params, $ids, $context));
251 }
252 else {
253 $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params, $ids));
254 }
255 if ($updated) {
256 $response = array('status' => 'record-updated-success');
257 }
258 }
259 }
260 }
261 echo json_encode($response);
262 CRM_Utils_System::civiExit();
263 }
264
265 static function getFinancialTransactionsList() {
266 $sortMapper =
267 array(
268 0 => '', 1 => '', 2 => 'sort_name',
269 3 => 'amount', 4 => 'trxn_id', 5 => 'transaction_date', 6 => 'payment_method', 7 => 'status', 8 => 'name',
270 );
271
272 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
273 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
274 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
275 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
276 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
277 $context = isset($_REQUEST['context']) ? CRM_Utils_Type::escape($_REQUEST['context'], 'String') : NULL;
278 $entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL;
279 $notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL;
280 $statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL;
281 $search = isset($_REQUEST['search']) ? TRUE : FALSE;
282
283 $params = $_POST;
284 if ($sort && $sortOrder) {
285 $params['sortBy'] = $sort . ' ' . $sortOrder;
286 }
287
288 $returnvalues =
289 array(
290 'civicrm_financial_trxn.payment_instrument_id as payment_method',
291 'civicrm_contribution.contact_id as contact_id',
292 'civicrm_contribution.id as contributionID',
293 'contact_a.sort_name',
294 'civicrm_financial_trxn.total_amount as amount',
295 'civicrm_financial_trxn.trxn_id as trxn_id',
296 'contact_a.contact_type',
297 'contact_a.contact_sub_type',
298 'civicrm_financial_trxn.trxn_date as transaction_date',
299 'name',
300 'civicrm_contribution.currency as currency',
301 'civicrm_financial_trxn.status_id as status',
302 'civicrm_financial_trxn.check_number as check_number',
303 );
304
305 $columnHeader =
306 array(
307 'contact_type' => '',
308 'sort_name' => ts('Contact Name'),
309 'amount' => ts('Amount'),
310 'trxn_id' => ts('Trxn ID'),
311 'transaction_date' => ts('Received'),
312 'payment_method' => ts('Payment Method'),
313 'status' => ts('Status'),
314 'name' => ts('Type'),
315 );
316
317 if ($sort && $sortOrder) {
318 $params['sortBy'] = $sort . ' ' . $sortOrder;
319 }
320
321 $params['page'] = ($offset / $rowCount) + 1;
322 $params['rp'] = $rowCount;
323
324 $params['context'] = $context;
325 $params['offset'] = ($params['page'] - 1) * $params['rp'];
326 $params['rowCount'] = $params['rp'];
327 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
328 $params['total'] = 0;
329
330 // get batch list
331 if (isset($notPresent)) {
332 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params);
333 if ($search) {
334 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params, TRUE);
335 }
336 else {
337 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, NULL, TRUE);
338 }
339 while ($unassignedTransactions->fetch()) {
340 $unassignedTransactionsCount[] = $unassignedTransactions->id;
341 }
342 if (!empty($unassignedTransactionsCount)) {
343 $params['total'] = count($unassignedTransactionsCount);
344 }
345
346 }
347 else {
348 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, NULL, $params);
349 $assignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues);
350 while ($assignedTransactions->fetch()) {
351 $assignedTransactionsCount[] = $assignedTransactions->id;
352 }
353 if (!empty($assignedTransactionsCount)) {
354 $params['total'] = count($assignedTransactionsCount);
355 }
356 }
357 $financialitems = array();
358 while ($financialItem->fetch()) {
359 $row[$financialItem->id] = array();
360 foreach ($columnHeader as $columnKey => $columnValue) {
361 if ($financialItem->contact_sub_type && $columnKey == 'contact_type') {
362 $row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type;
363 continue;
364 }
365 $row[$financialItem->id][$columnKey] = $financialItem->$columnKey;
366 if ($columnKey == 'sort_name' && $financialItem->$columnKey) {
367 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=".$financialItem->contact_id);
368 $row[$financialItem->id][$columnKey] = '<a href='.$url.'>'.$financialItem->$columnKey.'</a>';
369 }
370 elseif ($columnKey == 'payment_method' && $financialItem->$columnKey) {
371 $row[$financialItem->id][$columnKey] = CRM_Core_OptionGroup::getLabel('payment_instrument', $financialItem->$columnKey);
372 if ($row[$financialItem->id][$columnKey] == 'Check') {
373 $row[$financialItem->id][$columnKey] = $row[$financialItem->id][$columnKey].' ('.$financialItem->check_number.')';
374 }
375 }
376 elseif ($columnKey == 'amount' && $financialItem->$columnKey) {
377 $row[$financialItem->id][$columnKey] = CRM_Utils_Money::format($financialItem->$columnKey, $financialItem->currency);
378 }
379 elseif ($columnKey == 'transaction_date' && $financialItem->$columnKey) {
380 $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
381 }
382 elseif ($columnKey == 'status' && $financialItem->$columnKey) {
383 $row[$financialItem->id][$columnKey] = CRM_Core_OptionGroup::getLabel('contribution_status', $financialItem->$columnKey);
384 }
385 }
386 if ($statusID == CRM_Core_OptionGroup::getValue('batch_status','Open')) {
387 if (isset($notPresent)) {
388 $js = "enableActions('x')";
389 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_x_". $financialItem->id."' name='mark_x_". $financialItem->id."' value='1' onclick={$js}></input>";
390 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
391 CRM_Financial_Form_BatchTransaction::links(),
392 null,
393 array(
394 'id' => $financialItem->id,
395 'contid' => $financialItem->contributionID,
396 'cid' => $financialItem->contact_id
397 ),
398 ts('more'),
399 FALSE,
400 'financialItem.batch.row',
401 'FinancialItem',
402 $financialItem->id
403 );
404 }
405 else {
406 $js = "enableActions('y')";
407 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_y_". $financialItem->id."' name='mark_y_". $financialItem->id."' value='1' onclick={$js}></input>";
408 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
409 CRM_Financial_Page_BatchTransaction::links(),
410 null,
411 array(
412 'id' => $financialItem->id,
413 'contid' => $financialItem->contributionID,
414 'cid' => $financialItem->contact_id
415 ),
416 ts('more'),
417 FALSE,
418 'financialItem.batch.row',
419 'FinancialItem',
420 $financialItem->id
421 );
422 }
423 }
424 else {
425 $row[$financialItem->id]['check'] = NULL;
426 $links = CRM_Financial_Page_BatchTransaction::links();
427 unset($links['remove']);
428 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
429 $links,
430 null,
431 array(
432 'id' => $financialItem->id,
433 'contid' => $financialItem->contributionID,
434 'cid' => $financialItem->contact_id
435 ),
436 ts('more'),
437 FALSE,
438 'financialItem.batch.row',
439 'FinancialItem',
440 $financialItem->id
441 );
442 }
443 $row[$financialItem->id]['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage(CRM_Utils_Array::value('contact_sub_type',$row[$financialItem->id]) ? CRM_Utils_Array::value('contact_sub_type',$row[$financialItem->id]) : CRM_Utils_Array::value('contact_type',$row[$financialItem->id]) ,false, $financialItem->contact_id);
444 $financialitems = $row;
445 }
446
447 $iFilteredTotal = $iTotal = $params['total'];
448 $selectorElements =
449 array(
450 'check', 'contact_type', 'sort_name',
451 'amount', 'trxn_id', 'transaction_date', 'payment_method', 'status', 'name', 'action',
452 );
453
454 echo CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
455 CRM_Utils_System::civiExit();
456 }
457
458 static function bulkAssignRemove() {
459 $checkIDs = $_REQUEST['ID'];
460 $entityID = CRM_Utils_Type::escape($_REQUEST['entityID'], 'String');
461 $action = CRM_Utils_Type::escape($_REQUEST['action'], 'String');
462 foreach ($checkIDs as $key => $value) {
463 if ((substr($value,0,7) == "mark_x_" && $action == 'Assign') || (substr($value,0,7) == "mark_y_" && $action == 'Remove')) {
464 $contributions = explode("_",$value);
465 $cIDs[] = $contributions[2];
466 }
467 }
468
469 $batchPID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $entityID, 'payment_instrument_id');
470 $paymentInstrument = CRM_Core_OptionGroup::getLabel('payment_instrument',$batchPID);
471 foreach ($cIDs as $key => $value) {
472 $recordPID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $value, 'payment_instrument_id');
473 if ($action == 'Remove' || ($recordPID == $batchPID && $action == 'Assign') || !isset($batchPID)) {
474 $params =
475 array(
476 'entity_id' => $value,
477 'entity_table' => 'civicrm_financial_trxn',
478 'batch_id' => $entityID,
479 );
480 if ($action == 'Assign') {
481 $updated = CRM_Batch_BAO_Batch::addBatchEntity($params);
482 }
483 else {
484 $updated = CRM_Batch_BAO_Batch::removeBatchEntity($params);
485 }
486 }
487 }
488 if ($updated) {
489 $status = array('status' => 'record-updated-success');
490 }
491 else {
492 $status = array('status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", array( 1 => $paymentInstrument)));
493 }
494 echo json_encode($status);
495 CRM_Utils_System::civiExit();
496 }
497
498 static function getBatchSummary() {
499 $batchID = CRM_Utils_Type::escape($_REQUEST['batchID'], 'String');
500 $params = array('id' => $batchID);
501 $batchInfo = CRM_Batch_BAO_Batch::retrieve($params, $value);
502 $batchTotals = CRM_Batch_BAO_Batch::batchTotals(array($batchID));
503 $batchSummary =
504 array(
505 'created_by' => CRM_Contact_BAO_Contact::displayName($batchInfo->created_id),
506 'status' => CRM_Core_OptionGroup::getLabel('batch_status', $batchInfo->status_id),
507 'description' => $batchInfo->description,
508 'payment_instrument' => CRM_Core_OptionGroup::getLabel('payment_instrument', $batchInfo->payment_instrument_id),
509 'item_count' => $batchInfo->item_count,
510 'assigned_item_count' => $batchTotals[$batchID]['item_count'],
511 'total' => CRM_Utils_Money::format($batchInfo->total),
512 'assigned_total' => CRM_Utils_Money::format($batchTotals[$batchID]['total']),
513 'opened_date' => CRM_Utils_Date::customFormat($batchInfo->created_date),
514 );
515
516 echo json_encode($batchSummary);
517 CRM_Utils_System::civiExit();
518 }
519 }