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