3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
33 class CRM_Pledge_BAO_Pledge
extends CRM_Pledge_DAO_Pledge
{
36 * Static field for all the pledge information that we can potentially export.
40 static $_exportableFields = NULL;
45 public function __construct() {
46 parent
::__construct();
50 * Retrieve DB object based on input parameters.
52 * It also stores all the retrieved values in the default array.
54 * @param array $params
55 * (reference ) an assoc array of name/value pairs.
56 * @param array $defaults
57 * (reference ) an assoc array to hold the flattened values.
59 * @return CRM_Pledge_BAO_Pledge
61 public static function retrieve(&$params, &$defaults) {
62 $pledge = new CRM_Pledge_DAO_Pledge();
63 $pledge->copyValues($params);
64 if ($pledge->find(TRUE)) {
65 CRM_Core_DAO
::storeValues($pledge, $defaults);
74 * @param array $params
75 * Reference array contains the values submitted by the form.
80 public static function add(&$params) {
81 if (!empty($params['id'])) {
82 CRM_Utils_Hook
::pre('edit', 'Pledge', $params['id'], $params);
85 CRM_Utils_Hook
::pre('create', 'Pledge', NULL, $params);
88 $pledge = new CRM_Pledge_DAO_Pledge();
90 // if pledge is complete update end date as current date
91 if ($pledge->status_id
== 1) {
92 $pledge->end_date
= date('Ymd');
95 $pledge->copyValues($params);
97 // set currency for CRM-1496
98 if (!isset($pledge->currency
)) {
99 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
102 $result = $pledge->save();
104 if (!empty($params['id'])) {
105 CRM_Utils_Hook
::post('edit', 'Pledge', $pledge->id
, $pledge);
108 CRM_Utils_Hook
::post('create', 'Pledge', $pledge->id
, $pledge);
115 * Given the list of params in the params array, fetch the object
116 * and store the values in the values array
118 * @param array $params
119 * Input parameters to find object.
120 * @param array $values
121 * Output values of the object.
122 * @param array $returnProperties
123 * If you want to return specific fields.
126 * associated array of field values
128 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
129 if (empty($params)) {
132 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
137 * Takes an associative array and creates a pledge object.
139 * @param array $params
140 * (reference ) an assoc array of name/value pairs.
142 * @return CRM_Pledge_BAO_Pledge
144 public static function create(&$params) {
145 // FIXME: a cludgy hack to fix the dates to MySQL format
146 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
147 foreach ($dateFields as $df) {
148 if (isset($params[$df])) {
149 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
153 $isRecalculatePledgePayment = self
::isPaymentsRequireRecalculation($params);
154 $transaction = new CRM_Core_Transaction();
156 $paymentParams = array();
157 $paymentParams['status_id'] = CRM_Utils_Array
::value('status_id', $params);
158 if (!empty($params['installment_amount'])) {
159 $params['amount'] = $params['installment_amount'] * $params['installments'];
162 // get All Payments status types.
163 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
165 // update the pledge status only if it does NOT come from form
166 if (!isset($params['pledge_status_id'])) {
167 if (isset($params['contribution_id'])) {
168 if ($params['installments'] > 1) {
169 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
173 if (!empty($params['id'])) {
174 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
177 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
182 $pledge = self
::add($params);
183 if (is_a($pledge, 'CRM_Core_Error')) {
188 // handle custom data.
189 if (!empty($params['custom']) &&
190 is_array($params['custom'])
192 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
195 // skip payment stuff inedit mode
196 if (!isset($params['id']) ||
$isRecalculatePledgePayment) {
198 // if pledge is pending delete all payments and recreate.
199 if ($isRecalculatePledgePayment) {
200 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
203 // building payment params
204 $paymentParams['pledge_id'] = $pledge->id
;
205 $paymentKeys = array(
212 'frequency_interval',
214 'installment_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 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
242 $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) . ')';
244 // add the recently created Pledge
245 CRM_Utils_Recent
::add($title,
258 * Is this a change to an existing pending pledge requiring payment schedule changes.
260 * If the pledge is pending the code (slightly lazily) deletes & recreates pledge payments.
262 * If the payment dates or amounts have been manually edited then this can cause data loss. We can mitigate this to
263 * some extent by making sure we have a change that could potentially affect the schedule (rather than just a
264 * custom data change or similar).
266 * This calculation needs to be performed before update takes place as previous & new pledges are compared.
268 * @param array $params
272 protected static function isPaymentsRequireRecalculation($params) {
273 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
276 $scheduleChangingParameters = array(
279 'frequency_interval',
284 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
285 $existingPledgeDAO->id
= $params['id'];
286 $existingPledgeDAO->find(TRUE);
287 foreach ($scheduleChangingParameters as $parameter) {
288 if ($parameter == 'start_date') {
289 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
293 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
307 public static function deletePledge($id) {
308 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
310 $transaction = new CRM_Core_Transaction();
312 // check for no Completed Payment records with the pledge
313 $payment = new CRM_Pledge_DAO_PledgePayment();
314 $payment->pledge_id
= $id;
317 while ($payment->fetch()) {
318 // also delete associated contribution.
319 if ($payment->contribution_id
) {
320 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
325 $dao = new CRM_Pledge_DAO_Pledge();
327 $results = $dao->delete();
329 $transaction->commit();
331 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
333 // delete the recently created Pledge
334 $pledgeRecent = array(
338 CRM_Utils_Recent
::del($pledgeRecent);
344 * Get the amount details date wise.
346 * @param string $status
347 * @param string $startDate
348 * @param string $endDate
352 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
354 $select = $from = $queryDate = NULL;
356 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
357 $statusId = array_search($status, $allStatus);
361 $statusId = array_search('Cancelled', $allStatus);
362 $where[] = 'status_id != ' . $statusId;
366 $where[] = 'status_id = ' . $statusId;
370 $where[] = 'status_id = ' . $statusId;
374 $where[] = 'status_id = ' . $statusId;
378 $where[] = 'status_id = ' . $statusId;
383 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
386 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
389 $whereCond = implode(' AND ', $where);
392 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
394 WHERE $whereCond AND is_test=0
397 $start = substr($startDate, 0, 8);
398 $end = substr($endDate, 0, 8);
401 $dao = CRM_Core_DAO
::executeQuery($query);
402 while ($dao->fetch()) {
403 $pCount +
= $dao->pledge_count
;
404 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
407 $pledge_amount = array(
408 'pledge_amount' => implode(', ', $pamount),
409 'pledge_count' => $pCount,
410 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
411 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
416 $statusId = array_search($status, $allStatus);
419 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
420 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
421 $queryDate = 'receive_date';
422 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
426 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
427 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
428 $queryDate = 'receive_date';
429 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
433 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
434 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
435 $queryDate = 'scheduled_date';
436 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
440 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
441 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
442 $queryDate = 'scheduled_date';
443 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
448 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
451 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
454 $whereCond = implode(' AND ', $where);
457 SELECT $select, cp.currency
463 $dao = CRM_Core_DAO
::executeQuery($query);
467 while ($dao->fetch()) {
468 $count +
= $dao->received_count
;
469 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
473 return array_merge($pledge_amount, array(
474 'received_amount' => implode(', ', $amount),
475 'received_count' => $count,
476 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
477 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
483 return $pledge_amount;
489 * Get list of pledges In Honor of contact Ids.
491 * @param int $honorId
492 * In Honor of Contact ID.
495 * return the list of pledge fields
497 public static function getHonorContacts($honorId) {
499 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
500 $honorDAO->contact_id
= $honorId;
504 while ($honorDAO->fetch()) {
505 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
506 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
507 if ($pledgePaymentDAO->find(TRUE)) {
508 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
509 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
510 if ($pledgeDAO->find(TRUE)) {
511 $params[$pledgeDAO->id
] = array(
512 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
513 'honorId' => $pledgeDAO->contact_id
,
514 'amount' => $pledgeDAO->amount
,
515 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
516 'create_date' => $pledgeDAO->create_date
,
517 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
518 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
519 $pledgeDAO->financial_type_id
, 'name'
521 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
522 $pledgeDAO->contact_id
, 'display_name'
533 * Send Acknowledgment and create activity.
535 * @param CRM_Core_Form $form
537 * @param array $params
538 * An assoc array of name/value pairs.
540 public static function sendAcknowledgment(&$form, $params) {
541 //handle Acknowledgment.
542 $allPayments = $payments = array();
544 // get All Payments status types.
545 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
546 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
547 // get all paymnets details.
548 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
550 if (!empty($allPayments)) {
551 foreach ($allPayments as $payID => $values) {
552 $contributionValue = $contributionStatus = array();
553 if (isset($values['contribution_id'])) {
554 $contributionParams = array('id' => $values['contribution_id']);
555 $returnProperties = array('contribution_status_id', 'receive_date');
556 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
557 $contributionParams, $contributionStatus, $returnProperties
559 $contributionValue = array(
560 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
561 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
564 $payments[$payID] = array_merge($contributionValue,
566 'amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
567 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
571 // get the first valid payment id.
572 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
573 $paymentStatusTypes[$values['status_id']] == 'Overdue'
576 $form->paymentId
= $values['id'];
581 // assign pledge fields value to template.
582 $pledgeFields = array(
584 'total_pledge_amount',
585 'frequency_interval',
592 foreach ($pledgeFields as $field) {
593 if (!empty($params[$field])) {
594 $form->assign($field, $params[$field]);
598 // assign all payments details.
600 $form->assign('payments', $payments);
603 // handle domain token values
604 $domain = CRM_Core_BAO_Domain
::getDomain();
606 'domain' => array('name', 'phone', 'address', 'email'),
607 'contact' => CRM_Core_SelectValues
::contactTokens(),
609 $domainValues = array();
610 foreach ($tokens['domain'] as $token) {
611 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
613 $form->assign('domain', $domainValues);
615 // handle contact token values.
616 $ids = array($params['contact_id']);
617 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
618 array('display_name', 'checksum', 'contact_id')
620 foreach ($fields as $key => $val) {
621 $returnProperties[$val] = TRUE;
623 $details = CRM_Utils_Token
::getTokenDetails($ids,
629 $form->assign('contact', $details[0][$params['contact_id']]);
631 // handle custom data.
632 if (!empty($params['hidden_custom'])) {
633 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
634 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
635 $customGroup = array();
636 // retrieve custom data
637 foreach ($groupTree as $groupID => $group) {
638 $customFields = $customValues = array();
639 if ($groupID == 'info') {
642 foreach ($group['fields'] as $k => $field) {
643 $field['title'] = $field['label'];
644 $customFields["custom_{$k}"] = $field;
647 // to build array of customgroup & customfields in it
648 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
649 $customGroup[$group['title']] = $customValues;
652 $form->assign('customGroup', $customGroup);
655 // handle acknowledgment email stuff.
656 list($pledgerDisplayName,
658 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
660 // check for online pledge.
661 if (!empty($params['receipt_from_email'])) {
662 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
663 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
665 elseif (!empty($params['from_email_id'])) {
666 $receiptFrom = $params['from_email_id'];
668 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
669 // check for logged in user.
670 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
673 // set the domain values.
674 $userName = CRM_Utils_Array
::value('name', $domainValues);
675 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
678 if (!isset($receiptFrom)) {
679 $receiptFrom = "$userName <$userEmail>";
682 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
684 'groupName' => 'msg_tpl_workflow_pledge',
685 'valueName' => 'pledge_acknowledge',
686 'contactId' => $params['contact_id'],
687 'from' => $receiptFrom,
688 'toName' => $pledgerDisplayName,
689 'toEmail' => $pledgerEmail,
693 // check if activity record exist for this pledge
694 // Acknowledgment, if exist do not add activity.
695 $activityType = 'Pledge Acknowledgment';
696 $activity = new CRM_Activity_DAO_Activity();
697 $activity->source_record_id
= $params['id'];
698 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
704 $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)';
706 if (!$activity->find()) {
707 $activityParams = array(
708 'subject' => $subject,
709 'source_contact_id' => $params['contact_id'],
710 'source_record_id' => $params['id'],
711 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
715 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
716 'is_test' => $params['is_test'],
718 'details' => $details,
719 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
722 // lets insert assignee record.
723 if (!empty($params['contact_id'])) {
724 $activityParams['assignee_contact_id'] = $params['contact_id'];
727 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
728 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
734 * Combine all the exportable fields from the lower levels object.
736 * @param bool $checkPermission
739 * array of exportable Fields
741 public static function exportableFields($checkPermission = TRUE) {
742 if (!self
::$_exportableFields) {
743 if (!self
::$_exportableFields) {
744 self
::$_exportableFields = array();
747 $fields = CRM_Pledge_DAO_Pledge
::export();
749 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
751 // set title to calculated fields
752 $calculatedFields = array(
753 'pledge_total_paid' => array('title' => ts('Total Paid')),
754 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
755 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
756 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
757 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
758 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
759 'pledge_payment_status' => array(
760 'title' => ts('Pledge Payment Status'),
761 'name' => 'pledge_payment_status',
762 'data_type' => CRM_Utils_Type
::T_STRING
,
766 $pledgeFields = array(
767 'pledge_status' => array(
768 'title' => 'Pledge Status',
769 'name' => 'pledge_status',
770 'data_type' => CRM_Utils_Type
::T_STRING
,
772 'pledge_frequency_unit' => array(
773 'title' => 'Pledge Frequency Unit',
774 'name' => 'pledge_frequency_unit',
775 'data_type' => CRM_Utils_Type
::T_ENUM
,
777 'pledge_frequency_interval' => array(
778 'title' => 'Pledge Frequency Interval',
779 'name' => 'pledge_frequency_interval',
780 'data_type' => CRM_Utils_Type
::T_INT
,
782 'pledge_contribution_page_id' => array(
783 'title' => 'Pledge Contribution Page Id',
784 'name' => 'pledge_contribution_page_id',
785 'data_type' => CRM_Utils_Type
::T_INT
,
789 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
792 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
793 self
::$_exportableFields = $fields;
796 return self
::$_exportableFields;
800 * Get pending or in progress pledges.
802 * @param int $contactID
806 * associated array of pledge id(s)
808 public static function getContactPledges($contactID) {
809 $pledgeDetails = array();
810 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
814 // get pending and in progress status
820 if ($statusId = array_search($name, $pledgeStatuses)) {
821 $status[] = $statusId;
824 if (empty($status)) {
825 return $pledgeDetails;
828 $statusClause = " IN (" . implode(',', $status) . ")";
831 SELECT civicrm_pledge.id id
833 WHERE civicrm_pledge.status_id {$statusClause}
834 AND civicrm_pledge.contact_id = %1
837 $params[1] = array($contactID, 'Integer');
838 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
840 while ($pledge->fetch()) {
841 $pledgeDetails[] = $pledge->id
;
844 return $pledgeDetails;
848 * Get pledge record count for a Contact.
850 * @param int $contactID
853 * count of pledge records
855 public static function getContactPledgeCount($contactID) {
856 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
857 return CRM_Core_DAO
::singleValueQuery($query);
861 * @param array $params
865 public static function updatePledgeStatus($params) {
867 $returnMessages = array();
869 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
871 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
873 // unset statues that we never use for pledges
879 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
880 unset($allStatus[$key]);
884 $statusIds = implode(',', array_keys($allStatus));
888 SELECT pledge.contact_id as contact_id,
889 pledge.id as pledge_id,
890 pledge.amount as amount,
891 payment.scheduled_date as scheduled_date,
892 pledge.create_date as create_date,
893 payment.id as payment_id,
894 pledge.currency as currency,
895 pledge.contribution_page_id as contribution_page_id,
896 payment.reminder_count as reminder_count,
897 pledge.max_reminders as max_reminders,
898 payment.reminder_date as reminder_date,
899 pledge.initial_reminder_day as initial_reminder_day,
900 pledge.additional_reminder_day as additional_reminder_day,
901 pledge.status_id as pledge_status,
902 payment.status_id as payment_status,
903 pledge.is_test as is_test,
904 pledge.campaign_id as campaign_id,
905 SUM(payment.scheduled_amount) as amount_due,
906 ( SELECT sum(civicrm_pledge_payment.actual_amount)
907 FROM civicrm_pledge_payment
908 WHERE civicrm_pledge_payment.status_id = 1
909 AND civicrm_pledge_payment.pledge_id = pledge.id
911 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
912 WHERE pledge.id = payment.pledge_id
913 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
917 $dao = CRM_Core_DAO
::executeQuery($query);
920 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
921 while ($dao->fetch()) {
922 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
924 $pledgeDetails[$dao->payment_id
] = array(
925 'scheduled_date' => $dao->scheduled_date
,
926 'amount_due' => $dao->amount_due
,
927 'amount' => $dao->amount
,
928 'amount_paid' => $dao->amount_paid
,
929 'create_date' => $dao->create_date
,
930 'contact_id' => $dao->contact_id
,
931 'pledge_id' => $dao->pledge_id
,
932 'checksumValue' => $checksumValue,
933 'contribution_page_id' => $dao->contribution_page_id
,
934 'reminder_count' => $dao->reminder_count
,
935 'max_reminders' => $dao->max_reminders
,
936 'reminder_date' => $dao->reminder_date
,
937 'initial_reminder_day' => $dao->initial_reminder_day
,
938 'additional_reminder_day' => $dao->additional_reminder_day
,
939 'pledge_status' => $dao->pledge_status
,
940 'payment_status' => $dao->payment_status
,
941 'is_test' => $dao->is_test
,
942 'currency' => $dao->currency
,
943 'campaign_id' => $dao->campaign_id
,
946 $contactIds[$dao->contact_id
] = $dao->contact_id
;
947 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
949 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
951 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)
953 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
957 // process the updating script...
959 foreach ($pledgePayments as $pledgeId => $paymentIds) {
960 // 1. update the pledge /pledge payment status. returns new status when an update happens
961 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
963 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
964 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
966 if ($newStatus != $pledgeStatus[$pledgeId]) {
967 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
972 if ($sendReminders) {
973 // retrieve domain tokens
974 $domain = CRM_Core_BAO_Domain
::getDomain();
976 'domain' => array('name', 'phone', 'address', 'email'),
977 'contact' => CRM_Core_SelectValues
::contactTokens(),
980 $domainValues = array();
981 foreach ($tokens['domain'] as $token) {
982 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
985 // get the domain email address, since we don't carry w/ object.
986 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
987 $domainValues['email'] = $domainValue[1];
989 // retrieve contact tokens
991 // this function does NOT return Deceased contacts since we don't want to send them email
992 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
995 $tokens, 'CRM_UpdatePledgeRecord'
998 // assign domain values to template
999 $template = CRM_Core_Smarty
::singleton();
1000 $template->assign('domain', $domainValues);
1003 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
1005 foreach ($pledgeDetails as $paymentId => $details) {
1006 if (array_key_exists($details['contact_id'], $contactDetails)) {
1007 $contactId = $details['contact_id'];
1008 $pledgerName = $contactDetails[$contactId]['display_name'];
1014 if (empty($details['reminder_date'])) {
1015 $nextReminderDate = new DateTime($details['scheduled_date']);
1016 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
1017 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
1018 $nextReminderDate = $nextReminderDate->format("Ymd");
1021 $nextReminderDate = new DateTime($details['reminder_date']);
1022 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
1023 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
1024 $nextReminderDate = $nextReminderDate->format("Ymd");
1026 if (($details['reminder_count'] < $details['max_reminders'])
1027 && ($nextReminderDate <= $now)
1030 $toEmail = $doNotEmail = $onHold = NULL;
1032 if (!empty($contactDetails[$contactId]['email'])) {
1033 $toEmail = $contactDetails[$contactId]['email'];
1036 if (!empty($contactDetails[$contactId]['do_not_email'])) {
1037 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
1040 if (!empty($contactDetails[$contactId]['on_hold'])) {
1041 $onHold = $contactDetails[$contactId]['on_hold'];
1044 // 2. send acknowledgement mail
1045 if ($toEmail && !($doNotEmail ||
$onHold)) {
1046 // assign value to template
1047 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1048 $template->assign('contact', $contactDetails[$contactId]);
1049 $template->assign('next_payment', $details['scheduled_date']);
1050 $template->assign('amount_due', $details['amount_due']);
1051 $template->assign('checksumValue', $details['checksumValue']);
1052 $template->assign('contribution_page_id', $details['contribution_page_id']);
1053 $template->assign('pledge_id', $details['pledge_id']);
1054 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1055 $template->assign('amount', $details['amount']);
1056 $template->assign('create_date', $details['create_date']);
1057 $template->assign('currency', $details['currency']);
1058 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1060 'groupName' => 'msg_tpl_workflow_pledge',
1061 'valueName' => 'pledge_reminder',
1062 'contactId' => $contactId,
1063 'from' => $receiptFrom,
1064 'toName' => $pledgerName,
1065 'toEmail' => $toEmail,
1069 // 3. update pledge payment details
1071 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1072 $activityType = 'Pledge Reminder';
1073 $activityParams = array(
1074 'subject' => $subject,
1075 'source_contact_id' => $contactId,
1076 'source_record_id' => $paymentId,
1077 'assignee_contact_id' => $contactId,
1078 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1082 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1083 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1084 'is_test' => $details['is_test'],
1086 'campaign_id' => $details['campaign_id'],
1088 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1089 $returnMessages[] = "Failed creating Activity for acknowledgment";
1090 return array('is_error' => 1, 'message' => $returnMessages);
1092 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1097 // end foreach on $pledgeDetails
1099 // end if ( $sendReminders )
1100 $returnMessages[] = "{$updateCnt} records updated.";
1102 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1106 * Mark a pledge (and any outstanding payments) as cancelled.
1108 * @param int $pledgeID
1110 public static function cancel($pledgeID) {
1111 $paymentIDs = self
::findCancelablePayments($pledgeID);
1112 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1113 $cancelled = array_search('Cancelled', $status);
1114 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1115 $cancelled, 0, FALSE, TRUE
1120 * Find payments which can be safely canceled.
1122 * @param int $pledgeID
1124 * Array of int (civicrm_pledge_payment.id)
1126 public static function findCancelablePayments($pledgeID) {
1127 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1129 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1130 $paymentDAO->pledge_id
= $pledgeID;
1131 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1132 $statuses['Overdue'],
1133 $statuses['Pending']
1135 $paymentDAO->find();
1137 $paymentIDs = array();
1138 while ($paymentDAO->fetch()) {
1139 $paymentIDs[] = $paymentDAO->id
;
1145 * Is this pledge free from financial transactions (this is important to know as we allow editing
1146 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1147 * & recreating so we want to block that if appropriate).
1149 * @param int $pledgeID
1150 * @param int $pledgeStatusID
1152 * do financial transactions exist for this pledge?
1154 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1155 if (empty($pledgeStatusID)) {
1156 // why would this happen? If we can see where it does then we can see if we should look it up.
1157 // but assuming from form code it CAN be empty.
1160 if (self
::isTransactedStatus($pledgeStatusID)) {
1164 return civicrm_api3('pledge_payment', 'getcount', array(
1165 'pledge_id' => $pledgeID,
1166 'status_id' => array('IN' => self
::getTransactionalStatus()),
1171 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1172 * @param int $statusID
1176 * is it a transactional status?
1178 protected static function isTransactedStatus($statusID) {
1179 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1186 * Get array of non transactional statuses.
1188 * non transactional status ids
1190 protected static function getNonTransactionalStatus() {
1191 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1192 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1196 * Get array of non transactional statuses.
1198 * non transactional status ids
1200 protected static function getTransactionalStatus() {
1201 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1202 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());