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