Merge pull request #2423 from eileenmcnaughton/CRM-14139-static
[civicrm-core.git] / CRM / Batch / BAO / Batch.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36/**
37 *
38 */
39class CRM_Batch_BAO_Batch extends CRM_Batch_DAO_Batch {
40
41 /**
42 * Cache for the current batch object
43 */
44 static $_batch = NULL;
45
46 /**
47 * Not sure this is the best way to do this. Depends on how exportFinancialBatch() below gets called.
48 * Maybe a parameter to that function is better.
49 */
50 static $_exportFormat = NULL;
51
52 /**
53 * Create a new batch
54 *
55 * @param array $params associated array
56 * @param array $ids associated array of ids
57 * @param string $context string
58 *
59 * @return object $batch batch object
60 * @access public
61 */
62 static function create(&$params, $ids = NULL, $context = NULL) {
a7488080 63 if (empty($params['id'])) {
6a488035
TO
64 $params['name'] = CRM_Utils_String::titleToVar($params['title']);
65 }
66
67 $batch = new CRM_Batch_DAO_Batch();
68 $batch->copyValues($params);
8cc574cf 69 if ($context == 'financialBatch' && !empty($ids['batchID'])) {
6a488035
TO
70 $batch->id = $ids['batchID'];
71 }
72 $batch->save();
73
74 return $batch;
75 }
76
77 /**
78 * Retrieve the information about the batch
79 *
80 * @param array $params (reference ) an assoc array of name/value pairs
81 * @param array $defaults (reference ) an assoc array to hold the flattened values
82 *
83 * @return array CRM_Batch_BAO_Batch object on success, null otherwise
84 * @access public
85 * @static
86 */
87 static function retrieve(&$params, &$defaults) {
88 $batch = new CRM_Batch_DAO_Batch();
89 $batch->copyValues($params);
90 if ($batch->find(TRUE)) {
91 CRM_Core_DAO::storeValues($batch, $defaults);
92 return $batch;
93 }
94 return NULL;
95 }
96
97 /**
98 * Get profile id associated with the batch type
99 *
100 * @param int $batchTypeId batch type id
101 *
102 * @return int $profileId profile id
103 * @static
104 */
105 static function getProfileId($batchTypeId) {
106 //retrieve the profile specific to batch type
107 switch ($batchTypeId) {
108 case 1:
109 //batch profile used for contribution
110 $profileName = "contribution_batch_entry";
111 break;
112
113 case 2:
114 //batch profile used for memberships
115 $profileName = "membership_batch_entry";
116 }
117
118 // get and return the profile id
119 return CRM_Core_DAO::getFieldValue('CRM_Core_BAO_UFGroup', $profileName, 'id', 'name');
120 }
121
122 /**
123 * generate batch name
124 *
125 * @return batch name
126 * @static
127 */
128 static function generateBatchName() {
129 $sql = "SELECT max(id) FROM civicrm_batch";
130 $batchNo = CRM_Core_DAO::singleValueQuery($sql) + 1;
131 return ts('Batch %1', array(1 => $batchNo)) . ': ' . date('Y-m-d');
132 }
133
134 /**
135 * create entity batch entry
136 * @param array $params associated array
137 * @return batch array
138 * @access public
139 */
140 static function addBatchEntity(&$params) {
141 $entityBatch = new CRM_Batch_DAO_EntityBatch();
142 $entityBatch->copyValues($params);
143 $entityBatch->save();
144 return $entityBatch;
145 }
146
147 /**
148 * Remove entries from entity batch
149 * @param array $params associated array
150 * @return object CRM_Batch_DAO_EntityBatch
151 */
152 static function removeBatchEntity($params) {
153 $entityBatch = new CRM_Batch_DAO_EntityBatch();
154 $entityBatch->copyValues($params);
155 $entityBatch->delete();
156 return $entityBatch;
157 }
158
159 /**
160 * function to delete batch entry
161 *
162 * @param int $batchId batch id
163 *
164 * @return void
165 * @access public
166 */
167 static function deleteBatch($batchId) {
6a488035
TO
168 // delete entry from batch table
169 $batch = new CRM_Batch_DAO_Batch();
170 $batch->id = $batchId;
171 $batch->delete();
172 return true;
173 }
174
6a488035
TO
175 /**
176 * This function is a wrapper for ajax batch selector
177 *
178 * @param array $params associated array for params record id.
179 *
180 * @return array $batchList associated array of batch list
181 * @access public
182 */
183 public function getBatchListSelector(&$params) {
184 // format the params
185 $params['offset'] = ($params['page'] - 1) * $params['rp'];
186 $params['rowCount'] = $params['rp'];
187 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
188
189 // get batches
190 $batches = self::getBatchList($params);
191
192 // get batch totals for open batches
193 $fetchTotals = array();
194 if ($params['context'] == 'financialBatch') {
195 foreach ($batches as $id => $batch) {
196 if ($batch['status_id'] == 1) {
197 $fetchTotals[] = $id;
198 }
199 }
200 }
201 $totals = self::batchTotals($fetchTotals);
202
203 // add count
204 $params['total'] = self::getBatchCount($params);
205
206 // format params and add links
207 $batchList = array();
208
209 foreach ($batches as $id => $value) {
210 $batch = array();
211 if ($params['context'] == 'financialBatch') {
212 $batch['check'] = $value['check'];
213 }
214 $batch['batch_name'] = $value['title'];
215 $batch['total'] = $batch['item_count'] = '';
216 $batch['payment_instrument'] = $value['payment_instrument'];
217 $batch['item_count'] = CRM_Utils_Array::value('item_count', $value);
a7488080 218 if (!empty($value['total'])) {
6a488035
TO
219 $batch['total'] = CRM_Utils_Money::format($value['total']);
220 }
221
222 // Compare totals with actuals
223 if (isset($totals[$id])) {
224 $batch['item_count'] = self::displayTotals($totals[$id]['item_count'], $batch['item_count']);
225 $batch['total'] = self::displayTotals(CRM_Utils_Money::format($totals[$id]['total']), $batch['total']);
226 }
227 $batch['status'] = $value['batch_status'];
228 $batch['created_by'] = $value['created_by'];
229 $batch['links'] = $value['action'];
230 $batchList[$id] = $batch;
231 }
232 return $batchList;
233 }
234
235 /**
236 * Get list of batches
237 *
238 * @param array $params associated array for params
239 * @access public
240 */
241 static function getBatchList(&$params) {
242 $whereClause = self::whereClause($params);
243
244 if (!empty($params['rowCount']) && is_numeric($params['rowCount'])
245 && is_numeric($params['offset']) && $params['rowCount'] > 0
246 ) {
247 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
248 }
249
250 $orderBy = ' ORDER BY batch.id desc';
251 if (!empty($params['sort'])) {
21d32567 252 $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
6a488035
TO
253 }
254
255 $query = "
256 SELECT batch.*, c.sort_name created_by
257 FROM civicrm_batch batch
258 INNER JOIN civicrm_contact c ON batch.created_id = c.id
259 WHERE {$whereClause}
260 {$orderBy}
261 {$limit}";
262
263 $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Batch_DAO_Batch');
a7488080 264 if (!empty($params['context'])) {
6a488035
TO
265 $links = self::links($params['context']);
266 }
267 else {
268 $links = self::links();
269 }
270
97afa853
AS
271 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id');
272 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
6a488035
TO
273 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
274
275 $results = array();
276 while ($object->fetch()) {
277 $values = array();
278 $newLinks = $links;
279 CRM_Core_DAO::storeValues($object, $values);
280 $action = array_sum(array_keys($newLinks));
281
282 if ($values['status_id'] == 2 && $params['context'] != 'financialBatch') {
283 $newLinks = array();
284 }
285 elseif ($params['context'] == 'financialBatch') {
0b0941e2
DL
286 $values['check'] =
287 "<input type='checkbox' id='check_" .
288 $object->id .
289 "' name='check_" .
290 $object->id .
291 "' value='1' data-status_id='" .
292 $values['status_id']."' class='select-row'></input>";
6a488035
TO
293
294 switch ($values['status_id']) {
295 case '1':
296 CRM_Utils_Array::remove($newLinks, 'reopen', 'download');
297 break;
298 case '2':
299 CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'download');
300 break;
301 case '5':
302 CRM_Utils_Array::remove($newLinks, 'close', 'edit', 'reopen', 'export');
303 }
304 }
a7488080 305 if (!empty($values['type_id'])) {
6a488035
TO
306 $values['batch_type'] = $batchTypes[$values['type_id']];
307 }
308 $values['batch_status'] = $batchStatus[$values['status_id']];
309 $values['created_by'] = $object->created_by;
310 $values['payment_instrument'] = '';
311 if (!empty($object->payment_instrument_id)) {
312 $values['payment_instrument'] = $paymentInstrument[$object->payment_instrument_id];
313 }
314 $tokens = array('id' => $object->id, 'status' => $values['status_id']);
315 if ($values['status_id'] == CRM_Core_OptionGroup::getValue('batch_status', 'Exported')) {
316 $aid = CRM_Core_OptionGroup::getValue('activity_type','Export Accounting Batch');
0b0941e2 317 $activityParams = array('source_record_id' => $object->id, 'activity_type_id' => $aid);
6a488035 318 $exportActivity = CRM_Activity_BAO_Activity::retrieve($activityParams, $val);
0b0941e2 319 $fid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $exportActivity->id, 'file_id', 'entity_id');
6a488035
TO
320 $tokens = array_merge(array('eid' => $exportActivity->id, 'fid' => $fid), $tokens);
321 }
322 $values['action'] = CRM_Core_Action::formLink(
323 $newLinks,
324 $action,
c51d1602 325 $tokens,
87dab4a4
AH
326 ts('more'),
327 FALSE,
328 'batch.selector.row',
329 'Batch',
330 $object->id
6a488035
TO
331 );
332 $results[$object->id] = $values;
333 }
334
335 return $results;
336 }
337
338 /**
339 * Get count of batches
340 *
341 * @param array $params associated array for params
342 * @access public
343 */
b11c92be 344 public static function getBatchCount(&$params) {
6a488035
TO
345 $args = array();
346 $whereClause = self::whereClause($params, $args);
347 $query = " SELECT COUNT(*) FROM civicrm_batch batch
348 INNER JOIN civicrm_contact c ON batch.created_id = c.id
349 WHERE {$whereClause}";
350 return CRM_Core_DAO::singleValueQuery($query);
351 }
352
353 /**
354 * Format where clause for getting lists of batches
355 *
356 * @param array $params associated array for params
357 * @access public
358 */
b11c92be 359 public static function whereClause($params) {
6a488035
TO
360 $clauses = array();
361 // Exclude data-entry batches
362 if (empty($params['status_id'])) {
363 $clauses[] = 'batch.status_id <> 3';
364 }
365
366 $fields = array(
367 'title' => 'String',
368 'sort_name' => 'String',
369 'status_id' => 'Integer',
370 'payment_instrument_id' => 'Integer',
371 'item_count' => 'Integer',
372 'total' => 'Float',
373 );
374
375 foreach ($fields as $field => $type) {
376 $table = $field == 'sort_name' ? 'c' : 'batch';
377 if (isset($params[$field])) {
378 $value = CRM_Utils_Type::escape($params[$field], $type, FALSE);
379 if ($value && $type == 'String') {
380 $clauses[] = "$table.$field LIKE '%$value%'";
381 }
382 elseif ($value && $type == 'Float') {
383 $clauses[] = "$table.$field = '$value'";
384 }
385 elseif ($value) {
386 $clauses[] = "$table.$field = $value";
387 }
388 }
389 }
390 return $clauses ? implode(' AND ', $clauses) : '1';
391 }
392
393 /**
394 * Function to define action links
395 *
396 * @return array $links array of action links
397 * @access public
398 */
399 function links($context = NULL) {
400 if ($context == 'financialBatch') {
401 $links = array(
402 'transaction' => array(
403 'name' => ts('Transactions'),
404 'url' => 'civicrm/batchtransaction',
405 'qs' => 'reset=1&bid=%%id%%',
406 'title' => ts('View/Add Transactions to Batch'),
407 ),
408 'edit' => array(
409 'name' => ts('Edit'),
410 'url' => 'civicrm/financial/batch',
411 'qs' => 'reset=1&action=update&id=%%id%%&context=1',
412 'title' => ts('Edit Batch'),
413 ),
414 'close' => array(
415 'name' => ts('Close'),
416 'title' => ts('Close Batch'),
417 'url' => '#',
418 'extra' => 'rel="close"',
419 ),
420 'export' => array(
421 'name' => ts('Export'),
422 'title' => ts('Export Batch'),
423 'url' => '#',
424 'extra' => 'rel="export"',
425 ),
426 'reopen' => array(
427 'name' => ts('Re-open'),
428 'title' => ts('Re-open Batch'),
429 'url' => '#',
430 'extra' => 'rel="reopen"',
431 ),
432 'delete' => array(
433 'name' => ts('Delete'),
434 'title' => ts('Delete Batch'),
435 'url' => '#',
436 'extra' => 'rel="delete"',
437 ),
438 'download' => array(
439 'name' => ts('Download'),
440 'url' => 'civicrm/file',
441 'qs' => 'reset=1&id=%%fid%%&eid=%%eid%%',
442 'title' => ts('Download Batch'),
443 )
444 );
445 }
446 else {
447 $links = array(
448 CRM_Core_Action::COPY => array(
449 'name' => ts('Enter records'),
450 'url' => 'civicrm/batch/entry',
451 'qs' => 'id=%%id%%&reset=1',
452 'title' => ts('Batch Data Entry'),
453 ),
454 CRM_Core_Action::UPDATE => array(
455 'name' => ts('Edit'),
456 'url' => 'civicrm/batch',
457 'qs' => 'action=update&id=%%id%%&reset=1',
458 'title' => ts('Edit Batch'),
459 ),
460 CRM_Core_Action::DELETE => array(
461 'name' => ts('Delete'),
462 'url' => 'civicrm/batch',
463 'qs' => 'action=delete&id=%%id%%',
464 'title' => ts('Delete Batch'),
465 )
466 );
467 }
468 return $links;
469 }
470
471 /**
472 * function to get batch list
473 *
acb4ca2f 474 * @return array array of all batches
c8f66220 475 * excluding batches with data entry in progress
6a488035
TO
476 */
477 static function getBatches() {
acb4ca2f
DG
478 $dataEntryStatusId = CRM_Core_OptionGroup::getValue('batch_status','Data Entry');
479 $query = "SELECT id, title
6a488035 480 FROM civicrm_batch
acb4ca2f
DG
481 WHERE item_count >= 1
482 AND status_id != {$dataEntryStatusId}
483 ORDER BY id DESC";
6a488035
TO
484
485 $batches = array();
486 $dao = CRM_Core_DAO::executeQuery($query);
487 while ( $dao->fetch( ) ) {
488 $batches[$dao->id] = $dao->title;
489 }
490 return $batches;
491 }
492
493
494
495 /**
496 * Calculate sum of all entries in a batch
497 * Used to validate and update item_count and total when closing an accounting batch
498 *
499 * @param array $batchIds
500 * @return array
501 */
502 static function batchTotals($batchIds) {
503 $totals = array_fill_keys($batchIds, array('item_count' => 0, 'total' => 0));
504 if ($batchIds) {
505 $sql = "SELECT eb.batch_id, COUNT(tx.id) AS item_count, SUM(tx.total_amount) AS total
506 FROM civicrm_entity_batch eb
507 INNER JOIN civicrm_financial_trxn tx ON tx.id = eb.entity_id AND eb.entity_table = 'civicrm_financial_trxn'
508 WHERE eb.batch_id IN (" . implode(',', $batchIds) . ")
509 GROUP BY eb.batch_id";
510 $dao = CRM_Core_DAO::executeQuery($sql);
511 while ($dao->fetch()) {
512 $totals[$dao->batch_id] = (array) $dao;
513 }
514 $dao->free();
515 }
516 return $totals;
517 }
518
519 /**
520 * Format markup for comparing two totals
521 *
522 * @param $actual: calculated total
523 * @param $expected: user-entered total
524 * @return array
525 */
526 static function displayTotals($actual, $expected) {
527 $class = 'actual-value';
528 if ($expected && $expected != $actual) {
529 $class .= ' crm-error';
530 }
531 $actualTitle = ts('Current Total');
532 $output = "<span class='$class' title='$actualTitle'>$actual</span>";
533 if ($expected) {
534 $expectedTitle = ts('Expected Total');
535 $output .= " / <span class='expected-value' title='$expectedTitle'>$expected</span>";
536 }
537 return $output;
538 }
539
540 /**
541 * Function for exporting financial accounts, currently we support CSV and IIF format
542 * @see http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+Specifications+-++Batches#CiviAccountsSpecifications-Batches-%C2%A0Overviewofimplementation
543 *
544 * @param array $batchIds associated array of batch ids
545 * @param string $exportFormat export format
546 *
547 * @return void
548 *
549 * @static
550 * @access public
551 */
552 static function exportFinancialBatch($batchIds, $exportFormat) {
553 if (empty($batchIds)) {
554 CRM_Core_Error::fatal(ts('No batches were selected.'));
555 return;
556 }
557 if (empty($exportFormat)) {
558 CRM_Core_Error::fatal(ts('No export format selected.'));
559 return;
560 }
561 self::$_exportFormat = $exportFormat;
562
563 // Instantiate appropriate exporter based on user-selected format.
564 $exporterClass = "CRM_Financial_BAO_ExportFormat_" . self::$_exportFormat;
565 if ( class_exists( $exporterClass ) ) {
566 $exporter = new $exporterClass();
567 }
568 else {
569 CRM_Core_Error::fatal("Could not locate exporter: $exporterClass");
570 }
571 switch (self::$_exportFormat) {
572 case 'CSV':
573 foreach ($batchIds as $batchId) {
574 $export[$batchId] = $exporter->generateExportQuery($batchId);
575 }
576 $exporter->makeCSV($export);
577 break;
578
579 case 'IIF':
580 foreach ($batchIds as $batchId) {
581 $export[$batchId] = $exporter->generateExportQuery($batchId);
582 }
583 $exporter->makeIIF($export);
584 break;
585 }
586 }
587
588 static function closeReOpen($batchIds = array(), $status) {
f0ebbc90 589 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
6a488035
TO
590 $params['status_id'] = CRM_Utils_Array::key( $status, $batchStatus );
591 $session = CRM_Core_Session::singleton( );
592 $params['modified_date'] = date('YmdHis');
593 $params['modified_id'] = $session->get( 'userID' );
594 foreach ($batchIds as $key => $value) {
595 $params['id'] = $ids['batchID'] = $value;
596 self::create($params, $ids);
597 }
598 $url = CRM_Utils_System::url('civicrm/financial/financialbatches',"reset=1&batchStatus={$params['status_id']}");
599 CRM_Utils_System::redirect($url);
600 }
601
602 /**
603 * Function to retrieve financial items assigned for a batch
604 *
605 * @param int $entityID
606 * @param array $returnValues
607 * @param null $notPresent
608 * @param null $params
609 * @return Object
610 */
611 static function getBatchFinancialItems($entityID, $returnValues, $notPresent = NULL, $params = NULL, $getCount = FALSE) {
612 if (!$getCount) {
613 if (!empty($params['rowCount']) &&
614 $params['rowCount'] > 0
615 ) {
616 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
617 }
618 }
619 // action is taken depending upon the mode
620 $select = 'civicrm_financial_trxn.id ';
621 if (!empty( $returnValues)) {
622 $select .= " , ".implode(' , ', $returnValues);
623 }
624
625 $orderBy = " ORDER BY civicrm_financial_trxn.id";
21d32567
DL
626 if (!empty($params['sort'])) {
627 $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
6a488035
TO
628 }
629
630 $from = "civicrm_financial_trxn
631LEFT JOIN civicrm_entity_financial_trxn ON civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id
632LEFT JOIN civicrm_entity_batch ON civicrm_entity_batch.entity_id = civicrm_financial_trxn.id
633LEFT JOIN civicrm_contribution ON civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id
634LEFT JOIN civicrm_financial_type ON civicrm_financial_type.id = civicrm_contribution.financial_type_id
635LEFT JOIN civicrm_contact contact_a ON contact_a.id = civicrm_contribution.contact_id
636LEFT JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id
637";
638
639 $searchFields =
640 array(
641 'sort_name',
642 'financial_type_id',
643 'contribution_page_id',
644 'contribution_payment_instrument_id',
645 'contribution_transaction_id',
646 'contribution_source',
647 'contribution_currency_type',
648 'contribution_pay_later',
649 'contribution_recurring',
650 'contribution_test',
651 'contribution_thankyou_date_is_not_null',
652 'contribution_receipt_date_is_not_null',
653 'contribution_pcp_made_through_id',
654 'contribution_pcp_display_in_roll',
655 'contribution_date_relative',
656 'contribution_amount_low',
657 'contribution_amount_high',
658 'contribution_in_honor_of',
659 'contact_tags',
660 'group',
661 'contribution_date_relative',
662 'contribution_date_high',
663 'contribution_date_low',
664 'contribution_check_number',
665 'contribution_status_id',
666 );
667 $values = array();
668 foreach ($searchFields as $field) {
669 if (isset($params[$field])) {
670 $values[$field] = $params[$field];
671 if ($field == 'sort_name') {
672 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id
673 LEFT JOIN civicrm_email ON contact_b.id = civicrm_email.contact_id";
674 }
675 if ($field == 'contribution_in_honor_of') {
676 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id";
677 }
678 if ($field == 'contact_tags') {
679 $from .= " LEFT JOIN civicrm_entity_tag `civicrm_entity_tag-{$params[$field]}` ON `civicrm_entity_tag-{$params[$field]}`.entity_id = contact_a.id";
680 }
681 if ($field == 'group') {
682 $from .= " LEFT JOIN civicrm_group_contact `civicrm_group_contact-{$params[$field]}` ON contact_a.id = `civicrm_group_contact-{$params[$field]}`.contact_id ";
683 }
684 if ($field == 'contribution_date_relative') {
685 $relativeDate = explode('.', $params[$field]);
686 $date = CRM_Utils_Date::relativeToAbsolute($relativeDate[0], $relativeDate[1]);
687 $values['contribution_date_low'] = $date['from'];
688 $values['contribution_date_high'] = $date['to'];
689 }
690 $searchParams = CRM_Contact_BAO_Query::convertFormValues($values);
691 $query = new CRM_Contact_BAO_Query($searchParams,
692 CRM_Contribute_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_CONTRIBUTE,
693 FALSE
694 ),NULL, FALSE, FALSE,CRM_Contact_BAO_Query::MODE_CONTRIBUTE
695 );
696 if ($field == 'contribution_date_high' || $field == 'contribution_date_low') {
697 $query->dateQueryBuilder($params[$field], 'civicrm_contribution', 'contribution_date', 'receive_date', 'Contribution Date');
698 }
699 }
700 }
701 if (!empty($query->_where[0])) {
0b0941e2 702 $where = implode(' AND ', $query->_where[0]) .
ba9d40b9 703 " AND civicrm_entity_batch.batch_id IS NULL
0b0941e2 704 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'";
6a488035
TO
705 $searchValue = TRUE;
706 }
707 else {
708 $searchValue = FALSE;
709 }
710
711 if (!$searchValue) {
712 if (!$notPresent) {
713 $where = " ( civicrm_entity_batch.batch_id = {$entityID}
714 AND civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
715 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution') ";
716 }
717 else {
718 $where = " ( civicrm_entity_batch.batch_id IS NULL
719 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution')";
720 }
721 }
722
0b0941e2
DL
723 $sql = "
724SELECT {$select}
725FROM {$from}
726WHERE {$where}
727 {$orderBy}
6a488035
TO
728";
729
730 if (isset($limit)) {
731 $sql .= "{$limit}";
732 }
733
734 $result = CRM_Core_DAO::executeQuery($sql);
735 return $result;
736 }
737
738 /**
739 * function to get batch names
740 * @param string $batchIds
741 *
742 * @return array array of batches
743 */
744 static function getBatchNames($batchIds) {
745 $query = 'SELECT id, title
746 FROM civicrm_batch
0b0941e2 747 WHERE id IN ('. $batchIds . ')';
6a488035
TO
748
749 $batches = array();
750 $dao = CRM_Core_DAO::executeQuery($query);
751 while ( $dao->fetch( ) ) {
752 $batches[$dao->id] = $dao->title;
753 }
754 return $batches;
755 }
756
757 /**
758 * Function get batch statuses
759 *
760 * @param string $batchIds
761 *
762 * @return array array of batches
763 */
764 static function getBatchStatuses($batchIds) {
765 $query = 'SELECT id, status_id
766 FROM civicrm_batch
767 WHERE id IN ('.$batchIds.')';
768
769 $batches = array();
770 $dao = CRM_Core_DAO::executeQuery($query);
771 while ( $dao->fetch( ) ) {
772 $batches[$dao->id] = $dao->status_id;
773 }
774 return $batches;
775 }
776}