Sybunt.php 11.2 KB
Newer Older
bgm's avatar
bgm committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<?php

/*
 +--------------------------------------------------------------------+
 | CiviCRM version 3.2                                                |
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2010                                |
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
*/

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2010
 * $Id$
 *
 */
class CRM_Extendedreport_Form_Report_Pledge_Sybunt extends CRM_Extendedreport_Form_Report_ExtendedReport {
  protected $_add2groupSupported = FALSE;
  protected $_customGroupExtends = array(
    'Pledge'
  );

  /**
   *
   */
  public function __construct() {
    $yearsInPast = 8;
    $yearsInFuture = 2;
Mathieu Lutfy's avatar
Mathieu Lutfy committed
48
    $optionYear = NULL;
bgm's avatar
bgm committed
49 50 51 52 53 54 55
    $date = CRM_Core_SelectValues::date('custom', NULL, $yearsInPast, $yearsInFuture);
    $count = $date['maxYear'];
    while ($date['minYear'] <= $count) {
      $optionYear[$date['minYear']] = $date['minYear'];
      $date['minYear']++;
    }

Mathieu Lutfy's avatar
Mathieu Lutfy committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    $this->_columns = $this->getColumns('Contact')
      + $this->getColumns('Email')
      + $this->getColumns('Phone')
      + $this->getColumns('Pledge');

      $this->_columns['civicrm_pledge']['filters']['yid'] =
      $this->_columns['civicrm_pledge']['metadata']['yid'] = [
      'name' => 'start_date',
      'title' => ts('This Year'),
      'operatorType' => CRM_Report_Form::OP_SELECT,
      'type'    => CRM_Utils_Type::T_INT,
      'options' => $optionYear,
      'default' => date('Y'),
      'is_filters' => TRUE,
      'is_join_filters' => TRUE,
71 72
      'is_aggregate_columns' => FALSE,
      'is_aggregate_rows' => FALSE,
Mathieu Lutfy's avatar
Mathieu Lutfy committed
73 74 75 76 77 78
      'is_fields' => FALSE,
      'is_group_bys' => FALSE,
      'is_order_bys' => FALSE,
    ];

    $this->_groupFilter = TRUE;
bgm's avatar
bgm committed
79 80
    $this->_tagFilter = TRUE;
    parent::__construct();
Mathieu Lutfy's avatar
Mathieu Lutfy committed
81
    CRM_Core_DAO::disableFullGroupByMode();
bgm's avatar
bgm committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  }

  function select() {
    $select = array();
    $this->_columnHeaders = array();
    $current_year = $this->_params['yid_value'];
    $previous_year = $current_year - 1;
    $previous_pyear = $current_year - 2;
    $previous_ppyear = $current_year - 3;
    $upTo_year = $current_year - 4;

    foreach ($this->_columns as $tableName => $table) {
      if (array_key_exists('fields', $table)) {
        foreach ($table['fields'] as $fieldName => $field) {

          if (CRM_Utils_Array::value('required', $field) || CRM_Utils_Array::value($fieldName, $this->_params['fields'])) {
            if ($fieldName == 'amount') {
              $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";

              $this->_columnHeaders["civicrm_upto_{$upTo_year}"]['type'] = $field['type'];
              $this->_columnHeaders["civicrm_upto_{$upTo_year}"]['title'] = "Up To $upTo_year";

              $this->_columnHeaders["{$previous_ppyear}"]['type'] = $field['type'];
              $this->_columnHeaders["{$previous_ppyear}"]['title'] = $previous_ppyear;

              $this->_columnHeaders["{$previous_pyear}"]['type'] = $field['type'];
              $this->_columnHeaders["{$previous_pyear}"]['title'] = $previous_pyear;

              $this->_columnHeaders["{$previous_year}"]['type'] = $field['type'];
              $this->_columnHeaders["{$previous_year}"]['title'] = $previous_year;

              $this->_columnHeaders["civicrm_life_time_total"]['type'] = $field['type'];
              $this->_columnHeaders["civicrm_life_time_total"]['title'] = 'LifeTime';;
            }
            else {
              if ($fieldName == 'start_date') {
                $select[] = "Year({$field['dbAlias']} ) as {$tableName}_{$fieldName}";
              }
              else {
                $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
                $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
                $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
              }
            }
            if (CRM_Utils_Array::value('no_display', $field)) {
              $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
            }
          }
        }
      }
    }
133
    $this->_selectClauses = $select;
bgm's avatar
bgm committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    $this->_select = "SELECT " . implode(', ', $select) . " ";
  }

  function from() {
    $this->_from = "
        FROM  civicrm_pledge  {$this->_aliases['civicrm_pledge']}
             INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
                         ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_pledge']}.contact_id
             {$this->_aclFrom}
             LEFT  JOIN civicrm_email  {$this->_aliases['civicrm_email']}
                         ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
                         AND {$this->_aliases['civicrm_email']}.is_primary = 1
             LEFT  JOIN civicrm_phone  {$this->_aliases['civicrm_phone']}
                         ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
                            {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
  }

  /**
   * Specific where clause override.
   *
   * @param array $field
   * @param string $op
   * @param mixed $value
   * @param float $min
   * @param float $max
   *
   * @return string
   */
  public function whereClause(&$field, $op, $value, $min, $max) {
    if ($field['name'] == 'start_date') {
      $value = CRM_Utils_Type::escape($value, 'Int');
      return "
Mathieu Lutfy's avatar
Mathieu Lutfy committed
166
        {$this->_aliases['civicrm_pledge']}.contact_id NOT IN (
bgm's avatar
bgm committed
167 168 169 170 171 172
          SELECT distinct pledge.contact_id
          FROM civicrm_pledge pledge
          WHERE YEAR(pledge.start_date) = $value
          AND pledge.is_test = 0
        )";
    }
Mathieu Lutfy's avatar
Mathieu Lutfy committed
173
    return parent::whereClause($field, $op, $value, $min, $max);
bgm's avatar
bgm committed
174 175 176
  }

  function groupBy() {
177 178
    $this->_groupByArray = array($this->_aliases['civicrm_pledge'] . '.contact_id');
    $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $this->_groupByArray) . ", Year({$this->_aliases['civicrm_pledge']}.start_date) WITH ROLLUP ";
bgm's avatar
bgm committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  }

