Merge pull request #11495 from yashodha/CRM-21637
[civicrm-core.git] / CRM / Financial / Page / AJAX.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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' => 'create',
169 'remove' => 'del',
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 => 'receive_date',
259 7 => 'payment_method',
260 8 => 'status',
261 9 => 'name',
262 );
263
264 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
265 $return = isset($_REQUEST['return']) ? CRM_Utils_Type::escape($_REQUEST['return'], 'Boolean') : FALSE;
266 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
267 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
268 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
269 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
270 $context = isset($_REQUEST['context']) ? CRM_Utils_Type::escape($_REQUEST['context'], 'String') : NULL;
271 $entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL;
272 $notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL;
273 $statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL;
274 $search = isset($_REQUEST['search']) ? TRUE : FALSE;
275
276 $params = $_POST;
277 if ($sort && $sortOrder) {
278 $params['sortBy'] = $sort . ' ' . $sortOrder;
279 }
280
281 $returnvalues = array(
282 'civicrm_financial_trxn.payment_instrument_id as payment_method',
283 'civicrm_contribution.contact_id as contact_id',
284 'civicrm_contribution.id as contributionID',
285 'contact_a.sort_name',
286 'civicrm_financial_trxn.total_amount as amount',
287 'civicrm_financial_trxn.trxn_id as trxn_id',
288 'contact_a.contact_type',
289 'contact_a.contact_sub_type',
290 'civicrm_financial_trxn.trxn_date as transaction_date',
291 'civicrm_contribution.receive_date as receive_date',
292 'civicrm_financial_type.name',
293 'civicrm_financial_trxn.currency as currency',
294 'civicrm_financial_trxn.status_id as status',
295 'civicrm_financial_trxn.check_number as check_number',
296 'civicrm_financial_trxn.card_type_id',
297 'civicrm_financial_trxn.pan_truncation',
298 );
299
300 $columnHeader = array(
301 'contact_type' => '',
302 'sort_name' => ts('Contact Name'),
303 'amount' => ts('Amount'),
304 'trxn_id' => ts('Trxn ID'),
305 'transaction_date' => ts('Transaction Date'),
306 'receive_date' => ts('Received'),
307 'payment_method' => ts('Payment Method'),
308 'status' => ts('Status'),
309 'name' => ts('Type'),
310 );
311
312 if ($sort && $sortOrder) {
313 $params['sortBy'] = $sort . ' ' . $sortOrder;
314 }
315
316 $params['page'] = ($offset / $rowCount) + 1;
317 $params['rp'] = $rowCount;
318
319 $params['context'] = $context;
320 $params['offset'] = ($params['page'] - 1) * $params['rp'];
321 $params['rowCount'] = $params['rp'];
322 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
323 $params['total'] = 0;
324
325 // get batch list
326 if (isset($notPresent)) {
327 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params);
328 if ($search) {
329 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params, TRUE);
330 }
331 else {
332 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, NULL, TRUE);
333 }
334 while ($unassignedTransactions->fetch()) {
335 $unassignedTransactionsCount[] = $unassignedTransactions->id;
336 }
337 if (!empty($unassignedTransactionsCount)) {
338 $params['total'] = count($unassignedTransactionsCount);
339 }
340
341 }
342 else {
343 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, NULL, $params);
344 $assignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues);
345 while ($assignedTransactions->fetch()) {
346 $assignedTransactionsCount[] = $assignedTransactions->id;
347 }
348 if (!empty($assignedTransactionsCount)) {
349 $params['total'] = count($assignedTransactionsCount);
350 }
351 }
352 $financialitems = array();
353 if ($statusID) {
354 $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name', 'condition' => " v.value={$statusID}"));
355 $batchStatus = $batchStatuses[$statusID];
356 }
357 while ($financialItem->fetch()) {
358 $row[$financialItem->id] = array();
359 foreach ($columnHeader as $columnKey => $columnValue) {
360 if ($financialItem->contact_sub_type && $columnKey == 'contact_type') {
361 $row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type;
362 continue;
363 }
364 $row[$financialItem->id][$columnKey] = $financialItem->$columnKey;
365 if ($columnKey == 'sort_name' && $financialItem->$columnKey && $financialItem->contact_id) {
366 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=" . $financialItem->contact_id);
367 $row[$financialItem->id][$columnKey] = '<a href=' . $url . '>' . $financialItem->$columnKey . '</a>';
368 }
369 elseif ($columnKey == 'payment_method' && $financialItem->$columnKey) {
370 $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $financialItem->$columnKey);
371 if ($row[$financialItem->id][$columnKey] == 'Check') {
372 $checkNumber = $financialItem->check_number ? ' (' . $financialItem->check_number . ')' : '';
373 $row[$financialItem->id][$columnKey] = $row[$financialItem->id][$columnKey] . $checkNumber;
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 == 'receive_date' && $financialItem->$columnKey) {
383 $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
384 }
385 elseif ($columnKey == 'status' && $financialItem->$columnKey) {
386 $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $financialItem->$columnKey);
387 }
388 }
389 if (isset($batchStatus) && in_array($batchStatus, array('Open', 'Reopened'))) {
390 if (isset($notPresent)) {
391 $js = "enableActions('x')";
392 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_x_" . $financialItem->id . "' name='mark_x_" . $financialItem->id . "' value='1' onclick={$js}></input>";
393 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
394 CRM_Financial_Form_BatchTransaction::links(),
395 NULL,
396 array(
397 'id' => $financialItem->id,
398 'contid' => $financialItem->contributionID,
399 'cid' => $financialItem->contact_id,
400 ),
401 ts('more'),
402 FALSE,
403 'financialItem.batch.row',
404 'FinancialItem',
405 $financialItem->id
406 );
407 }
408 else {
409 $js = "enableActions('y')";
410 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_y_" . $financialItem->id . "' name='mark_y_" . $financialItem->id . "' value='1' onclick={$js}></input>";
411 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
412 CRM_Financial_Page_BatchTransaction::links(),
413 NULL,
414 array(
415 'id' => $financialItem->id,
416 'contid' => $financialItem->contributionID,
417 'cid' => $financialItem->contact_id,
418 ),
419 ts('more'),
420 FALSE,
421 'financialItem.batch.row',
422 'FinancialItem',
423 $financialItem->id
424 );
425 }
426 }
427 else {
428 $row[$financialItem->id]['check'] = NULL;
429 $tempBAO = new CRM_Financial_Page_BatchTransaction();
430 $links = $tempBAO->links();
431 unset($links['remove']);
432 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
433 $links,
434 NULL,
435 array(
436 'id' => $financialItem->id,
437 'contid' => $financialItem->contributionID,
438 'cid' => $financialItem->contact_id,
439 ),
440 ts('more'),
441 FALSE,
442 'financialItem.batch.row',
443 'FinancialItem',
444 $financialItem->id
445 );
446 }
447 if ($financialItem->contact_id) {
448 $row[$financialItem->id]['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage(CRM_Utils_Array::value('contact_sub_type', $row[$financialItem->id]) ? $row[$financialItem->id]['contact_sub_type'] : CRM_Utils_Array::value('contact_type', $row[$financialItem->id]), FALSE, $financialItem->contact_id);
449 }
450 $financialitems = $row;
451 }
452
453 $iFilteredTotal = $iTotal = $params['total'];
454 $selectorElements = array(
455 'check',
456 'contact_type',
457 'sort_name',
458 'amount',
459 'trxn_id',
460 'transaction_date',
461 'receive_date',
462 'payment_method',
463 'status',
464 'name',
465 'action',
466 );
467
468 if ($return) {
469 return CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
470 }
471 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
472 echo CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
473 CRM_Utils_System::civiExit();
474 }
475
476 public static function bulkAssignRemove() {
477 $checkIDs = $_REQUEST['ID'];
478 $entityID = CRM_Utils_Type::escape($_REQUEST['entityID'], 'String');
479 $action = CRM_Utils_Type::escape($_REQUEST['action'], 'String');
480 foreach ($checkIDs as $key => $value) {
481 if ((substr($value, 0, 7) == "mark_x_" && $action == 'Assign') || (substr($value, 0, 7) == "mark_y_" && $action == 'Remove')) {
482 $contributions = explode("_", $value);
483 $cIDs[] = $contributions[2];
484 }
485 }
486
487 $batchPID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $entityID, 'payment_instrument_id');
488 $paymentInstrument = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $batchPID);
489 foreach ($cIDs as $key => $value) {
490 $recordPID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $value, 'payment_instrument_id');
491 if ($action == 'Remove' || ($recordPID == $batchPID && $action == 'Assign') || !isset($batchPID)) {
492 $params = array(
493 'entity_id' => $value,
494 'entity_table' => 'civicrm_financial_trxn',
495 'batch_id' => $entityID,
496 );
497 if ($action == 'Assign') {
498 $updated = CRM_Batch_BAO_EntityBatch::create($params);
499 }
500 else {
501 $updated = CRM_Batch_BAO_EntityBatch::del($params);
502 }
503 }
504 }
505 if ($updated) {
506 $status = array('status' => 'record-updated-success');
507 }
508 else {
509 $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)));
510 }
511 CRM_Utils_JSON::output($status);
512 }
513
514 public static function getBatchSummary() {
515 $batchID = CRM_Utils_Type::escape($_REQUEST['batchID'], 'String');
516 $params = array('id' => $batchID);
517
518 $batchSummary = self::makeBatchSummary($batchID, $params);
519
520 CRM_Utils_JSON::output($batchSummary);
521 }
522
523 /**
524 * Makes an array of the batch's summary and returns array to parent getBatchSummary() function.
525 *
526 * @param $batchID
527 * @param $params
528 *
529 * @return array
530 */
531 public static function makeBatchSummary($batchID, $params) {
532 $batchInfo = CRM_Batch_BAO_Batch::retrieve($params, $value);
533 $batchTotals = CRM_Batch_BAO_Batch::batchTotals(array($batchID));
534 $batchSummary = array(
535 'created_by' => CRM_Contact_BAO_Contact::displayName($batchInfo->created_id),
536 'status' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'status_id', $batchInfo->status_id),
537 'description' => $batchInfo->description,
538 'payment_instrument' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $batchInfo->payment_instrument_id),
539 'item_count' => $batchInfo->item_count,
540 'assigned_item_count' => $batchTotals[$batchID]['item_count'],
541 'total' => CRM_Utils_Money::format($batchInfo->total),
542 'assigned_total' => CRM_Utils_Money::format($batchTotals[$batchID]['total']),
543 'opened_date' => CRM_Utils_Date::customFormat($batchInfo->created_date),
544 );
545
546 return $batchSummary;
547 }
548
549 }