3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 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 object CRM_Pledge_BAO_Pledge object
66 static function retrieve(&$params, &$defaults) {
67 $pledge = new CRM_Pledge_DAO_Pledge();
68 $pledge->copyValues($params);
69 if ($pledge->find(TRUE)) {
70 CRM_Core_DAO
::storeValues($pledge, $defaults);
77 * function to add pledge
79 * @param array $params reference array contains the values submitted by the form
86 static function add(&$params) {
87 if (!empty($params['id'])) {
88 CRM_Utils_Hook
::pre('edit', 'Pledge', $params['id'], $params);
91 CRM_Utils_Hook
::pre('create', 'Pledge', NULL, $params);
94 $pledge = new CRM_Pledge_DAO_Pledge();
96 // if pledge is complete update end date as current date
97 if ($pledge->status_id
== 1) {
98 $pledge->end_date
= date('Ymd');
101 $pledge->copyValues($params);
103 // set currency for CRM-1496
104 if (!isset($pledge->currency
)) {
105 $config = CRM_Core_Config
::singleton();
106 $pledge->currency
= $config->defaultCurrency
;
109 $result = $pledge->save();
111 if (!empty($params['id'])) {
112 CRM_Utils_Hook
::post('edit', 'Pledge', $pledge->id
, $pledge);
115 CRM_Utils_Hook
::post('create', 'Pledge', $pledge->id
, $pledge);
122 * Given the list of params in the params array, fetch the object
123 * and store the values in the values array
125 * @param array $params input parameters to find object
126 * @param array $values output values of the object
127 * @param array $returnProperties if you want to return specific fields
129 * @return array associated array of field values
133 static function &getValues(&$params, &$values, $returnProperties = NULL) {
134 if (empty($params)) {
137 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
142 * takes an associative array and creates a pledge object
144 * @param array $params (reference ) an assoc array of name/value pairs
146 * @return object CRM_Pledge_BAO_Pledge object
150 static function &create(&$params) {
151 //FIXME: a cludgy hack to fix the dates to MySQL format
152 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
153 foreach ($dateFields as $df) {
154 if (isset($params[$df])) {
155 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
159 $transaction = new CRM_Core_Transaction();
161 $paymentParams = array();
162 $paymentParams['status_id'] = CRM_Utils_Array
::value('status_id', $params);
163 if (!empty($params['installment_amount'])) {
164 $params['amount'] = $params['installment_amount'] * $params['installments'];
167 //get All Payments status types.
168 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
170 //update the pledge status only if it does NOT come from form
171 if (!isset($params['pledge_status_id'])) {
172 if (isset($params['contribution_id'])) {
173 if ($params['installments'] > 1) {
174 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
178 if (!empty($params['id'])) {
179 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
182 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
187 $pledge = self
::add($params);
188 if (is_a($pledge, 'CRM_Core_Error')) {
193 //handle custom data.
194 if (!empty($params['custom']) &&
195 is_array($params['custom'])
197 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
200 // skip payment stuff inedit mode
201 if (!isset($params['id']) ||
!empty($params['is_pledge_pending'])) {
204 //if pledge is pending delete all payments and recreate.
205 if (!empty($params['is_pledge_pending'])) {
206 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
209 //building payment params
210 $paymentParams['pledge_id'] = $pledge->id
;
211 $paymentKeys = array(
212 'amount', 'installments', 'scheduled_date', 'frequency_unit', 'currency',
213 'frequency_day', 'frequency_interval', 'contribution_id', 'installment_amount', 'actual_amount',
215 foreach ($paymentKeys as $key) {
216 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
218 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
221 $transaction->commit();
223 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
224 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
227 $recentOther = array();
228 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
229 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
230 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
233 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
234 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
235 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
239 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
240 $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) . ')';
242 // add the recently created Pledge
243 CRM_Utils_Recent
::add($title,
256 * Function to delete the pledge
258 * @param int $id pledge id
265 static function deletePledge($id) {
266 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
268 $transaction = new CRM_Core_Transaction();
270 //check for no Completed Payment records with the pledge
271 $payment = new CRM_Pledge_DAO_PledgePayment();
272 $payment->pledge_id
= $id;
275 while ($payment->fetch()) {
276 //also delete associated contribution.
277 if ($payment->contribution_id
) {
278 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
283 $dao = new CRM_Pledge_DAO_Pledge();
285 $results = $dao->delete();
287 $transaction->commit();
289 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
291 // delete the recently created Pledge
292 $pledgeRecent = array(
296 CRM_Utils_Recent
::del($pledgeRecent);
302 * function to get the amount details date wise.
304 * @param string $status
305 * @param string $startDate
306 * @param string $endDate
310 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
312 $select = $from = $queryDate = NULL;
314 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
315 $statusId = array_search($status, $allStatus);
319 $statusId = array_search('Cancelled', $allStatus);
320 $where[] = 'status_id != ' . $statusId;
324 $where[] = 'status_id = ' . $statusId;
328 $where[] = 'status_id = ' . $statusId;
332 $where[] = 'status_id = ' . $statusId;
336 $where[] = 'status_id = ' . $statusId;
341 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
344 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
347 $whereCond = implode(' AND ', $where);
350 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
352 WHERE $whereCond AND is_test=0
355 $start = substr($startDate, 0, 8);
356 $end = substr($endDate, 0, 8);
359 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
360 while ($dao->fetch()) {
361 $pCount +
= $dao->pledge_count
;
362 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
365 $pledge_amount = array('pledge_amount' => implode(', ', $pamount),
366 'pledge_count' => $pCount,
367 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
368 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
373 $statusId = array_search($status, $allStatus);
376 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
377 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
378 $queryDate = 'receive_date';
379 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
383 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
384 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
385 $queryDate = 'receive_date';
386 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
390 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
391 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
392 $queryDate = 'scheduled_date';
393 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
397 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
398 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
399 $queryDate = 'scheduled_date';
400 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
405 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
408 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
411 $whereCond = implode(' AND ', $where);
414 SELECT $select, cp.currency
420 // CRM_Core_Error::debug($status . ' start:' . $startDate . '- end:' . $endDate, $query);
421 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
425 while ($dao->fetch()) {
426 $count +
= $dao->received_count
;
427 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
431 return array_merge($pledge_amount, array('received_amount' => implode(', ', $amount),
432 'received_count' => $count,
433 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
434 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
440 return $pledge_amount;
446 * Function to get list of pledges In Honor of contact Ids
448 * @param int $honorId In Honor of Contact ID
450 * @return array return the list of pledge fields
455 static function getHonorContacts($honorId) {
457 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
458 $honorDAO->contact_id
= $honorId;
462 while ($honorDAO->fetch()) {
463 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
464 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
465 if ($pledgePaymentDAO->find(TRUE)) {
466 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
467 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
468 if ($pledgeDAO->find(TRUE)) {
469 $params[$pledgeDAO->id
] = array(
470 'honor_type' => CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value'),
471 'honorId' => $pledgeDAO->contact_id
,
472 'amount' => $pledgeDAO->amount
,
473 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
474 'create_date' => $pledgeDAO->create_date
,
475 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
476 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
477 $pledgeDAO->financial_type_id
, 'name'
479 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
480 $pledgeDAO->contact_id
, 'display_name'
491 * Function to send Acknowledgment and create activity.
493 * @param object $form form object.
494 * @param array $params (reference ) an assoc array of name/value pairs.
499 static function sendAcknowledgment(&$form, $params) {
500 //handle Acknowledgment.
501 $allPayments = $payments = array();
503 //get All Payments status types.
504 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
505 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
506 //get all paymnets details.
507 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
509 if (!empty($allPayments)) {
510 foreach ($allPayments as $payID => $values) {
511 $contributionValue = $contributionStatus = array();
512 if (isset($values['contribution_id'])) {
513 $contributionParams = array('id' => $values['contribution_id']);
514 $returnProperties = array('contribution_status_id', 'receive_date');
515 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
516 $contributionParams, $contributionStatus, $returnProperties
518 $contributionValue = array(
519 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
520 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
523 $payments[$payID] = array_merge($contributionValue,
524 array('amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
525 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
529 //get the first valid payment id.
530 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
531 $paymentStatusTypes[$values['status_id']] == 'Overdue'
533 $form->paymentId
= $values['id'];
539 //assign pledge fields value to template.
540 $pledgeFields = array(
541 'create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit',
542 'installments', 'frequency_day', 'scheduled_amount', 'currency',
544 foreach ($pledgeFields as $field) {
545 if (!empty($params[$field])) {
546 $form->assign($field, $params[$field]);
550 //assign all payments details.
552 $form->assign('payments', $payments);
555 //handle domain token values
556 $domain = CRM_Core_BAO_Domain
::getDomain();
557 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
558 'contact' => CRM_Core_SelectValues
::contactTokens(),
560 $domainValues = array();
561 foreach ($tokens['domain'] as $token) {
562 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
564 $form->assign('domain', $domainValues);
566 //handle contact token values.
567 $ids = array($params['contact_id']);
568 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
569 array('display_name', 'checksum', 'contact_id')
571 foreach ($fields as $key => $val) {
572 $returnProperties[$val] = TRUE;
574 $details = CRM_Utils_Token
::getTokenDetails($ids,
580 $form->assign('contact', $details[0][$params['contact_id']]);
582 //handle custom data.
583 if (!empty($params['hidden_custom'])) {
584 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
585 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
586 $customGroup = array();
587 // retrieve custom data
588 foreach ($groupTree as $groupID => $group) {
589 $customFields = $customValues = array();
590 if ($groupID == 'info') {
593 foreach ($group['fields'] as $k => $field) {
594 $field['title'] = $field['label'];
595 $customFields["custom_{$k}"] = $field;
598 //to build array of customgroup & customfields in it
599 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
600 $customGroup[$group['title']] = $customValues;
603 $form->assign('customGroup', $customGroup);
606 //handle acknowledgment email stuff.
607 list($pledgerDisplayName,
609 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
611 //check for online pledge.
612 $session = CRM_Core_Session
::singleton();
613 if (!empty($params['receipt_from_email'])) {
614 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
615 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
617 elseif (!empty($params['from_email_id'])) {
618 $receiptFrom = $params['from_email_id'];
620 elseif ($userID = $session->get('userID')) {
621 //check for logged in user.
622 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
625 //set the domain values.
626 $userName = CRM_Utils_Array
::value('name', $domainValues);
627 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
630 if (!isset($receiptFrom)) {
631 $receiptFrom = "$userName <$userEmail>";
634 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
636 'groupName' => 'msg_tpl_workflow_pledge',
637 'valueName' => 'pledge_acknowledge',
638 'contactId' => $params['contact_id'],
639 'from' => $receiptFrom,
640 'toName' => $pledgerDisplayName,
641 'toEmail' => $pledgerEmail,
645 //check if activity record exist for this pledge
646 //Acknowledgment, if exist do not add activity.
647 $activityType = 'Pledge Acknowledgment';
648 $activity = new CRM_Activity_DAO_Activity();
649 $activity->source_record_id
= $params['id'];
650 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
654 $config = CRM_Core_Config
::singleton();
656 $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)';
658 if (!$activity->find()) {
659 $activityParams = array(
660 'subject' => $subject,
661 'source_contact_id' => $params['contact_id'],
662 'source_record_id' => $params['id'],
663 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
667 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
668 'is_test' => $params['is_test'],
670 'details' => $details,
671 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
674 //lets insert assignee record.
675 if (!empty($params['contact_id'])) {
676 $activityParams['assignee_contact_id'] = $params['contact_id'];
679 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
680 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
686 * combine all the exportable fields from the lower levels object
688 * @return array array of exportable Fields
692 static function &exportableFields() {
693 if (!self
::$_exportableFields) {
694 if (!self
::$_exportableFields) {
695 self
::$_exportableFields = array();
698 $fields = CRM_Pledge_DAO_Pledge
::export();
700 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
702 //set title to calculated fields
703 $calculatedFields = array('pledge_total_paid' => array('title' => ts('Total Paid')),
704 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
705 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
706 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
707 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
708 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
709 'pledge_payment_status' => array('title' => ts('Pledge Payment Status'),
710 'name' => 'pledge_payment_status',
711 'data_type' => CRM_Utils_Type
::T_STRING
,
716 $pledgeFields = array(
717 'pledge_status' => array('title' => 'Pledge Status',
718 'name' => 'pledge_status',
719 'data_type' => CRM_Utils_Type
::T_STRING
,
721 'pledge_frequency_unit' => array(
722 'title' => 'Pledge Frequency Unit',
723 'name' => 'pledge_frequency_unit',
724 'data_type' => CRM_Utils_Type
::T_ENUM
,
726 'pledge_frequency_interval' => array(
727 'title' => 'Pledge Frequency Interval',
728 'name' => 'pledge_frequency_interval',
729 'data_type' => CRM_Utils_Type
::T_INT
,
731 'pledge_contribution_page_id' => array(
732 'title' => 'Pledge Contribution Page Id',
733 'name' => 'pledge_contribution_page_id',
734 'data_type' => CRM_Utils_Type
::T_INT
,
738 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
741 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
742 self
::$_exportableFields = $fields;
745 return self
::$_exportableFields;
749 * Function to get pending or in progress pledges
751 * @param int $contactID contact id
753 * @return array associated array of pledge id(s)
756 static function getContactPledges($contactID) {
757 $pledgeDetails = array();
758 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
762 //get pending and in progress status
764 'Pending', 'In Progress', 'Overdue') as $name) {
765 if ($statusId = array_search($name, $pledgeStatuses)) {
766 $status[] = $statusId;
769 if (empty($status)) {
770 return $pledgeDetails;
773 $statusClause = " IN (" . implode(',', $status) . ")";
776 SELECT civicrm_pledge.id id
778 WHERE civicrm_pledge.status_id {$statusClause}
779 AND civicrm_pledge.contact_id = %1
782 $params[1] = array($contactID, 'Integer');
783 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
785 while ($pledge->fetch()) {
786 $pledgeDetails[] = $pledge->id
;
789 return $pledgeDetails;
793 * Function to get pledge record count for a Contact
797 * @internal param int $contactId Contact ID
799 * @return int count of pledge records
803 static function getContactPledgeCount($contactID) {
804 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
805 return CRM_Core_DAO
::singleValueQuery($query);
813 public static function updatePledgeStatus($params) {
815 $returnMessages = array();
817 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
819 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
821 //unset statues that we never use for pledges
823 'Completed', 'Cancelled', 'Failed') as $statusKey) {
824 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
825 unset($allStatus[$key]);
829 $statusIds = implode(',', array_keys($allStatus));
833 SELECT pledge.contact_id as contact_id,
834 pledge.id as pledge_id,
835 pledge.amount as amount,
836 payment.scheduled_date as scheduled_date,
837 pledge.create_date as create_date,
838 payment.id as payment_id,
839 pledge.currency as currency,
840 pledge.contribution_page_id as contribution_page_id,
841 payment.reminder_count as reminder_count,
842 pledge.max_reminders as max_reminders,
843 payment.reminder_date as reminder_date,
844 pledge.initial_reminder_day as initial_reminder_day,
845 pledge.additional_reminder_day as additional_reminder_day,
846 pledge.status_id as pledge_status,
847 payment.status_id as payment_status,
848 pledge.is_test as is_test,
849 pledge.campaign_id as campaign_id,
850 SUM(payment.scheduled_amount) as amount_due,
851 ( SELECT sum(civicrm_pledge_payment.actual_amount)
852 FROM civicrm_pledge_payment
853 WHERE civicrm_pledge_payment.status_id = 1
854 AND civicrm_pledge_payment.pledge_id = pledge.id
856 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
857 WHERE pledge.id = payment.pledge_id
858 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
862 $dao = CRM_Core_DAO
::executeQuery($query);
865 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
866 while ($dao->fetch()) {
867 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
869 $pledgeDetails[$dao->payment_id
] = array(
870 'scheduled_date' => $dao->scheduled_date
,
871 'amount_due' => $dao->amount_due
,
872 'amount' => $dao->amount
,
873 'amount_paid' => $dao->amount_paid
,
874 'create_date' => $dao->create_date
,
875 'contact_id' => $dao->contact_id
,
876 'pledge_id' => $dao->pledge_id
,
877 'checksumValue' => $checksumValue,
878 'contribution_page_id' => $dao->contribution_page_id
,
879 'reminder_count' => $dao->reminder_count
,
880 'max_reminders' => $dao->max_reminders
,
881 'reminder_date' => $dao->reminder_date
,
882 'initial_reminder_day' => $dao->initial_reminder_day
,
883 'additional_reminder_day' => $dao->additional_reminder_day
,
884 'pledge_status' => $dao->pledge_status
,
885 'payment_status' => $dao->payment_status
,
886 'is_test' => $dao->is_test
,
887 'currency' => $dao->currency
,
888 'campaign_id' => $dao->campaign_id
,
891 $contactIds[$dao->contact_id
] = $dao->contact_id
;
892 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
894 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
896 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)) {
897 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
901 // process the updating script...
903 foreach ($pledgePayments as $pledgeId => $paymentIds) {
904 // 1. update the pledge /pledge payment status. returns new status when an update happens
905 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
907 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
908 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
910 if ($newStatus != $pledgeStatus[$pledgeId]) {
911 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
916 if ($sendReminders) {
917 // retrieve domain tokens
918 $domain = CRM_Core_BAO_Domain
::getDomain();
919 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
920 'contact' => CRM_Core_SelectValues
::contactTokens(),
923 $domainValues = array();
924 foreach ($tokens['domain'] as $token) {
925 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
928 //get the domain email address, since we don't carry w/ object.
929 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
930 $domainValues['email'] = $domainValue[1];
932 // retrieve contact tokens
934 // this function does NOT return Deceased contacts since we don't want to send them email
935 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
938 $tokens, 'CRM_UpdatePledgeRecord'
941 // assign domain values to template
942 $template = CRM_Core_Smarty
::singleton();
943 $template->assign('domain', $domainValues);
946 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
948 foreach ($pledgeDetails as $paymentId => $details) {
949 if (array_key_exists($details['contact_id'], $contactDetails)) {
950 $contactId = $details['contact_id'];
951 $pledgerName = $contactDetails[$contactId]['display_name'];
957 if (empty($details['reminder_date'])) {
958 $nextReminderDate = new DateTime($details['scheduled_date']);
959 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
960 $nextReminderDate = $nextReminderDate->format("Ymd");
963 $nextReminderDate = new DateTime($details['reminder_date']);
964 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
965 $nextReminderDate = $nextReminderDate->format("Ymd");
967 if (($details['reminder_count'] < $details['max_reminders'])
968 && ($nextReminderDate <= $now)
971 $toEmail = $doNotEmail = $onHold = NULL;
973 if (!empty($contactDetails[$contactId]['email'])) {
974 $toEmail = $contactDetails[$contactId]['email'];
977 if (!empty($contactDetails[$contactId]['do_not_email'])) {
978 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
981 if (!empty($contactDetails[$contactId]['on_hold'])) {
982 $onHold = $contactDetails[$contactId]['on_hold'];
985 // 2. send acknowledgement mail
986 if ($toEmail && !($doNotEmail ||
$onHold)) {
987 //assign value to template
988 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
989 $template->assign('contact', $contactDetails[$contactId]);
990 $template->assign('next_payment', $details['scheduled_date']);
991 $template->assign('amount_due', $details['amount_due']);
992 $template->assign('checksumValue', $details['checksumValue']);
993 $template->assign('contribution_page_id', $details['contribution_page_id']);
994 $template->assign('pledge_id', $details['pledge_id']);
995 $template->assign('scheduled_payment_date', $details['scheduled_date']);
996 $template->assign('amount', $details['amount']);
997 $template->assign('create_date', $details['create_date']);
998 $template->assign('currency', $details['currency']);
999 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1001 'groupName' => 'msg_tpl_workflow_pledge',
1002 'valueName' => 'pledge_reminder',
1003 'contactId' => $contactId,
1004 'from' => $receiptFrom,
1005 'toName' => $pledgerName,
1006 'toEmail' => $toEmail,
1010 // 3. update pledge payment details
1012 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1013 $activityType = 'Pledge Reminder';
1014 $activityParams = array(
1015 'subject' => $subject,
1016 'source_contact_id' => $contactId,
1017 'source_record_id' => $paymentId,
1018 'assignee_contact_id' => $contactId,
1019 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1023 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1024 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1025 'is_test' => $details['is_test'],
1027 'campaign_id' => $details['campaign_id'],
1029 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1030 $returnMessages[] = "Failed creating Activity for acknowledgment";
1031 return array('is_error' => 1, 'message' => $returnMessages);
1033 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1038 // end foreach on $pledgeDetails
1040 // end if ( $sendReminders )
1041 $returnMessages[] = "{$updateCnt} records updated.";
1043 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1047 * Mark a pledge (and any outstanding payments) as cancelled.
1049 * @param int $pledgeID
1051 public static function cancel($pledgeID) {
1052 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1053 $paymentIDs = self
::findCancelablePayments($pledgeID);
1054 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1055 $statuses['Cancelled'], 0, FALSE, TRUE
1060 * Find payments which can be safely canceled.
1062 * @param int $pledgeID
1063 * @return array of int (civicrm_pledge_payment.id)
1065 public static function findCancelablePayments($pledgeID) {
1066 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1068 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1069 $paymentDAO->pledge_id
= $pledgeID;
1070 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1071 $statuses['Overdue'],
1072 $statuses['Pending']
1074 $paymentDAO->find();
1076 $paymentIDs = array();
1077 while ($paymentDAO->fetch()) {
1078 $paymentIDs[] = $paymentDAO->id
;
1084 * Is this pledge free from financial transactions (this is important to know as we allow editing
1085 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1086 * & recreating so we want to block that if appropriate
1088 * @param integer $pledgeID
1089 * @param integer $pledgeStatusID
1090 * @return bool do financial transactions exist for this pledge?
1092 static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1093 if (empty($pledgeStatusID)) {
1094 //why would this happen? If we can see where it does then we can see if we should look it up
1095 //but assuming from form code it CAN be empty
1098 if (self
::isTransactedStatus($pledgeStatusID)) {
1102 return civicrm_api3('pledge_payment', 'getcount', array('pledge_id' => $pledgeID, 'status_id' => array('IN' => self
::getTransactionalStatus())));
1106 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1107 * @param int $statusID pledge status id
1109 * @return bool is it a transactional status?
1111 protected static function isTransactedStatus($statusID) {
1112 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1119 * Get array of non transactional statuses
1120 * @return array non transactional status ids
1122 protected static function getNonTransactionalStatus() {
1123 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1124 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1128 * Get array of non transactional statuses
1129 * @return array non transactional status ids
1131 protected static function getTransactionalStatus() {
1132 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1133 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());