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
35 class CRM_Pledge_BAO_Pledge
extends CRM_Pledge_DAO_Pledge
{
38 * Static field for all the pledge information that we can potentially export.
42 static $_exportableFields = NULL;
47 public function __construct() {
48 parent
::__construct();
52 * Retrieve DB object based on input parameters.
54 * It also stores all the retrieved values in the default array.
56 * @param array $params
57 * (reference ) an assoc array of name/value pairs.
58 * @param array $defaults
59 * (reference ) an assoc array to hold the flattened values.
61 * @return CRM_Pledge_BAO_Pledge
63 public static function retrieve(&$params, &$defaults) {
64 $pledge = new CRM_Pledge_DAO_Pledge();
65 $pledge->copyValues($params);
66 if ($pledge->find(TRUE)) {
67 CRM_Core_DAO
::storeValues($pledge, $defaults);
76 * @param array $params
77 * Reference array contains the values submitted by the form.
82 public static function add(&$params) {
83 if (!empty($params['id'])) {
84 CRM_Utils_Hook
::pre('edit', 'Pledge', $params['id'], $params);
87 CRM_Utils_Hook
::pre('create', 'Pledge', NULL, $params);
90 $pledge = new CRM_Pledge_DAO_Pledge();
92 // if pledge is complete update end date as current date
93 if ($pledge->status_id
== 1) {
94 $pledge->end_date
= date('Ymd');
97 $pledge->copyValues($params);
99 // set currency for CRM-1496
100 if (!isset($pledge->currency
)) {
101 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
104 $result = $pledge->save();
106 if (!empty($params['id'])) {
107 CRM_Utils_Hook
::post('edit', 'Pledge', $pledge->id
, $pledge);
110 CRM_Utils_Hook
::post('create', 'Pledge', $pledge->id
, $pledge);
117 * Given the list of params in the params array, fetch the object
118 * and store the values in the values array
120 * @param array $params
121 * Input parameters to find object.
122 * @param array $values
123 * Output values of the object.
124 * @param array $returnProperties
125 * If you want to return specific fields.
128 * associated array of field values
130 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
131 if (empty($params)) {
134 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
139 * Takes an associative array and creates a pledge object.
141 * @param array $params
142 * (reference ) an assoc array of name/value pairs.
144 * @return CRM_Pledge_BAO_Pledge
146 public static function &create(&$params) {
147 //FIXME: a cludgy hack to fix the dates to MySQL format
148 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
149 foreach ($dateFields as $df) {
150 if (isset($params[$df])) {
151 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
155 $transaction = new CRM_Core_Transaction();
157 $paymentParams = array();
158 $paymentParams['status_id'] = CRM_Utils_Array
::value('status_id', $params);
159 if (!empty($params['installment_amount'])) {
160 $params['amount'] = $params['installment_amount'] * $params['installments'];
163 //get All Payments status types.
164 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
166 //update the pledge status only if it does NOT come from form
167 if (!isset($params['pledge_status_id'])) {
168 if (isset($params['contribution_id'])) {
169 if ($params['installments'] > 1) {
170 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
174 if (!empty($params['id'])) {
175 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
178 $params['status_id'] = array_search('Pending', $paymentStatusTypes);
183 $pledge = self
::add($params);
184 if (is_a($pledge, 'CRM_Core_Error')) {
189 //handle custom data.
190 if (!empty($params['custom']) &&
191 is_array($params['custom'])
193 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
196 // skip payment stuff inedit mode
197 if (!isset($params['id']) ||
!empty($params['is_pledge_pending'])) {
199 //if pledge is pending delete all payments and recreate.
200 if (!empty($params['is_pledge_pending'])) {
201 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
204 //building payment params
205 $paymentParams['pledge_id'] = $pledge->id
;
206 $paymentKeys = array(
213 'frequency_interval',
215 'installment_amount',
218 foreach ($paymentKeys as $key) {
219 $paymentParams[$key] = CRM_Utils_Array
::value($key, $params, NULL);
221 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
224 $transaction->commit();
226 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
227 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
230 $recentOther = array();
231 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
232 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
233 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
236 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
237 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
238 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
242 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
243 $title = CRM_Contact_BAO_Contact
::displayName($pledge->contact_id
) . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money
::format($pledge->amount
, $pledge->currency
) . ' - ' . CRM_Utils_Array
::value($pledge->financial_type_id
, $contributionTypes) . ')';
245 // add the recently created Pledge
246 CRM_Utils_Recent
::add($title,
266 public static function deletePledge($id) {
267 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
269 $transaction = new CRM_Core_Transaction();
271 //check for no Completed Payment records with the pledge
272 $payment = new CRM_Pledge_DAO_PledgePayment();
273 $payment->pledge_id
= $id;
276 while ($payment->fetch()) {
277 //also delete associated contribution.
278 if ($payment->contribution_id
) {
279 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
284 $dao = new CRM_Pledge_DAO_Pledge();
286 $results = $dao->delete();
288 $transaction->commit();
290 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
292 // delete the recently created Pledge
293 $pledgeRecent = array(
297 CRM_Utils_Recent
::del($pledgeRecent);
303 * Get the amount details date wise.
305 * @param string $status
306 * @param string $startDate
307 * @param string $endDate
311 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
313 $select = $from = $queryDate = NULL;
315 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
316 $statusId = array_search($status, $allStatus);
320 $statusId = array_search('Cancelled', $allStatus);
321 $where[] = 'status_id != ' . $statusId;
325 $where[] = 'status_id = ' . $statusId;
329 $where[] = 'status_id = ' . $statusId;
333 $where[] = 'status_id = ' . $statusId;
337 $where[] = 'status_id = ' . $statusId;
342 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
345 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
348 $whereCond = implode(' AND ', $where);
351 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
353 WHERE $whereCond AND is_test=0
356 $start = substr($startDate, 0, 8);
357 $end = substr($endDate, 0, 8);
360 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
361 while ($dao->fetch()) {
362 $pCount +
= $dao->pledge_count
;
363 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
366 $pledge_amount = array(
367 'pledge_amount' => implode(', ', $pamount),
368 'pledge_count' => $pCount,
369 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
370 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
375 $statusId = array_search($status, $allStatus);
378 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
379 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
380 $queryDate = 'receive_date';
381 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
385 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
386 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
387 $queryDate = 'receive_date';
388 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
392 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
393 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
394 $queryDate = 'scheduled_date';
395 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
399 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
400 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
401 $queryDate = 'scheduled_date';
402 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
407 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
410 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
413 $whereCond = implode(' AND ', $where);
416 SELECT $select, cp.currency
422 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
426 while ($dao->fetch()) {
427 $count +
= $dao->received_count
;
428 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
432 return array_merge($pledge_amount, array(
433 'received_amount' => implode(', ', $amount),
434 'received_count' => $count,
435 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
436 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
442 return $pledge_amount;
448 * Get list of pledges In Honor of contact Ids.
450 * @param int $honorId
451 * In Honor of Contact ID.
454 * return the list of pledge fields
457 public static function getHonorContacts($honorId) {
459 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
460 $honorDAO->contact_id
= $honorId;
464 while ($honorDAO->fetch()) {
465 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
466 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
467 if ($pledgePaymentDAO->find(TRUE)) {
468 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
469 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
470 if ($pledgeDAO->find(TRUE)) {
471 $params[$pledgeDAO->id
] = array(
472 'honor_type' => CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value'),
473 'honorId' => $pledgeDAO->contact_id
,
474 'amount' => $pledgeDAO->amount
,
475 'status' => CRM_Contribute_PseudoConstant
::contributionStatus($pledgeDAO->status_id
),
476 'create_date' => $pledgeDAO->create_date
,
477 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
478 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
479 $pledgeDAO->financial_type_id
, 'name'
481 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
482 $pledgeDAO->contact_id
, 'display_name'
493 * Send Acknowledgment and create activity.
495 * @param CRM_Core_Form $form
497 * @param array $params
498 * An assoc array of name/value pairs.
502 public static function sendAcknowledgment(&$form, $params) {
503 //handle Acknowledgment.
504 $allPayments = $payments = array();
506 //get All Payments status types.
507 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
508 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
509 //get all paymnets details.
510 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
512 if (!empty($allPayments)) {
513 foreach ($allPayments as $payID => $values) {
514 $contributionValue = $contributionStatus = array();
515 if (isset($values['contribution_id'])) {
516 $contributionParams = array('id' => $values['contribution_id']);
517 $returnProperties = array('contribution_status_id', 'receive_date');
518 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
519 $contributionParams, $contributionStatus, $returnProperties
521 $contributionValue = array(
522 'status' => CRM_Utils_Array
::value('contribution_status_id', $contributionStatus),
523 'receive_date' => CRM_Utils_Array
::value('receive_date', $contributionStatus),
526 $payments[$payID] = array_merge($contributionValue,
528 'amount' => CRM_Utils_Array
::value('scheduled_amount', $values),
529 'due_date' => CRM_Utils_Array
::value('scheduled_date', $values),
533 //get the first valid payment id.
534 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
535 $paymentStatusTypes[$values['status_id']] == 'Overdue'
538 $form->paymentId
= $values['id'];
543 //assign pledge fields value to template.
544 $pledgeFields = array(
546 'total_pledge_amount',
547 'frequency_interval',
554 foreach ($pledgeFields as $field) {
555 if (!empty($params[$field])) {
556 $form->assign($field, $params[$field]);
560 //assign all payments details.
562 $form->assign('payments', $payments);
565 //handle domain token values
566 $domain = CRM_Core_BAO_Domain
::getDomain();
568 'domain' => array('name', 'phone', 'address', 'email'),
569 'contact' => CRM_Core_SelectValues
::contactTokens(),
571 $domainValues = array();
572 foreach ($tokens['domain'] as $token) {
573 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
575 $form->assign('domain', $domainValues);
577 //handle contact token values.
578 $ids = array($params['contact_id']);
579 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
580 array('display_name', 'checksum', 'contact_id')
582 foreach ($fields as $key => $val) {
583 $returnProperties[$val] = TRUE;
585 $details = CRM_Utils_Token
::getTokenDetails($ids,
591 $form->assign('contact', $details[0][$params['contact_id']]);
593 //handle custom data.
594 if (!empty($params['hidden_custom'])) {
595 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', CRM_Core_DAO
::$_nullObject, $params['id']);
596 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
597 $customGroup = array();
598 // retrieve custom data
599 foreach ($groupTree as $groupID => $group) {
600 $customFields = $customValues = array();
601 if ($groupID == 'info') {
604 foreach ($group['fields'] as $k => $field) {
605 $field['title'] = $field['label'];
606 $customFields["custom_{$k}"] = $field;
609 //to build array of customgroup & customfields in it
610 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
611 $customGroup[$group['title']] = $customValues;
614 $form->assign('customGroup', $customGroup);
617 //handle acknowledgment email stuff.
618 list($pledgerDisplayName,
620 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
622 //check for online pledge.
623 if (!empty($params['receipt_from_email'])) {
624 $userName = CRM_Utils_Array
::value('receipt_from_name', $params);
625 $userEmail = CRM_Utils_Array
::value('receipt_from_email', $params);
627 elseif (!empty($params['from_email_id'])) {
628 $receiptFrom = $params['from_email_id'];
630 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
631 //check for logged in user.
632 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
635 //set the domain values.
636 $userName = CRM_Utils_Array
::value('name', $domainValues);
637 $userEmail = CRM_Utils_Array
::value('email', $domainValues);
640 if (!isset($receiptFrom)) {
641 $receiptFrom = "$userName <$userEmail>";
644 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
646 'groupName' => 'msg_tpl_workflow_pledge',
647 'valueName' => 'pledge_acknowledge',
648 'contactId' => $params['contact_id'],
649 'from' => $receiptFrom,
650 'toName' => $pledgerDisplayName,
651 'toEmail' => $pledgerEmail,
655 //check if activity record exist for this pledge
656 //Acknowledgment, if exist do not add activity.
657 $activityType = 'Pledge Acknowledgment';
658 $activity = new CRM_Activity_DAO_Activity();
659 $activity->source_record_id
= $params['id'];
660 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
666 $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)';
668 if (!$activity->find()) {
669 $activityParams = array(
670 'subject' => $subject,
671 'source_contact_id' => $params['contact_id'],
672 'source_record_id' => $params['id'],
673 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
677 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
678 'is_test' => $params['is_test'],
680 'details' => $details,
681 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $params),
684 //lets insert assignee record.
685 if (!empty($params['contact_id'])) {
686 $activityParams['assignee_contact_id'] = $params['contact_id'];
689 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
690 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
696 * Combine all the exportable fields from the lower levels object.
699 * array of exportable Fields
701 public static function &exportableFields() {
702 if (!self
::$_exportableFields) {
703 if (!self
::$_exportableFields) {
704 self
::$_exportableFields = array();
707 $fields = CRM_Pledge_DAO_Pledge
::export();
709 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
711 //set title to calculated fields
712 $calculatedFields = array(
713 'pledge_total_paid' => array('title' => ts('Total Paid')),
714 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
715 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
716 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
717 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
718 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
719 'pledge_payment_status' => array(
720 'title' => ts('Pledge Payment Status'),
721 'name' => 'pledge_payment_status',
722 'data_type' => CRM_Utils_Type
::T_STRING
,
726 $pledgeFields = array(
727 'pledge_status' => array(
728 'title' => 'Pledge Status',
729 'name' => 'pledge_status',
730 'data_type' => CRM_Utils_Type
::T_STRING
,
732 'pledge_frequency_unit' => array(
733 'title' => 'Pledge Frequency Unit',
734 'name' => 'pledge_frequency_unit',
735 'data_type' => CRM_Utils_Type
::T_ENUM
,
737 'pledge_frequency_interval' => array(
738 'title' => 'Pledge Frequency Interval',
739 'name' => 'pledge_frequency_interval',
740 'data_type' => CRM_Utils_Type
::T_INT
,
742 'pledge_contribution_page_id' => array(
743 'title' => 'Pledge Contribution Page Id',
744 'name' => 'pledge_contribution_page_id',
745 'data_type' => CRM_Utils_Type
::T_INT
,
749 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
752 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge'));
753 self
::$_exportableFields = $fields;
756 return self
::$_exportableFields;
760 * Get pending or in progress pledges.
762 * @param int $contactID
766 * associated array of pledge id(s)
768 public static function getContactPledges($contactID) {
769 $pledgeDetails = array();
770 $pledgeStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
774 //get pending and in progress status
780 if ($statusId = array_search($name, $pledgeStatuses)) {
781 $status[] = $statusId;
784 if (empty($status)) {
785 return $pledgeDetails;
788 $statusClause = " IN (" . implode(',', $status) . ")";
791 SELECT civicrm_pledge.id id
793 WHERE civicrm_pledge.status_id {$statusClause}
794 AND civicrm_pledge.contact_id = %1
797 $params[1] = array($contactID, 'Integer');
798 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
800 while ($pledge->fetch()) {
801 $pledgeDetails[] = $pledge->id
;
804 return $pledgeDetails;
808 * Get pledge record count for a Contact.
810 * @param int $contactID
813 * count of pledge records
815 public static function getContactPledgeCount($contactID) {
816 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
817 return CRM_Core_DAO
::singleValueQuery($query);
821 * @param array $params
825 public static function updatePledgeStatus($params) {
827 $returnMessages = array();
829 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
831 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
833 //unset statues that we never use for pledges
839 if ($key = CRM_Utils_Array
::key($statusKey, $allStatus)) {
840 unset($allStatus[$key]);
844 $statusIds = implode(',', array_keys($allStatus));
848 SELECT pledge.contact_id as contact_id,
849 pledge.id as pledge_id,
850 pledge.amount as amount,
851 payment.scheduled_date as scheduled_date,
852 pledge.create_date as create_date,
853 payment.id as payment_id,
854 pledge.currency as currency,
855 pledge.contribution_page_id as contribution_page_id,
856 payment.reminder_count as reminder_count,
857 pledge.max_reminders as max_reminders,
858 payment.reminder_date as reminder_date,
859 pledge.initial_reminder_day as initial_reminder_day,
860 pledge.additional_reminder_day as additional_reminder_day,
861 pledge.status_id as pledge_status,
862 payment.status_id as payment_status,
863 pledge.is_test as is_test,
864 pledge.campaign_id as campaign_id,
865 SUM(payment.scheduled_amount) as amount_due,
866 ( SELECT sum(civicrm_pledge_payment.actual_amount)
867 FROM civicrm_pledge_payment
868 WHERE civicrm_pledge_payment.status_id = 1
869 AND civicrm_pledge_payment.pledge_id = pledge.id
871 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
872 WHERE pledge.id = payment.pledge_id
873 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )
877 $dao = CRM_Core_DAO
::executeQuery($query);
880 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
881 while ($dao->fetch()) {
882 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
884 $pledgeDetails[$dao->payment_id
] = array(
885 'scheduled_date' => $dao->scheduled_date
,
886 'amount_due' => $dao->amount_due
,
887 'amount' => $dao->amount
,
888 'amount_paid' => $dao->amount_paid
,
889 'create_date' => $dao->create_date
,
890 'contact_id' => $dao->contact_id
,
891 'pledge_id' => $dao->pledge_id
,
892 'checksumValue' => $checksumValue,
893 'contribution_page_id' => $dao->contribution_page_id
,
894 'reminder_count' => $dao->reminder_count
,
895 'max_reminders' => $dao->max_reminders
,
896 'reminder_date' => $dao->reminder_date
,
897 'initial_reminder_day' => $dao->initial_reminder_day
,
898 'additional_reminder_day' => $dao->additional_reminder_day
,
899 'pledge_status' => $dao->pledge_status
,
900 'payment_status' => $dao->payment_status
,
901 'is_test' => $dao->is_test
,
902 'currency' => $dao->currency
,
903 'campaign_id' => $dao->campaign_id
,
906 $contactIds[$dao->contact_id
] = $dao->contact_id
;
907 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
909 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
911 ) && $dao->payment_status
!= array_search('Overdue', $allStatus)
913 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
917 // process the updating script...
919 foreach ($pledgePayments as $pledgeId => $paymentIds) {
920 // 1. update the pledge /pledge payment status. returns new status when an update happens
921 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
923 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
924 array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE
926 if ($newStatus != $pledgeStatus[$pledgeId]) {
927 $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
932 if ($sendReminders) {
933 // retrieve domain tokens
934 $domain = CRM_Core_BAO_Domain
::getDomain();
936 'domain' => array('name', 'phone', 'address', 'email'),
937 'contact' => CRM_Core_SelectValues
::contactTokens(),
940 $domainValues = array();
941 foreach ($tokens['domain'] as $token) {
942 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
945 //get the domain email address, since we don't carry w/ object.
946 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
947 $domainValues['email'] = $domainValue[1];
949 // retrieve contact tokens
951 // this function does NOT return Deceased contacts since we don't want to send them email
952 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
955 $tokens, 'CRM_UpdatePledgeRecord'
958 // assign domain values to template
959 $template = CRM_Core_Smarty
::singleton();
960 $template->assign('domain', $domainValues);
963 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
965 foreach ($pledgeDetails as $paymentId => $details) {
966 if (array_key_exists($details['contact_id'], $contactDetails)) {
967 $contactId = $details['contact_id'];
968 $pledgerName = $contactDetails[$contactId]['display_name'];
974 if (empty($details['reminder_date'])) {
975 $nextReminderDate = new DateTime($details['scheduled_date']);
976 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
977 $nextReminderDate = $nextReminderDate->format("Ymd");
980 $nextReminderDate = new DateTime($details['reminder_date']);
981 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
982 $nextReminderDate = $nextReminderDate->format("Ymd");
984 if (($details['reminder_count'] < $details['max_reminders'])
985 && ($nextReminderDate <= $now)
988 $toEmail = $doNotEmail = $onHold = NULL;
990 if (!empty($contactDetails[$contactId]['email'])) {
991 $toEmail = $contactDetails[$contactId]['email'];
994 if (!empty($contactDetails[$contactId]['do_not_email'])) {
995 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
998 if (!empty($contactDetails[$contactId]['on_hold'])) {
999 $onHold = $contactDetails[$contactId]['on_hold'];
1002 // 2. send acknowledgement mail
1003 if ($toEmail && !($doNotEmail ||
$onHold)) {
1004 //assign value to template
1005 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1006 $template->assign('contact', $contactDetails[$contactId]);
1007 $template->assign('next_payment', $details['scheduled_date']);
1008 $template->assign('amount_due', $details['amount_due']);
1009 $template->assign('checksumValue', $details['checksumValue']);
1010 $template->assign('contribution_page_id', $details['contribution_page_id']);
1011 $template->assign('pledge_id', $details['pledge_id']);
1012 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1013 $template->assign('amount', $details['amount']);
1014 $template->assign('create_date', $details['create_date']);
1015 $template->assign('currency', $details['currency']);
1016 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1018 'groupName' => 'msg_tpl_workflow_pledge',
1019 'valueName' => 'pledge_reminder',
1020 'contactId' => $contactId,
1021 'from' => $receiptFrom,
1022 'toName' => $pledgerName,
1023 'toEmail' => $toEmail,
1027 // 3. update pledge payment details
1029 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1030 $activityType = 'Pledge Reminder';
1031 $activityParams = array(
1032 'subject' => $subject,
1033 'source_contact_id' => $contactId,
1034 'source_record_id' => $paymentId,
1035 'assignee_contact_id' => $contactId,
1036 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1040 'activity_date_time' => CRM_Utils_Date
::isoToMysql($now),
1041 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1042 'is_test' => $details['is_test'],
1044 'campaign_id' => $details['campaign_id'],
1046 if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
1047 $returnMessages[] = "Failed creating Activity for acknowledgment";
1048 return array('is_error' => 1, 'message' => $returnMessages);
1050 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1055 // end foreach on $pledgeDetails
1057 // end if ( $sendReminders )
1058 $returnMessages[] = "{$updateCnt} records updated.";
1060 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1064 * Mark a pledge (and any outstanding payments) as cancelled.
1066 * @param int $pledgeID
1068 public static function cancel($pledgeID) {
1069 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1070 $paymentIDs = self
::findCancelablePayments($pledgeID);
1071 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1072 $statuses['Cancelled'], 0, FALSE, TRUE
1077 * Find payments which can be safely canceled.
1079 * @param int $pledgeID
1081 * Array of int (civicrm_pledge_payment.id)
1083 public static function findCancelablePayments($pledgeID) {
1084 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus());
1086 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1087 $paymentDAO->pledge_id
= $pledgeID;
1088 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1089 $statuses['Overdue'],
1090 $statuses['Pending']
1092 $paymentDAO->find();
1094 $paymentIDs = array();
1095 while ($paymentDAO->fetch()) {
1096 $paymentIDs[] = $paymentDAO->id
;
1102 * Is this pledge free from financial transactions (this is important to know as we allow editing
1103 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1104 * & recreating so we want to block that if appropriate
1106 * @param int $pledgeID
1107 * @param int $pledgeStatusID
1109 * do financial transactions exist for this pledge?
1111 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1112 if (empty($pledgeStatusID)) {
1113 //why would this happen? If we can see where it does then we can see if we should look it up
1114 //but assuming from form code it CAN be empty
1117 if (self
::isTransactedStatus($pledgeStatusID)) {
1121 return civicrm_api3('pledge_payment', 'getcount', array(
1122 'pledge_id' => $pledgeID,
1123 'status_id' => array('IN' => self
::getTransactionalStatus()),
1128 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1129 * @param int $statusID
1133 * is it a transactional status?
1135 protected static function isTransactedStatus($statusID) {
1136 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1143 * Get array of non transactional statuses.
1145 * non transactional status ids
1147 protected static function getNonTransactionalStatus() {
1148 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1149 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1153 * Get array of non transactional statuses.
1155 * non transactional status ids
1157 protected static function getTransactionalStatus() {
1158 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1159 return array_diff(array_flip($paymentStatus), self
::getNonTransactionalStatus());