3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 (CRM_Utils_Array
::value('id', $params)) {
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 (CRM_Utils_Array
::value('id', $params)) {
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 (CRM_Utils_Array
::value('installment_amount', $params)) {
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 (CRM_Utils_Array
::value('custom', $params) &&
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']) ||
202 CRM_Utils_Array
::value('is_pledge_pending', $params)
206 //if pledge is pending delete all payments and recreate.
207 if (CRM_Utils_Array
::value('is_pledge_pending', $params)) {
208 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
211 //building payment params
212 $paymentParams['pledge_id'] = $pledge->id
;
213 $paymentKeys = array(
214 'amount', 'installments', 'scheduled_date', 'frequency_unit', 'currency',
215 'frequency_day', 'frequency_interval', 'contribution_id', 'installment_amount', 'actual_amount',
217 foreach ($paymentKeys as $key) {
218 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
220 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
223 $transaction->commit();
225 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
226 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
229 $recentOther = array();
230 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
231 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
232 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
235 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
236 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
237 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
241 $config = CRM_Core_Config
::singleton();
242 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
243 $title = CRM_Contact_BAO_Contact
::displayName($pledge->contact_id
) . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money
::format($pledge->amount
, $pledge->currency
) . ' - ' . $contributionTypes[$pledge->financial_type_id
] . ')';
245 // add the recently created Pledge
246 CRM_Utils_Recent
::add($title,
259 * Function to delete the pledge
261 * @param int $id pledge id
267 static function deletePledge($id) {
268 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
270 $transaction = new CRM_Core_Transaction();
272 //check for no Completed Payment records with the pledge
273 $payment = new CRM_Pledge_DAO_PledgePayment();
274 $payment->pledge_id
= $id;
277 while ($payment->fetch()) {
278 //also delete associated contribution.
279 if ($payment->contribution_id
) {
280 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
285 $dao = new CRM_Pledge_DAO_Pledge();
287 $results = $dao->delete();
289 $transaction->commit();
291 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
293 // delete the recently created Pledge
294 $pledgeRecent = array(
298 CRM_Utils_Recent
::del($pledgeRecent);
304 * function to get the amount details date wise.
306 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
308 $select = $from = $queryDate = NULL;
310 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
311 $statusId = array_search($status, $allStatus);
315 $statusId = array_search('Cancelled', $allStatus);
316 $where[] = 'status_id != ' . $statusId;
320 $where[] = 'status_id = ' . $statusId;
324 $where[] = 'status_id = ' . $statusId;
328 $where[] = 'status_id = ' . $statusId;
332 $where[] = 'status_id = ' . $statusId;
337 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
340 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
343 $whereCond = implode(' AND ', $where);
346 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
348 WHERE $whereCond AND is_test=0
351 $start = substr($startDate, 0, 8);
352 $end = substr($endDate, 0, 8);
355 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
356 while ($dao->fetch()) {
357 $pCount +
= $dao->pledge_count
;
358 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
361 $pledge_amount = array('pledge_amount' => implode(', ', $pamount),
362 'pledge_count' => $pCount,
363 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
364 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
369 $statusId = array_search($status, $allStatus);
372 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
373 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
374 $queryDate = 'receive_date';
375 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
379 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
380 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
381 $queryDate = 'receive_date';
382 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
386 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
387 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
388 $queryDate = 'scheduled_date';
389 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
393 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
394 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
395 $queryDate = 'scheduled_date';
396 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
401 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
404 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
407 $whereCond = implode(' AND ', $where);
410 SELECT $select, cp.currency
416 // CRM_Core_Error::debug($status . ' start:' . $startDate . '- end:' . $endDate, $query);
417 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
421 while ($dao->fetch()) {
422 $count +
= $dao->received_count
;
423 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
427 return array_merge($pledge_amount, array('received_amount' => implode(', ', $amount),
428 'received_count' => $count,
429 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
430 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
436 return $pledge_amount;
442 * Function to get list of pledges In Honor of contact Ids
444 * @param int $honorId In Honor of Contact ID
446 * @return return the list of pledge fields
451 static function getHonorContacts($honorId) {
453 $honorDAO = new CRM_Pledge_DAO_Pledge();
454 $honorDAO->honor_contact_id
= $honorId;
458 while ($honorDAO->fetch()) {
459 $params[$honorDAO->id
] = array(
460 'honorId' => $honorDAO->contact_id
,
461 'amount' => $honorDAO->amount
,
462 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($honorDAO->status_id
),
463 'create_date' => $honorDAO->create_date
,
464 'acknowledge_date' => $honorDAO->acknowledge_date
,
465 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
466 $honorDAO->financial_type_id
, 'name'
468 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
469 $honorDAO->contact_id
, 'display_name'
477 * Function to send Acknowledgment and create activity.
479 * @param object $form form object.
480 * @param array $params (reference ) an assoc array of name/value pairs.
485 function sendAcknowledgment(&$form, $params) {
486 //handle Acknowledgment.
487 $allPayments = $payments = array();
489 //get All Payments status types.
490 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
491 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
492 //get all paymnets details.
493 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
495 if (!empty($allPayments)) {
496 foreach ($allPayments as $payID => $values) {
497 $contributionValue = $contributionStatus = array();
498 if (isset($values['contribution_id'])) {
499 $contributionParams = array('id' => $values['contribution_id']);
500 $returnProperties = array('contribution_status_id', 'receive_date');
501 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
502 $contributionParams, $contributionStatus, $returnProperties
504 $contributionValue = array(
505 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
506 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
509 $payments[$payID] = array_merge($contributionValue,
510 array('amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
511 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
515 //get the first valid payment id.
516 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
517 $paymentStatusTypes[$values['status_id']] == 'Overdue'
519 $form->paymentId
= $values['id'];
525 //assign pledge fields value to template.
526 $pledgeFields = array(
527 'create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit',
528 'installments', 'frequency_day', 'scheduled_amount', 'currency',
530 foreach ($pledgeFields as $field) {
531 if (CRM_Utils_Array
::value($field, $params)) {
532 $form->assign($field, $params[$field]);
536 //assign all payments details.
538 $form->assign('payments', $payments);
541 //assign honor fields.
542 $honor_block_is_active = FALSE;
543 //make sure we have values for it
544 if (CRM_Utils_Array
::value('honor_type_id', $params) &&
545 ((!empty($params['honor_first_name']) && !empty($params['honor_last_name'])) ||
546 (!empty($params['honor_email']))
549 $honor_block_is_active = TRUE;
550 $prefix = CRM_Core_PseudoConstant
::individualPrefix();
551 $honor = CRM_Core_PseudoConstant
::honor();
552 $form->assign('honor_type', $honor[$params['honor_type_id']]);
553 $form->assign('honor_prefix', $prefix[$params['honor_prefix_id']]);
554 $form->assign('honor_first_name', $params['honor_first_name']);
555 $form->assign('honor_last_name', $params['honor_last_name']);
556 $form->assign('honor_email', $params['honor_email']);
558 $form->assign('honor_block_is_active', $honor_block_is_active);
560 //handle domain token values
561 $domain = CRM_Core_BAO_Domain
::getDomain();
562 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
563 'contact' => CRM_Core_SelectValues
::contactTokens(),
565 $domainValues = array();
566 foreach ($tokens['domain'] as $token) {
567 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
569 $form->assign('domain', $domainValues);
571 //handle contact token values.
572 $ids = array($params['contact_id']);
573 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
574 array('display_name', 'checksum', 'contact_id')
576 foreach ($fields as $key => $val) {
577 $returnProperties[$val] = TRUE;
579 $details = CRM_Utils_Token
::getTokenDetails($ids,
585 $form->assign('contact', $details[0][$params['contact_id']]);
587 //handle custom data.
588 if (CRM_Utils_Array
::value('hidden_custom', $params)) {
589 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
590 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
591 $customGroup = array();
592 // retrieve custom data
593 foreach ($groupTree as $groupID => $group) {
594 $customFields = $customValues = array();
595 if ($groupID == 'info') {
598 foreach ($group['fields'] as $k => $field) {
599 $field['title'] = $field['label'];
600 $customFields["custom_{$k}"] = $field;
603 //to build array of customgroup & customfields in it
604 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
605 $customGroup[$group['title']] = $customValues;
608 $form->assign('customGroup', $customGroup);
611 //handle acknowledgment email stuff.
612 list($pledgerDisplayName,
614 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
616 //check for online pledge.
617 $session = CRM_Core_Session
::singleton();
618 if (CRM_Utils_Array
::value('receipt_from_email', $params)) {
619 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
620 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
622 elseif (CRM_Utils_Array
::value('from_email_id', $params)) {
623 $receiptFrom = $params['from_email_id'];
625 elseif ($userID = $session->get('userID')) {
626 //check for loged in user.
627 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
630 //set the domain values.
631 $userName = CRM_Utils_Array
::value('name', $domainValues);
632 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
635 if (!isset($receiptFrom)) {
636 $receiptFrom = "$userName <$userEmail>";
639 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates
::sendTemplate(
641 'groupName' => 'msg_tpl_workflow_pledge',
642 'valueName' => 'pledge_acknowledge',
643 'contactId' => $params['contact_id'],
644 'from' => $receiptFrom,
645 'toName' => $pledgerDisplayName,
646 'toEmail' => $pledgerEmail,
650 //check if activity record exist for this pledge
651 //Acknowledgment, if exist do not add activity.
652 $activityType = 'Pledge Acknowledgment';
653 $activity = new CRM_Activity_DAO_Activity();
654 $activity->source_record_id
= $params['id'];
655 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
659 $config = CRM_Core_Config
::singleton();
661 $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)';
663 if (!$activity->find()) {
664 $activityParams = array(
665 'subject' => $subject,
666 'source_contact_id' => $params['contact_id'],
667 'source_record_id' => $params['id'],
668 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
672 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
673 'is_test' => $params['is_test'],
675 'details' => $details,
676 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
679 //lets insert assignee record.
680 if (CRM_Utils_Array
::value('contact_id', $params)) {
681 $activityParams['assignee_contact_id'] = $params['contact_id'];
684 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
685 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
691 * combine all the exportable fields from the lower levels object
693 * @return array array of exportable Fields
697 static function &exportableFields() {
698 if (!self
::$_exportableFields) {
699 if (!self
::$_exportableFields) {
700 self
::$_exportableFields = array();
703 $fields = CRM_Pledge_DAO_Pledge
::export();
705 //export campaign title.
706 if (isset($fields['pledge_campaign_id'])) {
707 $fields['pledge_campaign'] = array('title' => ts('Campaign Title'));
710 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
712 //set title to calculated fields
713 $calculatedFields = array('pledge_total_paid' => array('title' => ts('Total Paid')),
714 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
715 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
716 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
717 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
718 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
719 'pledge_payment_status' => array('title' => ts('Pledge Payment Status'),
720 'name' => 'pledge_payment_status',
721 'data_type' => CRM_Utils_Type
::T_STRING
,
726 $pledgeFields = array(
727 'pledge_status' => array('title' => 'Pledge Status',
728 'name' => 'pledge_status',
729 'data_type' => CRM_Utils_Type
::T_STRING
,
731 'pledge_frequency_unit' => array(
732 'title' => 'Pledge Frequency Unit',
733 'name' => 'pledge_frequency_unit',
734 'data_type' => CRM_Utils_Type
::T_ENUM
,
736 'pledge_frequency_interval' => array(
737 'title' => 'Pledge Frequency Interval',
738 'name' => 'pledge_frequency_interval',
739 'data_type' => CRM_Utils_Type
::T_INT
,
741 'pledge_contribution_page_id' => array(
742 'title' => 'Pledge Contribution Page Id',
743 'name' => 'pledge_contribution_page_id',
744 'data_type' => CRM_Utils_Type
::T_INT
,
748 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
751 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
752 self
::$_exportableFields = $fields;
755 return self
::$_exportableFields;
759 * Function to get pending or in progress pledges
761 * @param int $contactID contact id
763 * @return array associated array of pledge id(s)
766 static function getContactPledges($contactID) {
767 $pledgeDetails = array();
768 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
772 //get pending and in progress status
774 'Pending', 'In Progress', 'Overdue') as $name) {
775 if ($statusId = array_search($name, $pledgeStatuses)) {
776 $status[] = $statusId;
779 if (empty($status)) {
780 return $pledgeDetails;
783 $statusClause = " IN (" . implode(',', $status) . ")";
786 SELECT civicrm_pledge.id id
788 WHERE civicrm_pledge.status_id {$statusClause}
789 AND civicrm_pledge.contact_id = %1
792 $params[1] = array($contactID, 'Integer');
793 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
795 while ($pledge->fetch()) {
796 $pledgeDetails[] = $pledge->id
;
799 return $pledgeDetails;
803 * Function to get pledge record count for a Contact
805 * @param int $contactId Contact ID
807 * @return int count of pledge records
811 static function getContactPledgeCount($contactID) {
812 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
813 return CRM_Core_DAO
::singleValueQuery($query);
816 public function updatePledgeStatus($params) {
818 $returnMessages = array();
820 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
822 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
824 //unset statues that we never use for pledges
826 'Completed', 'Cancelled', 'Failed') as $statusKey) {
827 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
828 unset($allStatus[$key]);
832 $statusIds = implode(',', array_keys($allStatus));
836 SELECT pledge.contact_id as contact_id,
837 pledge.id as pledge_id,
838 pledge.amount as amount,
839 payment.scheduled_date as scheduled_date,
840 pledge.create_date as create_date,
841 payment.id as payment_id,
842 pledge.currency as currency,
843 pledge.contribution_page_id as contribution_page_id,
844 payment.reminder_count as reminder_count,
845 pledge.max_reminders as max_reminders,
846 payment.reminder_date as reminder_date,
847 pledge.initial_reminder_day as initial_reminder_day,
848 pledge.additional_reminder_day as additional_reminder_day,
849 pledge.status_id as pledge_status,
850 payment.status_id as payment_status,
851 pledge.is_test as is_test,
852 pledge.campaign_id as campaign_id,
853 SUM(payment.scheduled_amount) as amount_due,
854 ( SELECT sum(civicrm_pledge_payment.actual_amount)
855 FROM civicrm_pledge_payment
856 WHERE civicrm_pledge_payment.status_id = 1
857 AND civicrm_pledge_payment.pledge_id = pledge.id
859 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
860 WHERE pledge.id = payment.pledge_id
861 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
865 $dao = CRM_Core_DAO
::executeQuery($query);
868 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
869 while ($dao->fetch()) {
870 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
872 $pledgeDetails[$dao->payment_id
] = array(
873 'scheduled_date' => $dao->scheduled_date
,
874 'amount_due' => $dao->amount_due
,
875 'amount' => $dao->amount
,
876 'amount_paid' => $dao->amount_paid
,
877 'create_date' => $dao->create_date
,
878 'contact_id' => $dao->contact_id
,
879 'pledge_id' => $dao->pledge_id
,
880 'checksumValue' => $checksumValue,
881 'contribution_page_id' => $dao->contribution_page_id
,
882 'reminder_count' => $dao->reminder_count
,
883 'max_reminders' => $dao->max_reminders
,
884 'reminder_date' => $dao->reminder_date
,
885 'initial_reminder_day' => $dao->initial_reminder_day
,
886 'additional_reminder_day' => $dao->additional_reminder_day
,
887 'pledge_status' => $dao->pledge_status
,
888 'payment_status' => $dao->payment_status
,
889 'is_test' => $dao->is_test
,
890 'currency' => $dao->currency
,
891 'campaign_id' => $dao->campaign_id
,
894 $contactIds[$dao->contact_id
] = $dao->contact_id
;
895 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
897 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
899 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)) {
900 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
904 // process the updating script...
906 foreach ($pledgePayments as $pledgeId => $paymentIds) {
907 // 1. update the pledge /pledge payment status. returns new status when an update happens
908 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
910 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
911 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
913 if ($newStatus != $pledgeStatus[$pledgeId]) {
914 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
919 if ($sendReminders) {
920 // retrieve domain tokens
921 $domain = CRM_Core_BAO_Domain
::getDomain();
922 $tokens = array('domain' => array('name', 'phone', 'address', 'email'),
923 'contact' => CRM_Core_SelectValues
::contactTokens(),
926 $domainValues = array();
927 foreach ($tokens['domain'] as $token) {
928 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
931 //get the domain email address, since we don't carry w/ object.
932 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
933 $domainValues['email'] = $domainValue[1];
935 // retrieve contact tokens
937 // this function does NOT return Deceased contacts since we don't want to send them email
938 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
941 $tokens, 'CRM_UpdatePledgeRecord'
944 // assign domain values to template
945 $template = CRM_Core_Smarty
::singleton();
946 $template->assign('domain', $domainValues);
949 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
951 foreach ($pledgeDetails as $paymentId => $details) {
952 if (array_key_exists($details['contact_id'], $contactDetails)) {
953 $contactId = $details['contact_id'];
954 $pledgerName = $contactDetails[$contactId]['display_name'];
960 if (empty($details['reminder_date'])) {
961 $nextReminderDate = new DateTime($details['scheduled_date']);
962 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
963 $nextReminderDate = $nextReminderDate->format("Ymd");
966 $nextReminderDate = new DateTime($details['reminder_date']);
967 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
968 $nextReminderDate = $nextReminderDate->format("Ymd");
970 if (($details['reminder_count'] < $details['max_reminders'])
971 && ($nextReminderDate <= $now)
974 $toEmail = $doNotEmail = $onHold = NULL;
976 if (!empty($contactDetails[$contactId]['email'])) {
977 $toEmail = $contactDetails[$contactId]['email'];
980 if (!empty($contactDetails[$contactId]['do_not_email'])) {
981 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
984 if (!empty($contactDetails[$contactId]['on_hold'])) {
985 $onHold = $contactDetails[$contactId]['on_hold'];
988 // 2. send acknowledgement mail
989 if ($toEmail && !($doNotEmail ||
$onHold)) {
990 //assign value to template
991 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
992 $template->assign('contact', $contactDetails[$contactId]);
993 $template->assign('next_payment', $details['scheduled_date']);
994 $template->assign('amount_due', $details['amount_due']);
995 $template->assign('checksumValue', $details['checksumValue']);
996 $template->assign('contribution_page_id', $details['contribution_page_id']);
997 $template->assign('pledge_id', $details['pledge_id']);
998 $template->assign('scheduled_payment_date', $details['scheduled_date']);
999 $template->assign('amount', $details['amount']);
1000 $template->assign('create_date', $details['create_date']);
1001 $template->assign('currency', $details['currency']);
1002 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates
::sendTemplate(
1004 'groupName' => 'msg_tpl_workflow_pledge',
1005 'valueName' => 'pledge_reminder',
1006 'contactId' => $contactId,
1007 'from' => $receiptFrom,
1008 'toName' => $pledgerName,
1009 'toEmail' => $toEmail,
1013 // 3. update pledge payment details
1015 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1016 $activityType = 'Pledge Reminder';
1017 $activityParams = array(
1018 'subject' => $subject,
1019 'source_contact_id' => $contactId,
1020 'source_record_id' => $paymentId,
1021 'assignee_contact_id' => $contactId,
1022 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1026 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1027 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1028 'is_test' => $details['is_test'],
1030 'campaign_id' => $details['campaign_id'],
1032 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1033 $returnMessages[] = "Failed creating Activity for acknowledgment";
1034 return array('is_error' => 1, 'message' => $returnMessages);
1036 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1041 // end foreach on $pledgeDetails
1043 // end if ( $sendReminders )
1044 $returnMessages[] = "{$updateCnt} records updated.";
1046 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1050 * Mark a pledge (and any outstanding payments) as cancelled.
1052 * @param int $pledgeID
1054 public static function cancel($pledgeID) {
1055 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1056 $paymentIDs = self
::findCancelablePayments($pledgeID);
1057 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1058 $statuses['Cancelled'], 0, FALSE, TRUE
1063 * Find payments which can be safely canceled.
1065 * @param int $pledgeID
1066 * @return array of int (civicrm_pledge_payment.id)
1068 public static function findCancelablePayments($pledgeID) {
1069 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1071 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1072 $paymentDAO->pledge_id
= $pledgeID;
1073 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1074 $statuses['Overdue'],
1075 $statuses['Pending']
1077 $paymentDAO->find();
1079 $paymentIDs = array();
1080 while ($paymentDAO->fetch()) {
1081 $paymentIDs[] = $paymentDAO->id
;