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 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
163 if (isset($params['contribution_id'])) {
164 if ($params['installments'] > 1) {
165 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
169 if (!empty($params['id'])) {
170 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
173 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
178 $pledge = self
::add($params);
179 if (is_a($pledge, 'CRM_Core_Error')) {
184 // handle custom data.
185 if (!empty($params['custom']) &&
186 is_array($params['custom'])
188 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
191 // skip payment stuff inedit mode
192 if (!isset($params['id']) ||
$isRecalculatePledgePayment) {
194 // if pledge is pending delete all payments and recreate.
195 if ($isRecalculatePledgePayment) {
196 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
199 // building payment params
200 $paymentParams['pledge_id'] = $pledge->id
;
201 $paymentKeys = array(
208 'frequency_interval',
210 'installment_amount',
213 foreach ($paymentKeys as $key) {
214 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
216 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
219 $transaction->commit();
221 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
222 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
225 $recentOther = array();
226 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
227 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
228 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
231 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
232 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
233 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
237 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
238 $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) . ')';
240 // add the recently created Pledge
241 CRM_Utils_Recent
::add($title,
254 * Is this a change to an existing pending pledge requiring payment schedule changes.
256 * If the pledge is pending the code (slightly lazily) deletes & recreates pledge payments.
258 * If the payment dates or amounts have been manually edited then this can cause data loss. We can mitigate this to
259 * some extent by making sure we have a change that could potentially affect the schedule (rather than just a
260 * custom data change or similar).
262 * This calculation needs to be performed before update takes place as previous & new pledges are compared.
264 * @param array $params
268 protected static function isPaymentsRequireRecalculation($params) {
269 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
272 $scheduleChangingParameters = array(
275 'frequency_interval',
280 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
281 $existingPledgeDAO->id
= $params['id'];
282 $existingPledgeDAO->find(TRUE);
283 foreach ($scheduleChangingParameters as $parameter) {
284 if ($parameter == 'start_date') {
285 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
289 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
303 public static function deletePledge($id) {
304 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
306 $transaction = new CRM_Core_Transaction();
308 // check for no Completed Payment records with the pledge
309 $payment = new CRM_Pledge_DAO_PledgePayment();
310 $payment->pledge_id
= $id;
313 while ($payment->fetch()) {
314 // also delete associated contribution.
315 if ($payment->contribution_id
) {
316 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
321 $dao = new CRM_Pledge_DAO_Pledge();
323 $results = $dao->delete();
325 $transaction->commit();
327 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
329 // delete the recently created Pledge
330 $pledgeRecent = array(
334 CRM_Utils_Recent
::del($pledgeRecent);
340 * Get the amount details date wise.
342 * @param string $status
343 * @param string $startDate
344 * @param string $endDate
348 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
350 $select = $from = $queryDate = NULL;
351 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
355 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
362 $where[] = 'status_id = ' . $statusId;
367 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
370 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
373 $whereCond = implode(' AND ', $where);
376 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
378 WHERE $whereCond AND is_test=0
381 $start = substr($startDate, 0, 8);
382 $end = substr($endDate, 0, 8);
385 $dao = CRM_Core_DAO
::executeQuery($query);
386 while ($dao->fetch()) {
387 $pCount +
= $dao->pledge_count
;
388 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
391 $pledge_amount = array(
392 'pledge_amount' => implode(', ', $pamount),
393 'pledge_count' => $pCount,
394 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
395 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
402 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
403 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
404 $queryDate = 'receive_date';
405 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
409 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
410 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
411 $queryDate = 'receive_date';
412 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
416 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
417 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
418 $queryDate = 'scheduled_date';
419 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
423 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
424 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
425 $queryDate = 'scheduled_date';
426 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
431 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
434 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
437 $whereCond = implode(' AND ', $where);
440 SELECT $select, cp.currency
446 $dao = CRM_Core_DAO
::executeQuery($query);
450 while ($dao->fetch()) {
451 $count +
= $dao->received_count
;
452 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
456 return array_merge($pledge_amount, array(
457 'received_amount' => implode(', ', $amount),
458 'received_count' => $count,
459 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
460 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
466 return $pledge_amount;
472 * Get list of pledges In Honor of contact Ids.
474 * @param int $honorId
475 * In Honor of Contact ID.
478 * return the list of pledge fields
480 public static function getHonorContacts($honorId) {
482 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
483 $honorDAO->contact_id
= $honorId;
487 while ($honorDAO->fetch()) {
488 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
489 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
490 if ($pledgePaymentDAO->find(TRUE)) {
491 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
492 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
493 if ($pledgeDAO->find(TRUE)) {
494 $params[$pledgeDAO->id
] = array(
495 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
496 'honorId' => $pledgeDAO->contact_id
,
497 'amount' => $pledgeDAO->amount
,
498 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
499 'create_date' => $pledgeDAO->create_date
,
500 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
501 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
502 $pledgeDAO->financial_type_id
, 'name'
504 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
505 $pledgeDAO->contact_id
, 'display_name'
516 * Send Acknowledgment and create activity.
518 * @param CRM_Core_Form $form
520 * @param array $params
521 * An assoc array of name/value pairs.
523 public static function sendAcknowledgment(&$form, $params) {
524 //handle Acknowledgment.
525 $allPayments = $payments = array();
527 // get All Payments status types.
528 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
529 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
530 // get all paymnets details.
531 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
533 if (!empty($allPayments)) {
534 foreach ($allPayments as $payID => $values) {
535 $contributionValue = $contributionStatus = array();
536 if (isset($values['contribution_id'])) {
537 $contributionParams = array('id' => $values['contribution_id']);
538 $returnProperties = array('contribution_status_id', 'receive_date');
539 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
540 $contributionParams, $contributionStatus, $returnProperties
542 $contributionValue = array(
543 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
544 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
547 $payments[$payID] = array_merge($contributionValue,
549 'amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
550 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
554 // get the first valid payment id.
555 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
556 $paymentStatusTypes[$values['status_id']] == 'Overdue'
559 $form->paymentId
= $values['id'];
564 // assign pledge fields value to template.
565 $pledgeFields = array(
567 'total_pledge_amount',
568 'frequency_interval',
575 foreach ($pledgeFields as $field) {
576 if (!empty($params[$field])) {
577 $form->assign($field, $params[$field]);
581 // assign all payments details.
583 $form->assign('payments', $payments);
586 // handle domain token values
587 $domain = CRM_Core_BAO_Domain
::getDomain();
589 'domain' => array('name', 'phone', 'address', 'email'),
590 'contact' => CRM_Core_SelectValues
::contactTokens(),
592 $domainValues = array();
593 foreach ($tokens['domain'] as $token) {
594 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
596 $form->assign('domain', $domainValues);
598 // handle contact token values.
599 $ids = array($params['contact_id']);
600 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
601 array('display_name', 'checksum', 'contact_id')
603 foreach ($fields as $key => $val) {
604 $returnProperties[$val] = TRUE;
606 $details = CRM_Utils_Token
::getTokenDetails($ids,
612 $form->assign('contact', $details[0][$params['contact_id']]);
614 // handle custom data.
615 if (!empty($params['hidden_custom'])) {
616 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
617 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
618 $customGroup = array();
619 // retrieve custom data
620 foreach ($groupTree as $groupID => $group) {
621 $customFields = $customValues = array();
622 if ($groupID == 'info') {
625 foreach ($group['fields'] as $k => $field) {
626 $field['title'] = $field['label'];
627 $customFields["custom_{$k}"] = $field;
630 // to build array of customgroup & customfields in it
631 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
632 $customGroup[$group['title']] = $customValues;
635 $form->assign('customGroup', $customGroup);
638 // handle acknowledgment email stuff.
639 list($pledgerDisplayName,
641 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
643 // check for online pledge.
644 if (!empty($params['receipt_from_email'])) {
645 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
646 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
648 elseif (!empty($params['from_email_id'])) {
649 $receiptFrom = $params['from_email_id'];
651 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
652 // check for logged in user.
653 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
656 // set the domain values.
657 $userName = CRM_Utils_Array
::value('name', $domainValues);
658 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
661 if (!isset($receiptFrom)) {
662 $receiptFrom = "$userName <$userEmail>";
665 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
667 'groupName' => 'msg_tpl_workflow_pledge',
668 'valueName' => 'pledge_acknowledge',
669 'contactId' => $params['contact_id'],
670 'from' => $receiptFrom,
671 'toName' => $pledgerDisplayName,
672 'toEmail' => $pledgerEmail,
676 // check if activity record exist for this pledge
677 // Acknowledgment, if exist do not add activity.
678 $activityType = 'Pledge Acknowledgment';
679 $activity = new CRM_Activity_DAO_Activity();
680 $activity->source_record_id
= $params['id'];
681 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
687 $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)';
689 if (!$activity->find()) {
690 $activityParams = array(
691 'subject' => $subject,
692 'source_contact_id' => $params['contact_id'],
693 'source_record_id' => $params['id'],
694 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
698 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
699 'is_test' => $params['is_test'],
701 'details' => $details,
702 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
705 // lets insert assignee record.
706 if (!empty($params['contact_id'])) {
707 $activityParams['assignee_contact_id'] = $params['contact_id'];
710 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
711 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
717 * Combine all the exportable fields from the lower levels object.
719 * @param bool $checkPermission
722 * array of exportable Fields
724 public static function exportableFields($checkPermission = TRUE) {
725 if (!self
::$_exportableFields) {
726 if (!self
::$_exportableFields) {
727 self
::$_exportableFields = array();
730 $fields = CRM_Pledge_DAO_Pledge
::export();
732 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
734 // set title to calculated fields
735 $calculatedFields = array(
736 'pledge_total_paid' => array('title' => ts('Total Paid')),
737 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
738 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
739 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
740 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
741 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
742 'pledge_payment_status' => array(
743 'title' => ts('Pledge Payment Status'),
744 'name' => 'pledge_payment_status',
745 'data_type' => CRM_Utils_Type
::T_STRING
,
749 $pledgeFields = array(
750 'pledge_status' => array(
751 'title' => 'Pledge Status',
752 'name' => 'pledge_status',
753 'data_type' => CRM_Utils_Type
::T_STRING
,
755 'pledge_frequency_unit' => array(
756 'title' => 'Pledge Frequency Unit',
757 'name' => 'pledge_frequency_unit',
758 'data_type' => CRM_Utils_Type
::T_ENUM
,
760 'pledge_frequency_interval' => array(
761 'title' => 'Pledge Frequency Interval',
762 'name' => 'pledge_frequency_interval',
763 'data_type' => CRM_Utils_Type
::T_INT
,
765 'pledge_contribution_page_id' => array(
766 'title' => 'Pledge Contribution Page Id',
767 'name' => 'pledge_contribution_page_id',
768 'data_type' => CRM_Utils_Type
::T_INT
,
772 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
775 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
776 self
::$_exportableFields = $fields;
779 return self
::$_exportableFields;
783 * Get pending or in progress pledges.
785 * @param int $contactID
789 * associated array of pledge id(s)
791 public static function getContactPledges($contactID) {
792 $pledgeDetails = array();
793 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
797 // get pending and in progress status
803 if ($statusId = array_search($name, $pledgeStatuses)) {
804 $status[] = $statusId;
807 if (empty($status)) {
808 return $pledgeDetails;
811 $statusClause = " IN (" . implode(',', $status) . ")";
814 SELECT civicrm_pledge.id id
816 WHERE civicrm_pledge.status_id {$statusClause}
817 AND civicrm_pledge.contact_id = %1
820 $params[1] = array($contactID, 'Integer');
821 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
823 while ($pledge->fetch()) {
824 $pledgeDetails[] = $pledge->id
;
827 return $pledgeDetails;
831 * Get pledge record count for a Contact.
833 * @param int $contactID
836 * count of pledge records
838 public static function getContactPledgeCount($contactID) {
839 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
840 return CRM_Core_DAO
::singleValueQuery($query);
844 * @param array $params
848 public static function updatePledgeStatus($params) {
850 $returnMessages = array();
852 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
854 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
856 // unset statues that we never use for pledges
862 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
863 unset($allStatus[$key]);
867 $statusIds = implode(',', array_keys($allStatus));
871 SELECT pledge.contact_id as contact_id,
872 pledge.id as pledge_id,
873 pledge.amount as amount,
874 payment.scheduled_date as scheduled_date,
875 pledge.create_date as create_date,
876 payment.id as payment_id,
877 pledge.currency as currency,
878 pledge.contribution_page_id as contribution_page_id,
879 payment.reminder_count as reminder_count,
880 pledge.max_reminders as max_reminders,
881 payment.reminder_date as reminder_date,
882 pledge.initial_reminder_day as initial_reminder_day,
883 pledge.additional_reminder_day as additional_reminder_day,
884 pledge.status_id as pledge_status,
885 payment.status_id as payment_status,
886 pledge.is_test as is_test,
887 pledge.campaign_id as campaign_id,
888 SUM(payment.scheduled_amount) as amount_due,
889 ( SELECT sum(civicrm_pledge_payment.actual_amount)
890 FROM civicrm_pledge_payment
891 WHERE civicrm_pledge_payment.status_id = 1
892 AND civicrm_pledge_payment.pledge_id = pledge.id
894 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
895 WHERE pledge.id = payment.pledge_id
896 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
900 $dao = CRM_Core_DAO
::executeQuery($query);
903 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
904 while ($dao->fetch()) {
905 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
907 $pledgeDetails[$dao->payment_id
] = array(
908 'scheduled_date' => $dao->scheduled_date
,
909 'amount_due' => $dao->amount_due
,
910 'amount' => $dao->amount
,
911 'amount_paid' => $dao->amount_paid
,
912 'create_date' => $dao->create_date
,
913 'contact_id' => $dao->contact_id
,
914 'pledge_id' => $dao->pledge_id
,
915 'checksumValue' => $checksumValue,
916 'contribution_page_id' => $dao->contribution_page_id
,
917 'reminder_count' => $dao->reminder_count
,
918 'max_reminders' => $dao->max_reminders
,
919 'reminder_date' => $dao->reminder_date
,
920 'initial_reminder_day' => $dao->initial_reminder_day
,
921 'additional_reminder_day' => $dao->additional_reminder_day
,
922 'pledge_status' => $dao->pledge_status
,
923 'payment_status' => $dao->payment_status
,
924 'is_test' => $dao->is_test
,
925 'currency' => $dao->currency
,
926 'campaign_id' => $dao->campaign_id
,
929 $contactIds[$dao->contact_id
] = $dao->contact_id
;
930 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
932 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
934 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)
936 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
940 // process the updating script...
942 foreach ($pledgePayments as $pledgeId => $paymentIds) {
943 // 1. update the pledge /pledge payment status. returns new status when an update happens
944 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
946 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
947 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
949 if ($newStatus != $pledgeStatus[$pledgeId]) {
950 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
955 if ($sendReminders) {
956 // retrieve domain tokens
957 $domain = CRM_Core_BAO_Domain
::getDomain();
959 'domain' => array('name', 'phone', 'address', 'email'),
960 'contact' => CRM_Core_SelectValues
::contactTokens(),
963 $domainValues = array();
964 foreach ($tokens['domain'] as $token) {
965 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
968 // get the domain email address, since we don't carry w/ object.
969 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
970 $domainValues['email'] = $domainValue[1];
972 // retrieve contact tokens
974 // this function does NOT return Deceased contacts since we don't want to send them email
975 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
978 $tokens, 'CRM_UpdatePledgeRecord'
981 // assign domain values to template
982 $template = CRM_Core_Smarty
::singleton();
983 $template->assign('domain', $domainValues);
986 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
988 foreach ($pledgeDetails as $paymentId => $details) {
989 if (array_key_exists($details['contact_id'], $contactDetails)) {
990 $contactId = $details['contact_id'];
991 $pledgerName = $contactDetails[$contactId]['display_name'];
997 if (empty($details['reminder_date'])) {
998 $nextReminderDate = new DateTime($details['scheduled_date']);
999 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
1000 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
1001 $nextReminderDate = $nextReminderDate->format("Ymd");
1004 $nextReminderDate = new DateTime($details['reminder_date']);
1005 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
1006 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
1007 $nextReminderDate = $nextReminderDate->format("Ymd");
1009 if (($details['reminder_count'] < $details['max_reminders'])
1010 && ($nextReminderDate <= $now)
1013 $toEmail = $doNotEmail = $onHold = NULL;
1015 if (!empty($contactDetails[$contactId]['email'])) {
1016 $toEmail = $contactDetails[$contactId]['email'];
1019 if (!empty($contactDetails[$contactId]['do_not_email'])) {
1020 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
1023 if (!empty($contactDetails[$contactId]['on_hold'])) {
1024 $onHold = $contactDetails[$contactId]['on_hold'];
1027 // 2. send acknowledgement mail
1028 if ($toEmail && !($doNotEmail ||
$onHold)) {
1029 // assign value to template
1030 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1031 $template->assign('contact', $contactDetails[$contactId]);
1032 $template->assign('next_payment', $details['scheduled_date']);
1033 $template->assign('amount_due', $details['amount_due']);
1034 $template->assign('checksumValue', $details['checksumValue']);
1035 $template->assign('contribution_page_id', $details['contribution_page_id']);
1036 $template->assign('pledge_id', $details['pledge_id']);
1037 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1038 $template->assign('amount', $details['amount']);
1039 $template->assign('create_date', $details['create_date']);
1040 $template->assign('currency', $details['currency']);
1041 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1043 'groupName' => 'msg_tpl_workflow_pledge',
1044 'valueName' => 'pledge_reminder',
1045 'contactId' => $contactId,
1046 'from' => $receiptFrom,
1047 'toName' => $pledgerName,
1048 'toEmail' => $toEmail,
1052 // 3. update pledge payment details
1054 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1055 $activityType = 'Pledge Reminder';
1056 $activityParams = array(
1057 'subject' => $subject,
1058 'source_contact_id' => $contactId,
1059 'source_record_id' => $paymentId,
1060 'assignee_contact_id' => $contactId,
1061 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1065 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1066 'is_test' => $details['is_test'],
1068 'campaign_id' => $details['campaign_id'],
1071 civicrm_api3('activity', 'create', $activityParams);
1073 catch (CiviCRM_API3_Exception
$e) {
1074 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1075 return array('is_error' => 1, 'message' => $returnMessages);
1077 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1082 // end foreach on $pledgeDetails
1084 // end if ( $sendReminders )
1085 $returnMessages[] = "{$updateCnt} records updated.";
1087 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1091 * Mark a pledge (and any outstanding payments) as cancelled.
1093 * @param int $pledgeID
1095 public static function cancel($pledgeID) {
1096 $paymentIDs = self
::findCancelablePayments($pledgeID);
1097 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1098 $cancelled = array_search('Cancelled', $status);
1099 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1100 $cancelled, 0, FALSE, TRUE
1105 * Find payments which can be safely canceled.
1107 * @param int $pledgeID
1109 * Array of int (civicrm_pledge_payment.id)
1111 public static function findCancelablePayments($pledgeID) {
1112 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1114 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1115 $paymentDAO->pledge_id
= $pledgeID;
1116 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1117 $statuses['Overdue'],
1118 $statuses['Pending']
1120 $paymentDAO->find();
1122 $paymentIDs = array();
1123 while ($paymentDAO->fetch()) {
1124 $paymentIDs[] = $paymentDAO->id
;
1130 * Is this pledge free from financial transactions (this is important to know as we allow editing
1131 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1132 * & recreating so we want to block that if appropriate).
1134 * @param int $pledgeID
1135 * @param int $pledgeStatusID
1137 * do financial transactions exist for this pledge?
1139 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1140 if (empty($pledgeStatusID)) {
1141 // why would this happen? If we can see where it does then we can see if we should look it up.
1142 // but assuming from form code it CAN be empty.
1145 if (self
::isTransactedStatus($pledgeStatusID)) {
1149 return civicrm_api3('pledge_payment', 'getcount', array(
1150 'pledge_id' => $pledgeID,
1151 'contribution_id' => array('NOT NULL' => TRUE),
1156 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1157 * @param int $statusID
1161 * is it a transactional status?
1163 protected static function isTransactedStatus($statusID) {
1164 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1171 * Get array of non transactional statuses.
1173 * non transactional status ids
1175 protected static function getNonTransactionalStatus() {
1176 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1177 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1182 * Create array for recur record for pledge.
1184 * params for recur record
1186 public static function buildRecurParams($params) {
1187 $recurParams = array(
1189 'auto_renew' => TRUE,
1190 'frequency_unit' => $params['pledge_frequency_unit'],
1191 'frequency_interval' => $params['pledge_frequency_interval'],
1192 'installments' => $params['pledge_installments'],
1193 'start_date' => $params['receive_date'],
1195 return $recurParams;
1199 * Get pledge start date.
1204 public static function getPledgeStartDate($date, $pledgeBlock) {
1205 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1206 list($field, $value) = each($startDate);
1207 if (!empty($date) && !CRM_Utils_Array
::value('is_pledge_start_date_editable', $pledgeBlock)) {
1214 case 'contribution_date':
1216 $date = date('Ymd');
1220 case 'calendar_date':
1221 $date = date('Ymd', strtotime($date));
1224 case 'calendar_month':
1225 $date = self
::getPaymentDate($date);
1226 $date = date('Ymd', strtotime($date));
1237 * Get first payment date for pledge.
1240 public static function getPaymentDate($day) {
1242 // Find out if current month has 31 days, if not, set it to 30 (last day).
1248 $current = date('d');
1250 case ($day == $current):
1251 $date = date('m/d/Y');
1254 case ($day > $current):
1255 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1258 case ($day < $current):
1259 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1270 * Override buildOptions to hack out some statuses.
1272 * @todo instead of using & hacking the shared optionGroup contribution_status use a separate one.
1274 * @param string $fieldName
1275 * @param string $context
1276 * @param array $props
1278 * @return array|bool
1280 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1281 $result = parent
::buildOptions($fieldName, $context, $props);
1282 if ($fieldName == 'status_id') {
1283 $result = array_diff($result, array('Failed'));