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