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 $_charts = [
21 'barChart' => 'Bar Chart',
22 'pieChart' => 'Pie Chart',
25 protected $_customGroupExtends = [
31 public $_drilldownReport = ['contribute/detail' => 'Link to Detail Report'];
34 * This report has been optimised for group filtering.
37 * @see https://issues.civicrm.org/jira/browse/CRM-19170
39 protected $groupFilterNotOptimised = FALSE;
44 public function __construct() {
45 $this->_rollup
= 'WITH ROLLUP';
46 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
49 $date = CRM_Core_SelectValues
::date('custom', NULL, $yearsInPast, $yearsInFuture);
50 $count = $date['maxYear'];
51 while ($date['minYear'] <= $count) {
52 $optionYear[$date['minYear']] = $date['minYear'];
57 'civicrm_contact' => [
58 'dao' => 'CRM_Contact_DAO_Contact',
59 'grouping' => 'contact-field',
62 'title' => ts('Donor Name'),
66 'title' => ts('First Name'),
69 'title' => ts('Middle Name'),
72 'title' => ts('Last Name'),
79 'title' => ts('Gender'),
82 'title' => ts('Birth Date'),
86 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
89 'title' => ts('Contact Type'),
91 'contact_sub_type' => [
92 'title' => ts('Contact Subtype'),
97 'title' => ts('Last Name, First Name'),
99 'default_weight' => '0',
100 'default_order' => 'ASC',
103 'name' => 'first_name',
104 'title' => ts('First Name'),
107 'name' => 'gender_id',
108 'title' => ts('Gender'),
111 'name' => 'birth_date',
112 'title' => ts('Birth Date'),
115 'name' => 'age_at_event',
116 'title' => ts('Age at Event'),
119 'title' => ts('Contact Type'),
121 'contact_sub_type' => [
122 'title' => ts('Contact Subtype'),
127 'title' => ts('Donor Name'),
128 'operator' => 'like',
131 'title' => ts('Contact ID'),
132 'no_display' => TRUE,
135 'title' => ts('Gender'),
136 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
137 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
140 'title' => ts('Birth Date'),
141 'operatorType' => CRM_Report_Form
::OP_DATE
,
144 'title' => ts('Contact Type'),
146 'contact_sub_type' => [
147 'title' => ts('Contact Subtype'),
151 'civicrm_line_item' => [
152 'dao' => 'CRM_Price_DAO_LineItem',
155 'dao' => 'CRM_Core_DAO_Email',
156 'grouping' => 'contact-field',
159 'title' => ts('Email'),
165 'dao' => 'CRM_Core_DAO_Phone',
166 'grouping' => 'contact-field',
169 'title' => ts('Phone'),
175 $this->_columns +
= $this->addAddressFields();
177 'civicrm_contribution' => [
178 'dao' => 'CRM_Contribute_DAO_Contribution',
181 'title' => ts('contactId'),
182 'no_display' => TRUE,
187 'title' => ts('Total Amount'),
188 'no_display' => TRUE,
193 'title' => ts('Year'),
194 'no_display' => TRUE,
201 'name' => 'receive_date',
202 'title' => ts('This Year'),
203 'operatorType' => CRM_Report_Form
::OP_SELECT
,
204 'options' => $optionYear,
205 'default' => date('Y'),
206 'type' => CRM_Utils_Type
::T_INT
,
208 'financial_type_id' => [
209 'title' => ts('Financial Type'),
210 'type' => CRM_Utils_Type
::T_INT
,
211 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
212 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('financial_type_id', 'search'),
214 'contribution_status_id' => [
215 'title' => ts('Contribution Status'),
216 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
217 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search'),
224 'civicrm_financial_trxn' => [
225 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
228 'title' => ts('Credit Card Type'),
229 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
234 'title' => ts('Credit Card Type'),
235 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
237 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
238 'type' => CRM_Utils_Type
::T_STRING
,
244 // If we have a campaign, build out the relevant elements
245 $this->addCampaignFields('civicrm_contribution');
247 $this->_groupFilter
= TRUE;
248 $this->_tagFilter
= TRUE;
249 parent
::__construct();
252 public function preProcess() {
253 parent
::preProcess();
256 public function select() {
258 $this->_columnHeaders
= [];
259 $current_year = $this->_params
['yid_value'];
260 $previous_year = $current_year - 1;
261 $previous_pyear = $current_year - 2;
262 $previous_ppyear = $current_year - 3;
263 $upTo_year = $current_year - 4;
265 foreach ($this->_columns
as $tableName => $table) {
266 if (array_key_exists('fields', $table)) {
267 foreach ($table['fields'] as $fieldName => $field) {
269 if (!empty($field['required']) ||
270 !empty($this->_params
['fields'][$fieldName])
272 if ($fieldName == 'total_amount') {
273 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
275 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['type'] = $field['type'];
276 $this->_columnHeaders
["civicrm_upto_{$upTo_year}"]['title'] = ts("Up To %1", [1 => $upTo_year]);
278 $this->_columnHeaders
["year_{$previous_ppyear}"]['type'] = $field['type'];
279 $this->_columnHeaders
["year_{$previous_ppyear}"]['title'] = $previous_ppyear;
281 $this->_columnHeaders
["year_{$previous_pyear}"]['type'] = $field['type'];
282 $this->_columnHeaders
["year_{$previous_pyear}"]['title'] = $previous_pyear;
284 $this->_columnHeaders
["year_{$previous_year}"]['type'] = $field['type'];
285 $this->_columnHeaders
["year_{$previous_year}"]['title'] = $previous_year;
287 $this->_columnHeaders
["civicrm_life_time_total"]['type'] = $field['type'];
288 $this->_columnHeaders
["civicrm_life_time_total"]['title'] = ts('LifeTime');
290 elseif ($fieldName == 'receive_date') {
291 $select[] = self
::fiscalYearOffset($field['dbAlias']) .
292 " as {$tableName}_{$fieldName}";
295 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
296 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
297 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
299 if (!empty($field['no_display'])) {
300 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
306 $this->_selectClauses
= $select;
308 $this->_select
= "SELECT " . implode(', ', $select) . " ";
311 public function from() {
312 $this->setFromBase('civicrm_contribution', 'contact_id');
314 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
315 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
318 $this->joinPhoneFromContact();
319 $this->joinEmailFromContact();
321 // for credit card type
322 $this->addFinancialTrxnFromClause();
324 $this->joinAddressFromContact();
327 public function where() {
328 $this->_statusClause
= "";
329 $clauses = [$this->_aliases
['civicrm_contribution'] . '.is_test = 0'];
330 foreach ($this->_columns
as $tableName => $table) {
331 if (array_key_exists('filters', $table)) {
332 foreach ($table['filters'] as $fieldName => $field) {
334 if ($fieldName == 'yid') {
335 $clause = "contribution_civireport.contact_id NOT IN
336 (SELECT distinct cont.id FROM civicrm_contact cont, civicrm_contribution contri
337 WHERE cont.id = contri.contact_id AND " .
338 self
::fiscalYearOffset('contri.receive_date') .
339 " = {$this->_params['yid_value']} AND contri.is_test = 0 )";
341 elseif (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
343 $relative = $this->_params
["{$fieldName}_relative"] ??
NULL;
344 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
345 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
347 if ($relative ||
$from ||
$to) {
348 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
352 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
354 $clause = $this->whereClause($field,
356 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
357 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
358 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
360 if (($fieldName == 'contribution_status_id' ||
361 $fieldName == 'financial_type_id') && !empty($clause)
363 $this->_statusClause
.= " AND " . $clause;
368 if (!empty($clause)) {
369 $clauses[] = $clause;
375 $this->_where
= "WHERE " . implode(' AND ', $clauses);
377 if ($this->_aclWhere
) {
378 $this->_where
.= " AND {$this->_aclWhere} ";
382 public function groupBy() {
383 $this->assign('chartSupported', TRUE);
384 $fiscalYearOffset = self
::fiscalYearOffset("{$this->_aliases['civicrm_contribution']}.receive_date");
385 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, {$fiscalYearOffset}";
386 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($this->_selectClauses
, ["{$this->_aliases['civicrm_contribution']}.contact_id", $fiscalYearOffset]);
387 $this->_groupBy
.= " {$this->_rollup}";
395 public function statistics(&$rows) {
396 $statistics = parent
::statistics($rows);
401 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount ";
403 $sql = "{$select} {$this->_from} {$this->_where}";
404 $dao = CRM_Core_DAO
::executeQuery($sql);
406 $statistics['counts']['amount'] = [
407 'value' => $dao->amount
,
408 'title' => ts('Total LifeTime'),
409 'type' => CRM_Utils_Type
::T_MONEY
,
416 public function postProcess() {
417 // get ready with post process params
418 $this->beginPostProcess();
419 $this->buildACLClause($this->_aliases
['civicrm_contact']);
422 $rows = $contactIds = [];
423 if (empty($this->_params
['charts'])) {
425 $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}";
427 $dao = CRM_Core_DAO
::executeQuery($getContacts);
429 while ($dao->fetch()) {
430 $contactIds[] = $dao->cid
;
435 if (!empty($contactIds) ||
!empty($this->_params
['charts'])) {
436 if (!empty($this->_params
['charts'])) {
437 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
441 "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" .
442 implode(',', $contactIds) .
443 ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
446 $current_year = $this->_params
['yid_value'];
447 $previous_year = $current_year - 1;
448 $previous_pyear = $current_year - 2;
449 $previous_ppyear = $current_year - 3;
450 $upTo_year = $current_year - 4;
453 $dao = CRM_Core_DAO
::executeQuery($sql);
454 $contributionSum = 0;
456 while ($dao->fetch()) {
457 if (!$dao->civicrm_contribution_contact_id
) {
461 foreach ($this->_columnHeaders
as $key => $value) {
462 if (property_exists($dao, $key)) {
463 $rows[$dao->civicrm_contribution_contact_id
][$key] = $dao->$key;
466 if ($dao->civicrm_contribution_receive_date
) {
467 if ($dao->civicrm_contribution_receive_date
> $upTo_year) {
468 $contributionSum +
= $dao->civicrm_contribution_total_amount
;
469 $rows[$dao->civicrm_contribution_contact_id
]['year_' . $dao->civicrm_contribution_receive_date
] = $dao->civicrm_contribution_total_amount
;
473 $rows[$dao->civicrm_contribution_contact_id
]['civicrm_life_time_total'] = $dao->civicrm_contribution_total_amount
;
474 if (($dao->civicrm_contribution_total_amount
- $contributionSum) > 0
476 $rows[$dao->civicrm_contribution_contact_id
]["civicrm_upto_{$upTo_year}"]
477 = $dao->civicrm_contribution_total_amount
- $contributionSum;
479 $contributionSum = 0;
483 // format result set.
484 $this->formatDisplay($rows, FALSE);
486 // assign variables to templates
487 $this->doTemplateAssignment($rows);
489 // do print / pdf / instance stuff if needed
490 $this->endPostProcess($rows);
496 public function buildChart(&$rows) {
499 $current_year = $this->_params
['yid_value'];
500 $previous_year = $current_year - 1;
501 $previous_two_year = $current_year - 2;
502 $previous_three_year = $current_year - 3;
503 $upto = $current_year - 4;
505 $interval[$previous_year] = $previous_year;
506 $interval[$previous_two_year] = $previous_two_year;
507 $interval[$previous_three_year] = $previous_three_year;
508 $interval["upto_{$upto}"] = "Up To {$upto}";
510 foreach ($rows as $key => $row) {
511 $display["upto_{$upto}"]
512 = CRM_Utils_Array
::value("upto_{$upto}", $display) + CRM_Utils_Array
::value("civicrm_upto_{$upto}", $row);
513 $display[$previous_year]
514 = CRM_Utils_Array
::value($previous_year, $display) + CRM_Utils_Array
::value($previous_year, $row);
515 $display[$previous_two_year]
516 = CRM_Utils_Array
::value($previous_two_year, $display) + CRM_Utils_Array
::value($previous_two_year, $row);
517 $display[$previous_three_year]
518 = CRM_Utils_Array
::value($previous_three_year, $display) + CRM_Utils_Array
::value($previous_three_year, $row);
521 $graphRows['value'] = $display;
522 $config = CRM_Core_Config
::Singleton();
524 'legend' => ts('Sybunt Report'),
525 'xname' => ts('Year'),
526 'yname' => ts('Amount (%1)', [1 => $config->defaultCurrency
]),
528 if ($this->_params
['charts']) {
530 CRM_Utils_Chart
::reportChart($graphRows, $this->_params
['charts'], $interval, $chartInfo);
531 $this->assign('chartType', $this->_params
['charts']);
536 * Alter display of rows.
538 * Iterate through the rows retrieved via SQL and make changes for display purposes,
539 * such as rendering contacts as links.
542 * Rows generated by SQL, with an array for each row.
544 public function alterDisplay(&$rows) {
547 foreach ($rows as $rowNum => $row) {
548 //Convert Display name into link
549 if (array_key_exists('civicrm_contact_sort_name', $row) &&
550 array_key_exists('civicrm_contribution_contact_id', $row)
552 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
553 'reset=1&force=1&id_op=eq&id_value=' .
554 $row['civicrm_contribution_contact_id'],
555 $this->_absoluteUrl
, $this->_id
, $this->_drilldownReport
557 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
558 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");
562 // convert campaign_id to campaign title
563 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
564 if ($value = $row['civicrm_contribution_campaign_id']) {
565 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->campaigns
[$value];
570 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s)') ?
TRUE : $entryFound;
571 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, NULL, 'List all contribution(s)') ?
TRUE : $entryFound;
572 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
573 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
577 // skip looking further in rows, if first row itself doesn't
578 // have the column we need
586 * Override "This Year" $op options
587 * @param string $type
588 * @param null $fieldName
592 public function getOperationPair($type = "string", $fieldName = NULL) {
593 if ($fieldName == 'yid') {
595 'calendar' => ts('Is Calendar Year'),
596 'fiscal' => ts('Fiscal Year Starting'),
599 return parent
::getOperationPair($type, $fieldName);