f20650fe4c3dc9a6332a447d0d090fbd35893ee1
[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 ]
538 );
539
540 // get the first valid payment id.
541 if (!isset($form->paymentId) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
542 $paymentStatusTypes[$values['status_id']] == 'Overdue'
543 )
544 ) {
545 $form->paymentId = $values['id'];
546 }
547 }
548 }
549
550 // assign pledge fields value to template.
551 $pledgeFields = [
552 'create_date',
553 'total_pledge_amount',
554 'frequency_interval',
555 'frequency_unit',
556 'installments',
557 'frequency_day',
558 'scheduled_amount',
559 'currency',
560 ];
561 foreach ($pledgeFields as $field) {
562 if (!empty($params[$field])) {
563 $form->assign($field, $params[$field]);
564 }
565 }
566
567 // assign all payments details.
568 if ($payments) {
569 $form->assign('payments', $payments);
570 }
571
572 // handle custom data.
573 if (!empty($params['hidden_custom'])) {
574 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', NULL, $params['id']);
575 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
576 $customGroup = [];
577 // retrieve custom data
578 foreach ($groupTree as $groupID => $group) {
579 $customFields = $customValues = [];
580 if ($groupID == 'info') {
581 continue;
582 }
583 foreach ($group['fields'] as $k => $field) {
584 $field['title'] = $field['label'];
585 $customFields["custom_{$k}"] = $field;
586 }
587
588 // to build array of customgroup & customfields in it
589 CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
590 $customGroup[$group['title']] = $customValues;
591 }
592
593 $form->assign('customGroup', $customGroup);
594 }
595
596 // handle acknowledgment email stuff.
597 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
598
599 // check for online pledge.
600 if (!empty($params['receipt_from_email'])) {
601 $userName = $params['receipt_from_name'] ?? NULL;
602 $userEmail = $params['receipt_from_email'] ?? NULL;
603 }
604 elseif (!empty($params['from_email_id'])) {
605 $receiptFrom = $params['from_email_id'];
606 }
607 elseif ($userID = CRM_Core_Session::singleton()->get('userID')) {
608 // check for logged in user.
609 [
610 $userName,
611 $userEmail,
612 ] = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
613 }
614 else {
615 // set the domain values.
616 [$userName, $userEmail] = CRM_Core_BAO_Domain::getNameAndEmail();
617 }
618
619 if (!isset($receiptFrom)) {
620 $receiptFrom = "$userName <$userEmail>";
621 }
622
623 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate::sendTemplate(
624 [
625 'groupName' => 'msg_tpl_workflow_pledge',
626 'valueName' => 'pledge_acknowledge',
627 'contactId' => $params['contact_id'],
628 'from' => $receiptFrom,
629 'toName' => $pledgerDisplayName,
630 'toEmail' => $pledgerEmail,
631 ]
632 );
633
634 // check if activity record exist for this pledge
635 // Acknowledgment, if exist do not add activity.
636 $activityType = 'Pledge Acknowledgment';
637 $activity = new CRM_Activity_DAO_Activity();
638 $activity->source_record_id = $params['id'];
639 $activity->activity_type_id = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
640 'activity_type_id',
641 $activityType
642 );
643
644 // FIXME: Translate
645 $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)';
646
647 if (!$activity->find()) {
648 $activityParams = [
649 'subject' => $subject,
650 'source_contact_id' => $params['contact_id'],
651 'source_record_id' => $params['id'],
652 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
653 'activity_type_id',
654 $activityType
655 ),
656 'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']),
657 'is_test' => $params['is_test'],
658 'status_id' => 2,
659 'details' => $details,
660 'campaign_id' => $params['campaign_id'] ?? NULL,
661 ];
662
663 // lets insert assignee record.
664 if (!empty($params['contact_id'])) {
665 $activityParams['assignee_contact_id'] = $params['contact_id'];
666 }
667
668 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
669 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
670 }
671 }
672 }
673
674 /**
675 * Combine all the exportable fields from the lower levels object.
676 *
677 * @param bool $checkPermission
678 *
679 * @return array
680 * array of exportable Fields
681 */
682 public static function exportableFields($checkPermission = TRUE) {
683 if (!self::$_exportableFields) {
684 if (!self::$_exportableFields) {
685 self::$_exportableFields = [];
686 }
687
688 $fields = CRM_Pledge_DAO_Pledge::export();
689
690 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment::export());
691
692 // set title to calculated fields
693 $calculatedFields = [
694 'pledge_total_paid' => ['title' => ts('Total Paid')],
695 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
696 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
697 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
698 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
699 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
700 'pledge_payment_status' => [
701 'title' => ts('Pledge Payment Status'),
702 'name' => 'pledge_payment_status',
703 'data_type' => CRM_Utils_Type::T_STRING,
704 ],
705 ];
706
707 $pledgeFields = [
708 'pledge_status' => [
709 'title' => ts('Pledge Status'),
710 'name' => 'pledge_status',
711 'data_type' => CRM_Utils_Type::T_STRING,
712 ],
713 'pledge_frequency_unit' => [
714 'title' => ts('Pledge Frequency Unit'),
715 'name' => 'pledge_frequency_unit',
716 'data_type' => CRM_Utils_Type::T_ENUM,
717 ],
718 'pledge_frequency_interval' => [
719 'title' => ts('Pledge Frequency Interval'),
720 'name' => 'pledge_frequency_interval',
721 'data_type' => CRM_Utils_Type::T_INT,
722 ],
723 'pledge_contribution_page_id' => [
724 'title' => ts('Pledge Contribution Page Id'),
725 'name' => 'pledge_contribution_page_id',
726 'data_type' => CRM_Utils_Type::T_INT,
727 ],
728 ];
729
730 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
731
732 // add custom data
733 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
734 self::$_exportableFields = $fields;
735 }
736
737 return self::$_exportableFields;
738 }
739
740 /**
741 * Get pending or in progress pledges.
742 *
743 * @param int $contactID
744 * Contact id.
745 *
746 * @return array
747 * associated array of pledge id(s)
748 */
749 public static function getContactPledges($contactID) {
750 $pledgeDetails = [];
751 $pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status',
752 FALSE, FALSE, FALSE, NULL, 'name'
753 );
754
755 $status = [];
756
757 // get pending and in progress status
758 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
759 if ($statusId = array_search($name, $pledgeStatuses)) {
760 $status[] = $statusId;
761 }
762 }
763 if (empty($status)) {
764 return $pledgeDetails;
765 }
766
767 $statusClause = " IN (" . implode(',', $status) . ")";
768
769 $query = "
770 SELECT civicrm_pledge.id id
771 FROM civicrm_pledge
772 WHERE civicrm_pledge.status_id {$statusClause}
773 AND civicrm_pledge.contact_id = %1
774 ";
775
776 $params[1] = [$contactID, 'Integer'];
777 $pledge = CRM_Core_DAO::executeQuery($query, $params);
778
779 while ($pledge->fetch()) {
780 $pledgeDetails[] = $pledge->id;
781 }
782
783 return $pledgeDetails;
784 }
785
786 /**
787 * Get pledge record count for a Contact.
788 *
789 * @param int $contactID
790 *
791 * @return int
792 * count of pledge records
793 */
794 public static function getContactPledgeCount($contactID) {
795 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
796 return CRM_Core_DAO::singleValueQuery($query);
797 }
798
799 /**
800 * @param array $params
801 *
802 * @return array
803 * @throws \API_Exception
804 * @throws \CRM_Core_Exception
805 * @throws \CiviCRM_API3_Exception
806 */
807 public static function updatePledgeStatus($params): array {
808
809 $returnMessages = [];
810
811 $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE);
812
813 $allStatus = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
814 $allPledgeStatus = CRM_Core_OptionGroup::values('pledge_status',
815 TRUE, FALSE, FALSE, NULL, 'name', TRUE
816 );
817 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
818 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
819
820 $statusIds = implode(',', $allStatus);
821 $pledgeStatusIds = implode(',', $allPledgeStatus);
822 $updateCnt = 0;
823
824 $query = "
825 SELECT pledge.contact_id as contact_id,
826 pledge.id as pledge_id,
827 pledge.amount as amount,
828 payment.scheduled_date as scheduled_date,
829 pledge.create_date as create_date,
830 payment.id as payment_id,
831 pledge.currency as currency,
832 pledge.contribution_page_id as contribution_page_id,
833 payment.reminder_count as reminder_count,
834 pledge.max_reminders as max_reminders,
835 payment.reminder_date as reminder_date,
836 pledge.initial_reminder_day as initial_reminder_day,
837 pledge.additional_reminder_day as additional_reminder_day,
838 pledge.status_id as pledge_status,
839 payment.status_id as payment_status,
840 pledge.is_test as is_test,
841 pledge.campaign_id as campaign_id,
842 SUM(payment.scheduled_amount) as amount_due,
843 ( SELECT sum(civicrm_pledge_payment.actual_amount)
844 FROM civicrm_pledge_payment
845 WHERE civicrm_pledge_payment.status_id = 1
846 AND civicrm_pledge_payment.pledge_id = pledge.id
847 ) as amount_paid
848 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
849 WHERE pledge.id = payment.pledge_id
850 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
851 GROUP By payment.id
852 ";
853
854 $dao = CRM_Core_DAO::executeQuery($query);
855
856 $now = date('Ymd');
857 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
858 while ($dao->fetch()) {
859 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
860
861 $pledgeDetails[$dao->payment_id] = [
862 'scheduled_date' => $dao->scheduled_date,
863 'amount_due' => $dao->amount_due,
864 'amount' => $dao->amount,
865 'amount_paid' => $dao->amount_paid,
866 'create_date' => $dao->create_date,
867 'contact_id' => $dao->contact_id,
868 'pledge_id' => $dao->pledge_id,
869 'checksumValue' => $checksumValue,
870 'contribution_page_id' => $dao->contribution_page_id,
871 'reminder_count' => $dao->reminder_count,
872 'max_reminders' => $dao->max_reminders,
873 'reminder_date' => $dao->reminder_date,
874 'initial_reminder_day' => $dao->initial_reminder_day,
875 'additional_reminder_day' => $dao->additional_reminder_day,
876 'pledge_status' => $dao->pledge_status,
877 'payment_status' => $dao->payment_status,
878 'is_test' => $dao->is_test,
879 'currency' => $dao->currency,
880 'campaign_id' => $dao->campaign_id,
881 ];
882
883 $contactIds[$dao->contact_id] = $dao->contact_id;
884 $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
885
886 if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'),
887 $now
888 ) && $dao->payment_status != $allStatus['Overdue']
889 ) {
890 $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
891 }
892 }
893 $allPledgeStatus = array_flip($allPledgeStatus);
894
895 // process the updating script...
896 foreach ($pledgePayments as $pledgeId => $paymentIds) {
897 // 1. update the pledge /pledge payment status. returns new status when an update happens
898 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
899
900 $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds,
901 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
902 );
903 if ($newStatus != $pledgeStatus[$pledgeId]) {
904 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
905 $updateCnt += 1;
906 }
907 }
908
909 if ($sendReminders) {
910 // retrieve domain tokens
911 $tokens = [
912 'domain' => ['name', 'phone', 'address', 'email'],
913 'contact' => CRM_Core_SelectValues::contactTokens(),
914 ];
915
916 // retrieve contact tokens
917
918 // this function does NOT return Deceased contacts since we don't want to send them email
919 $contactDetails = civicrm_api3('Contact', 'get', [
920 'is_deceased' => 0,
921 'id' => ['IN' => $contactIds],
922 'return' => ['id', 'display_name', 'email', 'do_not_email', 'email', 'on_hold'],
923 ])['values'];
924
925 // assign domain values to template
926 $template = CRM_Core_Smarty::singleton();
927
928 // set receipt from
929 $receiptFrom = CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE);
930 $receiptFrom = reset($receiptFrom);
931
932 foreach ($pledgeDetails as $paymentId => $details) {
933 if (array_key_exists($details['contact_id'], $contactDetails)) {
934 $contactId = $details['contact_id'];
935 $pledgerName = $contactDetails[$contactId]['display_name'];
936 }
937 else {
938 continue;
939 }
940
941 if (empty($details['reminder_date'])) {
942 $nextReminderDate = new DateTime($details['scheduled_date']);
943 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ? 0 : $details['initial_reminder_day'];
944 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
945 $nextReminderDate = $nextReminderDate->format("Ymd");
946 }
947 else {
948 $nextReminderDate = new DateTime($details['reminder_date']);
949 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ? 0 : $details['additional_reminder_day'];
950 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
951 $nextReminderDate = $nextReminderDate->format("Ymd");
952 }
953 if (($details['reminder_count'] < $details['max_reminders'])
954 && ($nextReminderDate <= $now)
955 ) {
956
957 $toEmail = $doNotEmail = $onHold = NULL;
958
959 if (!empty($contactDetails[$contactId]['email'])) {
960 $toEmail = $contactDetails[$contactId]['email'];
961 }
962
963 if (!empty($contactDetails[$contactId]['do_not_email'])) {
964 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
965 }
966
967 if (!empty($contactDetails[$contactId]['on_hold'])) {
968 $onHold = $contactDetails[$contactId]['on_hold'];
969 }
970
971 // 2. send acknowledgement mail
972 if ($toEmail && !($doNotEmail || $onHold)) {
973 // assign value to template
974 $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
975 $template->assign('next_payment', $details['scheduled_date']);
976 $template->assign('amount_due', $details['amount_due']);
977 $template->assign('checksumValue', $details['checksumValue']);
978 $template->assign('contribution_page_id', $details['contribution_page_id']);
979 $template->assign('pledge_id', $details['pledge_id']);
980 $template->assign('scheduled_payment_date', $details['scheduled_date']);
981 $template->assign('amount', $details['amount']);
982 $template->assign('create_date', $details['create_date']);
983 $template->assign('currency', $details['currency']);
984 [
985 $mailSent,
986 $subject,
987 $message,
988 $html,
989 ] = CRM_Core_BAO_MessageTemplate::sendTemplate(
990 [
991 'groupName' => 'msg_tpl_workflow_pledge',
992 'valueName' => 'pledge_reminder',
993 'contactId' => $contactId,
994 'from' => $receiptFrom,
995 'toName' => $pledgerName,
996 'toEmail' => $toEmail,
997 ]
998 );
999
1000 // 3. update pledge payment details
1001 if ($mailSent) {
1002 CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
1003 $activityType = 'Pledge Reminder';
1004 $activityParams = [
1005 'subject' => $subject,
1006 'source_contact_id' => $contactId,
1007 'source_record_id' => $paymentId,
1008 'assignee_contact_id' => $contactId,
1009 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
1010 'activity_type_id',
1011 $activityType
1012 ),
1013 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']),
1014 'is_test' => $details['is_test'],
1015 'status_id' => 2,
1016 'campaign_id' => $details['campaign_id'],
1017 ];
1018 try {
1019 civicrm_api3('activity', 'create', $activityParams);
1020 }
1021 catch (CiviCRM_API3_Exception $e) {
1022 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1023 return ['is_error' => 1, 'message' => $returnMessages];
1024 }
1025 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1026 }
1027 }
1028 }
1029 }
1030 // end foreach on $pledgeDetails
1031 }
1032 // end if ( $sendReminders )
1033 $returnMessages[] = "{$updateCnt} records updated.";
1034
1035 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1036 }
1037
1038 /**
1039 * Mark a pledge (and any outstanding payments) as cancelled.
1040 *
1041 * @param int $pledgeID
1042 */
1043 public static function cancel($pledgeID) {
1044 $paymentIDs = self::findCancelablePayments($pledgeID);
1045 $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1046 $cancelled = array_search('Cancelled', $status);
1047 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1048 $cancelled, 0, FALSE, TRUE
1049 );
1050 }
1051
1052 /**
1053 * Find payments which can be safely canceled.
1054 *
1055 * @param int $pledgeID
1056 *
1057 * @return array
1058 * Array of int (civicrm_pledge_payment.id)
1059 */
1060 public static function findCancelablePayments($pledgeID) {
1061 $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'));
1062
1063 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1064 $paymentDAO->pledge_id = $pledgeID;
1065 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1066 $statuses['Overdue'],
1067 $statuses['Pending']
1068 ));
1069 $paymentDAO->find();
1070
1071 $paymentIDs = [];
1072 while ($paymentDAO->fetch()) {
1073 $paymentIDs[] = $paymentDAO->id;
1074 }
1075 return $paymentIDs;
1076 }
1077
1078 /**
1079 * Is this pledge free from financial transactions (this is important to know
1080 * as we allow editing when no transactions have taken place - the editing
1081 * process currently involves deleting all pledge payments & contributions
1082 * & recreating so we want to block that if appropriate).
1083 *
1084 * @param int $pledgeID
1085 * @param int $pledgeStatusID
1086 *
1087 * @return bool
1088 * do financial transactions exist for this pledge?
1089 */
1090 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1091 if (empty($pledgeStatusID)) {
1092 // why would this happen? If we can see where it does then we can see if we should look it up.
1093 // but assuming from form code it CAN be empty.
1094 return TRUE;
1095 }
1096 if (self::isTransactedStatus($pledgeStatusID)) {
1097 return TRUE;
1098 }
1099
1100 return civicrm_api3('pledge_payment', 'getcount', [
1101 'pledge_id' => $pledgeID,
1102 'contribution_id' => ['IS NOT NULL' => TRUE],
1103 ]);
1104 }
1105
1106 /**
1107 * Does this pledge / pledge payment status mean that a financial transaction
1108 * has taken place?
1109 *
1110 * @param int $statusID
1111 * Pledge status id.
1112 *
1113 * @return bool
1114 * is it a transactional status?
1115 */
1116 protected static function isTransactedStatus($statusID) {
1117 if (!in_array($statusID, self::getNonTransactionalStatus())) {
1118 return TRUE;
1119 }
1120 return FALSE;
1121 }
1122
1123 /**
1124 * Get array of non transactional statuses.
1125 *
1126 * @return array
1127 * non transactional status ids
1128 */
1129 protected static function getNonTransactionalStatus() {
1130 $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1131 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1132 }
1133
1134 /**
1135 * Create array for recur record for pledge.
1136 *
1137 * @return array
1138 * params for recur record
1139 */
1140 public static function buildRecurParams($params) {
1141 $recurParams = [
1142 'is_recur' => TRUE,
1143 'auto_renew' => TRUE,
1144 'frequency_unit' => $params['pledge_frequency_unit'],
1145 'frequency_interval' => $params['pledge_frequency_interval'],
1146 'installments' => $params['pledge_installments'],
1147 'start_date' => $params['receive_date'],
1148 ];
1149 return $recurParams;
1150 }
1151
1152 /**
1153 * Get pledge start date.
1154 *
1155 * @return string
1156 * start date
1157 */
1158 public static function getPledgeStartDate($date, $pledgeBlock) {
1159 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1160 foreach ($startDate as $field => $value) {
1161 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1162 return $date;
1163 }
1164 if (empty($date)) {
1165 $date = $value;
1166 }
1167 switch ($field) {
1168 case 'contribution_date':
1169 if (empty($date)) {
1170 $date = date('Ymd');
1171 }
1172 break;
1173
1174 case 'calendar_date':
1175 $date = date('Ymd', strtotime($date));
1176 break;
1177
1178 case 'calendar_month':
1179 $date = self::getPaymentDate($date);
1180 $date = date('Ymd', strtotime($date));
1181 break;
1182
1183 default:
1184 break;
1185
1186 }
1187 }
1188 return $date;
1189 }
1190
1191 /**
1192 * Get first payment date for pledge.
1193 *
1194 * @param int $day
1195 *
1196 * @return bool|string
1197 */
1198 public static function getPaymentDate($day) {
1199 if ($day == 31) {
1200 // Find out if current month has 31 days, if not, set it to 30 (last day).
1201 $t = date('t');
1202 if ($t != $day) {
1203 $day = $t;
1204 }
1205 }
1206 $current = date('d');
1207 switch (TRUE) {
1208 case ($day == $current):
1209 $date = date('m/d/Y');
1210 break;
1211
1212 case ($day > $current):
1213 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1214 break;
1215
1216 case ($day < $current):
1217 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1218 break;
1219
1220 default:
1221 break;
1222
1223 }
1224 return $date;
1225 }
1226
1227 /**
1228 * Override buildOptions to hack out some statuses.
1229 *
1230 * @param string $fieldName
1231 * @param string $context
1232 * @param array $props
1233 *
1234 * @return array|bool
1235 * @todo instead of using & hacking the shared optionGroup
1236 * contribution_status use a separate one.
1237 *
1238 */
1239 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1240 $result = parent::buildOptions($fieldName, $context, $props);
1241 if ($fieldName == 'status_id') {
1242 $result = array_diff($result, ['Failed']);
1243 }
1244 return $result;
1245 }
1246
1247 }