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