Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-08-19-00-06-22
[civicrm-core.git] / CRM / Report / Form / Contribute / Bookkeeping.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36 class CRM_Report_Form_Contribute_Bookkeeping extends CRM_Report_Form {
37 protected $_addressField = FALSE;
38
39 protected $_emailField = FALSE;
40
41 protected $_summary = NULL;
42
43 protected $_customGroupExtends = array(
44 'Membership');
45
46 /**
47 *
48 */
49 /**
50 *
51 */
52 function __construct() {
53 $this->_columns = array(
54 'civicrm_contact' =>
55 array(
56 'dao' => 'CRM_Contact_DAO_Contact',
57 'fields' =>
58 array(
59 'sort_name' =>
60 array('title' => ts('Contact Name'),
61 'required' => TRUE,
62 'no_repeat' => TRUE,
63 ),
64 'id' =>
65 array(
66 'no_display' => TRUE,
67 'required' => TRUE,
68 ),
69 'contact_type' =>
70 array(
71 'title' => ts('Contact Type'),
72 ),
73 'contact_sub_type' =>
74 array(
75 'title' => ts('Contact SubType'),
76 ),
77 ),
78 'filters' =>
79 array(
80 'sort_name' =>
81 array('title' => ts('Contact Name'),
82 'operator' => 'like',
83 ),
84 'id' =>
85 array('title' => ts('Contact ID'),
86 'no_display' => TRUE,
87 ),
88 ),
89 'order_bys' =>
90 array(
91 'sort_name' => array(
92 'title' => ts('Last Name, First Name'),
93 ),
94 ),
95 'grouping' => 'contact-fields',
96 ),
97 'civicrm_membership' =>
98 array(
99 'dao' => 'CRM_Member_DAO_Membership',
100 'fields' =>
101 array(
102 'id' =>
103 array('title' => ts('Membership #'),
104 'no_display' => TRUE,
105 'required' => TRUE,
106 ),
107 ),
108 ),
109 'civicrm_financial_account' => array(
110 'dao' => 'CRM_Financial_DAO_FinancialAccount',
111 'fields' => array(
112 'debit_accounting_code' => array(
113 'title' => ts('Financial Account Code - Debit'),
114 'name' => 'accounting_code',
115 'alias' => 'financial_account_civireport_debit',
116 'default' => TRUE,
117 ),
118 'credit_accounting_code' => array(
119 'title' => ts('Financial Account Code - Credit'),
120 'name' => 'accounting_code',
121 'alias' => 'financial_account_civireport_credit',
122 'default' => TRUE,
123 ),
124 'debit_name' => array(
125 'title' => ts('Financial Account Name - Debit'),
126 'name' => 'name',
127 'alias' => 'financial_account_civireport_debit',
128 'default' => TRUE,
129 ),
130 'credit_name' => array(
131 'title' => ts('Financial Account Name - Credit'),
132 'name' => 'name',
133 'alias' => 'financial_account_civireport_credit',
134 'default' => TRUE,
135 ),
136 ),
137 'filters' => array(
138 'debit_accounting_code' => array(
139 'title' => ts('Financial Account Code - Debit'),
140 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
141 'options' => CRM_Contribute_PseudoConstant::financialAccount(NULL, NULL, 'accounting_code', 'accounting_code'),
142 'name' => 'accounting_code',
143 'alias' => 'financial_account_civireport_debit',
144 ),
145 'credit_accounting_code' => array(
146 'title' => ts('Financial Account Code - Credit'),
147 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
148 'options' => CRM_Contribute_PseudoConstant::financialAccount(NULL, NULL, 'accounting_code', 'accounting_code'),
149 ),
150 'debit_name' => array(
151 'title' => ts('Financial Account Name - Debit'),
152 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
153 'options' => CRM_Contribute_PseudoConstant::financialAccount(),
154 'name' => 'id',
155 'alias' => 'financial_account_civireport_debit',
156 ),
157 'credit_name' => array(
158 'title' => ts('Financial Account Name - Credit'),
159 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
160 'options' => CRM_Contribute_PseudoConstant::financialAccount(),
161 ),
162 ),
163 ),
164 'civicrm_line_item' => array(
165 'dao' => 'CRM_Price_DAO_LineItem',
166 'fields' => array(
167 'financial_type_id' => array('title' => ts('Financial Type'),
168 'default' => TRUE,
169 ),
170 ),
171 'filters' => array(
172 'financial_type_id' => array(
173 'title' => ts('Financial Type'),
174 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
175 'options' => CRM_Contribute_PseudoConstant::financialType(),
176 ),
177 ),
178 'order_bys' => array(
179 'financial_type_id' => array('title' => ts('Financial Type')),
180 ),
181 ),
182 'civicrm_contribution' =>
183 array(
184 'dao' => 'CRM_Contribute_DAO_Contribution',
185 'fields' =>
186 array(
187 'receive_date' => array(
188 'default' => TRUE
189 ),
190 'invoice_id' => array(
191 'title' => ts('Invoice ID'),
192 'default' => TRUE,
193 ),
194 'contribution_status_id' => array('title' => ts('Contribution Status'),
195 'default' => TRUE,
196 ),
197 'id' => array('title' => ts('Contribution #'),
198 'default' => TRUE,
199 ),
200 ),
201 'filters' =>
202 array(
203 'receive_date' =>
204 array('operatorType' => CRM_Report_Form::OP_DATE),
205 'contribution_status_id' =>
206 array('title' => ts('Contribution Status'),
207 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
208 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
209 'default' => array(1),
210 ),
211 ),
212 'order_bys' => array(
213 'contribution_id' => array('title' => ts('Contribution #')),
214 'contribution_status_id' => array('title' => ts('Contribution Status')),
215 ),
216 'grouping' => 'contri-fields',
217 ),
218 'civicrm_financial_trxn' => array(
219 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
220 'fields' => array(
221 'check_number' => array(
222 'title' => ts('Cheque #'),
223 'default' => TRUE,
224 ),
225 'payment_instrument_id' => array('title' => ts('Payment Instrument'),
226 'default' => TRUE,
227 ),
228 'currency' => array(
229 'required' => TRUE,
230 'no_display' => TRUE,
231 ),
232 'trxn_date' => array(
233 'title' => ts('Transaction Date'),
234 'default' => TRUE,
235 'type' => CRM_Utils_Type::T_DATE,
236 ),
237 'trxn_id' => array(
238 'title' => ts('Trans #'),
239 'default' => TRUE,
240 ),
241 ),
242 'filters' =>
243 array(
244 'payment_instrument_id' => array(
245 'title' => ts('Payment Instrument'),
246 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
247 'options' => CRM_Contribute_PseudoConstant::paymentInstrument(),
248 ),
249 'currency' => array(
250 'title' => 'Currency',
251 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
252 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
253 'default' => NULL,
254 'type' => CRM_Utils_Type::T_STRING,
255 ),
256 'trxn_date' => array(
257 'title' => ts('Transaction Date'),
258 'operatorType' => CRM_Report_Form::OP_DATE,
259 'type' => CRM_Utils_Type::T_DATE,
260 ),
261 ),
262 'order_bys' => array(
263 'payment_instrument_id' => array('title' => ts('Payment Instrument')),
264 ),
265 ),
266 'civicrm_entity_financial_trxn' => array(
267 'dao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
268 'fields' => array(
269 'amount' => array(
270 'title' => ts('Amount'),
271 'default' => TRUE,
272 'type' => CRM_Utils_Type::T_STRING,
273 ),
274 ),
275 'filters' =>
276 array(
277 'amount' =>
278 array('title' => ts('Amount')),
279 ),
280 ),
281 'civicrm_group' =>
282 array(
283 'dao' => 'CRM_Contact_DAO_Group',
284 'alias' => 'cgroup',
285 'filters' =>
286 array(
287 'gid' =>
288 array(
289 'name' => 'group_id',
290 'title' => ts('Group'),
291 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
292 'group' => TRUE,
293 'options' => CRM_Core_PseudoConstant::group(),
294 ),
295 ),
296 ),
297 );
298
299 $this->_tagFilter = TRUE;
300 parent::__construct();
301 }
302
303 function preProcess() {
304 parent::preProcess();
305 }
306
307 function select() {
308 $select = array();
309
310 $this->_columnHeaders = array();
311 foreach ($this->_columns as $tableName => $table) {
312 if (array_key_exists('fields', $table)) {
313 foreach ($table['fields'] as $fieldName => $field) {
314 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
315 switch ($fieldName) {
316 case 'credit_accounting_code' :
317 $select[] = " CASE
318 WHEN {$this->_aliases['civicrm_financial_trxn']}.from_financial_account_id IS NOT NULL
319 THEN {$this->_aliases['civicrm_financial_account']}_credit_1.accounting_code
320 ELSE {$this->_aliases['civicrm_financial_account']}_credit_2.accounting_code
321 END AS civicrm_financial_account_credit_accounting_code ";
322 break;
323 case 'amount' :
324 $select[] = " CASE
325 WHEN {$this->_aliases['civicrm_entity_financial_trxn']}_item.entity_id IS NOT NULL
326 THEN {$this->_aliases['civicrm_entity_financial_trxn']}_item.amount
327 ELSE {$this->_aliases['civicrm_entity_financial_trxn']}.amount
328 END AS civicrm_entity_financial_trxn_amount ";
329 break;
330 case 'credit_name' :
331 $select[] = " CASE
332 WHEN {$this->_aliases['civicrm_financial_trxn']}.from_financial_account_id IS NOT NULL
333 THEN {$this->_aliases['civicrm_financial_account']}_credit_1.name
334 ELSE {$this->_aliases['civicrm_financial_account']}_credit_2.name
335 END AS civicrm_financial_account_credit_name ";
336 break;
337 default :
338 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
339 break;
340 }
341 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
342 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
343 }
344 }
345 }
346 }
347
348 $this->_select = 'SELECT ' . implode(', ', $select) . ' ';
349 }
350
351 function from() {
352 $this->_from = NULL;
353
354 $this->_from = "FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
355 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
356 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
357 {$this->_aliases['civicrm_contribution']}.is_test = 0
358 LEFT JOIN civicrm_membership_payment payment
359 ON ( {$this->_aliases['civicrm_contribution']}.id = payment.contribution_id )
360 LEFT JOIN civicrm_membership {$this->_aliases['civicrm_membership']}
361 ON payment.membership_id = {$this->_aliases['civicrm_membership']}.id
362 LEFT JOIN civicrm_entity_financial_trxn {$this->_aliases['civicrm_entity_financial_trxn']}
363 ON ({$this->_aliases['civicrm_contribution']}.id = {$this->_aliases['civicrm_entity_financial_trxn']}.entity_id AND
364 {$this->_aliases['civicrm_entity_financial_trxn']}.entity_table = 'civicrm_contribution')
365 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
366 ON {$this->_aliases['civicrm_financial_trxn']}.id = {$this->_aliases['civicrm_entity_financial_trxn']}.financial_trxn_id
367 LEFT JOIN civicrm_financial_account {$this->_aliases['civicrm_financial_account']}_debit
368 ON {$this->_aliases['civicrm_financial_trxn']}.to_financial_account_id = {$this->_aliases['civicrm_financial_account']}_debit.id
369 LEFT JOIN civicrm_financial_account {$this->_aliases['civicrm_financial_account']}_credit_1
370 ON {$this->_aliases['civicrm_financial_trxn']}.from_financial_account_id = {$this->_aliases['civicrm_financial_account']}_credit_1.id
371 LEFT JOIN civicrm_entity_financial_trxn {$this->_aliases['civicrm_entity_financial_trxn']}_item
372 ON ({$this->_aliases['civicrm_financial_trxn']}.id = {$this->_aliases['civicrm_entity_financial_trxn']}_item.financial_trxn_id AND
373 {$this->_aliases['civicrm_entity_financial_trxn']}_item.entity_table = 'civicrm_financial_item')
374 LEFT JOIN civicrm_financial_item fitem
375 ON fitem.id = {$this->_aliases['civicrm_entity_financial_trxn']}_item.entity_id
376 LEFT JOIN civicrm_financial_account {$this->_aliases['civicrm_financial_account']}_credit_2
377 ON fitem.financial_account_id = {$this->_aliases['civicrm_financial_account']}_credit_2.id
378 LEFT JOIN civicrm_line_item {$this->_aliases['civicrm_line_item']}
379 ON fitem.entity_id = {$this->_aliases['civicrm_line_item']}.id AND fitem.entity_table = 'civicrm_line_item' ";
380 }
381
382 function orderBy() {
383 parent::orderBy();
384
385 // please note this will just add the order-by columns to select query, and not display in column-headers.
386 // This is a solution to not throw fatal errors when there is a column in order-by, not present in select/display columns.
387 foreach ($this->_orderByFields as $orderBy) {
388 if (!array_key_exists($orderBy['name'], $this->_params['fields']) && empty($orderBy['section'])) {
389 $this->_select .= ", {$orderBy['dbAlias']} as {$orderBy['tplField']}";
390 }
391 }
392 }
393
394 function where() {
395 foreach ($this->_columns as $tableName => $table) {
396 if (array_key_exists('filters', $table)) {
397 foreach ($table['filters'] as $fieldName => $field) {
398 $clause = NULL;
399 if ($fieldName == 'credit_accounting_code') {
400 $field['dbAlias'] = "CASE
401 WHEN financial_trxn_civireport.from_financial_account_id IS NOT NULL
402 THEN financial_account_civireport_credit_1.accounting_code
403 ELSE financial_account_civireport_credit_2.accounting_code
404 END";
405 }
406 else if ($fieldName == 'credit_name') {
407 $field['dbAlias'] = "CASE
408 WHEN financial_trxn_civireport.from_financial_account_id IS NOT NULL
409 THEN financial_account_civireport_credit_1.id
410 ELSE financial_account_civireport_credit_2.id
411 END";
412 }
413 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
414 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
415 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
416 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
417
418 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
419 }
420 else {
421 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
422 if ($op) {
423 $clause = $this->whereClause($field,
424 $op,
425 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
426 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
427 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
428 );
429 }
430 }
431 if (!empty($clause)) {
432 $clauses[] = $clause;
433 }
434 }
435 }
436 }
437 if (empty($clauses)) {
438 $this->_where = 'WHERE ( 1 )';
439 }
440 else {
441 $this->_where = 'WHERE ' . implode(' AND ', $clauses);
442 }
443 }
444
445 function postProcess() {
446 // get the acl clauses built before we assemble the query
447 $this->buildACLClause($this->_aliases['civicrm_contact']);
448 parent::postProcess();
449 }
450
451 /**
452 * @param $rows
453 *
454 * @return array
455 */
456 function statistics(&$rows) {
457 $statistics = parent::statistics($rows);
458
459 $select = " SELECT COUNT({$this->_aliases['civicrm_financial_trxn']}.id ) as count,
460 {$this->_aliases['civicrm_contribution']}.currency,
461 SUM(CASE
462 WHEN {$this->_aliases['civicrm_entity_financial_trxn']}_item.entity_id IS NOT NULL
463 THEN {$this->_aliases['civicrm_entity_financial_trxn']}_item.amount
464 ELSE {$this->_aliases['civicrm_entity_financial_trxn']}.amount
465 END) as amount
466 ";
467
468 $sql = "{$select} {$this->_from} {$this->_where}
469 GROUP BY {$this->_aliases['civicrm_contribution']}.currency
470 ";
471
472 $dao = CRM_Core_DAO::executeQuery($sql);
473 while ($dao->fetch()) {
474 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
475 $avg[] = CRM_Utils_Money::format(round(($dao->amount / $dao->count), 2), $dao->currency);
476 }
477
478 $statistics['counts']['amount'] = array(
479 'value' => implode(', ', $amount),
480 'title' => 'Total Amount',
481 'type' => CRM_Utils_Type::T_STRING,
482 );
483 $statistics['counts']['avg'] = array(
484 'value' => implode(', ', $avg),
485 'title' => 'Average',
486 'type' => CRM_Utils_Type::T_STRING,
487 );
488 return $statistics;
489 }
490
491 /**
492 * @param $rows
493 */
494 function alterDisplay(&$rows) {
495 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
496 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
497 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
498 foreach ($rows as $rowNum => $row) {
499 // convert display name to links
500 if (array_key_exists('civicrm_contact_sort_name', $row) && !empty($rows[$rowNum]['civicrm_contact_sort_name']) &&
501 array_key_exists('civicrm_contact_id', $row)
502 ) {
503 $url = CRM_Utils_System::url('civicrm/contact/view',
504 'reset=1&cid=' . $row['civicrm_contact_id'],
505 $this->_absoluteUrl
506 );
507 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
508 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts('View Contact Summary for this Contact.');
509 }
510
511 // handle contribution status id
512 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
513 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
514 }
515
516 // handle payment instrument id
517 if ($value = CRM_Utils_Array::value('civicrm_financial_trxn_payment_instrument_id', $row)) {
518 $rows[$rowNum]['civicrm_financial_trxn_payment_instrument_id'] = $paymentInstruments[$value];
519 }
520
521 // handle financial type id
522 if ($value = CRM_Utils_Array::value('civicrm_line_item_financial_type_id', $row)) {
523 $rows[$rowNum]['civicrm_line_item_financial_type_id'] = $contributionTypes[$value];
524 }
525 if ($value = CRM_Utils_Array::value('civicrm_entity_financial_trxn_amount', $row)) {
526 $rows[$rowNum]['civicrm_entity_financial_trxn_amount'] = CRM_Utils_Money::format($rows[$rowNum]['civicrm_entity_financial_trxn_amount'],$rows[$rowNum]['civicrm_financial_trxn_currency']);
527 }
528 }
529 }
530 }
531