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