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