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