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