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