Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-07-16-12-52-48
[civicrm-core.git] / CRM / Financial / Page / AJAX.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
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 * Function to get financial accounts of required account relationship
43 * $financialAccountType array with key account relationship and value financial account type option groups
44 *
45 */
46 /**
47 * @param $config
48 */
49 static function jqFinancial($config) {
50 if (!isset($_GET['_value']) ||
51 empty($_GET['_value'])) {
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 );
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 echo json_encode($elements);
94 CRM_Utils_System::civiExit();
95 }
96
97 /**
98 * @param $config
99 */
100 static function jqFinancialRelation($config) {
101 if (!isset($_GET['_value']) ||
102 empty($_GET['_value'])) {
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 echo json_encode($elements);
154 CRM_Utils_System::civiExit();
155 }
156
157 /**
158 * @param $config
159 */
160 static function jqFinancialType($config) {
161 if (! isset($_GET['_value']) ||
162 empty($_GET['_value'])) {
163 CRM_Utils_System::civiExit();
164 }
165
166 $elements = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Product', $_GET['_value'], 'financial_type_id');
167 echo json_encode($elements);
168 CRM_Utils_System::civiExit();
169 }
170
171 /**
172 * Callback to perform action on batch records.
173 */
174 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 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 echo json_encode($response);
261 CRM_Utils_System::civiExit();
262 }
263
264 static function getFinancialTransactionsList() {
265 $sortMapper =
266 array(
267 0 => '', 1 => '', 2 => 'sort_name',
268 3 => 'amount', 4 => 'trxn_id', 5 => 'transaction_date', 6 => 'payment_method', 7 => 'status', 8 => 'name',
269 );
270
271 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
272 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
273 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
274 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
275 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
276 $context = isset($_REQUEST['context']) ? CRM_Utils_Type::escape($_REQUEST['context'], 'String') : NULL;
277 $entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL;
278 $notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL;
279 $statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL;
280 $search = isset($_REQUEST['search']) ? TRUE : FALSE;
281
282 $params = $_POST;
283 if ($sort && $sortOrder) {
284 $params['sortBy'] = $sort . ' ' . $sortOrder;
285 }
286
287 $returnvalues =
288 array(
289 'civicrm_financial_trxn.payment_instrument_id as payment_method',
290 'civicrm_contribution.contact_id as contact_id',
291 'civicrm_contribution.id as contributionID',
292 'contact_a.sort_name',
293 'civicrm_financial_trxn.total_amount as amount',
294 'civicrm_financial_trxn.trxn_id as trxn_id',
295 'contact_a.contact_type',
296 'contact_a.contact_sub_type',
297 'civicrm_financial_trxn.trxn_date as transaction_date',
298 'name',
299 'civicrm_contribution.currency as currency',
300 'civicrm_financial_trxn.status_id as status',
301 'civicrm_financial_trxn.check_number as check_number',
302 );
303
304 $columnHeader =
305 array(
306 'contact_type' => '',
307 'sort_name' => ts('Contact Name'),
308 'amount' => ts('Amount'),
309 'trxn_id' => ts('Trxn ID'),
310 'transaction_date' => ts('Received'),
311 'payment_method' => ts('Payment Method'),
312 'status' => ts('Status'),
313 'name' => ts('Type'),
314 );
315
316 if ($sort && $sortOrder) {
317 $params['sortBy'] = $sort . ' ' . $sortOrder;
318 }
319
320 $params['page'] = ($offset / $rowCount) + 1;
321 $params['rp'] = $rowCount;
322
323 $params['context'] = $context;
324 $params['offset'] = ($params['page'] - 1) * $params['rp'];
325 $params['rowCount'] = $params['rp'];
326 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
327 $params['total'] = 0;
328
329 // get batch list
330 if (isset($notPresent)) {
331 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params);
332 if ($search) {
333 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params, TRUE);
334 }
335 else {
336 $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, NULL, TRUE);
337 }
338 while ($unassignedTransactions->fetch()) {
339 $unassignedTransactionsCount[] = $unassignedTransactions->id;
340 }
341 if (!empty($unassignedTransactionsCount)) {
342 $params['total'] = count($unassignedTransactionsCount);
343 }
344
345 }
346 else {
347 $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, NULL, $params);
348 $assignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues);
349 while ($assignedTransactions->fetch()) {
350 $assignedTransactionsCount[] = $assignedTransactions->id;
351 }
352 if (!empty($assignedTransactionsCount)) {
353 $params['total'] = count($assignedTransactionsCount);
354 }
355 }
356 $financialitems = array();
357 while ($financialItem->fetch()) {
358 $row[$financialItem->id] = array();
359 foreach ($columnHeader as $columnKey => $columnValue) {
360 if ($financialItem->contact_sub_type && $columnKey == 'contact_type') {
361 $row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type;
362 continue;
363 }
364 $row[$financialItem->id][$columnKey] = $financialItem->$columnKey;
365 if ($columnKey == 'sort_name' && $financialItem->$columnKey) {
366 $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=".$financialItem->contact_id);
367 $row[$financialItem->id][$columnKey] = '<a href='.$url.'>'.$financialItem->$columnKey.'</a>';
368 }
369 elseif ($columnKey == 'payment_method' && $financialItem->$columnKey) {
370 $row[$financialItem->id][$columnKey] = CRM_Core_OptionGroup::getLabel('payment_instrument', $financialItem->$columnKey);
371 if ($row[$financialItem->id][$columnKey] == 'Check') {
372 $row[$financialItem->id][$columnKey] = $row[$financialItem->id][$columnKey].' ('.$financialItem->check_number.')';
373 }
374 }
375 elseif ($columnKey == 'amount' && $financialItem->$columnKey) {
376 $row[$financialItem->id][$columnKey] = CRM_Utils_Money::format($financialItem->$columnKey, $financialItem->currency);
377 }
378 elseif ($columnKey == 'transaction_date' && $financialItem->$columnKey) {
379 $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->$columnKey);
380 }
381 elseif ($columnKey == 'status' && $financialItem->$columnKey) {
382 $row[$financialItem->id][$columnKey] = CRM_Core_OptionGroup::getLabel('contribution_status', $financialItem->$columnKey);
383 }
384 }
385 if ($statusID == CRM_Core_OptionGroup::getValue('batch_status','Open')) {
386 if (isset($notPresent)) {
387 $js = "enableActions('x')";
388 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_x_". $financialItem->id."' name='mark_x_". $financialItem->id."' value='1' onclick={$js}></input>";
389 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
390 CRM_Financial_Form_BatchTransaction::links(),
391 null,
392 array(
393 'id' => $financialItem->id,
394 'contid' => $financialItem->contributionID,
395 'cid' => $financialItem->contact_id
396 ),
397 ts('more'),
398 FALSE,
399 'financialItem.batch.row',
400 'FinancialItem',
401 $financialItem->id
402 );
403 }
404 else {
405 $js = "enableActions('y')";
406 $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_y_". $financialItem->id."' name='mark_y_". $financialItem->id."' value='1' onclick={$js}></input>";
407 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
408 CRM_Financial_Page_BatchTransaction::links(),
409 null,
410 array(
411 'id' => $financialItem->id,
412 'contid' => $financialItem->contributionID,
413 'cid' => $financialItem->contact_id
414 ),
415 ts('more'),
416 FALSE,
417 'financialItem.batch.row',
418 'FinancialItem',
419 $financialItem->id
420 );
421 }
422 }
423 else {
424 $row[$financialItem->id]['check'] = NULL;
425 $links = CRM_Financial_Page_BatchTransaction::links();
426 unset($links['remove']);
427 $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
428 $links,
429 null,
430 array(
431 'id' => $financialItem->id,
432 'contid' => $financialItem->contributionID,
433 'cid' => $financialItem->contact_id
434 ),
435 ts('more'),
436 FALSE,
437 'financialItem.batch.row',
438 'FinancialItem',
439 $financialItem->id
440 );
441 }
442 $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);
443 $financialitems = $row;
444 }
445
446 $iFilteredTotal = $iTotal = $params['total'];
447 $selectorElements =
448 array(
449 'check', 'contact_type', 'sort_name',
450 'amount', 'trxn_id', 'transaction_date', 'payment_method', 'status', 'name', 'action',
451 );
452
453 echo CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
454 CRM_Utils_System::civiExit();
455 }
456
457 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_OptionGroup::getLabel('payment_instrument',$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 array(
475 'entity_id' => $value,
476 'entity_table' => 'civicrm_financial_trxn',
477 'batch_id' => $entityID,
478 );
479 if ($action == 'Assign') {
480 $updated = CRM_Batch_BAO_Batch::addBatchEntity($params);
481 }
482 else {
483 $updated = CRM_Batch_BAO_Batch::removeBatchEntity($params);
484 }
485 }
486 }
487 if ($updated) {
488 $status = array('status' => 'record-updated-success');
489 }
490 else {
491 $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)));
492 }
493 echo json_encode($status);
494 CRM_Utils_System::civiExit();
495 }
496
497 static function getBatchSummary() {
498 $batchID = CRM_Utils_Type::escape($_REQUEST['batchID'], 'String');
499 $params = array('id' => $batchID);
500 $batchInfo = CRM_Batch_BAO_Batch::retrieve($params, $value);
501 $batchTotals = CRM_Batch_BAO_Batch::batchTotals(array($batchID));
502 $batchSummary =
503 array(
504 'created_by' => CRM_Contact_BAO_Contact::displayName($batchInfo->created_id),
505 'status' => CRM_Core_OptionGroup::getLabel('batch_status', $batchInfo->status_id),
506 'description' => $batchInfo->description,
507 'payment_instrument' => CRM_Core_OptionGroup::getLabel('payment_instrument', $batchInfo->payment_instrument_id),
508 'item_count' => $batchInfo->item_count,
509 'assigned_item_count' => $batchTotals[$batchID]['item_count'],
510 'total' => CRM_Utils_Money::format($batchInfo->total),
511 'assigned_total' => CRM_Utils_Money::format($batchTotals[$batchID]['total']),
512 'opened_date' => CRM_Utils_Date::customFormat($batchInfo->created_date),
513 );
514
515 echo json_encode($batchSummary);
516 CRM_Utils_System::civiExit();
517 }
518 }