CRM-14043 - cid=0 contribution form giving contribution to logged in user
[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) {
63 if (!CRM_Utils_Array::value('id', $params)) {
64 $params['name'] = CRM_Utils_String::titleToVar($params['title']);
65 }
66
67 $batch = new CRM_Batch_DAO_Batch();
68 $batch->copyValues($params);
69 if ($context == 'financialBatch' && CRM_Utils_Array::value('batchID', $ids)) {
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);
218 if (CRM_Utils_Array::value('total', $value)) {
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');
264 if (CRM_Utils_Array::value('context', $params)) {
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 }
305 if (CRM_Utils_Array::value('type_id', $values)) {
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,
325 $tokens
326 );
327 $results[$object->id] = $values;
328 }
329
330 return $results;
331 }
332
333 /**
334 * Get count of batches
335 *
336 * @param array $params associated array for params
337 * @access public
338 */
b11c92be 339 public static function getBatchCount(&$params) {
6a488035
TO
340 $args = array();
341 $whereClause = self::whereClause($params, $args);
342 $query = " SELECT COUNT(*) FROM civicrm_batch batch
343 INNER JOIN civicrm_contact c ON batch.created_id = c.id
344 WHERE {$whereClause}";
345 return CRM_Core_DAO::singleValueQuery($query);
346 }
347
348 /**
349 * Format where clause for getting lists of batches
350 *
351 * @param array $params associated array for params
352 * @access public
353 */
b11c92be 354 public static function whereClause($params) {
6a488035
TO
355 $clauses = array();
356 // Exclude data-entry batches
357 if (empty($params['status_id'])) {
358 $clauses[] = 'batch.status_id <> 3';
359 }
360
361 $fields = array(
362 'title' => 'String',
363 'sort_name' => 'String',
364 'status_id' => 'Integer',
365 'payment_instrument_id' => 'Integer',
366 'item_count' => 'Integer',
367 'total' => 'Float',
368 );
369
370 foreach ($fields as $field => $type) {
371 $table = $field == 'sort_name' ? 'c' : 'batch';
372 if (isset($params[$field])) {
373 $value = CRM_Utils_Type::escape($params[$field], $type, FALSE);
374 if ($value && $type == 'String') {
375 $clauses[] = "$table.$field LIKE '%$value%'";
376 }
377 elseif ($value && $type == 'Float') {
378 $clauses[] = "$table.$field = '$value'";
379 }
380 elseif ($value) {
381 $clauses[] = "$table.$field = $value";
382 }
383 }
384 }
385 return $clauses ? implode(' AND ', $clauses) : '1';
386 }
387
388 /**
389 * Function to define action links
390 *
391 * @return array $links array of action links
392 * @access public
393 */
394 function links($context = NULL) {
395 if ($context == 'financialBatch') {
396 $links = array(
397 'transaction' => array(
398 'name' => ts('Transactions'),
399 'url' => 'civicrm/batchtransaction',
400 'qs' => 'reset=1&bid=%%id%%',
401 'title' => ts('View/Add Transactions to Batch'),
402 ),
403 'edit' => array(
404 'name' => ts('Edit'),
405 'url' => 'civicrm/financial/batch',
406 'qs' => 'reset=1&action=update&id=%%id%%&context=1',
407 'title' => ts('Edit Batch'),
408 ),
409 'close' => array(
410 'name' => ts('Close'),
411 'title' => ts('Close Batch'),
412 'url' => '#',
413 'extra' => 'rel="close"',
414 ),
415 'export' => array(
416 'name' => ts('Export'),
417 'title' => ts('Export Batch'),
418 'url' => '#',
419 'extra' => 'rel="export"',
420 ),
421 'reopen' => array(
422 'name' => ts('Re-open'),
423 'title' => ts('Re-open Batch'),
424 'url' => '#',
425 'extra' => 'rel="reopen"',
426 ),
427 'delete' => array(
428 'name' => ts('Delete'),
429 'title' => ts('Delete Batch'),
430 'url' => '#',
431 'extra' => 'rel="delete"',
432 ),
433 'download' => array(
434 'name' => ts('Download'),
435 'url' => 'civicrm/file',
436 'qs' => 'reset=1&id=%%fid%%&eid=%%eid%%',
437 'title' => ts('Download Batch'),
438 )
439 );
440 }
441 else {
442 $links = array(
443 CRM_Core_Action::COPY => array(
444 'name' => ts('Enter records'),
445 'url' => 'civicrm/batch/entry',
446 'qs' => 'id=%%id%%&reset=1',
447 'title' => ts('Batch Data Entry'),
448 ),
449 CRM_Core_Action::UPDATE => array(
450 'name' => ts('Edit'),
451 'url' => 'civicrm/batch',
452 'qs' => 'action=update&id=%%id%%&reset=1',
453 'title' => ts('Edit Batch'),
454 ),
455 CRM_Core_Action::DELETE => array(
456 'name' => ts('Delete'),
457 'url' => 'civicrm/batch',
458 'qs' => 'action=delete&id=%%id%%',
459 'title' => ts('Delete Batch'),
460 )
461 );
462 }
463 return $links;
464 }
465
466 /**
467 * function to get batch list
468 *
acb4ca2f 469 * @return array array of all batches
c8f66220 470 * excluding batches with data entry in progress
6a488035
TO
471 */
472 static function getBatches() {
acb4ca2f
DG
473 $dataEntryStatusId = CRM_Core_OptionGroup::getValue('batch_status','Data Entry');
474 $query = "SELECT id, title
6a488035 475 FROM civicrm_batch
acb4ca2f
DG
476 WHERE item_count >= 1
477 AND status_id != {$dataEntryStatusId}
478 ORDER BY id DESC";
6a488035
TO
479
480 $batches = array();
481 $dao = CRM_Core_DAO::executeQuery($query);
482 while ( $dao->fetch( ) ) {
483 $batches[$dao->id] = $dao->title;
484 }
485 return $batches;
486 }
487
488
489
490 /**
491 * Calculate sum of all entries in a batch
492 * Used to validate and update item_count and total when closing an accounting batch
493 *
494 * @param array $batchIds
495 * @return array
496 */
497 static function batchTotals($batchIds) {
498 $totals = array_fill_keys($batchIds, array('item_count' => 0, 'total' => 0));
499 if ($batchIds) {
500 $sql = "SELECT eb.batch_id, COUNT(tx.id) AS item_count, SUM(tx.total_amount) AS total
501 FROM civicrm_entity_batch eb
502 INNER JOIN civicrm_financial_trxn tx ON tx.id = eb.entity_id AND eb.entity_table = 'civicrm_financial_trxn'
503 WHERE eb.batch_id IN (" . implode(',', $batchIds) . ")
504 GROUP BY eb.batch_id";
505 $dao = CRM_Core_DAO::executeQuery($sql);
506 while ($dao->fetch()) {
507 $totals[$dao->batch_id] = (array) $dao;
508 }
509 $dao->free();
510 }
511 return $totals;
512 }
513
514 /**
515 * Format markup for comparing two totals
516 *
517 * @param $actual: calculated total
518 * @param $expected: user-entered total
519 * @return array
520 */
521 static function displayTotals($actual, $expected) {
522 $class = 'actual-value';
523 if ($expected && $expected != $actual) {
524 $class .= ' crm-error';
525 }
526 $actualTitle = ts('Current Total');
527 $output = "<span class='$class' title='$actualTitle'>$actual</span>";
528 if ($expected) {
529 $expectedTitle = ts('Expected Total');
530 $output .= " / <span class='expected-value' title='$expectedTitle'>$expected</span>";
531 }
532 return $output;
533 }
534
535 /**
536 * Function for exporting financial accounts, currently we support CSV and IIF format
537 * @see http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+Specifications+-++Batches#CiviAccountsSpecifications-Batches-%C2%A0Overviewofimplementation
538 *
539 * @param array $batchIds associated array of batch ids
540 * @param string $exportFormat export format
541 *
542 * @return void
543 *
544 * @static
545 * @access public
546 */
547 static function exportFinancialBatch($batchIds, $exportFormat) {
548 if (empty($batchIds)) {
549 CRM_Core_Error::fatal(ts('No batches were selected.'));
550 return;
551 }
552 if (empty($exportFormat)) {
553 CRM_Core_Error::fatal(ts('No export format selected.'));
554 return;
555 }
556 self::$_exportFormat = $exportFormat;
557
558 // Instantiate appropriate exporter based on user-selected format.
559 $exporterClass = "CRM_Financial_BAO_ExportFormat_" . self::$_exportFormat;
560 if ( class_exists( $exporterClass ) ) {
561 $exporter = new $exporterClass();
562 }
563 else {
564 CRM_Core_Error::fatal("Could not locate exporter: $exporterClass");
565 }
566 switch (self::$_exportFormat) {
567 case 'CSV':
568 foreach ($batchIds as $batchId) {
569 $export[$batchId] = $exporter->generateExportQuery($batchId);
570 }
571 $exporter->makeCSV($export);
572 break;
573
574 case 'IIF':
575 foreach ($batchIds as $batchId) {
576 $export[$batchId] = $exporter->generateExportQuery($batchId);
577 }
578 $exporter->makeIIF($export);
579 break;
580 }
581 }
582
583 static function closeReOpen($batchIds = array(), $status) {
f0ebbc90 584 $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
6a488035
TO
585 $params['status_id'] = CRM_Utils_Array::key( $status, $batchStatus );
586 $session = CRM_Core_Session::singleton( );
587 $params['modified_date'] = date('YmdHis');
588 $params['modified_id'] = $session->get( 'userID' );
589 foreach ($batchIds as $key => $value) {
590 $params['id'] = $ids['batchID'] = $value;
591 self::create($params, $ids);
592 }
593 $url = CRM_Utils_System::url('civicrm/financial/financialbatches',"reset=1&batchStatus={$params['status_id']}");
594 CRM_Utils_System::redirect($url);
595 }
596
597 /**
598 * Function to retrieve financial items assigned for a batch
599 *
600 * @param int $entityID
601 * @param array $returnValues
602 * @param null $notPresent
603 * @param null $params
604 * @return Object
605 */
606 static function getBatchFinancialItems($entityID, $returnValues, $notPresent = NULL, $params = NULL, $getCount = FALSE) {
607 if (!$getCount) {
608 if (!empty($params['rowCount']) &&
609 $params['rowCount'] > 0
610 ) {
611 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
612 }
613 }
614 // action is taken depending upon the mode
615 $select = 'civicrm_financial_trxn.id ';
616 if (!empty( $returnValues)) {
617 $select .= " , ".implode(' , ', $returnValues);
618 }
619
620 $orderBy = " ORDER BY civicrm_financial_trxn.id";
21d32567
DL
621 if (!empty($params['sort'])) {
622 $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
6a488035
TO
623 }
624
625 $from = "civicrm_financial_trxn
626LEFT JOIN civicrm_entity_financial_trxn ON civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id
627LEFT JOIN civicrm_entity_batch ON civicrm_entity_batch.entity_id = civicrm_financial_trxn.id
628LEFT JOIN civicrm_contribution ON civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id
629LEFT JOIN civicrm_financial_type ON civicrm_financial_type.id = civicrm_contribution.financial_type_id
630LEFT JOIN civicrm_contact contact_a ON contact_a.id = civicrm_contribution.contact_id
631LEFT JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id
632";
633
634 $searchFields =
635 array(
636 'sort_name',
637 'financial_type_id',
638 'contribution_page_id',
639 'contribution_payment_instrument_id',
640 'contribution_transaction_id',
641 'contribution_source',
642 'contribution_currency_type',
643 'contribution_pay_later',
644 'contribution_recurring',
645 'contribution_test',
646 'contribution_thankyou_date_is_not_null',
647 'contribution_receipt_date_is_not_null',
648 'contribution_pcp_made_through_id',
649 'contribution_pcp_display_in_roll',
650 'contribution_date_relative',
651 'contribution_amount_low',
652 'contribution_amount_high',
653 'contribution_in_honor_of',
654 'contact_tags',
655 'group',
656 'contribution_date_relative',
657 'contribution_date_high',
658 'contribution_date_low',
659 'contribution_check_number',
660 'contribution_status_id',
661 );
662 $values = array();
663 foreach ($searchFields as $field) {
664 if (isset($params[$field])) {
665 $values[$field] = $params[$field];
666 if ($field == 'sort_name') {
667 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id
668 LEFT JOIN civicrm_email ON contact_b.id = civicrm_email.contact_id";
669 }
670 if ($field == 'contribution_in_honor_of') {
671 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id";
672 }
673 if ($field == 'contact_tags') {
674 $from .= " LEFT JOIN civicrm_entity_tag `civicrm_entity_tag-{$params[$field]}` ON `civicrm_entity_tag-{$params[$field]}`.entity_id = contact_a.id";
675 }
676 if ($field == 'group') {
677 $from .= " LEFT JOIN civicrm_group_contact `civicrm_group_contact-{$params[$field]}` ON contact_a.id = `civicrm_group_contact-{$params[$field]}`.contact_id ";
678 }
679 if ($field == 'contribution_date_relative') {
680 $relativeDate = explode('.', $params[$field]);
681 $date = CRM_Utils_Date::relativeToAbsolute($relativeDate[0], $relativeDate[1]);
682 $values['contribution_date_low'] = $date['from'];
683 $values['contribution_date_high'] = $date['to'];
684 }
685 $searchParams = CRM_Contact_BAO_Query::convertFormValues($values);
686 $query = new CRM_Contact_BAO_Query($searchParams,
687 CRM_Contribute_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_CONTRIBUTE,
688 FALSE
689 ),NULL, FALSE, FALSE,CRM_Contact_BAO_Query::MODE_CONTRIBUTE
690 );
691 if ($field == 'contribution_date_high' || $field == 'contribution_date_low') {
692 $query->dateQueryBuilder($params[$field], 'civicrm_contribution', 'contribution_date', 'receive_date', 'Contribution Date');
693 }
694 }
695 }
696 if (!empty($query->_where[0])) {
0b0941e2 697 $where = implode(' AND ', $query->_where[0]) .
ba9d40b9 698 " AND civicrm_entity_batch.batch_id IS NULL
0b0941e2 699 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'";
6a488035
TO
700 $searchValue = TRUE;
701 }
702 else {
703 $searchValue = FALSE;
704 }
705
706 if (!$searchValue) {
707 if (!$notPresent) {
708 $where = " ( civicrm_entity_batch.batch_id = {$entityID}
709 AND civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
710 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution') ";
711 }
712 else {
713 $where = " ( civicrm_entity_batch.batch_id IS NULL
714 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution')";
715 }
716 }
717
0b0941e2
DL
718 $sql = "
719SELECT {$select}
720FROM {$from}
721WHERE {$where}
722 {$orderBy}
6a488035
TO
723";
724
725 if (isset($limit)) {
726 $sql .= "{$limit}";
727 }
728
729 $result = CRM_Core_DAO::executeQuery($sql);
730 return $result;
731 }
732
733 /**
734 * function to get batch names
735 * @param string $batchIds
736 *
737 * @return array array of batches
738 */
739 static function getBatchNames($batchIds) {
740 $query = 'SELECT id, title
741 FROM civicrm_batch
0b0941e2 742 WHERE id IN ('. $batchIds . ')';
6a488035
TO
743
744 $batches = array();
745 $dao = CRM_Core_DAO::executeQuery($query);
746 while ( $dao->fetch( ) ) {
747 $batches[$dao->id] = $dao->title;
748 }
749 return $batches;
750 }
751
752 /**
753 * Function get batch statuses
754 *
755 * @param string $batchIds
756 *
757 * @return array array of batches
758 */
759 static function getBatchStatuses($batchIds) {
760 $query = 'SELECT id, status_id
761 FROM civicrm_batch
762 WHERE id IN ('.$batchIds.')';
763
764 $batches = array();
765 $dao = CRM_Core_DAO::executeQuery($query);
766 while ( $dao->fetch( ) ) {
767 $batches[$dao->id] = $dao->status_id;
768 }
769 return $batches;
770 }
771}