3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Pledge_BAO_Pledge
extends CRM_Pledge_DAO_Pledge
{
38 * Static field for all the pledge information that we can potentially export
43 static $_exportableFields = NULL;
48 public function __construct() {
49 parent
::__construct();
53 * Takes a bunch of params that are needed to match certain criteria and
54 * retrieves the relevant objects. Typically the valid params are only
55 * pledge id. We'll tweak this function to be more full featured over a period
56 * of time. This is the inverse function of create. It also stores all the retrieved
57 * values in the default array
59 * @param array $params
60 * (reference ) an assoc array of name/value pairs.
61 * @param array $defaults
62 * (reference ) an assoc array to hold the flattened values.
64 * @return CRM_Pledge_BAO_Pledge object
67 public static function retrieve(&$params, &$defaults) {
68 $pledge = new CRM_Pledge_DAO_Pledge();
69 $pledge->copyValues($params);
70 if ($pledge->find(TRUE)) {
71 CRM_Core_DAO
::storeValues($pledge, $defaults);
80 * @param array $params
81 * Reference array contains the values submitted by the form.
87 public static function add(&$params) {
88 if (!empty($params['id'])) {
89 CRM_Utils_Hook
::pre('edit', 'Pledge', $params['id'], $params);
92 CRM_Utils_Hook
::pre('create', 'Pledge', NULL, $params);
95 $pledge = new CRM_Pledge_DAO_Pledge();
97 // if pledge is complete update end date as current date
98 if ($pledge->status_id
== 1) {
99 $pledge->end_date
= date('Ymd');
102 $pledge->copyValues($params);
104 // set currency for CRM-1496
105 if (!isset($pledge->currency
)) {
106 $config = CRM_Core_Config
::singleton();
107 $pledge->currency
= $config->defaultCurrency
;
110 $result = $pledge->save();
112 if (!empty($params['id'])) {
113 CRM_Utils_Hook
::post('edit', 'Pledge', $pledge->id
, $pledge);
116 CRM_Utils_Hook
::post('create', 'Pledge', $pledge->id
, $pledge);
123 * Given the list of params in the params array, fetch the object
124 * and store the values in the values array
126 * @param array $params
127 * Input parameters to find object.
128 * @param array $values
129 * Output values of the object.
130 * @param array $returnProperties
131 * If you want to return specific fields.
133 * @return array associated array of field values
136 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
137 if (empty($params)) {
140 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
145 * Takes an associative array and creates a pledge object
147 * @param array $params
148 * (reference ) an assoc array of name/value pairs.
150 * @return CRM_Pledge_BAO_Pledge object
153 public static function &create(&$params) {
154 //FIXME: a cludgy hack to fix the dates to MySQL format
155 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
156 foreach ($dateFields as $df) {
157 if (isset($params[$df])) {
158 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
162 $transaction = new CRM_Core_Transaction();
164 $paymentParams = array();
165 $paymentParams['status_id'] = CRM_Utils_Array
::value('status_id', $params);
166 if (!empty($params['installment_amount'])) {
167 $params['amount'] = $params['installment_amount'] * $params['installments'];
170 //get All Payments status types.
171 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
173 //update the pledge status only if it does NOT come from form
174 if (!isset($params['pledge_status_id'])) {
175 if (isset($params['contribution_id'])) {
176 if ($params['installments'] > 1) {
177 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
181 if (!empty($params['id'])) {
182 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
185 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
190 $pledge = self
::add($params);
191 if (is_a($pledge, 'CRM_Core_Error')) {
196 //handle custom data.
197 if (!empty($params['custom']) &&
198 is_array($params['custom'])
200 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
203 // skip payment stuff inedit mode
204 if (!isset($params['id']) ||
!empty($params['is_pledge_pending'])) {
206 //if pledge is pending delete all payments and recreate.
207 if (!empty($params['is_pledge_pending'])) {
208 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
211 //building payment params
212 $paymentParams['pledge_id'] = $pledge->id
;
213 $paymentKeys = array(
214 'amount', 'installments', 'scheduled_date', 'frequency_unit', 'currency',
215 'frequency_day', 'frequency_interval', 'contribution_id', 'installment_amount', 'actual_amount',
217 foreach ($paymentKeys as $key) {
218 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
220 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
223 $transaction->commit();
225 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
226 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
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"
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"
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) . ')';
244 // add the recently created Pledge
245 CRM_Utils_Recent
::add($title,
267 public static function deletePledge($id) {
268 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
270 $transaction = new CRM_Core_Transaction();
272 //check for no Completed Payment records with the pledge
273 $payment = new CRM_Pledge_DAO_PledgePayment();
274 $payment->pledge_id
= $id;
277 while ($payment->fetch()) {
278 //also delete associated contribution.
279 if ($payment->contribution_id
) {
280 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
285 $dao = new CRM_Pledge_DAO_Pledge();
287 $results = $dao->delete();
289 $transaction->commit();
291 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
293 // delete the recently created Pledge
294 $pledgeRecent = array(
298 CRM_Utils_Recent
::del($pledgeRecent);
304 * Get the amount details date wise.
306 * @param string $status
307 * @param string $startDate
308 * @param string $endDate
312 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
314 $select = $from = $queryDate = NULL;
316 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
317 $statusId = array_search($status, $allStatus);
321 $statusId = array_search('Cancelled', $allStatus);
322 $where[] = 'status_id != ' . $statusId;
326 $where[] = 'status_id = ' . $statusId;
330 $where[] = 'status_id = ' . $statusId;
334 $where[] = 'status_id = ' . $statusId;
338 $where[] = 'status_id = ' . $statusId;
343 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
346 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
349 $whereCond = implode(' AND ', $where);
352 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
354 WHERE $whereCond AND is_test=0
357 $start = substr($startDate, 0, 8);
358 $end = substr($endDate, 0, 8);
361 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
362 while ($dao->fetch()) {
363 $pCount +
= $dao->pledge_count
;
364 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
367 $pledge_amount = array(
368 'pledge_amount' => implode(', ', $pamount),
369 'pledge_count' => $pCount,
370 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
371 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
376 $statusId = array_search($status, $allStatus);
379 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
380 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
381 $queryDate = 'receive_date';
382 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
386 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
387 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
388 $queryDate = 'receive_date';
389 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
393 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
394 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
395 $queryDate = 'scheduled_date';
396 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
400 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
401 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
402 $queryDate = 'scheduled_date';
403 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
408 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
411 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
414 $whereCond = implode(' AND ', $where);
417 SELECT $select, cp.currency
423 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
427 while ($dao->fetch()) {
428 $count +
= $dao->received_count
;
429 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
433 return array_merge($pledge_amount, array(
434 'received_amount' => implode(', ', $amount),
435 'received_count' => $count,
436 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
437 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
443 return $pledge_amount;
449 * Get list of pledges In Honor of contact Ids
451 * @param int $honorId
452 * In Honor of Contact ID.
454 * @return array return the list of pledge fields
458 public static function getHonorContacts($honorId) {
460 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
461 $honorDAO->contact_id
= $honorId;
465 while ($honorDAO->fetch()) {
466 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
467 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
468 if ($pledgePaymentDAO->find(TRUE)) {
469 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
470 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
471 if ($pledgeDAO->find(TRUE)) {
472 $params[$pledgeDAO->id
] = array(
473 'honor_type' => CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value'),
474 'honorId' => $pledgeDAO->contact_id
,
475 'amount' => $pledgeDAO->amount
,
476 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
477 'create_date' => $pledgeDAO->create_date
,
478 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
479 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
480 $pledgeDAO->financial_type_id
, 'name'
482 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
483 $pledgeDAO->contact_id
, 'display_name'
494 * Send Acknowledgment and create activity.
496 * @param CRM_Core_Form $form
498 * @param array $params
499 * An assoc array of name/value pairs.
503 public static function sendAcknowledgment(&$form, $params) {
504 //handle Acknowledgment.
505 $allPayments = $payments = array();
507 //get All Payments status types.
508 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
509 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
510 //get all paymnets details.
511 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
513 if (!empty($allPayments)) {
514 foreach ($allPayments as $payID => $values) {
515 $contributionValue = $contributionStatus = array();
516 if (isset($values['contribution_id'])) {
517 $contributionParams = array('id' => $values['contribution_id']);
518 $returnProperties = array('contribution_status_id', 'receive_date');
519 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
520 $contributionParams, $contributionStatus, $returnProperties
522 $contributionValue = array(
523 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
524 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
527 $payments[$payID] = array_merge($contributionValue,
529 'amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
530 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
534 //get the first valid payment id.
535 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
536 $paymentStatusTypes[$values['status_id']] == 'Overdue'
538 $form->paymentId
= $values['id'];
543 //assign pledge fields value to template.
544 $pledgeFields = array(
545 'create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit',
546 'installments', 'frequency_day', 'scheduled_amount', 'currency',
548 foreach ($pledgeFields as $field) {
549 if (!empty($params[$field])) {
550 $form->assign($field, $params[$field]);
554 //assign all payments details.
556 $form->assign('payments', $payments);
559 //handle domain token values
560 $domain = CRM_Core_BAO_Domain
::getDomain();
562 'domain' => array('name', 'phone', 'address', 'email'),
563 'contact' => CRM_Core_SelectValues
::contactTokens(),
565 $domainValues = array();
566 foreach ($tokens['domain'] as $token) {
567 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
569 $form->assign('domain', $domainValues);
571 //handle contact token values.
572 $ids = array($params['contact_id']);
573 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
574 array('display_name', 'checksum', 'contact_id')
576 foreach ($fields as $key => $val) {
577 $returnProperties[$val] = TRUE;
579 $details = CRM_Utils_Token
::getTokenDetails($ids,
585 $form->assign('contact', $details[0][$params['contact_id']]);
587 //handle custom data.
588 if (!empty($params['hidden_custom'])) {
589 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
590 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
591 $customGroup = array();
592 // retrieve custom data
593 foreach ($groupTree as $groupID => $group) {
594 $customFields = $customValues = array();
595 if ($groupID == 'info') {
598 foreach ($group['fields'] as $k => $field) {
599 $field['title'] = $field['label'];
600 $customFields["custom_{$k}"] = $field;
603 //to build array of customgroup & customfields in it
604 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
605 $customGroup[$group['title']] = $customValues;
608 $form->assign('customGroup', $customGroup);
611 //handle acknowledgment email stuff.
612 list($pledgerDisplayName,
614 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
616 //check for online pledge.
617 $session = CRM_Core_Session
::singleton();
618 if (!empty($params['receipt_from_email'])) {
619 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
620 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
622 elseif (!empty($params['from_email_id'])) {
623 $receiptFrom = $params['from_email_id'];
625 elseif ($userID = $session->get('userID')) {
626 //check for logged in user.
627 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
630 //set the domain values.
631 $userName = CRM_Utils_Array
::value('name', $domainValues);
632 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
635 if (!isset($receiptFrom)) {
636 $receiptFrom = "$userName <$userEmail>";
639 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
641 'groupName' => 'msg_tpl_workflow_pledge',
642 'valueName' => 'pledge_acknowledge',
643 'contactId' => $params['contact_id'],
644 'from' => $receiptFrom,
645 'toName' => $pledgerDisplayName,
646 'toEmail' => $pledgerEmail,
650 //check if activity record exist for this pledge
651 //Acknowledgment, if exist do not add activity.
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',
659 $config = CRM_Core_Config
::singleton();
662 $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)';
664 if (!$activity->find()) {
665 $activityParams = array(
666 'subject' => $subject,
667 'source_contact_id' => $params['contact_id'],
668 'source_record_id' => $params['id'],
669 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
673 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
674 'is_test' => $params['is_test'],
676 'details' => $details,
677 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
680 //lets insert assignee record.
681 if (!empty($params['contact_id'])) {
682 $activityParams['assignee_contact_id'] = $params['contact_id'];
685 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
686 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
692 * Combine all the exportable fields from the lower levels object
694 * @return array array of exportable Fields
697 public static function &exportableFields() {
698 if (!self
::$_exportableFields) {
699 if (!self
::$_exportableFields) {
700 self
::$_exportableFields = array();
703 $fields = CRM_Pledge_DAO_Pledge
::export();
705 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
707 //set title to calculated fields
708 $calculatedFields = array(
709 'pledge_total_paid' => array('title' => ts('Total Paid')),
710 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
711 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
712 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
713 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
714 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
715 'pledge_payment_status' => array(
716 'title' => ts('Pledge Payment Status'),
717 'name' => 'pledge_payment_status',
718 'data_type' => CRM_Utils_Type
::T_STRING
,
722 $pledgeFields = array(
723 'pledge_status' => array(
724 'title' => 'Pledge Status',
725 'name' => 'pledge_status',
726 'data_type' => CRM_Utils_Type
::T_STRING
,
728 'pledge_frequency_unit' => array(
729 'title' => 'Pledge Frequency Unit',
730 'name' => 'pledge_frequency_unit',
731 'data_type' => CRM_Utils_Type
::T_ENUM
,
733 'pledge_frequency_interval' => array(
734 'title' => 'Pledge Frequency Interval',
735 'name' => 'pledge_frequency_interval',
736 'data_type' => CRM_Utils_Type
::T_INT
,
738 'pledge_contribution_page_id' => array(
739 'title' => 'Pledge Contribution Page Id',
740 'name' => 'pledge_contribution_page_id',
741 'data_type' => CRM_Utils_Type
::T_INT
,
745 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
748 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
749 self
::$_exportableFields = $fields;
752 return self
::$_exportableFields;
756 * Get pending or in progress pledges
758 * @param int $contactID
761 * @return array associated array of pledge id(s)
764 public static function getContactPledges($contactID) {
765 $pledgeDetails = array();
766 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
770 //get pending and in progress status
772 'Pending', 'In Progress', 'Overdue') as $name) {
773 if ($statusId = array_search($name, $pledgeStatuses)) {
774 $status[] = $statusId;
777 if (empty($status)) {
778 return $pledgeDetails;
781 $statusClause = " IN (" . implode(',', $status) . ")";
784 SELECT civicrm_pledge.id id
786 WHERE civicrm_pledge.status_id {$statusClause}
787 AND civicrm_pledge.contact_id = %1
790 $params[1] = array($contactID, 'Integer');
791 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
793 while ($pledge->fetch()) {
794 $pledgeDetails[] = $pledge->id
;
797 return $pledgeDetails;
801 * Get pledge record count for a Contact
803 * @param int $contactID
805 * @return int count of pledge records
808 public static function getContactPledgeCount($contactID) {
809 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
810 return CRM_Core_DAO
::singleValueQuery($query);
814 * @param array $params
818 public static function updatePledgeStatus($params) {
820 $returnMessages = array();
822 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
824 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
826 //unset statues that we never use for pledges
828 'Completed', 'Cancelled', 'Failed') as $statusKey) {
829 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
830 unset($allStatus[$key]);
834 $statusIds = implode(',', array_keys($allStatus));
838 SELECT pledge.contact_id as contact_id,
839 pledge.id as pledge_id,
840 pledge.amount as amount,
841 payment.scheduled_date as scheduled_date,
842 pledge.create_date as create_date,
843 payment.id as payment_id,
844 pledge.currency as currency,
845 pledge.contribution_page_id as contribution_page_id,
846 payment.reminder_count as reminder_count,
847 pledge.max_reminders as max_reminders,
848 payment.reminder_date as reminder_date,
849 pledge.initial_reminder_day as initial_reminder_day,
850 pledge.additional_reminder_day as additional_reminder_day,
851 pledge.status_id as pledge_status,
852 payment.status_id as payment_status,
853 pledge.is_test as is_test,
854 pledge.campaign_id as campaign_id,
855 SUM(payment.scheduled_amount) as amount_due,
856 ( SELECT sum(civicrm_pledge_payment.actual_amount)
857 FROM civicrm_pledge_payment
858 WHERE civicrm_pledge_payment.status_id = 1
859 AND civicrm_pledge_payment.pledge_id = pledge.id
861 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
862 WHERE pledge.id = payment.pledge_id
863 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
867 $dao = CRM_Core_DAO
::executeQuery($query);
870 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
871 while ($dao->fetch()) {
872 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
874 $pledgeDetails[$dao->payment_id
] = array(
875 'scheduled_date' => $dao->scheduled_date
,
876 'amount_due' => $dao->amount_due
,
877 'amount' => $dao->amount
,
878 'amount_paid' => $dao->amount_paid
,
879 'create_date' => $dao->create_date
,
880 'contact_id' => $dao->contact_id
,
881 'pledge_id' => $dao->pledge_id
,
882 'checksumValue' => $checksumValue,
883 'contribution_page_id' => $dao->contribution_page_id
,
884 'reminder_count' => $dao->reminder_count
,
885 'max_reminders' => $dao->max_reminders
,
886 'reminder_date' => $dao->reminder_date
,
887 'initial_reminder_day' => $dao->initial_reminder_day
,
888 'additional_reminder_day' => $dao->additional_reminder_day
,
889 'pledge_status' => $dao->pledge_status
,
890 'payment_status' => $dao->payment_status
,
891 'is_test' => $dao->is_test
,
892 'currency' => $dao->currency
,
893 'campaign_id' => $dao->campaign_id
,
896 $contactIds[$dao->contact_id
] = $dao->contact_id
;
897 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
899 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
901 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)) {
902 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
906 // process the updating script...
908 foreach ($pledgePayments as $pledgeId => $paymentIds) {
909 // 1. update the pledge /pledge payment status. returns new status when an update happens
910 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
912 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
913 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
915 if ($newStatus != $pledgeStatus[$pledgeId]) {
916 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
921 if ($sendReminders) {
922 // retrieve domain tokens
923 $domain = CRM_Core_BAO_Domain
::getDomain();
925 'domain' => array('name', 'phone', 'address', 'email'),
926 'contact' => CRM_Core_SelectValues
::contactTokens(),
929 $domainValues = array();
930 foreach ($tokens['domain'] as $token) {
931 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
934 //get the domain email address, since we don't carry w/ object.
935 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
936 $domainValues['email'] = $domainValue[1];
938 // retrieve contact tokens
940 // this function does NOT return Deceased contacts since we don't want to send them email
941 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
944 $tokens, 'CRM_UpdatePledgeRecord'
947 // assign domain values to template
948 $template = CRM_Core_Smarty
::singleton();
949 $template->assign('domain', $domainValues);
952 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
954 foreach ($pledgeDetails as $paymentId => $details) {
955 if (array_key_exists($details['contact_id'], $contactDetails)) {
956 $contactId = $details['contact_id'];
957 $pledgerName = $contactDetails[$contactId]['display_name'];
963 if (empty($details['reminder_date'])) {
964 $nextReminderDate = new DateTime($details['scheduled_date']);
965 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
966 $nextReminderDate = $nextReminderDate->format("Ymd");
969 $nextReminderDate = new DateTime($details['reminder_date']);
970 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
971 $nextReminderDate = $nextReminderDate->format("Ymd");
973 if (($details['reminder_count'] < $details['max_reminders'])
974 && ($nextReminderDate <= $now)
977 $toEmail = $doNotEmail = $onHold = NULL;
979 if (!empty($contactDetails[$contactId]['email'])) {
980 $toEmail = $contactDetails[$contactId]['email'];
983 if (!empty($contactDetails[$contactId]['do_not_email'])) {
984 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
987 if (!empty($contactDetails[$contactId]['on_hold'])) {
988 $onHold = $contactDetails[$contactId]['on_hold'];
991 // 2. send acknowledgement mail
992 if ($toEmail && !($doNotEmail ||
$onHold)) {
993 //assign value to template
994 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
995 $template->assign('contact', $contactDetails[$contactId]);
996 $template->assign('next_payment', $details['scheduled_date']);
997 $template->assign('amount_due', $details['amount_due']);
998 $template->assign('checksumValue', $details['checksumValue']);
999 $template->assign('contribution_page_id', $details['contribution_page_id']);
1000 $template->assign('pledge_id', $details['pledge_id']);
1001 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1002 $template->assign('amount', $details['amount']);
1003 $template->assign('create_date', $details['create_date']);
1004 $template->assign('currency', $details['currency']);
1005 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1007 'groupName' => 'msg_tpl_workflow_pledge',
1008 'valueName' => 'pledge_reminder',
1009 'contactId' => $contactId,
1010 'from' => $receiptFrom,
1011 'toName' => $pledgerName,
1012 'toEmail' => $toEmail,
1016 // 3. update pledge payment details
1018 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1019 $activityType = 'Pledge Reminder';
1020 $activityParams = array(
1021 'subject' => $subject,
1022 'source_contact_id' => $contactId,
1023 'source_record_id' => $paymentId,
1024 'assignee_contact_id' => $contactId,
1025 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1029 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1030 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1031 'is_test' => $details['is_test'],
1033 'campaign_id' => $details['campaign_id'],
1035 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1036 $returnMessages[] = "Failed creating Activity for acknowledgment";
1037 return array('is_error' => 1, 'message' => $returnMessages);
1039 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1044 // end foreach on $pledgeDetails
1046 // end if ( $sendReminders )
1047 $returnMessages[] = "{$updateCnt} records updated.";
1049 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1053 * Mark a pledge (and any outstanding payments) as cancelled.
1055 * @param int $pledgeID
1057 public static function cancel($pledgeID) {
1058 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1059 $paymentIDs = self
::findCancelablePayments($pledgeID);
1060 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1061 $statuses['Cancelled'], 0, FALSE, TRUE
1066 * Find payments which can be safely canceled.
1068 * @param int $pledgeID
1069 * @return array of int (civicrm_pledge_payment.id)
1071 public static function findCancelablePayments($pledgeID) {
1072 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1074 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1075 $paymentDAO->pledge_id
= $pledgeID;
1076 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1077 $statuses['Overdue'],
1078 $statuses['Pending']
1080 $paymentDAO->find();
1082 $paymentIDs = array();
1083 while ($paymentDAO->fetch()) {
1084 $paymentIDs[] = $paymentDAO->id
;
1090 * Is this pledge free from financial transactions (this is important to know as we allow editing
1091 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1092 * & recreating so we want to block that if appropriate
1094 * @param int $pledgeID
1095 * @param int $pledgeStatusID
1096 * @return bool do financial transactions exist for this pledge?
1098 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1099 if (empty($pledgeStatusID)) {
1100 //why would this happen? If we can see where it does then we can see if we should look it up
1101 //but assuming from form code it CAN be empty
1104 if (self
::isTransactedStatus($pledgeStatusID)) {
1108 return civicrm_api3('pledge_payment', 'getcount', array('pledge_id' => $pledgeID, 'status_id' => array('IN' => self
::getTransactionalStatus())));
1112 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1113 * @param int $statusID
1116 * @return bool is it a transactional status?
1118 protected static function isTransactedStatus($statusID) {
1119 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1126 * Get array of non transactional statuses
1127 * @return array non transactional status ids
1129 protected static function getNonTransactionalStatus() {
1130 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1131 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1135 * Get array of non transactional statuses
1136 * @return array non transactional status ids
1138 protected static function getTransactionalStatus() {
1139 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1140 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());