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