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