CRM-15603 - Fix missing space in 'World Region'
[civicrm-core.git] / CRM / Report / Form / Contribute / SoftCredit.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Contribute_SoftCredit extends CRM_Report_Form {
36
37 protected $_emailField = FALSE;
38 protected $_emailFieldCredit = FALSE;
39 protected $_phoneField = FALSE;
40 protected $_phoneFieldCredit = FALSE;
41 protected $_charts = array(
42 '' => 'Tabular',
43 'barChart' => 'Bar Chart',
44 'pieChart' => 'Pie Chart',
45 );
46 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
47
48 /**
49 *
50 */
51 /**
52 *
53 */
54 function __construct() {
55
56 // Check if CiviCampaign is a) enabled and b) has active campaigns
57 $config = CRM_Core_Config::singleton();
58 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
59 if ($campaignEnabled) {
60 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
61 $this->activeCampaigns = $getCampaigns['campaigns'];
62 asort($this->activeCampaigns);
63 }
64
65 $this->_columns = array(
66 'civicrm_contact' =>
67 array(
68 'dao' => 'CRM_Contact_DAO_Contact',
69 'fields' =>
70 array(
71 'display_name_creditor' =>
72 array('title' => ts('Soft Credit Name'),
73 'name' => 'sort_name',
74 'alias' => 'contact_civireport',
75 'required' => TRUE,
76 'no_repeat' => TRUE,
77 ),
78 'id_creditor' =>
79 array('title' => ts('Soft Credit Id'),
80 'name' => 'id',
81 'alias' => 'contact_civireport',
82 'no_display' => TRUE,
83 'required' => TRUE,
84 ),
85 'display_name_constituent' =>
86 array('title' => ts('Contributor Name'),
87 'name' => 'sort_name',
88 'alias' => 'constituentname',
89 'required' => TRUE,
90 ),
91 'id_constituent' =>
92 array('title' => ts('Const Id'),
93 'name' => 'id',
94 'alias' => 'constituentname',
95 'no_display' => TRUE,
96 'required' => TRUE,
97 ),
98 'contact_type' =>
99 array(
100 'title' => ts('Contact Type'),
101 ),
102 'contact_sub_type' =>
103 array(
104 'title' => ts('Contact SubType'),
105 ),
106 ),
107 'filters' =>
108 array(
109 'sort_name' =>
110 array(
111 'name' => 'sort_name',
112 'title' => ts('Soft Credit Name')
113 ),
114 ),
115 'grouping' => 'contact-fields',
116 ),
117 'civicrm_email' =>
118 array(
119 'dao' => 'CRM_Core_DAO_Email',
120 'fields' =>
121 array(
122 'email_creditor' =>
123 array('title' => ts('Soft Credit Email'),
124 'name' => 'email',
125 'alias' => 'emailcredit',
126 'default' => TRUE,
127 'no_repeat' => TRUE,
128 ),
129 'email_constituent' =>
130 array('title' => ts('Contributor\'s Email'),
131 'name' => 'email',
132 'alias' => 'emailconst',
133 ),
134 ),
135 'grouping' => 'contact-fields',
136 ),
137 'civicrm_phone' =>
138 array(
139 'dao' => 'CRM_Core_DAO_Phone',
140 'fields' =>
141 array(
142 'phone_creditor' =>
143 array('title' => ts('Soft Credit Phone'),
144 'name' => 'phone',
145 'alias' => 'pcredit',
146 'default' => TRUE,
147 ),
148 'phone_constituent' =>
149 array('title' => ts('Contributor\'s Phone'),
150 'name' => 'phone',
151 'alias' => 'pconst',
152 'no_repeat' => TRUE,
153 ),
154 ),
155 'grouping' => 'contact-fields',
156 ),
157 'civicrm_financial_type' =>
158 array('dao' => 'CRM_Financial_DAO_FinancialType',
159 'fields' => array('financial_type' => null,),
160 'filters' =>
161 array(
162 'id' =>
163 array(
164 'name' => 'id',
165 'title' => ts('Financial Type'),
166 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
167 'options' => CRM_Contribute_PseudoConstant::financialType()
168 ),
169 ),
170 'grouping' => 'softcredit-fields',
171 ),
172 'civicrm_contribution' =>
173 array(
174 'dao' => 'CRM_Contribute_DAO_Contribution',
175 'fields' =>
176 array(
177 'contribution_source' => NULL,
178 'currency' => array(
179 'required' => TRUE,
180 'no_display' => TRUE,
181 ),
182 'total_amount' =>
183 array('title' => ts('Amount Statistics'),
184 'default' => TRUE,
185 'statistics' =>
186 array('sum' => ts('Aggregate Amount'),
187 'count' => ts('Donations'),
188 'avg' => ts('Average'),
189 ),
190 ),
191 ),
192 'grouping' => 'softcredit-fields',
193 'filters' =>
194 array(
195 'receive_date' =>
196 array('operatorType' => CRM_Report_Form::OP_DATE),
197 'currency' =>
198 array('title' => 'Currency',
199 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
200 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
201 'default' => NULL,
202 'type' => CRM_Utils_Type::T_STRING,
203 ),
204 'contribution_status_id' =>
205 array('title' => ts('Donation Status'),
206 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
207 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
208 'default' => array(1),
209 ),
210 'total_amount' =>
211 array('title' => ts('Donation Amount'),
212 ),
213 ),
214 ),
215 'civicrm_contribution_soft' =>
216 array(
217 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
218 'fields' =>
219 array(
220 'contribution_id' =>
221 array('title' => ts('Contribution ID'),
222 'no_display' => TRUE,
223 'default' => TRUE,
224 ),
225 'id' =>
226 array(
227 'default' => TRUE,
228 'no_display' => TRUE,
229 ),
230 'soft_credit_type_id' => array('title' => ts('Soft Credit Type')),
231 ),
232 'filters' =>
233 array(
234 'soft_credit_type_id' =>
235 array('title' => 'Soft Credit Type',
236 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
237 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
238 'default' => NULL,
239 'type' => CRM_Utils_Type::T_STRING,
240 ),
241 ),
242 'grouping' => 'softcredit-fields',
243 ),
244 );
245
246 // If we have a campaign, build out the relevant elements
247 if ($campaignEnabled && !empty($this->activeCampaigns)) {
248 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
249 'title' => ts('Campaign'),
250 'default' => 'false',
251 );
252 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array('title' => ts('Campaign'),
253 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
254 'options' => $this->activeCampaigns,
255 );
256 }
257
258 $this->_groupFilter = TRUE;
259 $this->_tagFilter = TRUE;
260
261 $this->_currencyColumn = 'civicrm_contribution_currency';
262 parent::__construct();
263 }
264
265 function preProcess() {
266 parent::preProcess();
267 }
268
269 function select() {
270 $select = array();
271 $this->_columnHeaders = array();
272 foreach ($this->_columns as $tableName => $table) {
273 if (array_key_exists('fields', $table)) {
274 foreach ($table['fields'] as $fieldName => $field) {
275 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
276
277 // include email column if set
278 if ($tableName == 'civicrm_email') {
279 $this->_emailField = TRUE;
280 $this->_emailFieldCredit = TRUE;
281 }
282 elseif ($tableName == 'civicrm_email_creditor') {
283 $this->_emailFieldCredit = TRUE;
284 }
285
286 // include phone columns if set
287 if ($tableName == 'civicrm_phone') {
288 $this->_phoneField = TRUE;
289 $this->_phoneFieldCredit = TRUE;
290 }
291 elseif ($tableName == 'civicrm_phone_creditor') {
292 $this->_phoneFieldCredit = TRUE;
293 }
294
295 // only include statistics columns if set
296 if (!empty($field['statistics'])) {
297 foreach ($field['statistics'] as $stat => $label) {
298 switch (strtolower($stat)) {
299 case 'sum':
300 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
301 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
302 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
303 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
304 break;
305
306 case 'count':
307 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
308 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
309 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
310 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
311 break;
312
313 case 'avg':
314 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
315 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
316 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
317 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
318 break;
319 }
320 }
321 }
322 else {
323 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
324 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
325 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
326 }
327 }
328 }
329 }
330 }
331
332 $this->_select = 'SELECT ' . implode(', ', $select) . ' ';
333 }
334
335 /**
336 * @param $fields
337 * @param $files
338 * @param $self
339 *
340 * @return array
341 */
342 static function formRule($fields, $files, $self) {
343 $errors = $grouping = array();
344 return $errors;
345 }
346
347 function from() {
348 $alias_constituent = 'constituentname';
349 $alias_creditor = 'contact_civireport';
350 $this->_from = "
351 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
352 INNER JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
353 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id =
354 {$this->_aliases['civicrm_contribution']}.id
355 INNER JOIN civicrm_contact {$alias_constituent}
356 ON {$this->_aliases['civicrm_contribution']}.contact_id =
357 {$alias_constituent}.id
358 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
359 ON {$this->_aliases['civicrm_contribution']}.financial_type_id =
360 {$this->_aliases['civicrm_financial_type']}.id
361 LEFT JOIN civicrm_contact {$alias_creditor}
362 ON {$this->_aliases['civicrm_contribution_soft']}.contact_id =
363 {$alias_creditor}.id
364 {$this->_aclFrom} ";
365
366 // include Constituent email field if email column is to be included
367 if ($this->_emailField) {
368 $alias = 'emailconst';
369 $this->_from .= "
370 LEFT JOIN civicrm_email {$alias}
371 ON {$alias_constituent}.id =
372 {$alias}.contact_id AND
373 {$alias}.is_primary = 1\n";
374 }
375
376 // include Creditors email field if email column is to be included
377 if ($this->_emailFieldCredit) {
378 $alias = 'emailcredit';
379 $this->_from .= "
380 LEFT JOIN civicrm_email {$alias}
381 ON {$alias_creditor}.id =
382 {$alias}.contact_id AND
383 {$alias}.is_primary = 1\n";
384 }
385
386 // include Constituents phone field if email column is to be included
387 if ($this->_phoneField) {
388 $alias = 'pconst';
389 $this->_from .= "
390 LEFT JOIN civicrm_phone {$alias}
391 ON {$alias_constituent}.id =
392 {$alias}.contact_id AND
393 {$alias}.is_primary = 1\n";
394 }
395
396 // include Creditors phone field if email column is to be included
397 if ($this->_phoneFieldCredit) {
398 $alias = 'pcredit';
399 $this->_from .= "
400 LEFT JOIN civicrm_phone pcredit
401 ON {$alias_creditor}.id =
402 {$alias}.contact_id AND
403 {$alias}.is_primary = 1\n";
404 }
405 }
406
407 function groupBy() {
408 $this->_rollup = 'WITH ROLLUP';
409 $this->_groupBy = "
410 GROUP BY {$this->_aliases['civicrm_contribution_soft']}.contact_id, constituentname.id {$this->_rollup}";
411 }
412
413 function where() {
414 parent::where();
415 $this->_where .= " AND {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
416 }
417
418 /**
419 * @param $rows
420 *
421 * @return array
422 */
423 function statistics(&$rows) {
424 $statistics = parent::statistics($rows);
425
426 $select = "
427 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
428 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
429 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg,
430 {$this->_aliases['civicrm_contribution']}.currency as currency
431 ";
432
433 $sql = "{$select} {$this->_from} {$this->_where}
434 GROUP BY {$this->_aliases['civicrm_contribution']}.currency
435 ";
436
437 $dao = CRM_Core_DAO::executeQuery($sql);
438 $count = 0;
439 $totalAmount = $average = array();
440 while ($dao->fetch()) {
441 $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency).'('.$dao->count.')';
442 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
443 $count += $dao->count;
444 }
445 $statistics['counts']['amount'] = array(
446 'title' => ts('Total Amount'),
447 'value' => implode(', ', $totalAmount),
448 'type' => CRM_Utils_Type::T_STRING,
449 );
450 $statistics['counts']['count'] = array(
451 'title' => ts('Total Donations'),
452 'value' => $count,
453 );
454 $statistics['counts']['avg'] = array(
455 'title' => ts('Average'),
456 'value' => implode(', ', $average),
457 'type' => CRM_Utils_Type::T_STRING,
458 );
459
460 return $statistics;
461 }
462
463 function postProcess() {
464 $this->beginPostProcess();
465
466 $this->buildACLClause(array('constituentname', 'contact_civireport'));
467 $sql = $this->buildQuery();
468
469 $dao = CRM_Core_DAO::executeQuery($sql);
470 $rows = $graphRows = array();
471 $count = 0;
472 while ($dao->fetch()) {
473 $row = array();
474 foreach ($this->_columnHeaders as $key => $value) {
475 $row[$key] = $dao->$key;
476 }
477 $rows[] = $row;
478 }
479 $this->formatDisplay($rows);
480
481 // to hide the contact ID field from getting displayed
482 unset($this->_columnHeaders['civicrm_contact_id_constituent']);
483 unset($this->_columnHeaders['civicrm_contact_id_creditor']);
484
485 // assign variables to templates
486 $this->doTemplateAssignment($rows);
487 $this->endPostProcess($rows);
488 }
489
490 /**
491 * @param $rows
492 */
493 function alterDisplay(&$rows) {
494 // custom code to alter rows
495
496 $entryFound = FALSE;
497 $dispname_flag = $phone_flag = $email_flag = 0;
498 $prev_email = $prev_dispname = $prev_phone = NULL;
499
500 foreach ($rows as $rowNum => $row) {
501 // Link constituent (contributor) to contribution detail
502 if (array_key_exists('civicrm_contact_display_name_constituent', $row) &&
503 array_key_exists('civicrm_contact_id_constituent', $row)
504 ) {
505
506 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
507 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id_constituent'],
508 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
509 );
510 $rows[$rowNum]['civicrm_contact_display_name_constituent_link'] = $url;
511 $rows[$rowNum]['civicrm_contact_display_name_constituent_hover'] = ts('List all direct contribution(s) from this contact.');
512 $entryFound = TRUE;
513 }
514
515 // convert soft credit contact name to link
516 if (array_key_exists('civicrm_contact_display_name_creditor', $row) && !empty($rows[$rowNum]['civicrm_contact_display_name_creditor']) &&
517 array_key_exists('civicrm_contact_id_creditor', $row)
518 ) {
519 $url = CRM_Utils_System::url("civicrm/contact/view",
520 'reset=1&cid=' . $row['civicrm_contact_id_creditor'],
521 $this->_absoluteUrl
522 );
523 $rows[$rowNum]['civicrm_contact_display_name_creditor_link'] = $url;
524 $rows[$rowNum]['civicrm_contact_display_name_creditor_hover'] = ts("view contact summary");
525 }
526
527 // make subtotals look nicer
528 if (array_key_exists('civicrm_contact_id_constituent', $row) &&
529 !$row['civicrm_contact_id_constituent']
530 ) {
531 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
532 $entryFound = TRUE;
533 }
534
535 // convert campaign_id to campaign title
536 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
537 if ($value = $row['civicrm_contribution_campaign_id']) {
538 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
539 $entryFound = TRUE;
540 }
541 }
542
543 //convert soft_credit_type_id into label
544 if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) {
545 $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_OptionGroup::getLabel('soft_credit_type',
546 $row['civicrm_contribution_soft_soft_credit_type_id']);
547 }
548
549 // skip looking further in rows, if first row itself doesn't
550 // have the column we need
551 if (!$entryFound) {
552 break;
553 }
554 }
555
556 $this->removeDuplicates($rows);
557 }
558 }
559