Merge pull request #22599 from civicrm/5.46
[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 if ($op == 'remove' || $op == 'assign') {
174 $params = [
175 'entity_id' => $recordID,
176 'entity_table' => 'civicrm_financial_trxn',
177 'batch_id' => $entityID,
178 ];
179 }
180 break;
181
182 case 'close':
183 // Update totals when closing a batch
184 $params = $totals[$recordID];
185 case 'reopen':
186 $status = $op == 'close' ? 'Closed' : 'Reopened';
187 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
188 $params['status_id'] = CRM_Utils_Array::key($status, $batchStatus);
189 $session = CRM_Core_Session::singleton();
190 $params['modified_date'] = date('YmdHis');
191 $params['modified_id'] = $session->get('userID');
192 $params['id'] = $recordID;
193 break;
194
195 case 'delete':
196 $params = $recordID;
197 break;
198 }
199
200 if (method_exists($recordBAO, $methods[$op]) & !empty($params)) {
201 try {
202 $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params));
203 }
204 catch (\CRM_Core_Exception $e) {
205 $errorMessage = $e->getMessage();
206 }
207 if ($updated) {
208 $redirectStatus = $updated->status_id;
209 if ($batchStatus[$updated->status_id] == "Reopened") {
210 $redirectStatus = array_search("Open", $batchStatus);
211 }
212 $response = [
213 'status' => 'record-updated-success',
214 'status_id' => $redirectStatus,
215 ];
216 }
217 if ($errorMessage ?? FALSE) {
218 $response = ['status' => $errorMessage];
219 }
220 }
221 }
222 }
223 CRM_Utils_JSON::output($response);
224 }
225
226 /**
227 * This function uses the deprecated v1 datatable api and needs updating. See CRM-16353.
228 * @deprecated
229 *
230 * @return string|wtf??
231 */
232 public static function getFinancialTransactionsList() {
233 $sortMapper = [
234 0 => '',
235 1 => '',
236 2 => 'sort_name',
237 3 => 'amount',
238 4 => 'trxn_id',
239 5 => 'transaction_date',
240 6 => 'receive_date',
241 7 => 'payment_method',
242 8 => 'status',
243 9 => 'name',
244 ];
245
246 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
247 $return = isset($_REQUEST['return']) ? CRM_Utils_Type::escape($_REQUEST['return'], 'Boolean') : FALSE;
248 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
249 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
250 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
251 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
252 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
253 $entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL;
254 $notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL;
255 $statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL;
256 $search = isset($_REQUEST['search']);
257
258 $params = $_POST;
259 if ($sort && $sortOrder) {
260 $params['sortBy'] = $sort . ' ' . $sortOrder;
261 }
262
263 $returnvalues = [
264 'civicrm_financial_trxn.payment_instrument_id as payment_method',
265 'civicrm_contribution.contact_id as contact_id',
266 'civicrm_contribution.id as contributionID',
267 'contact_a.sort_name',
268 'civicrm_financial_trxn.total_amount as amount',
269 'civicrm_financial_trxn.trxn_id as trxn_id',
270 'contact_a.contact_type',
271 'contact_a.contact_sub_type',
272 'civicrm_financial_trxn.trxn_date as transaction_date',
273 'civicrm_contribution.receive_date as receive_date',
274 'civicrm_financial_type.name',
275 'civicrm_financial_trxn.currency as currency',
276 'civicrm_financial_trxn.status_id as status',
277 'civicrm_financial_trxn.check_number as check_number',
278 'civicrm_financial_trxn.card_type_id',
279 'civicrm_financial_trxn.pan_truncation',
280 ];
281
282 $columnHeader = [
283 'contact_type' => '',
284 'sort_name' => ts('Contact Name'),
285 'amount' => ts('Amount'),
286 'trxn_id' => ts('Trxn ID'),
287 'transaction_date' => ts('Transaction Date'),
288 'receive_date' => ts('Received'),
289 'payment_method' => ts('Payment Method'),
290 'status' => ts('Status'),
291 'name' => ts('Type'),
292 ];
293
294 if ($sort && $sortOrder) {
295 $params['sortBy'] = $sort . ' ' . $sortOrder;
296 }
297
298 $params['page'] = ($offset / $rowCount) + 1;
299 $params['rp'] = $rowCount;
300
301 $params['context'] = $context;
302 $params['offset'] = ($params['page'] - 1) * $params['rp'];
303 $params['rowCount'] = $params['rp'];
304 $params['sort'] = $params['sortBy'] ?? NULL;
305 $params['total'] = 0;
306
307 // get batch list
308 if (isset($notPresent)) {
309 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params);
310 if ($search) {
311 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params, TRUE);
312 }
313 else {
314 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, NULL, TRUE);
315 }
316 while ($unassignedTransactions->fetch()) {
317 $unassignedTransactionsCount[] = $unassignedTransactions->id;
318 }
319 if (!empty($unassignedTransactionsCount)) {
320 $params['total'] = count($unassignedTransactionsCount);
321 }
322
323 }
324 else {
325 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, NULL, $params);
326 $assignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues);
327 while ($assignedTransactions->fetch()) {
328 $assignedTransactionsCount[] = $assignedTransactions->id;
329 }
330 if (!empty($assignedTransactionsCount)) {
331 $params['total'] = count($assignedTransactionsCount);
332 }
333 }
334 $financialitems = [];
335 if ($statusID) {
336 $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name', 'condition' => " v.value={$statusID}"]);
337 $batchStatus = $batchStatuses[$statusID];
338 }
339 while ($financialItem->fetch()) {
340 $row[$financialItem->id] = [];
341 foreach ($columnHeader as $columnKey => $columnValue) {
342 if ($financialItem->contact_sub_type && $columnKey == 'contact_type') {
343 $row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type;
344 continue;
345 }
346 $row[$financialItem->id][$columnKey] = $financialItem->$columnKey;
347 if ($columnKey == 'sort_name' && $financialItem->$columnKey && $financialItem->contact_id) {
348 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=" . $financialItem->contact_id);
349 $row[$financialItem->id][$columnKey] = '<a href=' . $url . '>' . $financialItem->$columnKey . '</a>';
350 }
351 elseif ($columnKey == 'payment_method' && $financialItem->$columnKey) {
352 $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $financialItem->$columnKey);
353 if ($row[$financialItem->id][$columnKey] == 'Check') {
354 $checkNumber = $financialItem->check_number ? ' (' . $financialItem->check_number . ')' : '';
355 $row[$financialItem->id][$columnKey] = $row[$financialItem->id][$columnKey] . $checkNumber;
356 }
357 }
358 elseif ($columnKey == 'amount' && $financialItem->$columnKey) {
359 $row[$financialItem->id][$columnKey] = CRM_Utils_Money::format($financialItem->$columnKey, $financialItem->currency);
360 }
361 elseif ($columnKey == 'transaction_date' && $financialItem->$columnKey) {
362 $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
363 }
364 elseif ($columnKey == 'receive_date' && $financialItem->$columnKey) {
365 $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
366 }
367 elseif ($columnKey == 'status' && $financialItem->$columnKey) {
368 $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $financialItem->$columnKey);
369 }
370 }
371 if (isset($batchStatus) && in_array($batchStatus, ['Open', 'Reopened'])) {
372 if (isset($notPresent)) {
373 $js = "enableActions('x')";
374 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_x_" . $financialItem->id . "' name='mark_x_" . $financialItem->id . "' value='1' onclick={$js}></input>";
375 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
376 (new CRM_Financial_Form_BatchTransaction())->links(),
377 NULL,
378 [
379 'id' => $financialItem->id,
380 'contid' => $financialItem->contributionID,
381 'cid' => $financialItem->contact_id,
382 ],
383 ts('more'),
384 FALSE,
385 'financialItem.batch.row',
386 'FinancialItem',
387 $financialItem->id
388 );
389 }
390 else {
391 $js = "enableActions('y')";
392 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_y_" . $financialItem->id . "' name='mark_y_" . $financialItem->id . "' value='1' onclick={$js}></input>";
393 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
394 (new CRM_Financial_Page_BatchTransaction())->links(),
395 NULL,
396 [
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 }
409 else {
410 $row[$financialItem->id]['check'] = NULL;
411 $tempBAO = new CRM_Financial_Page_BatchTransaction();
412 $links = $tempBAO->links();
413 unset($links['remove']);
414 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
415 $links,
416 NULL,
417 [
418 'id' => $financialItem->id,
419 'contid' => $financialItem->contributionID,
420 'cid' => $financialItem->contact_id,
421 ],
422 ts('more'),
423 FALSE,
424 'financialItem.batch.row',
425 'FinancialItem',
426 $financialItem->id
427 );
428 }
429 if ($financialItem->contact_id) {
430 $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);
431 }
432 // @todo: Is this right? Shouldn't it be adding to the array as we loop?
433 $financialitems = $row;
434 }
435
436 $iFilteredTotal = $iTotal = $params['total'];
437 $selectorElements = [
438 'check',
439 'contact_type',
440 'sort_name',
441 'amount',
442 'trxn_id',
443 'transaction_date',
444 'receive_date',
445 'payment_method',
446 'status',
447 'name',
448 'action',
449 ];
450
451 if ($return) {
452 return CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
453 }
454 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
455 echo CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
456 CRM_Utils_System::civiExit();
457 }
458
459 public static function bulkAssignRemove() {
460 $checkIDs = $_REQUEST['ID'];
461 $entityID = CRM_Utils_Type::escape($_REQUEST['entityID'], 'String');
462 $action = CRM_Utils_Type::escape($_REQUEST['action'], 'String');
463 foreach ($checkIDs as $key => $value) {
464 if ((substr($value, 0, 7) == "mark_x_" && $action == 'Assign') || (substr($value, 0, 7) == "mark_y_" && $action == 'Remove')) {
465 $contributions = explode("_", $value);
466 $cIDs[] = $contributions[2];
467 }
468 }
469
470 foreach ($cIDs as $value) {
471 if ($action == 'Remove' || $action == 'Assign') {
472 $params = [
473 'entity_id' => $value,
474 'entity_table' => 'civicrm_financial_trxn',
475 'batch_id' => $entityID,
476 ];
477 try {
478 if ($action == 'Assign') {
479 CRM_Batch_BAO_EntityBatch::create($params);
480 }
481 else {
482 $delete = \Civi\Api4\EntityBatch::delete(FALSE);
483 foreach ($params as $field => $val) {
484 $delete->addWhere($field, '=', $val);
485 }
486 $delete->execute()->count();
487 }
488 }
489 catch (\CRM_Core_Exception $e) {
490 $errorMessage = $e->getMessage();
491 }
492 }
493 }
494 if ($errorMessage ?? FALSE) {
495 $status = ['status' => $errorMessage];
496 }
497 else {
498 $status = ['status' => 'record-updated-success'];
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 = ['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([$batchID]);
523 $batchSummary = [
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 }