Merge pull request #7190 from galgeek/patch-1
[civicrm-core.git] / CRM / Pledge / BAO / Pledge.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 */
33class CRM_Pledge_BAO_Pledge extends CRM_Pledge_DAO_Pledge {
34
35 /**
fe482240 36 * Static field for all the pledge information that we can potentially export.
6a488035
TO
37 *
38 * @var array
6a488035
TO
39 */
40 static $_exportableFields = NULL;
41
42 /**
fe482240 43 * Class constructor.
6a488035 44 */
00be9182 45 public function __construct() {
6a488035
TO
46 parent::__construct();
47 }
48
49 /**
fe482240
EM
50 * Retrieve DB object based on input parameters.
51 *
52 * It also stores all the retrieved values in the default array.
6a488035 53 *
3a1617b6
TO
54 * @param array $params
55 * (reference ) an assoc array of name/value pairs.
56 * @param array $defaults
57 * (reference ) an assoc array to hold the flattened values.
6a488035 58 *
16b10e64 59 * @return CRM_Pledge_BAO_Pledge
6a488035 60 */
00be9182 61 public static function retrieve(&$params, &$defaults) {
6a488035
TO
62 $pledge = new CRM_Pledge_DAO_Pledge();
63 $pledge->copyValues($params);
64 if ($pledge->find(TRUE)) {
65 CRM_Core_DAO::storeValues($pledge, $defaults);
66 return $pledge;
67 }
68 return NULL;
69 }
70
71 /**
fe482240 72 * Add pledge.
6a488035 73 *
3a1617b6
TO
74 * @param array $params
75 * Reference array contains the values submitted by the form.
6a488035 76 *
6a488035
TO
77 *
78 * @return object
79 */
00be9182 80 public static function add(&$params) {
a7488080 81 if (!empty($params['id'])) {
6a488035
TO
82 CRM_Utils_Hook::pre('edit', 'Pledge', $params['id'], $params);
83 }
84 else {
85 CRM_Utils_Hook::pre('create', 'Pledge', NULL, $params);
86 }
87
88 $pledge = new CRM_Pledge_DAO_Pledge();
89
90 // if pledge is complete update end date as current date
91 if ($pledge->status_id == 1) {
92 $pledge->end_date = date('Ymd');
93 }
94
95 $pledge->copyValues($params);
96
97 // set currency for CRM-1496
98 if (!isset($pledge->currency)) {
bb06e9ed 99 $pledge->currency = CRM_Core_Config::singleton()->defaultCurrency;
6a488035
TO
100 }
101
102 $result = $pledge->save();
103
a7488080 104 if (!empty($params['id'])) {
6a488035
TO
105 CRM_Utils_Hook::post('edit', 'Pledge', $pledge->id, $pledge);
106 }
107 else {
108 CRM_Utils_Hook::post('create', 'Pledge', $pledge->id, $pledge);
109 }
110
111 return $result;
112 }
113
114 /**
115 * Given the list of params in the params array, fetch the object
116 * and store the values in the values array
117 *
3a1617b6
TO
118 * @param array $params
119 * Input parameters to find object.
120 * @param array $values
121 * Output values of the object.
122 * @param array $returnProperties
123 * If you want to return specific fields.
6a488035 124 *
a6c01b45
CW
125 * @return array
126 * associated array of field values
6a488035 127 */
00be9182 128 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
6a488035
TO
129 if (empty($params)) {
130 return NULL;
131 }
132 CRM_Core_DAO::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
133 return $values;
134 }
135
136 /**
fe482240 137 * Takes an associative array and creates a pledge object.
6a488035 138 *
3a1617b6
TO
139 * @param array $params
140 * (reference ) an assoc array of name/value pairs.
6a488035 141 *
16b10e64 142 * @return CRM_Pledge_BAO_Pledge
6a488035 143 */
00be9182 144 public static function &create(&$params) {
cc28438b 145 // FIXME: a cludgy hack to fix the dates to MySQL format
6a488035
TO
146 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
147 foreach ($dateFields as $df) {
148 if (isset($params[$df])) {
149 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
150 }
151 }
152
153 $transaction = new CRM_Core_Transaction();
154
155 $paymentParams = array();
156 $paymentParams['status_id'] = CRM_Utils_Array::value('status_id', $params);
a7488080 157 if (!empty($params['installment_amount'])) {
6a488035
TO
158 $params['amount'] = $params['installment_amount'] * $params['installments'];
159 }
160
cc28438b 161 // get All Payments status types.
6a488035
TO
162 $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
163
cc28438b 164 // update the pledge status only if it does NOT come from form
6a488035
TO
165 if (!isset($params['pledge_status_id'])) {
166 if (isset($params['contribution_id'])) {
167 if ($params['installments'] > 1) {
168 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
169 }
170 }
171 else {
172 if (!empty($params['id'])) {
173 $params['status_id'] = CRM_Pledge_BAO_PledgePayment::calculatePledgeStatus($params['id']);
174 }
175 else {
176 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
177 }
178 }
179 }
180
181 $pledge = self::add($params);
182 if (is_a($pledge, 'CRM_Core_Error')) {
183 $pledge->rollback();
184 return $pledge;
185 }
186
cc28438b 187 // handle custom data.
a7488080 188 if (!empty($params['custom']) &&
6a488035
TO
189 is_array($params['custom'])
190 ) {
191 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pledge', $pledge->id);
192 }
193
194 // skip payment stuff inedit mode
8cc574cf 195 if (!isset($params['id']) || !empty($params['is_pledge_pending'])) {
6a488035 196
cc28438b 197 // if pledge is pending delete all payments and recreate.
a7488080 198 if (!empty($params['is_pledge_pending'])) {
6a488035
TO
199 CRM_Pledge_BAO_PledgePayment::deletePayments($pledge->id);
200 }
201
cc28438b 202 // building payment params
6a488035
TO
203 $paymentParams['pledge_id'] = $pledge->id;
204 $paymentKeys = array(
353ffa53
TO
205 'amount',
206 'installments',
207 'scheduled_date',
208 'frequency_unit',
209 'currency',
210 'frequency_day',
211 'frequency_interval',
212 'contribution_id',
213 'installment_amount',
214 'actual_amount',
6a488035
TO
215 );
216 foreach ($paymentKeys as $key) {
217 $paymentParams[$key] = CRM_Utils_Array::value($key, $params, NULL);
218 }
219 CRM_Pledge_BAO_PledgePayment::create($paymentParams);
220 }
221
222 $transaction->commit();
223
224 $url = CRM_Utils_System::url('civicrm/contact/view/pledge',
225 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
226 );
227
228 $recentOther = array();
229 if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
230 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
231 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
232 );
233 }
234 if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
235 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
236 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
237 );
238 }
239
25e778a5
E
240 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
241 $title = CRM_Contact_BAO_Contact::displayName($pledge->contact_id) . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($pledge->amount, $pledge->currency) . ' - ' . CRM_Utils_Array::value($pledge->financial_type_id, $contributionTypes) . ')';
6a488035
TO
242
243 // add the recently created Pledge
244 CRM_Utils_Recent::add($title,
245 $url,
246 $pledge->id,
247 'Pledge',
248 $pledge->contact_id,
249 NULL,
250 $recentOther
251 );
252
253 return $pledge;
254 }
255
256 /**
fe482240 257 * Delete the pledge.
6a488035 258 *
3a1617b6
TO
259 * @param int $id
260 * Pledge id.
6a488035 261 *
77b97be7 262 * @return mixed
6a488035 263 */
00be9182 264 public static function deletePledge($id) {
6a488035
TO
265 CRM_Utils_Hook::pre('delete', 'Pledge', $id, CRM_Core_DAO::$_nullArray);
266
267 $transaction = new CRM_Core_Transaction();
268
cc28438b 269 // check for no Completed Payment records with the pledge
6a488035
TO
270 $payment = new CRM_Pledge_DAO_PledgePayment();
271 $payment->pledge_id = $id;
272 $payment->find();
273
274 while ($payment->fetch()) {
cc28438b 275 // also delete associated contribution.
6a488035
TO
276 if ($payment->contribution_id) {
277 CRM_Contribute_BAO_Contribution::deleteContribution($payment->contribution_id);
278 }
279 $payment->delete();
280 }
281
353ffa53 282 $dao = new CRM_Pledge_DAO_Pledge();
6a488035
TO
283 $dao->id = $id;
284 $results = $dao->delete();
285
286 $transaction->commit();
287
288 CRM_Utils_Hook::post('delete', 'Pledge', $dao->id, $dao);
289
290 // delete the recently created Pledge
291 $pledgeRecent = array(
292 'id' => $id,
293 'type' => 'Pledge',
294 );
295 CRM_Utils_Recent::del($pledgeRecent);
296
297 return $results;
298 }
299
300 /**
100fef9d 301 * Get the amount details date wise.
b55cf2b2
EM
302 *
303 * @param string $status
304 * @param string $startDate
305 * @param string $endDate
306 *
307 * @return array|null
6a488035 308 */
00be9182 309 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
6a488035
TO
310 $where = array();
311 $select = $from = $queryDate = NULL;
cc28438b 312 // get all status
6a488035
TO
313 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
314 $statusId = array_search($status, $allStatus);
315
316 switch ($status) {
317 case 'Completed':
318 $statusId = array_search('Cancelled', $allStatus);
319 $where[] = 'status_id != ' . $statusId;
320 break;
321
322 case 'Cancelled':
323 $where[] = 'status_id = ' . $statusId;
324 break;
325
326 case 'In Progress':
327 $where[] = 'status_id = ' . $statusId;
328 break;
329
330 case 'Pending':
331 $where[] = 'status_id = ' . $statusId;
332 break;
333
334 case 'Overdue':
335 $where[] = 'status_id = ' . $statusId;
336 break;
337 }
338
339 if ($startDate) {
340 $where[] = "create_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
341 }
342 if ($endDate) {
343 $where[] = "create_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
344 }
345
346 $whereCond = implode(' AND ', $where);
347
348 $query = "
349SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
350FROM civicrm_pledge
351WHERE $whereCond AND is_test=0
352GROUP BY currency
353";
353ffa53
TO
354 $start = substr($startDate, 0, 8);
355 $end = substr($endDate, 0, 8);
356 $pCount = 0;
6a488035 357 $pamount = array();
9d2678f4 358 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
359 while ($dao->fetch()) {
360 $pCount += $dao->pledge_count;
361 $pamount[] = CRM_Utils_Money::format($dao->pledge_amount, $dao->currency);
362 }
363
098201d8 364 $pledge_amount = array(
353ffa53 365 'pledge_amount' => implode(', ', $pamount),
6a488035
TO
366 'pledge_count' => $pCount,
367 'purl' => CRM_Utils_System::url('civicrm/pledge/search',
368 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
369 ),
370 );
371
372 $where = array();
373 $statusId = array_search($status, $allStatus);
374 switch ($status) {
375 case 'Completed':
353ffa53
TO
376 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
377 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
6a488035 378 $queryDate = 'receive_date';
353ffa53 379 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
6a488035
TO
380 break;
381
382 case 'Cancelled':
353ffa53
TO
383 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
384 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
6a488035 385 $queryDate = 'receive_date';
353ffa53 386 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
6a488035
TO
387 break;
388
389 case 'Pending':
353ffa53
TO
390 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
391 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
6a488035 392 $queryDate = 'scheduled_date';
353ffa53 393 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
6a488035
TO
394 break;
395
396 case 'Overdue':
353ffa53
TO
397 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
398 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
6a488035 399 $queryDate = 'scheduled_date';
353ffa53 400 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
6a488035
TO
401 break;
402 }
403
404 if ($startDate) {
405 $where[] = " $queryDate >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
406 }
407 if ($endDate) {
408 $where[] = " $queryDate <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
409 }
410
411 $whereCond = implode(' AND ', $where);
412
413 $query = "
414 SELECT $select, cp.currency
415 FROM $from
416 WHERE $whereCond
417 GROUP BY cp.currency
418";
419 if ($select) {
9d2678f4 420 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 421 $amount = array();
353ffa53 422 $count = 0;
6a488035
TO
423
424 while ($dao->fetch()) {
425 $count += $dao->received_count;
426 $amount[] = CRM_Utils_Money::format($dao->received_pledge, $dao->currency);
427 }
428
429 if ($count) {
098201d8 430 return array_merge($pledge_amount, array(
353ffa53
TO
431 'received_amount' => implode(', ', $amount),
432 'received_count' => $count,
433 'url' => CRM_Utils_System::url('civicrm/pledge/search',
434 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
435 ),
436 ));
6a488035
TO
437 }
438 }
439 else {
440 return $pledge_amount;
441 }
442 return NULL;
443 }
444
445 /**
fe482240 446 * Get list of pledges In Honor of contact Ids.
6a488035 447 *
3a1617b6
TO
448 * @param int $honorId
449 * In Honor of Contact ID.
6a488035 450 *
a6c01b45
CW
451 * @return array
452 * return the list of pledge fields
6a488035 453 */
00be9182 454 public static function getHonorContacts($honorId) {
6a488035 455 $params = array();
8381af80 456 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
457 $honorDAO->contact_id = $honorId;
6a488035
TO
458 $honorDAO->find();
459
cc28438b 460 // get all status.
6a488035 461 while ($honorDAO->fetch()) {
8381af80 462 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
463 $pledgePaymentDAO->contribution_id = $honorDAO->contribution_id;
464 if ($pledgePaymentDAO->find(TRUE)) {
465 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
466 $pledgeDAO->id = $pledgePaymentDAO->pledge_id;
467 if ($pledgeDAO->find(TRUE)) {
468 $params[$pledgeDAO->id] = array(
b7617307 469 'honor_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id),
8381af80 470 'honorId' => $pledgeDAO->contact_id,
471 'amount' => $pledgeDAO->amount,
472 'status' => CRM_Contribute_PseudoConstant::contributionStatus($pledgeDAO->status_id),
473 'create_date' => $pledgeDAO->create_date,
474 'acknowledge_date' => $pledgeDAO->acknowledge_date,
475 'type' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
476 $pledgeDAO->financial_type_id, 'name'
477 ),
478 'display_name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
479 $pledgeDAO->contact_id, 'display_name'
480 ),
481 );
482 }
483 }
6a488035 484 }
8381af80 485
6a488035
TO
486 return $params;
487 }
488
489 /**
100fef9d 490 * Send Acknowledgment and create activity.
6a488035 491 *
3a1617b6
TO
492 * @param CRM_Core_Form $form
493 * Form object.
494 * @param array $params
495 * An assoc array of name/value pairs.
6a488035 496 */
00be9182 497 public static function sendAcknowledgment(&$form, $params) {
6a488035
TO
498 //handle Acknowledgment.
499 $allPayments = $payments = array();
500
cc28438b 501 // get All Payments status types.
6a488035
TO
502 $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
503 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
cc28438b 504 // get all paymnets details.
6a488035
TO
505 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
506
507 if (!empty($allPayments)) {
508 foreach ($allPayments as $payID => $values) {
509 $contributionValue = $contributionStatus = array();
510 if (isset($values['contribution_id'])) {
511 $contributionParams = array('id' => $values['contribution_id']);
512 $returnProperties = array('contribution_status_id', 'receive_date');
513 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_Contribution',
514 $contributionParams, $contributionStatus, $returnProperties
515 );
516 $contributionValue = array(
517 'status' => CRM_Utils_Array::value('contribution_status_id', $contributionStatus),
518 'receive_date' => CRM_Utils_Array::value('receive_date', $contributionStatus),
519 );
520 }
521 $payments[$payID] = array_merge($contributionValue,
098201d8 522 array(
353ffa53 523 'amount' => CRM_Utils_Array::value('scheduled_amount', $values),
6a488035
TO
524 'due_date' => CRM_Utils_Array::value('scheduled_date', $values),
525 )
526 );
527
cc28438b 528 // get the first valid payment id.
6a488035
TO
529 if (!isset($form->paymentId) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
530 $paymentStatusTypes[$values['status_id']] == 'Overdue'
353ffa53
TO
531 )
532 ) {
6a488035
TO
533 $form->paymentId = $values['id'];
534 }
535 }
536 }
6a488035 537
cc28438b 538 // assign pledge fields value to template.
6a488035 539 $pledgeFields = array(
353ffa53
TO
540 'create_date',
541 'total_pledge_amount',
542 'frequency_interval',
543 'frequency_unit',
544 'installments',
545 'frequency_day',
546 'scheduled_amount',
547 'currency',
6a488035
TO
548 );
549 foreach ($pledgeFields as $field) {
a7488080 550 if (!empty($params[$field])) {
6a488035
TO
551 $form->assign($field, $params[$field]);
552 }
553 }
554
cc28438b 555 // assign all payments details.
6a488035
TO
556 if ($payments) {
557 $form->assign('payments', $payments);
558 }
559
cc28438b 560 // handle domain token values
6a488035 561 $domain = CRM_Core_BAO_Domain::getDomain();
098201d8 562 $tokens = array(
353ffa53 563 'domain' => array('name', 'phone', 'address', 'email'),
6a488035
TO
564 'contact' => CRM_Core_SelectValues::contactTokens(),
565 );
566 $domainValues = array();
567 foreach ($tokens['domain'] as $token) {
568 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
569 }
570 $form->assign('domain', $domainValues);
571
cc28438b 572 // handle contact token values.
6a488035
TO
573 $ids = array($params['contact_id']);
574 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::importableFields()),
575 array('display_name', 'checksum', 'contact_id')
576 );
577 foreach ($fields as $key => $val) {
578 $returnProperties[$val] = TRUE;
579 }
580 $details = CRM_Utils_Token::getTokenDetails($ids,
581 $returnProperties,
582 TRUE, TRUE, NULL,
583 $tokens,
584 get_class($form)
585 );
586 $form->assign('contact', $details[0][$params['contact_id']]);
587
cc28438b 588 // handle custom data.
a7488080 589 if (!empty($params['hidden_custom'])) {
353ffa53 590 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', CRM_Core_DAO::$_nullObject, $params['id']);
6a488035 591 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
353ffa53 592 $customGroup = array();
6a488035
TO
593 // retrieve custom data
594 foreach ($groupTree as $groupID => $group) {
595 $customFields = $customValues = array();
596 if ($groupID == 'info') {
597 continue;
598 }
599 foreach ($group['fields'] as $k => $field) {
600 $field['title'] = $field['label'];
601 $customFields["custom_{$k}"] = $field;
602 }
603
cc28438b 604 // to build array of customgroup & customfields in it
6a488035
TO
605 CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
606 $customGroup[$group['title']] = $customValues;
607 }
608
609 $form->assign('customGroup', $customGroup);
610 }
611
cc28438b 612 // handle acknowledgment email stuff.
6a488035
TO
613 list($pledgerDisplayName,
614 $pledgerEmail
353ffa53 615 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
6a488035 616
cc28438b 617 // check for online pledge.
a7488080 618 if (!empty($params['receipt_from_email'])) {
6a488035
TO
619 $userName = CRM_Utils_Array::value('receipt_from_name', $params);
620 $userEmail = CRM_Utils_Array::value('receipt_from_email', $params);
621 }
a7488080 622 elseif (!empty($params['from_email_id'])) {
6a488035
TO
623 $receiptFrom = $params['from_email_id'];
624 }
bb06e9ed 625 elseif ($userID = CRM_Core_Session::singleton()->get('userID')) {
cc28438b 626 // check for logged in user.
6a488035
TO
627 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
628 }
629 else {
cc28438b 630 // set the domain values.
6a488035
TO
631 $userName = CRM_Utils_Array::value('name', $domainValues);
632 $userEmail = CRM_Utils_Array::value('email', $domainValues);
633 }
634
635 if (!isset($receiptFrom)) {
636 $receiptFrom = "$userName <$userEmail>";
637 }
638
c6327d7d 639 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
6a488035
TO
640 array(
641 'groupName' => 'msg_tpl_workflow_pledge',
642 'valueName' => 'pledge_acknowledge',
643 'contactId' => $params['contact_id'],
644 'from' => $receiptFrom,
645 'toName' => $pledgerDisplayName,
646 'toEmail' => $pledgerEmail,
647 )
648 );
649
cc28438b
SB
650 // check if activity record exist for this pledge
651 // Acknowledgment, if exist do not add activity.
6a488035
TO
652 $activityType = 'Pledge Acknowledgment';
653 $activity = new CRM_Activity_DAO_Activity();
654 $activity->source_record_id = $params['id'];
655 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
656 $activityType,
657 'name'
658 );
6a488035 659
6c68db9f 660 // FIXME: Translate
6a488035
TO
661 $details = 'Total Amount ' . CRM_Utils_Money::format($params['total_pledge_amount'], CRM_Utils_Array::value('currency', $params)) . ' To be paid in ' . $params['installments'] . ' installments of ' . CRM_Utils_Money::format($params['scheduled_amount'], CRM_Utils_Array::value('currency', $params)) . ' every ' . $params['frequency_interval'] . ' ' . $params['frequency_unit'] . '(s)';
662
663 if (!$activity->find()) {
664 $activityParams = array(
665 'subject' => $subject,
666 'source_contact_id' => $params['contact_id'],
667 'source_record_id' => $params['id'],
668 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
669 $activityType,
670 'name'
671 ),
672 'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']),
673 'is_test' => $params['is_test'],
674 'status_id' => 2,
675 'details' => $details,
676 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
677 );
678
cc28438b 679 // lets insert assignee record.
a7488080 680 if (!empty($params['contact_id'])) {
6a488035
TO
681 $activityParams['assignee_contact_id'] = $params['contact_id'];
682 }
683
684 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
685 CRM_Core_Error::fatal("Failed creating Activity for acknowledgment");
686 }
687 }
688 }
689
690 /**
fe482240 691 * Combine all the exportable fields from the lower levels object.
6a488035 692 *
a6c01b45
CW
693 * @return array
694 * array of exportable Fields
6a488035 695 */
00be9182 696 public static function &exportableFields() {
6a488035
TO
697 if (!self::$_exportableFields) {
698 if (!self::$_exportableFields) {
699 self::$_exportableFields = array();
700 }
701
702 $fields = CRM_Pledge_DAO_Pledge::export();
703
6a488035
TO
704 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment::export());
705
cc28438b 706 // set title to calculated fields
098201d8 707 $calculatedFields = array(
353ffa53 708 'pledge_total_paid' => array('title' => ts('Total Paid')),
6a488035
TO
709 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
710 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
711 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
712 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
713 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
098201d8 714 'pledge_payment_status' => array(
353ffa53 715 'title' => ts('Pledge Payment Status'),
6a488035
TO
716 'name' => 'pledge_payment_status',
717 'data_type' => CRM_Utils_Type::T_STRING,
718 ),
719 );
720
6a488035 721 $pledgeFields = array(
098201d8 722 'pledge_status' => array(
353ffa53 723 'title' => 'Pledge Status',
6a488035
TO
724 'name' => 'pledge_status',
725 'data_type' => CRM_Utils_Type::T_STRING,
726 ),
727 'pledge_frequency_unit' => array(
728 'title' => 'Pledge Frequency Unit',
729 'name' => 'pledge_frequency_unit',
730 'data_type' => CRM_Utils_Type::T_ENUM,
731 ),
732 'pledge_frequency_interval' => array(
733 'title' => 'Pledge Frequency Interval',
734 'name' => 'pledge_frequency_interval',
735 'data_type' => CRM_Utils_Type::T_INT,
736 ),
737 'pledge_contribution_page_id' => array(
738 'title' => 'Pledge Contribution Page Id',
739 'name' => 'pledge_contribution_page_id',
740 'data_type' => CRM_Utils_Type::T_INT,
741 ),
742 );
743
744 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
745
746 // add custom data
747 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge'));
748 self::$_exportableFields = $fields;
749 }
750
751 return self::$_exportableFields;
752 }
753
754 /**
fe482240 755 * Get pending or in progress pledges.
6a488035 756 *
3a1617b6
TO
757 * @param int $contactID
758 * Contact id.
6a488035 759 *
a6c01b45
CW
760 * @return array
761 * associated array of pledge id(s)
6a488035 762 */
00be9182 763 public static function getContactPledges($contactID) {
6a488035
TO
764 $pledgeDetails = array();
765 $pledgeStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
766
767 $status = array();
768
cc28438b 769 // get pending and in progress status
6a488035 770 foreach (array(
353ffa53
TO
771 'Pending',
772 'In Progress',
317fceb4 773 'Overdue',
353ffa53 774 ) as $name) {
6a488035
TO
775 if ($statusId = array_search($name, $pledgeStatuses)) {
776 $status[] = $statusId;
777 }
778 }
779 if (empty($status)) {
780 return $pledgeDetails;
781 }
782
783 $statusClause = " IN (" . implode(',', $status) . ")";
784
785 $query = "
786 SELECT civicrm_pledge.id id
787 FROM civicrm_pledge
788 WHERE civicrm_pledge.status_id {$statusClause}
789 AND civicrm_pledge.contact_id = %1
790";
791
792 $params[1] = array($contactID, 'Integer');
793 $pledge = CRM_Core_DAO::executeQuery($query, $params);
794
795 while ($pledge->fetch()) {
796 $pledgeDetails[] = $pledge->id;
797 }
798
799 return $pledgeDetails;
800 }
801
802 /**
fe482240 803 * Get pledge record count for a Contact.
6a488035 804 *
100fef9d 805 * @param int $contactID
2a6da8d7 806 *
a6c01b45
CW
807 * @return int
808 * count of pledge records
6a488035 809 */
00be9182 810 public static function getContactPledgeCount($contactID) {
6a488035
TO
811 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
812 return CRM_Core_DAO::singleValueQuery($query);
813 }
814
ffd93213 815 /**
c490a46a 816 * @param array $params
ffd93213
EM
817 *
818 * @return array
819 */
7670996e 820 public static function updatePledgeStatus($params) {
6a488035
TO
821
822 $returnMessages = array();
823
824 $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE);
825
826 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
827
cc28438b 828 // unset statues that we never use for pledges
6a488035 829 foreach (array(
353ffa53
TO
830 'Completed',
831 'Cancelled',
317fceb4 832 'Failed',
353ffa53 833 ) as $statusKey) {
6a488035
TO
834 if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) {
835 unset($allStatus[$key]);
836 }
837 }
838
839 $statusIds = implode(',', array_keys($allStatus));
840 $updateCnt = 0;
841
842 $query = "
843SELECT pledge.contact_id as contact_id,
844 pledge.id as pledge_id,
845 pledge.amount as amount,
846 payment.scheduled_date as scheduled_date,
847 pledge.create_date as create_date,
848 payment.id as payment_id,
849 pledge.currency as currency,
850 pledge.contribution_page_id as contribution_page_id,
851 payment.reminder_count as reminder_count,
852 pledge.max_reminders as max_reminders,
853 payment.reminder_date as reminder_date,
854 pledge.initial_reminder_day as initial_reminder_day,
855 pledge.additional_reminder_day as additional_reminder_day,
856 pledge.status_id as pledge_status,
857 payment.status_id as payment_status,
858 pledge.is_test as is_test,
859 pledge.campaign_id as campaign_id,
860 SUM(payment.scheduled_amount) as amount_due,
861 ( SELECT sum(civicrm_pledge_payment.actual_amount)
862 FROM civicrm_pledge_payment
863 WHERE civicrm_pledge_payment.status_id = 1
864 AND civicrm_pledge_payment.pledge_id = pledge.id
865 ) as amount_paid
866 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
867 WHERE pledge.id = payment.pledge_id
868 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
869 GROUP By payment.id
870 ";
871
872 $dao = CRM_Core_DAO::executeQuery($query);
873
874 $now = date('Ymd');
875 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
876 while ($dao->fetch()) {
877 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
878
879 $pledgeDetails[$dao->payment_id] = array(
880 'scheduled_date' => $dao->scheduled_date,
881 'amount_due' => $dao->amount_due,
882 'amount' => $dao->amount,
883 'amount_paid' => $dao->amount_paid,
884 'create_date' => $dao->create_date,
885 'contact_id' => $dao->contact_id,
886 'pledge_id' => $dao->pledge_id,
887 'checksumValue' => $checksumValue,
888 'contribution_page_id' => $dao->contribution_page_id,
889 'reminder_count' => $dao->reminder_count,
890 'max_reminders' => $dao->max_reminders,
891 'reminder_date' => $dao->reminder_date,
892 'initial_reminder_day' => $dao->initial_reminder_day,
893 'additional_reminder_day' => $dao->additional_reminder_day,
894 'pledge_status' => $dao->pledge_status,
895 'payment_status' => $dao->payment_status,
896 'is_test' => $dao->is_test,
897 'currency' => $dao->currency,
898 'campaign_id' => $dao->campaign_id,
899 );
900
901 $contactIds[$dao->contact_id] = $dao->contact_id;
902 $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
903
904 if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'),
905 $now
353ffa53
TO
906 ) && $dao->payment_status != array_search('Overdue', $allStatus)
907 ) {
6a488035
TO
908 $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
909 }
910 }
911
912 // process the updating script...
913
914 foreach ($pledgePayments as $pledgeId => $paymentIds) {
915 // 1. update the pledge /pledge payment status. returns new status when an update happens
916 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
917
918 $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds,
919 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
920 );
921 if ($newStatus != $pledgeStatus[$pledgeId]) {
922 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
923 $updateCnt += 1;
924 }
925 }
926
927 if ($sendReminders) {
928 // retrieve domain tokens
929 $domain = CRM_Core_BAO_Domain::getDomain();
098201d8 930 $tokens = array(
353ffa53 931 'domain' => array('name', 'phone', 'address', 'email'),
6a488035
TO
932 'contact' => CRM_Core_SelectValues::contactTokens(),
933 );
934
935 $domainValues = array();
936 foreach ($tokens['domain'] as $token) {
937 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
938 }
939
cc28438b 940 // get the domain email address, since we don't carry w/ object.
6a488035
TO
941 $domainValue = CRM_Core_BAO_Domain::getNameAndEmail();
942 $domainValues['email'] = $domainValue[1];
943
944 // retrieve contact tokens
945
946 // this function does NOT return Deceased contacts since we don't want to send them email
947 list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
948 NULL,
949 FALSE, FALSE, NULL,
950 $tokens, 'CRM_UpdatePledgeRecord'
951 );
952
953 // assign domain values to template
954 $template = CRM_Core_Smarty::singleton();
955 $template->assign('domain', $domainValues);
956
cc28438b 957 // set receipt from
6a488035
TO
958 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
959
960 foreach ($pledgeDetails as $paymentId => $details) {
961 if (array_key_exists($details['contact_id'], $contactDetails)) {
962 $contactId = $details['contact_id'];
963 $pledgerName = $contactDetails[$contactId]['display_name'];
964 }
965 else {
966 continue;
967 }
968
969 if (empty($details['reminder_date'])) {
970 $nextReminderDate = new DateTime($details['scheduled_date']);
971 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
972 $nextReminderDate = $nextReminderDate->format("Ymd");
973 }
974 else {
975 $nextReminderDate = new DateTime($details['reminder_date']);
976 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
977 $nextReminderDate = $nextReminderDate->format("Ymd");
978 }
979 if (($details['reminder_count'] < $details['max_reminders'])
980 && ($nextReminderDate <= $now)
981 ) {
982
983 $toEmail = $doNotEmail = $onHold = NULL;
984
985 if (!empty($contactDetails[$contactId]['email'])) {
986 $toEmail = $contactDetails[$contactId]['email'];
987 }
988
989 if (!empty($contactDetails[$contactId]['do_not_email'])) {
990 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
991 }
992
993 if (!empty($contactDetails[$contactId]['on_hold'])) {
994 $onHold = $contactDetails[$contactId]['on_hold'];
995 }
996
997 // 2. send acknowledgement mail
998 if ($toEmail && !($doNotEmail || $onHold)) {
cc28438b 999 // assign value to template
6a488035
TO
1000 $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
1001 $template->assign('contact', $contactDetails[$contactId]);
1002 $template->assign('next_payment', $details['scheduled_date']);
1003 $template->assign('amount_due', $details['amount_due']);
1004 $template->assign('checksumValue', $details['checksumValue']);
1005 $template->assign('contribution_page_id', $details['contribution_page_id']);
1006 $template->assign('pledge_id', $details['pledge_id']);
1007 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1008 $template->assign('amount', $details['amount']);
1009 $template->assign('create_date', $details['create_date']);
1010 $template->assign('currency', $details['currency']);
c6327d7d 1011 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
6a488035
TO
1012 array(
1013 'groupName' => 'msg_tpl_workflow_pledge',
1014 'valueName' => 'pledge_reminder',
1015 'contactId' => $contactId,
1016 'from' => $receiptFrom,
1017 'toName' => $pledgerName,
1018 'toEmail' => $toEmail,
1019 )
1020 );
1021
1022 // 3. update pledge payment details
1023 if ($mailSent) {
1024 CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
1025 $activityType = 'Pledge Reminder';
1026 $activityParams = array(
1027 'subject' => $subject,
1028 'source_contact_id' => $contactId,
1029 'source_record_id' => $paymentId,
1030 'assignee_contact_id' => $contactId,
1031 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
1032 $activityType,
1033 'name'
1034 ),
1035 'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
1036 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']),
1037 'is_test' => $details['is_test'],
1038 'status_id' => 2,
1039 'campaign_id' => $details['campaign_id'],
1040 );
1041 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1042 $returnMessages[] = "Failed creating Activity for acknowledgment";
1043 return array('is_error' => 1, 'message' => $returnMessages);
1044 }
1045 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1046 }
1047 }
1048 }
1049 }
1050 // end foreach on $pledgeDetails
1051 }
1052 // end if ( $sendReminders )
1053 $returnMessages[] = "{$updateCnt} records updated.";
1054
1055 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1056 }
1057
1058 /**
1059 * Mark a pledge (and any outstanding payments) as cancelled.
1060 *
1061 * @param int $pledgeID
1062 */
1063 public static function cancel($pledgeID) {
1064 $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus());
1065 $paymentIDs = self::findCancelablePayments($pledgeID);
1066 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1067 $statuses['Cancelled'], 0, FALSE, TRUE
1068 );
1069 }
1070
1071 /**
1072 * Find payments which can be safely canceled.
1073 *
1074 * @param int $pledgeID
a6c01b45 1075 * @return array
16b10e64 1076 * Array of int (civicrm_pledge_payment.id)
6a488035
TO
1077 */
1078 public static function findCancelablePayments($pledgeID) {
1079 $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus());
1080
1081 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1082 $paymentDAO->pledge_id = $pledgeID;
1083 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1084 $statuses['Overdue'],
1085 $statuses['Pending']
1086 ));
1087 $paymentDAO->find();
1088
1089 $paymentIDs = array();
1090 while ($paymentDAO->fetch()) {
1091 $paymentIDs[] = $paymentDAO->id;
1092 }
1093 return $paymentIDs;
1094 }
edb4c74d
E
1095
1096 /**
1097 * Is this pledge free from financial transactions (this is important to know as we allow editing
1098 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
cc28438b 1099 * & recreating so we want to block that if appropriate).
edb4c74d 1100 *
3a1617b6
TO
1101 * @param int $pledgeID
1102 * @param int $pledgeStatusID
a6c01b45
CW
1103 * @return bool
1104 * do financial transactions exist for this pledge?
edb4c74d 1105 */
098201d8 1106 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
edb4c74d 1107 if (empty($pledgeStatusID)) {
cc28438b
SB
1108 // why would this happen? If we can see where it does then we can see if we should look it up.
1109 // but assuming from form code it CAN be empty.
edb4c74d
E
1110 return TRUE;
1111 }
1112 if (self::isTransactedStatus($pledgeStatusID)) {
1113 return TRUE;
1114 }
1115
353ffa53
TO
1116 return civicrm_api3('pledge_payment', 'getcount', array(
1117 'pledge_id' => $pledgeID,
317fceb4 1118 'status_id' => array('IN' => self::getTransactionalStatus()),
353ffa53 1119 ));
098201d8 1120 }
edb4c74d
E
1121
1122 /**
1123 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
3a1617b6
TO
1124 * @param int $statusID
1125 * Pledge status id.
edb4c74d 1126 *
a6c01b45
CW
1127 * @return bool
1128 * is it a transactional status?
edb4c74d
E
1129 */
1130 protected static function isTransactedStatus($statusID) {
1131 if (!in_array($statusID, self::getNonTransactionalStatus())) {
1132 return TRUE;
1133 }
b55cf2b2 1134 return FALSE;
edb4c74d
E
1135 }
1136
1137 /**
fe482240 1138 * Get array of non transactional statuses.
a6c01b45
CW
1139 * @return array
1140 * non transactional status ids
edb4c74d
E
1141 */
1142 protected static function getNonTransactionalStatus() {
1143 $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1144 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1145 }
1146
1147 /**
fe482240 1148 * Get array of non transactional statuses.
a6c01b45
CW
1149 * @return array
1150 * non transactional status ids
edb4c74d
E
1151 */
1152 protected static function getTransactionalStatus() {
1153 $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1154 return array_diff(array_flip($paymentStatus), self::getNonTransactionalStatus());
1155 }
96025800 1156
6a488035 1157}