GrantPayment.php 15.2 KB
Newer Older
1 2 3 4
<?php

/*
 +--------------------------------------------------------------------+
5
 | CiviCRM version 4.4                                                |
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
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2011                                |
 +--------------------------------------------------------------------+
 | 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-2011
 * $Id$
 *
 */


38
class CRM_Grant_BAO_GrantPayment extends CRM_Grant_DAO_GrantPayment {
39 40 41
  const
    STOP = 1,
    REPRINT = 2;
42 43 44 45 46
  /**
   * static field for all the grant information that we can potentially export
   * @var array
   * @static
   */
47
  static $_exportableFields = NULL;
48 49 50 51

  /**
   * class constructor
   */
52 53
  function __construct() {
    parent::__construct();
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
  }

  /**
   * Takes a bunch of params that are needed to match certain criteria and
   * retrieves the relevant objects. Typically the valid params are only
   * contact_id. We'll tweak this function to be more full featured over a period
   * of time. This is the inverse function of create. It also stores all the retrieved
   * values in the default array
   *
   * @param array $params   (reference ) an assoc array of name/value pairs
   * @param array $defaults (reference ) an assoc array to hold the flattened values
   *
   * @return object CRM_Grant_BAO_ManageGrant object
   * @access public
   * @static
   */
70 71 72 73 74
  static function retrieve(&$params, &$defaults) {
    $grantPayment = new CRM_Grant_DAO_GrantPayment();
    $grantPayment->copyValues($params);
    if ($grantPayment->find(TRUE)) {
      CRM_Core_DAO::storeValues($grantPayment, $defaults);
75 76
      return $grantPayment;
    }
77
    return NULL;
78
  }
79

80 81 82 83
  function &exportableFields() {
    if (!self::$_exportableFields) {
      if (!self::$_exportableFields) {
        self::$_exportableFields = array();
84
      }
85 86 87

      $grantFields = array(
        'id' => array(
88 89
          'title' => 'Payment ID',
          'name' => 'id',
90
          'data_type' => CRM_Utils_Type::T_INT
91
        ),
92
        'payment_batch_number' => array(
93 94
          'title' => 'Payment Batch Nnumber',
          'name' => 'payment_batch_number',
95
          'data_type' => CRM_Utils_Type::T_INT
96
        ),
97
        'payment_number' => array(
98
          'title' => 'Check Number',
99
          'name' => 'payment_number',
100
          'data_type' => CRM_Utils_Type::T_INT
101
        ),
102
        'financial_type_id' => array(
103 104
          'title' => 'Financial Type ID',
          'name' => 'financial_type_id',
105
          'data_type' => CRM_Utils_Type::T_INT
106
        ),
107
        'contact_id' => array(
108 109
          'title' => 'Contact ID',
          'name' => 'contact_id',
110
          'data_type' => CRM_Utils_Type::T_INT
111
        ),
112
        'payment_created_date' => array(
113 114
          'title' => 'Payment Created Date',
          'name' => 'payment_created_date',
115
          'data_type' => CRM_Utils_Type::T_DATE
116
        ),
117
        'payment_date' => array(
118 119
          'title' => 'Payment Date',
          'name' => 'payment_date',
120
          'data_type' => CRM_Utils_Type::T_DATE
121 122 123 124
        ),
        'payable_to_name' => array(
          'title' => 'Payable To Name',
          'name' => 'payable_to_name',
125
          'data_type' => CRM_Utils_Type::T_STRING
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
        ),
        'payable_to_address' => array(
          'title' => 'Payable To Address',
          'name' => 'payable_to_address',
          'data_type' => CRM_Utils_Type::T_STRING
        ),
        'amount' => array(
          'title' => 'Amount',
          'name' => 'amount',
          'data_type' => CRM_Utils_Type::T_MONEY
        ),
        'currency' => array(
          'title' => 'Currency',
          'name' => 'currency',
          'data_type' => CRM_Utils_Type::T_STRING
        ),
        'payment_reason' => array(
          'title' => 'Payment Reason',
          'name' => 'payment_reason',
          'data_type' => CRM_Utils_Type::T_STRING
        ),
        'payment_status_id' => array(
          'title' => 'Payment Status ID',
          'name' => 'payment_status_id',
          'data_type' => CRM_Utils_Type::T_STRING
        ),
        'replaces_payment_id' => array(
          'title' => 'Payment Reason',
          'name' => 'replaces_payment_id',
          'data_type' => CRM_Utils_Type::T_STRING
        )
      );
158

159 160
      $fields = CRM_Grant_DAO_GrantPayment::export();
      self::$_exportableFields = $fields;
161
    }
162 163 164
    return self::$_exportableFields;
  }

165 166 167 168 169
  /**
   * function to add grant
   *
   * @param array $params reference array contains the values submitted by the form
   * @param array $ids    reference array contains the id
170
   *
171
   * @access public
172
   * @static
173
   * @return object
174
   */
175
  static function add(&$params, &$ids = []) {
176
    if (empty($params)) {
177 178
      return;
    }
179

180
    if (isset($params['total_amount'])) {
181
      $params[$field] = CRM_Utils_Rule::cleanMoney($params['total_amount']);
182 183
    }
    // convert dates to mysql format
184 185
    if (isset($params['payment_created_date'])) {
      $params['payment_created_date'] = CRM_Utils_Date::processDate($params['payment_created_date'], NULL, TRUE);
186
    }
187

188 189
    $grantPayment = new CRM_Grant_DAO_GrantPayment();
    $grantPayment->id = CRM_Utils_Array::value('id', $ids);
190

191 192
    $grantPayment->copyValues($params);
    return $grantPayment->save();
193 194
  }

195 196

