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