  /**
   * @param $rows
   *
   * @return mixed
   */
  function statistics(&$rows) {
    $statistics = parent::statistics($rows);

    if (!empty($rows)) {
      $select = "
                   SELECT
                        SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount ";

      $sql = "{$select} {$this->_from } {$this->_where}";
      $dao = CRM_Core_DAO::executeQuery($sql);
      if ($dao->fetch()) {
        $statistics['counts']['amount'] = array(
          'value' => $dao->amount,
          'title' => 'Total LifeTime',
          'type' => CRM_Utils_Type::T_MONEY
        );
      }
    }
    return $statistics;
  }

  function postProcess() {
    // get ready with post process params
    $this->beginPostProcess();

    $this->buildACLClause($this->_aliases['civicrm_contact']);
    $this->select();
    $this->from();
    $this->extendedCustomDataFrom();
    $this->where();
    $this->groupBy();

    $rows = $contactIds = array();
    if (!CRM_Utils_Array::value('charts', $this->_params)) {
      $this->limit();
      $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}";

      $dao = CRM_Core_DAO::executeQuery($getContacts);

      while ($dao->fetch()) {
        $contactIds[] = $dao->cid;
      }
      $this->setPager();
    }

    if (!empty($contactIds) || CRM_Utils_Array::value('charts', $this->_params)) {
      if (CRM_Utils_Array::value('charts', $this->_params)) {
        $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy}";
      }
      else {
        $sql = "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" . implode(',', $contactIds) . ") AND {$this->_aliases['civicrm_pledge']}.is_test = 0 {$this->_groupBy} ";
      }

      $current_year = $this->_params['yid_value'];
      $upTo_year = $current_year - 4;

      $rows = $row = array();
      $dao = CRM_Core_DAO::executeQuery($sql);
      $contributionSum = 0;
Mathieu Lutfy's avatar
Mathieu Lutfy committed
245

bgm's avatar
bgm committed
246
      while ($dao->fetch()) {
Mathieu Lutfy's avatar
Mathieu Lutfy committed
247
        if (!$dao->civicrm_pledge_pledge_contact_id) {
bgm's avatar
bgm committed
248 249 250 251
          continue;
        }
        foreach ($this->_columnHeaders as $key => $value) {
          if (property_exists($dao, $key)) {
Mathieu Lutfy's avatar
Mathieu Lutfy committed
252
            $rows[$dao->civicrm_pledge_pledge_contact_id][$key] = $dao->$key;
bgm's avatar
bgm committed
253 254
          }
        }
Mathieu Lutfy's avatar
Mathieu Lutfy committed
255 256
        if ($dao->civicrm_pledge_pledge_start_date) {
          if ($dao->civicrm_pledge_pledge_start_date > $upTo_year) {
bgm's avatar
bgm committed
257
            $contributionSum += $dao->civicrm_pledge_amount;
Mathieu Lutfy's avatar
Mathieu Lutfy committed
258
            $rows[$dao->civicrm_pledge_pledge_contact_id][$dao->civicrm_pledge_pledge_start_date] = $dao->civicrm_pledge_amount;
bgm's avatar
bgm committed
259 260 261
          }
        }
        else {
Mathieu Lutfy's avatar
Mathieu Lutfy committed
262
          $rows[$dao->civicrm_pledge_pledge_contact_id]['civicrm_life_time_total'] = $dao->civicrm_pledge_amount;
bgm's avatar
bgm committed
263
          if (($dao->civicrm_pledge_amount - $contributionSum) > 0) {
Mathieu Lutfy's avatar
Mathieu Lutfy committed
264
            $rows[$dao->civicrm_pledge_pledge_contact_id]["civicrm_upto_{$upTo_year}"] = $dao->civicrm_pledge_amount - $contributionSum;
bgm's avatar
bgm committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
          }
          $contributionSum = 0;
        }
      }
    }
    // format result set.
    $this->formatDisplay($rows, FALSE);

    // assign variables to templates
    $this->doTemplateAssignment($rows);

    // do print / pdf / instance stuff if needed
    $this->endPostProcess($rows);
  }

  /**
   * @param $rows
   */
  function alterDisplay(&$rows) {
    foreach ($rows as $rowNum => $row) {
      //Convert Display name into link
      if (array_key_exists('civicrm_contact_display_name', $row) && array_key_exists('civicrm_pledge_contact_id', $row)) {
        $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_pledge_contact_id'], $this->_absoluteUrl);
        $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
        $rows[$rowNum]['civicrm_contact_display_name_hover'] = ts("View Contribution Details for this Contact.");
      }
    }
  }
}