3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Pledge_BAO_Pledge
extends CRM_Pledge_DAO_Pledge
{
20 * Static field for all the pledge information that we can potentially export.
24 public static $_exportableFields = NULL;
29 public function __construct() {
30 parent
::__construct();
34 * Retrieve DB object based on input parameters.
36 * It also stores all the retrieved values in the default array.
38 * @param array $params
39 * (reference ) an assoc array of name/value pairs.
40 * @param array $defaults
41 * (reference ) an assoc array to hold the flattened values.
43 * @return CRM_Pledge_BAO_Pledge
45 public static function retrieve(&$params, &$defaults) {
46 $pledge = new CRM_Pledge_DAO_Pledge();
47 $pledge->copyValues($params);
48 if ($pledge->find(TRUE)) {
49 CRM_Core_DAO
::storeValues($pledge, $defaults);
58 * @param array $params
59 * Reference array contains the values submitted by the form.
61 * @return CRM_Pledge_DAO_Pledge
63 public static function add(array $params): CRM_Pledge_DAO_Pledge
{
64 CRM_Core_Error
::deprecatedFunctionWarning('v4 api');
65 $hook = empty($params['id']) ?
'create' : 'edit';
66 CRM_Utils_Hook
::pre($hook, 'Pledge', $params['id'] ??
NULL, $params);
68 $pledge = new CRM_Pledge_DAO_Pledge();
70 // if pledge is complete update end date as current date
71 if ($pledge->status_id
== 1) {
72 $pledge->end_date
= date('Ymd');
75 $pledge->copyValues($params);
77 // set currency for CRM-1496
78 if (!isset($pledge->currency
)) {
79 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
82 $result = $pledge->save();
84 CRM_Utils_Hook
::post($hook, 'Pledge', $pledge->id
, $pledge);
90 * Given the list of params in the params array, fetch the object
91 * and store the values in the values array
93 * @param array $params
94 * Input parameters to find object.
95 * @param array $values
96 * Output values of the object.
97 * @param array $returnProperties
98 * If you want to return specific fields.
101 * associated array of field values
103 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
104 if (empty($params)) {
107 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
112 * Takes an associative array and creates a pledge object.
114 * @param array $params
115 * Assoc array of name/value pairs.
117 * @return CRM_Pledge_DAO_Pledge
118 * @throws \CRM_Core_Exception
120 public static function create(array $params): CRM_Pledge_DAO_Pledge
{
122 $isRecalculatePledgePayment = self
::isPaymentsRequireRecalculation($params);
123 $transaction = new CRM_Core_Transaction();
126 if (!empty($params['installment_amount'])) {
127 $params['amount'] = $params['installment_amount'] * $params['installments'];
130 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
131 if (isset($params['contribution_id'])) {
132 if ($params['installments'] > 1) {
133 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
137 if (!empty($params['id'])) {
138 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
141 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
145 $paymentParams['status_id'] = $params['status_id'] ??
NULL;
147 $hook = empty($params['id']) ?
'create' : 'edit';
148 CRM_Utils_Hook
::pre($hook, 'Pledge', $params['id'] ??
NULL, $params);
150 $pledge = new CRM_Pledge_DAO_Pledge();
152 // if pledge is complete update end date as current date
153 if ($pledge->status_id
== 1) {
154 $pledge->end_date
= date('Ymd');
157 $pledge->copyValues($params);
159 // set currency for CRM-1496
160 if (!isset($pledge->currency
)) {
161 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
166 CRM_Utils_Hook
::post($hook, 'Pledge', $pledge->id
, $pledge);
168 // handle custom data.
169 if (!empty($params['custom']) &&
170 is_array($params['custom'])
172 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
175 // skip payment stuff inedit mode
176 if (!isset($params['id']) ||
$isRecalculatePledgePayment) {
178 // if pledge is pending delete all payments and recreate.
179 if ($isRecalculatePledgePayment) {
180 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
183 // building payment params
184 $paymentParams['pledge_id'] = $pledge->id
;
192 'frequency_interval',
194 'installment_amount',
197 foreach ($paymentKeys as $key) {
198 $paymentParams[$key] = $params[$key] ??
NULL;
200 CRM_Pledge_BAO_PledgePayment
::createMultiple($paymentParams);
203 $transaction->commit();
205 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
206 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
210 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
211 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
212 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
215 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
216 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
217 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
221 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
222 $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) . ')';
224 // add the recently created Pledge
225 CRM_Utils_Recent
::add($title,
238 * Is this a change to an existing pending pledge requiring payment schedule
241 * If the pledge is pending the code (slightly lazily) deletes & recreates
244 * If the payment dates or amounts have been manually edited then this can
245 * cause data loss. We can mitigate this to some extent by making sure we
246 * have a change that could potentially affect the schedule (rather than just
247 * a custom data change or similar).
249 * This calculation needs to be performed before update takes place as
250 * previous & new pledges are compared.
252 * @param array $params
256 protected static function isPaymentsRequireRecalculation($params) {
257 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
260 $scheduleChangingParameters = [
263 'frequency_interval',
268 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
269 $existingPledgeDAO->id
= $params['id'];
270 $existingPledgeDAO->find(TRUE);
271 foreach ($scheduleChangingParameters as $parameter) {
272 if ($parameter == 'start_date') {
273 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
277 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
291 public static function deletePledge($id) {
292 CRM_Utils_Hook
::pre('delete', 'Pledge', $id);
294 $transaction = new CRM_Core_Transaction();
296 // check for no Completed Payment records with the pledge
297 $payment = new CRM_Pledge_DAO_PledgePayment();
298 $payment->pledge_id
= $id;
301 while ($payment->fetch()) {
302 // also delete associated contribution.
303 if ($payment->contribution_id
) {
304 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
309 $dao = new CRM_Pledge_DAO_Pledge();
311 $results = $dao->delete();
313 $transaction->commit();
315 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
317 // delete the recently created Pledge
322 CRM_Utils_Recent
::del($pledgeRecent);
328 * Get the amount details date wise.
330 * @param string $status
331 * @param string $startDate
332 * @param string $endDate
336 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
338 $select = $from = $queryDate = NULL;
339 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
343 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
350 $where[] = 'status_id = ' . $statusId;
355 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
358 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
361 $whereCond = implode(' AND ', $where);
364 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
366 WHERE $whereCond AND is_test=0
369 $start = substr($startDate, 0, 8);
370 $end = substr($endDate, 0, 8);
373 $dao = CRM_Core_DAO
::executeQuery($query);
374 while ($dao->fetch()) {
375 $pCount +
= $dao->pledge_count
;
376 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
380 'pledge_amount' => implode(', ', $pamount),
381 'pledge_count' => $pCount,
382 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
383 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
390 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
391 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
392 $queryDate = 'receive_date';
393 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
397 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
398 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
399 $queryDate = 'receive_date';
400 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
404 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
405 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
406 $queryDate = 'scheduled_date';
407 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
411 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
412 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
413 $queryDate = 'scheduled_date';
414 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
419 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
422 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
425 $whereCond = implode(' AND ', $where);
428 SELECT $select, cp.currency
434 $dao = CRM_Core_DAO
::executeQuery($query);
438 while ($dao->fetch()) {
439 $count +
= $dao->received_count
;
440 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
444 return array_merge($pledge_amount, [
445 'received_amount' => implode(', ', $amount),
446 'received_count' => $count,
447 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
448 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
454 return $pledge_amount;
460 * Get list of pledges In Honor of contact Ids.
462 * @param int $honorId
463 * In Honor of Contact ID.
466 * return the list of pledge fields
468 public static function getHonorContacts($honorId) {
470 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
471 $honorDAO->contact_id
= $honorId;
475 while ($honorDAO->fetch()) {
476 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
477 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
478 if ($pledgePaymentDAO->find(TRUE)) {
479 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
480 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
481 if ($pledgeDAO->find(TRUE)) {
482 $params[$pledgeDAO->id
] = [
483 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
484 'honorId' => $pledgeDAO->contact_id
,
485 'amount' => $pledgeDAO->amount
,
486 'status' => CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id
),
487 'create_date' => $pledgeDAO->create_date
,
488 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
489 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
490 $pledgeDAO->financial_type_id
, 'name'
492 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
493 $pledgeDAO->contact_id
, 'display_name'
504 * Send Acknowledgment and create activity.
506 * @param CRM_Core_Form $form
508 * @param array $params
509 * An assoc array of name/value pairs.
511 public static function sendAcknowledgment(&$form, $params) {
512 //handle Acknowledgment.
513 $allPayments = $payments = [];
515 // get All Payments status types.
516 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
517 $returnProperties = [
523 // get all paymnets details.
524 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
526 if (!empty($allPayments)) {
527 foreach ($allPayments as $payID => $values) {
528 $contributionValue = $contributionStatus = [];
529 if (isset($values['contribution_id'])) {
530 $contributionParams = ['id' => $values['contribution_id']];
531 $returnProperties = ['contribution_status_id', 'receive_date'];
532 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
533 $contributionParams, $contributionStatus, $returnProperties
535 $contributionValue = [
536 'status' => $contributionStatus['contribution_status_id'] ??
NULL,
537 'receive_date' => $contributionStatus['receive_date'] ??
NULL,
540 $payments[$payID] = array_merge($contributionValue,
542 'amount' => $values['scheduled_amount'] ??
NULL,
543 'due_date' => $values['scheduled_date'] ??
NULL,
547 // get the first valid payment id.
548 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
549 $paymentStatusTypes[$values['status_id']] == 'Overdue'
552 $form->paymentId
= $values['id'];
557 // assign pledge fields value to template.
560 'total_pledge_amount',
561 'frequency_interval',
568 foreach ($pledgeFields as $field) {
569 if (!empty($params[$field])) {
570 $form->assign($field, $params[$field]);
574 // assign all payments details.
576 $form->assign('payments', $payments);
579 // handle domain token values
580 $domain = CRM_Core_BAO_Domain
::getDomain();
582 'domain' => ['name', 'phone', 'address', 'email'],
583 'contact' => CRM_Core_SelectValues
::contactTokens(),
586 foreach ($tokens['domain'] as $token) {
587 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
589 $form->assign('domain', $domainValues);
591 // handle contact token values.
592 $ids = [$params['contact_id']];
593 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
594 ['display_name', 'checksum', 'contact_id']
596 foreach ($fields as $key => $val) {
597 $returnProperties[$val] = TRUE;
599 [$details] = CRM_Utils_Token
::getTokenDetails($ids,
605 $form->assign('contact', $details[$params['contact_id']]);
607 // handle custom data.
608 if (!empty($params['hidden_custom'])) {
609 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', NULL, $params['id']);
610 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
612 // retrieve custom data
613 foreach ($groupTree as $groupID => $group) {
614 $customFields = $customValues = [];
615 if ($groupID == 'info') {
618 foreach ($group['fields'] as $k => $field) {
619 $field['title'] = $field['label'];
620 $customFields["custom_{$k}"] = $field;
623 // to build array of customgroup & customfields in it
624 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
625 $customGroup[$group['title']] = $customValues;
628 $form->assign('customGroup', $customGroup);
631 // handle acknowledgment email stuff.
632 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
634 // check for online pledge.
635 if (!empty($params['receipt_from_email'])) {
636 $userName = $params['receipt_from_name'] ??
NULL;
637 $userEmail = $params['receipt_from_email'] ??
NULL;
639 elseif (!empty($params['from_email_id'])) {
640 $receiptFrom = $params['from_email_id'];
642 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
643 // check for logged in user.
647 ] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
650 // set the domain values.
651 $userName = $domainValues['name'] ??
NULL;
652 $userEmail = $domainValues['email'] ??
NULL;
655 if (!isset($receiptFrom)) {
656 $receiptFrom = "$userName <$userEmail>";
659 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
661 'groupName' => 'msg_tpl_workflow_pledge',
662 'valueName' => 'pledge_acknowledge',
663 'contactId' => $params['contact_id'],
664 'from' => $receiptFrom,
665 'toName' => $pledgerDisplayName,
666 'toEmail' => $pledgerEmail,
670 // check if activity record exist for this pledge
671 // Acknowledgment, if exist do not add activity.
672 $activityType = 'Pledge Acknowledgment';
673 $activity = new CRM_Activity_DAO_Activity();
674 $activity->source_record_id
= $params['id'];
675 $activity->activity_type_id
= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
681 $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)';
683 if (!$activity->find()) {
685 'subject' => $subject,
686 'source_contact_id' => $params['contact_id'],
687 'source_record_id' => $params['id'],
688 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
692 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
693 'is_test' => $params['is_test'],
695 'details' => $details,
696 'campaign_id' => $params['campaign_id'] ??
NULL,
699 // lets insert assignee record.
700 if (!empty($params['contact_id'])) {
701 $activityParams['assignee_contact_id'] = $params['contact_id'];
704 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
705 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
711 * Combine all the exportable fields from the lower levels object.
713 * @param bool $checkPermission
716 * array of exportable Fields
718 public static function exportableFields($checkPermission = TRUE) {
719 if (!self
::$_exportableFields) {
720 if (!self
::$_exportableFields) {
721 self
::$_exportableFields = [];
724 $fields = CRM_Pledge_DAO_Pledge
::export();
726 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
728 // set title to calculated fields
729 $calculatedFields = [
730 'pledge_total_paid' => ['title' => ts('Total Paid')],
731 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
732 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
733 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
734 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
735 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
736 'pledge_payment_status' => [
737 'title' => ts('Pledge Payment Status'),
738 'name' => 'pledge_payment_status',
739 'data_type' => CRM_Utils_Type
::T_STRING
,
745 'title' => ts('Pledge Status'),
746 'name' => 'pledge_status',
747 'data_type' => CRM_Utils_Type
::T_STRING
,
749 'pledge_frequency_unit' => [
750 'title' => ts('Pledge Frequency Unit'),
751 'name' => 'pledge_frequency_unit',
752 'data_type' => CRM_Utils_Type
::T_ENUM
,
754 'pledge_frequency_interval' => [
755 'title' => ts('Pledge Frequency Interval'),
756 'name' => 'pledge_frequency_interval',
757 'data_type' => CRM_Utils_Type
::T_INT
,
759 'pledge_contribution_page_id' => [
760 'title' => ts('Pledge Contribution Page Id'),
761 'name' => 'pledge_contribution_page_id',
762 'data_type' => CRM_Utils_Type
::T_INT
,
766 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
769 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
770 self
::$_exportableFields = $fields;
773 return self
::$_exportableFields;
777 * Get pending or in progress pledges.
779 * @param int $contactID
783 * associated array of pledge id(s)
785 public static function getContactPledges($contactID) {
787 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
788 FALSE, FALSE, FALSE, NULL, 'name'
793 // get pending and in progress status
794 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
795 if ($statusId = array_search($name, $pledgeStatuses)) {
796 $status[] = $statusId;
799 if (empty($status)) {
800 return $pledgeDetails;
803 $statusClause = " IN (" . implode(',', $status) . ")";
806 SELECT civicrm_pledge.id id
808 WHERE civicrm_pledge.status_id {$statusClause}
809 AND civicrm_pledge.contact_id = %1
812 $params[1] = [$contactID, 'Integer'];
813 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
815 while ($pledge->fetch()) {
816 $pledgeDetails[] = $pledge->id
;
819 return $pledgeDetails;
823 * Get pledge record count for a Contact.
825 * @param int $contactID
828 * count of pledge records
830 public static function getContactPledgeCount($contactID) {
831 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
832 return CRM_Core_DAO
::singleValueQuery($query);
836 * @param array $params
840 public static function updatePledgeStatus($params) {
842 $returnMessages = [];
844 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
846 $allStatus = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
847 $allPledgeStatus = CRM_Core_OptionGroup
::values('pledge_status',
848 TRUE, FALSE, FALSE, NULL, 'name', TRUE
850 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
851 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
853 $statusIds = implode(',', $allStatus);
854 $pledgeStatusIds = implode(',', $allPledgeStatus);
858 SELECT pledge.contact_id as contact_id,
859 pledge.id as pledge_id,
860 pledge.amount as amount,
861 payment.scheduled_date as scheduled_date,
862 pledge.create_date as create_date,
863 payment.id as payment_id,
864 pledge.currency as currency,
865 pledge.contribution_page_id as contribution_page_id,
866 payment.reminder_count as reminder_count,
867 pledge.max_reminders as max_reminders,
868 payment.reminder_date as reminder_date,
869 pledge.initial_reminder_day as initial_reminder_day,
870 pledge.additional_reminder_day as additional_reminder_day,
871 pledge.status_id as pledge_status,
872 payment.status_id as payment_status,
873 pledge.is_test as is_test,
874 pledge.campaign_id as campaign_id,
875 SUM(payment.scheduled_amount) as amount_due,
876 ( SELECT sum(civicrm_pledge_payment.actual_amount)
877 FROM civicrm_pledge_payment
878 WHERE civicrm_pledge_payment.status_id = 1
879 AND civicrm_pledge_payment.pledge_id = pledge.id
881 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
882 WHERE pledge.id = payment.pledge_id
883 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
887 $dao = CRM_Core_DAO
::executeQuery($query);
890 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
891 while ($dao->fetch()) {
892 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
894 $pledgeDetails[$dao->payment_id
] = [
895 'scheduled_date' => $dao->scheduled_date
,
896 'amount_due' => $dao->amount_due
,
897 'amount' => $dao->amount
,
898 'amount_paid' => $dao->amount_paid
,
899 'create_date' => $dao->create_date
,
900 'contact_id' => $dao->contact_id
,
901 'pledge_id' => $dao->pledge_id
,
902 'checksumValue' => $checksumValue,
903 'contribution_page_id' => $dao->contribution_page_id
,
904 'reminder_count' => $dao->reminder_count
,
905 'max_reminders' => $dao->max_reminders
,
906 'reminder_date' => $dao->reminder_date
,
907 'initial_reminder_day' => $dao->initial_reminder_day
,
908 'additional_reminder_day' => $dao->additional_reminder_day
,
909 'pledge_status' => $dao->pledge_status
,
910 'payment_status' => $dao->payment_status
,
911 'is_test' => $dao->is_test
,
912 'currency' => $dao->currency
,
913 'campaign_id' => $dao->campaign_id
,
916 $contactIds[$dao->contact_id
] = $dao->contact_id
;
917 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
919 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
921 ) && $dao->payment_status
!= $allStatus['Overdue']
923 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
926 $allPledgeStatus = array_flip($allPledgeStatus);
928 // process the updating script...
929 foreach ($pledgePayments as $pledgeId => $paymentIds) {
930 // 1. update the pledge /pledge payment status. returns new status when an update happens
931 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
933 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
934 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
936 if ($newStatus != $pledgeStatus[$pledgeId]) {
937 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
942 if ($sendReminders) {
943 // retrieve domain tokens
944 $domain = CRM_Core_BAO_Domain
::getDomain();
946 'domain' => ['name', 'phone', 'address', 'email'],
947 'contact' => CRM_Core_SelectValues
::contactTokens(),
951 foreach ($tokens['domain'] as $token) {
952 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
955 // get the domain email address, since we don't carry w/ object.
956 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
957 $domainValues['email'] = $domainValue[1];
959 // retrieve contact tokens
961 // this function does NOT return Deceased contacts since we don't want to send them email
962 [$contactDetails] = CRM_Utils_Token
::getTokenDetails($contactIds,
965 $tokens, 'CRM_UpdatePledgeRecord'
968 // assign domain values to template
969 $template = CRM_Core_Smarty
::singleton();
970 $template->assign('domain', $domainValues);
973 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
975 foreach ($pledgeDetails as $paymentId => $details) {
976 if (array_key_exists($details['contact_id'], $contactDetails)) {
977 $contactId = $details['contact_id'];
978 $pledgerName = $contactDetails[$contactId]['display_name'];
984 if (empty($details['reminder_date'])) {
985 $nextReminderDate = new DateTime($details['scheduled_date']);
986 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
987 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
988 $nextReminderDate = $nextReminderDate->format("Ymd");
991 $nextReminderDate = new DateTime($details['reminder_date']);
992 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
993 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
994 $nextReminderDate = $nextReminderDate->format("Ymd");
996 if (($details['reminder_count'] < $details['max_reminders'])
997 && ($nextReminderDate <= $now)
1000 $toEmail = $doNotEmail = $onHold = NULL;
1002 if (!empty($contactDetails[$contactId]['email'])) {
1003 $toEmail = $contactDetails[$contactId]['email'];
1006 if (!empty($contactDetails[$contactId]['do_not_email'])) {
1007 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
1010 if (!empty($contactDetails[$contactId]['on_hold'])) {
1011 $onHold = $contactDetails[$contactId]['on_hold'];
1014 // 2. send acknowledgement mail
1015 if ($toEmail && !($doNotEmail ||
$onHold)) {
1016 // assign value to template
1017 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1018 $template->assign('contact', $contactDetails[$contactId]);
1019 $template->assign('next_payment', $details['scheduled_date']);
1020 $template->assign('amount_due', $details['amount_due']);
1021 $template->assign('checksumValue', $details['checksumValue']);
1022 $template->assign('contribution_page_id', $details['contribution_page_id']);
1023 $template->assign('pledge_id', $details['pledge_id']);
1024 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1025 $template->assign('amount', $details['amount']);
1026 $template->assign('create_date', $details['create_date']);
1027 $template->assign('currency', $details['currency']);
1033 ] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1035 'groupName' => 'msg_tpl_workflow_pledge',
1036 'valueName' => 'pledge_reminder',
1037 'contactId' => $contactId,
1038 'from' => $receiptFrom,
1039 'toName' => $pledgerName,
1040 'toEmail' => $toEmail,
1044 // 3. update pledge payment details
1046 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1047 $activityType = 'Pledge Reminder';
1049 'subject' => $subject,
1050 'source_contact_id' => $contactId,
1051 'source_record_id' => $paymentId,
1052 'assignee_contact_id' => $contactId,
1053 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
1057 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1058 'is_test' => $details['is_test'],
1060 'campaign_id' => $details['campaign_id'],
1063 civicrm_api3('activity', 'create', $activityParams);
1065 catch (CiviCRM_API3_Exception
$e) {
1066 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1067 return ['is_error' => 1, 'message' => $returnMessages];
1069 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1074 // end foreach on $pledgeDetails
1076 // end if ( $sendReminders )
1077 $returnMessages[] = "{$updateCnt} records updated.";
1079 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1083 * Mark a pledge (and any outstanding payments) as cancelled.
1085 * @param int $pledgeID
1087 public static function cancel($pledgeID) {
1088 $paymentIDs = self
::findCancelablePayments($pledgeID);
1089 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1090 $cancelled = array_search('Cancelled', $status);
1091 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1092 $cancelled, 0, FALSE, TRUE
1097 * Find payments which can be safely canceled.
1099 * @param int $pledgeID
1102 * Array of int (civicrm_pledge_payment.id)
1104 public static function findCancelablePayments($pledgeID) {
1105 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'));
1107 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1108 $paymentDAO->pledge_id
= $pledgeID;
1109 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1110 $statuses['Overdue'],
1111 $statuses['Pending']
1113 $paymentDAO->find();
1116 while ($paymentDAO->fetch()) {
1117 $paymentIDs[] = $paymentDAO->id
;
1123 * Is this pledge free from financial transactions (this is important to know
1124 * as we allow editing when no transactions have taken place - the editing
1125 * process currently involves deleting all pledge payments & contributions
1126 * & recreating so we want to block that if appropriate).
1128 * @param int $pledgeID
1129 * @param int $pledgeStatusID
1132 * do financial transactions exist for this pledge?
1134 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1135 if (empty($pledgeStatusID)) {
1136 // why would this happen? If we can see where it does then we can see if we should look it up.
1137 // but assuming from form code it CAN be empty.
1140 if (self
::isTransactedStatus($pledgeStatusID)) {
1144 return civicrm_api3('pledge_payment', 'getcount', [
1145 'pledge_id' => $pledgeID,
1146 'contribution_id' => ['IS NOT NULL' => TRUE],
1151 * Does this pledge / pledge payment status mean that a financial transaction
1154 * @param int $statusID
1158 * is it a transactional status?
1160 protected static function isTransactedStatus($statusID) {
1161 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1168 * Get array of non transactional statuses.
1171 * non transactional status ids
1173 protected static function getNonTransactionalStatus() {
1174 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1175 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1179 * Create array for recur record for pledge.
1182 * params for recur record
1184 public static function buildRecurParams($params) {
1187 'auto_renew' => TRUE,
1188 'frequency_unit' => $params['pledge_frequency_unit'],
1189 'frequency_interval' => $params['pledge_frequency_interval'],
1190 'installments' => $params['pledge_installments'],
1191 'start_date' => $params['receive_date'],
1193 return $recurParams;
1197 * Get pledge start date.
1202 public static function getPledgeStartDate($date, $pledgeBlock) {
1203 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1204 foreach ($startDate as $field => $value) {
1205 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1212 case 'contribution_date':
1214 $date = date('Ymd');
1218 case 'calendar_date':
1219 $date = date('Ymd', strtotime($date));
1222 case 'calendar_month':
1223 $date = self
::getPaymentDate($date);
1224 $date = date('Ymd', strtotime($date));
1236 * Get first payment date for pledge.
1240 * @return bool|string
1242 public static function getPaymentDate($day) {
1244 // Find out if current month has 31 days, if not, set it to 30 (last day).
1250 $current = date('d');
1252 case ($day == $current):
1253 $date = date('m/d/Y');
1256 case ($day > $current):
1257 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1260 case ($day < $current):
1261 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1272 * Override buildOptions to hack out some statuses.
1274 * @param string $fieldName
1275 * @param string $context
1276 * @param array $props
1278 * @return array|bool
1279 * @todo instead of using & hacking the shared optionGroup
1280 * contribution_status use a separate one.
1283 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1284 $result = parent
::buildOptions($fieldName, $context, $props);
1285 if ($fieldName == 'status_id') {
1286 $result = array_diff($result, ['Failed']);