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
{
121 $action = empty($params['id']) ?
'create' : 'edit';
122 if ($action === 'create') {
124 'currency' => CRM_Core_Config
::singleton()->defaultCurrency
,
125 'installments' => (int) self
::fields()['installments']['default'],
126 'scheduled_date' => $params['start_date'] ??
date('Ymd'),
128 $params = array_merge($defaults, $params);
131 $isRecalculatePledgePayment = self
::isPaymentsRequireRecalculation($params);
132 $transaction = new CRM_Core_Transaction();
135 if (!empty($params['installment_amount'])) {
136 $params['amount'] = $params['installment_amount'] * $params['installments'];
139 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
140 if (isset($params['contribution_id'])) {
141 if ($params['installments'] > 1) {
142 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
146 if (!empty($params['id'])) {
147 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
150 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
154 $paymentParams['status_id'] = $params['status_id'] ??
NULL;
156 CRM_Utils_Hook
::pre($action, 'Pledge', $params['id'] ??
NULL, $params);
157 $pledge = new CRM_Pledge_DAO_Pledge();
159 // if pledge is complete update end date as current date
160 if ($pledge->status_id
== 1) {
161 $pledge->end_date
= date('Ymd');
164 $pledge->copyValues($params);
166 CRM_Utils_Hook
::post($action, '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 in edit mode
176 if (empty($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);
321 * Get the amount details date wise.
323 * @param string $status
324 * @param string $startDate
325 * @param string $endDate
329 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
331 $select = $from = $queryDate = NULL;
332 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
336 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
343 $where[] = 'status_id = ' . $statusId;
348 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
351 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
354 $whereCond = implode(' AND ', $where);
357 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
359 WHERE $whereCond AND is_test=0
362 $start = substr($startDate, 0, 8);
363 $end = substr($endDate, 0, 8);
366 $dao = CRM_Core_DAO
::executeQuery($query);
367 while ($dao->fetch()) {
368 $pCount +
= $dao->pledge_count
;
369 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
373 'pledge_amount' => implode(', ', $pamount),
374 'pledge_count' => $pCount,
375 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
376 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
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( 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( 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';
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';
412 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
415 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
418 $whereCond = implode(' AND ', $where);
421 SELECT $select, cp.currency
427 $dao = CRM_Core_DAO
::executeQuery($query);
431 while ($dao->fetch()) {
432 $count +
= $dao->received_count
;
433 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
437 return array_merge($pledge_amount, [
438 'received_amount' => implode(', ', $amount),
439 'received_count' => $count,
440 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
441 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
447 return $pledge_amount;
453 * Get list of pledges In Honor of contact Ids.
455 * @param int $honorId
456 * In Honor of Contact ID.
459 * return the list of pledge fields
461 public static function getHonorContacts($honorId) {
463 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
464 $honorDAO->contact_id
= $honorId;
468 while ($honorDAO->fetch()) {
469 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
470 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
471 if ($pledgePaymentDAO->find(TRUE)) {
472 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
473 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
474 if ($pledgeDAO->find(TRUE)) {
475 $params[$pledgeDAO->id
] = [
476 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
477 'honorId' => $pledgeDAO->contact_id
,
478 'amount' => $pledgeDAO->amount
,
479 'status' => CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id
),
480 'create_date' => $pledgeDAO->create_date
,
481 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
482 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
483 $pledgeDAO->financial_type_id
, 'name'
485 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
486 $pledgeDAO->contact_id
, 'display_name'
497 * Send Acknowledgment and create activity.
499 * @param CRM_Core_Form $form
501 * @param array $params
502 * An assoc array of name/value pairs.
504 public static function sendAcknowledgment(&$form, $params) {
505 //handle Acknowledgment.
506 $allPayments = $payments = [];
508 // get All Payments status types.
509 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
510 $returnProperties = [
516 // get all paymnets details.
517 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
519 if (!empty($allPayments)) {
520 foreach ($allPayments as $payID => $values) {
521 $contributionValue = $contributionStatus = [];
522 if (isset($values['contribution_id'])) {
523 $contributionParams = ['id' => $values['contribution_id']];
524 $returnProperties = ['contribution_status_id', 'receive_date'];
525 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
526 $contributionParams, $contributionStatus, $returnProperties
528 $contributionValue = [
529 'status' => $contributionStatus['contribution_status_id'] ??
NULL,
530 'receive_date' => $contributionStatus['receive_date'] ??
NULL,
533 $payments[$payID] = array_merge($contributionValue,
535 'amount' => $values['scheduled_amount'] ??
NULL,
536 'due_date' => $values['scheduled_date'] ??
NULL,
537 'status' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'),
541 // get the first valid payment id.
542 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
543 $paymentStatusTypes[$values['status_id']] == 'Overdue'
546 $form->paymentId
= $values['id'];
551 // assign pledge fields value to template.
554 'total_pledge_amount',
555 'frequency_interval',
562 foreach ($pledgeFields as $field) {
563 if (!empty($params[$field])) {
564 $form->assign($field, $params[$field]);
568 // assign all payments details.
570 $form->assign('payments', $payments);
573 // handle custom data.
575 if (!empty($params['hidden_custom'])) {
576 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', NULL, $params['id']);
577 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
578 // retrieve custom data
579 foreach ($groupTree as $groupID => $group) {
580 $customFields = $customValues = [];
581 if ($groupID == 'info') {
584 foreach ($group['fields'] as $k => $field) {
585 $field['title'] = $field['label'];
586 $customFields["custom_{$k}"] = $field;
589 // to build array of customgroup & customfields in it
590 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
591 $customGroup[$group['title']] = $customValues;
595 $form->assign('customGroup', $customGroup);
597 // handle acknowledgment email stuff.
598 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
600 // check for online pledge.
601 if (!empty($params['receipt_from_email'])) {
602 $userName = $params['receipt_from_name'] ??
NULL;
603 $userEmail = $params['receipt_from_email'] ??
NULL;
605 elseif (!empty($params['from_email_id'])) {
606 $receiptFrom = $params['from_email_id'];
608 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
609 // check for logged in user.
613 ] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
616 // set the domain values.
617 [$userName, $userEmail] = CRM_Core_BAO_Domain
::getNameAndEmail();
620 if (!isset($receiptFrom)) {
621 $receiptFrom = "$userName <$userEmail>";
624 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
626 'groupName' => 'msg_tpl_workflow_pledge',
627 'valueName' => 'pledge_acknowledge',
628 'contactId' => $params['contact_id'],
629 'from' => $receiptFrom,
630 'toName' => $pledgerDisplayName,
631 'toEmail' => $pledgerEmail,
635 // check if activity record exist for this pledge
636 // Acknowledgment, if exist do not add activity.
637 $activityType = 'Pledge Acknowledgment';
638 $activity = new CRM_Activity_DAO_Activity();
639 $activity->source_record_id
= $params['id'];
640 $activity->activity_type_id
= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
646 $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)';
648 if (!$activity->find()) {
650 'subject' => $subject,
651 'source_contact_id' => $params['contact_id'],
652 'source_record_id' => $params['id'],
653 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
657 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
658 'is_test' => $params['is_test'],
660 'details' => $details,
661 'campaign_id' => $params['campaign_id'] ??
NULL,
664 // lets insert assignee record.
665 if (!empty($params['contact_id'])) {
666 $activityParams['assignee_contact_id'] = $params['contact_id'];
669 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
670 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
676 * Combine all the exportable fields from the lower levels object.
678 * @param bool $checkPermission
681 * array of exportable Fields
683 public static function exportableFields($checkPermission = TRUE) {
684 if (!self
::$_exportableFields) {
685 if (!self
::$_exportableFields) {
686 self
::$_exportableFields = [];
689 $fields = CRM_Pledge_DAO_Pledge
::export();
691 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
693 // set title to calculated fields
694 $calculatedFields = [
695 'pledge_total_paid' => ['title' => ts('Total Paid')],
696 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
697 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
698 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
699 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
700 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
701 'pledge_payment_status' => [
702 'title' => ts('Pledge Payment Status'),
703 'name' => 'pledge_payment_status',
704 'data_type' => CRM_Utils_Type
::T_STRING
,
710 'title' => ts('Pledge Status'),
711 'name' => 'pledge_status',
712 'data_type' => CRM_Utils_Type
::T_STRING
,
714 'pledge_frequency_unit' => [
715 'title' => ts('Pledge Frequency Unit'),
716 'name' => 'pledge_frequency_unit',
717 'data_type' => CRM_Utils_Type
::T_ENUM
,
719 'pledge_frequency_interval' => [
720 'title' => ts('Pledge Frequency Interval'),
721 'name' => 'pledge_frequency_interval',
722 'data_type' => CRM_Utils_Type
::T_INT
,
724 'pledge_contribution_page_id' => [
725 'title' => ts('Pledge Contribution Page Id'),
726 'name' => 'pledge_contribution_page_id',
727 'data_type' => CRM_Utils_Type
::T_INT
,
731 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
734 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
735 self
::$_exportableFields = $fields;
738 return self
::$_exportableFields;
742 * Get pending or in progress pledges.
744 * @param int $contactID
748 * associated array of pledge id(s)
750 public static function getContactPledges($contactID) {
752 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
753 FALSE, FALSE, FALSE, NULL, 'name'
758 // get pending and in progress status
759 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
760 if ($statusId = array_search($name, $pledgeStatuses)) {
761 $status[] = $statusId;
764 if (empty($status)) {
765 return $pledgeDetails;
768 $statusClause = " IN (" . implode(',', $status) . ")";
771 SELECT civicrm_pledge.id id
773 WHERE civicrm_pledge.status_id {$statusClause}
774 AND civicrm_pledge.contact_id = %1
777 $params[1] = [$contactID, 'Integer'];
778 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
780 while ($pledge->fetch()) {
781 $pledgeDetails[] = $pledge->id
;
784 return $pledgeDetails;
788 * Get pledge record count for a Contact.
790 * @param int $contactID
793 * count of pledge records
795 public static function getContactPledgeCount($contactID) {
796 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
797 return CRM_Core_DAO
::singleValueQuery($query);
801 * @param array $params
804 * @throws \API_Exception
805 * @throws \CRM_Core_Exception
806 * @throws \CiviCRM_API3_Exception
808 public static function updatePledgeStatus($params): array {
810 $returnMessages = [];
812 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
814 $allStatus = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
815 $allPledgeStatus = CRM_Core_OptionGroup
::values('pledge_status',
816 TRUE, FALSE, FALSE, NULL, 'name', TRUE
818 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
819 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
821 $statusIds = implode(',', $allStatus);
822 $pledgeStatusIds = implode(',', $allPledgeStatus);
826 SELECT pledge.contact_id as contact_id,
827 pledge.id as pledge_id,
828 pledge.amount as amount,
829 payment.scheduled_date as scheduled_date,
830 pledge.create_date as create_date,
831 payment.id as payment_id,
832 pledge.currency as currency,
833 pledge.contribution_page_id as contribution_page_id,
834 payment.reminder_count as reminder_count,
835 pledge.max_reminders as max_reminders,
836 payment.reminder_date as reminder_date,
837 pledge.initial_reminder_day as initial_reminder_day,
838 pledge.additional_reminder_day as additional_reminder_day,
839 pledge.status_id as pledge_status,
840 payment.status_id as payment_status,
841 pledge.is_test as is_test,
842 pledge.campaign_id as campaign_id,
843 SUM(payment.scheduled_amount) as amount_due,
844 ( SELECT sum(civicrm_pledge_payment.actual_amount)
845 FROM civicrm_pledge_payment
846 WHERE civicrm_pledge_payment.status_id = 1
847 AND civicrm_pledge_payment.pledge_id = pledge.id
849 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
850 WHERE pledge.id = payment.pledge_id
851 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
855 $dao = CRM_Core_DAO
::executeQuery($query);
858 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
859 while ($dao->fetch()) {
860 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
862 $pledgeDetails[$dao->payment_id
] = [
863 'scheduled_date' => $dao->scheduled_date
,
864 'amount_due' => $dao->amount_due
,
865 'amount' => $dao->amount
,
866 'amount_paid' => $dao->amount_paid
,
867 'create_date' => $dao->create_date
,
868 'contact_id' => $dao->contact_id
,
869 'pledge_id' => $dao->pledge_id
,
870 'checksumValue' => $checksumValue,
871 'contribution_page_id' => $dao->contribution_page_id
,
872 'reminder_count' => $dao->reminder_count
,
873 'max_reminders' => $dao->max_reminders
,
874 'reminder_date' => $dao->reminder_date
,
875 'initial_reminder_day' => $dao->initial_reminder_day
,
876 'additional_reminder_day' => $dao->additional_reminder_day
,
877 'pledge_status' => $dao->pledge_status
,
878 'payment_status' => $dao->payment_status
,
879 'is_test' => $dao->is_test
,
880 'currency' => $dao->currency
,
881 'campaign_id' => $dao->campaign_id
,
884 $contactIds[$dao->contact_id
] = $dao->contact_id
;
885 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
887 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
889 ) && $dao->payment_status
!= $allStatus['Overdue']
891 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
894 $allPledgeStatus = array_flip($allPledgeStatus);
896 // process the updating script...
897 foreach ($pledgePayments as $pledgeId => $paymentIds) {
898 // 1. update the pledge /pledge payment status. returns new status when an update happens
899 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
901 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
902 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
904 if ($newStatus != $pledgeStatus[$pledgeId]) {
905 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
910 if ($sendReminders) {
911 // retrieve domain tokens
913 'domain' => ['name', 'phone', 'address', 'email'],
914 'contact' => CRM_Core_SelectValues
::contactTokens(),
917 // retrieve contact tokens
919 // this function does NOT return Deceased contacts since we don't want to send them email
920 $contactDetails = civicrm_api3('Contact', 'get', [
922 'id' => ['IN' => $contactIds],
923 'return' => ['id', 'display_name', 'email', 'do_not_email', 'email', 'on_hold'],
926 // assign domain values to template
927 $template = CRM_Core_Smarty
::singleton();
930 $receiptFrom = CRM_Core_BAO_Domain
::getNameAndEmail(FALSE, TRUE);
931 $receiptFrom = reset($receiptFrom);
933 foreach ($pledgeDetails as $paymentId => $details) {
934 if (array_key_exists($details['contact_id'], $contactDetails)) {
935 $contactId = $details['contact_id'];
936 $pledgerName = $contactDetails[$contactId]['display_name'];
942 if (empty($details['reminder_date'])) {
943 $nextReminderDate = new DateTime($details['scheduled_date']);
944 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
945 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
946 $nextReminderDate = $nextReminderDate->format("Ymd");
949 $nextReminderDate = new DateTime($details['reminder_date']);
950 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
951 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
952 $nextReminderDate = $nextReminderDate->format("Ymd");
954 if (($details['reminder_count'] < $details['max_reminders'])
955 && ($nextReminderDate <= $now)
958 $toEmail = $doNotEmail = $onHold = NULL;
960 if (!empty($contactDetails[$contactId]['email'])) {
961 $toEmail = $contactDetails[$contactId]['email'];
964 if (!empty($contactDetails[$contactId]['do_not_email'])) {
965 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
968 if (!empty($contactDetails[$contactId]['on_hold'])) {
969 $onHold = $contactDetails[$contactId]['on_hold'];
972 // 2. send acknowledgement mail
973 if ($toEmail && !($doNotEmail ||
$onHold)) {
974 // assign value to template
975 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
976 $template->assign('next_payment', $details['scheduled_date']);
977 $template->assign('amount_due', $details['amount_due']);
978 $template->assign('checksumValue', $details['checksumValue']);
979 $template->assign('contribution_page_id', $details['contribution_page_id']);
980 $template->assign('pledge_id', $details['pledge_id']);
981 $template->assign('scheduled_payment_date', $details['scheduled_date']);
982 $template->assign('amount', $details['amount']);
983 $template->assign('create_date', $details['create_date']);
984 $template->assign('currency', $details['currency']);
990 ] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
992 'groupName' => 'msg_tpl_workflow_pledge',
993 'valueName' => 'pledge_reminder',
994 'contactId' => $contactId,
995 'from' => $receiptFrom,
996 'toName' => $pledgerName,
997 'toEmail' => $toEmail,
1001 // 3. update pledge payment details
1003 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1004 $activityType = 'Pledge Reminder';
1006 'subject' => $subject,
1007 'source_contact_id' => $contactId,
1008 'source_record_id' => $paymentId,
1009 'assignee_contact_id' => $contactId,
1010 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
1014 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1015 'is_test' => $details['is_test'],
1017 'campaign_id' => $details['campaign_id'],
1020 civicrm_api3('activity', 'create', $activityParams);
1022 catch (CiviCRM_API3_Exception
$e) {
1023 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1024 return ['is_error' => 1, 'message' => $returnMessages];
1026 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1031 // end foreach on $pledgeDetails
1033 // end if ( $sendReminders )
1034 $returnMessages[] = "{$updateCnt} records updated.";
1036 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1040 * Mark a pledge (and any outstanding payments) as cancelled.
1042 * @param int $pledgeID
1044 public static function cancel($pledgeID) {
1045 $paymentIDs = self
::findCancelablePayments($pledgeID);
1046 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1047 $cancelled = array_search('Cancelled', $status);
1048 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1049 $cancelled, 0, FALSE, TRUE
1054 * Find payments which can be safely canceled.
1056 * @param int $pledgeID
1059 * Array of int (civicrm_pledge_payment.id)
1061 public static function findCancelablePayments($pledgeID) {
1062 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'));
1064 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1065 $paymentDAO->pledge_id
= $pledgeID;
1066 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1067 $statuses['Overdue'],
1068 $statuses['Pending']
1070 $paymentDAO->find();
1073 while ($paymentDAO->fetch()) {
1074 $paymentIDs[] = $paymentDAO->id
;
1080 * Is this pledge free from financial transactions (this is important to know
1081 * as we allow editing when no transactions have taken place - the editing
1082 * process currently involves deleting all pledge payments & contributions
1083 * & recreating so we want to block that if appropriate).
1085 * @param int $pledgeID
1086 * @param int $pledgeStatusID
1089 * do financial transactions exist for this pledge?
1091 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1092 if (empty($pledgeStatusID)) {
1093 // why would this happen? If we can see where it does then we can see if we should look it up.
1094 // but assuming from form code it CAN be empty.
1097 if (self
::isTransactedStatus($pledgeStatusID)) {
1101 return civicrm_api3('pledge_payment', 'getcount', [
1102 'pledge_id' => $pledgeID,
1103 'contribution_id' => ['IS NOT NULL' => TRUE],
1108 * Does this pledge / pledge payment status mean that a financial transaction
1111 * @param int $statusID
1115 * is it a transactional status?
1117 protected static function isTransactedStatus($statusID) {
1118 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1125 * Get array of non transactional statuses.
1128 * non transactional status ids
1130 protected static function getNonTransactionalStatus() {
1131 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1132 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1136 * Create array for recur record for pledge.
1139 * params for recur record
1141 public static function buildRecurParams($params) {
1144 'auto_renew' => TRUE,
1145 'frequency_unit' => $params['pledge_frequency_unit'],
1146 'frequency_interval' => $params['pledge_frequency_interval'],
1147 'installments' => $params['pledge_installments'],
1148 'start_date' => $params['receive_date'],
1150 return $recurParams;
1154 * Get pledge start date.
1159 public static function getPledgeStartDate($date, $pledgeBlock) {
1160 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1161 foreach ($startDate as $field => $value) {
1162 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1169 case 'contribution_date':
1171 $date = date('Ymd');
1175 case 'calendar_date':
1176 $date = date('Ymd', strtotime($date));
1179 case 'calendar_month':
1180 $date = self
::getPaymentDate($date);
1181 $date = date('Ymd', strtotime($date));
1193 * Get first payment date for pledge.
1197 * @return bool|string
1199 public static function getPaymentDate($day) {
1201 // Find out if current month has 31 days, if not, set it to 30 (last day).
1207 $current = date('d');
1209 case ($day == $current):
1210 $date = date('m/d/Y');
1213 case ($day > $current):
1214 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1217 case ($day < $current):
1218 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1229 * Override buildOptions to hack out some statuses.
1231 * @param string $fieldName
1232 * @param string $context
1233 * @param array $props
1235 * @return array|bool
1236 * @todo instead of using & hacking the shared optionGroup
1237 * contribution_status use a separate one.
1240 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1241 $result = parent
::buildOptions($fieldName, $context, $props);
1242 if ($fieldName == 'status_id') {
1243 $result = array_diff($result, ['Failed']);