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 (reference ) an assoc array of name/value pairs
60 * @param array $defaults (reference ) an assoc array to hold the flattened values
62 * @return CRM_Pledge_BAO_Pledge object
65 public static function retrieve(&$params, &$defaults) {
66 $pledge = new CRM_Pledge_DAO_Pledge();
67 $pledge->copyValues($params);
68 if ($pledge->find(TRUE)) {
69 CRM_Core_DAO
::storeValues($pledge, $defaults);
78 * @param array $params reference array contains the values submitted by the form
84 public static function add(&$params) {
85 if (!empty($params['id'])) {
86 CRM_Utils_Hook
::pre('edit', 'Pledge', $params['id'], $params);
89 CRM_Utils_Hook
::pre('create', 'Pledge', NULL, $params);
92 $pledge = new CRM_Pledge_DAO_Pledge();
94 // if pledge is complete update end date as current date
95 if ($pledge->status_id
== 1) {
96 $pledge->end_date
= date('Ymd');
99 $pledge->copyValues($params);
101 // set currency for CRM-1496
102 if (!isset($pledge->currency
)) {
103 $config = CRM_Core_Config
::singleton();
104 $pledge->currency
= $config->defaultCurrency
;
107 $result = $pledge->save();
109 if (!empty($params['id'])) {
110 CRM_Utils_Hook
::post('edit', 'Pledge', $pledge->id
, $pledge);
113 CRM_Utils_Hook
::post('create', 'Pledge', $pledge->id
, $pledge);
120 * Given the list of params in the params array, fetch the object
121 * and store the values in the values array
123 * @param array $params input parameters to find object
124 * @param array $values output values of the object
125 * @param array $returnProperties if you want to return specific fields
127 * @return array associated array of field values
130 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
131 if (empty($params)) {
134 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
139 * Takes an associative array and creates a pledge object
141 * @param array $params (reference ) an assoc array of name/value pairs
143 * @return CRM_Pledge_BAO_Pledge object
146 public static function &create(&$params) {
147 //FIXME: a cludgy hack to fix the dates to MySQL format
148 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
149 foreach ($dateFields as $df) {
150 if (isset($params[$df])) {
151 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
155 $transaction = new CRM_Core_Transaction();
157 $paymentParams = array();
158 $paymentParams['status_id'] = CRM_Utils_Array
::value('status_id', $params);
159 if (!empty($params['installment_amount'])) {
160 $params['amount'] = $params['installment_amount'] * $params['installments'];
163 //get All Payments status types.
164 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
166 //update the pledge status only if it does NOT come from form
167 if (!isset($params['pledge_status_id'])) {
168 if (isset($params['contribution_id'])) {
169 if ($params['installments'] > 1) {
170 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
174 if (!empty($params['id'])) {
175 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
178 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
183 $pledge = self
::add($params);
184 if (is_a($pledge, 'CRM_Core_Error')) {
189 //handle custom data.
190 if (!empty($params['custom']) &&
191 is_array($params['custom'])
193 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
196 // skip payment stuff inedit mode
197 if (!isset($params['id']) ||
!empty($params['is_pledge_pending'])) {
200 //if pledge is pending delete all payments and recreate.
201 if (!empty($params['is_pledge_pending'])) {
202 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
205 //building payment params
206 $paymentParams['pledge_id'] = $pledge->id
;
207 $paymentKeys = array(
208 'amount', 'installments', 'scheduled_date', 'frequency_unit', 'currency',
209 'frequency_day', 'frequency_interval', 'contribution_id', 'installment_amount', 'actual_amount',
211 foreach ($paymentKeys as $key) {
212 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
214 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
217 $transaction->commit();
219 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
220 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
223 $recentOther = array();
224 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
225 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
226 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
229 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
230 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
231 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
235 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
236 $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) . ')';
238 // add the recently created Pledge
239 CRM_Utils_Recent
::add($title,
254 * @param int $id pledge id
260 public static function deletePledge($id) {
261 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
263 $transaction = new CRM_Core_Transaction();
265 //check for no Completed Payment records with the pledge
266 $payment = new CRM_Pledge_DAO_PledgePayment();
267 $payment->pledge_id
= $id;
270 while ($payment->fetch()) {
271 //also delete associated contribution.
272 if ($payment->contribution_id
) {
273 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
278 $dao = new CRM_Pledge_DAO_Pledge();
280 $results = $dao->delete();
282 $transaction->commit();
284 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
286 // delete the recently created Pledge
287 $pledgeRecent = array(
291 CRM_Utils_Recent
::del($pledgeRecent);
297 * Get the amount details date wise.
299 * @param string $status
300 * @param string $startDate
301 * @param string $endDate
305 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
307 $select = $from = $queryDate = NULL;
309 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
310 $statusId = array_search($status, $allStatus);
314 $statusId = array_search('Cancelled', $allStatus);
315 $where[] = 'status_id != ' . $statusId;
319 $where[] = 'status_id = ' . $statusId;
323 $where[] = 'status_id = ' . $statusId;
327 $where[] = 'status_id = ' . $statusId;
331 $where[] = 'status_id = ' . $statusId;
336 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
339 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
342 $whereCond = implode(' AND ', $where);
345 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
347 WHERE $whereCond AND is_test=0
350 $start = substr($startDate, 0, 8);
351 $end = substr($endDate, 0, 8);
354 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
355 while ($dao->fetch()) {
356 $pCount +
= $dao->pledge_count
;
357 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
360 $pledge_amount = array('pledge_amount' => implode(', ', $pamount),
361 'pledge_count' => $pCount,
362 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
363 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
368 $statusId = array_search($status, $allStatus);
371 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
372 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
373 $queryDate = 'receive_date';
374 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
378 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
379 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
380 $queryDate = 'receive_date';
381 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
385 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
386 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
387 $queryDate = 'scheduled_date';
388 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
392 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
393 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
394 $queryDate = 'scheduled_date';
395 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
400 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
403 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
406 $whereCond = implode(' AND ', $where);
409 SELECT $select, cp.currency
415 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
419 while ($dao->fetch()) {
420 $count +
= $dao->received_count
;
421 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
425 return array_merge($pledge_amount, array('received_amount' => implode(', ', $amount),
426 'received_count' => $count,
427 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
428 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
434 return $pledge_amount;
440 * Get list of pledges In Honor of contact Ids
442 * @param int $honorId In Honor of Contact ID
444 * @return array return the list of pledge fields
448 public static function getHonorContacts($honorId) {
450 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
451 $honorDAO->contact_id
= $honorId;
455 while ($honorDAO->fetch()) {
456 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
457 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
458 if ($pledgePaymentDAO->find(TRUE)) {
459 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
460 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
461 if ($pledgeDAO->find(TRUE)) {
462 $params[$pledgeDAO->id
] = array(
463 'honor_type' => CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value'),
464 'honorId' => $pledgeDAO->contact_id
,
465 'amount' => $pledgeDAO->amount
,
466 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
467 'create_date' => $pledgeDAO->create_date
,
468 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
469 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
470 $pledgeDAO->financial_type_id
, 'name'
472 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
473 $pledgeDAO->contact_id
, 'display_name'
484 * Send Acknowledgment and create activity.
486 * @param CRM_Core_Form $form form object.
487 * @param array $params an assoc array of name/value pairs.
491 public static function sendAcknowledgment(&$form, $params) {
492 //handle Acknowledgment.
493 $allPayments = $payments = array();
495 //get All Payments status types.
496 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
497 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
498 //get all paymnets details.
499 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
501 if (!empty($allPayments)) {
502 foreach ($allPayments as $payID => $values) {
503 $contributionValue = $contributionStatus = array();
504 if (isset($values['contribution_id'])) {
505 $contributionParams = array('id' => $values['contribution_id']);
506 $returnProperties = array('contribution_status_id', 'receive_date');
507 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
508 $contributionParams, $contributionStatus, $returnProperties
510 $contributionValue = array(
511 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
512 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
515 $payments[$payID] = array_merge($contributionValue,
516 array('amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
517 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
521 //get the first valid payment id.
522 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
523 $paymentStatusTypes[$values['status_id']] == 'Overdue'
525 $form->paymentId
= $values['id'];
530 //assign pledge fields value to template.
531 $pledgeFields = array(
532 'create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit',
533 'installments', 'frequency_day', 'scheduled_amount', 'currency',
535 foreach ($pledgeFields as $field) {
536 if (!empty($params[$field])) {
537 $form->assign($field, $params[$field]);
541 //assign all payments details.
543 $form->assign('payments', $payments);
546 //handle domain token values
547 $domain = CRM_Core_BAO_Domain
::getDomain();
548 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
549 'contact' => CRM_Core_SelectValues
::contactTokens(),
551 $domainValues = array();
552 foreach ($tokens['domain'] as $token) {
553 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
555 $form->assign('domain', $domainValues);
557 //handle contact token values.
558 $ids = array($params['contact_id']);
559 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
560 array('display_name', 'checksum', 'contact_id')
562 foreach ($fields as $key => $val) {
563 $returnProperties[$val] = TRUE;
565 $details = CRM_Utils_Token
::getTokenDetails($ids,
571 $form->assign('contact', $details[0][$params['contact_id']]);
573 //handle custom data.
574 if (!empty($params['hidden_custom'])) {
575 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
576 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
577 $customGroup = array();
578 // retrieve custom data
579 foreach ($groupTree as $groupID => $group) {
580 $customFields = $customValues = array();
581 if ($groupID == 'info') {
584 foreach ($group['fields'] as $k => $field) {
585 $field['title'] = $field['label'];
586 $customFields["custom_{$k}"] = $field;
589 //to build array of customgroup & customfields in it
590 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
591 $customGroup[$group['title']] = $customValues;
594 $form->assign('customGroup', $customGroup);
597 //handle acknowledgment email stuff.
598 list($pledgerDisplayName,
600 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
602 //check for online pledge.
603 $session = CRM_Core_Session
::singleton();
604 if (!empty($params['receipt_from_email'])) {
605 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
606 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
608 elseif (!empty($params['from_email_id'])) {
609 $receiptFrom = $params['from_email_id'];
611 elseif ($userID = $session->get('userID')) {
612 //check for logged in user.
613 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
616 //set the domain values.
617 $userName = CRM_Utils_Array
::value('name', $domainValues);
618 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
621 if (!isset($receiptFrom)) {
622 $receiptFrom = "$userName <$userEmail>";
625 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
627 'groupName' => 'msg_tpl_workflow_pledge',
628 'valueName' => 'pledge_acknowledge',
629 'contactId' => $params['contact_id'],
630 'from' => $receiptFrom,
631 'toName' => $pledgerDisplayName,
632 'toEmail' => $pledgerEmail,
636 //check if activity record exist for this pledge
637 //Acknowledgment, if exist do not add activity.
638 $activityType = 'Pledge Acknowledgment';
639 $activity = new CRM_Activity_DAO_Activity();
640 $activity->source_record_id
= $params['id'];
641 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
645 $config = CRM_Core_Config
::singleton();
648 $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)';
650 if (!$activity->find()) {
651 $activityParams = array(
652 'subject' => $subject,
653 'source_contact_id' => $params['contact_id'],
654 'source_record_id' => $params['id'],
655 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
659 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
660 'is_test' => $params['is_test'],
662 'details' => $details,
663 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
666 //lets insert assignee record.
667 if (!empty($params['contact_id'])) {
668 $activityParams['assignee_contact_id'] = $params['contact_id'];
671 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
672 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
678 * Combine all the exportable fields from the lower levels object
680 * @return array array of exportable Fields
683 public static function &exportableFields() {
684 if (!self
::$_exportableFields) {
685 if (!self
::$_exportableFields) {
686 self
::$_exportableFields = array();
689 $fields = CRM_Pledge_DAO_Pledge
::export();
691 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
693 //set title to calculated fields
694 $calculatedFields = array('pledge_total_paid' => array('title' => ts('Total Paid')),
695 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
696 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
697 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
698 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
699 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
700 'pledge_payment_status' => array('title' => ts('Pledge Payment Status'),
701 'name' => 'pledge_payment_status',
702 'data_type' => CRM_Utils_Type
::T_STRING
,
707 $pledgeFields = array(
708 'pledge_status' => array('title' => 'Pledge Status',
709 'name' => 'pledge_status',
710 'data_type' => CRM_Utils_Type
::T_STRING
,
712 'pledge_frequency_unit' => array(
713 'title' => 'Pledge Frequency Unit',
714 'name' => 'pledge_frequency_unit',
715 'data_type' => CRM_Utils_Type
::T_ENUM
,
717 'pledge_frequency_interval' => array(
718 'title' => 'Pledge Frequency Interval',
719 'name' => 'pledge_frequency_interval',
720 'data_type' => CRM_Utils_Type
::T_INT
,
722 'pledge_contribution_page_id' => array(
723 'title' => 'Pledge Contribution Page Id',
724 'name' => 'pledge_contribution_page_id',
725 'data_type' => CRM_Utils_Type
::T_INT
,
729 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
732 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
733 self
::$_exportableFields = $fields;
736 return self
::$_exportableFields;
740 * Get pending or in progress pledges
742 * @param int $contactID contact id
744 * @return array associated array of pledge id(s)
747 public static function getContactPledges($contactID) {
748 $pledgeDetails = array();
749 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
753 //get pending and in progress status
755 'Pending', 'In Progress', 'Overdue') as $name) {
756 if ($statusId = array_search($name, $pledgeStatuses)) {
757 $status[] = $statusId;
760 if (empty($status)) {
761 return $pledgeDetails;
764 $statusClause = " IN (" . implode(',', $status) . ")";
767 SELECT civicrm_pledge.id id
769 WHERE civicrm_pledge.status_id {$statusClause}
770 AND civicrm_pledge.contact_id = %1
773 $params[1] = array($contactID, 'Integer');
774 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
776 while ($pledge->fetch()) {
777 $pledgeDetails[] = $pledge->id
;
780 return $pledgeDetails;
784 * Get pledge record count for a Contact
786 * @param int $contactID
788 * @return int count of pledge records
791 public static function getContactPledgeCount($contactID) {
792 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
793 return CRM_Core_DAO
::singleValueQuery($query);
797 * @param array $params
801 public static function updatePledgeStatus($params) {
803 $returnMessages = array();
805 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
807 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
809 //unset statues that we never use for pledges
811 'Completed', 'Cancelled', 'Failed') as $statusKey) {
812 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
813 unset($allStatus[$key]);
817 $statusIds = implode(',', array_keys($allStatus));
821 SELECT pledge.contact_id as contact_id,
822 pledge.id as pledge_id,
823 pledge.amount as amount,
824 payment.scheduled_date as scheduled_date,
825 pledge.create_date as create_date,
826 payment.id as payment_id,
827 pledge.currency as currency,
828 pledge.contribution_page_id as contribution_page_id,
829 payment.reminder_count as reminder_count,
830 pledge.max_reminders as max_reminders,
831 payment.reminder_date as reminder_date,
832 pledge.initial_reminder_day as initial_reminder_day,
833 pledge.additional_reminder_day as additional_reminder_day,
834 pledge.status_id as pledge_status,
835 payment.status_id as payment_status,
836 pledge.is_test as is_test,
837 pledge.campaign_id as campaign_id,
838 SUM(payment.scheduled_amount) as amount_due,
839 ( SELECT sum(civicrm_pledge_payment.actual_amount)
840 FROM civicrm_pledge_payment
841 WHERE civicrm_pledge_payment.status_id = 1
842 AND civicrm_pledge_payment.pledge_id = pledge.id
844 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
845 WHERE pledge.id = payment.pledge_id
846 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
850 $dao = CRM_Core_DAO
::executeQuery($query);
853 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
854 while ($dao->fetch()) {
855 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
857 $pledgeDetails[$dao->payment_id
] = array(
858 'scheduled_date' => $dao->scheduled_date
,
859 'amount_due' => $dao->amount_due
,
860 'amount' => $dao->amount
,
861 'amount_paid' => $dao->amount_paid
,
862 'create_date' => $dao->create_date
,
863 'contact_id' => $dao->contact_id
,
864 'pledge_id' => $dao->pledge_id
,
865 'checksumValue' => $checksumValue,
866 'contribution_page_id' => $dao->contribution_page_id
,
867 'reminder_count' => $dao->reminder_count
,
868 'max_reminders' => $dao->max_reminders
,
869 'reminder_date' => $dao->reminder_date
,
870 'initial_reminder_day' => $dao->initial_reminder_day
,
871 'additional_reminder_day' => $dao->additional_reminder_day
,
872 'pledge_status' => $dao->pledge_status
,
873 'payment_status' => $dao->payment_status
,
874 'is_test' => $dao->is_test
,
875 'currency' => $dao->currency
,
876 'campaign_id' => $dao->campaign_id
,
879 $contactIds[$dao->contact_id
] = $dao->contact_id
;
880 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
882 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
884 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)) {
885 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
889 // process the updating script...
891 foreach ($pledgePayments as $pledgeId => $paymentIds) {
892 // 1. update the pledge /pledge payment status. returns new status when an update happens
893 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
895 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
896 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
898 if ($newStatus != $pledgeStatus[$pledgeId]) {
899 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
904 if ($sendReminders) {
905 // retrieve domain tokens
906 $domain = CRM_Core_BAO_Domain
::getDomain();
907 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
908 'contact' => CRM_Core_SelectValues
::contactTokens(),
911 $domainValues = array();
912 foreach ($tokens['domain'] as $token) {
913 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
916 //get the domain email address, since we don't carry w/ object.
917 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
918 $domainValues['email'] = $domainValue[1];
920 // retrieve contact tokens
922 // this function does NOT return Deceased contacts since we don't want to send them email
923 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
926 $tokens, 'CRM_UpdatePledgeRecord'
929 // assign domain values to template
930 $template = CRM_Core_Smarty
::singleton();
931 $template->assign('domain', $domainValues);
934 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
936 foreach ($pledgeDetails as $paymentId => $details) {
937 if (array_key_exists($details['contact_id'], $contactDetails)) {
938 $contactId = $details['contact_id'];
939 $pledgerName = $contactDetails[$contactId]['display_name'];
945 if (empty($details['reminder_date'])) {
946 $nextReminderDate = new DateTime($details['scheduled_date']);
947 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
948 $nextReminderDate = $nextReminderDate->format("Ymd");
951 $nextReminderDate = new DateTime($details['reminder_date']);
952 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
953 $nextReminderDate = $nextReminderDate->format("Ymd");
955 if (($details['reminder_count'] < $details['max_reminders'])
956 && ($nextReminderDate <= $now)
959 $toEmail = $doNotEmail = $onHold = NULL;
961 if (!empty($contactDetails[$contactId]['email'])) {
962 $toEmail = $contactDetails[$contactId]['email'];
965 if (!empty($contactDetails[$contactId]['do_not_email'])) {
966 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
969 if (!empty($contactDetails[$contactId]['on_hold'])) {
970 $onHold = $contactDetails[$contactId]['on_hold'];
973 // 2. send acknowledgement mail
974 if ($toEmail && !($doNotEmail ||
$onHold)) {
975 //assign value to template
976 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
977 $template->assign('contact', $contactDetails[$contactId]);
978 $template->assign('next_payment', $details['scheduled_date']);
979 $template->assign('amount_due', $details['amount_due']);
980 $template->assign('checksumValue', $details['checksumValue']);
981 $template->assign('contribution_page_id', $details['contribution_page_id']);
982 $template->assign('pledge_id', $details['pledge_id']);
983 $template->assign('scheduled_payment_date', $details['scheduled_date']);
984 $template->assign('amount', $details['amount']);
985 $template->assign('create_date', $details['create_date']);
986 $template->assign('currency', $details['currency']);
987 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
989 'groupName' => 'msg_tpl_workflow_pledge',
990 'valueName' => 'pledge_reminder',
991 'contactId' => $contactId,
992 'from' => $receiptFrom,
993 'toName' => $pledgerName,
994 'toEmail' => $toEmail,
998 // 3. update pledge payment details
1000 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1001 $activityType = 'Pledge Reminder';
1002 $activityParams = array(
1003 'subject' => $subject,
1004 'source_contact_id' => $contactId,
1005 'source_record_id' => $paymentId,
1006 'assignee_contact_id' => $contactId,
1007 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1011 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1012 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1013 'is_test' => $details['is_test'],
1015 'campaign_id' => $details['campaign_id'],
1017 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1018 $returnMessages[] = "Failed creating Activity for acknowledgment";
1019 return array('is_error' => 1, 'message' => $returnMessages);
1021 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1026 // end foreach on $pledgeDetails
1028 // end if ( $sendReminders )
1029 $returnMessages[] = "{$updateCnt} records updated.";
1031 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1035 * Mark a pledge (and any outstanding payments) as cancelled.
1037 * @param int $pledgeID
1039 public static function cancel($pledgeID) {
1040 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1041 $paymentIDs = self
::findCancelablePayments($pledgeID);
1042 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1043 $statuses['Cancelled'], 0, FALSE, TRUE
1048 * Find payments which can be safely canceled.
1050 * @param int $pledgeID
1051 * @return array of int (civicrm_pledge_payment.id)
1053 public static function findCancelablePayments($pledgeID) {
1054 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1056 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1057 $paymentDAO->pledge_id
= $pledgeID;
1058 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1059 $statuses['Overdue'],
1060 $statuses['Pending']
1062 $paymentDAO->find();
1064 $paymentIDs = array();
1065 while ($paymentDAO->fetch()) {
1066 $paymentIDs[] = $paymentDAO->id
;
1072 * Is this pledge free from financial transactions (this is important to know as we allow editing
1073 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1074 * & recreating so we want to block that if appropriate
1076 * @param integer $pledgeID
1077 * @param integer $pledgeStatusID
1078 * @return bool do financial transactions exist for this pledge?
1080 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1081 if (empty($pledgeStatusID)) {
1082 //why would this happen? If we can see where it does then we can see if we should look it up
1083 //but assuming from form code it CAN be empty
1086 if (self
::isTransactedStatus($pledgeStatusID)) {
1090 return civicrm_api3('pledge_payment', 'getcount', array('pledge_id' => $pledgeID, 'status_id' => array('IN' => self
::getTransactionalStatus())));
1094 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1095 * @param int $statusID pledge status id
1097 * @return bool is it a transactional status?
1099 protected static function isTransactedStatus($statusID) {
1100 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1107 * Get array of non transactional statuses
1108 * @return array non transactional status ids
1110 protected static function getNonTransactionalStatus() {
1111 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1112 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1116 * Get array of non transactional statuses
1117 * @return array non transactional status ids
1119 protected static function getTransactionalStatus() {
1120 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1121 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());