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