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) {
45 if (empty($params['id']) && empty($params['name'])) {
46 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
48 return self
::writeRecord($params);
52 * Retrieve the information about the batch.
54 * @param array $params
55 * (reference ) an assoc array of name/value pairs.
56 * @param array $defaults
57 * (reference ) an assoc array to hold the flattened values.
60 * CRM_Batch_BAO_Batch object on success, null otherwise
62 public static function retrieve(&$params, &$defaults) {
63 $batch = new CRM_Batch_DAO_Batch();
64 $batch->copyValues($params);
65 if ($batch->find(TRUE)) {
66 CRM_Core_DAO
::storeValues($batch, $defaults);
73 * Get profile id associated with the batch type.
75 * @param int $batchTypeId
79 * $profileId profile id
81 public static function getProfileId($batchTypeId) {
82 //retrieve the profile specific to batch type
83 switch ($batchTypeId) {
86 //batch profile used for pledges
87 $profileName = "contribution_batch_entry";
91 //batch profile used for memberships
92 $profileName = "membership_batch_entry";
96 // get and return the profile id
97 return CRM_Core_DAO
::getFieldValue('CRM_Core_BAO_UFGroup', $profileName, 'id', 'name');
101 * Generate batch name.
106 public static function generateBatchName() {
107 $sql = "SELECT max(id) FROM civicrm_batch";
108 $batchNo = CRM_Core_DAO
::singleValueQuery($sql) +
1;
109 return ts('Batch %1', [1 => $batchNo]) . ': ' . date('Y-m-d');
113 * Delete batch entry.
115 * @param int $batchId
120 public static function deleteBatch($batchId) {
121 // delete entry from batch table
122 CRM_Utils_Hook
::pre('delete', 'Batch', $batchId, CRM_Core_DAO
::$_nullArray);
123 $batch = new CRM_Batch_DAO_Batch();
124 $batch->id
= $batchId;
126 CRM_Utils_Hook
::post('delete', 'Batch', $batch->id
, $batch);
131 * wrapper for ajax batch selector.
133 * @param array $params
134 * Associated array for params record id.
137 * associated array of batch list
139 public static function getBatchListSelector(&$params) {
141 $params['offset'] = ($params['page'] - 1) * $params['rp'];
142 $params['rowCount'] = $params['rp'];
143 $params['sort'] = $params['sortBy'] ??
NULL;
146 $batches = self
::getBatchList($params);
148 // get batch totals for open batches
150 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
152 array_search('Open', $batchStatus),
153 array_search('Reopened', $batchStatus),
155 if ($params['context'] == 'financialBatch') {
156 foreach ($batches as $id => $batch) {
157 if (in_array($batch['status_id'], $batchStatus)) {
158 $fetchTotals[] = $id;
162 $totals = self
::batchTotals($fetchTotals);
165 $params['total'] = self
::getBatchCount($params);
167 // format params and add links
170 foreach ($batches as $id => $value) {
172 if ($params['context'] == 'financialBatch') {
173 $batch['check'] = $value['check'];
175 $batch['batch_name'] = $value['title'];
176 $batch['total'] = '';
177 $batch['payment_instrument'] = $value['payment_instrument'];
178 $batch['item_count'] = $value['item_count'] ??
NULL;
179 $batch['type'] = $value['batch_type'] ??
NULL;
180 if (!empty($value['total'])) {
182 $batch['total'] = CRM_Utils_Money
::format($value['total'], $value['currency']);
185 // Compare totals with actuals
186 if (isset($totals[$id])) {
187 $batch['item_count'] = self
::displayTotals($totals[$id]['item_count'], $batch['item_count']);
188 $batch['total'] = self
::displayTotals(CRM_Utils_Money
::format($totals[$id]['total']), $batch['total']);
190 $batch['status'] = $value['batch_status'];
191 $batch['created_by'] = $value['created_by'];
192 $batch['links'] = $value['action'];
193 $batchList[$id] = $batch;
199 * Get list of batches.
201 * @param array $params
202 * Associated array for params.
206 public static function getBatchList(&$params) {
207 $apiParams = self
::whereClause($params);
209 if (!empty($params['rowCount']) && is_numeric($params['rowCount'])
210 && is_numeric($params['offset']) && $params['rowCount'] > 0
212 $apiParams['options'] = ['offset' => $params['offset'], 'limit' => $params['rowCount']];
214 $apiParams['options']['sort'] = 'id DESC';
215 if (!empty($params['sort'])) {
216 $apiParams['options']['sort'] = CRM_Utils_Type
::escape($params['sort'], 'String');
233 "payment_instrument_id",
234 "created_id.sort_name",
237 $apiParams['return'] = $return;
238 $batches = civicrm_api3('Batch', 'get', $apiParams);
239 $obj = new CRM_Batch_BAO_Batch();
240 if (!empty($params['context'])) {
241 $links = $obj->links($params['context']);
244 $links = $obj->links();
247 $batchTypes = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'type_id');
248 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id');
249 $batchStatusByName = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
250 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
253 foreach ($batches['values'] as $values) {
255 $action = array_sum(array_keys($newLinks));
257 if ($values['status_id'] == array_search('Closed', $batchStatusByName) && $params['context'] != 'financialBatch') {
260 elseif ($params['context'] == 'financialBatch') {
261 $values['check'] = "<input type='checkbox' id='check_" .
265 "' value='1' data-status_id='" .
266 $values['status_id'] . "' class='select-row'></input>";
268 switch ($batchStatusByName[$values['status_id']]) {
271 CRM_Utils_Array
::remove($newLinks, 'reopen', 'download');
275 CRM_Utils_Array
::remove($newLinks, 'close', 'edit', 'download');
279 CRM_Utils_Array
::remove($newLinks, 'close', 'edit', 'reopen', 'export');
281 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('edit', $values['created_id'])) {
282 CRM_Utils_Array
::remove($newLinks, 'edit');
284 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('close', $values['created_id'])) {
285 CRM_Utils_Array
::remove($newLinks, 'close', 'export');
287 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('reopen', $values['created_id'])) {
288 CRM_Utils_Array
::remove($newLinks, 'reopen');
290 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('export', $values['created_id'])) {
291 CRM_Utils_Array
::remove($newLinks, 'export', 'download');
293 if (!CRM_Batch_BAO_Batch
::checkBatchPermission('delete', $values['created_id'])) {
294 CRM_Utils_Array
::remove($newLinks, 'delete');
297 if (!empty($values['type_id'])) {
298 $values['batch_type'] = $batchTypes[$values['type_id']];
300 $values['batch_status'] = $batchStatus[$values['status_id']];
301 $values['created_by'] = $values['created_id.sort_name'];
302 $values['payment_instrument'] = '';
303 if (!empty($values['payment_instrument_id'])) {
304 $values['payment_instrument'] = $paymentInstrument[$values['payment_instrument_id']];
306 $tokens = ['id' => $values['id'], 'status' => $values['status_id']];
307 if ($values['status_id'] == array_search('Exported', $batchStatusByName)) {
308 $aid = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Export Accounting Batch');
309 $activityParams = ['source_record_id' => $values['id'], 'activity_type_id' => $aid];
310 $exportActivity = CRM_Activity_BAO_Activity
::retrieve($activityParams, $val);
311 if ($exportActivity) {
312 $fid = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile', $exportActivity->id
, 'file_id', 'entity_id');
313 $fileHash = CRM_Core_BAO_File
::generateFileHash($exportActivity->id
, $fid);
314 $tokens = array_merge(['eid' => $exportActivity->id
, 'fid' => $fid, 'fcs' => $fileHash], $tokens);
317 CRM_Utils_Array
::remove($newLinks, 'export', 'download');
320 $values['action'] = CRM_Core_Action
::formLink(
326 'batch.selector.row',
331 $values['currency'] = CRM_Core_DAO
::singleValueQuery("
332 SELECT GROUP_CONCAT(DISTINCT ft.currency)
333 FROM civicrm_batch batch
334 JOIN civicrm_entity_batch eb
335 ON batch.id = eb.batch_id
336 JOIN civicrm_financial_trxn ft
337 ON eb.entity_id = ft.id
340 ", [1 => [$values['id'], 'Positive']]);
341 $results[$values['id']] = $values;
348 * Get count of batches.
350 * @param array $params
351 * Associated array for params.
353 * @return null|string
355 public static function getBatchCount(&$params) {
356 $apiParams = self
::whereClause($params);
357 return civicrm_api3('Batch', 'getCount', $apiParams);
361 * Format where clause for getting lists of batches.
363 * @param array $params
364 * Associated array for params.
368 public static function whereClause($params) {
370 // Exclude data-entry batches
371 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
372 if (empty($params['status_id'])) {
373 $clauses['status_id'] = ['NOT IN' => ["Data Entry"]];
390 "payment_instrument_id",
391 "created_id.sort_name",
394 if (!CRM_Core_Permission
::check("view all manual batches")) {
395 if (CRM_Core_Permission
::check("view own manual batches")) {
396 $loggedInContactId = CRM_Core_Session
::singleton()->get('userID');
397 $params['created_id'] = $loggedInContactId;
400 $params['created_id'] = 0;
403 foreach ($return as $field) {
404 if (!isset($params[$field])) {
407 $value = CRM_Utils_Type
::escape($params[$field], 'String', FALSE);
408 if (in_array($field, ['name', 'title', 'description', 'created_id.sort_name'])) {
409 $clauses[$field] = ['LIKE' => "%{$value}%"];
411 elseif ($field == 'status_id' && $value == array_search('Open', $batchStatus)) {
412 $clauses['status_id'] = ['IN' => ["Open", 'Reopened']];
415 $clauses[$field] = $value;
422 * Define action links.
424 * @param null $context
427 * array of action links
429 public function links($context = NULL) {
430 if ($context == 'financialBatch') {
433 'name' => ts('Transactions'),
434 'url' => 'civicrm/batchtransaction',
435 'qs' => 'reset=1&bid=%%id%%',
436 'title' => ts('View/Add Transactions to Batch'),
439 'name' => ts('Edit'),
440 'url' => 'civicrm/financial/batch',
441 'qs' => 'reset=1&action=update&id=%%id%%&context=1',
442 'title' => ts('Edit Batch'),
445 'name' => ts('Close'),
446 'title' => ts('Close Batch'),
448 'extra' => 'rel="close"',
451 'name' => ts('Export'),
452 'title' => ts('Export Batch'),
454 'extra' => 'rel="export"',
457 'name' => ts('Re-open'),
458 'title' => ts('Re-open Batch'),
460 'extra' => 'rel="reopen"',
463 'name' => ts('Delete'),
464 'title' => ts('Delete Batch'),
466 'extra' => 'rel="delete"',
469 'name' => ts('Download'),
470 'url' => 'civicrm/file',
471 'qs' => 'reset=1&id=%%fid%%&eid=%%eid%%&fcs=%%fcs%%',
472 'title' => ts('Download Batch'),
478 CRM_Core_Action
::COPY
=> [
479 'name' => ts('Enter records'),
480 'url' => 'civicrm/batch/entry',
481 'qs' => 'id=%%id%%&reset=1',
482 'title' => ts('Batch Data Entry'),
484 CRM_Core_Action
::UPDATE
=> [
485 'name' => ts('Edit'),
486 'url' => 'civicrm/batch',
487 'qs' => 'action=update&id=%%id%%&reset=1',
488 'title' => ts('Edit Batch'),
490 CRM_Core_Action
::DELETE
=> [
491 'name' => ts('Delete'),
492 'url' => 'civicrm/batch',
493 'qs' => 'action=delete&id=%%id%%',
494 'title' => ts('Delete Batch'),
505 * all batches excluding batches with data entry in progress
507 public static function getBatches() {
508 $dataEntryStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Data Entry');
509 $query = "SELECT id, title
511 WHERE item_count >= 1
512 AND status_id != {$dataEntryStatusId}
516 $dao = CRM_Core_DAO
::executeQuery($query);
517 while ($dao->fetch()) {
518 $batches[$dao->id
] = $dao->title
;
524 * Calculate sum of all entries in a batch.
525 * Used to validate and update item_count and total when closing an accounting batch
527 * @param array $batchIds
530 public static function batchTotals($batchIds) {
531 $totals = array_fill_keys($batchIds, ['item_count' => 0, 'total' => 0]);
533 $sql = "SELECT eb.batch_id, COUNT(tx.id) AS item_count, SUM(tx.total_amount) AS total
534 FROM civicrm_entity_batch eb
535 INNER JOIN civicrm_financial_trxn tx ON tx.id = eb.entity_id AND eb.entity_table = 'civicrm_financial_trxn'
536 WHERE eb.batch_id IN (" . implode(',', $batchIds) . ")
537 GROUP BY eb.batch_id";
538 $dao = CRM_Core_DAO
::executeQuery($sql);
539 while ($dao->fetch()) {
540 $totals[$dao->batch_id
] = (array) $dao;
547 * Format markup for comparing two totals.
555 public static function displayTotals($actual, $expected) {
556 $class = 'actual-value';
557 if ($expected && $expected != $actual) {
558 $class .= ' crm-error';
560 $actualTitle = ts('Current Total');
561 $output = "<span class='$class' title='$actualTitle'>$actual</span>";
563 $expectedTitle = ts('Expected Total');
564 $output .= " / <span class='expected-value' title='$expectedTitle'>$expected</span>";
570 * Function for exporting financial accounts, currently we support CSV and IIF format
571 * @see http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+Specifications+-++Batches#CiviAccountsSpecifications-Batches-%C2%A0Overviewofimplementation
573 * @param array $batchIds
574 * Associated array of batch ids.
575 * @param string $exportFormat
577 * @param bool $downloadFile
578 * Download export file?.
580 public static function exportFinancialBatch($batchIds, $exportFormat, $downloadFile) {
581 if (empty($batchIds)) {
582 CRM_Core_Error
::fatal(ts('No batches were selected.'));
585 if (empty($exportFormat)) {
586 CRM_Core_Error
::fatal(ts('No export format selected.'));
589 self
::$_exportFormat = $exportFormat;
591 // Instantiate appropriate exporter based on user-selected format.
592 $exporterClass = "CRM_Financial_BAO_ExportFormat_" . self
::$_exportFormat;
593 if (class_exists($exporterClass)) {
594 $exporter = new $exporterClass();
597 CRM_Core_Error
::fatal("Could not locate exporter: $exporterClass");
600 $exporter->_isDownloadFile
= $downloadFile;
601 foreach ($batchIds as $batchId) {
602 // export only batches whose status is set to Exported.
603 $result = civicrm_api3('Batch', 'getcount', [
605 'status_id' => "Exported",
610 $export[$batchId] = $exporter->generateExportQuery($batchId);
613 $exporter->makeExport($export);
618 * @param array $batchIds
621 public static function closeReOpen($batchIds = [], $status) {
622 $batchStatus = CRM_Core_PseudoConstant
::get('CRM_Batch_DAO_Batch', 'status_id');
623 $params['status_id'] = CRM_Utils_Array
::key($status, $batchStatus);
624 $session = CRM_Core_Session
::singleton();
625 $params['modified_date'] = date('YmdHis');
626 $params['modified_id'] = $session->get('userID');
627 foreach ($batchIds as $key => $value) {
628 $params['id'] = $ids['batchID'] = $value;
629 self
::create($params, $ids);
631 $url = CRM_Utils_System
::url('civicrm/financial/financialbatches', "reset=1&batchStatus={$params['status_id']}");
632 CRM_Utils_System
::redirect($url);
636 * Retrieve financial items assigned for a batch.
638 * @param int $entityID
639 * @param array $returnValues
640 * @param bool $notPresent
641 * @param array $params
642 * @param bool $getCount
644 * @return CRM_Core_DAO
646 public static function getBatchFinancialItems($entityID, $returnValues, $notPresent = NULL, $params = NULL, $getCount = FALSE) {
648 if (!empty($params['rowCount']) &&
649 $params['rowCount'] > 0
651 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
654 // action is taken depending upon the mode
655 $select = 'civicrm_financial_trxn.id ';
656 if (!empty($returnValues)) {
657 $select .= " , " . implode(' , ', $returnValues);
660 $orderBy = " ORDER BY civicrm_financial_trxn.id";
661 if (!empty($params['sort'])) {
662 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
665 $from = "civicrm_financial_trxn
666 INNER JOIN civicrm_entity_financial_trxn ON civicrm_entity_financial_trxn.financial_trxn_id = civicrm_financial_trxn.id
667 INNER JOIN civicrm_contribution ON (civicrm_contribution.id = civicrm_entity_financial_trxn.entity_id
668 AND civicrm_entity_financial_trxn.entity_table='civicrm_contribution')
669 LEFT JOIN civicrm_entity_batch ON civicrm_entity_batch.entity_table = 'civicrm_financial_trxn'
670 AND civicrm_entity_batch.entity_id = civicrm_financial_trxn.id
671 LEFT JOIN civicrm_financial_type ON civicrm_financial_type.id = civicrm_contribution.financial_type_id
672 LEFT JOIN civicrm_contact contact_a ON contact_a.id = civicrm_contribution.contact_id
673 LEFT JOIN civicrm_contribution_soft ON civicrm_contribution_soft.contribution_id = civicrm_contribution.id
679 'contribution_page_id',
680 'contribution_payment_instrument_id',
681 'contribution_trxn_id',
682 'contribution_source',
683 'contribution_currency_type',
684 'contribution_pay_later',
685 'contribution_recurring',
687 'contribution_thankyou_date_is_not_null',
688 'contribution_receipt_date_is_not_null',
689 'contribution_pcp_made_through_id',
690 'contribution_pcp_display_in_roll',
691 'contribution_amount_low',
692 'contribution_amount_high',
693 'contribution_in_honor_of',
696 'receive_date_relative',
699 'contribution_check_number',
700 'contribution_status_id',
701 'financial_trxn_card_type_id',
702 'financial_trxn_pan_truncation',
705 foreach ($searchFields as $field) {
706 if (isset($params[$field])) {
707 $values[$field] = $params[$field];
708 if ($field == 'sort_name') {
709 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id
710 LEFT JOIN civicrm_email ON contact_b.id = civicrm_email.contact_id";
712 if ($field == 'contribution_in_honor_of') {
713 $from .= " LEFT JOIN civicrm_contact contact_b ON contact_b.id = civicrm_contribution.contact_id";
715 if ($field == 'contact_tags') {
716 $from .= " LEFT JOIN civicrm_entity_tag `civicrm_entity_tag-{$params[$field]}` ON `civicrm_entity_tag-{$params[$field]}`.entity_id = contact_a.id";
718 if ($field == 'group') {
719 $from .= " LEFT JOIN civicrm_group_contact `civicrm_group_contact-{$params[$field]}` ON contact_a.id = `civicrm_group_contact-{$params[$field]}`.contact_id ";
721 if ($field == 'receive_date_relative') {
722 $relativeDate = explode('.', $params[$field]);
723 $date = CRM_Utils_Date
::relativeToAbsolute($relativeDate[0], $relativeDate[1]);
724 $values['receive_date_low'] = $date['from'];
725 $values['receive_date_high'] = $date['to'];
730 $searchParams = CRM_Contact_BAO_Query
::convertFormValues(
737 'contribution_soft_credit_type_id',
738 'contribution_status_id',
739 'contribution_page_id',
740 'financial_trxn_card_type_id',
741 'contribution_payment_instrument_id',
744 // @todo the use of defaultReturnProperties means the search will be inefficient
745 // as slow-unneeded properties are included.
746 $query = new CRM_Contact_BAO_Query($searchParams,
747 CRM_Contribute_BAO_Query
::defaultReturnProperties(CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
,
749 ), NULL, FALSE, FALSE, CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
752 if (!empty($query->_where
[0])) {
753 $where = implode(' AND ', $query->_where
[0]) .
754 " AND civicrm_entity_batch.batch_id IS NULL ";
755 $where = str_replace('civicrm_contribution.payment_instrument_id', 'civicrm_financial_trxn.payment_instrument_id', $where);
759 $where = " civicrm_entity_batch.batch_id = {$entityID} ";
762 $where = " civicrm_entity_batch.batch_id IS NULL ";
777 $result = CRM_Core_DAO
::executeQuery($sql);
783 * @param string $batchIds
788 public static function getBatchNames($batchIds) {
789 $query = 'SELECT id, title
791 WHERE id IN (' . $batchIds . ')';
794 $dao = CRM_Core_DAO
::executeQuery($query);
795 while ($dao->fetch()) {
796 $batches[$dao->id
] = $dao->title
;
802 * Function get batch statuses.
804 * @param string $batchIds
809 public static function getBatchStatuses($batchIds) {
810 $query = 'SELECT id, status_id
812 WHERE id IN (' . $batchIds . ')';
815 $dao = CRM_Core_DAO
::executeQuery($query);
816 while ($dao->fetch()) {
817 $batches[$dao->id
] = $dao->status_id
;
823 * Function to check permission for batch.
825 * @param string $action
826 * @param int $batchCreatedId
827 * batch created by contact id
831 public static function checkBatchPermission($action, $batchCreatedId = NULL) {
832 if (CRM_Core_Permission
::check("{$action} all manual batches")) {
835 if (CRM_Core_Permission
::check("{$action} own manual batches")) {
836 $loggedInContactId = CRM_Core_Session
::singleton()->get('userID');
837 if ($batchCreatedId == $loggedInContactId) {
840 elseif (CRM_Utils_System
::isNull($batchCreatedId)) {