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