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