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(
215 'amount', 'installments', 'scheduled_date', 'frequency_unit', 'currency',
216 'frequency_day', 'frequency_interval', 'contribution_id', 'installment_amount', 'actual_amount',
218 foreach ($paymentKeys as $key) {
219 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
221 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
224 $transaction->commit();
226 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
227 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
230 $recentOther = array();
231 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
232 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
233 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
236 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
237 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
238 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
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
) . ' - ' . CRM_Utils_Array
::value($pledge->financial_type_id
, $contributionTypes) . ')';
245 // add the recently created Pledge
246 CRM_Utils_Recent
::add($title,
267 public static function deletePledge($id) {
268 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
270 $transaction = new CRM_Core_Transaction();
272 //check for no Completed Payment records with the pledge
273 $payment = new CRM_Pledge_DAO_PledgePayment();
274 $payment->pledge_id
= $id;
277 while ($payment->fetch()) {
278 //also delete associated contribution.
279 if ($payment->contribution_id
) {
280 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
285 $dao = new CRM_Pledge_DAO_Pledge();
287 $results = $dao->delete();
289 $transaction->commit();
291 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
293 // delete the recently created Pledge
294 $pledgeRecent = array(
298 CRM_Utils_Recent
::del($pledgeRecent);
304 * Get the amount details date wise.
306 * @param string $status
307 * @param string $startDate
308 * @param string $endDate
312 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
314 $select = $from = $queryDate = NULL;
316 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
317 $statusId = array_search($status, $allStatus);
321 $statusId = array_search('Cancelled', $allStatus);
322 $where[] = 'status_id != ' . $statusId;
326 $where[] = 'status_id = ' . $statusId;
330 $where[] = 'status_id = ' . $statusId;
334 $where[] = 'status_id = ' . $statusId;
338 $where[] = 'status_id = ' . $statusId;
343 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
346 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
349 $whereCond = implode(' AND ', $where);
352 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
354 WHERE $whereCond AND is_test=0
357 $start = substr($startDate, 0, 8);
358 $end = substr($endDate, 0, 8);
361 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
362 while ($dao->fetch()) {
363 $pCount +
= $dao->pledge_count
;
364 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
367 $pledge_amount = array(
368 'pledge_amount' => implode(', ', $pamount),
369 'pledge_count' => $pCount,
370 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
371 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
376 $statusId = array_search($status, $allStatus);
379 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
380 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
381 $queryDate = 'receive_date';
382 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
386 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
387 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
388 $queryDate = 'receive_date';
389 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
393 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
394 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
395 $queryDate = 'scheduled_date';
396 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
400 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
401 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
402 $queryDate = 'scheduled_date';
403 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
408 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
411 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
414 $whereCond = implode(' AND ', $where);
417 SELECT $select, cp.currency
423 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
427 while ($dao->fetch()) {
428 $count +
= $dao->received_count
;
429 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
433 return array_merge($pledge_amount, array(
434 'received_amount' => implode(', ', $amount),
435 'received_count' => $count,
436 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
437 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
443 return $pledge_amount;
449 * Get list of pledges In Honor of contact Ids
451 * @param int $honorId
452 * In Honor of Contact ID.
455 * return the list of pledge fields
459 public static function getHonorContacts($honorId) {
461 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
462 $honorDAO->contact_id
= $honorId;
466 while ($honorDAO->fetch()) {
467 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
468 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
469 if ($pledgePaymentDAO->find(TRUE)) {
470 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
471 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
472 if ($pledgeDAO->find(TRUE)) {
473 $params[$pledgeDAO->id
] = array(
474 'honor_type' => CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value'),
475 'honorId' => $pledgeDAO->contact_id
,
476 'amount' => $pledgeDAO->amount
,
477 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
478 'create_date' => $pledgeDAO->create_date
,
479 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
480 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
481 $pledgeDAO->financial_type_id
, 'name'
483 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
484 $pledgeDAO->contact_id
, 'display_name'
495 * Send Acknowledgment and create activity.
497 * @param CRM_Core_Form $form
499 * @param array $params
500 * An assoc array of name/value pairs.
504 public static function sendAcknowledgment(&$form, $params) {
505 //handle Acknowledgment.
506 $allPayments = $payments = array();
508 //get All Payments status types.
509 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
510 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
511 //get all paymnets details.
512 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
514 if (!empty($allPayments)) {
515 foreach ($allPayments as $payID => $values) {
516 $contributionValue = $contributionStatus = array();
517 if (isset($values['contribution_id'])) {
518 $contributionParams = array('id' => $values['contribution_id']);
519 $returnProperties = array('contribution_status_id', 'receive_date');
520 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
521 $contributionParams, $contributionStatus, $returnProperties
523 $contributionValue = array(
524 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
525 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
528 $payments[$payID] = array_merge($contributionValue,
530 'amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
531 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
535 //get the first valid payment id.
536 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
537 $paymentStatusTypes[$values['status_id']] == 'Overdue'
539 $form->paymentId
= $values['id'];
544 //assign pledge fields value to template.
545 $pledgeFields = array(
546 'create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit',
547 'installments', 'frequency_day', 'scheduled_amount', 'currency',
549 foreach ($pledgeFields as $field) {
550 if (!empty($params[$field])) {
551 $form->assign($field, $params[$field]);
555 //assign all payments details.
557 $form->assign('payments', $payments);
560 //handle domain token values
561 $domain = CRM_Core_BAO_Domain
::getDomain();
563 'domain' => array('name', 'phone', 'address', 'email'),
564 'contact' => CRM_Core_SelectValues
::contactTokens(),
566 $domainValues = array();
567 foreach ($tokens['domain'] as $token) {
568 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
570 $form->assign('domain', $domainValues);
572 //handle contact token values.
573 $ids = array($params['contact_id']);
574 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
575 array('display_name', 'checksum', 'contact_id')
577 foreach ($fields as $key => $val) {
578 $returnProperties[$val] = TRUE;
580 $details = CRM_Utils_Token
::getTokenDetails($ids,
586 $form->assign('contact', $details[0][$params['contact_id']]);
588 //handle custom data.
589 if (!empty($params['hidden_custom'])) {
590 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
591 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
592 $customGroup = array();
593 // retrieve custom data
594 foreach ($groupTree as $groupID => $group) {
595 $customFields = $customValues = array();
596 if ($groupID == 'info') {
599 foreach ($group['fields'] as $k => $field) {
600 $field['title'] = $field['label'];
601 $customFields["custom_{$k}"] = $field;
604 //to build array of customgroup & customfields in it
605 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
606 $customGroup[$group['title']] = $customValues;
609 $form->assign('customGroup', $customGroup);
612 //handle acknowledgment email stuff.
613 list($pledgerDisplayName,
615 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
617 //check for online pledge.
618 $session = CRM_Core_Session
::singleton();
619 if (!empty($params['receipt_from_email'])) {
620 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
621 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
623 elseif (!empty($params['from_email_id'])) {
624 $receiptFrom = $params['from_email_id'];
626 elseif ($userID = $session->get('userID')) {
627 //check for logged in user.
628 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
631 //set the domain values.
632 $userName = CRM_Utils_Array
::value('name', $domainValues);
633 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
636 if (!isset($receiptFrom)) {
637 $receiptFrom = "$userName <$userEmail>";
640 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
642 'groupName' => 'msg_tpl_workflow_pledge',
643 'valueName' => 'pledge_acknowledge',
644 'contactId' => $params['contact_id'],
645 'from' => $receiptFrom,
646 'toName' => $pledgerDisplayName,
647 'toEmail' => $pledgerEmail,
651 //check if activity record exist for this pledge
652 //Acknowledgment, if exist do not add activity.
653 $activityType = 'Pledge Acknowledgment';
654 $activity = new CRM_Activity_DAO_Activity();
655 $activity->source_record_id
= $params['id'];
656 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
660 $config = CRM_Core_Config
::singleton();
663 $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)';
665 if (!$activity->find()) {
666 $activityParams = array(
667 'subject' => $subject,
668 'source_contact_id' => $params['contact_id'],
669 'source_record_id' => $params['id'],
670 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
674 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
675 'is_test' => $params['is_test'],
677 'details' => $details,
678 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
681 //lets insert assignee record.
682 if (!empty($params['contact_id'])) {
683 $activityParams['assignee_contact_id'] = $params['contact_id'];
686 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
687 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
693 * Combine all the exportable fields from the lower levels object
696 * array of exportable Fields
699 public static function &exportableFields() {
700 if (!self
::$_exportableFields) {
701 if (!self
::$_exportableFields) {
702 self
::$_exportableFields = array();
705 $fields = CRM_Pledge_DAO_Pledge
::export();
707 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
709 //set title to calculated fields
710 $calculatedFields = array(
711 'pledge_total_paid' => array('title' => ts('Total Paid')),
712 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
713 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
714 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
715 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
716 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
717 'pledge_payment_status' => array(
718 'title' => ts('Pledge Payment Status'),
719 'name' => 'pledge_payment_status',
720 'data_type' => CRM_Utils_Type
::T_STRING
,
724 $pledgeFields = array(
725 'pledge_status' => array(
726 'title' => 'Pledge Status',
727 'name' => 'pledge_status',
728 'data_type' => CRM_Utils_Type
::T_STRING
,
730 'pledge_frequency_unit' => array(
731 'title' => 'Pledge Frequency Unit',
732 'name' => 'pledge_frequency_unit',
733 'data_type' => CRM_Utils_Type
::T_ENUM
,
735 'pledge_frequency_interval' => array(
736 'title' => 'Pledge Frequency Interval',
737 'name' => 'pledge_frequency_interval',
738 'data_type' => CRM_Utils_Type
::T_INT
,
740 'pledge_contribution_page_id' => array(
741 'title' => 'Pledge Contribution Page Id',
742 'name' => 'pledge_contribution_page_id',
743 'data_type' => CRM_Utils_Type
::T_INT
,
747 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
750 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
751 self
::$_exportableFields = $fields;
754 return self
::$_exportableFields;
758 * Get pending or in progress pledges
760 * @param int $contactID
764 * associated array of pledge id(s)
767 public static function getContactPledges($contactID) {
768 $pledgeDetails = array();
769 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
773 //get pending and in progress status
775 'Pending', 'In Progress', 'Overdue') as $name) {
776 if ($statusId = array_search($name, $pledgeStatuses)) {
777 $status[] = $statusId;
780 if (empty($status)) {
781 return $pledgeDetails;
784 $statusClause = " IN (" . implode(',', $status) . ")";
787 SELECT civicrm_pledge.id id
789 WHERE civicrm_pledge.status_id {$statusClause}
790 AND civicrm_pledge.contact_id = %1
793 $params[1] = array($contactID, 'Integer');
794 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
796 while ($pledge->fetch()) {
797 $pledgeDetails[] = $pledge->id
;
800 return $pledgeDetails;
804 * Get pledge record count for a Contact
806 * @param int $contactID
809 * count of pledge records
812 public static function getContactPledgeCount($contactID) {
813 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
814 return CRM_Core_DAO
::singleValueQuery($query);
818 * @param array $params
822 public static function updatePledgeStatus($params) {
824 $returnMessages = array();
826 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
828 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
830 //unset statues that we never use for pledges
832 'Completed', 'Cancelled', 'Failed') as $statusKey) {
833 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
834 unset($allStatus[$key]);
838 $statusIds = implode(',', array_keys($allStatus));
842 SELECT pledge.contact_id as contact_id,
843 pledge.id as pledge_id,
844 pledge.amount as amount,
845 payment.scheduled_date as scheduled_date,
846 pledge.create_date as create_date,
847 payment.id as payment_id,
848 pledge.currency as currency,
849 pledge.contribution_page_id as contribution_page_id,
850 payment.reminder_count as reminder_count,
851 pledge.max_reminders as max_reminders,
852 payment.reminder_date as reminder_date,
853 pledge.initial_reminder_day as initial_reminder_day,
854 pledge.additional_reminder_day as additional_reminder_day,
855 pledge.status_id as pledge_status,
856 payment.status_id as payment_status,
857 pledge.is_test as is_test,
858 pledge.campaign_id as campaign_id,
859 SUM(payment.scheduled_amount) as amount_due,
860 ( SELECT sum(civicrm_pledge_payment.actual_amount)
861 FROM civicrm_pledge_payment
862 WHERE civicrm_pledge_payment.status_id = 1
863 AND civicrm_pledge_payment.pledge_id = pledge.id
865 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
866 WHERE pledge.id = payment.pledge_id
867 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
871 $dao = CRM_Core_DAO
::executeQuery($query);
874 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
875 while ($dao->fetch()) {
876 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
878 $pledgeDetails[$dao->payment_id
] = array(
879 'scheduled_date' => $dao->scheduled_date
,
880 'amount_due' => $dao->amount_due
,
881 'amount' => $dao->amount
,
882 'amount_paid' => $dao->amount_paid
,
883 'create_date' => $dao->create_date
,
884 'contact_id' => $dao->contact_id
,
885 'pledge_id' => $dao->pledge_id
,
886 'checksumValue' => $checksumValue,
887 'contribution_page_id' => $dao->contribution_page_id
,
888 'reminder_count' => $dao->reminder_count
,
889 'max_reminders' => $dao->max_reminders
,
890 'reminder_date' => $dao->reminder_date
,
891 'initial_reminder_day' => $dao->initial_reminder_day
,
892 'additional_reminder_day' => $dao->additional_reminder_day
,
893 'pledge_status' => $dao->pledge_status
,
894 'payment_status' => $dao->payment_status
,
895 'is_test' => $dao->is_test
,
896 'currency' => $dao->currency
,
897 'campaign_id' => $dao->campaign_id
,
900 $contactIds[$dao->contact_id
] = $dao->contact_id
;
901 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
903 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
905 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)) {
906 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
910 // process the updating script...
912 foreach ($pledgePayments as $pledgeId => $paymentIds) {
913 // 1. update the pledge /pledge payment status. returns new status when an update happens
914 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
916 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
917 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
919 if ($newStatus != $pledgeStatus[$pledgeId]) {
920 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
925 if ($sendReminders) {
926 // retrieve domain tokens
927 $domain = CRM_Core_BAO_Domain
::getDomain();
929 'domain' => array('name', 'phone', 'address', 'email'),
930 'contact' => CRM_Core_SelectValues
::contactTokens(),
933 $domainValues = array();
934 foreach ($tokens['domain'] as $token) {
935 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
938 //get the domain email address, since we don't carry w/ object.
939 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
940 $domainValues['email'] = $domainValue[1];
942 // retrieve contact tokens
944 // this function does NOT return Deceased contacts since we don't want to send them email
945 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
948 $tokens, 'CRM_UpdatePledgeRecord'
951 // assign domain values to template
952 $template = CRM_Core_Smarty
::singleton();
953 $template->assign('domain', $domainValues);
956 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
958 foreach ($pledgeDetails as $paymentId => $details) {
959 if (array_key_exists($details['contact_id'], $contactDetails)) {
960 $contactId = $details['contact_id'];
961 $pledgerName = $contactDetails[$contactId]['display_name'];
967 if (empty($details['reminder_date'])) {
968 $nextReminderDate = new DateTime($details['scheduled_date']);
969 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
970 $nextReminderDate = $nextReminderDate->format("Ymd");
973 $nextReminderDate = new DateTime($details['reminder_date']);
974 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
975 $nextReminderDate = $nextReminderDate->format("Ymd");
977 if (($details['reminder_count'] < $details['max_reminders'])
978 && ($nextReminderDate <= $now)
981 $toEmail = $doNotEmail = $onHold = NULL;
983 if (!empty($contactDetails[$contactId]['email'])) {
984 $toEmail = $contactDetails[$contactId]['email'];
987 if (!empty($contactDetails[$contactId]['do_not_email'])) {
988 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
991 if (!empty($contactDetails[$contactId]['on_hold'])) {
992 $onHold = $contactDetails[$contactId]['on_hold'];
995 // 2. send acknowledgement mail
996 if ($toEmail && !($doNotEmail ||
$onHold)) {
997 //assign value to template
998 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
999 $template->assign('contact', $contactDetails[$contactId]);
1000 $template->assign('next_payment', $details['scheduled_date']);
1001 $template->assign('amount_due', $details['amount_due']);
1002 $template->assign('checksumValue', $details['checksumValue']);
1003 $template->assign('contribution_page_id', $details['contribution_page_id']);
1004 $template->assign('pledge_id', $details['pledge_id']);
1005 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1006 $template->assign('amount', $details['amount']);
1007 $template->assign('create_date', $details['create_date']);
1008 $template->assign('currency', $details['currency']);
1009 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1011 'groupName' => 'msg_tpl_workflow_pledge',
1012 'valueName' => 'pledge_reminder',
1013 'contactId' => $contactId,
1014 'from' => $receiptFrom,
1015 'toName' => $pledgerName,
1016 'toEmail' => $toEmail,
1020 // 3. update pledge payment details
1022 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1023 $activityType = 'Pledge Reminder';
1024 $activityParams = array(
1025 'subject' => $subject,
1026 'source_contact_id' => $contactId,
1027 'source_record_id' => $paymentId,
1028 'assignee_contact_id' => $contactId,
1029 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1033 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1034 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1035 'is_test' => $details['is_test'],
1037 'campaign_id' => $details['campaign_id'],
1039 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1040 $returnMessages[] = "Failed creating Activity for acknowledgment";
1041 return array('is_error' => 1, 'message' => $returnMessages);
1043 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1048 // end foreach on $pledgeDetails
1050 // end if ( $sendReminders )
1051 $returnMessages[] = "{$updateCnt} records updated.";
1053 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1057 * Mark a pledge (and any outstanding payments) as cancelled.
1059 * @param int $pledgeID
1061 public static function cancel($pledgeID) {
1062 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1063 $paymentIDs = self
::findCancelablePayments($pledgeID);
1064 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1065 $statuses['Cancelled'], 0, FALSE, TRUE
1070 * Find payments which can be safely canceled.
1072 * @param int $pledgeID
1074 * of int (civicrm_pledge_payment.id)
1076 public static function findCancelablePayments($pledgeID) {
1077 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1079 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1080 $paymentDAO->pledge_id
= $pledgeID;
1081 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1082 $statuses['Overdue'],
1083 $statuses['Pending']
1085 $paymentDAO->find();
1087 $paymentIDs = array();
1088 while ($paymentDAO->fetch()) {
1089 $paymentIDs[] = $paymentDAO->id
;
1095 * Is this pledge free from financial transactions (this is important to know as we allow editing
1096 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1097 * & recreating so we want to block that if appropriate
1099 * @param int $pledgeID
1100 * @param int $pledgeStatusID
1102 * do financial transactions exist for this pledge?
1104 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1105 if (empty($pledgeStatusID)) {
1106 //why would this happen? If we can see where it does then we can see if we should look it up
1107 //but assuming from form code it CAN be empty
1110 if (self
::isTransactedStatus($pledgeStatusID)) {
1114 return civicrm_api3('pledge_payment', 'getcount', array('pledge_id' => $pledgeID, 'status_id' => array('IN' => self
::getTransactionalStatus())));
1118 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1119 * @param int $statusID
1123 * is it a transactional status?
1125 protected static function isTransactedStatus($statusID) {
1126 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1133 * Get array of non transactional statuses
1135 * non transactional status ids
1137 protected static function getNonTransactionalStatus() {
1138 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1139 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1143 * Get array of non transactional statuses
1145 * non transactional status ids
1147 protected static function getTransactionalStatus() {
1148 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1149 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());