3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 $transaction = new CRM_Core_Transaction();
155 $paymentParams = array();
156 $paymentParams['status_id'] = CRM_Utils_Array
::value('status_id', $params);
157 if (!empty($params['installment_amount'])) {
158 $params['amount'] = $params['installment_amount'] * $params['installments'];
161 // get All Payments status types.
162 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
164 // update the pledge status only if it does NOT come from form
165 if (!isset($params['pledge_status_id'])) {
166 if (isset($params['contribution_id'])) {
167 if ($params['installments'] > 1) {
168 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
172 if (!empty($params['id'])) {
173 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
176 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
181 $pledge = self
::add($params);
182 if (is_a($pledge, 'CRM_Core_Error')) {
187 // handle custom data.
188 if (!empty($params['custom']) &&
189 is_array($params['custom'])
191 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
194 // skip payment stuff inedit mode
195 if (!isset($params['id']) ||
!empty($params['is_pledge_pending'])) {
197 // if pledge is pending delete all payments and recreate.
198 if (!empty($params['is_pledge_pending'])) {
199 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
202 // building payment params
203 $paymentParams['pledge_id'] = $pledge->id
;
204 $paymentKeys = array(
211 'frequency_interval',
213 'installment_amount',
216 foreach ($paymentKeys as $key) {
217 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
219 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
222 $transaction->commit();
224 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
225 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
228 $recentOther = array();
229 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
230 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
231 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
234 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
235 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
236 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
240 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
241 $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) . ')';
243 // add the recently created Pledge
244 CRM_Utils_Recent
::add($title,
264 public static function deletePledge($id) {
265 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
267 $transaction = new CRM_Core_Transaction();
269 // check for no Completed Payment records with the pledge
270 $payment = new CRM_Pledge_DAO_PledgePayment();
271 $payment->pledge_id
= $id;
274 while ($payment->fetch()) {
275 // also delete associated contribution.
276 if ($payment->contribution_id
) {
277 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
282 $dao = new CRM_Pledge_DAO_Pledge();
284 $results = $dao->delete();
286 $transaction->commit();
288 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
290 // delete the recently created Pledge
291 $pledgeRecent = array(
295 CRM_Utils_Recent
::del($pledgeRecent);
301 * Get the amount details date wise.
303 * @param string $status
304 * @param string $startDate
305 * @param string $endDate
309 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
311 $select = $from = $queryDate = NULL;
313 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
314 $statusId = array_search($status, $allStatus);
318 $statusId = array_search('Cancelled', $allStatus);
319 $where[] = 'status_id != ' . $statusId;
323 $where[] = 'status_id = ' . $statusId;
327 $where[] = 'status_id = ' . $statusId;
331 $where[] = 'status_id = ' . $statusId;
335 $where[] = 'status_id = ' . $statusId;
340 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
343 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
346 $whereCond = implode(' AND ', $where);
349 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
351 WHERE $whereCond AND is_test=0
354 $start = substr($startDate, 0, 8);
355 $end = substr($endDate, 0, 8);
358 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
359 while ($dao->fetch()) {
360 $pCount +
= $dao->pledge_count
;
361 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
364 $pledge_amount = array(
365 'pledge_amount' => implode(', ', $pamount),
366 'pledge_count' => $pCount,
367 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
368 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
373 $statusId = array_search($status, $allStatus);
376 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
377 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
378 $queryDate = 'receive_date';
379 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
383 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
384 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
385 $queryDate = 'receive_date';
386 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
390 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
391 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
392 $queryDate = 'scheduled_date';
393 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
397 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
398 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
399 $queryDate = 'scheduled_date';
400 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
405 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
408 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
411 $whereCond = implode(' AND ', $where);
414 SELECT $select, cp.currency
420 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
424 while ($dao->fetch()) {
425 $count +
= $dao->received_count
;
426 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
430 return array_merge($pledge_amount, array(
431 'received_amount' => implode(', ', $amount),
432 'received_count' => $count,
433 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
434 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
440 return $pledge_amount;
446 * Get list of pledges In Honor of contact Ids.
448 * @param int $honorId
449 * In Honor of Contact ID.
452 * return the list of pledge fields
454 public static function getHonorContacts($honorId) {
456 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
457 $honorDAO->contact_id
= $honorId;
461 while ($honorDAO->fetch()) {
462 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
463 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
464 if ($pledgePaymentDAO->find(TRUE)) {
465 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
466 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
467 if ($pledgeDAO->find(TRUE)) {
468 $params[$pledgeDAO->id
] = array(
469 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
470 'honorId' => $pledgeDAO->contact_id
,
471 'amount' => $pledgeDAO->amount
,
472 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
473 'create_date' => $pledgeDAO->create_date
,
474 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
475 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
476 $pledgeDAO->financial_type_id
, 'name'
478 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
479 $pledgeDAO->contact_id
, 'display_name'
490 * Send Acknowledgment and create activity.
492 * @param CRM_Core_Form $form
494 * @param array $params
495 * An assoc array of name/value pairs.
497 public static function sendAcknowledgment(&$form, $params) {
498 //handle Acknowledgment.
499 $allPayments = $payments = array();
501 // get All Payments status types.
502 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
503 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
504 // get all paymnets details.
505 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
507 if (!empty($allPayments)) {
508 foreach ($allPayments as $payID => $values) {
509 $contributionValue = $contributionStatus = array();
510 if (isset($values['contribution_id'])) {
511 $contributionParams = array('id' => $values['contribution_id']);
512 $returnProperties = array('contribution_status_id', 'receive_date');
513 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
514 $contributionParams, $contributionStatus, $returnProperties
516 $contributionValue = array(
517 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
518 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
521 $payments[$payID] = array_merge($contributionValue,
523 'amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
524 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
528 // get the first valid payment id.
529 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
530 $paymentStatusTypes[$values['status_id']] == 'Overdue'
533 $form->paymentId
= $values['id'];
538 // assign pledge fields value to template.
539 $pledgeFields = array(
541 'total_pledge_amount',
542 'frequency_interval',
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 if (!empty($params['receipt_from_email'])) {
619 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
620 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
622 elseif (!empty($params['from_email_id'])) {
623 $receiptFrom = $params['from_email_id'];
625 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
626 // check for logged in user.
627 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
630 // set the domain values.
631 $userName = CRM_Utils_Array
::value('name', $domainValues);
632 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
635 if (!isset($receiptFrom)) {
636 $receiptFrom = "$userName <$userEmail>";
639 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
641 'groupName' => 'msg_tpl_workflow_pledge',
642 'valueName' => 'pledge_acknowledge',
643 'contactId' => $params['contact_id'],
644 'from' => $receiptFrom,
645 'toName' => $pledgerDisplayName,
646 'toEmail' => $pledgerEmail,
650 // check if activity record exist for this pledge
651 // Acknowledgment, if exist do not add activity.
652 $activityType = 'Pledge Acknowledgment';
653 $activity = new CRM_Activity_DAO_Activity();
654 $activity->source_record_id
= $params['id'];
655 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
661 $details = 'Total Amount ' . CRM_Utils_Money
::format($params['total_pledge_amount'], CRM_Utils_Array
::value('currency', $params)) . ' To be paid in ' . $params['installments'] . ' installments of ' . CRM_Utils_Money
::format($params['scheduled_amount'], CRM_Utils_Array
::value('currency', $params)) . ' every ' . $params['frequency_interval'] . ' ' . $params['frequency_unit'] . '(s)';
663 if (!$activity->find()) {
664 $activityParams = array(
665 'subject' => $subject,
666 'source_contact_id' => $params['contact_id'],
667 'source_record_id' => $params['id'],
668 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
672 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
673 'is_test' => $params['is_test'],
675 'details' => $details,
676 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
679 // lets insert assignee record.
680 if (!empty($params['contact_id'])) {
681 $activityParams['assignee_contact_id'] = $params['contact_id'];
684 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
685 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
691 * Combine all the exportable fields from the lower levels object.
694 * array of exportable Fields
696 public static function &exportableFields() {
697 if (!self
::$_exportableFields) {
698 if (!self
::$_exportableFields) {
699 self
::$_exportableFields = array();
702 $fields = CRM_Pledge_DAO_Pledge
::export();
704 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
706 // set title to calculated fields
707 $calculatedFields = array(
708 'pledge_total_paid' => array('title' => ts('Total Paid')),
709 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
710 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
711 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
712 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
713 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
714 'pledge_payment_status' => array(
715 'title' => ts('Pledge Payment Status'),
716 'name' => 'pledge_payment_status',
717 'data_type' => CRM_Utils_Type
::T_STRING
,
721 $pledgeFields = array(
722 'pledge_status' => array(
723 'title' => 'Pledge Status',
724 'name' => 'pledge_status',
725 'data_type' => CRM_Utils_Type
::T_STRING
,
727 'pledge_frequency_unit' => array(
728 'title' => 'Pledge Frequency Unit',
729 'name' => 'pledge_frequency_unit',
730 'data_type' => CRM_Utils_Type
::T_ENUM
,
732 'pledge_frequency_interval' => array(
733 'title' => 'Pledge Frequency Interval',
734 'name' => 'pledge_frequency_interval',
735 'data_type' => CRM_Utils_Type
::T_INT
,
737 'pledge_contribution_page_id' => array(
738 'title' => 'Pledge Contribution Page Id',
739 'name' => 'pledge_contribution_page_id',
740 'data_type' => CRM_Utils_Type
::T_INT
,
744 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
747 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
748 self
::$_exportableFields = $fields;
751 return self
::$_exportableFields;
755 * Get pending or in progress pledges.
757 * @param int $contactID
761 * associated array of pledge id(s)
763 public static function getContactPledges($contactID) {
764 $pledgeDetails = array();
765 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
769 // get pending and in progress status
775 if ($statusId = array_search($name, $pledgeStatuses)) {
776 $status[] = $statusId;
779 if (empty($status)) {
780 return $pledgeDetails;
783 $statusClause = " IN (" . implode(',', $status) . ")";
786 SELECT civicrm_pledge.id id
788 WHERE civicrm_pledge.status_id {$statusClause}
789 AND civicrm_pledge.contact_id = %1
792 $params[1] = array($contactID, 'Integer');
793 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
795 while ($pledge->fetch()) {
796 $pledgeDetails[] = $pledge->id
;
799 return $pledgeDetails;
803 * Get pledge record count for a Contact.
805 * @param int $contactID
808 * count of pledge records
810 public static function getContactPledgeCount($contactID) {
811 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
812 return CRM_Core_DAO
::singleValueQuery($query);
816 * @param array $params
820 public static function updatePledgeStatus($params) {
822 $returnMessages = array();
824 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
826 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
828 // unset statues that we never use for pledges
834 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
835 unset($allStatus[$key]);
839 $statusIds = implode(',', array_keys($allStatus));
843 SELECT pledge.contact_id as contact_id,
844 pledge.id as pledge_id,
845 pledge.amount as amount,
846 payment.scheduled_date as scheduled_date,
847 pledge.create_date as create_date,
848 payment.id as payment_id,
849 pledge.currency as currency,
850 pledge.contribution_page_id as contribution_page_id,
851 payment.reminder_count as reminder_count,
852 pledge.max_reminders as max_reminders,
853 payment.reminder_date as reminder_date,
854 pledge.initial_reminder_day as initial_reminder_day,
855 pledge.additional_reminder_day as additional_reminder_day,
856 pledge.status_id as pledge_status,
857 payment.status_id as payment_status,
858 pledge.is_test as is_test,
859 pledge.campaign_id as campaign_id,
860 SUM(payment.scheduled_amount) as amount_due,
861 ( SELECT sum(civicrm_pledge_payment.actual_amount)
862 FROM civicrm_pledge_payment
863 WHERE civicrm_pledge_payment.status_id = 1
864 AND civicrm_pledge_payment.pledge_id = pledge.id
866 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
867 WHERE pledge.id = payment.pledge_id
868 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
872 $dao = CRM_Core_DAO
::executeQuery($query);
875 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
876 while ($dao->fetch()) {
877 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
879 $pledgeDetails[$dao->payment_id
] = array(
880 'scheduled_date' => $dao->scheduled_date
,
881 'amount_due' => $dao->amount_due
,
882 'amount' => $dao->amount
,
883 'amount_paid' => $dao->amount_paid
,
884 'create_date' => $dao->create_date
,
885 'contact_id' => $dao->contact_id
,
886 'pledge_id' => $dao->pledge_id
,
887 'checksumValue' => $checksumValue,
888 'contribution_page_id' => $dao->contribution_page_id
,
889 'reminder_count' => $dao->reminder_count
,
890 'max_reminders' => $dao->max_reminders
,
891 'reminder_date' => $dao->reminder_date
,
892 'initial_reminder_day' => $dao->initial_reminder_day
,
893 'additional_reminder_day' => $dao->additional_reminder_day
,
894 'pledge_status' => $dao->pledge_status
,
895 'payment_status' => $dao->payment_status
,
896 'is_test' => $dao->is_test
,
897 'currency' => $dao->currency
,
898 'campaign_id' => $dao->campaign_id
,
901 $contactIds[$dao->contact_id
] = $dao->contact_id
;
902 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
904 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
906 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)
908 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
912 // process the updating script...
914 foreach ($pledgePayments as $pledgeId => $paymentIds) {
915 // 1. update the pledge /pledge payment status. returns new status when an update happens
916 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
918 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
919 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
921 if ($newStatus != $pledgeStatus[$pledgeId]) {
922 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
927 if ($sendReminders) {
928 // retrieve domain tokens
929 $domain = CRM_Core_BAO_Domain
::getDomain();
931 'domain' => array('name', 'phone', 'address', 'email'),
932 'contact' => CRM_Core_SelectValues
::contactTokens(),
935 $domainValues = array();
936 foreach ($tokens['domain'] as $token) {
937 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
940 // get the domain email address, since we don't carry w/ object.
941 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
942 $domainValues['email'] = $domainValue[1];
944 // retrieve contact tokens
946 // this function does NOT return Deceased contacts since we don't want to send them email
947 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
950 $tokens, 'CRM_UpdatePledgeRecord'
953 // assign domain values to template
954 $template = CRM_Core_Smarty
::singleton();
955 $template->assign('domain', $domainValues);
958 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
960 foreach ($pledgeDetails as $paymentId => $details) {
961 if (array_key_exists($details['contact_id'], $contactDetails)) {
962 $contactId = $details['contact_id'];
963 $pledgerName = $contactDetails[$contactId]['display_name'];
969 if (empty($details['reminder_date'])) {
970 $nextReminderDate = new DateTime($details['scheduled_date']);
971 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
972 $nextReminderDate = $nextReminderDate->format("Ymd");
975 $nextReminderDate = new DateTime($details['reminder_date']);
976 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
977 $nextReminderDate = $nextReminderDate->format("Ymd");
979 if (($details['reminder_count'] < $details['max_reminders'])
980 && ($nextReminderDate <= $now)
983 $toEmail = $doNotEmail = $onHold = NULL;
985 if (!empty($contactDetails[$contactId]['email'])) {
986 $toEmail = $contactDetails[$contactId]['email'];
989 if (!empty($contactDetails[$contactId]['do_not_email'])) {
990 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
993 if (!empty($contactDetails[$contactId]['on_hold'])) {
994 $onHold = $contactDetails[$contactId]['on_hold'];
997 // 2. send acknowledgement mail
998 if ($toEmail && !($doNotEmail ||
$onHold)) {
999 // assign value to template
1000 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1001 $template->assign('contact', $contactDetails[$contactId]);
1002 $template->assign('next_payment', $details['scheduled_date']);
1003 $template->assign('amount_due', $details['amount_due']);
1004 $template->assign('checksumValue', $details['checksumValue']);
1005 $template->assign('contribution_page_id', $details['contribution_page_id']);
1006 $template->assign('pledge_id', $details['pledge_id']);
1007 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1008 $template->assign('amount', $details['amount']);
1009 $template->assign('create_date', $details['create_date']);
1010 $template->assign('currency', $details['currency']);
1011 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1013 'groupName' => 'msg_tpl_workflow_pledge',
1014 'valueName' => 'pledge_reminder',
1015 'contactId' => $contactId,
1016 'from' => $receiptFrom,
1017 'toName' => $pledgerName,
1018 'toEmail' => $toEmail,
1022 // 3. update pledge payment details
1024 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1025 $activityType = 'Pledge Reminder';
1026 $activityParams = array(
1027 'subject' => $subject,
1028 'source_contact_id' => $contactId,
1029 'source_record_id' => $paymentId,
1030 'assignee_contact_id' => $contactId,
1031 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1035 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1036 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1037 'is_test' => $details['is_test'],
1039 'campaign_id' => $details['campaign_id'],
1041 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1042 $returnMessages[] = "Failed creating Activity for acknowledgment";
1043 return array('is_error' => 1, 'message' => $returnMessages);
1045 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1050 // end foreach on $pledgeDetails
1052 // end if ( $sendReminders )
1053 $returnMessages[] = "{$updateCnt} records updated.";
1055 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1059 * Mark a pledge (and any outstanding payments) as cancelled.
1061 * @param int $pledgeID
1063 public static function cancel($pledgeID) {
1064 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1065 $paymentIDs = self
::findCancelablePayments($pledgeID);
1066 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1067 $statuses['Cancelled'], 0, FALSE, TRUE
1072 * Find payments which can be safely canceled.
1074 * @param int $pledgeID
1076 * Array of int (civicrm_pledge_payment.id)
1078 public static function findCancelablePayments($pledgeID) {
1079 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1081 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1082 $paymentDAO->pledge_id
= $pledgeID;
1083 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1084 $statuses['Overdue'],
1085 $statuses['Pending']
1087 $paymentDAO->find();
1089 $paymentIDs = array();
1090 while ($paymentDAO->fetch()) {
1091 $paymentIDs[] = $paymentDAO->id
;
1097 * Is this pledge free from financial transactions (this is important to know as we allow editing
1098 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1099 * & recreating so we want to block that if appropriate).
1101 * @param int $pledgeID
1102 * @param int $pledgeStatusID
1104 * do financial transactions exist for this pledge?
1106 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1107 if (empty($pledgeStatusID)) {
1108 // why would this happen? If we can see where it does then we can see if we should look it up.
1109 // but assuming from form code it CAN be empty.
1112 if (self
::isTransactedStatus($pledgeStatusID)) {
1116 return civicrm_api3('pledge_payment', 'getcount', array(
1117 'pledge_id' => $pledgeID,
1118 'status_id' => array('IN' => self
::getTransactionalStatus()),
1123 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1124 * @param int $statusID
1128 * is it a transactional status?
1130 protected static function isTransactedStatus($statusID) {
1131 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1138 * Get array of non transactional statuses.
1140 * non transactional status ids
1142 protected static function getNonTransactionalStatus() {
1143 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1144 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1148 * Get array of non transactional statuses.
1150 * non transactional status ids
1152 protected static function getTransactionalStatus() {
1153 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1154 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());