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
17 class CRM_Report_Form_Contribute_Sybunt
extends CRM_Report_Form
{
19 protected $_customGroupExtends = [
25 public $_drilldownReport = ['contribute/detail' => 'Link to Detail Report'];
28 * This report has been optimised for group filtering.
31 * @see https://issues.civicrm.org/jira/browse/CRM-19170
33 protected $groupFilterNotOptimised = FALSE;
38 public function __construct() {
39 $this->_rollup
= 'WITH ROLLUP';
40 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
43 $date = CRM_Core_SelectValues
::date('custom', NULL, $yearsInPast, $yearsInFuture);
44 $count = $date['maxYear'];
45 while ($date['minYear'] <= $count) {
46 $optionYear[$date['minYear']] = $date['minYear'];
51 'civicrm_contact' => [
52 'dao' => 'CRM_Contact_DAO_Contact',
53 'grouping' => 'contact-field',
56 'title' => ts('Donor Name'),
60 'title' => ts('First Name'),
63 'title' => ts('Middle Name'),
66 'title' => ts('Last Name'),
73 'title' => ts('Gender'),
76 'title' => ts('Birth Date'),
80 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
83 'title' => ts('Contact Type'),
85 'contact_sub_type' => [
86 'title' => ts('Contact Subtype'),
91 'title' => ts('Last Name, First Name'),
93 'default_weight' => '0',
94 'default_order' => 'ASC',
97 'name' => 'first_name',
98 'title' => ts('First Name'),
101 'name' => 'gender_id',
102 'title' => ts('Gender'),
105 'name' => 'birth_date',
106 'title' => ts('Birth Date'),
109 'name' => 'age_at_event',
110 'title' => ts('Age at Event'),
113 'title' => ts('Contact Type'),
115 'contact_sub_type' => [
116 'title' => ts('Contact Subtype'),
121 'title' => ts('Donor Name'),
122 'operator' => 'like',
125 'title' => ts('Contact ID'),
126 'no_display' => TRUE,
129 'title' => ts('Gender'),
130 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
131 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
134 'title' => ts('Birth Date'),
135 'operatorType' => CRM_Report_Form
::OP_DATE
,
138 'title' => ts('Contact Type'),
140 'contact_sub_type' => [
141 'title' => ts('Contact Subtype'),
145 'civicrm_line_item' => [
146 'dao' => 'CRM_Price_DAO_LineItem',
149 'dao' => 'CRM_Core_DAO_Email',
150 'grouping' => 'contact-field',
153 'title' => ts('Email'),
159 'title' => ts('On Hold'),
160 'type' => CRM_Utils_Type
::T_INT
,
161 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
162 'options' => ['' => ts('Any')] + CRM_Core_PseudoConstant
::emailOnHoldOptions(),
167 'dao' => 'CRM_Core_DAO_Phone',
168 'grouping' => 'contact-field',
171 'title' => ts('Phone'),
177 $this->_columns +
= $this->addAddressFields();
179 'civicrm_contribution' => [
180 'dao' => 'CRM_Contribute_DAO_Contribution',
183 'title' => ts('contactId'),
184 'no_display' => TRUE,
189 'title' => ts('Total Amount'),
190 'no_display' => TRUE,
195 'title' => ts('Year'),
196 'no_display' => TRUE,
203 'name' => 'receive_date',
204 'title' => ts('This Year'),
205 'operatorType' => CRM_Report_Form
::OP_SELECT
,
206 'options' => $optionYear,
207 'default' => date('Y'),
208 'type' => CRM_Utils_Type
::T_INT
,
210 'financial_type_id' => [
211 'title' => ts('Financial Type'),
212 'type' => CRM_Utils_Type
::T_INT
,
213 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
214 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('financial_type_id', 'search'),
216 'contribution_status_id' => [
217 'title' => ts('Contribution Status'),
218 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
219 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search'),
226 'civicrm_financial_trxn' => [
227 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
230 'title' => ts('Credit Card Type'),
231 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
236 'title' => ts('Credit Card Type'),
237 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
239 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
240 'type' => CRM_Utils_Type
::T_STRING
,
246 // If we have a campaign, build out the relevant elements
247 $this->addCampaignFields('civicrm_contribution');
249 // Add charts support
252 'barChart' => ts('Bar Chart'),
253 'pieChart' => ts('Pie Chart'),
256 $this->_groupFilter
= TRUE;
257 $this->_tagFilter
= TRUE;
258 parent
::__construct();
261 public function preProcess() {
262 parent
::preProcess();
265 public function select() {
267 $this->_columnHeaders
= [];
268 $current_year = $this->_params
['yid_value'];
269 $previous_year = $current_year - 1;
270 $previous_pyear = $current_year - 2;
271 $previous_ppyear = $current_year - 3;
272 $upTo_year = $current_year - 4;
274 foreach ($this->_columns
as $tableName => $table) {
275 if (array_key_exists('fields', $table)) {
276 foreach ($table['fields'] as $fieldName => $field) {
278 if (!empty($field['required']) ||
279 !empty($this->_params
['fields'][$fieldName])
281 if ($fieldName == 'total_amount') {
282 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
284 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['type'] = $field['type'];
285 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['title'] = ts("Up To %1", [1 => $upTo_year]);
287 $this->_columnHeaders
["year_{$previous_ppyear}"]['type'] = $field['type'];
288 $this->_columnHeaders
["year_{$previous_ppyear}"]['title'] = $previous_ppyear;
290 $this->_columnHeaders
["year_{$previous_pyear}"]['type'] = $field['type'];
291 $this->_columnHeaders
["year_{$previous_pyear}"]['title'] = $previous_pyear;
293 $this->_columnHeaders
["year_{$previous_year}"]['type'] = $field['type'];
294 $this->_columnHeaders
["year_{$previous_year}"]['title'] = $previous_year;
296 $this->_columnHeaders
["civicrm_life_time_total"]['type'] = $field['type'];
297 $this->_columnHeaders
["civicrm_life_time_total"]['title'] = ts('LifeTime');
299 elseif ($fieldName == 'receive_date') {
300 $select[] = self
::fiscalYearOffset($field['dbAlias']) .
301 " as {$tableName}_{$fieldName}";
304 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
305 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
306 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
308 if (!empty($field['no_display'])) {
309 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
315 $this->_selectClauses
= $select;
317 $this->_select
= "SELECT " . implode(', ', $select) . " ";
320 public function from() {
321 $this->setFromBase('civicrm_contribution', 'contact_id');
323 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
324 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
327 $this->joinPhoneFromContact();
328 $this->joinEmailFromContact();
330 // for credit card type
331 $this->addFinancialTrxnFromClause();
333 $this->joinAddressFromContact();
336 public function where() {
337 $this->_statusClause
= "";
339 $this->_aliases
['civicrm_contribution'] . '.is_test = 0',
340 $this->_aliases
['civicrm_contribution'] . '.is_template = 0',
342 foreach ($this->_columns
as $tableName => $table) {
343 if (array_key_exists('filters', $table)) {
344 foreach ($table['filters'] as $fieldName => $field) {
346 if ($fieldName == 'yid') {
347 $clause = "contribution_civireport.contact_id NOT IN
348 (SELECT distinct cont.id FROM civicrm_contact cont, civicrm_contribution contri
349 WHERE cont.id = contri.contact_id AND " .
350 self
::fiscalYearOffset('contri.receive_date') .
351 " = {$this->_params['yid_value']} AND contri.is_test = 0 AND contri.is_template = 0 )";
353 elseif (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
355 $relative = $this->_params
["{$fieldName}_relative"] ??
NULL;
356 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
357 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
359 if ($relative ||
$from ||
$to) {
360 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
364 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
366 $clause = $this->whereClause($field,
368 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
369 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
370 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
372 if (($fieldName == 'contribution_status_id' ||
373 $fieldName == 'financial_type_id') && !empty($clause)
375 $this->_statusClause
.= " AND " . $clause;
380 if (!empty($clause)) {
381 $clauses[] = $clause;
387 $this->_where
= "WHERE " . implode(' AND ', $clauses);
389 if ($this->_aclWhere
) {
390 $this->_where
.= " AND {$this->_aclWhere} ";
394 public function groupBy() {
395 $this->assign('chartSupported', TRUE);
396 $fiscalYearOffset = self
::fiscalYearOffset("{$this->_aliases['civicrm_contribution']}.receive_date");
397 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, {$fiscalYearOffset}";
398 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, ["{$this->_aliases['civicrm_contribution']}.contact_id", $fiscalYearOffset]);
399 $this->_groupBy
.= " {$this->_rollup}";
407 public function statistics(&$rows) {
408 $statistics = parent
::statistics($rows);
413 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
415 $sql = "{$select} {$this->_from} {$this->_where}";
416 $dao = CRM_Core_DAO
::executeQuery($sql);
418 $statistics['counts']['amount'] = [
419 'value' => $dao->amount
,
420 'title' => ts('Total LifeTime'),
421 'type' => CRM_Utils_Type
::T_MONEY
,
428 public function postProcess() {
429 // get ready with post process params
430 $this->beginPostProcess();
431 $this->buildACLClause($this->_aliases
['civicrm_contact']);
434 $rows = $contactIds = [];
435 if (empty($this->_params
['charts'])) {
437 $getContacts = "SELECT SQL_CALC_FOUND_ROWS {$this->_aliases['civicrm_contact']}.id as cid {$this->_from} {$this->_where} GROUP BY {$this->_aliases['civicrm_contact']}.id {$this->_limit}";
439 $dao = CRM_Core_DAO
::executeQuery($getContacts);
441 while ($dao->fetch()) {
442 $contactIds[] = $dao->cid
;
447 if (!empty($contactIds) ||
!empty($this->_params
['charts'])) {
448 if (!empty($this->_params
['charts'])) {
449 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
453 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
454 implode(',', $contactIds) .
455 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 AND {$this->_aliases['civicrm_contribution']}.is_template = 0 {$this->_statusClause} {$this->_groupBy} ";
458 $current_year = $this->_params
['yid_value'];
459 $previous_year = $current_year - 1;
460 $previous_pyear = $current_year - 2;
461 $previous_ppyear = $current_year - 3;
462 $upTo_year = $current_year - 4;
465 $dao = CRM_Core_DAO
::executeQuery($sql);
466 $contributionSum = 0;
468 while ($dao->fetch()) {
469 if (!$dao->civicrm_contribution_contact_id
) {
473 foreach ($this->_columnHeaders
as $key => $value) {
474 if (property_exists($dao, $key)) {
475 $rows[$dao->civicrm_contribution_contact_id
][$key] = $dao->$key;
478 if ($dao->civicrm_contribution_receive_date
) {
479 if ($dao->civicrm_contribution_receive_date
> $upTo_year) {
480 $contributionSum +
= $dao->civicrm_contribution_total_amount
;
481 $rows[$dao->civicrm_contribution_contact_id
]['year_' . $dao->civicrm_contribution_receive_date
] = $dao->civicrm_contribution_total_amount
;
485 $rows[$dao->civicrm_contribution_contact_id
]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount
;
486 if (($dao->civicrm_contribution_total_amount
- $contributionSum) > 0
488 $rows[$dao->civicrm_contribution_contact_id
]["civicrm_upto_{$upTo_year}"]
489 = $dao->civicrm_contribution_total_amount
- $contributionSum;
491 $contributionSum = 0;
495 // format result set.
496 $this->formatDisplay($rows, FALSE);
498 // assign variables to templates
499 $this->doTemplateAssignment($rows);
501 // do print / pdf / instance stuff if needed
502 $this->endPostProcess($rows);
508 public function buildChart(&$rows) {
511 $current_year = $this->_params
['yid_value'];
512 $previous_year = $current_year - 1;
513 $previous_two_year = $current_year - 2;
514 $previous_three_year = $current_year - 3;
515 $upto = $current_year - 4;
517 $interval[$previous_year] = $previous_year;
518 $interval[$previous_two_year] = $previous_two_year;
519 $interval[$previous_three_year] = $previous_three_year;
520 $interval["upto_{$upto}"] = "Up To {$upto}";
522 foreach ($rows as $key => $row) {
523 $display["upto_{$upto}"]
524 = CRM_Utils_Array
::value("upto_{$upto}", $display) + CRM_Utils_Array
::value("civicrm_upto_{$upto}", $row);
525 $display[$previous_year]
526 = CRM_Utils_Array
::value($previous_year, $display) + CRM_Utils_Array
::value($previous_year, $row);
527 $display[$previous_two_year]
528 = CRM_Utils_Array
::value($previous_two_year, $display) + CRM_Utils_Array
::value($previous_two_year, $row);
529 $display[$previous_three_year]
530 = CRM_Utils_Array
::value($previous_three_year, $display) + CRM_Utils_Array
::value($previous_three_year, $row);
533 $graphRows['value'] = $display;
534 $config = CRM_Core_Config
::Singleton();
536 'legend' => ts('Sybunt Report'),
537 'xname' => ts('Year'),
538 'yname' => ts('Amount (%1)', [1 => $config->defaultCurrency
]),
540 if ($this->_params
['charts']) {
542 CRM_Utils_Chart
::reportChart($graphRows, $this->_params
['charts'], $interval, $chartInfo);
543 $this->assign('chartType', $this->_params
['charts']);
548 * Alter display of rows.
550 * Iterate through the rows retrieved via SQL and make changes for display purposes,
551 * such as rendering contacts as links.
554 * Rows generated by SQL, with an array for each row.
556 public function alterDisplay(&$rows) {
559 foreach ($rows as $rowNum => $row) {
560 //Convert Display name into link
561 if (array_key_exists('civicrm_contact_sort_name', $row) &&
562 array_key_exists('civicrm_contribution_contact_id', $row)
564 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
565 'reset=1&force=1&id_op=eq&id_value=' .
566 $row['civicrm_contribution_contact_id'],
567 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
569 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
570 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
574 // convert campaign_id to campaign title
575 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
576 if ($value = $row['civicrm_contribution_campaign_id']) {
577 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->campaigns
[$value];
582 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ?
TRUE : $entryFound;
583 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, NULL, 'List all contribution(s)') ?
TRUE : $entryFound;
584 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
585 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
589 // skip looking further in rows, if first row itself doesn't
590 // have the column we need
598 * Override "This Year" $op options
599 * @param string $type
600 * @param null $fieldName
604 public function getOperationPair($type = "string", $fieldName = NULL) {
605 if ($fieldName == 'yid') {
607 'calendar' => ts('Is Calendar Year'),
608 'fiscal' => ts('Fiscal Year Starting'),
611 return parent
::getOperationPair($type, $fieldName);