3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
39 class CRM_Batch_BAO_Batch
extends CRM_Batch_DAO_Batch
{
42 * Cache for the current batch object
44 static $_batch = NULL;
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.
50 static $_exportFormat = NULL;
55 * @param array $params associated array
56 * @param array $ids associated array of ids
57 * @param string $context string
59 * @return object $batch batch object
62 static function create(&$params, $ids = NULL, $context = NULL) {
63 if (empty($params['id'])) {
64 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
67 $batch = new CRM_Batch_DAO_Batch();
68 $batch->copyValues($params);
69 if ($context == 'financialBatch' && !empty($ids['batchID'])) {
70 $batch->id
= $ids['batchID'];
78 * Retrieve the information about the batch
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
83 * @return array CRM_Batch_BAO_Batch object on success, null otherwise
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);
98 * Get profile id associated with the batch type
100 * @param int $batchTypeId batch type id
102 * @return int $profileId profile id
105 static function getProfileId($batchTypeId) {
106 //retrieve the profile specific to batch type
107 switch ($batchTypeId) {
109 //batch profile used for contribution
110 $profileName = "contribution_batch_entry";
114 //batch profile used for memberships
115 $profileName = "membership_batch_entry";
118 // get and return the profile id
119 return CRM_Core_DAO
::getFieldValue('CRM_Core_BAO_UFGroup', $profileName, 'id', 'name');
123 * generate batch name
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');
135 * create entity batch entry
136 * @param array $params associated array
137 * @return batch array
140 static function addBatchEntity(&$params) {
141 $entityBatch = new CRM_Batch_DAO_EntityBatch();
142 $entityBatch->copyValues($params);
143 $entityBatch->save();
148 * Remove entries from entity batch
149 * @param array $params associated array
150 * @return object CRM_Batch_DAO_EntityBatch
152 static function removeBatchEntity($params) {
153 $entityBatch = new CRM_Batch_DAO_EntityBatch();
154 $entityBatch->copyValues($params);
155 $entityBatch->delete();
160 * function to delete batch entry
162 * @param int $batchId batch id
167 static function deleteBatch($batchId) {
168 // delete entry from batch table
169 $batch = new CRM_Batch_DAO_Batch();
170 $batch->id
= $batchId;
176 * This function is a wrapper for ajax batch selector
178 * @param array $params associated array for params record id.
180 * @return array $batchList associated array of batch list
183 public function getBatchListSelector(&$params) {
185 $params['offset'] = ($params['page'] - 1) * $params['rp'];
186 $params['rowCount'] = $params['rp'];
187 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
190 $batches = self
::getBatchList($params);
192 // get batch totals for open batches
193 $fetchTotals = array();
194 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
195 $batchStatus = array(
196 array_search('Open', $batchStatus),
197 array_search('Reopened', $batchStatus),
199 if ($params['context'] == 'financialBatch') {
200 foreach ($batches as $id => $batch) {
201 if (in_array($batch['status_id'], $batchStatus)) {
202 $fetchTotals[] = $id;
206 $totals = self
::batchTotals($fetchTotals);
209 $params['total'] = self
::getBatchCount($params);
211 // format params and add links
212 $batchList = array();
214 foreach ($batches as $id => $value) {
216 if ($params['context'] == 'financialBatch') {
217 $batch['check'] = $value['check'];
219 $batch['batch_name'] = $value['title'];
220 $batch['total'] = $batch['item_count'] = '';
221 $batch['payment_instrument'] = $value['payment_instrument'];
222 $batch['item_count'] = CRM_Utils_Array
::value('item_count', $value);
223 if (!empty($value['total'])) {
224 $batch['total'] = CRM_Utils_Money
::format($value['total']);
227 // Compare totals with actuals
228 if (isset($totals[$id])) {
229 $batch['item_count'] = self
::displayTotals($totals[$id]['item_count'], $batch['item_count']);
230 $batch['total'] = self
::displayTotals(CRM_Utils_Money
::format($totals[$id]['total']), $batch['total']);
232 $batch['status'] = $value['batch_status'];
233 $batch['created_by'] = $value['created_by'];
234 $batch['links'] = $value['action'];
235 $batchList[$id] = $batch;
241 * Get list of batches
243 * @param array $params associated array for params
246 static function getBatchList(&$params) {
247 $whereClause = self
::whereClause($params);
249 if (!empty($params['rowCount']) && is_numeric($params['rowCount'])
250 && is_numeric($params['offset']) && $params['rowCount'] > 0
252 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
255 $orderBy = ' ORDER BY batch.id desc';
256 if (!empty($params['sort'])) {
257 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
261 SELECT batch.*, c.sort_name created_by
262 FROM civicrm_batch batch
263 INNER JOIN civicrm_contact c ON batch.created_id = c.id
268 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Batch_DAO_Batch');
269 if (!empty($params['context'])) {
270 $links = self
::links($params['context']);
273 $links = self
::links();
276 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id');
277 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id');
278 $batchStatusByName = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
279 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
282 while ($object->fetch()) {
285 CRM_Core_DAO
::storeValues($object, $values);
286 $action = array_sum(array_keys($newLinks));
288 if ($values['status_id'] == array_search('Closed', $batchStatusByName) && $params['context'] != 'financialBatch') {
291 elseif ($params['context'] == 'financialBatch') {
293 "<input type='checkbox' id='check_" .
297 "' value='1' data-status_id='" .
298 $values['status_id']."' class='select-row'></input>";
300 switch ($batchStatusByName[$values['status_id']]) {
302 CRM_Utils_Array
::remove($newLinks, 'reopen', 'download');
305 CRM_Utils_Array
::remove($newLinks, 'close', 'edit', 'download');
308 CRM_Utils_Array
::remove($newLinks, 'close', 'edit', 'reopen', 'export');
311 if (!empty($values['type_id'])) {
312 $values['batch_type'] = $batchTypes[$values['type_id']];
314 $values['batch_status'] = $batchStatus[$values['status_id']];
315 $values['created_by'] = $object->created_by
;
316 $values['payment_instrument'] = '';
317 if (!empty($object->payment_instrument_id
)) {
318 $values['payment_instrument'] = $paymentInstrument[$object->payment_instrument_id
];
320 $tokens = array('id' => $object->id
, 'status' => $values['status_id']);
321 if ($values['status_id'] == array_search('Exported', $batchStatusByName)) {
322 $aid = CRM_Core_OptionGroup
::getValue('activity_type','Export Accounting Batch');
323 $activityParams = array('source_record_id' => $object->id
, 'activity_type_id' => $aid);
324 $exportActivity = CRM_Activity_BAO_Activity
::retrieve($activityParams, $val);
325 $fid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile', $exportActivity->id
, 'file_id', 'entity_id');
326 $tokens = array_merge(array('eid' => $exportActivity->id
, 'fid' => $fid), $tokens);
328 $values['action'] = CRM_Core_Action
::formLink(
334 'batch.selector.row',
338 $results[$object->id
] = $values;
345 * Get count of batches
347 * @param array $params associated array for params
350 public static function getBatchCount(&$params) {
352 $whereClause = self
::whereClause($params, $args);
353 $query = " SELECT COUNT(*) FROM civicrm_batch batch
354 INNER JOIN civicrm_contact c ON batch.created_id = c.id
355 WHERE {$whereClause}";
356 return CRM_Core_DAO
::singleValueQuery($query);
360 * Format where clause for getting lists of batches
362 * @param array $params associated array for params
365 public static function whereClause($params) {
367 // Exclude data-entry batches
368 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
369 if (empty($params['status_id'])) {
370 $clauses[] = 'batch.status_id <> ' . array_search('Data Entry', $batchStatus);
375 'sort_name' => 'String',
376 'status_id' => 'Integer',
377 'payment_instrument_id' => 'Integer',
378 'item_count' => 'Integer',
382 foreach ($fields as $field => $type) {
383 $table = $field == 'sort_name' ?
'c' : 'batch';
384 if (isset($params[$field])) {
385 $value = CRM_Utils_Type
::escape($params[$field], $type, FALSE);
386 if ($value && $type == 'String') {
387 $clauses[] = "$table.$field LIKE '%$value%'";
389 elseif ($value && $type == 'Float') {
390 $clauses[] = "$table.$field = '$value'";
393 if ($field == 'status_id' && $value == array_search('Open', $batchStatus)) {
394 $clauses[] = "$table.$field IN ($value," . array_search('Reopened', $batchStatus) . ')';
397 $clauses[] = "$table.$field = $value";
402 return $clauses ?
implode(' AND ', $clauses) : '1';
406 * Function to define action links
408 * @return array $links array of action links
411 function links($context = NULL) {
412 if ($context == 'financialBatch') {
414 'transaction' => array(
415 'name' => ts('Transactions'),
416 'url' => 'civicrm/batchtransaction',
417 'qs' => 'reset=1&bid=%%id%%',
418 'title' => ts('View/Add Transactions to Batch'),
421 'name' => ts('Edit'),
422 'url' => 'civicrm/financial/batch',
423 'qs' => 'reset=1&action=update&id=%%id%%&context=1',
424 'title' => ts('Edit Batch'),
427 'name' => ts('Close'),
428 'title' => ts('Close Batch'),
430 'extra' => 'rel="close"',
433 'name' => ts('Export'),
434 'title' => ts('Export Batch'),
436 'extra' => 'rel="export"',
439 'name' => ts('Re-open'),
440 'title' => ts('Re-open Batch'),
442 'extra' => 'rel="reopen"',
445 'name' => ts('Delete'),
446 'title' => ts('Delete Batch'),
448 'extra' => 'rel="delete"',
451 'name' => ts('Download'),
452 'url' => 'civicrm/file',
453 'qs' => 'reset=1&id=%%fid%%&eid=%%eid%%',
454 'title' => ts('Download Batch'),
460 CRM_Core_Action
::COPY
=> array(
461 'name' => ts('Enter records'),
462 'url' => 'civicrm/batch/entry',
463 'qs' => 'id=%%id%%&reset=1',
464 'title' => ts('Batch Data Entry'),
466 CRM_Core_Action
::UPDATE
=> array(
467 'name' => ts('Edit'),
468 'url' => 'civicrm/batch',
469 'qs' => 'action=update&id=%%id%%&reset=1',
470 'title' => ts('Edit Batch'),
472 CRM_Core_Action
::DELETE
=> array(
473 'name' => ts('Delete'),
474 'url' => 'civicrm/batch',
475 'qs' => 'action=delete&id=%%id%%',
476 'title' => ts('Delete Batch'),
484 * function to get batch list
486 * @return array array of all batches
487 * excluding batches with data entry in progress
489 static function getBatches() {
490 $dataEntryStatusId = CRM_Core_OptionGroup
::getValue('batch_status','Data Entry', 'name');
491 $query = "SELECT id, title
493 WHERE item_count >= 1
494 AND status_id != {$dataEntryStatusId}
498 $dao = CRM_Core_DAO
::executeQuery($query);
499 while ( $dao->fetch( ) ) {
500 $batches[$dao->id
] = $dao->title
;
508 * Calculate sum of all entries in a batch
509 * Used to validate and update item_count and total when closing an accounting batch
511 * @param array $batchIds
514 static function batchTotals($batchIds) {
515 $totals = array_fill_keys($batchIds, array('item_count' => 0, 'total' => 0));
517 $sql = "SELECT eb.batch_id, COUNT(tx.id) AS item_count, SUM(tx.total_amount) AS total
518 FROM civicrm_entity_batch eb
519 INNER JOIN civicrm_financial_trxn tx ON tx.id = eb.entity_id AND eb.entity_table = 'civicrm_financial_trxn'
520 WHERE eb.batch_id IN (" . implode(',', $batchIds) . ")
521 GROUP BY eb.batch_id";
522 $dao = CRM_Core_DAO
::executeQuery($sql);
523 while ($dao->fetch()) {
524 $totals[$dao->batch_id
] = (array) $dao;
532 * Format markup for comparing two totals
534 * @param $actual: calculated total
535 * @param $expected: user-entered total
538 static function displayTotals($actual, $expected) {
539 $class = 'actual-value';
540 if ($expected && $expected != $actual) {
541 $class .= ' crm-error';
543 $actualTitle = ts('Current Total');
544 $output = "<span class='$class' title='$actualTitle'>$actual</span>";
546 $expectedTitle = ts('Expected Total');
547 $output .= " / <span class='expected-value' title='$expectedTitle'>$expected</span>";
553 * Function for exporting financial accounts, currently we support CSV and IIF format
554 * @see http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+Specifications+-++Batches#CiviAccountsSpecifications-Batches-%C2%A0Overviewofimplementation
556 * @param array $batchIds associated array of batch ids
557 * @param string $exportFormat export format
564 static function exportFinancialBatch($batchIds, $exportFormat) {
565 if (empty($batchIds)) {
566 CRM_Core_Error
::fatal(ts('No batches were selected.'));
569 if (empty($exportFormat)) {
570 CRM_Core_Error
::fatal(ts('No export format selected.'));
573 self
::$_exportFormat = $exportFormat;
575 // Instantiate appropriate exporter based on user-selected format.
576 $exporterClass = "CRM_Financial_BAO_ExportFormat_" . self
::$_exportFormat;
577 if ( class_exists( $exporterClass ) ) {
578 $exporter = new $exporterClass();
581 CRM_Core_Error
::fatal("Could not locate exporter: $exporterClass");
583 switch (self
::$_exportFormat) {
585 foreach ($batchIds as $batchId) {
586 $export[$batchId] = $exporter->generateExportQuery($batchId);
588 $exporter->makeCSV($export);
592 foreach ($batchIds as $batchId) {
593 $export[$batchId] = $exporter->generateExportQuery($batchId);
595 $exporter->makeIIF($export);
600 static function closeReOpen($batchIds = array(), $status) {
601 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id');
602 $params['status_id'] = CRM_Utils_Array
::key( $status, $batchStatus );
603 $session = CRM_Core_Session
::singleton( );
604 $params['modified_date'] = date('YmdHis');
605 $params['modified_id'] = $session->get( 'userID' );
606 foreach ($batchIds as $key => $value) {
607 $params['id'] = $ids['batchID'] = $value;
608 self
::create($params, $ids);
610 $url = CRM_Utils_System
::url('civicrm/financial/financialbatches',"reset=1&batchStatus={$params['status_id']}");
611 CRM_Utils_System
::redirect($url);
615 * Function to retrieve financial items assigned for a batch
617 * @param int $entityID
618 * @param array $returnValues
619 * @param null $notPresent
620 * @param null $params
623 static function getBatchFinancialItems($entityID, $returnValues, $notPresent = NULL, $params = NULL, $getCount = FALSE) {
625 if (!empty($params['rowCount']) &&
626 $params['rowCount'] > 0
628 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
631 // action is taken depending upon the mode
632 $select = 'civicrm_financial_trxn.id ';
633 if (!empty( $returnValues)) {
634 $select .= " , ".implode(' , ', $returnValues);
637 $orderBy = " ORDER BY civicrm_financial_trxn.id";
638 if (!empty($params['sort'])) {
639 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
642 $from = "civicrm_financial_trxn
643 LEFT JOIN civicrm_entity_financial_trxn ON civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id
644 LEFT JOIN civicrm_entity_batch ON civicrm_entity_batch.entity_id = civicrm_financial_trxn.id
645 LEFT JOIN civicrm_contribution ON civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id
646 LEFT JOIN civicrm_financial_type ON civicrm_financial_type.id = civicrm_contribution.financial_type_id
647 LEFT JOIN civicrm_contact contact_a ON contact_a.id = civicrm_contribution.contact_id
648 LEFT JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id
655 'contribution_page_id',
656 'contribution_payment_instrument_id',
657 'contribution_transaction_id',
658 'contribution_source',
659 'contribution_currency_type',
660 'contribution_pay_later',
661 'contribution_recurring',
663 'contribution_thankyou_date_is_not_null',
664 'contribution_receipt_date_is_not_null',
665 'contribution_pcp_made_through_id',
666 'contribution_pcp_display_in_roll',
667 'contribution_date_relative',
668 'contribution_amount_low',
669 'contribution_amount_high',
670 'contribution_in_honor_of',
673 'contribution_date_relative',
674 'contribution_date_high',
675 'contribution_date_low',
676 'contribution_check_number',
677 'contribution_status_id',
680 foreach ($searchFields as $field) {
681 if (isset($params[$field])) {
682 $values[$field] = $params[$field];
683 if ($field == 'sort_name') {
684 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id
685 LEFT JOIN civicrm_email ON contact_b.id = civicrm_email.contact_id";
687 if ($field == 'contribution_in_honor_of') {
688 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id";
690 if ($field == 'contact_tags') {
691 $from .= " LEFT JOIN civicrm_entity_tag `civicrm_entity_tag-{$params[$field]}` ON `civicrm_entity_tag-{$params[$field]}`.entity_id = contact_a.id";
693 if ($field == 'group') {
694 $from .= " LEFT JOIN civicrm_group_contact `civicrm_group_contact-{$params[$field]}` ON contact_a.id = `civicrm_group_contact-{$params[$field]}`.contact_id ";
696 if ($field == 'contribution_date_relative') {
697 $relativeDate = explode('.', $params[$field]);
698 $date = CRM_Utils_Date
::relativeToAbsolute($relativeDate[0], $relativeDate[1]);
699 $values['contribution_date_low'] = $date['from'];
700 $values['contribution_date_high'] = $date['to'];
702 $searchParams = CRM_Contact_BAO_Query
::convertFormValues($values);
703 $query = new CRM_Contact_BAO_Query($searchParams,
704 CRM_Contribute_BAO_Query
::defaultReturnProperties(CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
,
706 ),NULL, FALSE, FALSE,CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
708 if ($field == 'contribution_date_high' ||
$field == 'contribution_date_low') {
709 $query->dateQueryBuilder($params[$field], 'civicrm_contribution', 'contribution_date', 'receive_date', 'Contribution Date');
713 if (!empty($query->_where
[0])) {
714 $where = implode(' AND ', $query->_where
[0]) .
715 " AND civicrm_entity_batch.batch_id IS NULL
716 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution'";
720 $searchValue = FALSE;
725 $where = " ( civicrm_entity_batch.batch_id = {$entityID}
726 AND civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
727 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution') ";
730 $where = " ( civicrm_entity_batch.batch_id IS NULL
731 AND civicrm_entity_financial_trxn.entity_table = 'civicrm_contribution')";
746 $result = CRM_Core_DAO
::executeQuery($sql);
751 * function to get batch names
752 * @param string $batchIds
754 * @return array array of batches
756 static function getBatchNames($batchIds) {
757 $query = 'SELECT id, title
759 WHERE id IN ('. $batchIds . ')';
762 $dao = CRM_Core_DAO
::executeQuery($query);
763 while ( $dao->fetch( ) ) {
764 $batches[$dao->id
] = $dao->title
;
770 * Function get batch statuses
772 * @param string $batchIds
774 * @return array array of batches
776 static function getBatchStatuses($batchIds) {
777 $query = 'SELECT id, status_id
779 WHERE id IN ('.$batchIds.')';
782 $dao = CRM_Core_DAO
::executeQuery($query);
783 while ( $dao->fetch( ) ) {
784 $batches[$dao->id
] = $dao->status_id
;