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