3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 class CRM_Batch_BAO_Batch
extends CRM_Batch_DAO_Batch
{
24 * Cache for the current batch object.
27 public static $_batch = NULL;
30 * Not sure this is the best way to do this. Depends on how exportFinancialBatch() below gets called.
31 * Maybe a parameter to that function is better.
34 public static $_exportFormat = NULL;
39 * @param array $params
44 public static function create(&$params) {
46 $batchId = CRM_Utils_Array
::value('id', $params);
49 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
51 CRM_Utils_Hook
::pre($op, 'Batch', $batchId, $params);
52 $batch = new CRM_Batch_DAO_Batch();
53 $batch->copyValues($params);
56 CRM_Utils_Hook
::post($op, 'Batch', $batch->id
, $batch);
62 * Retrieve the information about the batch.
64 * @param array $params
65 * (reference ) an assoc array of name/value pairs.
66 * @param array $defaults
67 * (reference ) an assoc array to hold the flattened values.
70 * CRM_Batch_BAO_Batch object on success, null otherwise
72 public static function retrieve(&$params, &$defaults) {
73 $batch = new CRM_Batch_DAO_Batch();
74 $batch->copyValues($params);
75 if ($batch->find(TRUE)) {
76 CRM_Core_DAO
::storeValues($batch, $defaults);
83 * Get profile id associated with the batch type.
85 * @param int $batchTypeId
89 * $profileId profile id
91 public static function getProfileId($batchTypeId) {
92 //retrieve the profile specific to batch type
93 switch ($batchTypeId) {
96 //batch profile used for pledges
97 $profileName = "contribution_batch_entry";
101 //batch profile used for memberships
102 $profileName = "membership_batch_entry";
106 // get and return the profile id
107 return CRM_Core_DAO
::getFieldValue('CRM_Core_BAO_UFGroup', $profileName, 'id', 'name');
111 * Generate batch name.
116 public static function generateBatchName() {
117 $sql = "SELECT max(id) FROM civicrm_batch";
118 $batchNo = CRM_Core_DAO
::singleValueQuery($sql) +
1;
119 return ts('Batch %1', [1 => $batchNo]) . ': ' . date('Y-m-d');
123 * Delete batch entry.
125 * @param int $batchId
130 public static function deleteBatch($batchId) {
131 // delete entry from batch table
132 CRM_Utils_Hook
::pre('delete', 'Batch', $batchId, CRM_Core_DAO
::$_nullArray);
133 $batch = new CRM_Batch_DAO_Batch();
134 $batch->id
= $batchId;
136 CRM_Utils_Hook
::post('delete', 'Batch', $batch->id
, $batch);
141 * wrapper for ajax batch selector.
143 * @param array $params
144 * Associated array for params record id.
147 * associated array of batch list
149 public static function getBatchListSelector(&$params) {
151 $params['offset'] = ($params['page'] - 1) * $params['rp'];
152 $params['rowCount'] = $params['rp'];
153 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
156 $batches = self
::getBatchList($params);
158 // get batch totals for open batches
160 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
162 array_search('Open', $batchStatus),
163 array_search('Reopened', $batchStatus),
165 if ($params['context'] == 'financialBatch') {
166 foreach ($batches as $id => $batch) {
167 if (in_array($batch['status_id'], $batchStatus)) {
168 $fetchTotals[] = $id;
172 $totals = self
::batchTotals($fetchTotals);
175 $params['total'] = self
::getBatchCount($params);
177 // format params and add links
180 foreach ($batches as $id => $value) {
182 if ($params['context'] == 'financialBatch') {
183 $batch['check'] = $value['check'];
185 $batch['batch_name'] = $value['title'];
186 $batch['total'] = '';
187 $batch['payment_instrument'] = $value['payment_instrument'];
188 $batch['item_count'] = CRM_Utils_Array
::value('item_count', $value);
189 $batch['type'] = CRM_Utils_Array
::value('batch_type', $value);
190 if (!empty($value['total'])) {
192 $batch['total'] = CRM_Utils_Money
::format($value['total'], $value['currency']);
195 // Compare totals with actuals
196 if (isset($totals[$id])) {
197 $batch['item_count'] = self
::displayTotals($totals[$id]['item_count'], $batch['item_count']);
198 $batch['total'] = self
::displayTotals(CRM_Utils_Money
::format($totals[$id]['total']), $batch['total']);
200 $batch['status'] = $value['batch_status'];
201 $batch['created_by'] = $value['created_by'];
202 $batch['links'] = $value['action'];
203 $batchList[$id] = $batch;
209 * Get list of batches.
211 * @param array $params
212 * Associated array for params.
216 public static function getBatchList(&$params) {
217 $apiParams = self
::whereClause($params);
219 if (!empty($params['rowCount']) && is_numeric($params['rowCount'])
220 && is_numeric($params['offset']) && $params['rowCount'] > 0
222 $apiParams['options'] = ['offset' => $params['offset'], 'limit' => $params['rowCount']];
224 $apiParams['options']['sort'] = 'id DESC';
225 if (!empty($params['sort'])) {
226 $apiParams['options']['sort'] = CRM_Utils_Type
::escape($params['sort'], 'String');
243 "payment_instrument_id",
244 "created_id.sort_name",
247 $apiParams['return'] = $return;
248 $batches = civicrm_api3('Batch', 'get', $apiParams);
249 $obj = new CRM_Batch_BAO_Batch();
250 if (!empty($params['context'])) {
251 $links = $obj->links($params['context']);
254 $links = $obj->links();
257 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id');
258 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id');
259 $batchStatusByName = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
260 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
263 foreach ($batches['values'] as $values) {
265 $action = array_sum(array_keys($newLinks));
267 if ($values['status_id'] == array_search('Closed', $batchStatusByName) && $params['context'] != 'financialBatch') {
270 elseif ($params['context'] == 'financialBatch') {
271 $values['check'] = "<input type='checkbox' id='check_" .
275 "' value='1' data-status_id='" .
276 $values['status_id'] . "' class='select-row'></input>";
278 switch ($batchStatusByName[$values['status_id']]) {
281 CRM_Utils_Array
::remove($newLinks, 'reopen', 'download');
285 CRM_Utils_Array
::remove($newLinks, 'close', 'edit', 'download');
289 CRM_Utils_Array
::remove($newLinks, 'close', 'edit', 'reopen', 'export');
291 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('edit', $values['created_id'])) {
292 CRM_Utils_Array
::remove($newLinks, 'edit');
294 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('close', $values['created_id'])) {
295 CRM_Utils_Array
::remove($newLinks, 'close', 'export');
297 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('reopen', $values['created_id'])) {
298 CRM_Utils_Array
::remove($newLinks, 'reopen');
300 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('export', $values['created_id'])) {
301 CRM_Utils_Array
::remove($newLinks, 'export', 'download');
303 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('delete', $values['created_id'])) {
304 CRM_Utils_Array
::remove($newLinks, 'delete');
307 if (!empty($values['type_id'])) {
308 $values['batch_type'] = $batchTypes[$values['type_id']];
310 $values['batch_status'] = $batchStatus[$values['status_id']];
311 $values['created_by'] = $values['created_id.sort_name'];
312 $values['payment_instrument'] = '';
313 if (!empty($values['payment_instrument_id'])) {
314 $values['payment_instrument'] = $paymentInstrument[$values['payment_instrument_id']];
316 $tokens = ['id' => $values['id'], 'status' => $values['status_id']];
317 if ($values['status_id'] == array_search('Exported', $batchStatusByName)) {
318 $aid = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Export Accounting Batch');
319 $activityParams = ['source_record_id' => $values['id'], 'activity_type_id' => $aid];
320 $exportActivity = CRM_Activity_BAO_Activity
::retrieve($activityParams, $val);
321 if ($exportActivity) {
322 $fid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile', $exportActivity->id
, 'file_id', 'entity_id');
323 $fileHash = CRM_Core_BAO_File
::generateFileHash($exportActivity->id
, $fid);
324 $tokens = array_merge(['eid' => $exportActivity->id
, 'fid' => $fid, 'fcs' => $fileHash], $tokens);
327 CRM_Utils_Array
::remove($newLinks, 'export', 'download');
330 $values['action'] = CRM_Core_Action
::formLink(
336 'batch.selector.row',
341 $values['currency'] = CRM_Core_DAO
::singleValueQuery("
342 SELECT GROUP_CONCAT(DISTINCT ft.currency)
343 FROM civicrm_batch batch
344 JOIN civicrm_entity_batch eb
345 ON batch.id = eb.batch_id
346 JOIN civicrm_financial_trxn ft
347 ON eb.entity_id = ft.id
350 ", [1 => [$values['id'], 'Positive']]);
351 $results[$values['id']] = $values;
358 * Get count of batches.
360 * @param array $params
361 * Associated array for params.
363 * @return null|string
365 public static function getBatchCount(&$params) {
366 $apiParams = self
::whereClause($params);
367 return civicrm_api3('Batch', 'getCount', $apiParams);
371 * Format where clause for getting lists of batches.
373 * @param array $params
374 * Associated array for params.
378 public static function whereClause($params) {
380 // Exclude data-entry batches
381 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
382 if (empty($params['status_id'])) {
383 $clauses['status_id'] = ['NOT IN' => ["Data Entry"]];
400 "payment_instrument_id",
401 "created_id.sort_name",
404 if (!CRM_Core_Permission
::check("view all manual batches")) {
405 if (CRM_Core_Permission
::check("view own manual batches")) {
406 $loggedInContactId = CRM_Core_Session
::singleton()->get('userID');
407 $params['created_id'] = $loggedInContactId;
410 $params['created_id'] = 0;
413 foreach ($return as $field) {
414 if (!isset($params[$field])) {
417 $value = CRM_Utils_Type
::escape($params[$field], 'String', FALSE);
418 if (in_array($field, ['name', 'title', 'description', 'created_id.sort_name'])) {
419 $clauses[$field] = ['LIKE' => "%{$value}%"];
421 elseif ($field == 'status_id' && $value == array_search('Open', $batchStatus)) {
422 $clauses['status_id'] = ['IN' => ["Open", 'Reopened']];
425 $clauses[$field] = $value;
432 * Define action links.
434 * @param null $context
437 * array of action links
439 public function links($context = NULL) {
440 if ($context == 'financialBatch') {
443 'name' => ts('Transactions'),
444 'url' => 'civicrm/batchtransaction',
445 'qs' => 'reset=1&bid=%%id%%',
446 'title' => ts('View/Add Transactions to Batch'),
449 'name' => ts('Edit'),
450 'url' => 'civicrm/financial/batch',
451 'qs' => 'reset=1&action=update&id=%%id%%&context=1',
452 'title' => ts('Edit Batch'),
455 'name' => ts('Close'),
456 'title' => ts('Close Batch'),
458 'extra' => 'rel="close"',
461 'name' => ts('Export'),
462 'title' => ts('Export Batch'),
464 'extra' => 'rel="export"',
467 'name' => ts('Re-open'),
468 'title' => ts('Re-open Batch'),
470 'extra' => 'rel="reopen"',
473 'name' => ts('Delete'),
474 'title' => ts('Delete Batch'),
476 'extra' => 'rel="delete"',
479 'name' => ts('Download'),
480 'url' => 'civicrm/file',
481 'qs' => 'reset=1&id=%%fid%%&eid=%%eid%%&fcs=%%fcs%%',
482 'title' => ts('Download Batch'),
488 CRM_Core_Action
::COPY
=> [
489 'name' => ts('Enter records'),
490 'url' => 'civicrm/batch/entry',
491 'qs' => 'id=%%id%%&reset=1',
492 'title' => ts('Batch Data Entry'),
494 CRM_Core_Action
::UPDATE
=> [
495 'name' => ts('Edit'),
496 'url' => 'civicrm/batch',
497 'qs' => 'action=update&id=%%id%%&reset=1',
498 'title' => ts('Edit Batch'),
500 CRM_Core_Action
::DELETE
=> [
501 'name' => ts('Delete'),
502 'url' => 'civicrm/batch',
503 'qs' => 'action=delete&id=%%id%%',
504 'title' => ts('Delete Batch'),
515 * all batches excluding batches with data entry in progress
517 public static function getBatches() {
518 $dataEntryStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Data Entry');
519 $query = "SELECT id, title
521 WHERE item_count >= 1
522 AND status_id != {$dataEntryStatusId}
526 $dao = CRM_Core_DAO
::executeQuery($query);
527 while ($dao->fetch()) {
528 $batches[$dao->id
] = $dao->title
;
534 * Calculate sum of all entries in a batch.
535 * Used to validate and update item_count and total when closing an accounting batch
537 * @param array $batchIds
540 public static function batchTotals($batchIds) {
541 $totals = array_fill_keys($batchIds, ['item_count' => 0, 'total' => 0]);
543 $sql = "SELECT eb.batch_id, COUNT(tx.id) AS item_count, SUM(tx.total_amount) AS total
544 FROM civicrm_entity_batch eb
545 INNER JOIN civicrm_financial_trxn tx ON tx.id = eb.entity_id AND eb.entity_table = 'civicrm_financial_trxn'
546 WHERE eb.batch_id IN (" . implode(',', $batchIds) . ")
547 GROUP BY eb.batch_id";
548 $dao = CRM_Core_DAO
::executeQuery($sql);
549 while ($dao->fetch()) {
550 $totals[$dao->batch_id
] = (array) $dao;
557 * Format markup for comparing two totals.
565 public static function displayTotals($actual, $expected) {
566 $class = 'actual-value';
567 if ($expected && $expected != $actual) {
568 $class .= ' crm-error';
570 $actualTitle = ts('Current Total');
571 $output = "<span class='$class' title='$actualTitle'>$actual</span>";
573 $expectedTitle = ts('Expected Total');
574 $output .= " / <span class='expected-value' title='$expectedTitle'>$expected</span>";
580 * Function for exporting financial accounts, currently we support CSV and IIF format
581 * @see http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+Specifications+-++Batches#CiviAccountsSpecifications-Batches-%C2%A0Overviewofimplementation
583 * @param array $batchIds
584 * Associated array of batch ids.
585 * @param string $exportFormat
587 * @param bool $downloadFile
588 * Download export file?.
590 public static function exportFinancialBatch($batchIds, $exportFormat, $downloadFile) {
591 if (empty($batchIds)) {
592 CRM_Core_Error
::fatal(ts('No batches were selected.'));
595 if (empty($exportFormat)) {
596 CRM_Core_Error
::fatal(ts('No export format selected.'));
599 self
::$_exportFormat = $exportFormat;
601 // Instantiate appropriate exporter based on user-selected format.
602 $exporterClass = "CRM_Financial_BAO_ExportFormat_" . self
::$_exportFormat;
603 if (class_exists($exporterClass)) {
604 $exporter = new $exporterClass();
607 CRM_Core_Error
::fatal("Could not locate exporter: $exporterClass");
610 $exporter->_isDownloadFile
= $downloadFile;
611 foreach ($batchIds as $batchId) {
612 // export only batches whose status is set to Exported.
613 $result = civicrm_api3('Batch', 'getcount', [
615 'status_id' => "Exported",
620 $export[$batchId] = $exporter->generateExportQuery($batchId);
623 $exporter->makeExport($export);
628 * @param array $batchIds
631 public static function closeReOpen($batchIds = [], $status) {
632 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id');
633 $params['status_id'] = CRM_Utils_Array
::key($status, $batchStatus);
634 $session = CRM_Core_Session
::singleton();
635 $params['modified_date'] = date('YmdHis');
636 $params['modified_id'] = $session->get('userID');
637 foreach ($batchIds as $key => $value) {
638 $params['id'] = $ids['batchID'] = $value;
639 self
::create($params, $ids);
641 $url = CRM_Utils_System
::url('civicrm/financial/financialbatches', "reset=1&batchStatus={$params['status_id']}");
642 CRM_Utils_System
::redirect($url);
646 * Retrieve financial items assigned for a batch.
648 * @param int $entityID
649 * @param array $returnValues
650 * @param bool $notPresent
651 * @param array $params
652 * @param bool $getCount
654 * @return CRM_Core_DAO
656 public static function getBatchFinancialItems($entityID, $returnValues, $notPresent = NULL, $params = NULL, $getCount = FALSE) {
658 if (!empty($params['rowCount']) &&
659 $params['rowCount'] > 0
661 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
664 // action is taken depending upon the mode
665 $select = 'civicrm_financial_trxn.id ';
666 if (!empty($returnValues)) {
667 $select .= " , " . implode(' , ', $returnValues);
670 $orderBy = " ORDER BY civicrm_financial_trxn.id";
671 if (!empty($params['sort'])) {
672 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
675 $from = "civicrm_financial_trxn
676 INNER JOIN civicrm_entity_financial_trxn ON civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id
677 INNER JOIN civicrm_contribution ON (civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id
678 AND civicrm_entity_financial_trxn.entity_table='civicrm_contribution')
679 LEFT JOIN civicrm_entity_batch ON civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
680 AND civicrm_entity_batch.entity_id = civicrm_financial_trxn.id
681 LEFT JOIN civicrm_financial_type ON civicrm_financial_type.id = civicrm_contribution.financial_type_id
682 LEFT JOIN civicrm_contact contact_a ON contact_a.id = civicrm_contribution.contact_id
683 LEFT JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id
689 'contribution_page_id',
690 'contribution_payment_instrument_id',
691 'contribution_trxn_id',
692 'contribution_source',
693 'contribution_currency_type',
694 'contribution_pay_later',
695 'contribution_recurring',
697 'contribution_thankyou_date_is_not_null',
698 'contribution_receipt_date_is_not_null',
699 'contribution_pcp_made_through_id',
700 'contribution_pcp_display_in_roll',
701 'contribution_amount_low',
702 'contribution_amount_high',
703 'contribution_in_honor_of',
706 'receive_date_relative',
709 'contribution_check_number',
710 'contribution_status_id',
711 'financial_trxn_card_type_id',
712 'financial_trxn_pan_truncation',
715 foreach ($searchFields as $field) {
716 if (isset($params[$field])) {
717 $values[$field] = $params[$field];
718 if ($field == 'sort_name') {
719 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id
720 LEFT JOIN civicrm_email ON contact_b.id = civicrm_email.contact_id";
722 if ($field == 'contribution_in_honor_of') {
723 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id";
725 if ($field == 'contact_tags') {
726 $from .= " LEFT JOIN civicrm_entity_tag `civicrm_entity_tag-{$params[$field]}` ON `civicrm_entity_tag-{$params[$field]}`.entity_id = contact_a.id";
728 if ($field == 'group') {
729 $from .= " LEFT JOIN civicrm_group_contact `civicrm_group_contact-{$params[$field]}` ON contact_a.id = `civicrm_group_contact-{$params[$field]}`.contact_id ";
731 if ($field == 'receive_date_relative') {
732 $relativeDate = explode('.', $params[$field]);
733 $date = CRM_Utils_Date
::relativeToAbsolute($relativeDate[0], $relativeDate[1]);
734 $values['receive_date_low'] = $date['from'];
735 $values['receive_date_high'] = $date['to'];
740 $searchParams = CRM_Contact_BAO_Query
::convertFormValues(
747 'contribution_soft_credit_type_id',
748 'contribution_status_id',
749 'contribution_page_id',
750 'financial_trxn_card_type_id',
751 'contribution_payment_instrument_id',
754 // @todo the use of defaultReturnProperties means the search will be inefficient
755 // as slow-unneeded properties are included.
756 $query = new CRM_Contact_BAO_Query($searchParams,
757 CRM_Contribute_BAO_Query
::defaultReturnProperties(CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
,
759 ), NULL, FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
762 if (!empty($query->_where
[0])) {
763 $where = implode(' AND ', $query->_where
[0]) .
764 " AND civicrm_entity_batch.batch_id IS NULL ";
765 $where = str_replace('civicrm_contribution.payment_instrument_id', 'civicrm_financial_trxn.payment_instrument_id', $where);
769 $where = " civicrm_entity_batch.batch_id = {$entityID} ";
772 $where = " civicrm_entity_batch.batch_id IS NULL ";
787 $result = CRM_Core_DAO
::executeQuery($sql);
793 * @param string $batchIds
798 public static function getBatchNames($batchIds) {
799 $query = 'SELECT id, title
801 WHERE id IN (' . $batchIds . ')';
804 $dao = CRM_Core_DAO
::executeQuery($query);
805 while ($dao->fetch()) {
806 $batches[$dao->id
] = $dao->title
;
812 * Function get batch statuses.
814 * @param string $batchIds
819 public static function getBatchStatuses($batchIds) {
820 $query = 'SELECT id, status_id
822 WHERE id IN (' . $batchIds . ')';
825 $dao = CRM_Core_DAO
::executeQuery($query);
826 while ($dao->fetch()) {
827 $batches[$dao->id
] = $dao->status_id
;
833 * Function to check permission for batch.
835 * @param string $action
836 * @param int $batchCreatedId
837 * batch created by contact id
841 public static function checkBatchPermission($action, $batchCreatedId = NULL) {
842 if (CRM_Core_Permission
::check("{$action} all manual batches")) {
845 if (CRM_Core_Permission
::check("{$action} own manual batches")) {
846 $loggedInContactId = CRM_Core_Session
::singleton()->get('userID');
847 if ($batchCreatedId == $loggedInContactId) {
850 elseif (CRM_Utils_System
::isNull($batchCreatedId)) {