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;
27 * Retrieve DB object based on input parameters.
29 * It also stores all the retrieved values in the default array.
31 * @param array $params
32 * (reference ) an assoc array of name/value pairs.
33 * @param array $defaults
34 * (reference ) an assoc array to hold the flattened values.
36 * @return CRM_Pledge_BAO_Pledge
38 public static function retrieve(&$params, &$defaults) {
39 $pledge = new CRM_Pledge_DAO_Pledge();
40 $pledge->copyValues($params);
41 if ($pledge->find(TRUE)) {
42 CRM_Core_DAO
::storeValues($pledge, $defaults);
51 * @param array $params
52 * Reference array contains the values submitted by the form.
54 * @return CRM_Pledge_DAO_Pledge
56 public static function add(array $params): CRM_Pledge_DAO_Pledge
{
57 CRM_Core_Error
::deprecatedFunctionWarning('v4 api');
58 $hook = empty($params['id']) ?
'create' : 'edit';
59 CRM_Utils_Hook
::pre($hook, 'Pledge', $params['id'] ??
NULL, $params);
61 $pledge = new CRM_Pledge_DAO_Pledge();
63 // if pledge is complete update end date as current date
64 if ($pledge->status_id
== 1) {
65 $pledge->end_date
= date('Ymd');
68 $pledge->copyValues($params);
70 // set currency for CRM-1496
71 if (!isset($pledge->currency
)) {
72 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
75 $result = $pledge->save();
77 CRM_Utils_Hook
::post($hook, 'Pledge', $pledge->id
, $pledge);
83 * Given the list of params in the params array, fetch the object
84 * and store the values in the values array
86 * @param array $params
87 * Input parameters to find object.
88 * @param array $values
89 * Output values of the object.
90 * @param array $returnProperties
91 * If you want to return specific fields.
94 * associated array of field values
96 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
100 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
105 * Takes an associative array and creates a pledge object.
107 * @param array $params
108 * Assoc array of name/value pairs.
110 * @return CRM_Pledge_DAO_Pledge
111 * @throws \CRM_Core_Exception
113 public static function create(array $params): CRM_Pledge_DAO_Pledge
{
114 $action = empty($params['id']) ?
'create' : 'edit';
115 if ($action === 'create') {
117 'currency' => CRM_Core_Config
::singleton()->defaultCurrency
,
118 'installments' => (int) self
::fields()['installments']['default'],
119 'scheduled_date' => $params['start_date'] ??
date('Ymd'),
121 $params = array_merge($defaults, $params);
124 $isRecalculatePledgePayment = self
::isPaymentsRequireRecalculation($params);
125 $transaction = new CRM_Core_Transaction();
128 if (!empty($params['installment_amount'])) {
129 $params['amount'] = $params['installment_amount'] * $params['installments'];
132 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
133 if (isset($params['contribution_id'])) {
134 if ($params['installments'] > 1) {
135 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
139 if (!empty($params['id'])) {
140 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
143 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
147 $paymentParams['status_id'] = $params['status_id'] ??
NULL;
149 $pledge = self
::writeRecord($params);
151 // skip payment stuff in edit mode
152 if (empty($params['id']) ||
$isRecalculatePledgePayment) {
154 // if pledge is pending delete all payments and recreate.
155 if ($isRecalculatePledgePayment) {
156 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
159 // building payment params
160 $paymentParams['pledge_id'] = $pledge->id
;
168 'frequency_interval',
170 'installment_amount',
173 foreach ($paymentKeys as $key) {
174 $paymentParams[$key] = $params[$key] ??
NULL;
176 CRM_Pledge_BAO_PledgePayment
::createMultiple($paymentParams);
179 $transaction->commit();
181 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
182 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
186 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
187 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
188 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
191 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
192 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
193 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
197 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
198 $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) . ')';
200 // add the recently created Pledge
201 CRM_Utils_Recent
::add($title,
214 * Is this a change to an existing pending pledge requiring payment schedule
217 * If the pledge is pending the code (slightly lazily) deletes & recreates
220 * If the payment dates or amounts have been manually edited then this can
221 * cause data loss. We can mitigate this to some extent by making sure we
222 * have a change that could potentially affect the schedule (rather than just
223 * a custom data change or similar).
225 * This calculation needs to be performed before update takes place as
226 * previous & new pledges are compared.
228 * @param array $params
232 protected static function isPaymentsRequireRecalculation($params) {
233 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
236 $scheduleChangingParameters = [
239 'frequency_interval',
244 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
245 $existingPledgeDAO->id
= $params['id'];
246 $existingPledgeDAO->find(TRUE);
247 foreach ($scheduleChangingParameters as $parameter) {
248 if ($parameter == 'start_date') {
249 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
253 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
267 public static function deletePledge($id) {
268 CRM_Utils_Hook
::pre('delete', 'Pledge', $id);
270 $transaction = new CRM_Core_Transaction();
272 // check for no Completed Payment records with the pledge
273 $payment = new CRM_Pledge_DAO_PledgePayment();
274 $payment->pledge_id
= $id;
277 while ($payment->fetch()) {
278 // also delete associated contribution.
279 if ($payment->contribution_id
) {
280 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
285 $dao = new CRM_Pledge_DAO_Pledge();
287 $results = $dao->delete();
289 $transaction->commit();
291 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
297 * Get the amount details date wise.
299 * @param string $status
300 * @param string $startDate
301 * @param string $endDate
305 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
307 $select = $from = $queryDate = NULL;
308 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
312 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
319 $where[] = 'status_id = ' . $statusId;
324 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
327 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
330 $whereCond = implode(' AND ', $where);
333 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
335 WHERE $whereCond AND is_test=0
338 $start = substr($startDate, 0, 8);
339 $end = substr($endDate, 0, 8);
342 $dao = CRM_Core_DAO
::executeQuery($query);
343 while ($dao->fetch()) {
344 $pCount +
= $dao->pledge_count
;
345 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
349 'pledge_amount' => implode(', ', $pamount),
350 'pledge_count' => $pCount,
351 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
352 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
359 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
360 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
361 $queryDate = 'receive_date';
362 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
366 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
367 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
368 $queryDate = 'receive_date';
369 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
373 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
374 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
375 $queryDate = 'scheduled_date';
376 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
380 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
381 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
382 $queryDate = 'scheduled_date';
383 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
388 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
391 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
394 $whereCond = implode(' AND ', $where);
397 SELECT $select, cp.currency
403 $dao = CRM_Core_DAO
::executeQuery($query);
407 while ($dao->fetch()) {
408 $count +
= $dao->received_count
;
409 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
413 return array_merge($pledge_amount, [
414 'received_amount' => implode(', ', $amount),
415 'received_count' => $count,
416 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
417 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
423 return $pledge_amount;
429 * Get list of pledges In Honor of contact Ids.
431 * @param int $honorId
432 * In Honor of Contact ID.
435 * return the list of pledge fields
437 public static function getHonorContacts($honorId) {
439 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
440 $honorDAO->contact_id
= $honorId;
444 while ($honorDAO->fetch()) {
445 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
446 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
447 if ($pledgePaymentDAO->find(TRUE)) {
448 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
449 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
450 if ($pledgeDAO->find(TRUE)) {
451 $params[$pledgeDAO->id
] = [
452 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
453 'honorId' => $pledgeDAO->contact_id
,
454 'amount' => $pledgeDAO->amount
,
455 'status' => CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id
),
456 'create_date' => $pledgeDAO->create_date
,
457 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
458 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
459 $pledgeDAO->financial_type_id
, 'name'
461 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
462 $pledgeDAO->contact_id
, 'display_name'
473 * Send Acknowledgment and create activity.
475 * @param CRM_Core_Form $form
477 * @param array $params
478 * An assoc array of name/value pairs.
480 public static function sendAcknowledgment(&$form, $params) {
481 //handle Acknowledgment.
482 $allPayments = $payments = [];
484 // get All Payments status types.
485 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
486 $returnProperties = [
492 // get all paymnets details.
493 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
495 if (!empty($allPayments)) {
496 foreach ($allPayments as $payID => $values) {
497 $contributionValue = $contributionStatus = [];
498 if (isset($values['contribution_id'])) {
499 $contributionParams = ['id' => $values['contribution_id']];
500 $returnProperties = ['contribution_status_id', 'receive_date'];
501 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
502 $contributionParams, $contributionStatus, $returnProperties
504 $contributionValue = [
505 'status' => $contributionStatus['contribution_status_id'] ??
NULL,
506 'receive_date' => $contributionStatus['receive_date'] ??
NULL,
509 $payments[$payID] = array_merge($contributionValue,
511 'amount' => $values['scheduled_amount'] ??
NULL,
512 'due_date' => $values['scheduled_date'] ??
NULL,
513 'status' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'),
517 // get the first valid payment id.
518 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
519 $paymentStatusTypes[$values['status_id']] == 'Overdue'
522 $form->paymentId
= $values['id'];
527 // assign pledge fields value to template.
530 'total_pledge_amount',
531 'frequency_interval',
538 foreach ($pledgeFields as $field) {
539 if (!empty($params[$field])) {
540 $form->assign($field, $params[$field]);
544 // assign all payments details.
546 $form->assign('payments', $payments);
549 // handle custom data.
551 if (!empty($params['hidden_custom'])) {
552 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', NULL, $params['id']);
553 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
554 // retrieve custom data
555 foreach ($groupTree as $groupID => $group) {
556 $customFields = $customValues = [];
557 if ($groupID == 'info') {
560 foreach ($group['fields'] as $k => $field) {
561 $field['title'] = $field['label'];
562 $customFields["custom_{$k}"] = $field;
565 // to build array of customgroup & customfields in it
566 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
567 $customGroup[$group['title']] = $customValues;
571 $form->assign('customGroup', $customGroup);
573 // handle acknowledgment email stuff.
574 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
576 // check for online pledge.
577 if (!empty($params['receipt_from_email'])) {
578 $userName = $params['receipt_from_name'] ??
NULL;
579 $userEmail = $params['receipt_from_email'] ??
NULL;
581 elseif (!empty($params['from_email_id'])) {
582 $receiptFrom = $params['from_email_id'];
584 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
585 // check for logged in user.
589 ] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
592 // set the domain values.
593 [$userName, $userEmail] = CRM_Core_BAO_Domain
::getNameAndEmail();
596 if (!isset($receiptFrom)) {
597 $receiptFrom = "$userName <$userEmail>";
600 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
602 'groupName' => 'msg_tpl_workflow_pledge',
603 'valueName' => 'pledge_acknowledge',
604 'contactId' => $params['contact_id'],
605 'from' => $receiptFrom,
606 'toName' => $pledgerDisplayName,
607 'toEmail' => $pledgerEmail,
611 // check if activity record exist for this pledge
612 // Acknowledgment, if exist do not add activity.
613 $activityType = 'Pledge Acknowledgment';
614 $activity = new CRM_Activity_DAO_Activity();
615 $activity->source_record_id
= $params['id'];
616 $activity->activity_type_id
= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
622 $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)';
624 if (!$activity->find()) {
626 'subject' => $subject,
627 'source_contact_id' => $params['contact_id'],
628 'source_record_id' => $params['id'],
629 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
633 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
634 'is_test' => $params['is_test'],
636 'details' => $details,
637 'campaign_id' => $params['campaign_id'] ??
NULL,
640 // lets insert assignee record.
641 if (!empty($params['contact_id'])) {
642 $activityParams['assignee_contact_id'] = $params['contact_id'];
645 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
646 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
652 * Combine all the exportable fields from the lower levels object.
654 * @param bool $checkPermission
657 * array of exportable Fields
659 public static function exportableFields($checkPermission = TRUE) {
660 if (!self
::$_exportableFields) {
661 if (!self
::$_exportableFields) {
662 self
::$_exportableFields = [];
665 $fields = CRM_Pledge_DAO_Pledge
::export();
667 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
669 // set title to calculated fields
670 $calculatedFields = [
671 'pledge_total_paid' => ['title' => ts('Total Paid')],
672 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
673 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
674 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
675 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
676 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
677 'pledge_payment_status' => [
678 'title' => ts('Pledge Payment Status'),
679 'name' => 'pledge_payment_status',
680 'data_type' => CRM_Utils_Type
::T_STRING
,
686 'title' => ts('Pledge Status'),
687 'name' => 'pledge_status',
688 'data_type' => CRM_Utils_Type
::T_STRING
,
690 'pledge_frequency_unit' => [
691 'title' => ts('Pledge Frequency Unit'),
692 'name' => 'pledge_frequency_unit',
693 'data_type' => CRM_Utils_Type
::T_ENUM
,
695 'pledge_frequency_interval' => [
696 'title' => ts('Pledge Frequency Interval'),
697 'name' => 'pledge_frequency_interval',
698 'data_type' => CRM_Utils_Type
::T_INT
,
700 'pledge_contribution_page_id' => [
701 'title' => ts('Pledge Contribution Page Id'),
702 'name' => 'pledge_contribution_page_id',
703 'data_type' => CRM_Utils_Type
::T_INT
,
707 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
710 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
711 self
::$_exportableFields = $fields;
714 return self
::$_exportableFields;
718 * Get pending or in progress pledges.
720 * @param int $contactID
724 * associated array of pledge id(s)
726 public static function getContactPledges($contactID) {
728 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
729 FALSE, FALSE, FALSE, NULL, 'name'
734 // get pending and in progress status
735 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
736 if ($statusId = array_search($name, $pledgeStatuses)) {
737 $status[] = $statusId;
740 if (empty($status)) {
741 return $pledgeDetails;
744 $statusClause = " IN (" . implode(',', $status) . ")";
747 SELECT civicrm_pledge.id id
749 WHERE civicrm_pledge.status_id {$statusClause}
750 AND civicrm_pledge.contact_id = %1
753 $params[1] = [$contactID, 'Integer'];
754 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
756 while ($pledge->fetch()) {
757 $pledgeDetails[] = $pledge->id
;
760 return $pledgeDetails;
764 * Get pledge record count for a Contact.
766 * @param int $contactID
769 * count of pledge records
771 public static function getContactPledgeCount($contactID) {
772 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
773 return CRM_Core_DAO
::singleValueQuery($query);
777 * @param array $params
780 * @throws \API_Exception
781 * @throws \CRM_Core_Exception
782 * @throws \CiviCRM_API3_Exception
784 public static function updatePledgeStatus($params): array {
786 $returnMessages = [];
788 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
790 $allStatus = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
791 $allPledgeStatus = CRM_Core_OptionGroup
::values('pledge_status',
792 TRUE, FALSE, FALSE, NULL, 'name', TRUE
794 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
795 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
797 $statusIds = implode(',', $allStatus);
798 $pledgeStatusIds = implode(',', $allPledgeStatus);
802 SELECT pledge.contact_id as contact_id,
803 pledge.id as pledge_id,
804 pledge.amount as amount,
805 payment.scheduled_date as scheduled_date,
806 pledge.create_date as create_date,
807 payment.id as payment_id,
808 pledge.currency as currency,
809 pledge.contribution_page_id as contribution_page_id,
810 payment.reminder_count as reminder_count,
811 pledge.max_reminders as max_reminders,
812 payment.reminder_date as reminder_date,
813 pledge.initial_reminder_day as initial_reminder_day,
814 pledge.additional_reminder_day as additional_reminder_day,
815 pledge.status_id as pledge_status,
816 payment.status_id as payment_status,
817 pledge.is_test as is_test,
818 pledge.campaign_id as campaign_id,
819 SUM(payment.scheduled_amount) as amount_due,
820 ( SELECT sum(civicrm_pledge_payment.actual_amount)
821 FROM civicrm_pledge_payment
822 WHERE civicrm_pledge_payment.status_id = 1
823 AND civicrm_pledge_payment.pledge_id = pledge.id
825 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
826 WHERE pledge.id = payment.pledge_id
827 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
831 $dao = CRM_Core_DAO
::executeQuery($query);
834 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
835 while ($dao->fetch()) {
836 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
838 $pledgeDetails[$dao->payment_id
] = [
839 'scheduled_date' => $dao->scheduled_date
,
840 'amount_due' => $dao->amount_due
,
841 'amount' => $dao->amount
,
842 'amount_paid' => $dao->amount_paid
,
843 'create_date' => $dao->create_date
,
844 'contact_id' => $dao->contact_id
,
845 'pledge_id' => $dao->pledge_id
,
846 'checksumValue' => $checksumValue,
847 'contribution_page_id' => $dao->contribution_page_id
,
848 'reminder_count' => $dao->reminder_count
,
849 'max_reminders' => $dao->max_reminders
,
850 'reminder_date' => $dao->reminder_date
,
851 'initial_reminder_day' => $dao->initial_reminder_day
,
852 'additional_reminder_day' => $dao->additional_reminder_day
,
853 'pledge_status' => $dao->pledge_status
,
854 'payment_status' => $dao->payment_status
,
855 'is_test' => $dao->is_test
,
856 'currency' => $dao->currency
,
857 'campaign_id' => $dao->campaign_id
,
860 $contactIds[$dao->contact_id
] = $dao->contact_id
;
861 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
863 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
865 ) && $dao->payment_status
!= $allStatus['Overdue']
867 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
870 $allPledgeStatus = array_flip($allPledgeStatus);
872 // process the updating script...
873 foreach ($pledgePayments as $pledgeId => $paymentIds) {
874 // 1. update the pledge /pledge payment status. returns new status when an update happens
875 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
877 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
878 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
880 if ($newStatus != $pledgeStatus[$pledgeId]) {
881 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
886 if ($sendReminders) {
887 // retrieve domain tokens
889 'domain' => ['name', 'phone', 'address', 'email'],
890 'contact' => CRM_Core_SelectValues
::contactTokens(),
893 // retrieve contact tokens
895 // this function does NOT return Deceased contacts since we don't want to send them email
896 $contactDetails = civicrm_api3('Contact', 'get', [
898 'id' => ['IN' => $contactIds],
899 'return' => ['id', 'display_name', 'email', 'do_not_email', 'email', 'on_hold'],
902 // assign domain values to template
903 $template = CRM_Core_Smarty
::singleton();
906 $receiptFrom = CRM_Core_BAO_Domain
::getNameAndEmail(FALSE, TRUE);
907 $receiptFrom = reset($receiptFrom);
909 foreach ($pledgeDetails as $paymentId => $details) {
910 if (array_key_exists($details['contact_id'], $contactDetails)) {
911 $contactId = $details['contact_id'];
912 $pledgerName = $contactDetails[$contactId]['display_name'];
918 if (empty($details['reminder_date'])) {
919 $nextReminderDate = new DateTime($details['scheduled_date']);
920 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
921 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
922 $nextReminderDate = $nextReminderDate->format("Ymd");
925 $nextReminderDate = new DateTime($details['reminder_date']);
926 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
927 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
928 $nextReminderDate = $nextReminderDate->format("Ymd");
930 if (($details['reminder_count'] < $details['max_reminders'])
931 && ($nextReminderDate <= $now)
934 $toEmail = $doNotEmail = $onHold = NULL;
936 if (!empty($contactDetails[$contactId]['email'])) {
937 $toEmail = $contactDetails[$contactId]['email'];
940 if (!empty($contactDetails[$contactId]['do_not_email'])) {
941 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
944 if (!empty($contactDetails[$contactId]['on_hold'])) {
945 $onHold = $contactDetails[$contactId]['on_hold'];
948 // 2. send acknowledgement mail
949 if ($toEmail && !($doNotEmail ||
$onHold)) {
950 // assign value to template
951 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
952 $template->assign('next_payment', $details['scheduled_date']);
953 $template->assign('amount_due', $details['amount_due']);
954 $template->assign('checksumValue', $details['checksumValue']);
955 $template->assign('contribution_page_id', $details['contribution_page_id']);
956 $template->assign('pledge_id', $details['pledge_id']);
957 $template->assign('scheduled_payment_date', $details['scheduled_date']);
958 $template->assign('amount', $details['amount']);
959 $template->assign('create_date', $details['create_date']);
960 $template->assign('currency', $details['currency']);
966 ] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
968 'groupName' => 'msg_tpl_workflow_pledge',
969 'valueName' => 'pledge_reminder',
970 'contactId' => $contactId,
971 'from' => $receiptFrom,
972 'toName' => $pledgerName,
973 'toEmail' => $toEmail,
977 // 3. update pledge payment details
979 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
980 $activityType = 'Pledge Reminder';
982 'subject' => $subject,
983 'source_contact_id' => $contactId,
984 'source_record_id' => $paymentId,
985 'assignee_contact_id' => $contactId,
986 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
990 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
991 'is_test' => $details['is_test'],
993 'campaign_id' => $details['campaign_id'],
996 civicrm_api3('activity', 'create', $activityParams);
998 catch (CiviCRM_API3_Exception
$e) {
999 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1000 return ['is_error' => 1, 'message' => $returnMessages];
1002 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1007 // end foreach on $pledgeDetails
1009 // end if ( $sendReminders )
1010 $returnMessages[] = "{$updateCnt} records updated.";
1012 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1016 * Mark a pledge (and any outstanding payments) as cancelled.
1018 * @param int $pledgeID
1020 public static function cancel($pledgeID) {
1021 $paymentIDs = self
::findCancelablePayments($pledgeID);
1022 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1023 $cancelled = array_search('Cancelled', $status);
1024 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1025 $cancelled, 0, FALSE, TRUE
1030 * Find payments which can be safely canceled.
1032 * @param int $pledgeID
1035 * Array of int (civicrm_pledge_payment.id)
1037 public static function findCancelablePayments($pledgeID) {
1038 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'));
1040 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1041 $paymentDAO->pledge_id
= $pledgeID;
1042 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1043 $statuses['Overdue'],
1044 $statuses['Pending']
1046 $paymentDAO->find();
1049 while ($paymentDAO->fetch()) {
1050 $paymentIDs[] = $paymentDAO->id
;
1056 * Is this pledge free from financial transactions (this is important to know
1057 * as we allow editing when no transactions have taken place - the editing
1058 * process currently involves deleting all pledge payments & contributions
1059 * & recreating so we want to block that if appropriate).
1061 * @param int $pledgeID
1062 * @param int $pledgeStatusID
1065 * do financial transactions exist for this pledge?
1067 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1068 if (empty($pledgeStatusID)) {
1069 // why would this happen? If we can see where it does then we can see if we should look it up.
1070 // but assuming from form code it CAN be empty.
1073 if (self
::isTransactedStatus($pledgeStatusID)) {
1077 return civicrm_api3('pledge_payment', 'getcount', [
1078 'pledge_id' => $pledgeID,
1079 'contribution_id' => ['IS NOT NULL' => TRUE],
1084 * Does this pledge / pledge payment status mean that a financial transaction
1087 * @param int $statusID
1091 * is it a transactional status?
1093 protected static function isTransactedStatus($statusID) {
1094 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1101 * Get array of non transactional statuses.
1104 * non transactional status ids
1106 protected static function getNonTransactionalStatus() {
1107 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1108 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1112 * Create array for recur record for pledge.
1115 * params for recur record
1117 public static function buildRecurParams($params) {
1120 'auto_renew' => TRUE,
1121 'frequency_unit' => $params['pledge_frequency_unit'],
1122 'frequency_interval' => $params['pledge_frequency_interval'],
1123 'installments' => $params['pledge_installments'],
1124 'start_date' => $params['receive_date'],
1126 return $recurParams;
1130 * Get pledge start date.
1135 public static function getPledgeStartDate($date, $pledgeBlock) {
1136 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1137 foreach ($startDate as $field => $value) {
1138 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1145 case 'contribution_date':
1147 $date = date('Ymd');
1151 case 'calendar_date':
1152 $date = date('Ymd', strtotime($date));
1155 case 'calendar_month':
1156 $date = self
::getPaymentDate($date);
1157 $date = date('Ymd', strtotime($date));
1169 * Get first payment date for pledge.
1173 * @return bool|string
1175 public static function getPaymentDate($day) {
1177 // Find out if current month has 31 days, if not, set it to 30 (last day).
1183 $current = date('d');
1185 case ($day == $current):
1186 $date = date('m/d/Y');
1189 case ($day > $current):
1190 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1193 case ($day < $current):
1194 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1205 * Override buildOptions to hack out some statuses.
1207 * @param string $fieldName
1208 * @param string $context
1209 * @param array $props
1211 * @return array|bool
1212 * @todo instead of using & hacking the shared optionGroup
1213 * contribution_status use a separate one.
1216 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1217 $result = parent
::buildOptions($fieldName, $context, $props);
1218 if ($fieldName == 'status_id') {
1219 $result = array_diff($result, ['Failed']);