Merge pull request #21199 from colemanw/fkDeleteBetter
[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 'delete':
202 $params = $recordID;
203 break;
204 }
205
206 if (method_exists($recordBAO, $methods[$op]) & !empty($params)) {
207 $updated = call_user_func_array(array($recordBAO, $methods[$op]), array(&$params));
208 if ($updated) {
209 $redirectStatus = $updated->status_id;
210 if ($batchStatus[$updated->status_id] == "Reopened") {
211 $redirectStatus = array_search("Open", $batchStatus);
212 }
213 $response = [
214 'status' => 'record-updated-success',
215 'status_id' => $redirectStatus,
216 ];
217 }
218 }
219 }
220 }
221 CRM_Utils_JSON::output($response);
222 }
223
224 /**
225 * This function uses the deprecated v1 datatable api and needs updating. See CRM-16353.
226 * @deprecated
227 *
228 * @return string|wtf??
229 */
230 public static function getFinancialTransactionsList() {
231 $sortMapper = [
232 0 => '',
233 1 => '',
234 2 => 'sort_name',
235 3 => 'amount',
236 4 => 'trxn_id',
237 5 => 'transaction_date',
238 6 => 'receive_date',
239 7 => 'payment_method',
240 8 => 'status',
241 9 => 'name',
242 ];
243
244 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
245 $return = isset($_REQUEST['return']) ? CRM_Utils_Type::escape($_REQUEST['return'], 'Boolean') : FALSE;
246 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
247 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
248 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
249 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
250 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
251 $entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL;
252 $notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL;
253 $statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL;
254 $search = isset($_REQUEST['search']);
255
256 $params = $_POST;
257 if ($sort && $sortOrder) {
258 $params['sortBy'] = $sort . ' ' . $sortOrder;
259 }
260
261 $returnvalues = [
262 'civicrm_financial_trxn.payment_instrument_id as payment_method',
263 'civicrm_contribution.contact_id as contact_id',
264 'civicrm_contribution.id as contributionID',
265 'contact_a.sort_name',
266 'civicrm_financial_trxn.total_amount as amount',
267 'civicrm_financial_trxn.trxn_id as trxn_id',
268 'contact_a.contact_type',
269 'contact_a.contact_sub_type',
270 'civicrm_financial_trxn.trxn_date as transaction_date',
271 'civicrm_contribution.receive_date as receive_date',
272 'civicrm_financial_type.name',
273 'civicrm_financial_trxn.currency as currency',
274 'civicrm_financial_trxn.status_id as status',
275 'civicrm_financial_trxn.check_number as check_number',
276 'civicrm_financial_trxn.card_type_id',
277 'civicrm_financial_trxn.pan_truncation',
278 ];
279
280 $columnHeader = [
281 'contact_type' => '',
282 'sort_name' => ts('Contact Name'),
283 'amount' => ts('Amount'),
284 'trxn_id' => ts('Trxn ID'),
285 'transaction_date' => ts('Transaction Date'),
286 'receive_date' => ts('Received'),
287 'payment_method' => ts('Payment Method'),
288 'status' => ts('Status'),
289 'name' => ts('Type'),
290 ];
291
292 if ($sort && $sortOrder) {
293 $params['sortBy'] = $sort . ' ' . $sortOrder;
294 }
295
296 $params['page'] = ($offset / $rowCount) + 1;
297 $params['rp'] = $rowCount;
298
299 $params['context'] = $context;
300 $params['offset'] = ($params['page'] - 1) * $params['rp'];
301 $params['rowCount'] = $params['rp'];
302 $params['sort'] = $params['sortBy'] ?? NULL;
303 $params['total'] = 0;
304
305 // get batch list
306 if (isset($notPresent)) {
307 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params);
308 if ($search) {
309 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params, TRUE);
310 }
311 else {
312 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, NULL, TRUE);
313 }
314 while ($unassignedTransactions->fetch()) {
315 $unassignedTransactionsCount[] = $unassignedTransactions->id;
316 }
317 if (!empty($unassignedTransactionsCount)) {
318 $params['total'] = count($unassignedTransactionsCount);
319 }
320
321 }
322 else {
323 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, NULL, $params);
324 $assignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues);
325 while ($assignedTransactions->fetch()) {
326 $assignedTransactionsCount[] = $assignedTransactions->id;
327 }
328 if (!empty($assignedTransactionsCount)) {
329 $params['total'] = count($assignedTransactionsCount);
330 }
331 }
332 $financialitems = [];
333 if ($statusID) {
334 $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name', 'condition' => " v.value={$statusID}"]);
335 $batchStatus = $batchStatuses[$statusID];
336 }
337 while ($financialItem->fetch()) {
338 $row[$financialItem->id] = [];
339 foreach ($columnHeader as $columnKey => $columnValue) {
340 if ($financialItem->contact_sub_type && $columnKey == 'contact_type') {
341 $row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type;
342 continue;
343 }
344 $row[$financialItem->id][$columnKey] = $financialItem->$columnKey;
345 if ($columnKey == 'sort_name' && $financialItem->$columnKey && $financialItem->contact_id) {
346 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=" . $financialItem->contact_id);
347 $row[$financialItem->id][$columnKey] = '<a href=' . $url . '>' . $financialItem->$columnKey . '</a>';
348 }
349 elseif ($columnKey == 'payment_method' && $financialItem->$columnKey) {
350 $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $financialItem->$columnKey);
351 if ($row[$financialItem->id][$columnKey] == 'Check') {
352 $checkNumber = $financialItem->check_number ? ' (' . $financialItem->check_number . ')' : '';
353 $row[$financialItem->id][$columnKey] = $row[$financialItem->id][$columnKey] . $checkNumber;
354 }
355 }
356 elseif ($columnKey == 'amount' && $financialItem->$columnKey) {
357 $row[$financialItem->id][$columnKey] = CRM_Utils_Money::format($financialItem->$columnKey, $financialItem->currency);
358 }
359 elseif ($columnKey == 'transaction_date' && $financialItem->$columnKey) {
360 $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
361 }
362 elseif ($columnKey == 'receive_date' && $financialItem->$columnKey) {
363 $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
364 }
365 elseif ($columnKey == 'status' && $financialItem->$columnKey) {
366 $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $financialItem->$columnKey);
367 }
368 }
369 if (isset($batchStatus) && in_array($batchStatus, ['Open', 'Reopened'])) {
370 if (isset($notPresent)) {
371 $js = "enableActions('x')";
372 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_x_" . $financialItem->id . "' name='mark_x_" . $financialItem->id . "' value='1' onclick={$js}></input>";
373 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
374 (new CRM_Financial_Form_BatchTransaction())->links(),
375 NULL,
376 [
377 'id' => $financialItem->id,
378 'contid' => $financialItem->contributionID,
379 'cid' => $financialItem->contact_id,
380 ],
381 ts('more'),
382 FALSE,
383 'financialItem.batch.row',
384 'FinancialItem',
385 $financialItem->id
386 );
387 }
388 else {
389 $js = "enableActions('y')";
390 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_y_" . $financialItem->id . "' name='mark_y_" . $financialItem->id . "' value='1' onclick={$js}></input>";
391 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
392 (new CRM_Financial_Page_BatchTransaction())->links(),
393 NULL,
394 [
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 }
407 else {
408 $row[$financialItem->id]['check'] = NULL;
409 $tempBAO = new CRM_Financial_Page_BatchTransaction();
410 $links = $tempBAO->links();
411 unset($links['remove']);
412 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
413 $links,
414 NULL,
415 [
416 'id' => $financialItem->id,
417 'contid' => $financialItem->contributionID,
418 'cid' => $financialItem->contact_id,
419 ],
420 ts('more'),
421 FALSE,
422 'financialItem.batch.row',
423 'FinancialItem',
424 $financialItem->id
425 );
426 }
427 if ($financialItem->contact_id) {
428 $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);
429 }
430 // @todo: Is this right? Shouldn't it be adding to the array as we loop?
431 $financialitems = $row;
432 }
433
434 $iFilteredTotal = $iTotal = $params['total'];
435 $selectorElements = [
436 'check',
437 'contact_type',
438 'sort_name',
439 'amount',
440 'trxn_id',
441 'transaction_date',
442 'receive_date',
443 'payment_method',
444 'status',
445 'name',
446 'action',
447 ];
448
449 if ($return) {
450 return CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
451 }
452 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
453 echo CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
454 CRM_Utils_System::civiExit();
455 }
456
457 public static function bulkAssignRemove() {
458 $checkIDs = $_REQUEST['ID'];
459 $entityID = CRM_Utils_Type::escape($_REQUEST['entityID'], 'String');
460 $action = CRM_Utils_Type::escape($_REQUEST['action'], 'String');
461 foreach ($checkIDs as $key => $value) {
462 if ((substr($value, 0, 7) == "mark_x_" && $action == 'Assign') || (substr($value, 0, 7) == "mark_y_" && $action == 'Remove')) {
463 $contributions = explode("_", $value);
464 $cIDs[] = $contributions[2];
465 }
466 }
467
468 $batchPID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $entityID, 'payment_instrument_id');
469 $paymentInstrument = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $batchPID);
470 foreach ($cIDs as $key => $value) {
471 $recordPID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $value, 'payment_instrument_id');
472 if ($action == 'Remove' || ($recordPID == $batchPID && $action == 'Assign') || !isset($batchPID)) {
473 $params = [
474 'entity_id' => $value,
475 'entity_table' => 'civicrm_financial_trxn',
476 'batch_id' => $entityID,
477 ];
478 if ($action == 'Assign') {
479 $updated = 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 $updated = $delete->execute()->count();
487 }
488 }
489 }
490 if ($updated) {
491 $status = ['status' => 'record-updated-success'];
492 }
493 else {
494 $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])];
495 }
496 CRM_Utils_JSON::output($status);
497 }
498
499 public static function getBatchSummary() {
500 $batchID = CRM_Utils_Type::escape($_REQUEST['batchID'], 'String');
501 $params = ['id' => $batchID];
502
503 $batchSummary = self::makeBatchSummary($batchID, $params);
504
505 CRM_Utils_JSON::output($batchSummary);
506 }
507
508 /**
509 * Makes an array of the batch's summary and returns array to parent getBatchSummary() function.
510 *
511 * @param $batchID
512 * @param $params
513 *
514 * @return array
515 */
516 public static function makeBatchSummary($batchID, $params) {
517 $batchInfo = CRM_Batch_BAO_Batch::retrieve($params, $value);
518 $batchTotals = CRM_Batch_BAO_Batch::batchTotals([$batchID]);
519 $batchSummary = [
520 'created_by' => CRM_Contact_BAO_Contact::displayName($batchInfo->created_id),
521 'status' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'status_id', $batchInfo->status_id),
522 'description' => $batchInfo->description,
523 'payment_instrument' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $batchInfo->payment_instrument_id),
524 'item_count' => $batchInfo->item_count,
525 'assigned_item_count' => $batchTotals[$batchID]['item_count'],
526 'total' => CRM_Utils_Money::format($batchInfo->total),
527 'assigned_total' => CRM_Utils_Money::format($batchTotals[$batchID]['total']),
528 'opened_date' => CRM_Utils_Date::customFormat($batchInfo->created_date),
529 ];
530
531 return $batchSummary;
532 }
533
534 }