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