Merge pull request #21943 from mattwire/gccacheignore
[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 use Civi\Api4\Batch;
19
20 /**
21 * This class contains all the function that are called using AJAX
22 */
23 class CRM_Financial_Page_AJAX {
24
25 /**
26 * get financial accounts of required account relationship.
27 * $financialAccountType array with key account relationship and value financial account type option groups
28 *
29 * @param $config
30 */
31 public static function jqFinancial($config) {
32 if (!isset($_GET['_value']) ||
33 empty($_GET['_value'])
34 ) {
35 CRM_Utils_System::civiExit();
36 }
37 $defaultId = NULL;
38 if ($_GET['_value'] == 'select') {
39 $result = CRM_Contribute_PseudoConstant::financialAccount();
40 }
41 else {
42 $financialAccountType = CRM_Financial_BAO_FinancialAccount::getfinancialAccountRelations();
43 $financialAccountType = $financialAccountType[$_GET['_value']] ?? NULL;
44 $result = CRM_Contribute_PseudoConstant::financialAccount(NULL, $financialAccountType);
45 if ($financialAccountType) {
46 $defaultId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = $financialAccountType");
47 }
48 }
49 $elements = [
50 [
51 'name' => ts('- select -'),
52 'value' => 'select',
53 ],
54 ];
55
56 if (!empty($result)) {
57 foreach ($result as $id => $name) {
58 $selectedArray = [];
59 if ($id == $defaultId) {
60 $selectedArray['selected'] = 'Selected';
61 }
62 $elements[] = [
63 'name' => $name,
64 'value' => $id,
65 ] + $selectedArray;
66 }
67 }
68 CRM_Utils_JSON::output($elements);
69 }
70
71 /**
72 * @param $config
73 */
74 public static function jqFinancialRelation($config) {
75 if (!isset($_GET['_value']) ||
76 empty($_GET['_value'])
77 ) {
78 CRM_Utils_System::civiExit();
79 }
80
81 if ($_GET['_value'] != 'select') {
82 $financialAccountType = CRM_Financial_BAO_FinancialAccount::getfinancialAccountRelations(TRUE);
83 $financialAccountId = CRM_Utils_Request::retrieve('_value', 'Positive');
84 $financialAccountTypeId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $financialAccountId, 'financial_account_type_id');
85 }
86 $params['orderColumn'] = 'label';
87 $result = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
88
89 $elements = [
90 [
91 'name' => ts('- Select Financial Account Relationship -'),
92 'value' => 'select',
93 ],
94 ];
95
96 $countResult = count($financialAccountType[$financialAccountTypeId]);
97 if (!empty($result)) {
98 foreach ($result as $id => $name) {
99 if (in_array($id, $financialAccountType[$financialAccountTypeId]) && $_GET['_value'] != 'select') {
100 if ($countResult != 1) {
101 $elements[] = [
102 'name' => $name,
103 'value' => $id,
104 ];
105 }
106 else {
107 $elements[] = [
108 'name' => $name,
109 'value' => $id,
110 'selected' => 'Selected',
111 ];
112 }
113 }
114 elseif ($_GET['_value'] == 'select') {
115 $elements[] = [
116 'name' => $name,
117 'value' => $id,
118 ];
119 }
120 }
121 }
122 CRM_Utils_JSON::output($elements);
123 }
124
125 /**
126 * @param $config
127 */
128 public static function jqFinancialType($config) {
129 if (!isset($_GET['_value']) ||
130 empty($_GET['_value'])
131 ) {
132 CRM_Utils_System::civiExit();
133 }
134 $productId = CRM_Utils_Request::retrieve('_value', 'Positive');
135 $elements = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Product', $productId, 'financial_type_id');
136 CRM_Utils_JSON::output($elements);
137 }
138
139 /**
140 * Callback to perform action on batch records.
141 */
142 public static function assignRemove() {
143 $op = CRM_Utils_Type::escape($_POST['op'], 'String');
144 $recordBAO = CRM_Utils_Type::escape($_POST['recordBAO'], 'String');
145 foreach ($_POST['records'] as $record) {
146 $recordID = CRM_Utils_Type::escape($record, 'Positive', FALSE);
147 if ($recordID) {
148 $records[] = $recordID;
149 }
150 }
151
152 $entityID = CRM_Utils_Request::retrieve('entityID', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST');
153 $methods = [
154 'assign' => 'create',
155 'remove' => 'del',
156 'reopen' => 'create',
157 'close' => 'create',
158 'delete' => 'deleteBatch',
159 ];
160 if ($op == 'close') {
161 $totals = CRM_Batch_BAO_Batch::batchTotals($records);
162 }
163 $response = ['status' => 'record-updated-fail'];
164 // first munge and clean the recordBAO and get rid of any non alpha numeric characters
165 $recordBAO = CRM_Utils_String::munge($recordBAO);
166 $recordClass = explode('_', $recordBAO);
167 // make sure recordClass is in the CRM namespace and
168 // at least 3 levels deep
169 if ($recordClass[0] == 'CRM' && count($recordClass) >= 3) {
170 foreach ($records as $recordID) {
171 $params = [];
172 switch ($op) {
173 case 'assign':
174 case 'remove':
175 if ($op == 'remove' || $op == 'assign') {
176 $params = [
177 'entity_id' => $recordID,
178 'entity_table' => 'civicrm_financial_trxn',
179 'batch_id' => $entityID,
180 ];
181 }
182 break;
183
184 case 'close':
185 // Update totals when closing a batch
186 $params = $totals[$recordID];
187 case 'reopen':
188 $status = $op == 'close' ? 'Closed' : 'Reopened';
189 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
190 $params['status_id'] = CRM_Utils_Array::key($status, $batchStatus);
191 $session = CRM_Core_Session::singleton();
192 $params['modified_date'] = date('YmdHis');
193 $params['modified_id'] = $session->get('userID');
194 $params['id'] = $recordID;
195 break;
196
197 case 'delete':
198 $params = $recordID;
199 break;
200 }
201
202 if (method_exists($recordBAO, $methods[$op]) & !empty($params)) {
203 try {
204 $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params));
205 }
206 catch (\CRM_Core_Exception $e) {
207 $errorMessage = $e->getMessage();
208 }
209 if ($updated) {
210 $redirectStatus = $updated->status_id;
211 if ($batchStatus[$updated->status_id] == "Reopened") {
212 $redirectStatus = array_search("Open", $batchStatus);
213 }
214 $response = [
215 'status' => 'record-updated-success',
216 'status_id' => $redirectStatus,
217 ];
218 }
219 if ($errorMessage ?? FALSE) {
220 $response = ['status' => $errorMessage];
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] = Civi::format()->money($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 (new 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 (new 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 // @todo: Is this right? Shouldn't it be adding to the array as we loop?
435 $financialitems = $row;
436 }
437
438 $iFilteredTotal = $iTotal = $params['total'];
439 $selectorElements = [
440 'check',
441 'contact_type',
442 'sort_name',
443 'amount',
444 'trxn_id',
445 'transaction_date',
446 'receive_date',
447 'payment_method',
448 'status',
449 'name',
450 'action',
451 ];
452
453 if ($return) {
454 return CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
455 }
456 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
457 echo CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
458 CRM_Utils_System::civiExit();
459 }
460
461 public static function bulkAssignRemove() {
462 $checkIDs = $_REQUEST['ID'];
463 $entityID = CRM_Utils_Type::escape($_REQUEST['entityID'], 'String');
464 $action = CRM_Utils_Type::escape($_REQUEST['action'], 'String');
465 foreach ($checkIDs as $key => $value) {
466 if ((substr($value, 0, 7) == "mark_x_" && $action == 'Assign') || (substr($value, 0, 7) == "mark_y_" && $action == 'Remove')) {
467 $contributions = explode("_", $value);
468 $cIDs[] = $contributions[2];
469 }
470 }
471
472 foreach ($cIDs as $value) {
473 if ($action == 'Remove' || $action == 'Assign') {
474 $params = [
475 'entity_id' => $value,
476 'entity_table' => 'civicrm_financial_trxn',
477 'batch_id' => $entityID,
478 ];
479 try {
480 if ($action == 'Assign') {
481 CRM_Batch_BAO_EntityBatch::create($params);
482 }
483 else {
484 $delete = \Civi\Api4\EntityBatch::delete(FALSE);
485 foreach ($params as $field => $val) {
486 $delete->addWhere($field, '=', $val);
487 }
488 $delete->execute()->count();
489 }
490 }
491 catch (\CRM_Core_Exception $e) {
492 $errorMessage = $e->getMessage();
493 }
494 }
495 }
496 if ($errorMessage ?? FALSE) {
497 $status = ['status' => $errorMessage];
498 }
499 else {
500 $status = ['status' => 'record-updated-success'];
501 }
502 CRM_Utils_JSON::output($status);
503 }
504
505 /**
506 * @throws \API_Exception
507 * @throws \CRM_Core_Exception
508 */
509 public static function getBatchSummary(): void {
510 CRM_Utils_JSON::output(self::makeBatchSummary(CRM_Utils_Type::escape($_REQUEST['batchID'], 'Integer')));
511 }
512
513 /**
514 * Get a summary of the batch..
515 *
516 * @param $batchID
517 *
518 * @return array
519 * @throws \API_Exception
520 * @throws \CRM_Core_Exception
521 */
522 public static function makeBatchSummary(int $batchID): array {
523 // We use permissions false because the old function did that & we
524 // have not tested to ensure permissions are correct - but ideally
525 // we would setCheckPermissions = TRUE.
526 $batchInfo = Batch::get(FALSE)
527 ->addWhere('id', '=', $batchID)
528 ->addSelect(
529 'description',
530 'item_count',
531 'total',
532 'created_date',
533 'created_id.display_name',
534 'status_id:label',
535 'payment_instrument_id:label'
536 )
537 ->execute()->first();
538 $batchTotals = CRM_Batch_BAO_Batch::batchTotals([$batchID]);
539 return [
540 'created_by' => $batchInfo['created_id.display_name'],
541 'status' => $batchInfo['status_id:label'],
542 'description' => $batchInfo['description'],
543 'payment_instrument' => $batchInfo['payment_instrument_id:label'],
544 'item_count' => $batchInfo['item_count'],
545 'assigned_item_count' => $batchTotals[$batchID]['item_count'],
546 'total' => Civi::format()->money($batchInfo['total']),
547 'assigned_total' => Civi::format()->money($batchTotals[$batchID]['total']),
548 'opened_date' => CRM_Utils_Date::customFormat($batchInfo['created_date']),
549 ];
550 }
551
552 }