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.
134 * associated array of field values
137 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
138 if (empty($params)) {
141 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
146 * Takes an associative array and creates a pledge object
148 * @param array $params
149 * (reference ) an assoc array of name/value pairs.
151 * @return CRM_Pledge_BAO_Pledge object
154 public static function &create(&$params) {
155 //FIXME: a cludgy hack to fix the dates to MySQL format
156 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
157 foreach ($dateFields as $df) {
158 if (isset($params[$df])) {
159 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
163 $transaction = new CRM_Core_Transaction();
165 $paymentParams = array();
166 $paymentParams['status_id'] = CRM_Utils_Array
::value('status_id', $params);
167 if (!empty($params['installment_amount'])) {
168 $params['amount'] = $params['installment_amount'] * $params['installments'];
171 //get All Payments status types.
172 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
174 //update the pledge status only if it does NOT come from form
175 if (!isset($params['pledge_status_id'])) {
176 if (isset($params['contribution_id'])) {
177 if ($params['installments'] > 1) {
178 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
182 if (!empty($params['id'])) {
183 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
186 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
191 $pledge = self
::add($params);
192 if (is_a($pledge, 'CRM_Core_Error')) {
197 //handle custom data.
198 if (!empty($params['custom']) &&
199 is_array($params['custom'])
201 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
204 // skip payment stuff inedit mode
205 if (!isset($params['id']) ||
!empty($params['is_pledge_pending'])) {
207 //if pledge is pending delete all payments and recreate.
208 if (!empty($params['is_pledge_pending'])) {
209 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
212 //building payment params
213 $paymentParams['pledge_id'] = $pledge->id
;
214 $paymentKeys = array(
221 'frequency_interval',
223 'installment_amount',
226 foreach ($paymentKeys as $key) {
227 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
229 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
232 $transaction->commit();
234 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
235 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
238 $recentOther = array();
239 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
240 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
241 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
244 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
245 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
246 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
250 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
251 $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) . ')';
253 // add the recently created Pledge
254 CRM_Utils_Recent
::add($title,
275 public static function deletePledge($id) {
276 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
278 $transaction = new CRM_Core_Transaction();
280 //check for no Completed Payment records with the pledge
281 $payment = new CRM_Pledge_DAO_PledgePayment();
282 $payment->pledge_id
= $id;
285 while ($payment->fetch()) {
286 //also delete associated contribution.
287 if ($payment->contribution_id
) {
288 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
293 $dao = new CRM_Pledge_DAO_Pledge();
295 $results = $dao->delete();
297 $transaction->commit();
299 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
301 // delete the recently created Pledge
302 $pledgeRecent = array(
306 CRM_Utils_Recent
::del($pledgeRecent);
312 * Get the amount details date wise.
314 * @param string $status
315 * @param string $startDate
316 * @param string $endDate
320 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
322 $select = $from = $queryDate = NULL;
324 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
325 $statusId = array_search($status, $allStatus);
329 $statusId = array_search('Cancelled', $allStatus);
330 $where[] = 'status_id != ' . $statusId;
334 $where[] = 'status_id = ' . $statusId;
338 $where[] = 'status_id = ' . $statusId;
342 $where[] = 'status_id = ' . $statusId;
346 $where[] = 'status_id = ' . $statusId;
351 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
354 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
357 $whereCond = implode(' AND ', $where);
360 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
362 WHERE $whereCond AND is_test=0
365 $start = substr($startDate, 0, 8);
366 $end = substr($endDate, 0, 8);
369 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
370 while ($dao->fetch()) {
371 $pCount +
= $dao->pledge_count
;
372 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
375 $pledge_amount = array(
376 'pledge_amount' => implode(', ', $pamount),
377 'pledge_count' => $pCount,
378 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
379 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
384 $statusId = array_search($status, $allStatus);
387 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
388 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
389 $queryDate = 'receive_date';
390 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
394 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
395 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
396 $queryDate = 'receive_date';
397 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
401 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
402 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
403 $queryDate = 'scheduled_date';
404 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
408 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
409 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
410 $queryDate = 'scheduled_date';
411 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
416 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
419 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
422 $whereCond = implode(' AND ', $where);
425 SELECT $select, cp.currency
431 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
435 while ($dao->fetch()) {
436 $count +
= $dao->received_count
;
437 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
441 return array_merge($pledge_amount, array(
442 'received_amount' => implode(', ', $amount),
443 'received_count' => $count,
444 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
445 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
451 return $pledge_amount;
457 * Get list of pledges In Honor of contact Ids
459 * @param int $honorId
460 * In Honor of Contact ID.
463 * return the list of pledge fields
467 public static function getHonorContacts($honorId) {
469 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
470 $honorDAO->contact_id
= $honorId;
474 while ($honorDAO->fetch()) {
475 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
476 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
477 if ($pledgePaymentDAO->find(TRUE)) {
478 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
479 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
480 if ($pledgeDAO->find(TRUE)) {
481 $params[$pledgeDAO->id
] = array(
482 'honor_type' => CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value'),
483 'honorId' => $pledgeDAO->contact_id
,
484 'amount' => $pledgeDAO->amount
,
485 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
486 'create_date' => $pledgeDAO->create_date
,
487 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
488 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
489 $pledgeDAO->financial_type_id
, 'name'
491 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
492 $pledgeDAO->contact_id
, 'display_name'
503 * Send Acknowledgment and create activity.
505 * @param CRM_Core_Form $form
507 * @param array $params
508 * An assoc array of name/value pairs.
512 public static function sendAcknowledgment(&$form, $params) {
513 //handle Acknowledgment.
514 $allPayments = $payments = array();
516 //get All Payments status types.
517 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
518 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
519 //get all paymnets details.
520 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
522 if (!empty($allPayments)) {
523 foreach ($allPayments as $payID => $values) {
524 $contributionValue = $contributionStatus = array();
525 if (isset($values['contribution_id'])) {
526 $contributionParams = array('id' => $values['contribution_id']);
527 $returnProperties = array('contribution_status_id', 'receive_date');
528 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
529 $contributionParams, $contributionStatus, $returnProperties
531 $contributionValue = array(
532 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
533 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
536 $payments[$payID] = array_merge($contributionValue,
538 'amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
539 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
543 //get the first valid payment id.
544 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
545 $paymentStatusTypes[$values['status_id']] == 'Overdue'
548 $form->paymentId
= $values['id'];
553 //assign pledge fields value to template.
554 $pledgeFields = array(
556 'total_pledge_amount',
557 'frequency_interval',
564 foreach ($pledgeFields as $field) {
565 if (!empty($params[$field])) {
566 $form->assign($field, $params[$field]);
570 //assign all payments details.
572 $form->assign('payments', $payments);
575 //handle domain token values
576 $domain = CRM_Core_BAO_Domain
::getDomain();
578 'domain' => array('name', 'phone', 'address', 'email'),
579 'contact' => CRM_Core_SelectValues
::contactTokens(),
581 $domainValues = array();
582 foreach ($tokens['domain'] as $token) {
583 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
585 $form->assign('domain', $domainValues);
587 //handle contact token values.
588 $ids = array($params['contact_id']);
589 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
590 array('display_name', 'checksum', 'contact_id')
592 foreach ($fields as $key => $val) {
593 $returnProperties[$val] = TRUE;
595 $details = CRM_Utils_Token
::getTokenDetails($ids,
601 $form->assign('contact', $details[0][$params['contact_id']]);
603 //handle custom data.
604 if (!empty($params['hidden_custom'])) {
605 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
606 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
607 $customGroup = array();
608 // retrieve custom data
609 foreach ($groupTree as $groupID => $group) {
610 $customFields = $customValues = array();
611 if ($groupID == 'info') {
614 foreach ($group['fields'] as $k => $field) {
615 $field['title'] = $field['label'];
616 $customFields["custom_{$k}"] = $field;
619 //to build array of customgroup & customfields in it
620 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
621 $customGroup[$group['title']] = $customValues;
624 $form->assign('customGroup', $customGroup);
627 //handle acknowledgment email stuff.
628 list($pledgerDisplayName,
630 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
632 //check for online pledge.
633 $session = CRM_Core_Session
::singleton();
634 if (!empty($params['receipt_from_email'])) {
635 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
636 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
638 elseif (!empty($params['from_email_id'])) {
639 $receiptFrom = $params['from_email_id'];
641 elseif ($userID = $session->get('userID')) {
642 //check for logged in user.
643 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
646 //set the domain values.
647 $userName = CRM_Utils_Array
::value('name', $domainValues);
648 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
651 if (!isset($receiptFrom)) {
652 $receiptFrom = "$userName <$userEmail>";
655 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
657 'groupName' => 'msg_tpl_workflow_pledge',
658 'valueName' => 'pledge_acknowledge',
659 'contactId' => $params['contact_id'],
660 'from' => $receiptFrom,
661 'toName' => $pledgerDisplayName,
662 'toEmail' => $pledgerEmail,
666 //check if activity record exist for this pledge
667 //Acknowledgment, if exist do not add activity.
668 $activityType = 'Pledge Acknowledgment';
669 $activity = new CRM_Activity_DAO_Activity();
670 $activity->source_record_id
= $params['id'];
671 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
675 $config = CRM_Core_Config
::singleton();
678 $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)';
680 if (!$activity->find()) {
681 $activityParams = array(
682 'subject' => $subject,
683 'source_contact_id' => $params['contact_id'],
684 'source_record_id' => $params['id'],
685 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
689 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
690 'is_test' => $params['is_test'],
692 'details' => $details,
693 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
696 //lets insert assignee record.
697 if (!empty($params['contact_id'])) {
698 $activityParams['assignee_contact_id'] = $params['contact_id'];
701 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
702 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
708 * Combine all the exportable fields from the lower levels object
711 * array of exportable Fields
714 public static function &exportableFields() {
715 if (!self
::$_exportableFields) {
716 if (!self
::$_exportableFields) {
717 self
::$_exportableFields = array();
720 $fields = CRM_Pledge_DAO_Pledge
::export();
722 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
724 //set title to calculated fields
725 $calculatedFields = array(
726 'pledge_total_paid' => array('title' => ts('Total Paid')),
727 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
728 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
729 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
730 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
731 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
732 'pledge_payment_status' => array(
733 'title' => ts('Pledge Payment Status'),
734 'name' => 'pledge_payment_status',
735 'data_type' => CRM_Utils_Type
::T_STRING
,
739 $pledgeFields = array(
740 'pledge_status' => array(
741 'title' => 'Pledge Status',
742 'name' => 'pledge_status',
743 'data_type' => CRM_Utils_Type
::T_STRING
,
745 'pledge_frequency_unit' => array(
746 'title' => 'Pledge Frequency Unit',
747 'name' => 'pledge_frequency_unit',
748 'data_type' => CRM_Utils_Type
::T_ENUM
,
750 'pledge_frequency_interval' => array(
751 'title' => 'Pledge Frequency Interval',
752 'name' => 'pledge_frequency_interval',
753 'data_type' => CRM_Utils_Type
::T_INT
,
755 'pledge_contribution_page_id' => array(
756 'title' => 'Pledge Contribution Page Id',
757 'name' => 'pledge_contribution_page_id',
758 'data_type' => CRM_Utils_Type
::T_INT
,
762 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
765 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
766 self
::$_exportableFields = $fields;
769 return self
::$_exportableFields;
773 * Get pending or in progress pledges
775 * @param int $contactID
779 * associated array of pledge id(s)
782 public static function getContactPledges($contactID) {
783 $pledgeDetails = array();
784 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
788 //get pending and in progress status
794 if ($statusId = array_search($name, $pledgeStatuses)) {
795 $status[] = $statusId;
798 if (empty($status)) {
799 return $pledgeDetails;
802 $statusClause = " IN (" . implode(',', $status) . ")";
805 SELECT civicrm_pledge.id id
807 WHERE civicrm_pledge.status_id {$statusClause}
808 AND civicrm_pledge.contact_id = %1
811 $params[1] = array($contactID, 'Integer');
812 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
814 while ($pledge->fetch()) {
815 $pledgeDetails[] = $pledge->id
;
818 return $pledgeDetails;
822 * Get pledge record count for a Contact
824 * @param int $contactID
827 * count of pledge records
830 public static function getContactPledgeCount($contactID) {
831 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
832 return CRM_Core_DAO
::singleValueQuery($query);
836 * @param array $params
840 public static function updatePledgeStatus($params) {
842 $returnMessages = array();
844 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
846 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
848 //unset statues that we never use for pledges
854 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
855 unset($allStatus[$key]);
859 $statusIds = implode(',', array_keys($allStatus));
863 SELECT pledge.contact_id as contact_id,
864 pledge.id as pledge_id,
865 pledge.amount as amount,
866 payment.scheduled_date as scheduled_date,
867 pledge.create_date as create_date,
868 payment.id as payment_id,
869 pledge.currency as currency,
870 pledge.contribution_page_id as contribution_page_id,
871 payment.reminder_count as reminder_count,
872 pledge.max_reminders as max_reminders,
873 payment.reminder_date as reminder_date,
874 pledge.initial_reminder_day as initial_reminder_day,
875 pledge.additional_reminder_day as additional_reminder_day,
876 pledge.status_id as pledge_status,
877 payment.status_id as payment_status,
878 pledge.is_test as is_test,
879 pledge.campaign_id as campaign_id,
880 SUM(payment.scheduled_amount) as amount_due,
881 ( SELECT sum(civicrm_pledge_payment.actual_amount)
882 FROM civicrm_pledge_payment
883 WHERE civicrm_pledge_payment.status_id = 1
884 AND civicrm_pledge_payment.pledge_id = pledge.id
886 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
887 WHERE pledge.id = payment.pledge_id
888 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
892 $dao = CRM_Core_DAO
::executeQuery($query);
895 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
896 while ($dao->fetch()) {
897 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
899 $pledgeDetails[$dao->payment_id
] = array(
900 'scheduled_date' => $dao->scheduled_date
,
901 'amount_due' => $dao->amount_due
,
902 'amount' => $dao->amount
,
903 'amount_paid' => $dao->amount_paid
,
904 'create_date' => $dao->create_date
,
905 'contact_id' => $dao->contact_id
,
906 'pledge_id' => $dao->pledge_id
,
907 'checksumValue' => $checksumValue,
908 'contribution_page_id' => $dao->contribution_page_id
,
909 'reminder_count' => $dao->reminder_count
,
910 'max_reminders' => $dao->max_reminders
,
911 'reminder_date' => $dao->reminder_date
,
912 'initial_reminder_day' => $dao->initial_reminder_day
,
913 'additional_reminder_day' => $dao->additional_reminder_day
,
914 'pledge_status' => $dao->pledge_status
,
915 'payment_status' => $dao->payment_status
,
916 'is_test' => $dao->is_test
,
917 'currency' => $dao->currency
,
918 'campaign_id' => $dao->campaign_id
,
921 $contactIds[$dao->contact_id
] = $dao->contact_id
;
922 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
924 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
926 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)
928 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
932 // process the updating script...
934 foreach ($pledgePayments as $pledgeId => $paymentIds) {
935 // 1. update the pledge /pledge payment status. returns new status when an update happens
936 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
938 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
939 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
941 if ($newStatus != $pledgeStatus[$pledgeId]) {
942 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
947 if ($sendReminders) {
948 // retrieve domain tokens
949 $domain = CRM_Core_BAO_Domain
::getDomain();
951 'domain' => array('name', 'phone', 'address', 'email'),
952 'contact' => CRM_Core_SelectValues
::contactTokens(),
955 $domainValues = array();
956 foreach ($tokens['domain'] as $token) {
957 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
960 //get the domain email address, since we don't carry w/ object.
961 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
962 $domainValues['email'] = $domainValue[1];
964 // retrieve contact tokens
966 // this function does NOT return Deceased contacts since we don't want to send them email
967 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
970 $tokens, 'CRM_UpdatePledgeRecord'
973 // assign domain values to template
974 $template = CRM_Core_Smarty
::singleton();
975 $template->assign('domain', $domainValues);
978 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
980 foreach ($pledgeDetails as $paymentId => $details) {
981 if (array_key_exists($details['contact_id'], $contactDetails)) {
982 $contactId = $details['contact_id'];
983 $pledgerName = $contactDetails[$contactId]['display_name'];
989 if (empty($details['reminder_date'])) {
990 $nextReminderDate = new DateTime($details['scheduled_date']);
991 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
992 $nextReminderDate = $nextReminderDate->format("Ymd");
995 $nextReminderDate = new DateTime($details['reminder_date']);
996 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
997 $nextReminderDate = $nextReminderDate->format("Ymd");
999 if (($details['reminder_count'] < $details['max_reminders'])
1000 && ($nextReminderDate <= $now)
1003 $toEmail = $doNotEmail = $onHold = NULL;
1005 if (!empty($contactDetails[$contactId]['email'])) {
1006 $toEmail = $contactDetails[$contactId]['email'];
1009 if (!empty($contactDetails[$contactId]['do_not_email'])) {
1010 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
1013 if (!empty($contactDetails[$contactId]['on_hold'])) {
1014 $onHold = $contactDetails[$contactId]['on_hold'];
1017 // 2. send acknowledgement mail
1018 if ($toEmail && !($doNotEmail ||
$onHold)) {
1019 //assign value to template
1020 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1021 $template->assign('contact', $contactDetails[$contactId]);
1022 $template->assign('next_payment', $details['scheduled_date']);
1023 $template->assign('amount_due', $details['amount_due']);
1024 $template->assign('checksumValue', $details['checksumValue']);
1025 $template->assign('contribution_page_id', $details['contribution_page_id']);
1026 $template->assign('pledge_id', $details['pledge_id']);
1027 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1028 $template->assign('amount', $details['amount']);
1029 $template->assign('create_date', $details['create_date']);
1030 $template->assign('currency', $details['currency']);
1031 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1033 'groupName' => 'msg_tpl_workflow_pledge',
1034 'valueName' => 'pledge_reminder',
1035 'contactId' => $contactId,
1036 'from' => $receiptFrom,
1037 'toName' => $pledgerName,
1038 'toEmail' => $toEmail,
1042 // 3. update pledge payment details
1044 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1045 $activityType = 'Pledge Reminder';
1046 $activityParams = array(
1047 'subject' => $subject,
1048 'source_contact_id' => $contactId,
1049 'source_record_id' => $paymentId,
1050 'assignee_contact_id' => $contactId,
1051 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1055 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1056 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1057 'is_test' => $details['is_test'],
1059 'campaign_id' => $details['campaign_id'],
1061 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1062 $returnMessages[] = "Failed creating Activity for acknowledgment";
1063 return array('is_error' => 1, 'message' => $returnMessages);
1065 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1070 // end foreach on $pledgeDetails
1072 // end if ( $sendReminders )
1073 $returnMessages[] = "{$updateCnt} records updated.";
1075 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1079 * Mark a pledge (and any outstanding payments) as cancelled.
1081 * @param int $pledgeID
1083 public static function cancel($pledgeID) {
1084 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1085 $paymentIDs = self
::findCancelablePayments($pledgeID);
1086 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1087 $statuses['Cancelled'], 0, FALSE, TRUE
1092 * Find payments which can be safely canceled.
1094 * @param int $pledgeID
1096 * of int (civicrm_pledge_payment.id)
1098 public static function findCancelablePayments($pledgeID) {
1099 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1101 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1102 $paymentDAO->pledge_id
= $pledgeID;
1103 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1104 $statuses['Overdue'],
1105 $statuses['Pending']
1107 $paymentDAO->find();
1109 $paymentIDs = array();
1110 while ($paymentDAO->fetch()) {
1111 $paymentIDs[] = $paymentDAO->id
;
1117 * Is this pledge free from financial transactions (this is important to know as we allow editing
1118 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1119 * & recreating so we want to block that if appropriate
1121 * @param int $pledgeID
1122 * @param int $pledgeStatusID
1124 * do financial transactions exist for this pledge?
1126 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1127 if (empty($pledgeStatusID)) {
1128 //why would this happen? If we can see where it does then we can see if we should look it up
1129 //but assuming from form code it CAN be empty
1132 if (self
::isTransactedStatus($pledgeStatusID)) {
1136 return civicrm_api3('pledge_payment', 'getcount', array(
1137 'pledge_id' => $pledgeID,
1138 'status_id' => array('IN' => self
::getTransactionalStatus())
1143 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1144 * @param int $statusID
1148 * is it a transactional status?
1150 protected static function isTransactedStatus($statusID) {
1151 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1158 * Get array of non transactional statuses
1160 * non transactional status ids
1162 protected static function getNonTransactionalStatus() {
1163 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1164 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1168 * Get array of non transactional statuses
1170 * non transactional status ids
1172 protected static function getTransactionalStatus() {
1173 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1174 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());