  static function del($id) {
197
    CRM_Utils_Hook::pre('delete', 'GrantPayment', $id, CRM_Core_DAO::$_nullArray);
198

199
    $grantPayment = new CRM_Grant_DAO_GrantPayment();
200
    $grantPayment->id = $id;
201 202 203 204 205

    $grantPayment->find();

    // delete the recently created Grant
    $grantPaymentRecent = array(
206 207 208 209
      'id'   => $id,
      'type' => 'GrantPayment'
    );
    CRM_Utils_Recent::del($grantPaymentRecent);
210

211
    if ($grantPayment->fetch()) {
212
      $results = $grantPayment->delete();
213
      CRM_Utils_Hook::post('delete', 'GrantPayment', $grantPayment->id, $grantPayment);
214 215
      return $results;
    }
216
    return FALSE;
217
  }
218

219
  static function getMaxPayementBatchNumber() {
Mayur Jadhav's avatar
Mayur Jadhav committed
220
    $query = "SELECT MAX(payment_number) as payment_number, MAX(payment_batch_number) as payment_batch_number FROM civicrm_payment";
221 222
    $dao = CRM_Core_DAO::executeQuery($query);
    while($dao->fetch()) {
223 224 225 226 227
      $grantPrograms['payment_number'] = $dao->payment_number;
      $grantPrograms['payment_batch_number'] = $dao->payment_batch_number;
    }
    return $grantPrograms;
  }
228

229
  static function getPaymentNumber($id) {
Mayur Jadhav's avatar
Mayur Jadhav committed
230
    $query = "SELECT id FROM civicrm_payment WHERE payment_number = {$id}";
231
    return CRM_Core_DAO::singleValueQuery($query);
232
  }
233

234
  static function getPaymentBatchNumber($id) {
Mayur Jadhav's avatar
Mayur Jadhav committed
235
    $query = "SELECT id FROM civicrm_payment WHERE payment_batch_number = {$id}";
236
    return CRM_Core_DAO::singleValueQuery($query);
237
  }
238

239
  static function makeReport($fileName, $rows) {
240 241 242 243 244 245 246 247
    $config = CRM_Core_Config::singleton();
    $pdf_filename = $config->customFileUploadDir . $fileName;
    $query = "SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template WHERE msg_title = 'Grant Payment Report'";
    $dao = CRM_Core_DAO::executeQuery($query);
    $dao->fetch();
    if (!$dao->N) {
      if ($params['messageTemplateID']) {
        CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
248
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
249
      else {
250 251 252 253 254
        CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName'])));
      }
    }

    $subject = $dao->subject;
255 256 257 258
    $text = $dao->text;
    $html = $dao->html;
    $format = $dao->format;
    $dao->free();
259

260 261 262
    civicrm_smarty_register_string_resource();
    $smarty = CRM_Core_Smarty::singleton();
    foreach(array('text', 'html') as $elem) {
263 264
      $$elem = $smarty->fetch("string:{$$elem}");
    }
265 266
    $output = file_put_contents($pdf_filename,
      CRM_Utils_PDF_Utils::html2pdf(
267 268 269 270 271 272
        $html,
        $fileName,
        true,
        'Letter'
      )
    );
273 274
    return $fileName;
  }
275

276
  static function createCSV($filename, $grantPayment) {
277 278 279 280 281 282 283 284 285 286 287 288 289 290

    $headers[] = array (
      'Contact Id',
      'Financial Type',
      'Batch Number',
      'Payment Number',
      'Payment Date',
      'Payment Created Date',
      'Payable To Name',
      'Payable To Address',
      'Amount',
      'Currency',
      'Payment Reason',
      'Payment Replaces Id',
291
    );
292

293
    $rows = array_merge($headers, $grantPayment);
294
    $fp = fopen($filename, "w");
Mayur Jadhav's avatar
Mayur Jadhav committed
295
    $line = '';
296 297
    $comma = "";
    $contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes();
298
    foreach ($rows as $value) {
299 300
      if (isset($value['financial_type_id'])) {
        $value['financial_type_id'] = $contributionTypes[$value['financial_type_id']];
301
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
302
      $line .= '"'.implode('","', $value).'"';
303 304 305 306 307
      $line .= "\n";
    }
    fputs($fp, $line);
    fclose($fp);
  }
308

309
  static function makePDF($fileName, $rows) {
310 311
    $config = CRM_Core_Config::singleton();
    $pdf_filename = $config->customFileUploadDir . $fileName;
Edselopez's avatar
Edselopez committed
312
    $query = "SELECT msg_subject subject, msg_html html, msg_text text, pdf_format_id format
313
              FROM civicrm_msg_template
Mayur Jadhav's avatar
Mayur Jadhav committed
314
              WHERE msg_title = 'Grant Payment Check' AND is_default = 1;";
315 316
    $grantDao = CRM_Core_DAO::executeQuery($query);
    $grantDao->fetch();
317

318
    if (!$grantDao->N) {
319
      CRM_Core_Error::fatal(ts('No such message template.'));
320 321
    }
    $subject = $grantDao->subject;
322
    $html = $grantDao->html;
Mayur Jadhav's avatar
Mayur Jadhav committed
323 324 325
    $text = $grantDao->text;
    $format = $grantDao->format;
    $grantDao->free();
326

Mayur Jadhav's avatar
Mayur Jadhav committed
327 328 329 330
    civicrm_smarty_register_string_resource();
    $smarty = CRM_Core_Smarty::singleton();
    foreach(array('text', 'html') as $elem) {
      $$elem = $smarty->fetch("string:{$$elem}");
331
    }
332 333 334 335

    $output = file_put_contents(
      $pdf_filename,
      CRM_Utils_PDF_Utils::html2pdf(
Mayur Jadhav's avatar
Mayur Jadhav committed
336
        $html,
337 338 339 340 341
        $fileName,
        TRUE,
        'Letter'
      )
    );
342 343
    return $fileName;
  }
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

  /**
   * Function to get events Summary
   *
   * @static
   *
   * @return array Array of event summary values
   */
  static function getGrantSummary($admin = FALSE) {
    $query = "SELECT
      p.id,
      p.label,
      g.status_id,
      count(g.id) AS status_total,
      sum(g.amount_total) AS amount_requested,
      sum(g.amount_granted) AS amount_granted,
      sum(cp.amount) AS total_paid,
      sum(g.amount_granted)/count(g.id) AS average_amount
      FROM civicrm_grant_program p
      LEFT JOIN civicrm_grant g ON g.grant_program_id = p.id
      LEFT JOIN civicrm_entity_payment ep ON ep.entity_id = g.id AND ep.entity_table = 'civicrm_grant'
      LEFT JOIN civicrm_payment cp ON cp.id = ep.payment_id
      WHERE g.status_id IS NOT NULL
      GROUP BY g.grant_program_id, g.status_id WITH ROLLUP";

    $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);

    $status = array( );
    $summary = array( );
    $summary['total_grants'] = $programs = NULL;
    $summary['no_of_grants'] = NULL;
    $querys = "SELECT
      v.label as label,
      v.weight as value,
      v.value as info
      FROM civicrm_option_value v, civicrm_option_group g
      WHERE  v.option_group_id = g.id
      AND  g.name = 'grant_status'
      AND  g.is_active = 1
      ORDER BY v.weight";
    $daos = CRM_Core_DAO::executeQuery($querys, CRM_Core_DAO::$_nullArray);
    while ($daos->fetch()) {
      $status[$daos->value] = array(
        'weight' => $daos->value,
        'value' => $daos->info,
        'label' => $daos->label,
        'total' => 0,
      );
    }
    foreach ($status as $id => $name) {
      $stats[$status[$id]['value']] = array(
        'label' => $name['label'],
        'value' => $name['value'],
        'weight' => $name['weight'],
        'total' => 0
      );
    }
    $count = 1;
    while ($dao->fetch()) {
      if ($dao->N == $count) {
        $summary['total_grants']['total_requested'] = $dao->amount_requested ? CRM_Utils_Money::format($dao->amount_requested) : CRM_Utils_Money::format(0);
        $summary['total_grants']['total_granted'] = $dao->amount_granted ? CRM_Utils_Money::format($dao->amount_granted) : CRM_Utils_Money::format(0);
        $summary['total_grants']['total_paid'] = $dao->total_paid ? CRM_Utils_Money::format($dao->total_paid) : CRM_Utils_Money::format(0);
        $summary['total_grants']['total_average'] = $dao->average_amount ? CRM_Utils_Money::format($dao->average_amount) : CRM_Utils_Money::format(0);
        continue;
      }
      if (!empty($dao->status_id)) {
        $programs[$dao->label][$stats[$dao->status_id]['weight']] = array(
          'label' => $stats[$dao->status_id]['label'],
          'total' => $dao->status_total,
          'value' => $stats[$dao->status_id]['value'],
          'amount_requested' => $dao->amount_requested ? CRM_Utils_Money::format($dao->amount_requested) : CRM_Utils_Money::format(0),
          'amount_granted' => $dao->amount_granted ? CRM_Utils_Money::format($dao->amount_granted) : CRM_Utils_Money::format(0),
          'total_paid' => $dao->total_paid ? CRM_Utils_Money::format($dao->total_paid) : CRM_Utils_Money::format(0),
          'average_amount' => $dao->average_amount ? CRM_Utils_Money::format($dao->average_amount) : CRM_Utils_Money::format(0),
          'pid' => $dao->id,
        );
        $programs[$dao->label] = $programs[$dao->label] + array_diff_key($status, $programs[$dao->label]); //add the two arrays
        ksort($programs[$dao->label]);
        $summary['total_grants']['all'] = 'All';
        $summary['no_of_grants'] += $dao->status_total;
      }
      else {
        $programs["<b>Subtotal $dao->label </b>"]['subtotal'] = array(
          'label' => '',
          'total' => $dao->status_total,
          'amount_requested' => $dao->amount_requested ? CRM_Utils_Money::format($dao->amount_requested) : CRM_Utils_Money::format(0),
          'amount_granted' => $dao->amount_granted ? CRM_Utils_Money::format($dao->amount_granted) : CRM_Utils_Money::format(0),
          'total_paid' => $dao->total_paid ? CRM_Utils_Money::format($dao->total_paid) : CRM_Utils_Money::format(0),
          'average_amount' => $dao->average_amount ? CRM_Utils_Money::format($dao->average_amount) : CRM_Utils_Money::format(0),
        );
      }
      $count++;
    }
    $summary['per_status'] = $programs;
    return $summary;
  }

}