Merge pull request #23897 from agh1/5.51.0-releasenotes-initial
[civicrm-core.git] / CRM / Pledge / BAO / Pledge.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Pledge_BAO_Pledge extends CRM_Pledge_DAO_Pledge {
18
19 /**
20 * Static field for all the pledge information that we can potentially export.
21 *
22 * @var array
23 */
24 public static $_exportableFields = NULL;
25
26 /**
27 * Retrieve DB object and copy to defaults array.
28 *
29 * @param array $params
30 * Array of criteria values.
31 * @param array $defaults
32 * Array to be populated with found values.
33 *
34 * @return self|null
35 * The DAO object, if found.
36 *
37 * @deprecated
38 */
39 public static function retrieve($params, &$defaults) {
40 return self::commonRetrieve(self::class, $params, $defaults);
41 }
42
43 /**
44 * Add pledge.
45 *
46 * @param array $params
47 * Reference array contains the values submitted by the form.
48 *
49 * @return CRM_Pledge_DAO_Pledge
50 */
51 public static function add(array $params): CRM_Pledge_DAO_Pledge {
52 CRM_Core_Error::deprecatedFunctionWarning('v4 api');
53 $hook = empty($params['id']) ? 'create' : 'edit';
54 CRM_Utils_Hook::pre($hook, 'Pledge', $params['id'] ?? NULL, $params);
55
56 $pledge = new CRM_Pledge_DAO_Pledge();
57
58 // if pledge is complete update end date as current date
59 if ($pledge->status_id == 1) {
60 $pledge->end_date = date('Ymd');
61 }
62
63 $pledge->copyValues($params);
64
65 // set currency for CRM-1496
66 if (!isset($pledge->currency)) {
67 $pledge->currency = CRM_Core_Config::singleton()->defaultCurrency;
68 }
69
70 $result = $pledge->save();
71
72 CRM_Utils_Hook::post($hook, 'Pledge', $pledge->id, $pledge);
73
74 return $result;
75 }
76
77 /**
78 * Given the list of params in the params array, fetch the object
79 * and store the values in the values array
80 *
81 * @param array $params
82 * Input parameters to find object.
83 * @param array $values
84 * Output values of the object.
85 * @param array $returnProperties
86 * If you want to return specific fields.
87 *
88 * @return array
89 * associated array of field values
90 */
91 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
92 if (empty($params)) {
93 return NULL;
94 }
95 CRM_Core_DAO::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
96 return $values;
97 }
98
99 /**
100 * Takes an associative array and creates a pledge object.
101 *
102 * @param array $params
103 * Assoc array of name/value pairs.
104 *
105 * @return CRM_Pledge_DAO_Pledge
106 * @throws \CRM_Core_Exception
107 */
108 public static function create(array $params): CRM_Pledge_DAO_Pledge {
109 $action = empty($params['id']) ? 'create' : 'edit';
110 if ($action === 'create') {
111 $defaults = [
112 'currency' => CRM_Core_Config::singleton()->defaultCurrency,
113 'installments' => (int) self::fields()['installments']['default'],
114 'scheduled_date' => $params['start_date'] ?? date('Ymd'),
115 ];
116 $params = array_merge($defaults, $params);
117 }
118
119 $isRecalculatePledgePayment = self::isPaymentsRequireRecalculation($params);
120 $transaction = new CRM_Core_Transaction();
121
122 $paymentParams = [];
123 if (!empty($params['installment_amount'])) {
124 $params['amount'] = $params['installment_amount'] * $params['installments'];
125 }
126
127 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
128 if (isset($params['contribution_id'])) {
129 if ($params['installments'] > 1) {
130 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
131 }
132 }
133 else {
134 if (!empty($params['id'])) {
135 $params['status_id'] = CRM_Pledge_BAO_PledgePayment::calculatePledgeStatus($params['id']);
136 }
137 else {
138 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
139 }
140 }
141 }
142 $paymentParams['status_id'] = $params['status_id'] ?? NULL;
143
144 $pledge = self::writeRecord($params);
145
146 // skip payment stuff in edit mode
147 if (empty($params['id']) || $isRecalculatePledgePayment) {
148
149 // if pledge is pending delete all payments and recreate.
150 if ($isRecalculatePledgePayment) {
151 CRM_Pledge_BAO_PledgePayment::deletePayments($pledge->id);
152 }
153
154 // building payment params
155 $paymentParams['pledge_id'] = $pledge->id;
156 $paymentKeys = [
157 'amount',
158 'installments',
159 'scheduled_date',
160 'frequency_unit',
161 'currency',
162 'frequency_day',
163 'frequency_interval',
164 'contribution_id',
165 'installment_amount',
166 'actual_amount',
167 ];
168 foreach ($paymentKeys as $key) {
169 $paymentParams[$key] = $params[$key] ?? NULL;
170 }
171 CRM_Pledge_BAO_PledgePayment::createMultiple($paymentParams);
172 }
173
174 $transaction->commit();
175
176 $url = CRM_Utils_System::url('civicrm/contact/view/pledge',
177 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
178 );
179
180 $recentOther = [];
181 if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
182 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
183 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
184 );
185 }
186 if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
187 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
188 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
189 );
190 }
191
192 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
193 $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) . ')';
194
195 // add the recently created Pledge
196 CRM_Utils_Recent::add($title,
197 $url,
198 $pledge->id,
199 'Pledge',
200 $pledge->contact_id,
201 NULL,
202 $recentOther
203 );
204
205 return $pledge;
206 }
207
208 /**
209 * Is this a change to an existing pending pledge requiring payment schedule
210 * changes.
211 *
212 * If the pledge is pending the code (slightly lazily) deletes & recreates
213 * pledge payments.
214 *
215 * If the payment dates or amounts have been manually edited then this can
216 * cause data loss. We can mitigate this to some extent by making sure we
217 * have a change that could potentially affect the schedule (rather than just
218 * a custom data change or similar).
219 *
220 * This calculation needs to be performed before update takes place as
221 * previous & new pledges are compared.
222 *
223 * @param array $params
224 *
225 * @return bool
226 */
227 protected static function isPaymentsRequireRecalculation($params) {
228 if (empty($params['is_pledge_pending']) || empty($params['id'])) {
229 return FALSE;
230 }
231 $scheduleChangingParameters = [
232 'amount',
233 'frequency_unit',
234 'frequency_interval',
235 'frequency_day',
236 'installments',
237 'start_date',
238 ];
239 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
240 $existingPledgeDAO->id = $params['id'];
241 $existingPledgeDAO->find(TRUE);
242 foreach ($scheduleChangingParameters as $parameter) {
243 if ($parameter == 'start_date') {
244 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
245 return TRUE;
246 }
247 }
248 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
249 return TRUE;
250 }
251 }
252 }
253
254 /**
255 * Delete the pledge.
256 *
257 * @param int $id
258 * Pledge id.
259 *
260 * @return mixed
261 */
262 public static function deletePledge($id) {
263 CRM_Utils_Hook::pre('delete', 'Pledge', $id);
264
265 $transaction = new CRM_Core_Transaction();
266
267 // check for no Completed Payment records with the pledge
268 $payment = new CRM_Pledge_DAO_PledgePayment();
269 $payment->pledge_id = $id;
270 $payment->find();
271
272 while ($payment->fetch()) {
273 // also delete associated contribution.
274 if ($payment->contribution_id) {
275 CRM_Contribute_BAO_Contribution::deleteContribution($payment->contribution_id);
276 }
277 $payment->delete();
278 }
279
280 $dao = new CRM_Pledge_DAO_Pledge();
281 $dao->id = $id;
282 $results = $dao->delete();
283
284 $transaction->commit();
285
286 CRM_Utils_Hook::post('delete', 'Pledge', $dao->id, $dao);
287
288 return $results;
289 }
290
291 /**
292 * Get the amount details date wise.
293 *
294 * @param string $status
295 * @param string $startDate
296 * @param string $endDate
297 *
298 * @return array|null
299 */
300 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
301 $where = [];
302 $select = $from = $queryDate = NULL;
303 $statusId = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
304
305 switch ($status) {
306 case 'Completed':
307 $where[] = 'status_id != ' . CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
308 break;
309
310 case 'Cancelled':
311 case 'In Progress':
312 case 'Pending':
313 case 'Overdue':
314 $where[] = 'status_id = ' . $statusId;
315 break;
316 }
317
318 if ($startDate) {
319 $where[] = "create_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
320 }
321 if ($endDate) {
322 $where[] = "create_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
323 }
324
325 $whereCond = implode(' AND ', $where);
326
327 $query = "
328 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
329 FROM civicrm_pledge
330 WHERE $whereCond AND is_test=0
331 GROUP BY currency
332 ";
333 $start = substr($startDate, 0, 8);
334 $end = substr($endDate, 0, 8);
335 $pCount = 0;
336 $pamount = [];
337 $dao = CRM_Core_DAO::executeQuery($query);
338 while ($dao->fetch()) {
339 $pCount += $dao->pledge_count;
340 $pamount[] = CRM_Utils_Money::format($dao->pledge_amount, $dao->currency);
341 }
342
343 $pledge_amount = [
344 'pledge_amount' => implode(', ', $pamount),
345 'pledge_count' => $pCount,
346 'purl' => CRM_Utils_System::url('civicrm/pledge/search',
347 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
348 ),
349 ];
350
351 $where = [];
352 switch ($status) {
353 case 'Completed':
354 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
355 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
356 $queryDate = 'receive_date';
357 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
358 break;
359
360 case 'Cancelled':
361 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
362 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
363 $queryDate = 'receive_date';
364 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
365 break;
366
367 case 'Pending':
368 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
369 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
370 $queryDate = 'scheduled_date';
371 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
372 break;
373
374 case 'Overdue':
375 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
376 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
377 $queryDate = 'scheduled_date';
378 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
379 break;
380 }
381
382 if ($startDate) {
383 $where[] = " $queryDate >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
384 }
385 if ($endDate) {
386 $where[] = " $queryDate <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
387 }
388
389 $whereCond = implode(' AND ', $where);
390
391 $query = "
392 SELECT $select, cp.currency
393 FROM $from
394 WHERE $whereCond
395 GROUP BY cp.currency
396 ";
397 if ($select) {
398 $dao = CRM_Core_DAO::executeQuery($query);
399 $amount = [];
400 $count = 0;
401
402 while ($dao->fetch()) {
403 $count += $dao->received_count;
404 $amount[] = CRM_Utils_Money::format($dao->received_pledge, $dao->currency);
405 }
406
407 if ($count) {
408 return array_merge($pledge_amount, [
409 'received_amount' => implode(', ', $amount),
410 'received_count' => $count,
411 'url' => CRM_Utils_System::url('civicrm/pledge/search',
412 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
413 ),
414 ]);
415 }
416 }
417 else {
418 return $pledge_amount;
419 }
420 return NULL;
421 }
422
423 /**
424 * Get list of pledges In Honor of contact Ids.
425 *
426 * @param int $honorId
427 * In Honor of Contact ID.
428 *
429 * @return array
430 * return the list of pledge fields
431 */
432 public static function getHonorContacts($honorId) {
433 $params = [];
434 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
435 $honorDAO->contact_id = $honorId;
436 $honorDAO->find();
437
438 // get all status.
439 while ($honorDAO->fetch()) {
440 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
441 $pledgePaymentDAO->contribution_id = $honorDAO->contribution_id;
442 if ($pledgePaymentDAO->find(TRUE)) {
443 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
444 $pledgeDAO->id = $pledgePaymentDAO->pledge_id;
445 if ($pledgeDAO->find(TRUE)) {
446 $params[$pledgeDAO->id] = [
447 'honor_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id),
448 'honorId' => $pledgeDAO->contact_id,
449 'amount' => $pledgeDAO->amount,
450 'status' => CRM_Core_PseudoConstant::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id),
451 'create_date' => $pledgeDAO->create_date,
452 'acknowledge_date' => $pledgeDAO->acknowledge_date,
453 'type' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
454 $pledgeDAO->financial_type_id, 'name'
455 ),
456 'display_name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
457 $pledgeDAO->contact_id, 'display_name'
458 ),
459 ];
460 }
461 }
462 }
463
464 return $params;
465 }
466
467 /**
468 * Send Acknowledgment and create activity.
469 *
470 * @param CRM_Core_Form $form
471 * Form object.
472 * @param array $params
473 * An assoc array of name/value pairs.
474 */
475 public static function sendAcknowledgment(&$form, $params) {
476 //handle Acknowledgment.
477 $allPayments = $payments = [];
478
479 // get All Payments status types.
480 $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
481 $returnProperties = [
482 'status_id',
483 'scheduled_amount',
484 'scheduled_date',
485 'contribution_id',
486 ];
487 // get all paymnets details.
488 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
489
490 if (!empty($allPayments)) {
491 foreach ($allPayments as $payID => $values) {
492 $contributionValue = $contributionStatus = [];
493 if (isset($values['contribution_id'])) {
494 $contributionParams = ['id' => $values['contribution_id']];
495 $returnProperties = ['contribution_status_id', 'receive_date'];
496 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_Contribution',
497 $contributionParams, $contributionStatus, $returnProperties
498 );
499 $contributionValue = [
500 'status' => $contributionStatus['contribution_status_id'] ?? NULL,
501 'receive_date' => $contributionStatus['receive_date'] ?? NULL,
502 ];
503 }
504 $payments[$payID] = array_merge($contributionValue,
505 [
506 'amount' => $values['scheduled_amount'] ?? NULL,
507 'due_date' => $values['scheduled_date'] ?? NULL,
508 'status' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'),
509 ]
510 );
511
512 // get the first valid payment id.
513 if (!isset($form->paymentId) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
514 $paymentStatusTypes[$values['status_id']] == 'Overdue'
515 )
516 ) {
517 $form->paymentId = $values['id'];
518 }
519 }
520 }
521
522 // assign pledge fields value to template.
523 $pledgeFields = [
524 'create_date',
525 'total_pledge_amount',
526 'frequency_interval',
527 'frequency_unit',
528 'installments',
529 'frequency_day',
530 'scheduled_amount',
531 'currency',
532 ];
533 foreach ($pledgeFields as $field) {
534 if (!empty($params[$field])) {
535 $form->assign($field, $params[$field]);
536 }
537 }
538
539 // assign all payments details.
540 if ($payments) {
541 $form->assign('payments', $payments);
542 }
543
544 // handle custom data.
545 $customGroup = [];
546 if (!empty($params['hidden_custom'])) {
547 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', NULL, $params['id']);
548 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
549 // retrieve custom data
550 foreach ($groupTree as $groupID => $group) {
551 $customFields = $customValues = [];
552 if ($groupID == 'info') {
553 continue;
554 }
555 foreach ($group['fields'] as $k => $field) {
556 $field['title'] = $field['label'];
557 $customFields["custom_{$k}"] = $field;
558 }
559
560 // to build array of customgroup & customfields in it
561 CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
562 $customGroup[$group['title']] = $customValues;
563 }
564
565 }
566 $form->assign('customGroup', $customGroup);
567
568 // handle acknowledgment email stuff.
569 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
570
571 // check for online pledge.
572 if (!empty($params['receipt_from_email'])) {
573 $userName = $params['receipt_from_name'] ?? NULL;
574 $userEmail = $params['receipt_from_email'] ?? NULL;
575 }
576 elseif (!empty($params['from_email_id'])) {
577 $receiptFrom = $params['from_email_id'];
578 }
579 elseif ($userID = CRM_Core_Session::singleton()->get('userID')) {
580 // check for logged in user.
581 [
582 $userName,
583 $userEmail,
584 ] = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
585 }
586 else {
587 // set the domain values.
588 [$userName, $userEmail] = CRM_Core_BAO_Domain::getNameAndEmail();
589 }
590
591 if (!isset($receiptFrom)) {
592 $receiptFrom = "$userName <$userEmail>";
593 }
594
595 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate::sendTemplate(
596 [
597 'groupName' => 'msg_tpl_workflow_pledge',
598 'valueName' => 'pledge_acknowledge',
599 'contactId' => $params['contact_id'],
600 'from' => $receiptFrom,
601 'toName' => $pledgerDisplayName,
602 'toEmail' => $pledgerEmail,
603 ]
604 );
605
606 // check if activity record exist for this pledge
607 // Acknowledgment, if exist do not add activity.
608 $activityType = 'Pledge Acknowledgment';
609 $activity = new CRM_Activity_DAO_Activity();
610 $activity->source_record_id = $params['id'];
611 $activity->activity_type_id = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
612 'activity_type_id',
613 $activityType
614 );
615
616 // FIXME: Translate
617 $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)';
618
619 if (!$activity->find()) {
620 $activityParams = [
621 'subject' => $subject,
622 'source_contact_id' => $params['contact_id'],
623 'source_record_id' => $params['id'],
624 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
625 'activity_type_id',
626 $activityType
627 ),
628 'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']),
629 'is_test' => $params['is_test'],
630 'status_id' => 2,
631 'details' => $details,
632 'campaign_id' => $params['campaign_id'] ?? NULL,
633 ];
634
635 // lets insert assignee record.
636 if (!empty($params['contact_id'])) {
637 $activityParams['assignee_contact_id'] = $params['contact_id'];
638 }
639
640 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
641 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
642 }
643 }
644 }
645
646 /**
647 * Combine all the exportable fields from the lower levels object.
648 *
649 * @param bool $checkPermission
650 *
651 * @return array
652 * array of exportable Fields
653 */
654 public static function exportableFields($checkPermission = TRUE) {
655 if (!self::$_exportableFields) {
656 if (!self::$_exportableFields) {
657 self::$_exportableFields = [];
658 }
659
660 $fields = CRM_Pledge_DAO_Pledge::export();
661
662 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment::export());
663
664 // set title to calculated fields
665 $calculatedFields = [
666 'pledge_total_paid' => ['title' => ts('Total Paid')],
667 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
668 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
669 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
670 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
671 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
672 'pledge_payment_status' => [
673 'title' => ts('Pledge Payment Status'),
674 'name' => 'pledge_payment_status',
675 'data_type' => CRM_Utils_Type::T_STRING,
676 ],
677 ];
678
679 $pledgeFields = [
680 'pledge_status' => [
681 'title' => ts('Pledge Status'),
682 'name' => 'pledge_status',
683 'data_type' => CRM_Utils_Type::T_STRING,
684 ],
685 'pledge_frequency_unit' => [
686 'title' => ts('Pledge Frequency Unit'),
687 'name' => 'pledge_frequency_unit',
688 'data_type' => CRM_Utils_Type::T_ENUM,
689 ],
690 'pledge_frequency_interval' => [
691 'title' => ts('Pledge Frequency Interval'),
692 'name' => 'pledge_frequency_interval',
693 'data_type' => CRM_Utils_Type::T_INT,
694 ],
695 'pledge_contribution_page_id' => [
696 'title' => ts('Pledge Contribution Page Id'),
697 'name' => 'pledge_contribution_page_id',
698 'data_type' => CRM_Utils_Type::T_INT,
699 ],
700 ];
701
702 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
703
704 // add custom data
705 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
706 self::$_exportableFields = $fields;
707 }
708
709 return self::$_exportableFields;
710 }
711
712 /**
713 * Get pending or in progress pledges.
714 *
715 * @param int $contactID
716 * Contact id.
717 *
718 * @return array
719 * associated array of pledge id(s)
720 */
721 public static function getContactPledges($contactID) {
722 $pledgeDetails = [];
723 $pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status',
724 FALSE, FALSE, FALSE, NULL, 'name'
725 );
726
727 $status = [];
728
729 // get pending and in progress status
730 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
731 if ($statusId = array_search($name, $pledgeStatuses)) {
732 $status[] = $statusId;
733 }
734 }
735 if (empty($status)) {
736 return $pledgeDetails;
737 }
738
739 $statusClause = " IN (" . implode(',', $status) . ")";
740
741 $query = "
742 SELECT civicrm_pledge.id id
743 FROM civicrm_pledge
744 WHERE civicrm_pledge.status_id {$statusClause}
745 AND civicrm_pledge.contact_id = %1
746 ";
747
748 $params[1] = [$contactID, 'Integer'];
749 $pledge = CRM_Core_DAO::executeQuery($query, $params);
750
751 while ($pledge->fetch()) {
752 $pledgeDetails[] = $pledge->id;
753 }
754
755 return $pledgeDetails;
756 }
757
758 /**
759 * Get pledge record count for a Contact.
760 *
761 * @param int $contactID
762 *
763 * @return int
764 * count of pledge records
765 */
766 public static function getContactPledgeCount($contactID) {
767 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
768 return CRM_Core_DAO::singleValueQuery($query);
769 }
770
771 /**
772 * @param array $params
773 *
774 * @return array
775 * @throws \API_Exception
776 * @throws \CRM_Core_Exception
777 * @throws \CiviCRM_API3_Exception
778 */
779 public static function updatePledgeStatus($params): array {
780
781 $returnMessages = [];
782
783 $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE);
784
785 $allStatus = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
786 $allPledgeStatus = CRM_Core_OptionGroup::values('pledge_status',
787 TRUE, FALSE, FALSE, NULL, 'name', TRUE
788 );
789 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
790 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
791
792 $statusIds = implode(',', $allStatus);
793 $pledgeStatusIds = implode(',', $allPledgeStatus);
794 $updateCnt = 0;
795
796 $query = "
797 SELECT pledge.contact_id as contact_id,
798 pledge.id as pledge_id,
799 pledge.amount as amount,
800 payment.scheduled_date as scheduled_date,
801 pledge.create_date as create_date,
802 payment.id as payment_id,
803 pledge.currency as currency,
804 pledge.contribution_page_id as contribution_page_id,
805 payment.reminder_count as reminder_count,
806 pledge.max_reminders as max_reminders,
807 payment.reminder_date as reminder_date,
808 pledge.initial_reminder_day as initial_reminder_day,
809 pledge.additional_reminder_day as additional_reminder_day,
810 pledge.status_id as pledge_status,
811 payment.status_id as payment_status,
812 pledge.is_test as is_test,
813 pledge.campaign_id as campaign_id,
814 SUM(payment.scheduled_amount) as amount_due,
815 ( SELECT sum(civicrm_pledge_payment.actual_amount)
816 FROM civicrm_pledge_payment
817 WHERE civicrm_pledge_payment.status_id = 1
818 AND civicrm_pledge_payment.pledge_id = pledge.id
819 ) as amount_paid
820 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
821 WHERE pledge.id = payment.pledge_id
822 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
823 GROUP By payment.id
824 ";
825
826 $dao = CRM_Core_DAO::executeQuery($query);
827
828 $now = date('Ymd');
829 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
830 while ($dao->fetch()) {
831 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
832
833 $pledgeDetails[$dao->payment_id] = [
834 'scheduled_date' => $dao->scheduled_date,
835 'amount_due' => $dao->amount_due,
836 'amount' => $dao->amount,
837 'amount_paid' => $dao->amount_paid,
838 'create_date' => $dao->create_date,
839 'contact_id' => $dao->contact_id,
840 'pledge_id' => $dao->pledge_id,
841 'checksumValue' => $checksumValue,
842 'contribution_page_id' => $dao->contribution_page_id,
843 'reminder_count' => $dao->reminder_count,
844 'max_reminders' => $dao->max_reminders,
845 'reminder_date' => $dao->reminder_date,
846 'initial_reminder_day' => $dao->initial_reminder_day,
847 'additional_reminder_day' => $dao->additional_reminder_day,
848 'pledge_status' => $dao->pledge_status,
849 'payment_status' => $dao->payment_status,
850 'is_test' => $dao->is_test,
851 'currency' => $dao->currency,
852 'campaign_id' => $dao->campaign_id,
853 ];
854
855 $contactIds[$dao->contact_id] = $dao->contact_id;
856 $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
857
858 if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'),
859 $now
860 ) && $dao->payment_status != $allStatus['Overdue']
861 ) {
862 $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
863 }
864 }
865 $allPledgeStatus = array_flip($allPledgeStatus);
866
867 // process the updating script...
868 foreach ($pledgePayments as $pledgeId => $paymentIds) {
869 // 1. update the pledge /pledge payment status. returns new status when an update happens
870 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
871
872 $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds,
873 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
874 );
875 if ($newStatus != $pledgeStatus[$pledgeId]) {
876 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
877 $updateCnt += 1;
878 }
879 }
880
881 if ($sendReminders) {
882 // retrieve domain tokens
883 $tokens = [
884 'domain' => ['name', 'phone', 'address', 'email'],
885 'contact' => CRM_Core_SelectValues::contactTokens(),
886 ];
887
888 // retrieve contact tokens
889
890 // this function does NOT return Deceased contacts since we don't want to send them email
891 $contactDetails = civicrm_api3('Contact', 'get', [
892 'is_deceased' => 0,
893 'id' => ['IN' => $contactIds],
894 'return' => ['id', 'display_name', 'email', 'do_not_email', 'email', 'on_hold'],
895 ])['values'];
896
897 // assign domain values to template
898 $template = CRM_Core_Smarty::singleton();
899
900 // set receipt from
901 $receiptFrom = CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE);
902 $receiptFrom = reset($receiptFrom);
903
904 foreach ($pledgeDetails as $paymentId => $details) {
905 if (array_key_exists($details['contact_id'], $contactDetails)) {
906 $contactId = $details['contact_id'];
907 $pledgerName = $contactDetails[$contactId]['display_name'];
908 }
909 else {
910 continue;
911 }
912
913 if (empty($details['reminder_date'])) {
914 $nextReminderDate = new DateTime($details['scheduled_date']);
915 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ? 0 : $details['initial_reminder_day'];
916 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
917 $nextReminderDate = $nextReminderDate->format("Ymd");
918 }
919 else {
920 $nextReminderDate = new DateTime($details['reminder_date']);
921 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ? 0 : $details['additional_reminder_day'];
922 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
923 $nextReminderDate = $nextReminderDate->format("Ymd");
924 }
925 if (($details['reminder_count'] < $details['max_reminders'])
926 && ($nextReminderDate <= $now)
927 ) {
928
929 $toEmail = $doNotEmail = $onHold = NULL;
930
931 if (!empty($contactDetails[$contactId]['email'])) {
932 $toEmail = $contactDetails[$contactId]['email'];
933 }
934
935 if (!empty($contactDetails[$contactId]['do_not_email'])) {
936 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
937 }
938
939 if (!empty($contactDetails[$contactId]['on_hold'])) {
940 $onHold = $contactDetails[$contactId]['on_hold'];
941 }
942
943 // 2. send acknowledgement mail
944 if ($toEmail && !($doNotEmail || $onHold)) {
945 // assign value to template
946 $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
947 $template->assign('next_payment', $details['scheduled_date']);
948 $template->assign('amount_due', $details['amount_due']);
949 $template->assign('checksumValue', $details['checksumValue']);
950 $template->assign('contribution_page_id', $details['contribution_page_id']);
951 $template->assign('pledge_id', $details['pledge_id']);
952 $template->assign('scheduled_payment_date', $details['scheduled_date']);
953 $template->assign('amount', $details['amount']);
954 $template->assign('create_date', $details['create_date']);
955 $template->assign('currency', $details['currency']);
956 [
957 $mailSent,
958 $subject,
959 $message,
960 $html,
961 ] = CRM_Core_BAO_MessageTemplate::sendTemplate(
962 [
963 'groupName' => 'msg_tpl_workflow_pledge',
964 'valueName' => 'pledge_reminder',
965 'contactId' => $contactId,
966 'from' => $receiptFrom,
967 'toName' => $pledgerName,
968 'toEmail' => $toEmail,
969 ]
970 );
971
972 // 3. update pledge payment details
973 if ($mailSent) {
974 CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
975 $activityType = 'Pledge Reminder';
976 $activityParams = [
977 'subject' => $subject,
978 'source_contact_id' => $contactId,
979 'source_record_id' => $paymentId,
980 'assignee_contact_id' => $contactId,
981 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
982 'activity_type_id',
983 $activityType
984 ),
985 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']),
986 'is_test' => $details['is_test'],
987 'status_id' => 2,
988 'campaign_id' => $details['campaign_id'],
989 ];
990 try {
991 civicrm_api3('activity', 'create', $activityParams);
992 }
993 catch (CiviCRM_API3_Exception $e) {
994 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
995 return ['is_error' => 1, 'message' => $returnMessages];
996 }
997 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
998 }
999 }
1000 }
1001 }
1002 // end foreach on $pledgeDetails
1003 }
1004 // end if ( $sendReminders )
1005 $returnMessages[] = "{$updateCnt} records updated.";
1006
1007 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1008 }
1009
1010 /**
1011 * Mark a pledge (and any outstanding payments) as cancelled.
1012 *
1013 * @param int $pledgeID
1014 */
1015 public static function cancel($pledgeID) {
1016 $paymentIDs = self::findCancelablePayments($pledgeID);
1017 $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1018 $cancelled = array_search('Cancelled', $status);
1019 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1020 $cancelled, 0, FALSE, TRUE
1021 );
1022 }
1023
1024 /**
1025 * Find payments which can be safely canceled.
1026 *
1027 * @param int $pledgeID
1028 *
1029 * @return array
1030 * Array of int (civicrm_pledge_payment.id)
1031 */
1032 public static function findCancelablePayments($pledgeID) {
1033 $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'));
1034
1035 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1036 $paymentDAO->pledge_id = $pledgeID;
1037 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1038 $statuses['Overdue'],
1039 $statuses['Pending']
1040 ));
1041 $paymentDAO->find();
1042
1043 $paymentIDs = [];
1044 while ($paymentDAO->fetch()) {
1045 $paymentIDs[] = $paymentDAO->id;
1046 }
1047 return $paymentIDs;
1048 }
1049
1050 /**
1051 * Is this pledge free from financial transactions (this is important to know
1052 * as we allow editing when no transactions have taken place - the editing
1053 * process currently involves deleting all pledge payments & contributions
1054 * & recreating so we want to block that if appropriate).
1055 *
1056 * @param int $pledgeID
1057 * @param int $pledgeStatusID
1058 *
1059 * @return bool
1060 * do financial transactions exist for this pledge?
1061 */
1062 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1063 if (empty($pledgeStatusID)) {
1064 // why would this happen? If we can see where it does then we can see if we should look it up.
1065 // but assuming from form code it CAN be empty.
1066 return TRUE;
1067 }
1068 if (self::isTransactedStatus($pledgeStatusID)) {
1069 return TRUE;
1070 }
1071
1072 return civicrm_api3('pledge_payment', 'getcount', [
1073 'pledge_id' => $pledgeID,
1074 'contribution_id' => ['IS NOT NULL' => TRUE],
1075 ]);
1076 }
1077
1078 /**
1079 * Does this pledge / pledge payment status mean that a financial transaction
1080 * has taken place?
1081 *
1082 * @param int $statusID
1083 * Pledge status id.
1084 *
1085 * @return bool
1086 * is it a transactional status?
1087 */
1088 protected static function isTransactedStatus($statusID) {
1089 if (!in_array($statusID, self::getNonTransactionalStatus())) {
1090 return TRUE;
1091 }
1092 return FALSE;
1093 }
1094
1095 /**
1096 * Get array of non transactional statuses.
1097 *
1098 * @return array
1099 * non transactional status ids
1100 */
1101 protected static function getNonTransactionalStatus() {
1102 $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1103 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1104 }
1105
1106 /**
1107 * Create array for recur record for pledge.
1108 *
1109 * @return array
1110 * params for recur record
1111 */
1112 public static function buildRecurParams($params) {
1113 $recurParams = [
1114 'is_recur' => TRUE,
1115 'auto_renew' => TRUE,
1116 'frequency_unit' => $params['pledge_frequency_unit'],
1117 'frequency_interval' => $params['pledge_frequency_interval'],
1118 'installments' => $params['pledge_installments'],
1119 'start_date' => $params['receive_date'],
1120 ];
1121 return $recurParams;
1122 }
1123
1124 /**
1125 * Get pledge start date.
1126 *
1127 * @return string
1128 * start date
1129 */
1130 public static function getPledgeStartDate($date, $pledgeBlock) {
1131 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1132 foreach ($startDate as $field => $value) {
1133 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1134 return $date;
1135 }
1136 if (empty($date)) {
1137 $date = $value;
1138 }
1139 switch ($field) {
1140 case 'contribution_date':
1141 if (empty($date)) {
1142 $date = date('Ymd');
1143 }
1144 break;
1145
1146 case 'calendar_date':
1147 $date = date('Ymd', strtotime($date));
1148 break;
1149
1150 case 'calendar_month':
1151 $date = self::getPaymentDate($date);
1152 $date = date('Ymd', strtotime($date));
1153 break;
1154
1155 default:
1156 break;
1157
1158 }
1159 }
1160 return $date;
1161 }
1162
1163 /**
1164 * Get first payment date for pledge.
1165 *
1166 * @param int $day
1167 *
1168 * @return bool|string
1169 */
1170 public static function getPaymentDate($day) {
1171 if ($day == 31) {
1172 // Find out if current month has 31 days, if not, set it to 30 (last day).
1173 $t = date('t');
1174 if ($t != $day) {
1175 $day = $t;
1176 }
1177 }
1178 $current = date('d');
1179 switch (TRUE) {
1180 case ($day == $current):
1181 $date = date('m/d/Y');
1182 break;
1183
1184 case ($day > $current):
1185 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1186 break;
1187
1188 case ($day < $current):
1189 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1190 break;
1191
1192 default:
1193 break;
1194
1195 }
1196 return $date;
1197 }
1198
1199 /**
1200 * Override buildOptions to hack out some statuses.
1201 *
1202 * @param string $fieldName
1203 * @param string $context
1204 * @param array $props
1205 *
1206 * @return array|bool
1207 * @todo instead of using & hacking the shared optionGroup
1208 * contribution_status use a separate one.
1209 *
1210 */
1211 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1212 $result = parent::buildOptions($fieldName, $context, $props);
1213 if ($fieldName == 'status_id') {
1214 $result = array_diff($result, ['Failed']);
1215 }
1216 return $result;
1217 }
1218
1219 }