Update pledge acknowledgement to use token processor only
[civicrm-core.git] / CRM / Pledge / BAO / Pledge.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17class CRM_Pledge_BAO_Pledge extends CRM_Pledge_DAO_Pledge {
18
19 /**
fe482240 20 * Static field for all the pledge information that we can potentially export.
6a488035
TO
21 *
22 * @var array
6a488035 23 */
c86d4e7c 24 public static $_exportableFields = NULL;
6a488035
TO
25
26 /**
fe482240 27 * Class constructor.
6a488035 28 */
00be9182 29 public function __construct() {
6a488035
TO
30 parent::__construct();
31 }
32
33 /**
fe482240
EM
34 * Retrieve DB object based on input parameters.
35 *
36 * It also stores all the retrieved values in the default array.
6a488035 37 *
3a1617b6
TO
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.
6a488035 42 *
16b10e64 43 * @return CRM_Pledge_BAO_Pledge
6a488035 44 */
00be9182 45 public static function retrieve(&$params, &$defaults) {
6a488035
TO
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 /**
fe482240 56 * Add pledge.
6a488035 57 *
3a1617b6
TO
58 * @param array $params
59 * Reference array contains the values submitted by the form.
6a488035 60 *
45ae836f 61 * @return CRM_Pledge_DAO_Pledge
6a488035 62 */
45ae836f 63 public static function add(array $params): CRM_Pledge_DAO_Pledge {
1f6f2538 64 CRM_Core_Error::deprecatedFunctionWarning('v4 api');
45ae836f 65 $hook = empty($params['id']) ? 'create' : 'edit';
66 CRM_Utils_Hook::pre($hook, 'Pledge', $params['id'] ?? NULL, $params);
6a488035
TO
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)) {
bb06e9ed 79 $pledge->currency = CRM_Core_Config::singleton()->defaultCurrency;
6a488035
TO
80 }
81
82 $result = $pledge->save();
83
45ae836f 84 CRM_Utils_Hook::post($hook, 'Pledge', $pledge->id, $pledge);
6a488035
TO
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 *
3a1617b6
TO
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.
6a488035 99 *
a6c01b45
CW
100 * @return array
101 * associated array of field values
6a488035 102 */
00be9182 103 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
6a488035
TO
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 /**
fe482240 112 * Takes an associative array and creates a pledge object.
6a488035 113 *
3a1617b6 114 * @param array $params
45ae836f 115 * Assoc array of name/value pairs.
6a488035 116 *
45ae836f 117 * @return CRM_Pledge_DAO_Pledge
118 * @throws \CRM_Core_Exception
6a488035 119 */
1f6f2538 120 public static function create(array $params): CRM_Pledge_DAO_Pledge {
7c86e53f 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 }
6a488035 130
f27fa890 131 $isRecalculatePledgePayment = self::isPaymentsRequireRecalculation($params);
6a488035
TO
132 $transaction = new CRM_Core_Transaction();
133
affcc9d2 134 $paymentParams = [];
a7488080 135 if (!empty($params['installment_amount'])) {
6a488035
TO
136 $params['amount'] = $params['installment_amount'] * $params['installments'];
137 }
138
1c0174c9 139 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
6a488035
TO
140 if (isset($params['contribution_id'])) {
141 if ($params['installments'] > 1) {
ab6ba136 142 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
6a488035
TO
143 }
144 }
145 else {
146 if (!empty($params['id'])) {
147 $params['status_id'] = CRM_Pledge_BAO_PledgePayment::calculatePledgeStatus($params['id']);
148 }
149 else {
ab6ba136 150 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
6a488035
TO
151 }
152 }
153 }
9c1bc317 154 $paymentParams['status_id'] = $params['status_id'] ?? NULL;
6a488035 155
7c86e53f 156 CRM_Utils_Hook::pre($action, 'Pledge', $params['id'] ?? NULL, $params);
1f6f2538 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');
6a488035
TO
162 }
163
1f6f2538 164 $pledge->copyValues($params);
1f6f2538 165 $pledge->save();
7c86e53f 166 CRM_Utils_Hook::post($action, 'Pledge', $pledge->id, $pledge);
1f6f2538 167
cc28438b 168 // handle custom data.
a7488080 169 if (!empty($params['custom']) &&
6a488035
TO
170 is_array($params['custom'])
171 ) {
172 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pledge', $pledge->id);
173 }
174
7c86e53f 175 // skip payment stuff in edit mode
f27fa890 176 if (empty($params['id']) || $isRecalculatePledgePayment) {
6a488035 177
cc28438b 178 // if pledge is pending delete all payments and recreate.
f27fa890 179 if ($isRecalculatePledgePayment) {
6a488035
TO
180 CRM_Pledge_BAO_PledgePayment::deletePayments($pledge->id);
181 }
182
cc28438b 183 // building payment params
6a488035 184 $paymentParams['pledge_id'] = $pledge->id;
6f1bfb6d 185 $paymentKeys = [
353ffa53
TO
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',
6f1bfb6d 196 ];
6a488035 197 foreach ($paymentKeys as $key) {
9c1bc317 198 $paymentParams[$key] = $params[$key] ?? NULL;
6a488035 199 }
4cc3286d 200 CRM_Pledge_BAO_PledgePayment::createMultiple($paymentParams);
6a488035
TO
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
affcc9d2 209 $recentOther = [];
6a488035
TO
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
25e778a5
E
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) . ')';
6a488035
TO
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
1e071f70 237 /**
6f1bfb6d 238 * Is this a change to an existing pending pledge requiring payment schedule
239 * changes.
1e071f70 240 *
6f1bfb6d 241 * If the pledge is pending the code (slightly lazily) deletes & recreates
242 * pledge payments.
1e071f70 243 *
6f1bfb6d 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).
1e071f70 248 *
6f1bfb6d 249 * This calculation needs to be performed before update takes place as
250 * previous & new pledges are compared.
1e071f70 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 }
6f1bfb6d 260 $scheduleChangingParameters = [
1e071f70 261 'amount',
262 'frequency_unit',
263 'frequency_interval',
264 'frequency_day',
265 'installments',
266 'start_date',
6f1bfb6d 267 ];
1e071f70 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
6a488035 283 /**
fe482240 284 * Delete the pledge.
6a488035 285 *
3a1617b6
TO
286 * @param int $id
287 * Pledge id.
6a488035 288 *
77b97be7 289 * @return mixed
6a488035 290 */
00be9182 291 public static function deletePledge($id) {
be12df5a 292 CRM_Utils_Hook::pre('delete', 'Pledge', $id);
6a488035
TO
293
294 $transaction = new CRM_Core_Transaction();
295
cc28438b 296 // check for no Completed Payment records with the pledge
6a488035
TO
297 $payment = new CRM_Pledge_DAO_PledgePayment();
298 $payment->pledge_id = $id;
299 $payment->find();
300
301 while ($payment->fetch()) {
cc28438b 302 // also delete associated contribution.
6a488035
TO
303 if ($payment->contribution_id) {
304 CRM_Contribute_BAO_Contribution::deleteContribution($payment->contribution_id);
305 }
306 $payment->delete();
307 }
308
353ffa53 309 $dao = new CRM_Pledge_DAO_Pledge();
6a488035
TO
310 $dao->id = $id;
311 $results = $dao->delete();
312
313 $transaction->commit();
314
315 CRM_Utils_Hook::post('delete', 'Pledge', $dao->id, $dao);
316
6a488035
TO
317 return $results;
318 }
319
320 /**
100fef9d 321 * Get the amount details date wise.
b55cf2b2
EM
322 *
323 * @param string $status
324 * @param string $startDate
325 * @param string $endDate
326 *
327 * @return array|null
6a488035 328 */
00be9182 329 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
affcc9d2 330 $where = [];
6a488035 331 $select = $from = $queryDate = NULL;
ab6ba136 332 $statusId = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
6a488035
TO
333
334 switch ($status) {
335 case 'Completed':
ab6ba136 336 $where[] = 'status_id != ' . CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
6a488035
TO
337 break;
338
339 case 'Cancelled':
6a488035 340 case 'In Progress':
6a488035 341 case 'Pending':
6a488035
TO
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 = "
357SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
358FROM civicrm_pledge
359WHERE $whereCond AND is_test=0
360GROUP BY currency
361";
353ffa53
TO
362 $start = substr($startDate, 0, 8);
363 $end = substr($endDate, 0, 8);
364 $pCount = 0;
affcc9d2 365 $pamount = [];
9d2678f4 366 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
367 while ($dao->fetch()) {
368 $pCount += $dao->pledge_count;
369 $pamount[] = CRM_Utils_Money::format($dao->pledge_amount, $dao->currency);
370 }
371
6f1bfb6d 372 $pledge_amount = [
353ffa53 373 'pledge_amount' => implode(', ', $pamount),
6a488035
TO
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 ),
6f1bfb6d 378 ];
6a488035 379
affcc9d2 380 $where = [];
6a488035
TO
381 switch ($status) {
382 case 'Completed':
353ffa53
TO
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';
6a488035 385 $queryDate = 'receive_date';
353ffa53 386 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
6a488035
TO
387 break;
388
389 case 'Cancelled':
353ffa53
TO
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';
6a488035 392 $queryDate = 'receive_date';
353ffa53 393 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
6a488035
TO
394 break;
395
396 case 'Pending':
353ffa53
TO
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';
6a488035 399 $queryDate = 'scheduled_date';
353ffa53 400 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
6a488035
TO
401 break;
402
403 case 'Overdue':
353ffa53
TO
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';
6a488035 406 $queryDate = 'scheduled_date';
353ffa53 407 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
6a488035
TO
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) {
9d2678f4 427 $dao = CRM_Core_DAO::executeQuery($query);
affcc9d2 428 $amount = [];
353ffa53 429 $count = 0;
6a488035
TO
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) {
6f1bfb6d 437 return array_merge($pledge_amount, [
353ffa53
TO
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 ),
6f1bfb6d 443 ]);
6a488035
TO
444 }
445 }
446 else {
447 return $pledge_amount;
448 }
449 return NULL;
450 }
451
452 /**
fe482240 453 * Get list of pledges In Honor of contact Ids.
6a488035 454 *
3a1617b6
TO
455 * @param int $honorId
456 * In Honor of Contact ID.
6a488035 457 *
a6c01b45
CW
458 * @return array
459 * return the list of pledge fields
6a488035 460 */
00be9182 461 public static function getHonorContacts($honorId) {
affcc9d2 462 $params = [];
8381af80 463 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
464 $honorDAO->contact_id = $honorId;
6a488035
TO
465 $honorDAO->find();
466
cc28438b 467 // get all status.
6a488035 468 while ($honorDAO->fetch()) {
8381af80 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)) {
6f1bfb6d 475 $params[$pledgeDAO->id] = [
b7617307 476 'honor_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id),
8381af80 477 'honorId' => $pledgeDAO->contact_id,
478 'amount' => $pledgeDAO->amount,
01dac399 479 'status' => CRM_Core_PseudoConstant::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id),
8381af80 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 ),
6f1bfb6d 488 ];
8381af80 489 }
490 }
6a488035 491 }
8381af80 492
6a488035
TO
493 return $params;
494 }
495
496 /**
100fef9d 497 * Send Acknowledgment and create activity.
6a488035 498 *
3a1617b6
TO
499 * @param CRM_Core_Form $form
500 * Form object.
501 * @param array $params
502 * An assoc array of name/value pairs.
6a488035 503 */
00be9182 504 public static function sendAcknowledgment(&$form, $params) {
6a488035 505 //handle Acknowledgment.
affcc9d2 506 $allPayments = $payments = [];
6a488035 507
cc28438b 508 // get All Payments status types.
6a488035 509 $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
6f1bfb6d 510 $returnProperties = [
511 'status_id',
512 'scheduled_amount',
513 'scheduled_date',
514 'contribution_id',
515 ];
cc28438b 516 // get all paymnets details.
6a488035
TO
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) {
affcc9d2 521 $contributionValue = $contributionStatus = [];
6a488035 522 if (isset($values['contribution_id'])) {
6f1bfb6d 523 $contributionParams = ['id' => $values['contribution_id']];
524 $returnProperties = ['contribution_status_id', 'receive_date'];
6a488035
TO
525 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_Contribution',
526 $contributionParams, $contributionStatus, $returnProperties
527 );
6f1bfb6d 528 $contributionValue = [
6b409353
CW
529 'status' => $contributionStatus['contribution_status_id'] ?? NULL,
530 'receive_date' => $contributionStatus['receive_date'] ?? NULL,
6f1bfb6d 531 ];
6a488035
TO
532 }
533 $payments[$payID] = array_merge($contributionValue,
6f1bfb6d 534 [
6b409353
CW
535 'amount' => $values['scheduled_amount'] ?? NULL,
536 'due_date' => $values['scheduled_date'] ?? NULL,
6f1bfb6d 537 ]
6a488035
TO
538 );
539
cc28438b 540 // get the first valid payment id.
6a488035
TO
541 if (!isset($form->paymentId) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
542 $paymentStatusTypes[$values['status_id']] == 'Overdue'
353ffa53
TO
543 )
544 ) {
6a488035
TO
545 $form->paymentId = $values['id'];
546 }
547 }
548 }
6a488035 549
cc28438b 550 // assign pledge fields value to template.
6f1bfb6d 551 $pledgeFields = [
353ffa53
TO
552 'create_date',
553 'total_pledge_amount',
554 'frequency_interval',
555 'frequency_unit',
556 'installments',
557 'frequency_day',
558 'scheduled_amount',
559 'currency',
6f1bfb6d 560 ];
6a488035 561 foreach ($pledgeFields as $field) {
a7488080 562 if (!empty($params[$field])) {
6a488035
TO
563 $form->assign($field, $params[$field]);
564 }
565 }
566
cc28438b 567 // assign all payments details.
6a488035
TO
568 if ($payments) {
569 $form->assign('payments', $payments);
570 }
571
cc28438b 572 // handle custom data.
a7488080 573 if (!empty($params['hidden_custom'])) {
0b330e6d 574 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', NULL, $params['id']);
6f1bfb6d 575 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
affcc9d2 576 $customGroup = [];
6a488035
TO
577 // retrieve custom data
578 foreach ($groupTree as $groupID => $group) {
affcc9d2 579 $customFields = $customValues = [];
6a488035
TO
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
cc28438b 588 // to build array of customgroup & customfields in it
6a488035
TO
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
cc28438b 596 // handle acknowledgment email stuff.
6f1bfb6d 597 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
6a488035 598
cc28438b 599 // check for online pledge.
a7488080 600 if (!empty($params['receipt_from_email'])) {
9c1bc317
CW
601 $userName = $params['receipt_from_name'] ?? NULL;
602 $userEmail = $params['receipt_from_email'] ?? NULL;
6a488035 603 }
a7488080 604 elseif (!empty($params['from_email_id'])) {
6a488035
TO
605 $receiptFrom = $params['from_email_id'];
606 }
bb06e9ed 607 elseif ($userID = CRM_Core_Session::singleton()->get('userID')) {
cc28438b 608 // check for logged in user.
6f1bfb6d 609 [
610 $userName,
611 $userEmail,
612 ] = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
6a488035
TO
613 }
614 else {
cc28438b 615 // set the domain values.
aa7dd30f 616 [$userName, $userEmail] = CRM_Core_BAO_Domain::getNameAndEmail();
6a488035
TO
617 }
618
619 if (!isset($receiptFrom)) {
620 $receiptFrom = "$userName <$userEmail>";
621 }
622
6f1bfb6d 623 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate::sendTemplate(
624 [
6a488035
TO
625 'groupName' => 'msg_tpl_workflow_pledge',
626 'valueName' => 'pledge_acknowledge',
627 'contactId' => $params['contact_id'],
628 'from' => $receiptFrom,
629 'toName' => $pledgerDisplayName,
630 'toEmail' => $pledgerEmail,
6f1bfb6d 631 ]
6a488035
TO
632 );
633
cc28438b
SB
634 // check if activity record exist for this pledge
635 // Acknowledgment, if exist do not add activity.
6a488035
TO
636 $activityType = 'Pledge Acknowledgment';
637 $activity = new CRM_Activity_DAO_Activity();
638 $activity->source_record_id = $params['id'];
363b8345
PN
639 $activity->activity_type_id = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
640 'activity_type_id',
641 $activityType
6a488035 642 );
6a488035 643
6c68db9f 644 // FIXME: Translate
6a488035
TO
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()) {
6f1bfb6d 648 $activityParams = [
6a488035
TO
649 'subject' => $subject,
650 'source_contact_id' => $params['contact_id'],
651 'source_record_id' => $params['id'],
363b8345
PN
652 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
653 'activity_type_id',
654 $activityType
6a488035
TO
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,
6b409353 660 'campaign_id' => $params['campaign_id'] ?? NULL,
6f1bfb6d 661 ];
6a488035 662
cc28438b 663 // lets insert assignee record.
a7488080 664 if (!empty($params['contact_id'])) {
6a488035
TO
665 $activityParams['assignee_contact_id'] = $params['contact_id'];
666 }
667
668 if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
ba968e38 669 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
6a488035
TO
670 }
671 }
672 }
673
674 /**
fe482240 675 * Combine all the exportable fields from the lower levels object.
6a488035 676 *
e9ff5391 677 * @param bool $checkPermission
678 *
a6c01b45
CW
679 * @return array
680 * array of exportable Fields
6a488035 681 */
b3460c23 682 public static function exportableFields($checkPermission = TRUE) {
6a488035
TO
683 if (!self::$_exportableFields) {
684 if (!self::$_exportableFields) {
affcc9d2 685 self::$_exportableFields = [];
6a488035
TO
686 }
687
688 $fields = CRM_Pledge_DAO_Pledge::export();
689
6a488035
TO
690 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment::export());
691
cc28438b 692 // set title to calculated fields
6f1bfb6d 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' => [
353ffa53 701 'title' => ts('Pledge Payment Status'),
6a488035
TO
702 'name' => 'pledge_payment_status',
703 'data_type' => CRM_Utils_Type::T_STRING,
6f1bfb6d 704 ],
705 ];
6a488035 706
6f1bfb6d 707 $pledgeFields = [
708 'pledge_status' => [
e300cf31 709 'title' => ts('Pledge Status'),
6a488035
TO
710 'name' => 'pledge_status',
711 'data_type' => CRM_Utils_Type::T_STRING,
6f1bfb6d 712 ],
713 'pledge_frequency_unit' => [
e300cf31 714 'title' => ts('Pledge Frequency Unit'),
6a488035
TO
715 'name' => 'pledge_frequency_unit',
716 'data_type' => CRM_Utils_Type::T_ENUM,
6f1bfb6d 717 ],
718 'pledge_frequency_interval' => [
e300cf31 719 'title' => ts('Pledge Frequency Interval'),
6a488035
TO
720 'name' => 'pledge_frequency_interval',
721 'data_type' => CRM_Utils_Type::T_INT,
6f1bfb6d 722 ],
723 'pledge_contribution_page_id' => [
e300cf31 724 'title' => ts('Pledge Contribution Page Id'),
6a488035
TO
725 'name' => 'pledge_contribution_page_id',
726 'data_type' => CRM_Utils_Type::T_INT,
6f1bfb6d 727 ],
728 ];
6a488035
TO
729
730 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
731
732 // add custom data
e9ff5391 733 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
6a488035
TO
734 self::$_exportableFields = $fields;
735 }
736
737 return self::$_exportableFields;
738 }
739
740 /**
fe482240 741 * Get pending or in progress pledges.
6a488035 742 *
3a1617b6
TO
743 * @param int $contactID
744 * Contact id.
6a488035 745 *
a6c01b45
CW
746 * @return array
747 * associated array of pledge id(s)
6a488035 748 */
00be9182 749 public static function getContactPledges($contactID) {
affcc9d2 750 $pledgeDetails = [];
01dac399
JP
751 $pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status',
752 FALSE, FALSE, FALSE, NULL, 'name'
753 );
6a488035 754
affcc9d2 755 $status = [];
6a488035 756
cc28438b 757 // get pending and in progress status
6f1bfb6d 758 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
6a488035
TO
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
6f1bfb6d 776 $params[1] = [$contactID, 'Integer'];
6a488035
TO
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 /**
fe482240 787 * Get pledge record count for a Contact.
6a488035 788 *
100fef9d 789 * @param int $contactID
2a6da8d7 790 *
a6c01b45
CW
791 * @return int
792 * count of pledge records
6a488035 793 */
00be9182 794 public static function getContactPledgeCount($contactID) {
6a488035
TO
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
ffd93213 799 /**
c490a46a 800 * @param array $params
ffd93213
EM
801 *
802 * @return array
803 */
7670996e 804 public static function updatePledgeStatus($params) {
6a488035 805
affcc9d2 806 $returnMessages = [];
6a488035
TO
807
808 $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE);
809
e7212d86
JP
810 $allStatus = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
811 $allPledgeStatus = CRM_Core_OptionGroup::values('pledge_status',
812 TRUE, FALSE, FALSE, NULL, 'name', TRUE
813 );
814 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
815 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
6a488035 816
e7212d86
JP
817 $statusIds = implode(',', $allStatus);
818 $pledgeStatusIds = implode(',', $allPledgeStatus);
6a488035
TO
819 $updateCnt = 0;
820
821 $query = "
822SELECT pledge.contact_id as contact_id,
823 pledge.id as pledge_id,
824 pledge.amount as amount,
825 payment.scheduled_date as scheduled_date,
826 pledge.create_date as create_date,
827 payment.id as payment_id,
828 pledge.currency as currency,
829 pledge.contribution_page_id as contribution_page_id,
830 payment.reminder_count as reminder_count,
831 pledge.max_reminders as max_reminders,
832 payment.reminder_date as reminder_date,
833 pledge.initial_reminder_day as initial_reminder_day,
834 pledge.additional_reminder_day as additional_reminder_day,
835 pledge.status_id as pledge_status,
836 payment.status_id as payment_status,
837 pledge.is_test as is_test,
838 pledge.campaign_id as campaign_id,
839 SUM(payment.scheduled_amount) as amount_due,
840 ( SELECT sum(civicrm_pledge_payment.actual_amount)
841 FROM civicrm_pledge_payment
842 WHERE civicrm_pledge_payment.status_id = 1
843 AND civicrm_pledge_payment.pledge_id = pledge.id
844 ) as amount_paid
845 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
846 WHERE pledge.id = payment.pledge_id
e7212d86 847 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
6a488035
TO
848 GROUP By payment.id
849 ";
850
851 $dao = CRM_Core_DAO::executeQuery($query);
852
853 $now = date('Ymd');
affcc9d2 854 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
6a488035
TO
855 while ($dao->fetch()) {
856 $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
857
6f1bfb6d 858 $pledgeDetails[$dao->payment_id] = [
6a488035
TO
859 'scheduled_date' => $dao->scheduled_date,
860 'amount_due' => $dao->amount_due,
861 'amount' => $dao->amount,
862 'amount_paid' => $dao->amount_paid,
863 'create_date' => $dao->create_date,
864 'contact_id' => $dao->contact_id,
865 'pledge_id' => $dao->pledge_id,
866 'checksumValue' => $checksumValue,
867 'contribution_page_id' => $dao->contribution_page_id,
868 'reminder_count' => $dao->reminder_count,
869 'max_reminders' => $dao->max_reminders,
870 'reminder_date' => $dao->reminder_date,
871 'initial_reminder_day' => $dao->initial_reminder_day,
872 'additional_reminder_day' => $dao->additional_reminder_day,
873 'pledge_status' => $dao->pledge_status,
874 'payment_status' => $dao->payment_status,
875 'is_test' => $dao->is_test,
876 'currency' => $dao->currency,
877 'campaign_id' => $dao->campaign_id,
6f1bfb6d 878 ];
6a488035
TO
879
880 $contactIds[$dao->contact_id] = $dao->contact_id;
881 $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
882
883 if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'),
884 $now
e7212d86 885 ) && $dao->payment_status != $allStatus['Overdue']
353ffa53 886 ) {
6a488035
TO
887 $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
888 }
889 }
e7212d86 890 $allPledgeStatus = array_flip($allPledgeStatus);
6a488035
TO
891
892 // process the updating script...
6a488035
TO
893 foreach ($pledgePayments as $pledgeId => $paymentIds) {
894 // 1. update the pledge /pledge payment status. returns new status when an update happens
e7212d86 895 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
6a488035
TO
896
897 $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds,
e7212d86 898 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
6a488035
TO
899 );
900 if ($newStatus != $pledgeStatus[$pledgeId]) {
e7212d86 901 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
6a488035
TO
902 $updateCnt += 1;
903 }
904 }
905
906 if ($sendReminders) {
907 // retrieve domain tokens
908 $domain = CRM_Core_BAO_Domain::getDomain();
6f1bfb6d 909 $tokens = [
910 'domain' => ['name', 'phone', 'address', 'email'],
6a488035 911 'contact' => CRM_Core_SelectValues::contactTokens(),
6f1bfb6d 912 ];
6a488035 913
affcc9d2 914 $domainValues = [];
6a488035
TO
915 foreach ($tokens['domain'] as $token) {
916 $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
917 }
918
cc28438b 919 // get the domain email address, since we don't carry w/ object.
6a488035
TO
920 $domainValue = CRM_Core_BAO_Domain::getNameAndEmail();
921 $domainValues['email'] = $domainValue[1];
922
923 // retrieve contact tokens
924
925 // this function does NOT return Deceased contacts since we don't want to send them email
6f1bfb6d 926 [$contactDetails] = CRM_Utils_Token::getTokenDetails($contactIds,
6a488035
TO
927 NULL,
928 FALSE, FALSE, NULL,
929 $tokens, 'CRM_UpdatePledgeRecord'
930 );
931
932 // assign domain values to template
933 $template = CRM_Core_Smarty::singleton();
934 $template->assign('domain', $domainValues);
935
cc28438b 936 // set receipt from
6a488035
TO
937 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
938
939 foreach ($pledgeDetails as $paymentId => $details) {
940 if (array_key_exists($details['contact_id'], $contactDetails)) {
941 $contactId = $details['contact_id'];
942 $pledgerName = $contactDetails[$contactId]['display_name'];
943 }
944 else {
945 continue;
946 }
947
948 if (empty($details['reminder_date'])) {
949 $nextReminderDate = new DateTime($details['scheduled_date']);
64b4078f 950 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ? 0 : $details['initial_reminder_day'];
6a488035
TO
951 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
952 $nextReminderDate = $nextReminderDate->format("Ymd");
953 }
954 else {
955 $nextReminderDate = new DateTime($details['reminder_date']);
64b4078f 956 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ? 0 : $details['additional_reminder_day'];
6a488035
TO
957 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
958 $nextReminderDate = $nextReminderDate->format("Ymd");
959 }
960 if (($details['reminder_count'] < $details['max_reminders'])
961 && ($nextReminderDate <= $now)
962 ) {
963
964 $toEmail = $doNotEmail = $onHold = NULL;
965
966 if (!empty($contactDetails[$contactId]['email'])) {
967 $toEmail = $contactDetails[$contactId]['email'];
968 }
969
970 if (!empty($contactDetails[$contactId]['do_not_email'])) {
971 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
972 }
973
974 if (!empty($contactDetails[$contactId]['on_hold'])) {
975 $onHold = $contactDetails[$contactId]['on_hold'];
976 }
977
978 // 2. send acknowledgement mail
979 if ($toEmail && !($doNotEmail || $onHold)) {
cc28438b 980 // assign value to template
6a488035
TO
981 $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
982 $template->assign('contact', $contactDetails[$contactId]);
983 $template->assign('next_payment', $details['scheduled_date']);
984 $template->assign('amount_due', $details['amount_due']);
985 $template->assign('checksumValue', $details['checksumValue']);
986 $template->assign('contribution_page_id', $details['contribution_page_id']);
987 $template->assign('pledge_id', $details['pledge_id']);
988 $template->assign('scheduled_payment_date', $details['scheduled_date']);
989 $template->assign('amount', $details['amount']);
990 $template->assign('create_date', $details['create_date']);
991 $template->assign('currency', $details['currency']);
6f1bfb6d 992 [
993 $mailSent,
994 $subject,
995 $message,
996 $html,
997 ] = CRM_Core_BAO_MessageTemplate::sendTemplate(
998 [
6a488035
TO
999 'groupName' => 'msg_tpl_workflow_pledge',
1000 'valueName' => 'pledge_reminder',
1001 'contactId' => $contactId,
1002 'from' => $receiptFrom,
1003 'toName' => $pledgerName,
1004 'toEmail' => $toEmail,
6f1bfb6d 1005 ]
6a488035
TO
1006 );
1007
1008 // 3. update pledge payment details
1009 if ($mailSent) {
1010 CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
1011 $activityType = 'Pledge Reminder';
6f1bfb6d 1012 $activityParams = [
6a488035
TO
1013 'subject' => $subject,
1014 'source_contact_id' => $contactId,
1015 'source_record_id' => $paymentId,
1016 'assignee_contact_id' => $contactId,
363b8345
PN
1017 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
1018 'activity_type_id',
1019 $activityType
6a488035 1020 ),
6a488035
TO
1021 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']),
1022 'is_test' => $details['is_test'],
1023 'status_id' => 2,
1024 'campaign_id' => $details['campaign_id'],
6f1bfb6d 1025 ];
c06e1e95
MW
1026 try {
1027 civicrm_api3('activity', 'create', $activityParams);
1028 }
1029 catch (CiviCRM_API3_Exception $e) {
1030 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
6f1bfb6d 1031 return ['is_error' => 1, 'message' => $returnMessages];
6a488035
TO
1032 }
1033 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1034 }
1035 }
1036 }
1037 }
1038 // end foreach on $pledgeDetails
1039 }
1040 // end if ( $sendReminders )
1041 $returnMessages[] = "{$updateCnt} records updated.";
1042
6f1bfb6d 1043 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
6a488035
TO
1044 }
1045
1046 /**
1047 * Mark a pledge (and any outstanding payments) as cancelled.
1048 *
1049 * @param int $pledgeID
1050 */
1051 public static function cancel($pledgeID) {
6a488035 1052 $paymentIDs = self::findCancelablePayments($pledgeID);
10874ecc 1053 $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1054 $cancelled = array_search('Cancelled', $status);
6a488035 1055 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
10874ecc 1056 $cancelled, 0, FALSE, TRUE
6a488035
TO
1057 );
1058 }
1059
1060 /**
1061 * Find payments which can be safely canceled.
1062 *
1063 * @param int $pledgeID
6f1bfb6d 1064 *
a6c01b45 1065 * @return array
16b10e64 1066 * Array of int (civicrm_pledge_payment.id)
6a488035
TO
1067 */
1068 public static function findCancelablePayments($pledgeID) {
c3b82060 1069 $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'));
6a488035
TO
1070
1071 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1072 $paymentDAO->pledge_id = $pledgeID;
1073 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1074 $statuses['Overdue'],
1075 $statuses['Pending']
1076 ));
1077 $paymentDAO->find();
1078
affcc9d2 1079 $paymentIDs = [];
6a488035
TO
1080 while ($paymentDAO->fetch()) {
1081 $paymentIDs[] = $paymentDAO->id;
1082 }
1083 return $paymentIDs;
1084 }
edb4c74d
E
1085
1086 /**
6f1bfb6d 1087 * Is this pledge free from financial transactions (this is important to know
1088 * as we allow editing when no transactions have taken place - the editing
1089 * process currently involves deleting all pledge payments & contributions
cc28438b 1090 * & recreating so we want to block that if appropriate).
edb4c74d 1091 *
3a1617b6
TO
1092 * @param int $pledgeID
1093 * @param int $pledgeStatusID
6f1bfb6d 1094 *
a6c01b45
CW
1095 * @return bool
1096 * do financial transactions exist for this pledge?
edb4c74d 1097 */
098201d8 1098 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
edb4c74d 1099 if (empty($pledgeStatusID)) {
cc28438b
SB
1100 // why would this happen? If we can see where it does then we can see if we should look it up.
1101 // but assuming from form code it CAN be empty.
edb4c74d
E
1102 return TRUE;
1103 }
1104 if (self::isTransactedStatus($pledgeStatusID)) {
1105 return TRUE;
1106 }
1107
6f1bfb6d 1108 return civicrm_api3('pledge_payment', 'getcount', [
e2a918bf 1109 'pledge_id' => $pledgeID,
6f1bfb6d 1110 'contribution_id' => ['IS NOT NULL' => TRUE],
1111 ]);
098201d8 1112 }
edb4c74d
E
1113
1114 /**
6f1bfb6d 1115 * Does this pledge / pledge payment status mean that a financial transaction
1116 * has taken place?
1117 *
3a1617b6
TO
1118 * @param int $statusID
1119 * Pledge status id.
edb4c74d 1120 *
a6c01b45
CW
1121 * @return bool
1122 * is it a transactional status?
edb4c74d
E
1123 */
1124 protected static function isTransactedStatus($statusID) {
1125 if (!in_array($statusID, self::getNonTransactionalStatus())) {
1126 return TRUE;
1127 }
b55cf2b2 1128 return FALSE;
edb4c74d
E
1129 }
1130
1131 /**
fe482240 1132 * Get array of non transactional statuses.
6f1bfb6d 1133 *
a6c01b45
CW
1134 * @return array
1135 * non transactional status ids
edb4c74d
E
1136 */
1137 protected static function getNonTransactionalStatus() {
1138 $paymentStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
6f1bfb6d 1139 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
edb4c74d
E
1140 }
1141
dccd9f4f
ERL
1142 /**
1143 * Create array for recur record for pledge.
6f1bfb6d 1144 *
dccd9f4f
ERL
1145 * @return array
1146 * params for recur record
1147 */
1148 public static function buildRecurParams($params) {
6f1bfb6d 1149 $recurParams = [
dccd9f4f
ERL
1150 'is_recur' => TRUE,
1151 'auto_renew' => TRUE,
1152 'frequency_unit' => $params['pledge_frequency_unit'],
1153 'frequency_interval' => $params['pledge_frequency_interval'],
1154 'installments' => $params['pledge_installments'],
1155 'start_date' => $params['receive_date'],
6f1bfb6d 1156 ];
dccd9f4f
ERL
1157 return $recurParams;
1158 }
1159
1160 /**
1161 * Get pledge start date.
1162 *
1163 * @return string
1164 * start date
1165 */
1166 public static function getPledgeStartDate($date, $pledgeBlock) {
1167 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
9de112cd 1168 foreach ($startDate as $field => $value) {
de6c59ca 1169 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
9de112cd
SL
1170 return $date;
1171 }
1172 if (empty($date)) {
1173 $date = $value;
1174 }
1175 switch ($field) {
1176 case 'contribution_date':
1177 if (empty($date)) {
1178 $date = date('Ymd');
1179 }
1180 break;
dccd9f4f 1181
9de112cd
SL
1182 case 'calendar_date':
1183 $date = date('Ymd', strtotime($date));
1184 break;
dccd9f4f 1185
9de112cd
SL
1186 case 'calendar_month':
1187 $date = self::getPaymentDate($date);
1188 $date = date('Ymd', strtotime($date));
1189 break;
dccd9f4f 1190
9de112cd
SL
1191 default:
1192 break;
dccd9f4f 1193
9de112cd 1194 }
dccd9f4f
ERL
1195 }
1196 return $date;
1197 }
1198
1199 /**
1200 * Get first payment date for pledge.
1201 *
bf48aa29 1202 * @param int $day
1203 *
1204 * @return bool|string
dccd9f4f
ERL
1205 */
1206 public static function getPaymentDate($day) {
1207 if ($day == 31) {
1208 // Find out if current month has 31 days, if not, set it to 30 (last day).
1209 $t = date('t');
1210 if ($t != $day) {
1211 $day = $t;
1212 }
1213 }
1214 $current = date('d');
1215 switch (TRUE) {
1216 case ($day == $current):
1217 $date = date('m/d/Y');
1218 break;
1219
1220 case ($day > $current):
1221 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1222 break;
1223
1224 case ($day < $current):
1225 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1226 break;
1227
1228 default:
1229 break;
1230
1231 }
1232 return $date;
1233 }
1234
ab6ba136 1235 /**
1236 * Override buildOptions to hack out some statuses.
1237 *
ab6ba136 1238 * @param string $fieldName
1239 * @param string $context
1240 * @param array $props
1241 *
1242 * @return array|bool
6f1bfb6d 1243 * @todo instead of using & hacking the shared optionGroup
1244 * contribution_status use a separate one.
1245 *
ab6ba136 1246 */
affcc9d2 1247 public static function buildOptions($fieldName, $context = NULL, $props = []) {
ab6ba136 1248 $result = parent::buildOptions($fieldName, $context, $props);
1249 if ($fieldName == 'status_id') {
6f1bfb6d 1250 $result = array_diff($result, ['Failed']);
ab6ba136 1251 }
1252 return $result;
1253 }
1254
6a488035 1255}